From a354d09af41d9211ded03417387380e1d1bbe25e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:10:28 -0800 Subject: [PATCH] Scripts: folder listings take their time limit from the session's clock script::folder::list and script::startup::list measured the 250 ms listing limit (MAX_SCAN) with a real Instant. script.listInstalled, script.startup.run and the File > Scripts menu read the folders through them, so a test that went through any of these got a truncated listing and missing scripts whenever the disk stalled for 250 ms. - folder::Clock is either Wall (the real time since the listing started, the default) or Fixed (the same time at every check). Both list functions take one. - Session::set_script_listing_clock sets the clock the two commands and the menu's listing job use; the app keeps the real clock. - The script folder, startup script, scripts menu, script run and Safe Mode tests list with a fixed zero time, so a slow disk cannot cut a listing short. Direct listing calls use the test file's list helper. - New tests check that script.listInstalled, script.startup.run and the menu stop at the session's clock once it is past the limit and list everything at the limit. --- crates/engine/src/cmd/scripts.rs | 16 +++++++++-- crates/engine/src/lib.rs | 3 ++ crates/engine/src/script/folder.rs | 33 ++++++++++++++++++---- crates/engine/src/script/startup.rs | 9 +++--- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_folder.rs | 36 ++++++++++++++++++------ crates/engine/tests/script_startup.rs | 20 ++++++++++++- crates/ui-egui/src/scripts_menu.rs | 3 +- crates/ui-egui/src/tests/script_run.rs | 6 +++- crates/ui-egui/src/tests/scripts_menu.rs | 17 ++++++++++- crates/ui-egui/tests/safe_mode.rs | 1 + 11 files changed, 120 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 4529cef221..b3bd2f1298 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -295,6 +295,18 @@ impl Session { self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) } + /// Have listings of the Scripts and Startup Scripts folders measure their time with `clock` + /// instead of the real time ([`script::folder::Clock::Wall`], the default). + pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) { + self.script_listing_clock = clock; + } + + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + pub fn script_listing_clock(&self) -> script::folder::Clock { + self.script_listing_clock + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::startup::list(&root); + let listing = script::startup::list(&root, s.script_listing_clock); let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let (disabled, scripts): (Vec<_>, Vec<_>) = listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); @@ -647,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { let folder = root.to_string_lossy(); // The Scripts folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::folder::list(root); + let listing = script::folder::list(root, s.script_listing_clock); let scripts: Vec = listing .scripts() .into_iter() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 15fedf19dc..c8bd8c3f40 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -222,6 +222,9 @@ pub struct Session { /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder /// ([`Session::attach_startup_scripts_dir`]). startup_scripts_dir: Option, + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + script_listing_clock: script::folder::Clock, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index 9ec36c2447..f9e6c49be5 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -50,6 +50,30 @@ impl Default for Limits { } } +/// How a listing measures the time it has taken, which [`Limits::time`] bounds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Clock { + /// The real time since the listing started. + #[default] + Wall, + /// The same time at every check, whatever the real time: the listing reaches the time limit + /// only when this time is past it. + Fixed(Duration), +} + +impl Clock { + /// Calls `f` with this clock's time since `f` was called. + pub fn time(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T { + match self { + Clock::Wall => { + let start = std::time::Instant::now(); + f(&mut || start.elapsed()) + } + Clock::Fixed(elapsed) => f(&mut || elapsed), + } + } +} + /// One row of a listing. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Entry { @@ -93,11 +117,10 @@ impl Listing { } } -/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives -/// an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &Limits::default(), &mut || start.elapsed()) +/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`. +/// A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: Clock) -> Listing { + clock.time(|elapsed| list_with(root, &Limits::default(), elapsed)) } /// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken. diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs index e20e67de3f..a24dd08244 100644 --- a/crates/engine/src/script/startup.rs +++ b/crates/engine/src/script/startup.rs @@ -37,11 +37,10 @@ pub fn takes(name: &str) -> bool { && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) } -/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist -/// gives an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by +/// `clock`. A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: folder::Clock) -> Listing { + clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed)) } /// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2890618dd8..9e8e8f4163 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -112,6 +112,7 @@ impl Session { plugin_loads_in_background: false, scripts_dir: None, startup_scripts_dir: None, + script_listing_clock: Default::default(), metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 01d84ac99f..7d8f06700e 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { touch(&root, name); } std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); assert!(!listing.truncated && !listing.unreadable); // Each script keeps the path the folder gave, whatever its label. @@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { touch(&root, name); } // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. - assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); + assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); let _ = std::fs::remove_dir_all(dir); } @@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() touch(&root, "a\u{202E}sj.js"); let long = "n".repeat(200); touch(&root, &format!("{long}.jsx")); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); assert_eq!(labels[0], "a\\u{202E}sj"); assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); @@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() { let marked = touch(&root, "marked.js"); assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); } - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "shown"); assert!(!listing.truncated && !listing.unreadable); // Nor is a file behind a link read as a listed script. @@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada let dir = folder("root"); let root = dir.join("Scripts"); touch(&root, "a.js"); - assert_eq!(folder::list(&dir.join("None")), Listing::default()); + assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default()); let file = touch(&dir, "file"); - assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() }); let link = dir.join("Link"); link_folder(&root, &link); - assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() }); assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); let _ = std::fs::remove_dir_all(&link); let _ = std::fs::remove_dir_all(dir); @@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let root = dir.join("Scripts"); touch(&root, "1/2/3/4/kept.js"); touch(&root, "1/2/3/4/5/deeper.js"); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); assert!(listing.truncated); assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); @@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let listing = list(&root, Limits { folders: 1, ..Limits::default() }); assert_eq!(rows(&listing.entries), "a/[x]"); assert!(listing.truncated); - assert!(!folder::list(&root).truncated); + assert!(!list(&root, Limits::default()).truncated); let _ = std::fs::remove_dir_all(dir); let _ = std::fs::remove_dir_all(two); } @@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { touch(&root, "Tidy Layers.jsx"); touch(&root, "Export/All Artboards.js"); let mut s = Session::new(); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); assert_eq!( s.execute("script.listInstalled", &json!({})).unwrap(), json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) @@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("command-clock"); + let root = dir.join("Scripts"); + touch(&root, "a.jsx"); + let mut s = Session::new(); + s.attach_scripts_dir(root); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let late = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true))); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN)); + let on_time = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false))); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_installed_script_is_read_as_script_run_reads_a_file() { let dir = folder("installed"); @@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { std::fs::create_dir_all(&work).unwrap(); let mut s = Session::new(); s.attach_scripts_dir(root.clone()); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); // The Scripts folder is the app's: the error keeps the root and names the folder by its name. diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 527374c9f6..6b15ec0932 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -9,9 +9,11 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; +use std::time::Duration; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::script::folder::{self, Clock}; use vectorcraft_plugins::safe_mode; use vectorcraft_testkit::TempDir; @@ -56,9 +58,11 @@ fn write(dir: &Path, name: &str, text: &str) -> PathBuf { path } -/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take +/// no time. fn session(dir: &Path) -> Session { let mut s = Session::new(); + s.set_script_listing_clock(Clock::Fixed(Duration::ZERO)); s.attach_startup_scripts_dir(dir.to_path_buf()); s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); s @@ -115,6 +119,20 @@ fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script( assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); } +#[test] +fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let _f = fresh(); + let dir = tmp_dir("clock"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true))); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN)); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false))); +} + #[test] fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { let _f = fresh(); diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index c27df08742..443984de53 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -166,9 +166,10 @@ pub fn refresh(app: &VectorcraftApp, ctx: &egui::Context) { } if let Some(queue) = &state.queue { let read = root.clone(); + let clock = app.session.script_listing_clock(); // The app's own folder, read for the person at the keyboard. queue.submit(root, Priority::VISIBLE, move |_| { - vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read)) + vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read, clock)) }); } if !state.loaded && state.first_read.is_none() { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4a65e884e1..6b94d92d59 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -7,6 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::scripts::TOO_LARGE; use vectorcraft_engine::script::MAX_SOURCE_BYTES; +use vectorcraft_engine::script::folder::Clock; use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set}; use crate::dialogs::script_run::{ @@ -15,8 +16,11 @@ use crate::dialogs::script_run::{ use crate::tests::picks::{Picker, scripted}; use crate::{VectorcraftApp, menus, script_runs}; +/// An app with a document, whose folder listings take no time. fn app() -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default())); + let mut session = Session::new(); + session.set_script_listing_clock(Clock::Fixed(std::time::Duration::ZERO)); + let mut app = crate::testing::windowed(VectorcraftApp::new(session, crate::Services::default())); app.run("file.new", json!({})).unwrap(); app } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 300e0dbb32..2b25e7cb12 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -32,9 +32,10 @@ fn folder(name: &str) -> vectorcraft_testkit::TempDir { dir } -/// An app with a document whose Scripts folder is `dir`'s. +/// An app with a document whose Scripts folder is `dir`'s, and whose folder listings take no time. fn app(dir: &std::path::Path) -> VectorcraftApp { let mut session = Session::new(); + session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO)); session.attach_scripts_dir(dir.join("Scripts")); let mut app = VectorcraftApp::new(session, crate::Services::default()); app.ui_ctx = Some(ctx()); @@ -304,6 +305,20 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn the_menu_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("clock"); + let mut app = app(&dir); + write(&dir, "a.js", ""); + let late = vectorcraft_engine::script::folder::MAX_SCAN + Duration::from_millis(1); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(late)); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED)); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO)); + read(&app); + assert_eq!(shape(&scripts()), format!("a, -, {FIXED}")); +} + #[test] fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() { use vectorcraft_engine::file_access::{AutomationRoots, confine}; diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index 5bb94e3d37..8ce074111d 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -232,6 +232,7 @@ fn startup_scripts_wait_for_the_choice_and_disable_and_continue_leaves_out_the_o std::fs::write(launch_dir.join("launch-1-dead.json"), item.to_string()).unwrap(); let stopped = ui::begin_launch(Some(&launch_dir), false); let mut session = Session::new(); + session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); session.attach_startup_scripts_dir(scripts); session.prefs.run_startup_scripts = true; let mut app = VectorcraftApp::new(session, Services::default());