diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index ef0e4171c9..0484e170e0 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -158,6 +158,17 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -216,7 +227,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -226,12 +237,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -441,8 +447,12 @@ impl Session { /// [`Self::take_startup_failures`], and the next one starts. → the reply of the script queued /// after them when it ran to its end at once. pub(crate) fn start_queued(&mut self) -> Option { - while !self.script_running() { - match self.script_queue.pop_front()? { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + let mut reply = None; + while self.script_key.is_none() { + let Some(next) = queue.pop_front() else { break }; + match next { script::startup::Queued::Startup { path, fuel } => { if let Err(e) = self.start_startup(&path, fuel) { self.startup_failures.push((file_name_of(&path), e)); @@ -450,15 +460,16 @@ impl Session { } script::startup::Queued::Then(params) => { match run(self, ¶ms) { - Ok(_) if self.script_running() => {} - Ok(v) => return Some(v), + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), } - return None; + break; } } } - None + self.script_queue = queue; + reply } /// The runs `script.startup.run` queued that could not start since the last call, as (name, @@ -517,6 +528,10 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { if s.script_running() { return Err(EngineError::Busy); } + // A chosen script that cannot start ends the request before any startup script runs. + if let Some(then) = &then { + prepare(s, then)?; + } let root = match (s.startup_skip(), s.startup_scripts_dir()) { (None, Some(root)) => root.to_path_buf(), (why, _) => { @@ -541,7 +556,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let queued = s.script_queue.len(); s.startup_failures.clear(); let then = s.start_queued(); - let failed: Vec = s.startup_failures.iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); let mut out = json!({ "reason": reason, "skipped": false, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f5c1326c8d..d006f0500d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1653,9 +1653,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1868,9 +1869,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -2124,12 +2126,27 @@ impl Session { /// Advances the running script by one slice. `None` while it is still running; otherwise the /// run has ended: its report, or the error that ended it, with the documents put back. When - /// `script.startup.run` queued more runs, the next one starts then, and a queued run that cannot - /// start is kept for [`Self::take_startup_failures`]. + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { - let result = self.pump_one()?; + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && self.script_key.is_some() { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; self.startup_ended(); - self.start_queued(); Some(result) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..58a7c3848c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -61,7 +61,7 @@ impl Session { pub fn execute(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // 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/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 74afe9efa5..f0135636d4 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -266,27 +266,77 @@ fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startu } #[test] -fn in_the_app_a_chosen_script_that_cannot_start_leaves_the_startup_scripts_result() { +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { let _f = fresh(); let dir = tmp_dir("app-then"); write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); let mut s = session(&dir); s.script_frames = true; - let missing = dir.join("gone").join("missing.jsx"); - let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": missing.to_string_lossy()}})).unwrap(); - assert_eq!((r["running"].clone(), r["queued"].clone()), (json!(true), json!(2))); - let mut results = vec![]; - for _ in 0..10_000 { - if !s.script_running() { - break; - } - if let Some(r) = s.script_pump() { - results.push(r.is_ok()); + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); } - assert_eq!(results, [true], "the startup script's own result"); - let failures = s.take_startup_failures(); - assert_eq!(failures.iter().map(|(name, _)| name.as_str()).collect::>(), ["missing.jsx"]); } #[test] @@ -301,5 +351,5 @@ fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); assert_eq!(r["running"], json!(false)); assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); - assert_eq!(s.take_startup_failures().len(), 1, "and kept for the app's status bar"); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 907bbdb9bc..41f25e3f72 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -12,10 +12,7 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); - // Each run `script.startup.run` queued that could not start. - for (name, error) in app.session.take_startup_failures() { - app.status(format!("{name}: {error}")); - } + startup_failures(app); if !app.session.script_running() { return; } @@ -26,6 +23,9 @@ pub fn poll(app: &mut VectorcraftApp) { let name = app.session.script_name().unwrap_or_default(); let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); let Some(result) = app.session.script_pump() else { + // A pump that started the next queued run shows the runs before it that could not start + // in this frame: with none left running, the app may draw no next one. + startup_failures(app); // The app draws no more frames while the run waits: its question opens in this one. ask(app); return; @@ -49,6 +49,13 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// Shows each run `script.startup.run` queued that could not start. +fn startup_failures(app: &mut VectorcraftApp) { + for (name, error) in app.session.take_startup_failures() { + app.status(format!("{name}: {error}")); + } +} + /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index c1f418e62b..405593d3d6 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -600,6 +600,71 @@ fn with_run_startup_scripts_on_other_script_and_the_launch_run_the_startup_scrip let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_stopped_startup_script_says_it_was_stopped_and_the_chosen_script_still_runs() { + let dir = folder("startup-stop"); + let mut app = app(&dir); + let startup = dir.join("Startup Scripts"); + std::fs::create_dir_all(&startup).unwrap(); + std::fs::write(startup.join("a.jsx"), "for (;;) {}").unwrap(); + app.session.attach_startup_scripts_dir(startup); + app.session.prefs.show_external_script_warning = false; + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": DRAW, "name": "chosen" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_request_stop()); + app.status("before"); + for _ in 0..10_000 { + if app.ui.status != "before" { + break; + } + script_runs::poll(&mut app); + } + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "chosen"]); + assert_eq!(app.ui.status, "Ran chosen"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_last_startup_script_that_cannot_start_shows_in_the_status_bar_when_the_runs_end() { + let dir = folder("startup-last-fails"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + std::fs::write(dir.join("Startup Scripts").join("b.jsx"), big).unwrap(); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + finish(&mut app); + assert_eq!(started(&app), ["a.jsx", "b.jsx"]); + assert_eq!(app.ui.status, format!("b.jsx: {}", vectorcraft_engine::cmd::scripts::TOO_LARGE)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn with_run_startup_scripts_on_other_script_with_a_missing_file_fails_before_the_startup_scripts() { + let dir = folder("startup-missing"); + let mut app = app(&dir); + startup_folder(&mut app, &dir); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + let missing = dir.join("gone.jsx").to_string_lossy().into_owned(); + let alone = app.run("script.run", json!({ "path": missing })).unwrap_err(); + for warning in [false, true] { + app.session.prefs.show_external_script_warning = warning; + let e = match menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": missing })).unwrap() { + Err(e) => e, + // The warning opens first; its Run button gives the error. + Ok(_) => crate::dialogs::confirm(&mut app).unwrap_err(), + }; + assert_eq!(e, alone, "the error script.run gives, warning {warning}"); + assert!(!app.session.script_running()); + assert!(started(&app).is_empty(), "no startup script ran, warning {warning}"); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_startup_scripts_folder_that_cannot_be_read_shows_in_the_status_bar_at_launch_and_a_missing_one_does_not() { let dir = folder("startup-unreadable"); diff --git a/docs/mcp.md b/docs/mcp.md index 6f81dbb3f7..761ad4a579 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3191,13 +3191,16 @@ The rest of this section is VectorCraft's own rules: `vectorcraft-cli` uses the same folder and runs it only through `script.startup.run`. `script.startup.run {reason: launch|menu, then?, maxFuel?}` runs the folder now. `then` holds `script.run`'s -parameters for a script that runs after the startup scripts; `maxFuel` limits each startup script's instructions +parameters for a script that runs after the startup scripts. A `then` that `script.run` would refuse, such as a +missing file or one larger than 8 MiB, ends the request with `script.run`'s error before any startup script runs. +`maxFuel` limits each startup script's instructions (from 1 to 100,000,000,000, default 1,000,000,000). It returns `{reason, skipped: true, why}` with `why` set to `off`, `safeMode` or `noFolder` when nothing runs, and otherwise `{reason, skipped: false, ran, failed: [{name, error}], disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In the app the runs are queued and the reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming -the runs that could not start before the first one did; each run then reports as a `script.run` in the app does, and -a later run that cannot start, the chosen script included, is named in the status bar. Under `--automation-read-root` it reads the folder only when the folder lies inside a +the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the +next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the +status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. ```sh