VectorCraft: An open-source, vector art tool written by scratch in pure Rust
M14.4: a batch journals the dates and preferences its steps used
bflatastic766b612070f5
diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rsindex 108e0ffd7..a975d6c28 100644--- a/crates/engine/src/cmd/fileio/batch.rs+++ b/crates/engine/src/cmd/fileio/batch.rs@@ -6,21 +6,30 @@ use super::super::*;use crate::EngineError;pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {- let cmds = p.get("commands").and_then(Value::as_array).ok_or_else(|| bad("command.batch", "missing commands"))?.clone();+ let mut cmds = p.get("commands").and_then(Value::as_array).ok_or_else(|| bad("command.batch", "missing commands"))?.clone();let label = str_param(p, "label").unwrap_or("Batch").to_string();s.begin_interaction(&label)?;// Session-level state a step may change (paint defaults, drawing mode) rolls back too.let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone());let mut results = vec![];- for c in &cmds {- let id = c.get("command").and_then(Value::as_str).unwrap_or("");+ for c in &mut cmds {+ let id = c.get("command").and_then(Value::as_str).unwrap_or("").to_string();if id == "command.batch" {s.cancel_interaction()?;return Err(bad("command.batch", "batches cannot nest"));}let params = c.get("params").cloned().unwrap_or(json!({}));- match s.execute(id, ¶ms) {- Ok(v) => results.push(v),+ match s.execute_step(&id, ¶ms) {+ Ok((v, noted)) => {+ // The step's journal entry records what it took from the preferences or the+ // clock (a save's date), as a command of its own would.+ if noted != params+ && let Some(c) = c.as_object_mut()+ {+ c.insert("params".into(), noted);+ }+ results.push(v);+ }Err(e) => {s.cancel_interaction()?;(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard) = saved;@@ -29,8 +38,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {}}// Commit as one undo step (the interaction's "preview" is the batch itself).+ let mut entry = p.clone();+ if let Some(o) = entry.as_object_mut() {+ o.insert("commands".into(), Value::Array(cmds));+ }if let Some(it) = s.doc_mut()?.interaction.as_mut() {- it.preview = Some(("command.batch".into(), p.clone()));+ it.preview = Some(("command.batch".into(), entry));}s.commit_interaction()?;Ok(json!({ "results": results }))diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 12247d64b..0b4c64e70 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -207,6 +207,27 @@ pub const MAX_COORD: f64 = 4.0e6;/// ([`Session::journal_for_action`]).const REPLAY_ONLY: [(&str, &str); 3] = [("file.new", "created"), ("document.save", "modified"), ("file.saveAs", "modified")];+/// `p`, the params of command `id`, without its [`REPLAY_ONLY`] values (a batch: its steps').+fn strip_replay_only(id: &str, p: &mut Value) {+ let strip = |id: &str, p: &mut Value| {+ if let Value::Object(m) = p {+ m.retain(|k, _| !REPLAY_ONLY.iter().any(|&(c, key)| c == id && key == k));+ }+ };+ strip(id, p);+ // Batches don't nest: one level of steps.+ if id == "command.batch"+ && let Some(Value::Array(steps)) = p.get_mut("commands")+ {+ for step in steps {+ let id = step.get("command").and_then(Value::as_str).unwrap_or_default().to_string();+ if let Some(p) = step.get_mut("params") {+ strip(&id, p);+ }+ }+ }+}+/// Cheap sanity check after an edit: artboards and the objects just touched (the selection) must/// have finite, in-range geometry, so saved files always reload and renderers never see NaN/∞.fn doc_sane(d: &Document, sel: &Selection) -> bool {@@ -587,6 +608,9 @@ pub struct Session {/// Parameters the running top-level command resolved from the preferences or the clock, added/// to its journal entry so a replay does the same ([`Session::note_journal`]).journal_note: serde_json::Map<String, Value>,+ /// The depth of the command whose values [`Session::note_journal`] keeps: 1 (the top-level+ /// command), or a step's while a batch runs it ([`Session::execute_step`]).+ note_depth: u32,}impl Default for Session {@@ -624,6 +648,7 @@ impl Session {style_libraries: Default::default(),recent_urls: vec![],journal_note: Default::default(),+ note_depth: 1,}}@@ -752,6 +777,7 @@ impl Session {// be recorded twice and replay differently).if self.depth == 0 {self.journal_note.clear();+ self.note_depth = 1;}let r = if self.depth == 0 { self.run_guarded(id, |s| (spec.run)(s, params)) } else { self.run_nested(|s| (spec.run)(s, params)) };let r = r?;@@ -766,13 +792,26 @@ impl Session {}/// Record `key: value` in the running top-level command's journal entry (or its interaction's- /// preview) unless its params give `key`: a value it resolved from the preferences or the clock.+ /// preview, or its step in a batch) unless its params give `key`: a value it resolved from the+ /// preferences or the clock.pub fn note_journal(&mut self, key: &str, value: Value) {- if self.depth == 1 {+ if self.depth == self.note_depth {self.journal_note.insert(key.to_string(), value);}}+ /// Run `id` as a step of the running command, which journals its steps (`command.batch`):+ /// → the step's result and its params with what it noted ([`Session::note_journal`]), for the+ /// step in the running command's journal entry.+ pub(crate) fn execute_step(&mut self, id: &str, params: &Value) -> Result<(Value, Value)> {+ let outer = (std::mem::take(&mut self.journal_note), self.note_depth);+ self.note_depth = self.depth + 1;+ let r = self.execute(id, params);+ let noted = self.noted(params);+ (self.journal_note, self.note_depth) = outer;+ Ok((r?, noted))+ }+/// The journal from entry `start` on, as an action records it: without the params that only/// pin a replay to the original run ([`REPLAY_ONLY`]), so playing the action later acts now.pub fn journal_for_action(&self, start: usize) -> Vec<(String, Value)> {@@ -781,11 +820,7 @@ impl Session {.skip(start).cloned().map(|(id, mut p)| {- if let Value::Object(m) = &mut p {- for (_, key) in REPLAY_ONLY.iter().filter(|(c, _)| *c == id) {- m.remove(*key);- }- }+ strip_replay_only(&id, &mut p);(id, p)}).collect()diff --git a/crates/engine/src/tests_journal.rs b/crates/engine/src/tests_journal.rsindex 5b021f8cd..a9e5d7d41 100644--- a/crates/engine/src/tests_journal.rs+++ b/crates/engine/src/tests_journal.rs@@ -97,3 +97,59 @@ fn a_save_records_its_date_and_replays_it() {assert_eq!(r.doc().unwrap().doc.metadata, s.doc().unwrap().doc.metadata);assert!(s.journal_for_action(0).iter().all(|(_, p)| p.get("modified").is_none() && p.get("created").is_none()));}++/// The document `s` ends on after replaying the journal of `s` in a new session.+fn replayed(s: &Session) -> Session {+ let mut r = Session::new();+ for (id, p) in &s.journal {+ r.execute(id, p).unwrap();+ }+ r+}++#[test]+fn a_save_in_a_batch_records_its_date_and_replays_it() {+ let path = vectorcraft_testkit::temp_dir("journal-batch").join("a.vectorcraft").to_string_lossy().into_owned();+ let mut s = Session::new();+ s.execute("file.new", &json!({"created": 1_000_000_000})).unwrap();+ let rect = json!({"x": 10, "y": 10, "width": 50, "height": 40});+ let steps = json!([{"command": "shape.rectangle", "params": rect}, {"command": "document.save", "params": {"path": path}}]);+ s.execute("command.batch", &json!({ "commands": steps })).unwrap();+ let modified = s.doc().unwrap().doc.metadata.modified;+ assert!(modified.is_some(), "the save in the batch dates the document");+ // The step's entry records the date it used; steps that take nothing from elsewhere stay as given.+ let (id, p) = s.journal.last().unwrap().clone();+ assert_eq!(id, "command.batch");+ assert_eq!(p["commands"][0], steps[0]);+ assert_eq!(p["commands"][1]["params"], json!({"path": path, "modified": modified}));+ // As if the original run happened at another time: the replay lands on the recorded date.+ s.journal.last_mut().unwrap().1["commands"][1]["params"]["modified"] = json!(1_234_567_890);+ let r = replayed(&s);+ assert_eq!(r.doc().unwrap().doc.metadata.modified, Some(1_234_567_890));+ assert_eq!(r.doc().unwrap().doc.metadata.created, Some(1_000_000_000));+ assert_eq!(r.doc().unwrap().doc.node_count(), s.doc().unwrap().doc.node_count());+ // An action leaves the step's date out, so playing it later dates the document then.+ let action = s.journal_for_action(0);+ assert_eq!(action[1].1["commands"][1]["params"], json!({ "path": path }));+ assert_eq!(action[1].1["commands"][0], steps[0]);+}++#[test]+fn a_batch_step_records_what_it_took_from_the_preferences() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"created": null})).unwrap();+ s.prefs.scale_strokes = true;+ let steps = json!([+ {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 50, "height": 40}},+ {"command": "stroke.set", "params": {"weight": 2}},+ {"command": "object.scale", "params": {"sx": 300}},+ ]);+ s.execute("command.batch", &json!({ "commands": steps })).unwrap();+ let p = &s.journal.last().unwrap().1;+ assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false}));+ // Replayed with other preferences, the scale still scales the stroke.+ let r = replayed(&s);+ assert!(!r.prefs.scale_strokes);+ let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();+ assert_eq!(doc(&r), doc(&s));+}diff --git a/docs/mcp.md b/docs/mcp.mdindex c1cc79e5c..5cb808fa3 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -979,7 +979,8 @@ creation date) as text chunks, and SVG export writes the description as `<desc>`all of it as Dublin Core. `file.new {created}` and a save to a file (`document.save` or `file.saveAs` with`{path, modified}`) use the given date (Unix seconds, or `null` for none) instead of now. Their journal entries alwaysrecord the date they used, so replaying the journal makes the same document whenever it runs (an action recorded in-the Actions panel leaves the date out: playing it later dates the document then).+the Actions panel leaves the date out: playing it later dates the document then). As a step of `command.batch`, a+command records the date it used (and any value it takes from the preferences) in its step of the batch's journal entry.```json{"name":"run_command","arguments":{"command":"file.info","params":{"author":"Ada","keywords":"poster, fair","rating":4,"copyrightStatus":"copyrighted","copyrightNotice":"© 2026 Ada"}}}