feat: retain managed visual objects and dispatch native input through Endor
Verify Tessera GUI / verify (push) Successful in 9m28s

This commit is contained in:
2026-10-21 01:49:35 +08:00
parent 757fa22d9b
commit 0d5e4b318d
21 changed files with 3295 additions and 892 deletions
+359 -54
View File
@@ -40,9 +40,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
candidate.globals = Some(globals);
candidate.roots.push(globals);
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
candidate
.vm
.dict_set(globals, Value::Text("ui".into()), Value::Object(bridge.ui))?;
bridge.install_globals(&mut candidate.vm, globals)?;
let limits = match &plan {
SourcePlan::Module(_) => LIMITS,
SourcePlan::Script(_) => ExecutionLimits {
@@ -61,7 +59,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
}
let ui_root = match &plan {
SourcePlan::Script(_) => bridge
.rendered()?
.rendered(&candidate.vm)?
.ok_or_else(|| anyhow::anyhow!("script must call ui.page().render(root)"))?,
SourcePlan::Module(_) => {
let entry = candidate
@@ -77,10 +75,12 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
.vm
.call_with_limits(entry, &[], LIMITS)
.map_err(|error| runtime_error(&candidate.vm, error))?;
let snapshot = bridge.rendered().and_then(|rendered| match rendered {
Some(root) => Ok(root),
None => ui_bridge::snapshot(&candidate.vm, &value),
});
let snapshot = bridge
.rendered(&candidate.vm)
.and_then(|rendered| match rendered {
Some(root) => Ok(root),
None => ui_bridge::snapshot(&candidate.vm, &value),
});
candidate.vm.release_value(value)?;
snapshot?
}
@@ -141,7 +141,15 @@ pub fn evaluate(source: &str) -> Result<String> {
}
fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::CompiledCode>> {
compile_plan_with_globals(source, plan, BTreeSet::from(["ui".to_owned()]))
compile_plan_with_globals(
source,
plan,
std::iter::once("ui")
.chain(ui_bridge::TYPE_NAMES.iter().copied())
.chain(ui_bridge::QUERY_NAMES.iter().copied())
.map(str::to_owned)
.collect(),
)
}
fn compile_plan_with_globals(
@@ -156,8 +164,11 @@ fn compile_plan_with_globals(
if let AstRoot::Interactive(input) = root {
for statement in &input.statements {
if let StmtKind::Declaration(decl) = &statement.kind {
let DeclKind::Function(function) = &decl.kind;
globals.insert(function.name.text.clone());
let name = match &decl.kind {
DeclKind::Function(function) => &function.name,
DeclKind::Class(class) => &class.name,
};
globals.insert(name.text.clone());
}
}
}
@@ -185,7 +196,7 @@ fn compile_plan_with_globals(
}
/// One real VM, owned only by the existing execution worker. No history replay.
/// The UI bridge's fixed pools are session-wide and reclaimed by explicit reset.
/// The UI bridge shares the same managed object heap and publishes atomic frames.
pub struct ReplSession {
candidate: Candidate,
bridge: ui_bridge::UiBridge,
@@ -194,6 +205,8 @@ pub struct ReplSession {
ast_nodes: usize,
source: String,
nodes: Vec<CodeNode>,
faulted: bool,
program_root: Option<CodeNode>,
}
pub struct ReplResult {
pub value: String,
@@ -202,15 +215,88 @@ pub struct ReplResult {
pub input: usize,
}
impl ReplSession {
/// Compile once into an isolated candidate, then keep its actual heap and
/// callback environments alive after the first successful publication.
pub fn load(
source: &str,
namespace: &str,
submission: u64,
id: u64,
) -> Result<(Self, RenderDocument)> {
if source.len() > MAX_SOURCE_BYTES {
bail!("source exceeds the 1 MiB limit");
}
let unit = EndorReader::from_text(format!("{namespace} [submission {submission}]"), source);
let plan = endor_script::parse(&unit)?;
let mut budget = AstBudget::default();
for ast in plan.roots() {
budget.visit_ast_root(ast)?;
}
let compiled = compile_plan(&unit, &plan)?;
let mut runtime = Self::new(id)?;
let globals = runtime.candidate.globals.expect("program globals");
let limits = if matches!(plan, SourcePlan::Script(_)) {
ExecutionLimits {
max_instructions: LIMITS.max_instructions / compiled.len().max(1),
..LIMITS
}
} else {
LIMITS
};
for template in &compiled {
let code = template.load(&mut runtime.candidate.vm)?;
let result = runtime
.candidate
.vm
.execute_with_limits(code, globals, limits)
.map_err(|error| runtime_error(&runtime.candidate.vm, error));
runtime.candidate.vm.release(code)?;
runtime.candidate.vm.release_value(result?)?;
}
if matches!(plan, SourcePlan::Module(_)) {
let main = runtime
.candidate
.vm
.dict_get(globals, &Value::Text("main".into()))?
.ok_or_else(|| anyhow::anyhow!("declare a main function"))?;
let Value::Object(main) = main else {
bail!("main must be callable");
};
let value = runtime
.candidate
.vm
.call_with_limits(main, &[], LIMITS)
.map_err(|error| runtime_error(&runtime.candidate.vm, error))?;
let opened = if runtime.bridge.has_page()? {
Ok(())
} else {
runtime.bridge.open_value(&mut runtime.candidate.vm, &value)
};
runtime.candidate.vm.release_value(value)?;
opened?;
}
if !runtime.bridge.has_page()? {
bail!("script must call page.render(root) or ui.open(value)");
}
runtime.source = source.into();
runtime.ast_nodes = budget.nodes;
runtime.program_root = Some(architecture(&unit, &plan, namespace, submission));
let document = runtime
.refresh_document()?
.ok_or_else(|| anyhow::anyhow!("program did not publish a Page"))?;
runtime
.bridge
.reclaim(&mut runtime.candidate.vm, &mut runtime.candidate.roots)?;
Ok((runtime, document))
}
pub fn new(id: u64) -> Result<Self> {
let mut candidate = Candidate::new()?;
let globals = candidate.vm.new_dict()?;
candidate.globals = Some(globals);
candidate.roots.push(globals);
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
candidate
.vm
.dict_set(globals, Value::Text("ui".into()), Value::Object(bridge.ui))?;
bridge.install_globals(&mut candidate.vm, globals)?;
Ok(Self {
candidate,
bridge,
@@ -219,9 +305,16 @@ impl ReplSession {
ast_nodes: 0,
source: String::new(),
nodes: Vec::new(),
faulted: false,
program_root: None,
})
}
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
if self.faulted {
bail!(
"runtime stopped after an event failure; reset the session or replace its program"
);
}
if source.len() > MAX_SOURCE_BYTES {
bail!("input exceeds 1 MiB");
}
@@ -257,11 +350,17 @@ impl ReplSession {
let compiled = compile_plan_with_globals(&source, &plan, names)?;
// Parsing/compilation finish before any new statement runs. Successful earlier
// statements in a runtime-failed input remain live, as in an ordinary REPL.
self.bridge.discard_pending()?;
self.bridge.discard_pending(&mut self.candidate.vm)?;
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
self.inputs += 1;
self.ast_nodes += budget.nodes;
if let Some(root) = self.program_root.take() {
self.nodes.push(root);
}
if !self.source.is_empty() && !self.source.ends_with('\n') {
self.source.push('\n');
}
let offset = line_starts(&self.source).len();
self.source
.push_str(&format!("// Console input {}\n", self.inputs));
@@ -269,7 +368,12 @@ impl ReplSession {
if !self.source.ends_with('\n') {
self.source.push('\n');
}
let mut node = architecture(&source, &plan, namespace, self.inputs as u64);
let mut node = architecture(
&source,
&plan,
&format!("{namespace}:console-{}", self.id),
self.inputs as u64,
);
node.name = format!("Input {}", self.inputs);
shift_node_lines(&mut node, offset);
self.nodes.push(node);
@@ -315,30 +419,7 @@ impl ReplSession {
retained?;
rendered_value = repr?;
}
let document = if let Some(root) = self.bridge.prepare_frame()? {
let document = RenderDocument {
source: self.source.clone(),
root: Some(CodeNode {
id: format!("console-session-{}", self.id),
name: format!("Console session {}", self.id),
kind: "repl-session".into(),
start_line: 1,
end_line: self.source.lines().count(),
children: self.nodes.clone(),
}),
frame: root
.as_ref()
.map(|root| layout::frame(root))
.transpose()?
.unwrap_or_default(),
ui_root: root.clone(),
};
document.validate()?;
self.bridge.commit_frame(root)?;
Some(document)
} else {
None
};
let document = self.refresh_document()?;
Ok(ReplResult {
value: rendered_value,
document,
@@ -352,7 +433,7 @@ impl ReplSession {
})
})();
if result.is_err() {
self.bridge.discard_pending()?;
self.bridge.discard_pending(&mut self.candidate.vm)?;
if let Some(node) = self.nodes.last_mut() {
node.name
.push_str(" (error; earlier statements may remain live)");
@@ -362,6 +443,83 @@ impl ReplSession {
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
result
}
fn refresh_document(&mut self) -> Result<Option<RenderDocument>> {
let mut last = None;
let mut work = 0;
let mut mutated_mounts = false;
let result = (|| loop {
let Some(root) = self.bridge.prepare_frame(&mut self.candidate.vm)? else {
return Ok(last);
};
let mut document = RenderDocument {
source: self.source.clone(),
root: Some(self.program_root.clone().unwrap_or_else(|| CodeNode {
id: format!("console-session-{}", self.id),
name: format!("Console session {}", self.id),
kind: "repl-session".into(),
start_line: 1,
end_line: self.source.lines().count(),
children: self.nodes.clone(),
})),
frame: root
.as_ref()
.map(|root| self.bridge.layout_frame(&self.candidate.vm, root))
.transpose()?
.unwrap_or_default(),
ui_root: root.clone(),
};
document.frame.session = self.id;
document.validate()?;
work += document.frame.mounts.len().max(1);
if work > 200_000 {
bail!("layout dependencies did not stabilize within the rendering work budget");
}
mutated_mounts = true;
self.bridge
.commit_frame(&mut self.candidate.vm, root, &document.frame)?;
last = Some(document);
})();
if result.is_err() && mutated_mounts {
self.faulted = true;
}
result
}
pub fn is_faulted(&self) -> bool {
self.faulted
}
pub fn dispatch(&mut self, input: &crate::events::Input) -> Result<ReplResult> {
if self.faulted {
bail!("runtime stopped after an event failure");
}
if input.session != self.id {
bail!("event belongs to another runtime session");
}
let result = (|| {
self.bridge.dispatch(&mut self.candidate.vm, input)?;
let document = self.refresh_document()?;
Ok(ReplResult {
value: "nil".into(),
document,
bindings: self
.candidate
.vm
.dict_items(self.candidate.globals.expect("live globals"))?
.len()
.saturating_sub(1),
input: self.inputs,
})
})();
if result.is_err() {
self.faulted = true;
self.bridge.discard_pending(&mut self.candidate.vm)?;
}
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
result
}
}
fn shift_node_lines(node: &mut CodeNode, offset: usize) {
node.start_line += offset;
@@ -530,7 +688,21 @@ impl Architecture {
}
fn declaration(&mut self, declaration: &Decl) -> CodeNode {
let DeclKind::Function(function) = &declaration.kind;
match &declaration.kind {
DeclKind::Function(function) => self.function(function),
DeclKind::Class(class) => {
let mut children: Vec<_> = class
.fields
.iter()
.map(|field| self.node(field.name.text.clone(), "field", field.span, vec![]))
.collect();
children.extend(class.methods.iter().map(|method| self.function(method)));
self.node(class.name.text.clone(), "class", class.span, children)
}
}
}
fn function(&mut self, function: &frontend::ast::Function) -> CodeNode {
let children = function
.body
.statements
@@ -547,6 +719,16 @@ impl Architecture {
fn statement(&mut self, statement: &Stmt) -> CodeNode {
match &statement.kind {
StmtKind::MemberAssignment(assignment) => {
let object = self.expression(&assignment.object);
let value = self.expression(&assignment.value);
self.node(
assignment.name.text.clone(),
"member-assign",
statement.span,
vec![object, value],
)
}
StmtKind::Binding(binding) => {
let child = self.expression(&binding.value);
self.node(
@@ -613,6 +795,124 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn loaded_program_console_and_native_events_share_unique_source_ids() {
let (mut session, initial) = ReplSession::load(
include_str!("../examples/managed-types.endor"),
"app.main",
1,
1,
)
.unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("isInstance(page, Block)", "app.main")
.unwrap()
.value,
"true"
);
let mount = initial
.frame
.mounts
.iter()
.find(|mount| mount.interactive)
.unwrap();
let event = crate::events::Input {
session: 1,
layout_version: initial.frame.layout_version,
mount: mount.id,
kind: "click".into(),
};
let updated = session.dispatch(&event).unwrap().document.unwrap();
updated.validate().unwrap();
assert_eq!(
updated
.frame
.commands
.iter()
.filter(|command| matches!(command,
RenderCommand::Text { value, .. } if value == "10"
))
.count(),
2
);
assert!(!session.is_faulted());
}
#[test]
fn native_method_callbacks_update_two_explicit_bindings() {
let mut session = ReplSession::new(21).unwrap();
session.execute("counter = ui.state(9)\nfirst = ui.textOf(counter, \"value\")\nsecond = ui.textOf(counter, \"value\")\nbutton = ui.button(\"increment\")\nfunction increment(): Unit { counter.increment() }\nbutton.onClick(increment)\npage = ui.page()\npage.render(ui.row(0, 8, first, second, button))", "app.main").unwrap();
let updated = session
.execute("button.click()", "app.main")
.unwrap()
.document
.unwrap();
let texts: Vec<_> = updated
.frame
.commands
.iter()
.filter_map(|command| match command {
RenderCommand::Text { value, .. } => Some(value.as_str()),
_ => None,
})
.collect();
assert_eq!(&texts[..2], &["10", "10"]);
}
#[test]
fn closing_a_page_releases_its_root_without_retaining_it_through_shared_content() {
let mut session = ReplSession::new(22).unwrap();
session
.execute(
"card = ui.rect(10, 20)\npage = ui.page()\npage.render(card)",
"app.main",
)
.unwrap();
let globals = session.candidate.globals.unwrap();
let Value::Object(page) = session
.candidate
.vm
.dict_get(globals, &Value::Text("page".into()))
.unwrap()
.unwrap()
else {
panic!("expected Page")
};
let weak = session.candidate.vm.downgrade(page).unwrap();
session.execute("page.close()", "app.main").unwrap();
session
.execute("card.setColor(\"#FFEEDD\")", "app.main")
.unwrap();
assert!(
session
.execute("page.open()", "app.main")
.unwrap()
.document
.is_some()
);
session.execute("page.close()", "app.main").unwrap();
session
.candidate
.vm
.dict_delete(globals, &Value::Text("page".into()))
.unwrap();
session
.bridge
.reclaim(&mut session.candidate.vm, &mut session.candidate.roots)
.unwrap();
assert!(session.candidate.vm.upgrade(weak).unwrap().is_none());
assert!(
session
.candidate
.vm
.dict_get(globals, &Value::Text("card".into()))
.unwrap()
.is_some()
);
}
#[test]
fn mounted_aliases_update_nested_positions_unmount_and_reject_cycles() {
let mut session = ReplSession::new(10).unwrap();
@@ -776,8 +1076,14 @@ mod tests {
assert_eq!(document.display_list(2.0).unwrap().commands().len(), 3);
let wrapped = compile(include_str!("../examples/main.endor"), "app.main", 10).unwrap();
assert_eq!(
serde_json::to_value(&document.frame).unwrap(),
serde_json::to_value(&wrapped.frame).unwrap()
serde_json::to_value(&document.frame.commands).unwrap(),
serde_json::to_value(&wrapped.frame.commands).unwrap()
);
// Separate VM instances render the same commands with independent
// managed object identities and presentation contexts.
assert_ne!(
document.frame.mounts[0].block_id,
wrapped.frame.mounts[0].block_id
);
}
@@ -874,7 +1180,7 @@ paint(ui.text("last"))"#;
}
#[test]
fn page_creation_has_a_separate_bounded_pool() {
fn page_creation_has_a_separate_live_object_budget() {
let mut source = String::new();
for index in 0..=ui_bridge::MAX_PAGES {
source.push_str(&format!("let page{index} = ui.page()\n"));
@@ -917,10 +1223,9 @@ paint(ui.text("last"))"#;
fn developer_selection_resets_to_the_new_source_snapshot() {
let first = compile(PAGE, "app.main", 1).unwrap();
let second = compile(PAGE, "app.main", 2).unwrap();
let mut tools = crate::developer_tools::DeveloperToolsState {
open: true,
selected_node_id: Some(first.root.as_ref().unwrap().children[0].id.clone()),
};
let mut tools = crate::developer_tools::DeveloperToolsState::default();
tools.open = true;
tools.selected_node_id = Some(first.root.as_ref().unwrap().children[0].id.clone());
tools.document_updated(&second);
assert_eq!(
tools.selected_node_id.as_deref(),
@@ -1060,13 +1365,13 @@ function main(): View { let child = ui.text("shared") return wrap(child) }"#;
assert!(error.to_string().contains("4096 node budget"), "{error:#}");
let error = compile(&nested_functions(14, true), "app.main", 2).unwrap_err();
assert!(
error.to_string().contains("expanded UI layout"),
error.to_string().contains("expanded Block graph"),
"{error:#}"
);
}
#[test]
fn ui_depth_is_bounded_independently_of_call_frames() {
fn managed_ui_depth_is_not_truncated_at_64_levels() {
let mut source = "function node0(): View { return ui.text(\"x\") }\n".to_owned();
for index in 1..=64 {
source.push_str(&format!(
@@ -1075,8 +1380,8 @@ function main(): View { let child = ui.text("shared") return wrap(child) }"#;
));
}
source.push_str("function main(): View { return node64() }");
let error = compile(&source, "app.main", 1).unwrap_err();
assert!(error.to_string().contains("64 levels"), "{error:#}");
let document = compile(&source, "app.main", 1).unwrap();
assert_eq!(document.frame.commands.len(), 1);
}
#[test]