diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index c80702776b..2f3d97ceeb 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -176,8 +176,10 @@ pub struct FilterJob { /// The run of a filter that calls commands that holds the documents ([`FilterRun::begin_calls`]): /// the run, what its calls keep fixed, and its open undo step. pub(crate) struct Calling { - /// The command that applies its output: `plugin.run`, or the plug-in command it runs. + /// The command that applies its output: `plugin.run`, or the plug-in command it runs, and the + /// params it was started with, which that command must be given. cmd: String, + params: Value, run: FilterRun, calls: super::plugin_call::Calls, tx: super::plugin_call::Transaction, @@ -350,7 +352,7 @@ impl FilterRun { let may = r.plugin.manifest().permissions(); let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); let job = r.job(); - s.plugin_calling = Some(Calling { cmd: c.to_string(), run: r, calls, tx }); + s.plugin_calling = Some(Calling { cmd: c.to_string(), params: p.clone(), run: r, calls, tx }); Ok(job) } @@ -473,13 +475,14 @@ fn run(s: &mut Session, p: &Value) -> Result { } /// Ends the run that holds the documents ([`FilterRun::begin_calls`]) when command `c` (with params -/// `p`) is the one that applies its output and `handed` is that output: applied in the run's own -/// undo step → the command's result. Any other command is refused while a run holds them. `None`: -/// no run holds them. +/// `p`, the params the run was started with) is the one that applies its output and `handed` is +/// that output: applied in the run's own undo step, to the objects the run was given → the +/// command's result. Any other command, or other params, is refused while a run holds them. +/// `None`: no run holds them. fn end_held(s: &mut Session, c: &str, p: &Value, handed: &mut Option) -> Option> { let held = s.plugin_calling.take()?; let serial = held.run.plugin.serial(); - let same = held.cmd == c && (c != "plugin.run" || plugin_by_id(c, p).is_ok_and(|plugin| plugin.serial() == serial)); + let same = held.cmd == c && *p == held.params && (c != "plugin.run" || plugin_by_id(c, p).is_ok_and(|plugin| plugin.serial() == serial)); let mine = handed.take().filter(|h| same && (h.serial, &h.input, &h.params) == (serial, &held.run.input, &held.run.params)); let Some(h) = mine else { s.plugin_calling = Some(held); diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 90cd158bf0..dd16443b27 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -528,9 +528,15 @@ impl Transaction { Err(e) => { let open = std::mem::replace(&mut s.docs, start); for st in &mut s.docs { - // Past the newest revision the document reached, so the restored one redraws. - let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision); - st.revision = newest.max(st.revision).saturating_add(1); + // Past the newest revision the document reached, so the restored one redraws. A + // document the transaction left as it was keeps its revision, so a run made + // away from the session on it still applies. + let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect(); + let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection); + if !unchanged { + let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision); + st.revision = newest.max(st.revision).saturating_add(1); + } crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection); } s.active = active; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 47150cd532..28b4dd8714 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -65,8 +65,10 @@ impl Session { return Err(EngineError::Busy); } // While a plug-in run that calls commands holds the documents, only queries run, and the - // command that applies its output. - if self.depth == 0 && self.plugin_calls_open() && !self.plugin_calls_end_with(id) && spec.journal && !JOURNALED_READS.contains(&id) { + // command that applies its output. A clipboard import is refused too: the run's end would put + // back the clipboard it started with. + let changes = (spec.journal && !JOURNALED_READS.contains(&id)) || id.starts_with("clipboard.import"); + if self.depth == 0 && self.plugin_calls_open() && !self.plugin_calls_end_with(id) && changes { return Err(EngineError::PluginBusy); } // A step of a batch a script runs is held to the same rule as the script's own commands. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index bd6490d0a1..6458b43cba 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -5461,3 +5461,67 @@ fn a_checked_module_installs_without_running_its_code() { assert!(s.execute("plugin.inspect", &json!({"dataBase64": vectorcraft_format::base64_encode(&other)})).is_err()); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// A run that holds the documents and ends before it changed anything leaves the document's +/// revision as it was, so another run made away from the session on that document still applies; +/// one whose calls changed the selection moves it on, so the restored document redraws. +#[test] +fn a_calling_run_that_ends_unchanged_keeps_the_revision() { + use cmd::plugin::FilterRun; + let (plain, caller) = ("test.engine.keeprev.plain", "test.engine.keeprev.caller"); + let mut s = session(); + install_wat(&mut s, &tpl::returning(&tpl::manifest(plain, "filter", "{}"), r#"{"objects":[]}"#)); + install_select_all_then_remove(&mut s, caller); + let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00")); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let first = FilterRun::prepare(&s, &json!({"id": plain})).unwrap(); + // It fails before its first call. + FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": caller})).unwrap(); + s.end_plugin_calls(); + assert!(first.current(&s), "nothing changed: the other run still applies"); + let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": caller})).unwrap(); + run_job_away(&mut s, &job); + s.end_plugin_calls(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a]); + assert!(!first.current(&s), "its call changed the selection, which was put back"); + run(&mut s, "plugin.remove", json!({"id": plain})); + run(&mut s, "plugin.remove", json!({"id": caller})); +} + +/// The output of a run that holds the documents applies only through the command and the params +/// it was started with: `plugin.run` for other objects is refused and leaves the run holding them. +#[test] +fn a_held_run_applies_only_with_the_params_it_was_started_with() { + use cmd::plugin::FilterRun; + let id = "test.engine.heldparams"; + let mut s = session(); + install_select_all_then_remove(&mut s, id); + let (a, b) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00")); + let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id, "ids": [a.0]})).unwrap(); + let output = run_job_away(&mut s, &job); + s.hand_in_plugin_calls(output.clone()); + assert!(matches!(s.execute("plugin.run", &json!({"id": id, "ids": [b.0]})), Err(EngineError::PluginBusy))); + assert!(s.plugin_calls_open()); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some(), "nothing applied"); + s.hand_in_plugin_calls(output); + run(&mut s, "plugin.run", json!({"id": id, "ids": [a.0]})); + assert!(!s.plugin_calls_open()); + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_some()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A clipboard import is refused while a run holds the documents: the run's end would put back the +/// clipboard it started with. +#[test] +fn a_clipboard_import_is_refused_while_a_run_holds_the_documents() { + use cmd::plugin::FilterRun; + let id = "test.engine.heldclipboard"; + let mut s = session(); + install_select_all_then_remove(&mut s, id); + rect(&mut s, 10.0, "#ff0000"); + FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap(); + assert!(matches!(s.execute("clipboard.importText", &json!({"text": "Hello"})), Err(EngineError::PluginBusy))); + s.end_plugin_calls(); + run(&mut s, "clipboard.importText", json!({"text": "Hello"})); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/plugins/src/worker.rs b/crates/plugins/src/worker.rs index cee7eb6991..a2a09f1d84 100644 --- a/crates/plugins/src/worker.rs +++ b/crates/plugins/src/worker.rs @@ -26,7 +26,7 @@ use crate::{Error, Limits, Plugin, Result}; /// The version of these messages, which [`FromWorker::Ready`] gives: a page and a worker of other /// builds (a worker file a browser kept from before an update) don't run plug-ins together. -pub const PROTOCOL: u64 = 1; +pub const PROTOCOL: u64 = 2; /// What the page asks the worker to do. #[derive(Clone, Debug, PartialEq)] @@ -188,7 +188,8 @@ impl ToWorker { ToWorker::Run { module, manifest, input, params, limits, calls } => { pack(json!({"kind": "run", "limits": limits_json(limits), "calls": calls}), &[module, manifest, input, params]) } - ToWorker::Answer(Ok(result)) => pack(json!({"kind": "answer", "result": result}), &[]), + // The result goes in a blob of its own, so it may nest as deep as a command's result. + ToWorker::Answer(Ok(result)) => pack(json!({"kind": "answer"}), &[result.to_string().as_bytes()]), ToWorker::Answer(Err(f)) => pack(json!({"kind": "answer", "failure": {"code": f.code, "why": f.why}}), &[]), } } @@ -203,8 +204,8 @@ impl ToWorker { let limits = limits_from(h.get("limits")?)?; Some(ToWorker::Run { module, manifest, input, params, limits, calls: h.get("calls")?.as_bool()? }) } - ("answer", 0) => match (h.get("result"), h.get("failure")) { - (Some(result), None) => Some(ToWorker::Answer(Ok(result.clone()))), + ("answer", n) => match (blobs.pop(), h.get("failure")) { + (Some(result), None) if n == 1 => Some(ToWorker::Answer(Ok(serde_json::from_slice(&result).ok()?))), (None, Some(f)) => { let code = i32::try_from(f.get("code")?.as_i64()?).ok()?; Some(ToWorker::Answer(Err(CallFailure { code, why: f.get("why")?.as_str()?.to_string() }))) @@ -224,7 +225,8 @@ impl FromWorker { FromWorker::Checked(Ok(manifest)) => pack(json!({"kind": "checked"}), &[manifest]), FromWorker::Checked(Err(e)) => pack(json!({"kind": "checked", "error": error_json(e)}), &[]), FromWorker::Progress { done, total } => pack(json!({"kind": "progress", "done": done, "total": total}), &[]), - FromWorker::Call { command, args } => pack(json!({"kind": "call", "command": command, "args": args}), &[]), + // The arguments go in a blob of their own, so they may nest as deep as a call's arguments. + FromWorker::Call { command, args } => pack(json!({"kind": "call", "command": command}), &[args.to_string().as_bytes()]), FromWorker::Done(out, lines) => { let lines: Vec = lines.iter().map(|l| json!([level_name(l.level), l.text])).collect(); match out { @@ -244,7 +246,9 @@ impl FromWorker { ("checked", 1, None) => Some(FromWorker::Checked(Ok(blobs.pop()?))), ("checked", 0, Some(e)) => Some(FromWorker::Checked(Err(error_from(e)?))), ("progress", 0, None) => Some(FromWorker::Progress { done: h.get("done")?.as_u64()?, total: h.get("total")?.as_u64()? }), - ("call", 0, None) => Some(FromWorker::Call { command: h.get("command")?.as_str()?.to_string(), args: h.get("args")?.clone() }), + ("call", 1, None) => { + Some(FromWorker::Call { command: h.get("command")?.as_str()?.to_string(), args: serde_json::from_slice(&blobs.pop()?).ok()? }) + } ("done", n, e) => { let mut lines = Vec::new(); for l in h.get("lines")?.as_array()? { @@ -433,6 +437,20 @@ mod tests { } } + /// A call's arguments and a command's result read back at the deepest nesting a JSON parse + /// takes: the message adds no level around them. + #[test] + fn arguments_and_results_as_deep_as_json_takes_read_back() { + let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n)); + let deepest = (1..512).take_while(|&n| serde_json::from_str::(&nested(n)).is_ok()).last().unwrap(); + assert!(deepest < 511, "the parse has a depth limit"); + let value: Value = serde_json::from_str(&nested(deepest)).unwrap(); + let call = FromWorker::Call { command: "select.all".into(), args: value.clone() }; + assert_eq!(FromWorker::decode(&call.encode()), Some(call)); + let answer = ToWorker::Answer(Ok(value)); + assert_eq!(ToWorker::decode(&answer.encode()), Some(answer)); + } + #[test] fn a_cut_or_padded_message_is_not_read() { let m = ToWorker::Check { module: b"\0asm".to_vec() }.encode(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f0651c735b..bdeb69dcb8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -260,9 +260,11 @@ impl VectorcraftApp { /// called from the host's `eframe::App` impl. impl VectorcraftApp { /// Applies the work that finished off the UI thread. It stays pending while a script runs, since - /// every change to the documents ends in a busy error until the script ends. + /// every change to the documents ends in a busy error until the script ends. Plug-in worker runs + /// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]). pub(crate) fn poll_finished_work(&mut self) { if self.session.script_running() { + plugin_runs::poll(self); return; } background::poll(self); diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 14c2da5e23..1e09267049 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -18,7 +18,7 @@ //! //! The web build has no threads. There the app runs every filter it starts here in a Web Worker //! of its own ([`Workers`], [`vectorcraft_plugins::worker`]), and it checks a module being installed -//! in one too ([`check_install`]), so a plug-in never runs on the page. The page posts the module, +//! in one too ([`check_install`]), so neither runs plug-in code on the page. The page posts the module, //! the input, the parameters and the limits, and reads the replies each frame ([`poll`]) from a //! bounded inbox ([`Inbox`]). Cancel terminates the worker at once, and so does a run past its //! time budget ([`GRACE_MS`] after the worker should have ended it) and a run whose document or @@ -161,8 +161,9 @@ impl InWorker { } /// While a dialog is open, its answer waits in its inbox: this posts its request once it is - /// ready → why it must end now (it failed, or its deadline passed with no answer waiting), if it - /// must. + /// ready → why it must end now (it failed, or its deadline passed with no final answer waiting), + /// if it must. A command call waiting is not answered then, so it doesn't keep the run past its + /// deadline. fn watch(&mut self, now: f64) -> Option { while matches!(self.inbox.borrow().messages.front(), Some(FromWorker::Ready { .. })) { if let Err(e) = self.next(f64::NEG_INFINITY) { @@ -173,7 +174,8 @@ impl InWorker { if let Some(e) = inbox.error.take() { return Some(e); } - (now >= self.deadline && inbox.messages.is_empty()).then(|| vectorcraft_plugins::Error::Limit("time budget".into()).to_string()) + let answered = inbox.messages.iter().any(|m| matches!(m, FromWorker::Done(..) | FromWorker::Checked(_))); + (now >= self.deadline && !answered).then(|| vectorcraft_plugins::Error::Limit("time budget".into()).to_string()) } } @@ -334,6 +336,10 @@ pub fn start_command(app: &mut VectorcraftApp, id: &str, p: Value) -> Result Result { + // Its output could not apply before the script ends. + if app.session.script_running() { + return Err(EngineError::Busy.to_string()); + } if app.plugin_runs.in_workers() >= MAX_WORKERS || app.session.plugin_calls_open() { return Err(EngineError::PluginBusy.to_string()); } @@ -416,12 +422,14 @@ fn now(app: &VectorcraftApp) -> f64 { /// active document, which a run's result changes; the results wait until it is closed. Worker runs /// and install checks are read from their inboxes, and their command calls are made; a checked /// install waits for the dialog too, since it may ask in one. While a dialog is open, a worker -/// still gets its request, and Cancel and a passed deadline still end it. +/// still gets its request, and Cancel, a passed deadline and a change to its document still end +/// it. While a script runs, the runs wait as they do for a dialog: every change to the documents +/// is refused until it ends. pub fn poll(app: &mut VectorcraftApp) { poll_checks(app); let mut i = 0; while let Some(r) = app.plugin_runs.running.get(i) { - let dialog = app.ui.dialog.is_some(); + let dialog = app.ui.dialog.is_some() || app.session.script_running(); let ended = match &r.backend { Backend::Thread(_) if dialog => None, Backend::Worker(..) if dialog => watch_worker(app, i), @@ -455,15 +463,19 @@ enum Ended { Worker(Option, String>>), } -/// Worker run `i` while a dialog is open ([`InWorker::watch`]) → how it ended, if Cancel or its -/// deadline ended it. +/// Worker run `i` while a dialog is open ([`InWorker::watch`]) → how it ended, if Cancel, its +/// deadline or a change to its document or its plug-in ended it. fn watch_worker(app: &mut VectorcraftApp, i: usize) -> Option { let t = now(app); let r = app.plugin_runs.running.get_mut(i)?; if r.progress.cancelled() { return Some(Ended::Worker(Some(Err(EngineError::Cancelled.to_string())))); } - let Backend::Worker(worker, _) = &mut r.backend else { return None }; + let Backend::Worker(worker, run) = &mut r.backend else { return None }; + // As in [`poll_worker`]: its output can't apply. + if run.as_ref().is_some_and(|run| !run.current(&app.session)) { + return Some(Ended::Worker(None)); + } if worker.held.is_some() { return None; } @@ -572,13 +584,13 @@ fn finish_worker(app: &mut VectorcraftApp, r: Running, out: Option bool { /// a run that holds the documents, whose window has Cancel only). Not while a dialog or the export /// progress window is open: never two modals at once. pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(first) = app.plugin_runs.running.iter().find(|r| r.shown()) else { return }; + // The run that holds the documents comes first: only its Cancel goes through. + let runs = &app.plugin_runs.running; + let Some(first) = runs.iter().find(|r| r.shown() && r.holds()).or_else(|| runs.iter().find(|r| r.shown())) else { return }; let now = ctx.input(|i| i.time); let since = ctx.data_mut(|m| { let seen = m.get_temp_mut_or_insert_with(egui::Id::unique("plugin-run-seen"), || (first.id, now)); diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs index 9d787954ea..6bcf3d7a40 100644 --- a/crates/ui-egui/src/recovery.rs +++ b/crates/ui-egui/src/recovery.rs @@ -87,7 +87,9 @@ pub fn offer(app: &mut VectorcraftApp) -> bool { } /// Start a recovery copy of every document that needs one when the interval has passed since the -/// last (the first call only starts the clock) → how many were started. +/// last (the first call only starts the clock) → how many were started. While a plug-in run holds +/// the documents ([`vectorcraft_engine::cmd::plugin::FilterRun::begin_calls`]) the round waits for +/// it to end, since its edits are undone when it fails or is canceled. pub fn tick(app: &mut VectorcraftApp, now: f64) -> usize { let prefs = &app.session.prefs; let Some(store) = recovery::store(&app.session).filter(|_| prefs.autosave_recovery) else { @@ -97,6 +99,7 @@ pub fn tick(app: &mut VectorcraftApp, now: f64) -> usize { let interval = f64::from(prefs.autosave_interval.max(1)) * 60.0; match app.recovery.last { Some(t) if now >= t && now - t < interval => return 0, + Some(t) if now >= t && app.session.plugin_calls_open() => return 0, Some(t) if now >= t => app.recovery.last = Some(now), // First call, or a clock that went back: the interval starts now. _ => { @@ -108,8 +111,11 @@ pub fn tick(app: &mut VectorcraftApp, now: f64) -> usize { } /// Start a recovery copy of every document that needs one and `pick` picks (by uid) → how many -/// were started. +/// were started. None while a plug-in run holds the documents ([`tick`]). fn write(app: &mut VectorcraftApp, store: &Arc, pick: impl Fn(u64) -> bool) -> usize { + if app.session.plugin_calls_open() { + return 0; + } recovery::forget_clean(&mut app.session); // The folder `store` writes to, named in a failure even when the preference changes meanwhile. let place = recovery::folder(&app.session); diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 613041c7a8..c8a67e8b26 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -795,6 +795,149 @@ fn a_worker_inbox_is_bounded() { assert!(app.plugin_runs.running.is_empty() && fake.worker(2).terminated.get(), "a message it can't read"); } +/// Installs filter `id`, which calls `select.all` and then returns `output`, granted as the user +/// would grant it. +fn install_caller(app: &mut VectorcraftApp, id: &str, output: &str) { + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"]}}"#); + let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "select.all") + (data (i32.const 0x2100) "{}")"#; + let first = "(drop (call $vc_call (i32.const 0x2000) (i32.const 10) (i32.const 0x2100) (i32.const 2)))"; + let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, first, output)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap(); +} + +/// A dialog that some other part of the app opened. +fn open_dialog(app: &mut VectorcraftApp) { + app.ui.dialog = Some(crate::state::Dialog::new("test.other", json!({}))); +} + +/// While a dialog is open, a command call waiting in the inbox is not answered, so it doesn't keep +/// the run, and its hold on the documents, past the run's deadline. +#[test] +fn on_the_web_a_call_waiting_under_a_dialog_ends_at_the_time_budget() { + let (mut app, fake) = web_app(); + let id = "test.ui.web.callunderdialog"; + install_caller(&mut app, id, TRIANGLE); + let doc = app.session.doc().unwrap().doc.clone(); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert!(app.session.plugin_calls_open()); + open_dialog(&mut app); + fake.ready(0); + plugin_runs::poll(&mut app); + // The worker runs it to its command call, which waits for the dialog. + fake.serve(0); + fake.clock.set(vectorcraft_plugins::Limits::default().wall_time_ms as f64 + plugin_runs::GRACE_MS); + plugin_runs::poll(&mut app); + assert!(app.plugin_runs.running.is_empty() && fake.worker(0).terminated.get()); + assert!(!app.session.plugin_calls_open(), "the documents are free again"); + assert_eq!(app.session.doc().unwrap().doc, doc); +} + +/// A run whose document changes is stopped at once, also while a dialog is open. +#[test] +fn on_the_web_an_edit_ends_the_worker_while_a_dialog_is_open() { + let (mut app, fake) = web_app(); + let id = "test.ui.web.staleunderdialog"; + install_light(&mut app, id, false, "{}", ""); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + fake.ready(0); + plugin_runs::poll(&mut app); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + open_dialog(&mut app); + plugin_runs::poll(&mut app); + assert!(app.plugin_runs.running.is_empty() && fake.worker(0).terminated.get(), "stopped once the document changed"); + assert_eq!(app.ui.status, format!("“Test {id}” stopped: the document or the plug-in changed meanwhile: run it again")); +} + +/// A module checked while a run holds the documents installs once the run ends, without asking +/// for it again. +#[test] +fn on_the_web_a_checked_install_waits_for_the_run_that_holds_the_documents() { + let (mut app, fake) = web_app(); + let (id, caller) = ("test.ui.web.installwaits", "test.ui.web.installwaits.caller"); + install_caller(&mut app, caller, TRIANGLE); + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), TRIANGLE)).unwrap(); + let r = app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + assert_eq!(r, json!({"pending": true})); + app.run("plugin.dialog", json!({"id": caller})).unwrap(); + assert!(app.session.plugin_calls_open()); + fake.ready(0); + plugin_runs::poll(&mut app); + fake.serve(0); + plugin_runs::poll(&mut app); + assert!(registry::get(id).is_none(), "not while the run holds the documents"); + assert_eq!(app.run("plugin.cancelRuns", json!({})).unwrap()["cancelled"], 1); + plugin_runs::poll(&mut app); + assert!(registry::get(id).is_some(), "{}", app.ui.status); + registry::remove(id); +} + +/// The progress window shows the run that holds the documents at once, with Cancel only, also when +/// a run that started before it is running. +#[test] +fn on_the_web_the_progress_window_shows_the_run_that_holds_the_documents_first() { + let (mut app, _fake) = web_app(); + let (plain, caller) = ("test.ui.web.showplain", "test.ui.web.showholder"); + install_light(&mut app, plain, false, "{}", ""); + install_caller(&mut app, caller, TRIANGLE); + app.run("plugin.dialog", json!({"id": plain})).unwrap(); + app.run("plugin.dialog", json!({"id": caller})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + progress(&mut app, &ctx, 0.0); // a new window measures itself unseen first + let texts = progress(&mut app, &ctx, 0.1); + assert!(texts.contains(&format!("Running “Test {caller}”…")), "{texts}"); + assert!(texts.contains("Cancel") && !texts.contains("Continue in Background"), "{texts}"); + app.run("plugin.cancelRuns", json!({})).unwrap(); +} + +/// While a script runs, a worker run still gets its request and its time budget still ends it, and +/// no other run starts in a worker. +#[test] +fn on_the_web_a_worker_run_is_ended_at_its_time_budget_while_a_script_runs() { + let (mut app, fake) = web_app(); + let id = "test.ui.web.underscript"; + install_light(&mut app, id, false, "{}", ""); + app.session.prefs.show_external_script_warning = false; + app.run("plugin.dialog", json!({"id": id})).unwrap(); + fake.ready(0); + crate::menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "while (true) {}"})).unwrap().unwrap(); + assert!(app.session.script_running()); + app.poll_finished_work(); + assert_eq!(fake.worker(0).sent.borrow().len(), 1, "the run is posted while the script runs"); + assert!(app.run("plugin.dialog", json!({"id": id})).is_err(), "no new worker run"); + fake.clock.set(vectorcraft_plugins::Limits::default().wall_time_ms as f64 + plugin_runs::GRACE_MS); + app.poll_finished_work(); + assert!(app.plugin_runs.running.is_empty() && fake.worker(0).terminated.get()); + app.run("script.stop", json!({})).unwrap(); + while app.session.script_running() { + crate::script_runs::poll(&mut app); + } +} + +/// A recovery round waits while a run holds the documents, since a run that fails or is canceled +/// undoes its edits, and runs once the run ends. +#[test] +fn recovery_copies_wait_for_the_run_that_holds_the_documents() { + let store = std::sync::Arc::new(vectorcraft_engine::cmd::recovery::MemoryStore::default()); + let services = crate::Services { recovery_store: Some(store), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.allow_plugin_grants_from_requests(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + let id = "test.ui.recovery.holds"; + install_caller(&mut app, id, r#"{"objects":[]}"#); + app.session.prefs.autosave_interval = 2; + assert_eq!(crate::recovery::tick(&mut app, 10.0), 0); + vectorcraft_engine::cmd::plugin::FilterRun::begin_calls(&mut app.session, "plugin.run", &json!({"id": id})).unwrap(); + assert_eq!(crate::recovery::tick(&mut app, 130.0), 0, "not while the run holds the documents"); + app.session.end_plugin_calls(); + assert_eq!(crate::recovery::tick(&mut app, 131.0), 1); + registry::remove(id); +} + /// `CRAFT_UI_HEAVY_FILTER_WASM=` writes a heavy test filter to install in the app /// (`order-paths-test-filter.wasm`): it computes until it is cancelled or its budget runs out, so /// its progress window stays up for a picture. diff --git a/docs/plugins.md b/docs/plugins.md index 5d32d4f368..25f354ab65 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -194,19 +194,25 @@ how much there is only once the run has ended. ### The web build -The web build checks plug-ins and runs filters in Web Workers, so a plug-in's code never runs on the page. Trunk +The web build checks plug-ins in Web Workers, and runs there the filters and plug-in commands that the menus and +their dialogs start, so that code of a plug-in does not run on the page (the last item below lists the runs that +still do). Trunk builds the worker, `vectorcraft-plugin-worker` (`apps/vectorcraft-plugin-worker`), beside the app, and the page starts one worker for each check and each run (`vectorcraft_plugins::worker` describes the messages). - **Installing.** Install Plug-in… and File › Open send the module to a worker, which loads it as the desktop app does: its start function, `vc_abi_version` and `vc_manifest` run there. The page then makes the checks that run none of the module's code and installs it with the manifest the worker read. A module that fails in the worker is - not installed, and the status bar says why. + not installed, and the status bar says why. `ui.installPlugin` with module bytes that no worker has checked yet + returns `{"pending": true}` while the worker checks them, before it is known whether the install needs approval. + The install then goes on in the app: an approval question, if one is needed, shows in its dialog, and the reply + to that `ui.installPlugin` does not report it. - **Running a filter.** A filter's item in Object › Plug-ins, a plug-in command, or OK in their dialog, runs the filter in a worker, shown in the status bar and the progress window as a heavy filter is. The dialogs have no Preview. A command's run is one undo step named after the command, as on the desktop. The page terminates the worker at once on Cancel, when the document or the plug-in changes before the run ends (the status bar says to run - it again), and 5 s past the run's time budget when the worker has not answered (`Limit("time budget")`). + it again), and 5 s past the run's time budget when the worker has not answered (`Limit("time budget")`). The + budget counts from when the page starts the worker, so the worker's start-up counts toward it. - **Command calls.** A filter that calls commands sends each call to the page, which makes it and sends back the answer before the filter goes on. The calls and the output are one undo step. While it runs, every other command and edit is refused with "a plug-in is running: cancel it or wait for it to finish", and the progress window shows diff --git a/packaging/web/README.md b/packaging/web/README.md index dde861a32d..a9e23c118f 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -33,9 +33,11 @@ files need revalidation. `vectorcraft-web-` `.wasm` and `.js` files, and `no-cache` on `index.html` and the `vectorcraft-plugin-worker` files. The page refuses a cached worker whose messages differ from its own, and plug-ins then fail to install and run until the browser fetches the new worker. -- **Content Security Policy:** a site that sends one needs `worker-src 'self'` (or a `script-src` - that allows the site's own scripts) for the plug-in worker. Without it the app runs, and plug-ins - fail to install and run. +- **Content Security Policy:** a site that sends one needs `worker-src 'self'` for the plug-in + worker. Without `worker-src`, the browser uses `child-src`, then `script-src`, then + `default-src` ([CSP Level 3](https://www.w3.org/TR/CSP3/)), so a `script-src` that allows the + site's own scripts is enough only when the policy sets neither `worker-src` nor `child-src`. + When the policy blocks the worker, the app runs, and plug-ins fail to install and run. - **HTTPS:** WebGPU (and the clipboard) only work in a secure context, which means `https://` or `http://localhost`. Over plain HTTP elsewhere, the app falls back to WebGL2. - **No special isolation headers:** VectorCraft doesn't use `SharedArrayBuffer`, so it doesn't