use std::fs; use std::path::Path; use std::rc::Rc; use std::time::Duration; use crate::abi; use psychoscript::HostValue; use super::value; use super::vm::{Activation, CallOutcome, Compiled, HostBindings, MEMORY}; use super::*; use crate::client; use crate::loader::tests::script_loader_tests::{footer_text, install_script, settle_script}; use crate::loader::tests::{TestHost, dynamic, entry, host, logged}; use crate::loader::{Configured, Loader}; use crate::source::Sources; use crate::{Host, Registry, Status}; /// Tiny sync prelude for low-level `HostValue` serde and heap-cap tests that inspect raw `Activation` results. const ECHO_PRELUDE: &str = r#" import { done, fail } from "opencode:host" const handlers = [] export function define(setup) { return { setup } } export function tasked() { return { handler(fn) { return handlers.push(fn) - 1 } } } export function dispatch(call) { try { done(call[0], handlers[call[1]](call[2])) } catch (e) { fail(call[0], e?.name || "", e?.message || String(e), e?.stack || "") } } "#; fn echo_start(files: &[(&str, &str)], limit: Duration, memory: usize) -> Result { let srcs = Sources::from_files(files.iter().copied()); let compiled = Compiled::new(&srcs, "test.script", files[0].0, ECHO_PRELUDE)?; Activation::start(&compiled, ECHO_PRELUDE, limit, memory, |_| HostBindings::default()) } fn script_sources(init: &str) -> Sources { Sources::from_files([("plugin.toml", "id = \"test.script\"\ncontract = \"2.0\""), ("init.ts", init)]) } fn running(host: &Rc, definition: crate::Definition) -> Rc { let registry = Rc::new(Registry::define(Vec::new(), [])); registry.add(definition); registry.activate(&dynamic(host)); registry } fn plugin_with(host: &Rc, body: &str) -> Rc { let init = format!( "import {{ FENCE_NODE, FOCUS_INPUT, all, client, column, command, define, every, show, sleep, spawn, text }} from \"opencode:plugin\"\nexport default define((setup) => {{\n{body}\n}})\n" ); running(host, define(&script_sources(&init), None).unwrap().0) } fn reloadable(host: &Rc, init: &str) -> (Rc, impl Fn()) { let srcs = script_sources(init); let registry = Rc::new(Registry::define(Vec::new(), [])); let load = { let (host, registry, srcs) = (host.clone(), registry.clone(), srcs); move || { let (def, error) = define(&srcs, None).unwrap(); registry.load(&dynamic(&host), def.external("/plugins/test", error)); } }; load(); registry.activate(&dynamic(host)); (registry, load) } fn run_cmd(host: &TestHost, name: &str, input: Option<&str>) { host.keymap().dispatch(name, input); host.app.advance(Duration::from_millis(1)); } fn said(host: &TestHost) -> Vec { host.toasts.borrow().iter().filter(|t| t.variant == abi::Variant::Info).map(|t| t.message.clone()).collect() } fn failure(registry: &Registry, id: &str) -> Option { registry.entries().into_iter().find(|e| e.id == id).and_then(|e| match e.status { Status::Failed(err) => Some(err), _ => None, }) } fn asked(host: &TestHost) -> (abi::Dialog, (String, Option)) { let (_, dialog) = host.dialogs.borrow().last().expect("no dialog shown").clone(); match dialog { abi::Dialog::Dismissable { dialog, dismissed } => { let abi::Action::Command { name, input } = dismissed; (*dialog, (name, input)) } other => panic!("expected dismissable dialog: {other:?}"), } } fn answers(dialog: &abi::Dialog) -> String { let action = match dialog { abi::Dialog::Select(s) => &s.action, abi::Dialog::Prompt(p) => &p.action, abi::Dialog::Confirm(c) => &c.action, other => panic!("dialog has no answer action: {other:?}"), }; let abi::Action::Command { name, .. } = action; name.clone() } fn answer_fetch(host: &TestHost, result: Result) { let (_, reply) = host.fetches.borrow_mut().remove(0); reply(result); host.app.advance(Duration::from_millis(1)); } fn loader(config: &Path, cwd: &Path) -> Loader { Loader::new(config.to_path_buf(), cwd.to_path_buf(), Vec::::new()).with_script(|| {}) } fn cpu(f: impl FnOnce() -> R) -> (Duration, R) { let start = crate::contain::thread_cpu().expect("this OS gives a thread's CPU time"); let result = f(); (crate::contain::thread_cpu().unwrap().saturating_sub(start), result) } /// A plugin in `dir` whose `init.ts` holds an array literal of `items` numbers: about `2 * items` bytes. fn big_plugin(dir: &Path, items: usize) { fs::create_dir_all(dir).unwrap(); fs::write(dir.join(MANIFEST), "id = \"test.big\"\n").unwrap(); let init = format!( "import {{ define }} from \"opencode:plugin\"\nconst big = [{}]\nexport default define(() => {{ void big }})\n", "1,".repeat(items) ); fs::write(dir.join("init.ts"), init).unwrap(); } fn checked(body: &str) -> (Vec, Option) { let host = host(); let registry = plugin_with( &host, &format!( " setup.command({{ name: \"check\" }}, (host) => {{\n const say = (message: string) => host.toast({{ variant: \"info\", message }})\n {body}\n }})" ), ); run_cmd(&host, "check", None); (said(&host), failure(®istry, "test.script")) } // --- Error reporting, serde crossing, and decoder/crossing bounds --- #[test] fn a_script_error_names_the_plugin_the_file_and_the_line() { let syntax = "import { define } from \"opencode:plugin\"\n\nconst = 1\n"; let err = define(&script_sources(syntax), None).err().unwrap(); assert!(err.starts_with("test.script: init.ts:3:"), "{err}"); let util = "export function width(node: { text: string }) {\n return node.text.length\n}\n"; let init = r#"import { define } from "opencode:plugin" import { width } from "./lib/util.ts" export default define((setup) => { setup.command({ name: "boom" }, () => { void width(null as unknown as { text: string }) }) setup.command({ name: "raw" }, () => { throw "raw boom" }) }) "#; let mut srcs = script_sources(init); srcs.files.insert("lib/util.ts".into(), util.as_bytes().to_vec()); let h = host(); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "boom", None); let error = failure(®, "test.script").unwrap(); assert!(error.starts_with("test.script: lib/util.ts:2:") && error.contains("TypeError:"), "{error}"); let traceback = error.split_once("\nstack traceback:\n").map(|(_, frames)| frames).unwrap_or_default(); assert!(traceback.contains("lib/util.ts:2:") && traceback.contains("init.ts:5:"), "{error}"); for noise in ["opencode:entry", "opencode:plugin", "opencode:host"] { assert!(!error.contains(noise), "{noise}: {error}"); } let h = host(); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "raw", None); let error = failure(®, "test.script").unwrap(); assert!(error.starts_with("test.script:") && error.contains("raw boom"), "{error}"); } #[test] fn a_long_error_is_cut_and_escaped() { let init = r#"import { define } from "opencode:plugin" export default define((setup) => { setup.command({ name: "big" }, () => { throw new Error("\x1b]0;title\x07" + "E".repeat(6 * 1024 * 1024)) }) }) "#; let h = host(); let reg = running(&h, define(&script_sources(init), None).unwrap().0); run_cmd(&h, "big", None); let error = failure(®, "test.script").unwrap(); assert!(error.len() < 4096 + 200, "{} bytes: {:?}", error.len(), error.get(..200)); assert!(error.starts_with("test.script: init.ts:4:"), "{:?}", error.get(..200)); assert!(error.contains(r"\u{1b}]0;title\u{7}EEE") && !error.contains('\u{1b}')); let (message, frames) = error.split_once("\nstack traceback:\n").unwrap_or((&error, "")); assert!(message.ends_with(" bytes)") && frames.contains("init.ts:4:"), "{error}"); } #[test] fn a_json_value_crosses_into_script_and_back() { let init = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.handler((value) => value) setup.handler((input) => ({ hasSession: "session_id" in input, hasPrompt: "prompt" in input, sessionIsUndef: input.session_id === undefined, nullKept: input.null_field === null, })) }) "#; let mut act = echo_start(&[("init.js", init)], Duration::from_secs(2), MEMORY).unwrap(); let sample = serde_json::json!({ "a": [1, null, "x", { "b": null, "c": 2.5, "neg": -42 }], "d": { "e": [], "f": {} }, "é ü": true, "n": null, "s": "ß\u{0}t", }); let CallOutcome::Done(back) = act.call(0, vec![value::to_host(&sample).unwrap()]).unwrap() else { panic!("sync handler waited") }; assert_eq!(value::from_host::(&back).unwrap(), sample); // A 300-entry map and mixed-shape records cross cleanly too. let many: serde_json::Map = (0..300).map(|i| (format!("ses_{i}"), serde_json::json!({ "id": i }))).collect(); let page = serde_json::json!({ "data": [{ "id": "msg_0", "time": { "created": 0 } }, { "id": "msg_1" }], "many": many, }); let CallOutcome::Done(back) = act.call(0, vec![value::to_host(&page).unwrap()]).unwrap() else { panic!("sync handler waited") }; assert_eq!(value::from_host::(&back).unwrap(), page); // Contract types: Option::None is omitted (undefined), while JSON null stays null. #[derive(serde::Serialize)] struct Probe { session_id: Option, prompt: Option, null_field: serde_json::Value, } let probe = Probe { session_id: None, prompt: Some(true), null_field: serde_json::Value::Null }; let CallOutcome::Done(seen) = act.call(1, vec![value::to_host(&probe).unwrap()]).unwrap() else { panic!("sync handler waited") }; assert_eq!( value::from_host::(&seen).unwrap(), serde_json::json!({ "hasSession": false, "hasPrompt": true, "sessionIsUndef": true, "nullKept": true }) ); // ABI contract types round-trip directly with no JSON step. let render = abi::Render::Show(abi::Node::Text { spans: vec![abi::Span::new("hello").fg("text.muted")], fg: None, wrap: abi::Wrap::default(), truncate: false, selectable: true, hover_fg: None, layout: abi::Layout::default(), on_click: Some(abi::Click::command("hello.greet")), }); let CallOutcome::Done(back) = act.call(0, vec![value::to_host(&render).unwrap()]).unwrap() else { panic!("sync handler waited") }; assert_eq!(value::from_host::(&back).unwrap(), render); } #[test] fn a_node_tree_decodes_as_serde_reads_it() { fn check(js_expr: &str) -> String { let init = format!( "import {{ define }} from \"opencode:plugin\"\nexport default define((setup) => {{ setup.handler(() => {{ {js_expr} }}) }})\n" ); let mut act = echo_start(&[("init.js", &init)], Duration::from_secs(2), MEMORY).unwrap(); let CallOutcome::Done(HostValue::Array(items)) = act.call(0, vec![]).unwrap() else { panic!("expected array of cases") }; items .iter() .enumerate() .map(|(at, item)| { let val = item.as_ref().unwrap_or(&HostValue::Undefined); let direct = value::from_host::(val); let json = value::from_host::(val).unwrap(); let serde = serde_json::from_value::(json.clone()); match (&direct, &serde) { (Ok(a), Ok(b)) => assert_eq!(a, b, "case {} ({json})", at + 1), (Err(_), Err(_)) => {} (a, b) => panic!("case {} ({json}): direct={a:?}, serde={b:?}", at + 1), } if direct.is_ok() { '+' } else { '-' } }) .collect() } let renders = r##" const click = { action: { type: "command", name: "x" }, on: "up" } const span = { text: "a", fg: "text.muted", bg: "#010203ff", bold: true, italic: true, underline: true, dim: true, strikethrough: true, link: "https://x" } const text = { type: "text", spans: [span, { text: "b", fg: "#abcdef" }], fg: "#abcdef", wrap: "char", truncate: true, selectable: false, hover_fg: "accent", layout: { grow: true }, on_click: click } const box = { type: "box", row: true, gap: 2, padding: [1, 2], justify: "space-between", align: "center", bg: "#11223344", layout: { grow: true }, on_click: click, border: { title: "t" }, padding_sides: { top: 1, left: -1 }, wrap: true, overflow: "hidden", children: [ text, { type: "slot", path: "home.footer.x" }, { type: "markdown", text: "**m**" }, { type: "spinner", label: "l" }, { type: "box" }, { type: "text", spans: [] }, ] } return [ { type: "show", node: box }, { type: "keep" }, { type: "hide" }, { type: "show", node: { type: "text", spans: [{ text: "c" }], id: "unknown key" } }, { type: "show", node: { type: "text", spans: [], on_click: { action: { type: "command", name: "x", input: "v" }, on: "down" } } }, { type: "show", node: { type: "text", spans: [], on_click: { action: { type: "nope" }, on: "up" } } }, { type: "show", node: { type: "text", spans: [], on_click: { action: { type: "command", name: "x" } } } }, { type: "show", node: { type: "text", spans: [], on_click: { action: click.action, on: "sideways" } } }, { type: "show", node: { type: "nope" } }, { type: "show", node: { type: "text" } }, { type: "show", node: { type: "box", gap: "x" } }, { type: "show", node: { type: "box", gap: 70000 } }, { type: "show", node: { type: "text", spans: [{ text: 1 }] } }, { type: "show", node: { type: "text", spans: [{ text: "a", fg: 5 }] } }, { type: "show", node: { type: "text", spans: [{ fg: "x" }] } }, { type: "show", node: { type: "box", children: [{ type: "box", children: [{ type: "x" }] }] } }, { type: "show", node: { type: "box", children: { a: 1 } } }, { type: "show", node: "x" }, { type: "show", node: { type: "text", spans: ["a"] } }, { type: "show", node: { type: "box", children: [1, true] } }, { type: "show", node: { type: "box", justify: 5 } }, { type: "show" }, { type: "keep", node: box }, { type: "wat" }, { node: box }, "show", 5, ] "##; assert_eq!(check::(renders), "+++++----------------------"); let surfaces = r##" return [ { type: "box", id: "b", row: true, gap: 1, visible: false, bg: "text.base", children: [ { type: "text", id: "t", spans: [{ text: "x", bold: true }], hover_events: true }, { type: "box", focusable: true, id: "f" }, { type: "spinner", label: "s" }, ] }, { type: "text", spans: [] }, { type: "box", children: [{ type: "text", spans: [{ text: 1 }] }] }, { type: "text", spans: [{ text: "x" }], hover_events: "yes" }, ] "##; assert_eq!(check::(surfaces), "++--"); } #[test] fn decoder_bounds_refuse_depth_text_parts_ignored_fields_and_functions() { let refused = |val: &HostValue| -> Vec { [value::from_host::(val).map(drop), value::from_host::(val).map(drop)] .into_iter() .map(|res| match res { Err(value::Error::Limit(why)) => format!("bound: {why}"), Err(value::Error::Message(why)) => format!("value: {why}"), Ok(()) => "decoded".to_owned(), }) .collect() }; // Nesting past 128 levels in HostDeserializer. let mut boxes = HostValue::object([("type", HostValue::from("box"))]); for _ in 0..70 { boxes = HostValue::object([("type", HostValue::from("box")), ("children", HostValue::array([boxes]))]); } let deep = HostValue::object([("type", HostValue::from("show")), ("node", boxes)]); for got in refused(&deep) { assert!(got.starts_with("bound:") && got.contains("nested deeper than 128 levels"), "{got}"); } // Text byte limit (`Limits::plugin_content`). let restore = crate::limits::set(crate::limits::Limits { plugin_content: 8, ..crate::limits::Limits::default() }); let long_span = HostValue::object([ ("type", HostValue::from("show")), ( "node", HostValue::object([ ("type", HostValue::from("text")), ("spans", HostValue::array([HostValue::object([("text", HostValue::from("more than 8"))])])), ]), ), ]); for got in refused(&long_span) { assert!(got.starts_with("bound:") && got.contains("its text is more than 8 bytes"), "{got}"); } drop(restore); // Parts limit (`16 * Limits::nodes`): exact boundary succeeds, +1 fails, and ignored struct fields still charge. let restore = crate::limits::set(crate::limits::Limits { nodes: 2, ..crate::limits::Limits::default() }); let exact = HostValue::array((0..31).map(|i| HostValue::Number(f64::from(i)))); assert_eq!(value::from_host::>(&exact).unwrap().len(), 31); let over = HostValue::array((0..32).map(|i| HostValue::Number(f64::from(i)))); let err = value::from_host::>(&over).unwrap_err(); assert!(err.is_limit() && err.to_string().contains("more than 32 parts"), "{err}"); #[derive(serde::Deserialize, Debug)] struct Small { #[allow(dead_code)] keep: u32, } let sneaked = HostValue::object([("keep", HostValue::Number(1.0)), ("ignored", over)]); assert!(value::from_host::(&sneaked).unwrap_err().is_limit(), "ignored field must still be charged"); drop(restore); // JS crossing limits: functions, shared strings past max_value_string_bytes, and nesting past max_value_depth. let js = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.handler(() => ({ text: () => {} })) setup.handler(() => { const s = "a".repeat(1024 * 1024); return Array.from({ length: 40 }, () => s) }) setup.handler(() => { let d: unknown = "leaf"; for (let i = 0; i < 140; i++) d = [d]; return d }) }) "#; for (idx, expected) in [(0, &["TypeError", "function"][..]), (1, &["RangeError"][..]), (2, &["depth", "TypeError"][..])] { let mut act = echo_start(&[("init.ts", js)], Duration::from_secs(2), MEMORY).unwrap(); let err = act.call(idx, vec![]).unwrap_err(); assert!(expected.iter().any(|needle| err.contains(needle)), "case {idx}: {err}"); } } // U4 bound test: shared DAG, sparse arrays, and uncatchable host refusals stop before blowing up host memory; // small shared values, exact-budget arrays, and a 200-row output-heavy render still succeed. #[test] fn crossing_bounds_stop_shared_dags_sparse_arrays_and_uncatchable_refusals() { let render_built = |build: &str| -> (Option, Duration) { let h = host(); let init = format!( "import {{ define, show }} from \"opencode:plugin\"\nlet node: unknown\n{build}\nexport default define((setup) => {{\n setup.slot({{ path: \"home.footer\" }}, () => show(node))\n}})\n" ); let reg = running(&h, define(&script_sources(&init), None).unwrap().0); let (used, _) = cpu(|| footer_text(&h, ®)); (failure(®, "test.script"), used) }; // Small shared leaf and 200-row output-heavy render succeed. assert_eq!( render_built( r#"const leaf = { text: "leaf", bold: true } node = { type: "box", children: [{ type: "text", spans: [leaf, leaf] }, { type: "text", spans: [leaf] }] }"# ) .0, None ); assert_eq!( render_built( r#"const rows = [] for (let i = 1; i <= 200; i++) rows.push({ type: "text", spans: [{ text: "row ", fg: "text.muted" }, { text: String(i), bold: true }] }) node = { type: "box", row: false, children: rows }"# ) .0, None ); // 20-level shared DAG and 1M shared sparse array are refused quickly by U4 max_value_nodes. for (name, build) in [ ( "dag", r#"node = { type: "text", spans: [{ text: "leaf" }] } for (let i = 0; i < 20; i++) node = { type: "box", children: [node, node] }"#, ), ( "sparse", r#"const sparse = new Array(1048576); sparse[0] = { type: "text", spans: [] } const inner = { type: "box", children: sparse } node = { type: "box", children: Array.from({ length: 1000 }, () => inner) }"#, ), ] { let (failed, used) = render_built(build); let failed = failed.unwrap_or_else(|| panic!("{name} must be refused")); assert!(used < Duration::from_millis(500), "{name} took {used:?}"); assert!(failed.contains("RangeError") || failed.contains("more than"), "{name}: {failed}"); } // Sparse array counted before filling gaps vs exact 15-item sequence under nodes = 1 (16 parts). let restore = crate::limits::set(crate::limits::Limits { nodes: 1, ..crate::limits::Limits::default() }); let h = host(); let reg = plugin_with( &h, r#" setup.storageKey("items") setup.command({ name: "sparse" }, (host) => { const sparse = new Array(100000) sparse[99999] = "x" host.storageSet("items", sparse) }) setup.command({ name: "sequence" }, (host) => { host.storageSet("items", Array.from({ length: 15 }, () => "x")) }) "#, ); run_cmd(&h, "sequence", None); assert_eq!(failure(®, "test.script"), None); assert_eq!(h.storage.borrow().values().next().unwrap(), &serde_json::to_string(&["x"; 15]).unwrap()); run_cmd(&h, "sparse", None); let err = failure(®, "test.script").expect("sparse refused"); assert!(err.contains("more than 16 parts") || err.contains("RangeError"), "{err}"); drop(restore); // Value between parts_limit (32) and max_value_nodes (48) triggers uncatchable Refusal::refuse; past 48 trips U4. let _restore = crate::limits::set(crate::limits::Limits { nodes: 2, ..crate::limits::Limits::default() }); let (toasts, failed) = checked( r#"const spans = Array.from({ length: 36 }, (_, i) => i) try { host.storageSet("big", spans) } catch {} say("after the refusal")"#, ); assert!(failed.expect("caught refusal must fail").contains("more than 32 parts")); assert!(toasts.is_empty(), "{toasts:?}"); let (toasts, failed) = checked( r#"const spans = Array.from({ length: 50 }, () => ({ text: "x" })) host.storageSet("big", spans) say("after the refusal")"#, ); assert!(failed.expect("U4 refusal must fail").contains("RangeError")); assert!(toasts.is_empty(), "{toasts:?}"); } // --- Render/setup contracts, console, lazy Changed, and idle memory --- #[test] fn a_render_that_asks_for_an_effect_fails() { let run_footer = |init: &str| -> (Rc, Option) { let h = host(); let reg = running(&h, define(&script_sources(init), None).unwrap().0); _ = footer_text(&h, ®); let err = failure(®, "test.script"); (h, err) }; for (label, init, expected_prefix, expected_msg) in [ ( "read.toast", r#"import { define } from "opencode:plugin" export default define((setup) => { setup.slot({ path: "home.footer" }, (read) => { (read as any).toast({ variant: "info", message: "from a render" }) }) })"#, "test.script:", "not a function", ), ( "saved host.toast", r#"import { define } from "opencode:plugin" export default define((setup) => { const held = setup.host setup.slot({ path: "home.footer" }, () => { held.toast({ variant: "info", message: "from a render" }) }) })"#, "test.script:", "a render or a view may read, and ask for nothing", ), ( "arrow async render", r#"import { define, show, text } from "opencode:plugin" export default define((setup) => { setup.slot({ path: "home.footer" }, async () => show(text("async render"))) })"#, "test.script: init.ts:3:", "TypeError: a render cannot wait", ), ( "named async render", r#"import { define, show, text } from "opencode:plugin" async function slowRender() { return show(text("async render")) } export default define((setup) => { setup.slot({ path: "home.footer" }, slowRender) })"#, "test.script: init.ts:3:", "TypeError: a render cannot wait", ), ] { let (h, err) = run_footer(init); let err = err.unwrap_or_else(|| panic!("{label} must fail")); assert!(err.starts_with(expected_prefix) && err.contains(expected_msg), "{label}: {err}"); assert!(h.toasts.borrow().iter().all(|t| t.message != "from a render"), "{label}"); } // Async setup (both `define(async ...)` and bare `export default async function`) locates at setup's line. for (label, src, expected_prefix) in [ ( "define async", "import { define } from \"opencode:plugin\"\n\nexport default define(async () => {\n await Promise.resolve()\n})\n", "test.script: init.ts:3:", ), ( "bare async default", "export default async function setup() {\n await Promise.resolve()\n}\n", "test.script: init.ts:1:", ), ] { let compiled = vm::Compiled::new(&script_sources(src), "test.script", "init.ts", bind::PRELUDE).unwrap(); let mut reg = abi::Registered::new("test.script", None); let err = bind::setup(&compiled, &mut reg.setup(), Duration::from_millis(100), MEMORY, None) .err() .unwrap_or_else(|| panic!("{label}: async setup must fail")); assert!( err.starts_with(expected_prefix) && err.contains("TypeError: plugin setup cannot wait"), "{label}: {err}" ); } } #[test] fn console_writes_one_escaped_line_to_the_log() { let logged = logged(); let h = host(); let init = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.command({ name: "print" }, () => { console.log("\x1b]0;title\x07\x1b[2J", 1, null, true) console.info("x".repeat(8 * 1024 * 1024)) }) }) "#; let srcs = Sources::from_files([("plugin.toml", "id = \"test.script.print\""), ("init.ts", init)]); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "print", None); assert_eq!(failure(®, "test.script.print"), None); let printed: Vec = logged.lock().unwrap().iter().filter(|line| line.starts_with("plugin test.script.print ")).cloned().collect(); let [escaped, cut] = printed.as_slice() else { panic!("{printed:?}") }; assert_eq!(escaped, r"plugin test.script.print printed: \u{1b}]0;title\u{7}\u{1b}[2J 1 null true"); assert_eq!( *cut, format!("plugin test.script.print printed: {}... ({} bytes, cut at 4096)", "x".repeat(4096), 8 << 20) ); } #[test] fn render_arity_and_lazy_changed_deliver_exact_fields() { let init = r#" import { define, show, span, text } from "opencode:plugin" const line = (s: string) => show(text([span(s)])) export default define((setup) => { setup.slot({ path: "home.footer" }, () => line("zero")) setup.slot({ path: "home.footer" }, (_read, input) => line("two:" + String(input.session_id))) setup.slot({ path: "home.footer" }, (_read, input, changed) => { const keys = Object.keys(changed).sort().join(",") const spread = { ...changed } const s1 = changed.sessions ? changed.sessions.join(",") : "none" const s2 = changed.sessions ? changed.sessions.length : 0 const l = changed.lists ? changed.lists.join(",") : "none" const m = spread.messages ? spread.messages[0][1] : "none" return line([keys, input.session_id, s1, s2, l, m, changed.local, changed.all].map(String).join("|")) }) setup.slot({ path: "home.footer" }, (...args: any[]) => line("rest:" + (args[2].sessions ? args[2].sessions.length : 0))) setup.route("r0", () => line("route0")) setup.route("r2", (_read, changed) => line("route2:" + Object.keys(changed).sort().join(",") + ":" + String(changed.all))) }) "#; let compiled = vm::Compiled::new(&script_sources(init), "test.arity", "init.ts", bind::PRELUDE).unwrap(); let mut reg = abi::Registered::new("test.arity", None); let _plugin = bind::setup(&compiled, &mut reg.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); struct DummyRead; impl abi::Read for DummyRead { fn theme_mode(&self) -> abi::ThemeMode { abi::ThemeMode::Dark } fn color(&self, _: &str) -> Option { None } } let slot_input = abi::SlotInput { session_id: Some("ses_1".into()), ..abi::SlotInput::default() }; let changed = abi::Changed { sessions: vec!["ses_1".into(), "ses_2".into()], lists: vec!["list_a".into()], messages: vec![("ses_1".into(), "msg_9".into())], local: true, ..abi::Changed::default() }; let text_of = |r: abi::Render| match r { abi::Render::Show(abi::Node::Text { spans, .. }) => spans[0].text.clone(), other => panic!("{other:?}"), }; let renders: Vec<_> = reg.renders().map(|(_, _, r)| r).collect(); assert_eq!(text_of(renders[0](&DummyRead, &slot_input, &changed)), "zero"); assert_eq!(text_of(renders[1](&DummyRead, &slot_input, &changed)), "two:ses_1"); assert_eq!( text_of(renders[2](&DummyRead, &slot_input, &changed)), "lists,local,messages,sessions|ses_1|ses_1,ses_2|2|list_a|msg_9|true|undefined" ); assert_eq!(text_of(renders[3](&DummyRead, &slot_input, &changed)), "rest:2"); assert_eq!(text_of((reg.routes()[0].1)(&DummyRead, &changed)), "route0"); assert_eq!(text_of((reg.routes()[1].1)(&DummyRead, &abi::Changed::everything())), "route2:all:true"); assert_eq!(text_of((reg.routes()[1].1)(&DummyRead, &abi::Changed::default())), "route2::undefined"); } #[test] fn hello_example_compiles_and_measures_idle_memory() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/script/hello"); let bytes = idle_memory(&read(&dir).unwrap()).unwrap(); assert!(bytes > 0 && bytes < 256 * 1024, "unexpected idle heap for hello: {bytes} bytes"); } // --- Tasks, waits, dialogs, timers, and client Namespace --- #[test] fn a_dialog_answers_its_task_and_an_escape_gives_nil() { let h = host(); let reg = plugin_with( &h, r#" const say = (host, msg) => host.toast({ variant: "info", message: msg }) setup.command({ name: "ask" }, async (host) => { say(host, "confirm " + String(await host.confirm({ title: "Sure?", message: "Really", label: { confirm: "Yes", cancel: "No" } }))) say(host, "prompt " + String(await host.prompt({ title: "Name", placeholder: "a name" }))) await host.alert({ title: "Told", message: "said" }) say(host, "alerted") }) setup.command({ name: "pick" }, async (host) => { say(host, "pick " + String(await host.select({ title: "Pick", key: "rich", options: [{ title: "One", value: "1" }] }))) }) "#, ); run_cmd(&h, "ask", None); let (dialog, closed) = asked(&h); let answer = answers(&dialog); let abi::Dialog::Confirm(confirm) = dialog else { panic!("{dialog:?}") }; assert_eq!((confirm.title.as_str(), confirm.message.as_str()), ("Sure?", "Really")); run_cmd(&h, &answer, Some("true")); run_cmd(&h, &closed.0, closed.1.as_deref()); assert_eq!(said(&h), ["confirm true"]); let (dialog, closed) = asked(&h); assert!(matches!(dialog, abi::Dialog::Prompt(ref prompt) if prompt.title == "Name"), "{dialog:?}"); run_cmd(&h, &closed.0, closed.1.as_deref()); assert_eq!(said(&h)[1..], ["prompt undefined"]); let (dialog, closed) = asked(&h); assert!(matches!(dialog, abi::Dialog::Alert(_)), "{dialog:?}"); run_cmd(&h, &closed.0, closed.1.as_deref()); assert_eq!(said(&h)[2..], ["alerted"]); // A select replaced by a confirm: the select's close answers its task undefined, and the confirm's answer is its own. run_cmd(&h, "pick", None); let (pick, replaced) = asked(&h); assert!(matches!(pick, abi::Dialog::Select(select) if select.key.is_none())); run_cmd(&h, "ask", None); let (dialog, closed) = asked(&h); run_cmd(&h, &replaced.0, replaced.1.as_deref()); assert_eq!(said(&h)[3..], ["pick undefined"]); run_cmd(&h, &answers(&dialog), Some("false")); run_cmd(&h, &closed.0, closed.1.as_deref()); assert_eq!(said(&h)[4..], ["confirm false"]); assert_eq!(failure(®, "test.script"), None); } #[test] fn plugin_all_waits_for_each_of_its_tasks() { let h = host(); let reg = plugin_with( &h, r#" const get = (host, path) => () => host.fetch({ method: "GET", path }) setup.command({ name: "all" }, async (host) => { try { const values = await all([get(host, "/a"), get(host, "/b"), () => 3]) host.toast({ variant: "info", message: values[0].name + values[1].name + values[2] }) } catch (err) { host.toast({ variant: "info", message: "failed " + err.message }) } }) "#, ); run_cmd(&h, "all", None); assert_eq!(h.fetches.borrow().len(), 2); h.reply(); h.app.advance(Duration::from_millis(1)); assert_eq!(said(&h), ["/a/b3"]); run_cmd(&h, "all", None); answer_fetch(&h, Err("Transport: down".to_owned())); assert_eq!(said(&h).len(), 1, "{:?}", said(&h)); answer_fetch(&h, Ok(serde_json::json!({ "name": "/b" }))); assert_eq!(said(&h)[1..], ["failed Transport: down"]); assert_eq!(failure(®, "test.script"), None); } #[test] fn typed_calls_check_field_names_and_return_data() { let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "call" }, async (host) => { const hasSession = Object.keys(client).includes("session") const items = await client.session.inbox.list({ sessionID: "ses 1" }) let misspelled = "" try { await client.session.inbox.list({ sesionID: "ses_1" }) } catch (e) { misspelled = e.name + ":" + e.message } let unknown = "" try { await client.session.nothing({ sessionID: "ses_1" }) } catch (e) { unknown = e.name + ":" + e.message } const created = await client.session.create({}) host.toast({ variant: "info", message: [hasSession, items.length, misspelled, unknown, created.id].join(" | ") }) }) "#, ); run_cmd(&h, "call", None); answer_fetch(&h, Ok(serde_json::json!({ "data": [{ "id": "a" }, { "id": "b" }] }))); let (method, path, body) = { let fetch = &h.fetches.borrow()[0].0; (fetch.method.clone(), fetch.path.clone(), fetch.body.clone()) }; assert_eq!((method.as_str(), path.as_str(), body), ("POST", "/api/session", Some(serde_json::json!({})))); answer_fetch(&h, Ok(serde_json::json!({ "data": { "id": "ses_new" } }))); assert_eq!( said(&h), [ "true | 2 | HostError:session.inbox.list: no field sesionID | HostError:plugin.client has no operation session.nothing | ses_new" ] ); assert_eq!(failure(®, "test.script"), None); } #[test] fn a_wait_outside_a_task_is_refused() { for (body, render, expected) in [ ( r#"const held = setup.host setup.slot({ path: "home.footer" }, () => { held.confirm({ title: "no", message: "no" }); return show(text("drawn")) })"#, true, "host.confirm waits, and only a task can", ), (r#"setup.host.fetch({ method: "GET", path: "/x" })"#, false, "host.fetch waits, and only a task can"), (r#"client.session.list({})"#, false, "client.session.list waits, and only a task can"), ] { let h = host(); let reg = plugin_with(&h, body); if render { assert!(!footer_text(&h, ®).contains("drawn")); } let err = failure(®, "test.script").expect("wait outside task must fail"); assert!(err.contains(expected), "{expected}: {err}"); } } #[test] fn the_cpu_budget_holds_for_each_stretch_of_a_task() { let h = host(); let body = r#" const work = () => { let sum = 0; for (let i = 0; i < 10_000; i++) sum += i; return sum } setup.command({ name: "twice" }, async (host) => { work() await host.fetch({ method: "GET", path: "/x" }) work() host.toast({ variant: "info", message: "both" }) }) setup.command({ name: "spin" }, async (host) => { await host.fetch({ method: "GET", path: "/x" }) host.toast({ variant: "info", message: "spun" }) while (true) {} }) setup.command({ name: "raise" }, async (host) => { await host.fetch({ method: "GET", path: "/x" }) throw new Error("after the reply") }) "#; let reg = plugin_with(&h, body); run_cmd(&h, "twice", None); h.reply(); h.app.advance(Duration::from_millis(1)); assert_eq!((said(&h), failure(®, "test.script")), (vec!["both".into()], None)); run_cmd(&h, "spin", None); h.reply(); h.app.advance(Duration::from_millis(1)); let error = failure(®, "test.script").expect("the spin was stopped"); assert!(error.contains("script budget") && !said(&h).contains(&"spun".to_owned()), "{error}"); let reg = plugin_with(&h, body); run_cmd(&h, "raise", None); h.reply(); h.app.advance(Duration::from_millis(1)); let error = failure(®, "test.script").expect("the error failed the plugin"); assert!(error.contains("init.ts:") && error.contains("after the reply"), "{error}"); } #[test] fn a_parked_task_is_dropped_with_its_activation() { let h = host(); let init = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.command({ name: "wait" }, async (host) => { await host.fetch({ method: "GET", path: "/x" }) host.toast({ variant: "info", message: "resumed" }) }) setup.command({ name: "ask" }, async (host) => { await host.confirm({ title: "t", message: "m" }) host.toast({ variant: "info", message: "answered" }) }) }) "#; let (reg, reload) = reloadable(&h, init); run_cmd(&h, "wait", None); reload(); h.reply(); h.app.advance(Duration::from_millis(1)); assert!(said(&h).is_empty(), "{:?}", said(&h)); run_cmd(&h, "wait", None); h.reply(); h.app.advance(Duration::from_millis(1)); assert_eq!(said(&h), ["resumed"]); run_cmd(&h, "wait", None); run_cmd(&h, "ask", None); let (dialog, closed) = asked(&h); assert!(reg.set_active(&dynamic(&h), "test.script", false)); h.reply(); run_cmd(&h, &answers(&dialog), Some("true")); run_cmd(&h, &closed.0, closed.1.as_deref()); assert_eq!((said(&h), failure(®, "test.script")), (vec!["resumed".into()], None)); } #[test] fn a_plugin_parks_at_most_256_tasks() { let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "many" }, (host, input) => { for (let i = 0; i < Number(input); i++) spawn(async () => { await host.fetch({ method: "GET", path: "/x" }) }) }) "#, ); run_cmd(&h, "many", Some("256")); assert_eq!((h.fetches.borrow().len(), failure(®, "test.script")), (256, None)); h.reply(); h.app.advance(Duration::from_millis(1)); run_cmd(&h, "many", Some("256")); assert_eq!((h.fetches.borrow().len(), failure(®, "test.script")), (256, None)); run_cmd(&h, "many", Some("1")); let error = failure(®, "test.script").expect("the 257th wait failed"); assert!(error.contains("host.fetch: more than 256 tasks of the plugin wait"), "{error}"); } #[test] fn a_key_handler_that_waits_takes_its_key() { let init = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.layer({ scope: "global", keys: [{ key: "x", name: "wait" }, { key: "y", name: "pass" }] }, async (host, event) => { if (event.bind === "wait") await host.fetch({ method: "GET", path: "/x" }) return "pass" }) }) "#; let mut registered = abi::Registered::new("test.script", None); let compiled = vm::Compiled::new(&script_sources(init), "test.script", "init.ts", bind::PRELUDE).unwrap(); let _plugin = bind::setup(&compiled, &mut registered.setup(), Duration::from_millis(100), MEMORY, None).unwrap(); let handler = registered.layers()[0].1.clone(); let key = |bind: &str| -> abi::interact::Event { serde_json::from_value(serde_json::json!({ "type": "key", "key": "x", "bind": bind })).unwrap() }; struct MinHost; impl abi::Read for MinHost { fn theme_mode(&self) -> abi::ThemeMode { abi::ThemeMode::Dark } fn color(&self, _: &str) -> Option { None } } impl abi::Host for MinHost { fn storage_set(&self, _: &str, _: serde_json::Value) {} fn dispatch(&self, _: &str, _: Option<&str>) {} fn toast(&self, _: abi::Toast) {} fn attention(&self, _: abi::Attention) {} fn open_route(&self, _: &str) {} fn navigate(&self, _: abi::Route) {} fn try_fetch(&self, _: abi::Fetch) -> Result { Ok(abi::RequestId(1)) } fn dialog(&self, _: abi::Dialog) {} fn copy(&self, _: &str, _: Option) {} } assert_eq!(handler(&MinHost, &key("wait")), abi::interact::Handled::Consume); assert_eq!(handler(&MinHost, &key("pass")), abi::interact::Handled::Pass); } #[test] fn an_answer_after_eight_replacements_reaches_its_own_dialog() { let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "ask" }, (host) => { for (let at = 1; at <= 9; at++) { const n = at spawn(async () => { const answer = await host.prompt({ title: "prompt " + n }) host.toast({ variant: "info", message: n + " " + String(answer) }) }) } }) "#, ); run_cmd(&h, "ask", None); let dialog = |at: usize| match &h.dialogs.borrow()[at] { (_, abi::Dialog::Dismissable { dialog, .. }) => answers(dialog), other => panic!("{other:?}"), }; let (first, ninth) = (dialog(0), dialog(8)); let abi::Dialog::Dismissable { dismissed: abi::Action::Command { name, input }, .. } = h.dialogs.borrow()[0].1.clone() else { panic!("expected dismissable") }; assert_ne!(first, ninth, "the ninth prompt took the first one's answer command"); run_cmd(&h, &first, Some("first")); run_cmd(&h, &name, input.as_deref()); assert_eq!(said(&h), ["1 first"]); run_cmd(&h, &ninth, Some("ninth")); assert_eq!((said(&h), failure(®, "test.script")), (vec!["1 first".into(), "9 ninth".into()], None)); } #[test] fn plugin_sleep_waits_on_the_hosts_clock_and_every_ticks_until_false() { let h = host(); let reg = plugin_with( &h, r#" const say = (host, msg) => host.toast({ variant: "info", message: msg }) setup.command({ name: "nap" }, async (host) => { spawn(async () => { await sleep(Infinity) say(host, "huge") }) await sleep(100) say(host, "slept") await sleep(1) say(host, "short") await sleep(20.9) say(host, "fraction") }) let ticks = 0 every(1000, (host) => { ticks += 1 say(host, "tick " + ticks) return ticks < 2 }) "#, ); run_cmd(&h, "nap", None); h.app.advance(Duration::from_millis(98)); assert!(said(&h).is_empty(), "{:?}", said(&h)); h.app.advance(Duration::from_millis(1)); assert_eq!(said(&h), ["slept"]); // 20 ms floor on sleep(1). h.app.advance(Duration::from_millis(19)); assert_eq!(said(&h), ["slept"]); h.app.advance(Duration::from_millis(1)); assert_eq!(said(&h), ["slept", "short"]); // Fractional sub-ms preserved on sleep(20.9). h.app.advance(Duration::from_millis(20)); assert_eq!(said(&h), ["slept", "short"]); h.app.advance(Duration::from_millis(1)); assert_eq!(said(&h), ["slept", "short", "fraction"]); // every stops on false, and sleep(Infinity) never fires. h.app.advance(Duration::from_secs(3600)); assert_eq!(said(&h)[3..], ["tick 1", "tick 2"]); assert_eq!(failure(®, "test.script"), None); } #[test] fn a_plugin_waits_on_at_most_32_timers_which_end_with_it() { let h = host(); let init = r#" import { define, sleep, spawn } from "opencode:plugin" export default define((setup) => { setup.command({ name: "many" }, (host) => { let slept = 0 for (let i = 0; i < 33; i++) { spawn(async () => { try { await sleep(1000) slept += 1 if (slept === 32) host.toast({ variant: "info", message: "slept 32" }) } catch (err) { host.toast({ variant: "info", message: err.message }) } }) } }) }) "#; let (reg, reload) = reloadable(&h, init); run_cmd(&h, "many", None); assert_eq!(said(&h), ["more than 32 timers of the plugin wait"]); h.app.advance(Duration::from_millis(1000)); assert_eq!(said(&h)[1..], ["slept 32"]); run_cmd(&h, "many", None); assert_eq!(said(&h)[2..], ["more than 32 timers of the plugin wait"], "fired timers kept their places"); reload(); run_cmd(&h, "many", None); assert_eq!(said(&h)[3..], ["more than 32 timers of the plugin wait"]); h.app.advance(Duration::from_millis(1000)); assert_eq!(said(&h)[4..], ["slept 32"], "old activation's sleeps returned"); run_cmd(&h, "many", None); assert!(reg.set_active(&dynamic(&h), "test.script", false)); h.app.advance(Duration::from_millis(1000)); assert_eq!(said(&h).len(), 6, "disabled plugin's sleeps returned: {:?}", said(&h)); } #[test] fn an_uncaught_host_error_ends_the_task_without_failing_the_plugin() { let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "uncaught" }, async (host) => { await host.fetch({ method: "GET", path: "/fail" }) host.toast({ variant: "info", message: "after" }) }) setup.command({ name: "still_alive" }, (host) => host.toast({ variant: "info", message: "alive" })) "#, ); run_cmd(&h, "uncaught", None); answer_fetch(&h, Err("UnexpectedStatus: 500".to_owned())); assert_eq!((failure(®, "test.script"), said(&h)), (None, Vec::::new())); run_cmd(&h, "still_alive", None); assert_eq!(said(&h), ["alive"]); } // --- Containment, budgets, compilation worker, sandbox, modules, and host surface --- #[test] fn no_vm_is_made_without_a_script_plugin() { let temp = opencode_util::temp::tempdir().unwrap(); let config = temp.path().join("config"); fs::create_dir_all(config.join("plugins").join("not-script")).unwrap(); fs::write(config.join("plugins").join("not-script").join("package.json"), "{}").unwrap(); let (h, reg) = (host(), Registry::define(Vec::new(), [])); let loader = loader(&config, temp.path()); let before = vm::made(); settle_script(&loader, &h, ®); assert_eq!(vm::made(), before, "a VM without a script plugin"); install_script("hello", &config.join("plugins").join("hello")); settle_script(&loader, &h, ®); assert_eq!(vm::made(), before + 1); } #[test] fn a_manifest_reads_its_flat_keys() { let srcs = Sources::from_files([ ("plugin.toml", "# a comment\nid = \"example.hello\"\nname = \"Hello\"\ncontract = \"2.0\"\n"), ("init.ts", "export default () => {}"), ]); let manifest = parse_manifest(&srcs).unwrap(); assert_eq!((manifest.id.as_str(), manifest.entry.as_str()), ("example.hello", "init.ts")); let js_only = Sources::from_files([("plugin.toml", "id = \"example.js\"\n"), ("init.js", "export default () => {}")]); assert_eq!(parse_manifest(&js_only).unwrap().entry, "init.js"); let err = |toml: &str| parse_manifest(&Sources::from_files([("plugin.toml", toml)])).unwrap_err(); for (toml, expected) in [ ("id = \"x\"\ncontract = \"1.0\"", "contract 1.0"), ("id = [\"x\"]", "only `key = \"string\"`"), ("entry = \"../x.ts\"\nid = \"x\"", "not a .ts or .js file"), ("entry = \"types.d.ts\"\nid = \"x\"", "declaration file"), ] { let got = err(toml); assert!(got.contains(expected), "{toml}: {got}"); } } #[test] fn a_spinning_plugin_is_failed_on_cpu_time_and_the_thread_is_back_at_once() { let init = r#" import { define } from "opencode:plugin" export default define((setup) => { setup.command({ name: "spin" }, (host) => { host.toast({ variant: "info", message: "before the spin" }) while (true) {} }) setup.command({ name: "caught" }, () => { while (true) { try { while (true) {} } catch {} } }) setup.slot({ path: "home.footer" }, () => { let n = 0; while (true) n += 1 }) }) "#; for command in ["spin", "caught"] { let h = host(); let reg = running(&h, define(&script_sources(init), None).unwrap().0); run_cmd(&h, command, None); let error = failure(®, "test.script").expect("the spinning plugin failed"); assert!(error.contains("CPU") && error.contains("script budget"), "{command}: {error}"); assert!(h.toasts.borrow().iter().all(|toast| toast.message != "before the spin")); } let h = host(); let reg = running(&h, define(&script_sources(init), None).unwrap().0); let text = footer_text(&h, ®); assert!(failure(®, "test.script").is_some_and(|e| e.contains("script budget"))); assert!(!text.contains('n'), "{text}"); } // U7 bound test: exponential, quadratic, and caught backtracking RegExps stop within the 100 ms CPU budget. #[test] fn a_runaway_pattern_is_stopped_at_the_budget() { for (name, expr) in [ ("alternation", r#"/(a|a)*b/.test("a".repeat(28))"#), ("quadratic", r#"/.*.*b/.test("a".repeat(100_000))"#), ("caught", r#"try { /(a+)+$/.test("a".repeat(40) + "!") } catch {}"#), ] { let h = host(); let init = format!( "import {{ define }} from \"opencode:plugin\"\nexport default define((setup) => {{\n setup.command({{ name: \"match\" }}, (host) => {{\n {expr}\n host.toast({{ variant: \"info\", message: \"matched\" }})\n }})\n}})\n" ); let reg = running(&h, define(&script_sources(&init), None).unwrap().0); let (used, _) = cpu(|| h.keymap().dispatch("match", None)); h.app.advance(Duration::from_millis(1)); let failed = failure(®, "test.script").unwrap_or_else(|| panic!("{name} was not stopped")); assert!(failed.contains("script budget"), "{name}: {failed} after {used:?}"); assert!(used <= Duration::from_millis(300), "{name} ran {used:?} of CPU on a 100 ms budget"); assert!(said(&h).is_empty(), "{name}"); } } // Callback-driven built-ins and O(N) native built-ins (U13 `native-fuel`) stop within the 100 ms CPU budget. #[test] fn a_loop_of_expensive_built_ins_is_stopped_within_the_budget() { for (name, body) in [ ( "sort", "const t = new Array(50000); for (let i = 0; i < t.length; i++) t[i] = (i * 7919) % 1000003; while (true) { t.sort((a, b) => a - b); const x = t[0]; t[0] = t[t.length - 1]; t[t.length - 1] = x }", ), ( "replace-regex", "const s = 'ab'.repeat(2 * 1024); let n = 0; while (true) { n += s.replace(/a/g, 'c').length }", ), ("repeat-512k", "let n = 0; while (true) { n += 'a'.repeat(512 * 1024).length }"), ] { let h = host(); let init = format!( "import {{ define }} from \"opencode:plugin\"\nexport default define((setup) => {{\n setup.command({{ name: \"spin\" }}, () => {{ {body} }})\n}})\n" ); let reg = running(&h, define(&script_sources(&init), None).unwrap().0); let (used, _) = cpu(|| h.keymap().dispatch("spin", None)); h.app.advance(Duration::from_millis(1)); let error = failure(®, "test.script").unwrap_or_else(|| panic!("{name} was not stopped")); assert!(error.contains("script budget"), "{name}: {error}"); assert!(used <= Duration::from_millis(300), "{name} ran {used:?} of CPU on a 100 ms budget"); } } #[test] fn a_plugin_that_allocates_past_its_cap_fails() { for (label, handler) in [ ("uncaught", "() => { fill(); keep = [] }"), ("sync catch", "() => { try { fill() } catch {}; keep = [] }"), ("async catch", "async () => { try { await Promise.resolve().then(fill) } catch {}; keep = [] }"), ] { let h = host(); let init = format!( "import {{ define }} from \"opencode:plugin\"\nlet keep: string[] = []\nfunction fill() {{\n for (let i = 0; ; i++) keep.push(\"x\".repeat(1024) + i)\n}}\nexport default define((setup) => {{\n setup.command({{ name: \"hog\" }}, {handler})\n}})\n" ); let reg = running(&h, define_with(&script_sources(&init), None, 4 << 20).unwrap().0); run_cmd(&h, "hog", None); let error = failure(®, "test.script").unwrap_or_else(|| panic!("{label}: OOM did not fail")); assert!(error.contains("out of memory: an allocation went past its 4 MiB script heap cap"), "{label}: {error}"); } } #[test] fn a_big_plugin_compiles_off_the_ui_thread() { let temp = opencode_util::temp::tempdir().unwrap(); let config = temp.path().join("config"); let dir = config.join("plugins").join("big"); big_plugin(&dir, (SOURCES as usize - 1024) / 2); let (h, reg) = (host(), Registry::define(Vec::new(), [])); let loader = loader(&config, temp.path()); loader.reconcile(&dynamic(&h), ®); while loader.script_walking() { std::thread::yield_now(); } loader.reconcile(&dynamic(&h), ®); assert_eq!(entry(®.entries(), &dir.to_string_lossy()).status, Status::Skipped(STARTING.to_owned())); assert!(loader.script_walking(), "the compilation runs after the reconcile returned"); settle_script(&loader, &h, ®); let big = entry(®.entries(), &dir.to_string_lossy()).clone(); assert_eq!((big.id.as_str(), big.status), ("test.big", Status::Active)); } #[test] fn a_plugin_past_the_source_limit_is_refused() { let temp = opencode_util::temp::tempdir().unwrap(); let config = temp.path().join("config"); let dir = config.join("plugins").join("big"); big_plugin(&dir, SOURCES as usize / 2 + 1); let (h, reg) = (host(), Registry::define(Vec::new(), [])); settle_script(&loader(&config, temp.path()), &h, ®); let entries = reg.entries(); let Status::Failed(error) = &entry(&entries, &dir.to_string_lossy()).status else { panic!("{entries:?}") }; assert!(error.contains("sources larger than 1 MiB"), "{error}"); } #[test] fn one_thread_compiles_a_plugin_and_the_newest_save_wins() { let temp = opencode_util::temp::tempdir().unwrap(); let dir = temp.path().join("big"); big_plugin(&dir, 200_000); let builds = Builds::new(std::sync::Arc::new(|| {})); let mut most = 0; for key in 1..=8 { assert!(builds.built("big", &dir, key, false).is_none()); most = most.max(builds.threads()); } while builds.running() { most = most.max(builds.threads()); std::thread::yield_now(); } assert_eq!(most, 1, "threads compiled at once"); assert!(builds.built("big", &dir, 8, false).is_some_and(|built| built.is_ok())); } #[test] fn a_build_holds_the_files_its_key_names() { let temp = opencode_util::temp::tempdir().unwrap(); let dir = temp.path().join("plugin"); install_script("hello", &dir); let good = fs::read(dir.join("init.ts")).unwrap(); let key = crate::pipe::tree::light(&dir).unwrap(); fs::write(dir.join("init.ts"), "export default define((setup) => { const = 1 })").unwrap(); let mut retries = 0; let sources = crate::source::read_wanted_with( &dir, key, true, || true, || { retries += 1; fs::write(dir.join("init.ts"), &good).unwrap(); }, ) .expect("sources") .expect("matched after retry"); assert_eq!(retries, 1); assert!(Built::new(&sources).is_ok()); } #[test] fn a_build_for_a_plugin_that_went_is_dropped() { let temp = opencode_util::temp::tempdir().unwrap(); let config = temp.path().join("config"); let dir = config.join("plugins").join("big"); big_plugin(&dir, (SOURCES as usize - 1024) / 2); let (h, reg) = (host(), Registry::define(Vec::new(), [])); let loader = loader(&config, temp.path()); loader.reconcile(&dynamic(&h), ®); while loader.script_walking() { std::thread::yield_now(); } loader.reconcile(&dynamic(&h), ®); assert!(loader.script_walking(), "the compilation runs"); fs::remove_dir_all(&dir).unwrap(); settle_script(&loader, &h, ®); assert!(!loader.script_ready()); assert!(reg.entries().iter().all(|entry| entry.target.as_deref() != Some(&*dir.to_string_lossy()))); } #[test] fn a_plugin_runs_under_small_and_tight_caps() { let init = r#" import { define } from "opencode:plugin" let keep: unknown[] = [] export default define((setup) => { setup.handler(() => { for (let i = 0; i < 64; i++) keep.push("x".repeat(512) + keep.length) }) setup.handler(() => "idle") }) "#; for (cap, free) in [(1 << 20, 200 << 10), (4 << 20, 400 << 10)] { let mut act = echo_start(&[("init.ts", init)], Duration::from_secs(10), cap).unwrap(); while (act.heap_bytes().unwrap_or(0) as usize) + free < cap { act.call(0, vec![]).unwrap(); } act.call(1, vec![]).unwrap(); } } #[test] fn the_sandbox_holds_a_plugin_to_its_own_files() { let h = host(); let init = r#" import { define, KEEP } from "opencode:plugin" import { value as mine } from "./mine.ts" function refused(f: () => unknown): string { try { f(); return "allowed" } catch (err) { return String(err) } } export default define((setup) => { setup.command({ name: "probe" }, (host) => { const seen: Record = { eval: typeof eval, fetch: typeof fetch, setTimeout: typeof setTimeout, setInterval: typeof setInterval, process: typeof process, Intl: typeof Intl, Proxy: typeof Proxy, Reflect: typeof Reflect, hostGlobal: typeof __opencode_host, setProto: typeof (Object as Record).setPrototypeOf, funcCtor: refused(() => Function("return 1")), reqUp: refused(() => require("../escape.ts")), reqAbs: refused(() => require("/etc/passwd")), reqFs: refused(() => require("fs")), reqHost: refused(() => require("opencode:host")), frozenHost: refused(() => { (host as Record).toast = null }), frozenKeep: refused(() => { (KEEP as Record).type = "x" }), mine, } host.toast({ variant: "info", message: Object.keys(seen).sort().map((k) => k + "=" + seen[k]).join("\n") }) }) }) "#; let mut srcs = script_sources(init); srcs.files.insert("mine.ts".into(), b"export const value = 'own'".to_vec()); let reg = running(&h, define(&srcs, None).unwrap().0); run_cmd(&h, "probe", None); assert_eq!(failure(®, "test.script"), None); let message = h.toasts.borrow().last().unwrap().message.clone(); let seen: std::collections::BTreeMap<&str, &str> = message.lines().filter_map(|line| line.split_once('=')).collect(); for missing in ["eval", "fetch", "setTimeout", "setInterval", "process", "Intl", "Proxy", "Reflect", "hostGlobal", "setProto"] { assert_eq!(seen[missing], "undefined", "{missing}: {message}"); } for blocked in ["funcCtor", "reqUp", "reqAbs", "reqFs", "reqHost", "frozenHost", "frozenKeep"] { assert_ne!(seen[blocked], "allowed", "{blocked} was allowed: {message}"); } assert_eq!(seen["mine"], "own"); for bad in ["../escape.ts", "./../escape.ts", "/etc/passwd", "fs", "opencode:host"] { let escape = format!("import x from {bad:?}\nexport default () => x\n"); assert!(define(&script_sources(&escape), None).is_err(), "{bad} compiled"); } } #[test] fn imports_resolve_cache_erase_types_and_refuse_cycles() { let temp = opencode_util::temp::tempdir().unwrap(); let dir = temp.path().join("plugin"); let init = r#" import { contract, define } from "opencode:plugin" import type { Boxed } from "./x.ts" import { box as one } from "./x.ts" import { box as two } from "./lib/again.ts" import { one as libOne } from "./lib/one.ts" import { sibling } from "./lib/sibling.ts" export default define((setup) => { setup.command({ name: "probe" }, (host) => { const typed: Boxed = one satisfies Boxed host.toast({ variant: "info", message: [(one === two) + ":" + typed.loads, libOne, sibling, contract as string].join("|"), }) }) }) "#; for (path, text) in [ ("plugin.toml", "id = \"test.script\"\ncontract = \"2.0\""), ("init.ts", init), ( "x.ts", "export interface Boxed { loads: number }\nlet loads = 0; loads += 1; export const box: Boxed = { loads }", ), ("two.ts", "export const two = 'root'"), ("lib/again.ts", "export { box } from '../x.ts'"), ("lib/one.ts", "import { two } from './two.ts'\nexport const one = 'lib/one:' + two"), ("lib/two.ts", "export const two = 'lib/two'"), ("lib/sibling.ts", "import { box } from '../x.ts'\nexport const sibling = 'sib:' + box.loads"), ] { fs::create_dir_all(dir.join(path).parent().unwrap()).unwrap(); fs::write(dir.join(path), text).unwrap(); } let definition = define(&read(&dir).unwrap(), None).unwrap().0; // Delete the directory on disk before activating: nothing is read after load. fs::remove_dir_all(&dir).unwrap(); let h = host(); let reg = running(&h, definition); run_cmd(&h, "probe", None); assert_eq!((failure(®, "test.script"), said(&h)), (None, vec!["true:1|lib/one:lib/two|sib:1|2.0".into()])); // A cycle fails at build time naming the modules in the cycle. let mut cyclic = script_sources("import { a } from './a.ts'\nexport default () => a\n"); cyclic.files.insert("a.ts".into(), b"import { b } from './b.ts'\nexport const a = b".to_vec()); cyclic.files.insert("b.ts".into(), b"import { a } from './a.ts'\nexport const b = a".to_vec()); let err = define(&cyclic, None).err().expect("cycle refused"); assert!( (err.contains("Circular") || err.contains("cycle")) && err.contains("a.ts") && err.contains("b.ts"), "{err}" ); // 40 KB of nesting overflowed the compiler's stack and aborted the client: it fails at build time, naming the file. let deep = format!("export const a = {}{}", "[".repeat(20_000), "]".repeat(20_000)); let mut nested = script_sources("import { a } from './a.ts'\nexport default () => a\n"); nested.files.insert("a.ts".into(), deep.clone().into_bytes()); for sources in [script_sources(&deep), nested] { let err = define(&sources, None).err().expect("nesting refused"); assert!(err.contains("nested too deeply") && err.contains(".ts"), "{err}"); } } #[test] fn a_script_plugin_reads_host_facts_and_dialog_options() { let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "script.facts", slash: "script-facts", aliases: ["sf"] }, (host) => { const a = host.abi() const m = host.measure("ab日") host.toast({ variant: "info", message: [ a.major + "." + a.minor, a.features.join(","), host.hasFeature(FOCUS_INPUT), host.hasFeature(FENCE_NODE), host.hasFeature("fence-nodes"), host.info().locale, host.utcOffset(0), m.cells, m.graphemes, ].join(" "), }) const action = command("script.facts") host.dialog({ type: "select", title: "pick", options: [{ title: "one", value: "1" }], action, centered: true }) host.dialog({ type: "alert", title: "told", message: "said", size: "xlarge", centered: true }) host.dialog({ type: "confirm", title: "asked", message: "sure?", action, size: "large", centered: true }) host.dialog({ type: "prompt", title: "name", value: "script", description: "described", action }) }) "#, ); run_cmd(&h, "script.facts", None); let features = abi::FEATURES.join(","); assert_eq!(said(&h), [format!("2.0 {features} true true false nb-NO 3600 4 3")]); let dialogs: Vec = h.dialogs.borrow().iter().map(|(_, d)| d.clone()).collect(); let [ abi::Dialog::Select(select), abi::Dialog::Alert(alert), abi::Dialog::Confirm(confirm), abi::Dialog::Prompt(prompt), ] = dialogs.as_slice() else { panic!("{dialogs:?}") }; assert!(select.centered && alert.centered && confirm.centered, "{dialogs:?}"); assert_eq!((alert.size, confirm.size), (Some(abi::PanelSize::XLarge), Some(abi::PanelSize::Large))); assert_eq!((prompt.value.as_deref(), prompt.description.as_deref()), (Some("script"), Some("described"))); assert_eq!(failure(®, "test.script"), None); } #[test] fn a_script_command_starts_disabled_and_one_declines() { use opentui::keymap::RunResult; let h = host(); let reg = plugin_with( &h, r#" setup.command({ name: "script.gated", enabled: false }, (host) => host.toast({ variant: "info", message: "gated" })) setup.command({ name: "script.gate" }, (host, input) => host.setEnabled("script.gated", input === "on")) setup.command({ name: "script.pass" }, () => "pass") setup.command({ name: "script.other" }, () => "consume") "#, ); let dispatch = |name: &str, input: Option<&str>| { let result = h.keymap().dispatch(name, input); h.app.advance(Duration::from_millis(1)); result }; assert_eq!(dispatch("script.gated", None), RunResult::Disabled); assert_eq!(dispatch("script.gate", Some("on")), RunResult::Ok); assert_eq!(dispatch("script.gated", None), RunResult::Ok); assert_eq!((dispatch("script.pass", None), dispatch("script.other", None)), (RunResult::Rejected, RunResult::Ok)); assert_eq!(dispatch("script.gate", Some("off")), RunResult::Ok); assert_eq!(dispatch("script.gated", None), RunResult::Disabled); assert_eq!((said(&h), failure(®, "test.script")), (vec!["gated".into()], None)); } #[test] fn the_guides_script_wait_runs_as_written() { let guide = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/plugins.md")).unwrap(); let body = guide .split("```ts\n") .find(|block| block.starts_with("setup.command({ name: \"x.clear\"")) .and_then(|block| block.split("```").next()) .expect("the guide's script wait"); let h = host(); let reg = plugin_with(&h, body); let ask = |confirmed: &str| { run_cmd(&h, "x.clear", None); let (dialog, closed) = asked(&h); assert!(matches!(dialog, abi::Dialog::Confirm(ref confirm) if confirm.title == "Clear?"), "{dialog:?}"); run_cmd(&h, &answers(&dialog), Some(confirmed)); run_cmd(&h, &closed.0, closed.1.as_deref()); }; ask("false"); assert!(h.fetches.borrow().is_empty(), "an unconfirmed dialog sent the request"); ask("true"); answer_fetch(&h, Err("UnexpectedStatus: 404".to_owned())); let (dialog, closed) = asked(&h); assert!(matches!(dialog, abi::Dialog::Alert(ref a) if a.message == "UnexpectedStatus: 404"), "{dialog:?}"); run_cmd(&h, &closed.0, closed.1.as_deref()); let toasts = || h.toasts.borrow().iter().map(|t| t.message.clone()).collect::>(); assert!(toasts().is_empty(), "{:?}", toasts()); ask("true"); answer_fetch(&h, Ok(serde_json::Value::Null)); assert_eq!((toasts(), failure(®, "test.script")), (vec!["Cleared".into()], None)); } #[test] fn every_operation_is_one_request_in_script_rust_and_the_generated_client() { let samples: serde_json::Map = serde_json::from_str(include_str!("../client-samples.json")).unwrap(); let names: std::collections::BTreeSet<&str> = client::names().collect(); assert_eq!(names, samples.keys().map(String::as_str).collect(), "table and samples name other operations"); let sorted = |mut pairs: Vec<(String, String)>| { pairs.sort_by(|a, b| a.0.cmp(&b.0)); pairs }; let mut refused = Vec::new(); for (name, input) in &samples { let rust = opencode_api_types::client::probe(name, input).unwrap_or_else(|| panic!("the client has no {name}")); let script = client::request(name, input).map(|(fetch, _)| fetch); let Ok(rust) = rust else { assert!(script.is_err(), "{name}: Rust has no request for it, Script sends {script:?}"); refused.push(name.as_str()); continue; }; assert!(rust.error.is_none(), "{name}: {:?}", rust.error); let sdk = abi::call::fetch_of(&rust); match (sdk, script) { (Ok(sdk), Ok(script)) => { let generated = (rust.method.to_owned(), rust.path.clone(), sorted(rust.query.clone())); let generated_body = match &rust.body { Some(opencode_api_types::call::Body::Json(value)) => Some(value.clone()), _ => None, }; for (column, fetch) in [("Rust", &sdk), ("Script", &script)] { let request = (fetch.method.clone(), fetch.path.clone(), sorted(fetch.query.clone())); assert_eq!(request, generated, "{name}: {column}'s request is not the generated client's"); assert_eq!(fetch.body, generated_body, "{name}: {column}'s body is not the generated client's"); } assert_eq!(sdk.bytes, script.bytes, "{name}"); } (Err(_), Err(_)) => refused.push(name.as_str()), (sdk, script) => panic!("{name}: Rust {sdk:?}, Script {script:?}"), } } assert_eq!((samples.len(), refused.len()), (195, 7), "refused: {refused:?}"); let expected_ns: std::collections::BTreeSet = client::names().filter_map(|n| n.split('.').next().map(str::to_owned)).collect(); let h = host(); let reg = plugin_with( &h, r#"setup.command({ name: "ns" }, (host) => host.toast({ variant: "info", message: Object.keys(client).sort().join(",") }))"#, ); run_cmd(&h, "ns", None); let expected: String = expected_ns.into_iter().collect::>().join(","); assert_eq!((failure(®, "test.script"), said(&h)), (None, vec![expected])); } #[test] fn a_malformed_slot_path_fails_a_script_plugins_activation() { let h = host(); let reg = plugin_with( &h, r#"setup.slot({ path: "home.footer" }, () => show(text("bad"))) setup.slot({ path: "home..footer" }, () => show(text("nope")))"#, ); let err = failure(®, "test.script").expect("malformed slot path must fail activation"); assert!(err.contains("home..footer"), "{err}"); assert!(!footer_text(&h, ®).contains("bad")); }