feat: add system widgets and a persistent native Console with bare assignments
Verify Tessera GUI / verify (push) Failing after 7m17s

This commit is contained in:
2026-10-20 18:36:48 +08:00
parent 1d4b1d3c86
commit 53e8d7b287
15 changed files with 1549 additions and 245 deletions
+286 -2
View File
@@ -1,4 +1,5 @@
//! One source submission uses a fresh Aster VM and publishes an owned snapshot.
//! Compile complete source in a fresh VM or retain a worker-owned Console VM.
//! Console publishes owned native snapshots only after a successful explicit render.
use anyhow::{Result, bail};
use endor_core::{ExecutionLimits, ObjectRef, Value, Vm, VmError};
use frontend::{
@@ -140,7 +141,14 @@ pub fn evaluate(source: &str) -> Result<String> {
}
fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::CompiledCode>> {
let mut globals = BTreeSet::from(["ui".to_owned()]);
compile_plan_with_globals(source, plan, BTreeSet::from(["ui".to_owned()]))
}
fn compile_plan_with_globals(
source: &SourceUnit,
plan: &SourcePlan,
mut globals: BTreeSet<String>,
) -> Result<Vec<compiler::CompiledCode>> {
// Match Aster module behavior for function forward references. Bindings are
// added in source order; every executable statement still uses Aster's own
// single-input Interactive compiler and the candidate's shared globals.
@@ -167,6 +175,8 @@ fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::
for statement in &input.statements {
if let StmtKind::Binding(binding) = &statement.kind {
globals.insert(binding.name.text.clone());
} else if let StmtKind::Assignment(assignment) = &statement.kind {
globals.insert(assignment.name.text.clone());
}
}
}
@@ -174,6 +184,193 @@ fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::
Ok(compiled)
}
/// 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.
pub struct ReplSession {
candidate: Candidate,
bridge: ui_bridge::UiBridge,
pub id: u64,
inputs: usize,
ast_nodes: usize,
source: String,
nodes: Vec<CodeNode>,
}
pub struct ReplResult {
pub value: String,
pub document: Option<RenderDocument>,
pub bindings: usize,
pub input: usize,
}
impl ReplSession {
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))?;
Ok(Self {
candidate,
bridge,
id,
inputs: 0,
ast_nodes: 0,
source: String::new(),
nodes: Vec::new(),
})
}
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
if source.len() > MAX_SOURCE_BYTES {
bail!("input exceeds 1 MiB");
}
if self.inputs >= 256 || self.source.len() + source.len() + 80 > MAX_SOURCE_BYTES {
bail!("console session exceeds 256 inputs or 1 MiB; reset the session to continue");
}
let source = EndorReader::from_text(
format!("console session {} input {}", self.id, self.inputs + 1),
source,
);
let plan = endor_script::parse(&source)?;
let mut budget = AstBudget::default();
for ast in plan.roots() {
budget.visit_ast_root(ast)?;
}
if self.ast_nodes + budget.nodes > MAX_AST_NODES {
bail!("console session exceeds 10000 AST nodes; reset the session to continue");
}
let globals = self.candidate.globals.expect("live console globals");
let names = self
.candidate
.vm
.dict_items(globals)?
.iter()
.filter_map(|(key, _)| {
if let Value::Text(name) = key {
Some(name.clone())
} else {
None
}
})
.collect();
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.take_rendered()?;
self.inputs += 1;
self.ast_nodes += budget.nodes;
let offset = line_starts(&self.source).len();
self.source
.push_str(&format!("// Console input {}\n", self.inputs));
self.source.push_str(source.text());
if !self.source.ends_with('\n') {
self.source.push('\n');
}
let mut node = architecture(&source, &plan, namespace, self.inputs as u64);
node.name = format!("Input {}", self.inputs);
shift_node_lines(&mut node, offset);
self.nodes.push(node);
let result: Result<ReplResult> = (|| {
let limits = ExecutionLimits {
max_instructions: LIMITS.max_instructions / compiled.len().max(1),
..LIMITS
};
let mut rendered_value = "nil".to_owned();
for (ast, template) in plan.roots().iter().zip(&compiled) {
let code = template.load(&mut self.candidate.vm)?;
let executed = self
.candidate
.vm
.execute_with_limits(code, globals, limits)
.map_err(|error| runtime_error(&self.candidate.vm, error));
self.candidate.vm.release(code)?;
let value = executed?;
// Keep the actual last result accessible as `_`, including unnamed UI objects.
let display = if let AstRoot::Interactive(input) = ast {
match &input.statements[0].kind {
StmtKind::Binding(binding) => self
.candidate
.vm
.dict_get(globals, &Value::Text(binding.name.text.clone()))?
.unwrap_or_else(|| value.clone()),
StmtKind::Assignment(assignment) => self
.candidate
.vm
.dict_get(globals, &Value::Text(assignment.name.text.clone()))?
.unwrap_or_else(|| value.clone()),
_ => value.clone(),
}
} else {
value.clone()
};
let repr = value_repr(&self.candidate.vm, &display);
let retained =
self.candidate
.vm
.dict_set(globals, Value::Text("_".into()), display);
self.candidate.vm.release_value(value)?;
retained?;
rendered_value = repr?;
}
let document = if let Some(root) = self.bridge.take_rendered()? {
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: layout::frame(&root)?,
ui_root: Some(root),
};
document.validate()?;
Some(document)
} else {
None
};
Ok(ReplResult {
value: rendered_value,
document,
bindings: self
.candidate
.vm
.dict_items(globals)?
.len()
.saturating_sub(1),
input: self.inputs,
})
})();
if result.is_err() {
self.bridge.take_rendered()?;
if let Some(node) = self.nodes.last_mut() {
node.name
.push_str(" (error; earlier statements may remain live)");
}
}
result
}
}
fn shift_node_lines(node: &mut CodeNode, offset: usize) {
node.start_line += offset;
node.end_line += offset;
for child in &mut node.children {
shift_node_lines(child, offset);
}
}
fn value_repr(vm: &Vm, value: &Value) -> Result<String> {
Ok(match value {
Value::Nil => "nil".into(),
Value::Bool(v) => v.to_string(),
Value::Text(v) => format!("{v:?}"),
Value::Number(v) => v.to_string(),
Value::Object(v) => vm.repr(*v)?,
})
}
struct Candidate {
vm: Vm,
roots: Vec<ObjectRef>,
@@ -350,6 +547,15 @@ impl Architecture {
vec![child],
)
}
StmtKind::Assignment(assignment) => {
let child = self.expression(&assignment.value);
self.node(
assignment.name.text.clone(),
"assign",
statement.span,
vec![child],
)
}
StmtKind::Return(returned) => {
let children = returned
.value
@@ -398,6 +604,84 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn live_session_retains_real_objects_and_renders_only_on_request() {
let mut session = ReplSession::new(7).unwrap();
let created = session
.execute(
r##"title = ui.text("你好,Tessera", 2, "#243047")"##,
"app.main",
)
.unwrap();
assert!(created.document.is_none());
assert_eq!(
session.execute("title", "app.main").unwrap().value,
created.value
);
assert_eq!(
session.execute("_", "app.main").unwrap().value,
created.value
);
let rendered = session
.execute("page = ui.page()\npage.render(title)", "app.main")
.unwrap()
.document
.unwrap();
assert!(
matches!(&rendered.frame.commands[0], RenderCommand::Text { value, .. } if value == "你好,Tessera")
);
assert_eq!(rendered.root.as_ref().unwrap().kind, "repl-session");
assert!(
session
.execute(r#"title = ui.text("changed")"#, "app.main")
.unwrap()
.document
.is_none()
);
let updated = session
.execute("page.render(title)", "app.main")
.unwrap()
.document
.unwrap();
assert!(
matches!(&updated.frame.commands[0], RenderCommand::Text { value, .. } if value == "changed")
);
assert!(updated.source.contains("// Console input 6"));
assert!(
session
.execute("title", "app.main")
.unwrap()
.document
.is_none()
);
}
#[test]
fn live_session_compiles_before_execution_and_discards_failed_render() {
let mut session = ReplSession::new(8).unwrap();
session
.execute("value = 1\npage = ui.page()", "app.main")
.unwrap();
assert!(session.execute("value = 2\nmissing", "app.main").is_err());
assert_eq!(session.execute("value", "app.main").unwrap().value, "1");
assert!(
session
.execute(
"value = 3\npage.render(ui.text(\"discarded\"))\nui.rect(-1, 1, 0)",
"app.main"
)
.is_err()
);
let retained = session.execute("value", "app.main").unwrap();
assert_eq!(retained.value, "3");
assert!(retained.document.is_none());
session.execute("function local(value: Number): Number { result = value result = 42 return result }", "app.main").unwrap();
assert_eq!(
session.execute("local(40)", "app.main").unwrap().value,
"42"
);
}
#[test]
fn top_level_goal_script_renders_without_a_main_or_synthetic_wrapper() {
let document = compile(PAGE, "app.main", 9).unwrap();