Declare visual capabilities and dispatch explicit Presentable views
Verify Tessera GUI / verify (push) Failing after 7m41s

This commit is contained in:
2026-10-21 21:37:22 +08:00
parent 8d980745ea
commit 7acc5783a5
9 changed files with 363 additions and 4 deletions
+9
View File
@@ -14,6 +14,7 @@
| mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries |
| events.rs | Bounded native input transport to the owning VM |
| event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver |
| protocols.rs | Register explicit Visual/EventTarget/Children/Presentable managed traits and native type declarations |
| presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work |
| tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation and opaque published Page identities |
| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards and coalesced GUI projections |
@@ -106,3 +107,11 @@ read versions and borrowed output values for equality without adding GC roots;
cache updates do not mutate the connection's business version. Target content
traces the compute function. Subscription tokens are weak and also support bindings.
All binding work settles before published frames; compute failure stops the VM.
The host registers Trait definitions through Aster's checked nominal capability
API. Source subclasses validate inherited method arity before class publication.
Presentable dispatch uses a generated validated bytecode continuation inside the
current call budget, passes the current managed Window, and validates a real
Block result before opening it. Native base visual methods and runtime result
checks remain the rendering boundary. Matching present names without an explicit
implementation keep the summary fallback and do not execute guest methods.
+4
View File
@@ -1042,6 +1042,10 @@ Source measure and arrange overrides execute bottom-up and top-down in one read-
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; full parameter/return annotation and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
For a plain object explicitly implementing Presentable, present(self, window: Window): Block is invoked by ui.present(value) or ui.open(value), using the current managed Window and the same VM budget. The result must be an actual Block. Blocks pass through directly; unregistered values retain the summary fallback. Source views retain their business object via managed fields/callbacks/bindings, as in examples/presentable.endor. Viewing function definitions does not itself execute them. Rendering methods still run read-only with nominal result checks.
Block.bind(property, compute) binds an existing managed Block field to a zero-argument function and returns Subscription (disconnect/isConnected). This includes source-defined fields and native TextBlock.text/size/color, RectBlock.width/height/radius/color, Spacer.size and container padding/gap. Native fields can also be assigned directly. The target content owns compute/captures; tokens and host registry are weak. Rebinding disconnects the old connection; disconnect keeps the last value. Actual read dependencies are tracked at object granularity, including conservative global reads; no explicit source-list parameter is required. Hidden retained Blocks update at successful input/event stabilization boundaries before all windows publish. Computes are read-only for existing objects and may allocate results. They have 100000 instructions/128 frames each, 128 active bindings per Block and a 10000-computation refresh limit that errors rather than truncates propagation. Binding failure stops the live VM and preserves published pictures. Non-Block targets, explicit dependency lists and general type/effect checking remain pending. See examples/property-bindings.endor.
Native input POST /events is a transport envelope, not Endor source. Each frame and input carries an opaque runtime window identity; omitted input window defaults to 1 for existing clients. GET /code exposes X-Tessera-Window. A window/session/layout identity mismatch is rejected before invoking code. Tab actions use kind tab-activate/tab-close/tab-detach and the mount wire field carries the opaque tab ID from frame.tabs; point/press_point must be omitted. All spatial/tab actions validate session and layout_version before dispatch. Resource window-close uses mount=0 and no points; it validates the live window/session rather than its old layout version. The window
+110
View File
@@ -2562,6 +2562,116 @@ mod tests {
assert!(!session.is_faulted());
}
#[test]
fn presentable_dispatch_preserves_source_identity_and_reactive_display() {
let (mut session, initial) = ReplSession::load(
include_str!("../examples/presentable.endor"),
"app.main",
1,
230,
)
.unwrap();
assert!(initial.frame.commands.iter().any(|command| matches!(command,RenderCommand::Text { value, .. } if value == "普通对象的显式展示能力")));
let globals = session.candidate.globals.unwrap();
let Value::Object(product) = session
.candidate
.vm
.dict_get(globals, &Value::Text("product".into()))
.unwrap()
.unwrap()
else {
panic!("expected Product");
};
let Value::Object(view) = session
.candidate
.vm
.dict_get(globals, &Value::Text("view".into()))
.unwrap()
.unwrap()
else {
panic!("expected Block");
};
assert_eq!(
session.candidate.vm.get_attr(view, "source").unwrap(),
Value::Object(product)
);
assert_eq!(
session
.execute("ui.supports(product,Presentable)", "app.main")
.unwrap()
.value,
"true"
);
let changed = session
.execute("product.name = \"updated\"", "app.main")
.unwrap()
.document
.unwrap();
assert!(changed.frame.commands.iter().any(
|command| matches!(command,RenderCommand::Text { value, .. } if value == "updated")
));
assert!(session.execute("class Bad: RectBlock { function paint(self: Bad): DisplayList { return DisplayList(ObjectList()) } }","app.main").err().unwrap().to_string().contains("trait Visual method paint"));
assert!(!session.is_faulted());
}
#[test]
fn matching_present_method_does_not_implicitly_declare_presentable() {
let mut session = ReplSession::new(231).unwrap();
session
.execute(
r#"
class Data {
marker: Object
function present(self: Data, window: Window): Block {
self.marker.increment()
return TextBlock("custom")
}
}
marker = ui.state(0)
data = Data(marker)
fallback = ui.present(data)
"#,
"app.main",
)
.unwrap();
assert_eq!(
session.execute("marker.value", "app.main").unwrap().value,
"0"
);
assert_eq!(
session
.execute("ui.supports(data,Presentable)", "app.main")
.unwrap()
.value,
"false"
);
session
.execute(
"ui.implement(Data,Presentable)\ncustom = ui.open(data)",
"app.main",
)
.unwrap();
assert_eq!(
session.execute("marker.value", "app.main").unwrap().value,
"1"
);
let before = session.documents.clone();
assert!(
session
.execute(
"class Missing {}\nui.implement(Missing,Presentable)",
"app.main"
)
.is_err()
);
assert_eq!(
session.documents[&crate::window::MAIN_WINDOW]
.frame
.layout_version,
before[&crate::window::MAIN_WINDOW].frame.layout_version
);
}
#[test]
fn managed_property_bindings_update_hidden_objects_and_shared_window_geometry() {
let mut session = ReplSession::new(220).unwrap();
+1
View File
@@ -17,6 +17,7 @@ mod mount;
mod native_visual;
mod object_list;
mod presentation;
mod protocols;
mod scene;
mod snapshot;
mod software_renderer;
+60
View File
@@ -0,0 +1,60 @@
//! Host capability definitions over Aster's explicit managed trait relations.
use endor_core::{MethodRequirement, ObjectRef, Value, Vm, VmError};
pub fn install(
vm: &mut Vm,
roots: &mut Vec<ObjectRef>,
desktop: ObjectRef,
ui: ObjectRef,
) -> Result<(), VmError> {
let Value::Object(trait_type) = vm.get_attr(ui, "Trait")? else {
return Err(VmError::InvalidArgument("missing Trait type"));
};
let Value::Object(types) = vm.get_attr(desktop, "types")? else {
return Err(VmError::InvalidArgument("missing type registry"));
};
for (name, methods, owner) in [
(
"Visual",
vec![("measure", 2), ("arrange", 2), ("paint", 2), ("hitTest", 2)],
Some("Block"),
),
(
"EventTarget",
vec![("on", 3), ("dispatch", 2), ("onEvent", 1)],
Some("Block"),
),
(
"Children",
vec![
("append", 1),
("remove", 1),
("replace", 2),
("move", 2),
("children", 0),
],
Some("ContainerBlock"),
),
("Presentable", vec![("present", 1)], None),
] {
let requirements = methods
.into_iter()
.map(|(name, parameters)| MethodRequirement {
name: name.into(),
parameters,
})
.collect();
let capability = vm.new_trait(name, requirements)?;
roots.push(capability);
vm.attach_type(capability, trait_type)?;
vm.set_attr(ui, name, Value::Object(capability))?;
vm.dict_set(types, Value::Text(name.into()), Value::Object(capability))?;
if let Some(owner) = owner {
let Value::Object(owner) = vm.get_attr(ui, owner)? else {
return Err(VmError::InvalidArgument("missing protocol owner"));
};
vm.implement_trait(owner, capability)?;
}
}
Ok(())
}
+146 -2
View File
@@ -20,6 +20,11 @@ pub const TYPE_NAMES: &[&str] = &[
"Object",
"Type",
"Function",
"Trait",
"Visual",
"EventTarget",
"Children",
"Presentable",
"Block",
"ContainerBlock",
"TextBlock",
@@ -42,7 +47,13 @@ pub const TYPE_NAMES: &[&str] = &[
"DisplayList",
"PaintCommand",
];
pub const QUERY_NAMES: &[&str] = &["isInstance", "isSubtype"];
pub const QUERY_NAMES: &[&str] = &[
"isInstance",
"isSubtype",
"implement",
"implements",
"supports",
];
#[derive(Debug, Clone, PartialEq)]
pub struct UiNode {
@@ -199,6 +210,9 @@ type Shared = Arc<Mutex<Session>>;
#[derive(Debug, Clone, Copy)]
enum Operation {
IsInstance,
Implement,
Implements,
Supports,
IsSubtype,
OpenValue,
Mounts,
@@ -565,6 +579,36 @@ fn show(cx: &mut NativeContext<'_>, page: ObjectRef, session: &Shared) -> Result
show_in(cx, page, session, None)
}
#[derive(Debug)]
struct PresentResult {
open: bool,
session: Shared,
}
impl NativeCallable for PresentResult {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let [Value::Object(root)] = args else {
return Err(invalid("Presentable.present must return a Block"));
};
let is_page = cx.store().payload::<block::Block>(*root, "Block")?.page;
let result = if self.open {
let page = if is_page {
*root
} else {
new_block(
cx,
Data::new(Kind::Page, vec![*root], 0.0, 0.0),
&self.session,
)?
};
show(cx, page, &self.session)?;
page
} else {
*root
};
Ok(NativeResult::Return(Value::Object(result)))
}
}
fn present_value(
cx: &mut NativeContext<'_>,
value: &Value,
@@ -610,7 +654,7 @@ impl NativeCallable for Function {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
use Operation::*;
let (minimum, maximum) = match self.operation {
IsInstance | IsSubtype | Bind => (2, 2),
IsInstance | IsSubtype | Bind | Implement | Implements | Supports => (2, 2),
Stats | Viewport | Window | PageWindow | Mounts => (0, 0),
State | StateSet => (1, 1),
Increment => (0, 0),
@@ -633,6 +677,30 @@ impl NativeCallable for Function {
if !(minimum..=maximum).contains(&args.len()) {
return Err(invalid("incorrect UI method argument count"));
}
if matches!(self.operation, Implement | Implements | Supports) {
let capability = object(args.get(1))?;
let value = match self.operation {
Implement => {
cx.implement_trait(object(args.first())?, capability)?;
Value::Nil
}
Implements => Value::Bool(
cx.store()
.implements_trait(object(args.first())?, capability)?,
),
Supports => {
// Validate the contract even for immediate scalar values.
cx.store()
.payload::<endor_core::EndorTraitObject>(capability, "Trait")?;
Value::Bool(match args[0] {
Value::Object(value) => cx.store().supports(value, capability)?,
_ => false,
})
}
_ => unreachable!(),
};
return Ok(NativeResult::Return(value));
}
if matches!(self.operation, IsInstance | IsSubtype) {
let candidate = object(args.first())?;
let expected = object(args.get(1))?;
@@ -946,6 +1014,74 @@ impl NativeCallable for Function {
self.requested_type,
)?)));
}
if matches!(self.operation, OpenValue | Present)
&& let Value::Object(value) = args[0]
{
let (desktop, current) = {
let state = self
.session
.lock()
.map_err(|_| invalid("UI session poisoned"))?;
(state.master, state.desktop)
};
let capability = desktop_type(cx.store(), "Presentable", desktop)?;
if !cx
.store()
.object(value)?
.payload()
.as_any()
.is::<block::Block>()
&& cx.store().supports(value, capability)?
{
let definition = cx
.store()
.type_of(value)?
.ok_or(invalid("untyped Presentable"))?;
let function = cx
.store()
.lookup_method(definition, "present")?
.ok_or(invalid("missing present method"))?;
let window = object(Some(&cx.store().get_attr(current, "window")?))?;
let complete = cx.allocate(ContextNativeFunction::new(
"validate presentation",
PresentResult {
open: matches!(self.operation, OpenValue),
session: self.session.clone(),
},
vec![desktop],
))?;
let instructions = [
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 0),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 1),
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 2),
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 3),
endor_core::Instruction::new(endor_core::Opcode::Call, 2),
endor_core::Instruction::new(endor_core::Opcode::Call, 1),
endor_core::Instruction::simple(endor_core::Opcode::ReturnValue),
];
let code = endor_core::EndorCode::from_instructions(
&instructions,
vec![
Value::Object(complete),
Value::Object(function),
Value::Object(value),
Value::Object(window),
],
endor_core::CodeLayout::default(),
)?
.with_location("Presentable.present", "<tessera>", 1);
let code = cx.allocate(endor_core::EndorCodeObject::new(code))?;
let globals = cx.new_dict()?;
let driver = cx.new_function("Presentable.present", code, globals)?;
attach_desktop_type(cx, driver, "Function", desktop)?;
return Ok(NativeResult::Invoke {
function: driver,
arguments: vec![],
});
}
}
if matches!(self.operation, OpenValue) {
let root = present_value(cx, &args[0], &self.session)?;
let page = if cx.store().payload::<block::Block>(root, "Block")?.page {
@@ -1976,6 +2112,9 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
retired_commands: Vec::new(),
}));
for (name, operation) in [
("implement", Operation::Implement),
("implements", Operation::Implements),
("supports", Operation::Supports),
("isInstance", Operation::IsInstance),
("isSubtype", Operation::IsSubtype),
("open", Operation::OpenValue),
@@ -2015,6 +2154,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
("Type", root_types.type_type),
];
for (name, base_name, constructor_name) in [
("Trait", "Object", None),
("Function", "Object", None),
("Block", "Object", None),
("ContainerBlock", "Block", None),
@@ -2149,6 +2289,9 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
"window",
"isInstance",
"isSubtype",
"implement",
"implements",
"supports",
] {
let function = object(Some(&vm.get_attr(ui, name)?))?;
vm.attach_type(function, function_type)?;
@@ -2205,6 +2348,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
let event_type = object(Some(&vm.get_attr(ui, "Event")?))?;
let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?;
crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?;
crate::protocols::install(vm, roots, desktop, ui)?;
Ok(UiBridge { ui, session })
}