From 7be9fdda792a4f3af38b74397d588999e16ca6b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 7 Nov 2026 21:46:52 -0500 Subject: [PATCH 1/9] feat(ui): the Session log names each entry's project and copies it back to the Script pane (#1579) --- crates/engine/src/cmd/exports.rs | 3 +- crates/engine/src/cmd/project.rs | 2 +- crates/engine/src/lib.rs | 9 +- crates/engine/src/project_log.rs | 50 ++++- crates/engine/src/tests.rs | 91 +++++++++- crates/ui-egui/src/analysispane.rs | 32 +++- crates/ui-egui/src/sessionlog.rs | 283 ++++++++++++++++++++++++++--- docs/user-guide/workspace.md | 25 ++- 8 files changed, 437 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 6122412017..0889076270 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -268,7 +268,8 @@ pub fn export_land(s: &mut Session, started: Started, done: Result Vec { // The session log (#797): read, written out, emptied, turned on or off. It sits outside // the project, so none of these changes the project or takes an undo step. C::new("project.log", "Session Log", "Project", log).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params( - r#"{"since"?: milliseconds since 1970 (UTC), "until"?: milliseconds, "command"?: "a command id, or the start of one (layer.)", "failed"?: bool (true: only those that failed; false: only those that succeeded), "limit"?: entries, a whole number (default 100, the newest; 1 to 1000)} → {"entries": [{"at", "command", "params", "ok", "error"?, "millis"}], "count": matching, "total": in the log, "on": bool}"#, + r#"{"since"?: milliseconds since 1970 (UTC), "until"?: milliseconds, "command"?: "a command id, or the start of one (layer.)", "failed"?: bool (true: only those that failed; false: only those that succeeded), "limit"?: entries, a whole number (default 100, the newest; 1 to 1000)} → {"entries": [{"at", "command", "params", "ok", "error"?, "millis", "project": the project open when it ran, "partial"?: true when params were cut or had secrets taken out}], "count": matching, "total": in the log, "on": bool}"#, ), C::new("project.exportLog", "Export Session Log", "Project", export_log).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e452d32259..4b9278eaaa 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1496,11 +1496,12 @@ impl Session { // command's result as it was, without an entry, and says so in the app's log. let logged = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { if project_log::is_logged(self, id, params) { - let params = match step { - Some(label) => serde_json::json!({"step": label}), - None => project_log::kept_params(params), + // The step's label isn't a parameter: the command, run again, takes none. + let (params, partial) = match step { + Some(label) => (serde_json::json!({"step": label}), false), + None => project_log::kept(params), }; - let e = project_log::entry(id, params, &res, at, start.elapsed()); + let e = project_log::entry(self, id, params, partial, &res, at, start.elapsed()); if joins && res.is_ok() { self.log.join_last(e) } else { self.log.push(e) } } })); diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 7898e2ae87..6aa2b5a43a 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -273,7 +273,16 @@ pub(crate) fn json_in_text_redacted(t: &str) -> String { match objects.next() { Some(Ok(v @ Value::Object(_))) => { let end = objects.byte_offset(); - out.push_str(&serde_json::to_string(&crate::cmd::history::redacted(&v)).unwrap_or_default()); + // Nothing taken out: the object as written, so a script copied back from the log + // is the one run, and isn't said to be partial for its spacing. Not one naming a + // secret: a key written twice is read as its last, and the text keeps the first. + let kept = crate::cmd::history::redacted(&v); + let written = from.get(..end).unwrap_or(""); + if kept == v && last_secret_name(written).is_none() { + out.push_str(written); + } else { + out.push_str(&serde_json::to_string(&kept).unwrap_or_default()); + } rest = from.get(end..).unwrap_or(""); } // Cut short by the clip, or an object that doesn't parse (a trailing comma, single @@ -430,7 +439,9 @@ fn clip(v: &Value, chars: usize, items: usize, depth: usize) -> Value { /// The entry of command `id`, which started at `at` and took `took`; its error without secrets, /// clipped to [`LOG_ERROR_CHARS`]. -pub(crate) fn entry(id: &str, params: Value, res: &CmdResult, at: u64, took: web_time::Duration) -> LogEntry { +/// `partial`: its parameters aren't all as given ([`kept`]). It is the entry of the project open +/// in `s` as it ended: the one a command that opens a project opened. +pub(crate) fn entry(s: &Session, id: &str, params: Value, partial: bool, res: &CmdResult, at: u64, took: web_time::Duration) -> LogEntry { let error = res.as_ref().err().map(|e| kept_error(e)); LogEntry { at, @@ -439,9 +450,20 @@ pub(crate) fn entry(id: &str, params: Value, res: &CmdResult, at: u64, took: web ok: res.is_ok(), error, millis: u64::try_from(took.as_millis()).unwrap_or(u64::MAX), + project: s.title().chars().take(200).collect(), + opened: s.opened, + partial, } } +/// `params` as the log keeps them ([`kept_params`]), and whether that is less than they were: +/// cut to fit or with secrets taken out, so they wouldn't run again as they ran. +pub(crate) fn kept(params: &Value) -> (Value, bool) { + let kept = kept_params(params); + let partial = kept != *params; + (kept, partial) +} + /// Most entries the log keeps; past it, the oldest go first. pub const LOG_LIMIT: usize = 10_000; /// The most entries of plugins' commands the log keeps, their oldest going first past it: a @@ -454,9 +476,9 @@ pub const LOG_LIST_ITEMS: usize = 100; pub const LOG_ERROR_CHARS: usize = 500; /// One command run in the session: when it started (UTC, milliseconds since 1970), its id, its -/// parameters (secrets taken out, large values clipped), whether it succeeded, its error, and how -/// long it took. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +/// parameters (secrets taken out, large values clipped), whether it succeeded, its error, how +/// long it took, and the project it ran in. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct LogEntry { pub at: u64, pub command: String, @@ -467,6 +489,17 @@ pub struct LogEntry { pub error: Option, #[serde(default)] pub millis: u64, + /// The name of the project open when it ran (the one it opened, for a command that opens one). + #[serde(default)] + pub project: String, + /// Which of the session's projects that was ([`Session::opened`]), so two of the same name + /// (two new ones, both "Untitled") are told apart. The session's own: not saved with the log. + #[serde(skip)] + pub opened: u64, + /// Its parameters aren't all as given (cut to fit, or with secrets taken out): copied, they + /// wouldn't run as they ran. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub partial: bool, } impl LogEntry { @@ -607,7 +640,7 @@ impl SessionLog { /// line). Entry by entry, so a long log isn't held as text first. pub fn write(&self, w: &mut dyn std::io::Write, csv: bool) -> std::io::Result<()> { if csv { - w.write_all(b"time_utc,at,command,ok,millis,error,params\n")?; + w.write_all(b"time_utc,at,command,ok,millis,error,params,project\n")?; } self.entries.iter().try_for_each(|e| write_entry(w, e, csv)) } @@ -634,14 +667,15 @@ fn write_entry(w: &mut dyn std::io::Write, e: &LogEntry, csv: bool) -> std::io:: if csv { writeln!( w, - "{},{},{},{},{},{},{}", + "{},{},{},{},{},{},{},{}", e.time_utc(), e.at, csv_cell(&e.command), e.ok, e.millis, csv_cell(e.error.as_deref().unwrap_or("")), - csv_cell(&e.params.to_string()) + csv_cell(&e.params.to_string()), + csv_cell(&e.project) ) } else { serde_json::to_writer(&mut *w, e).map_err(std::io::Error::other)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c0872918db..c65bb6deed 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28740,7 +28740,15 @@ fn the_session_log_records_each_command_run_in_the_session() { assert_eq!(doc.params["text"], json!(format!("(a document of {} characters)", qgs.chars().count())), "{doc:?}"); // A step joined to the newest entry (a held key's nudges) is a change too, so a view of the // log reads it again. - let nudge = |millis| LogEntry { at: 1, command: "layout.nudge".into(), params: json!({"dx": 1}), ok: true, error: None, millis }; + let nudge = |millis| LogEntry { + at: 1, + command: "layout.nudge".into(), + params: json!({"dx": 1}), + ok: true, + error: None, + millis, + ..Default::default() + }; s.log.push(nudge(2)); let before = s.log.changes(); s.log.join_last(nudge(3)); @@ -28800,7 +28808,15 @@ fn the_session_log_records_each_command_run_in_the_session() { assert!(s.run("project.log", &json!({"failed": "true"})).is_err()); assert!(s.run("project.log", &json!({"command": 7})).is_err()); // An error that starts as a spreadsheet formula is written as text in the CSV. - let formula = LogEntry { at: 2, command: "x".into(), params: Value::Null, ok: false, error: Some("=HYPERLINK(1)".into()), millis: 0 }; + let formula = LogEntry { + at: 2, + command: "x".into(), + params: Value::Null, + ok: false, + error: Some("=HYPERLINK(1)".into()), + millis: 0, + ..Default::default() + }; s.log.push(formula); // Written out as CSV and JSON Lines. let dir = std::env::temp_dir().join(format!("rustgis-session-log-{}", std::process::id())); @@ -28808,7 +28824,10 @@ fn the_session_log_records_each_command_run_in_the_session() { let csv = dir.join("log.csv"); s.run("project.exportLog", &json!({"path": csv.to_string_lossy()})).unwrap(); let csv_text = std::fs::read_to_string(&csv).unwrap(); - assert!(csv_text.starts_with("time_utc,at,command,ok,millis,error,params\n") && csv_text.contains("\"edit.undo\""), "{csv_text}"); + assert!( + csv_text.starts_with("time_utc,at,command,ok,millis,error,params,project\n") && csv_text.contains("\"edit.undo\""), + "{csv_text}" + ); assert!(csv_text.contains("\"'=HYPERLINK(1)\"") && !csv_text.contains(",\"=HYPERLINK"), "{csv_text}"); let jsonl = dir.join("log.jsonl"); s.run("project.exportLog", &json!({"path": jsonl.to_string_lossy()})).unwrap(); @@ -28851,7 +28870,15 @@ fn the_session_log_records_each_command_run_in_the_session() { s.run("project.logCommands", &json!({"on": true})).unwrap(); // Capped: the oldest go first. for i in 0..LOG_LIMIT + 5 { - s.log.push(LogEntry { at: i as u64, command: "x".into(), params: Value::Null, ok: true, error: None, millis: 0 }); + s.log.push(LogEntry { + at: i as u64, + command: "x".into(), + params: Value::Null, + ok: true, + error: None, + millis: 0, + ..Default::default() + }); } assert_eq!(s.log.len(), LOG_LIMIT); assert_eq!(s.log.entries().next().unwrap().at, 5); @@ -28882,6 +28909,52 @@ fn the_session_log_records_each_command_run_in_the_session() { assert_eq!(s.log.len(), n, "nothing to undo or redo: not logged"); } +/// Each entry names the project it ran in (the one it opened, for a command that opens one), and +/// another project of the same name is told apart; parameters cut to fit or without their secrets +/// are said to be partial, as they wouldn't run as they ran; a saved log keeps the project's name. +#[test] +fn session_log_entries_name_their_project_and_say_when_their_params_are_partial() { + #[cfg(not(target_arch = "wasm32"))] + if isolate_process_test("tests::session_log_entries_name_their_project_and_say_when_their_params_are_partial") { + return; + } + let mut s = world(); + s.log.clear(); + let last = |s: &Session| s.log.entries().last().cloned().unwrap(); + s.run("project.rename", &json!({"name": "Atlas"})).unwrap(); + let renamed = last(&s); + assert_eq!((renamed.project.as_str(), renamed.opened, renamed.partial), ("Atlas", s.opened, false), "{renamed:?}"); + s.run("project.new", &json!({"name": "Atlas"})).unwrap(); + let made = last(&s); + assert_eq!((made.command.as_str(), made.project.as_str(), made.opened), ("project.new", "Atlas", s.opened)); + assert_ne!(made.opened, renamed.opened, "the same name, another project"); + // A script with nothing to take out is kept as written, its spacing too: not partial. + let script = "map.new {\"name\": \"Third\"}\n# a { that isn't JSON"; + s.run("script.run", &json!({"script": script})).unwrap(); + let ran = last(&s); + assert_eq!((ran.params["script"].as_str(), ran.partial), (Some(script), false), "{ran:?}"); + // A secret's key written twice is read as its last value: the first isn't kept as written. + let _ = + s.run("script.run", &json!({"script": "map.new {\"name\": \"M\", \"secretAccessKey\": \"S3CRET\", \"secretAccessKey\": \"\"}"})); + let twice = last(&s); + assert!(!twice.params.to_string().contains("S3CRET") && twice.partial, "{twice:?}"); + // A script past the log's bound is cut: partial, so it isn't run again as a part. + let long = format!("# {}", "x".repeat(crate::project_log::LOG_PARAMS_BYTES * 2)); + s.run("script.run", &json!({"script": long})).unwrap(); + assert!(last(&s).partial); + // An address without its token: partial too. + let _ = s.run("service.layers", &json!({"url": "https://x.org/wms?token=S3CRET&layers=a", "text": "not a capabilities document"})); + assert!(last(&s).partial, "{:?}", last(&s)); + // Saved: the project's name last in a CSV row; in JSON, the name, and `partial` only when so. + let mut csv = Vec::new(); + s.log.write(&mut csv, true).unwrap(); + let csv = String::from_utf8(csv).unwrap(); + assert!(csv.lines().nth(1).is_some_and(|row| row.ends_with(",\"Atlas\"")), "{csv}"); + let json = serde_json::to_value(&renamed).unwrap(); + assert_eq!(json["project"], "Atlas"); + assert!(json.get("opened").is_none() && json.get("partial").is_none(), "{json}"); +} + /// What the session log keeps of a command's parameters: bounded in bytes, keys and time, and /// without secrets, those in JSON a text holds and in SQL `CREATE … SECRET` options included. #[test] @@ -28950,7 +29023,15 @@ fn plugins_can_neither_clear_the_session_log_nor_crowd_out_the_users_entries() { use crate::project_log::LogEntry; // Plugins' commands keep at most their own share of the log: the user's entries stay. let mut log = crate::project_log::SessionLog::default(); - let entry = |command: &str| LogEntry { at: 1, command: command.into(), params: Value::Null, ok: true, error: None, millis: 0 }; + let entry = |command: &str| LogEntry { + at: 1, + command: command.into(), + params: Value::Null, + ok: true, + error: None, + millis: 0, + ..Default::default() + }; log.push(entry("layer.rename")); for _ in 0..crate::project_log::LOG_PLUGIN_LIMIT + 5 { log.push(entry("plugin:p/flood")); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9482dacf53..b098b27fb0 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1576,16 +1576,42 @@ fn start_over_in_another_project(app: &mut RustGisApp) { /// the focus given to the box, so Ctrl+Z brings the script back. The box records undo steps only /// while focused, so the step is added here, as `scriptcomplete::accept` does. fn clear_keeping_undo(app: &mut RustGisApp, ui: &Ui, box_id: egui::Id) { + keep_for_undo(app, ui.ctx(), box_id); + clear_script(app); + ui.memory_mut(|m| m.request_focus(box_id)); +} + +/// The Script box's script kept as an undo step of the box, its cursor at the start, before +/// something else replaces it (Clear, Open in Script Pane). +fn keep_for_undo(app: &RustGisApp, ctx: &egui::Context, box_id: egui::Id) { use egui::text::{CCursor, CCursorRange}; - let mut state = egui::widgets::text_edit::TextEditState::load(ui.ctx(), box_id).unwrap_or_default(); + let mut state = egui::widgets::text_edit::TextEditState::load(ctx, box_id).unwrap_or_default(); let mut undoer = state.undoer(); let end = CCursorRange::one(CCursor::new(app.workflow.script.chars().count())); undoer.add_undo(&(state.cursor.char_range().unwrap_or(end), app.workflow.script.clone())); state.set_undoer(undoer); state.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(0)))); - state.store(ui.ctx(), box_id); + state.store(ctx, box_id); +} + +/// Whether a Script pane run is under way or waiting: what lands from it would land in a script +/// replaced meanwhile. +pub(crate) fn script_running(app: &RustGisApp) -> bool { + !app.workflow.script_started.is_empty() +} + +/// Opens `script` in the Script pane (the session log's Open in Script Pane), in place of the +/// pane's script and results, as Clear empties them: the script that was there comes back with +/// Ctrl+Z, even one left from a project since replaced (kept first, then the pane started over, +/// so that doesn't empty it when it next shows). +pub(crate) fn open_script(app: &mut RustGisApp, ctx: &egui::Context, script: String) { + let box_id = egui::Id::unique("script_text"); + keep_for_undo(app, ctx, box_id); + start_over_in_another_project(app); clear_script(app); - ui.memory_mut(|m| m.request_focus(box_id)); + app.workflow.script = script; + app.ui.open_right(crate::RightPane::Script); + ctx.memory_mut(|m| m.request_focus(box_id)); } /// The Script pane emptied: its script, results and count, so the next run is `Run #1`, and the diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 1da4562c77..18207ab241 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -1,6 +1,7 @@ //! The History pane's session log (opengeos/RustGIS#797, part 2): the commands run in the -//! session, newest first, filtered by command and to those that failed; saved as CSV or JSON -//! Lines; cleared or turned off. It shows the session's log (`Session::log`) as `project.log` +//! session, newest first, each with its project, filtered by command, to those that failed and to +//! the project open now; copied back as Script pane lines; saved as CSV or JSON Lines; cleared or +//! turned off. It shows the session's log (`Session::log`) as `project.log` //! gives it, and changes it only through the log's commands, so what the pane does is logged as //! a script's would be. @@ -15,8 +16,9 @@ use crate::theme::{Tokens, semibold}; pub const SHOWN: usize = 200; /// What the listed rows were picked from: the log's [`changes`](rustgis_engine::project_log::SessionLog::changes) -/// and the filters, the query as typed (trimmed). -type Key = (u64, String, bool); +/// and the filters, the query as typed (trimmed), and the project open now when only its entries +/// are listed. +type Key = (u64, String, bool, Option); /// An entry as the pane draws it: its texts made once, when the rows are picked. struct Row { @@ -27,10 +29,14 @@ struct Row { /// How long it took, and when it started. took: String, at: String, + /// Its command can run as a script's line: one the session has (not a plugin's, which a + /// script can't run) and not one refused there (scripts, notebooks, the interface's own). + scriptable: bool, } impl Row { - fn of(e: LogEntry) -> Row { + fn of(e: LogEntry, registry: &rustgis_engine::Registry) -> Row { + let scriptable = registry.get(&e.command).is_some() && !rustgis_engine::cmd::workflows::refused_in_script(&e.command); let params = params_text(&e); // One line in the list; the whole of it (up to the log's 4 KB) on hover. let mut line: String = params.chars().take(120).collect(); @@ -38,8 +44,12 @@ impl Row { line.push('…'); } let took = crate::i18n::fmt("{ms} ms", &[("ms", &e.millis.to_string())]); - let at = crate::i18n::fmt("{time} UTC", &[("time", &e.time_utc())]); - Row { e, params, line, took, at } + let at = if e.project.is_empty() { + crate::i18n::fmt("{time} UTC", &[("time", &e.time_utc())]) + } else { + crate::i18n::fmt("{time} UTC · {project}", &[("time", &e.time_utc()), ("project", &e.project)]) + }; + Row { e, params, line, took, at, scriptable } } } @@ -52,6 +62,8 @@ pub struct State { pub query: String, /// Only the commands that failed. pub failed: bool, + /// Only the commands run in the project open now. + pub this_project: bool, /// The rows last listed and how many match and are in the log, kept while their [`Key`] /// holds: the pane is drawn each frame, and picking them goes through the whole log. cache: Option<(Key, Vec, usize, usize)>, @@ -72,29 +84,34 @@ pub fn tabs(app: &mut RustGisApp, ui: &mut Ui) -> bool { app.ui.session_log.open } -/// Whether entry `e` is one the filters keep: `query` already in lower case. -fn kept(e: &LogEntry, query: &str, failed: bool) -> bool { - (!failed || !e.ok) && (query.is_empty() || e.command.to_lowercase().contains(query)) +/// Whether entry `e` is one the filters keep: `query` already in lower case; `project`, the +/// project its entries are the only ones kept ([`rustgis_engine::Session::opened`]). +fn kept(e: &LogEntry, query: &str, failed: bool, project: Option) -> bool { + (!failed || !e.ok) && (query.is_empty() || e.command.to_lowercase().contains(query)) && project.is_none_or(|p| e.opened == p) } /// The session log: its filters, its newest entries that match, and what can be done with it. pub fn pane(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { - ui.horizontal(|ui| { + // Wrapped: in a narrow pane the filters go on to the next line, the field kept as wide. + ui.horizontal_wrapped(|ui| { let s = &mut app.ui.session_log; ui.add(egui::TextEdit::singleline(&mut s.query).hint_text(tl!("Filter by command")).desired_width(170.0)) .on_hover_text(tl!("Words in the command's id, such as layer. or export")); + ui.toggle_value(&mut s.this_project, tl!("This project")).on_hover_text(tl!("Only the commands run in the project open now")); ui.checkbox(&mut s.failed, tl!("Failed only")); }); // Compared in place, so a repaint that changes nothing picks, formats and clones nothing; // the rows (and their texts) are made again only when the key changed. - let (log, State { query, failed, cache, .. }) = (&app.session.log, &mut app.ui.session_log); + let (log, registry, State { query, failed, this_project, cache, .. }) = + (&app.session.log, &app.session.registry, &mut app.ui.session_log); let raw = query.trim(); - let same = cache.as_ref().is_some_and(|(k, ..)| k.0 == log.changes() && k.1 == raw && k.2 == *failed); + let project = this_project.then_some(app.session.opened); + let same = cache.as_ref().is_some_and(|(k, ..)| k.0 == log.changes() && k.1 == raw && k.2 == *failed && k.3 == project); if !same { let lower = raw.to_lowercase(); - let (shown, count, total) = log.select(|e| kept(e, &lower, *failed), SHOWN); - let rows = shown.into_iter().map(Row::of).collect(); - *cache = Some(((log.changes(), raw.to_string(), *failed), rows, count, total)); + let (shown, count, total) = log.select(|e| kept(e, &lower, *failed, project), SHOWN); + let rows = shown.into_iter().map(|e| Row::of(e, registry)).collect(); + *cache = Some(((log.changes(), raw.to_string(), *failed, project), rows, count, total)); } let (count, total, listed) = cache.as_ref().map_or((0, 0, 0), |(_, rows, matched, all)| (*matched, *all, rows.len())); let note = if total == 0 { @@ -119,12 +136,21 @@ pub fn pane(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.label(egui::RichText::new(tl!("Logging is off: commands run now aren't recorded.")).size(11.0).color(t.red)); } ui.add_space(4.0); + let running = crate::analysispane::script_running(app); + let mut picked = None; if let Some((_, rows, ..)) = &app.ui.session_log.cache { for r in rows.iter().rev() { - row(ui, r, t); + picked = row(ui, r, t, running).or(picked); ui.add_space(4.0); } } + match picked { + Some(Picked::Open(script)) => crate::analysispane::open_script(app, ui.ctx(), script), + Some(Picked::CopiedPartial) => app + .session + .notify(tl!("Copied. The log cut its parameters short or took their secrets out, so it may not run as it ran."), false), + None => {} + } ui.horizontal_wrapped(|ui| { let tip = tl!("The whole log, as CSV or JSON Lines (.jsonl): it may name files and addresses, so look at it before sharing it"); if ui.add_enabled(total > 0, egui::Button::new(tl!("Save Log As…"))).on_hover_text(tip).clicked() { @@ -154,10 +180,37 @@ fn params_text(e: &LogEntry) -> String { } } -/// One entry: whether it worked, its command, how long it took, when it started, its error and -/// its parameters (all of them on hover; right-click copies them). The right-click is sensed -/// behind the row's contents, which only sense hover, so their hover texts still show. -fn row(ui: &mut Ui, item: &Row, t: &Tokens) { +/// A Script pane line for entry `e`: its command and parameters, as History's Copy as Command +/// writes one. Undo and redo alone: what the log keeps of them is the step's label, not a +/// parameter. +fn command_line(e: &LogEntry) -> String { + let params = params_text(e); + if params.is_empty() || matches!(e.command.as_str(), "edit.undo" | "edit.redo") { + e.command.clone() + } else { + format!("{} {params}", e.command) + } +} + +/// The script a `script.run` entry ran, as the log kept it. +fn script_of(e: &LogEntry) -> Option<&str> { + if e.command == "script.run" { e.params.get("script").and_then(Value::as_str) } else { None } +} + +/// What a row's menu asked for that the pane does once the rows are drawn. +enum Picked { + /// Open in Script Pane, with this script. + Open(String), + /// Copy Command, of parameters the log cut short or took secrets out of: said. + CopiedPartial, +} + +/// One entry: whether it worked, its command, how long it took, when it started and in which +/// project, its error and its parameters (all of them on hover). A right-click copies them, or +/// the entry as a Script pane line; a script run, its script, or opens it in the Script pane +/// (not while `running`, a run of the pane's own under way). The right-click is sensed behind +/// the row's contents, which only sense hover, so their hover texts still show. +fn row(ui: &mut Ui, item: &Row, t: &Tokens, running: bool) -> Option { let (e, params) = (&item.e, item.params.as_str()); let frame = egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)); @@ -189,16 +242,38 @@ fn row(ui: &mut Ui, item: &Row, t: &Tokens) { } }) }); + let mut picked = None; r.response.context_menu(|ui| { if ui.add_enabled(!params.is_empty(), egui::Button::new(tl!("Copy Parameters"))).clicked() { ui.ctx().copy_text(params.to_string()); ui.close(); } - if ui.button(tl!("Copy Command")).clicked() { - ui.ctx().copy_text(e.command.clone()); - ui.close(); + if let Some(script) = script_of(e) { + // A script cut short would run only its first part: neither copied nor opened. + let cut = tl!("The log cut it short or took its secrets out: it would run only in part"); + let copy = ui.add_enabled(!e.partial, egui::Button::new(tl!("Copy Script"))); + if copy.on_hover_text(tl!("The script, for the Script pane")).on_disabled_hover_text(cut).clicked() { + ui.ctx().copy_text(script.to_string()); + ui.close(); + } + let undo = if ui.ctx().os().is_mac() { "⌘+Z" } else { "Ctrl+Z" }; + let tip = crate::i18n::fmt("In place of the Script pane's script ({keys} brings it back)", &[("keys", undo)]); + let why = if e.partial { cut } else { tl!("Wait for the Script pane's run to finish") }; + let open = ui.add_enabled(!e.partial && !running, egui::Button::new(tl!("Open in Script Pane"))); + if open.on_hover_text(tip).on_disabled_hover_text(why).clicked() { + picked = Some(Picked::Open(script.to_string())); + ui.close(); + } + } else { + let copy = ui.add_enabled(item.scriptable, egui::Button::new(tl!("Copy Command"))); + if copy.on_hover_text(tl!("A line for the Script pane")).on_disabled_hover_text(tl!("It can't run in a script")).clicked() { + ui.ctx().copy_text(command_line(e)); + picked = e.partial.then_some(Picked::CopiedPartial); + ui.close(); + } } }); + picked } /// A row's text: not selectable, so a right-click on it reaches the row. @@ -320,7 +395,15 @@ mod tests { fn a_joined_entry_is_shown_as_it_is_now() { let mut app = RustGisApp::with_sample(); app.session.log.clear(); - let nudge = |millis| LogEntry { at: 1, command: "layout.nudge".into(), params: json!({"dx": 1}), ok: true, error: None, millis }; + let nudge = |millis| LogEntry { + at: 1, + command: "layout.nudge".into(), + params: json!({"dx": 1}), + ok: true, + error: None, + millis, + ..Default::default() + }; app.session.log.push(nudge(2)); app.ui.session_log.open = true; let mut h = harness(app); @@ -357,7 +440,15 @@ mod tests { let mut app = RustGisApp::with_sample(); app.session.log.clear(); for i in 0..rustgis_engine::project_log::LOG_LIMIT + 7 { - app.session.log.push(LogEntry { at: i as u64, command: "x".into(), params: Value::Null, ok: true, error: None, millis: 0 }); + app.session.log.push(LogEntry { + at: i as u64, + command: "x".into(), + params: Value::Null, + ok: true, + error: None, + millis: 0, + ..Default::default() + }); } app.ui.session_log.open = true; let mut h = harness(app); @@ -368,7 +459,15 @@ mod tests { app.session.log.clear(); for i in 0..rustgis_engine::project_log::LOG_PLUGIN_LIMIT + 2 { let command = format!("{}eng/f", rustgis_plugins::PREFIX); - app.session.log.push(LogEntry { at: i as u64, command, params: Value::Null, ok: true, error: None, millis: 0 }); + app.session.log.push(LogEntry { + at: i as u64, + command, + params: Value::Null, + ok: true, + error: None, + millis: 0, + ..Default::default() + }); } h.run(); assert!(h.query_by_label("2 older plugin command entries were dropped past the 1000 kept for plugins").is_some()); @@ -425,7 +524,7 @@ mod tests { save(&mut app); let (name, text) = got.borrow_mut().take().expect("downloaded"); assert_eq!(name, "session-log.csv"); - assert!(text.starts_with("time_utc,at,command,ok,millis,error,params\n"), "{text}"); + assert!(text.starts_with("time_utc,at,command,ok,millis,error,params,project\n"), "{text}"); assert!(text.contains("\"map.new\",true"), "{text}"); let dropped = |app: &RustGisApp| { app.session.notices.iter().any(|n| n.text.contains("session-log.csv: not in it: 4 oldest entries were dropped past")) @@ -433,7 +532,15 @@ mod tests { assert!(!dropped(&app), "nothing dropped, nothing said"); // Past the log's limit, the download says how many it lacks. for i in 0..rustgis_engine::project_log::LOG_LIMIT + 3 { - app.session.log.push(LogEntry { at: i as u64, command: "x".into(), params: Value::Null, ok: true, error: None, millis: 0 }); + app.session.log.push(LogEntry { + at: i as u64, + command: "x".into(), + params: Value::Null, + ok: true, + error: None, + millis: 0, + ..Default::default() + }); } save(&mut app); assert!(got.borrow_mut().take().is_some()); @@ -472,4 +579,122 @@ mod tests { h.run(); assert!(h.query_by_label("Copy Command").is_some()); } + + /// Each row says the project it ran in; This project lists only the project open now's. + #[test] + fn each_entry_names_its_project_and_this_project_lists_the_open_ones() { + let mut app = RustGisApp::with_sample(); + app.session.log.clear(); + app.run("map.new", json!({"name": "Before"})).unwrap(); + app.run("project.new", json!({"name": "Second project"})).unwrap(); + app.run("map.new", json!({"name": "After"})).unwrap(); + app.ui.session_log.open = true; + let mut h = harness(app); + h.run(); + assert!(h.query_by_label("3 entries").is_some()); + assert_eq!(h.query_all_by_label_contains("UTC · Second project").count(), 2, "the open and what came after"); + h.get_by_label("This project").click(); + h.run(); + assert!(h.state().ui.session_log.this_project); + assert!(h.query_by_label("2 of 3 entries").is_some()); + assert!(h.query_by_label(r#"{"name":"Before"}"#).is_none() && h.query_by_label(r#"{"name":"After"}"#).is_some()); + } + + /// Right-clicks row `row` and picks `item` in its menu: the text it put on the clipboard. + fn pick(h: &mut egui_kittest::Harness<'_, RustGisApp>, row: &str, item: &str) -> Vec { + h.get_by_label(row).click_secondary(); + h.run(); + h.get_by_label(item).click(); + let mut copied = Vec::new(); + for _ in 0..4 { + h.step(); + for c in &h.output().platform_output.commands { + if let egui::OutputCommand::CopyText(t) = c { + copied.push(t.clone()); + } + } + } + copied + } + + /// Copy Command copies a Script pane line; a script run copies its script, or opens it in the + /// Script pane in place of the pane's, which Ctrl+Z brings back. + #[test] + fn a_row_copies_its_line_and_a_script_run_opens_in_the_script_pane() { + let mut app = RustGisApp::with_sample(); + app.session.log.clear(); + app.run("map.new", json!({"name": "Second"})).unwrap(); + let script = "map.new {\"name\": \"Third\"}"; + app.run("script.run", json!({"script": script})).unwrap(); + app.workflow.script = "kept".into(); + app.ui.session_log.open = true; + let mut h = harness(app); + h.run(); + assert_eq!(pick(&mut h, "map.new", "Copy Command"), [r#"map.new {"name":"Second"}"#]); + assert_eq!(pick(&mut h, "script.run", "Copy Script"), [script]); + h.get_by_label("script.run").click_secondary(); + h.run(); + assert!(h.query_by_label("Copy Command").is_none(), "a script can't run in a script"); + h.get_by_label("Open in Script Pane").click(); + h.run(); + assert_eq!(h.state().workflow.script, script); + assert_eq!(h.state().ui.right, Some(crate::RightPane::Script)); + let id = egui::Id::unique("script_text"); + let state = egui::widgets::text_edit::TextEditState::load(&h.ctx, id).expect("the box's state"); + let mut undoer = state.undoer(); + let at = state.cursor.char_range().expect("a cursor"); + assert_eq!(undoer.undo(&(at, script.to_string())).map(|(_, t)| t.as_str()), Some("kept"), "Ctrl+Z brings the script back"); + // Opened after another project replaced the pane's, the script left in it still comes back + // with Ctrl+Z: the pane starting over doesn't lose it first. + h.state_mut().workflow.script = "unrun".into(); + h.state_mut().run("project.new", json!({"name": "Other"})).unwrap(); + // Drawn again first: the new entry moves the rows down. + h.run(); + h.get_by_label("script.run").click_secondary(); + h.run(); + h.get_by_label("Open in Script Pane").click(); + h.run(); + assert_eq!(h.state().workflow.script, script); + let state = egui::widgets::text_edit::TextEditState::load(&h.ctx, id).expect("the box's state"); + let at = state.cursor.char_range().expect("a cursor"); + assert_eq!(state.undoer().undo(&(at, script.to_string())).map(|(_, t)| t.as_str()), Some("unrun")); + } + + /// Undo copies as itself (the log keeps its step's label, no parameter); a command that can't + /// run in a script (refused there, or a plugin's) isn't copied as a line; parameters the log cut or took secrets out of say + /// so when copied, and such a script is neither copied nor opened. + #[test] + fn partial_and_unscriptable_entries_are_copied_as_they_can_run() { + use egui_kittest::kittest::NodeT; + let mut app = RustGisApp::with_sample(); + app.session.log.clear(); + let entry = + |command: &str, params: Value, partial| LogEntry { command: command.into(), params, ok: true, partial, ..Default::default() }; + app.session.log.push(entry("edit.undo", json!({"step": "Rename"}), false)); + app.session.log.push(entry("notebook.run", json!({}), false)); + app.session.log.push(entry(&format!("{}eng/f", rustgis_plugins::PREFIX), json!({}), false)); + app.session.log.push(entry("map.new", json!({"name": "S…"}), true)); + app.session.log.push(entry("script.run", json!({"script": "map.new {\"na…"}), true)); + app.ui.session_log.open = true; + let mut h = harness(app); + h.run(); + assert_eq!(pick(&mut h, "edit.undo", "Copy Command"), ["edit.undo"]); + assert_eq!(pick(&mut h, "map.new", "Copy Command"), [r#"map.new {"name":"S…"}"#]); + assert!(h.state().session.notices.iter().any(|n| n.text.contains("may not run as it ran")), "{:?}", h.state().session.notices); + h.get_by_label("notebook.run").click_secondary(); + h.run(); + assert!(h.get_by_label("Copy Command").accesskit_node().is_disabled()); + h.key_press(egui::Key::Escape); + h.run(); + // A plugin's command: a script can't run it either. + h.get_by_label(&format!("{}eng/f", rustgis_plugins::PREFIX)).click_secondary(); + h.run(); + assert!(h.get_by_label("Copy Command").accesskit_node().is_disabled()); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_label("script.run").click_secondary(); + h.run(); + assert!(h.get_by_label("Copy Script").accesskit_node().is_disabled()); + assert!(h.get_by_label("Open in Script Pane").accesskit_node().is_disabled()); + } } diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index aa20d181a6..767857e62b 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -83,15 +83,24 @@ The browser app doesn't autosave yet; it warns before you leave a page with unsa RustGIS keeps a **log** of the commands run in the session: what was done, when, with what, and whether it worked. It is an audit trail of the session, for reviewing work or recalling what was -run; it runs nothing again (History's Copy as code and recorded tasks do that). Every +run; it runs nothing again by itself, but an entry can be copied back as a Script pane line. Every front end goes into it alike: the app, scripts, the AI Assistant, the command line, Python and MCP. In the app, the **History** pane has two views: **Tool runs**, the tools run on the project (saved with it, and each can run again), and **Session log**, which shows the log newest first: each -command with whether it worked, when it started (UTC), how long it took, its error and its -parameters (on one line; all of them on hover, and a right-click copies them). It lists the newest -200 that match and says how many there are; type part of a command's id (`layer.`, `export`) to -filter, or tick **Failed only**. **Save Log As…** writes the whole log as CSV or JSON Lines, as +command with whether it worked, when it started (UTC) and in which project, how long it took, its +error and its parameters (on one line; all of them on hover). It lists the newest 200 that match +and says how many there are; type part of a command's id (`layer.`, `export`) to filter, press +**This project** to list only the commands run in the project open now (two projects of the same +name are told apart), or tick **Failed only**. + +A right-click on an entry offers **Copy Parameters** and **Copy Command**, the entry as a line for +the Script pane (`layer.buffer {"distance": 10}`; undo and redo as themselves). A script run offers +**Copy Script** and **Open in Script Pane** instead, which puts the script in the Script pane in +place of its own (Ctrl+Z, ⌘+Z on a Mac, brings that back; not while the pane runs one). Where the +log cut an entry's parameters short or took secrets out of them, copying its command says so, as +it may not run as it ran, and its script can be neither copied nor opened: it would run only in +part. **Save Log As…** writes the whole log as CSV or JSON Lines, as the name's extension says (CSV without one; in the browser it is downloaded as CSV, and the download isn't itself an entry in the log, as a saved file is). **Clear Log** empties it and **Log Commands** turns it off or on. @@ -105,7 +114,9 @@ download isn't itself an entry in the log, as a saved file is). **Clear Log** em file permission, since it names the files and addresses the user's commands used. - **Each entry:** `at` (when it started, in milliseconds since 1970, UTC; for a plugin's command that waited for its downloads, when its last run started), `command`, `params`, `ok`, `error` - when it failed, and `millis`, how long it took. + when it failed, `millis`, how long it took, `project`, the name of the project open when it ran + (the one it opened, for a command that opens one), and `partial`, true when its parameters were + cut short or had secrets taken out. - **For the session only:** the log is kept in memory, across the projects opened or made in the session, until RustGIS closes or the log is cleared. A saved project, its recovery copy, a package or a template carries none of it, so sharing a project shares no log. Reading, writing @@ -130,7 +141,7 @@ From scripts: `project.log {"since"?, "until"?, "command"?, "failed"?, "limit"?} newest last (`command` is an id, or the start of one ending in a dot, `layer.`; `limit` is a whole number, 100 by default and at most 1,000, with `count` saying how many match), and `project.exportLog {"path": "log.csv"}` writes it out as CSV (one row an entry, the parameters as a -JSON column) or JSON Lines (`.jsonl` or `.ndjson`), as the path's extension says; any other +JSON column, the project last) or JSON Lines (`.jsonl` or `.ndjson`), as the path's extension says; any other extension (a `.json`, a project) is refused, whatever `format` is given. `project.clearLog` empties it (leaving its own entry) and `project.logCommands {"on": false}` stops it (what is there stays). From 078f35fa2b1ec073d382e7adad3d896450eed29e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 7 Nov 2026 22:37:55 -0500 Subject: [PATCH 2/9] fix(engine): keep a logged JSON object as written only when no key repeats; mark a cut project name (#1579) --- crates/engine/src/project_log.rs | 66 ++++++++++++++++++++++++++++++-- crates/engine/src/tests.rs | 15 ++++++++ 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 6aa2b5a43a..71fbfd54ac 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -258,6 +258,56 @@ fn embedded_redacted(v: &Value, depth: usize) -> Value { } } +/// JSON whose every object has each of its keys once, as its text is read: deserializing one with +/// a key written twice (at any depth) fails. +struct OnceEach; + +impl<'de> Deserialize<'de> for OnceEach { + fn deserialize>(d: D) -> Result { + d.deserialize_any(OnceEach) + } +} + +impl<'de> serde::de::Visitor<'de> for OnceEach { + type Value = OnceEach; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("JSON") + } + fn visit_bool(self, _: bool) -> Result { + Ok(self) + } + fn visit_i64(self, _: i64) -> Result { + Ok(self) + } + fn visit_u64(self, _: u64) -> Result { + Ok(self) + } + fn visit_f64(self, _: f64) -> Result { + Ok(self) + } + fn visit_str(self, _: &str) -> Result { + Ok(self) + } + fn visit_unit(self) -> Result { + Ok(self) + } + fn visit_seq>(self, mut items: A) -> Result { + while items.next_element::()?.is_some() {} + Ok(self) + } + fn visit_map>(self, mut keys: A) -> Result { + let mut seen = std::collections::HashSet::new(); + while let Some(key) = keys.next_key::()? { + if !seen.insert(key) { + return Err(serde::de::Error::custom("a key written twice")); + } + keys.next_value::()?; + } + Ok(self) + } +} + /// `t` with each JSON object it holds (from a `{` to where the object ends) redacted. Texts are /// clipped before this, so trying each `{` stays cheap; the secret names are looked for once. pub(crate) fn json_in_text_redacted(t: &str) -> String { @@ -274,11 +324,12 @@ pub(crate) fn json_in_text_redacted(t: &str) -> String { Some(Ok(v @ Value::Object(_))) => { let end = objects.byte_offset(); // Nothing taken out: the object as written, so a script copied back from the log - // is the one run, and isn't said to be partial for its spacing. Not one naming a - // secret: a key written twice is read as its last, and the text keeps the first. + // is the one run, and isn't said to be partial for its spacing. Only one with no + // key written twice: it is read as its last value, and its text keeps the others + // (a secret's first, its last left empty, its name escaped or not). let kept = crate::cmd::history::redacted(&v); let written = from.get(..end).unwrap_or(""); - if kept == v && last_secret_name(written).is_none() { + if kept == v && serde_json::from_str::(written).is_ok() { out.push_str(written); } else { out.push_str(&serde_json::to_string(&kept).unwrap_or_default()); @@ -450,12 +501,19 @@ pub(crate) fn entry(s: &Session, id: &str, params: Value, partial: bool, res: &C ok: res.is_ok(), error, millis: u64::try_from(took.as_millis()).unwrap_or(u64::MAX), - project: s.title().chars().take(200).collect(), + project: kept_name(&s.title()), opened: s.opened, partial, } } +/// A project's name as the log keeps it: cut at [`crate::cmd::MAX_NAME`] characters and a `…`, as +/// a name read from a file may be longer than one given to `project.rename`. +fn kept_name(name: &str) -> String { + let max = crate::cmd::MAX_NAME; + if name.chars().nth(max).is_some() { format!("{}…", name.chars().take(max).collect::()) } else { name.to_string() } +} + /// `params` as the log keeps them ([`kept_params`]), and whether that is less than they were: /// cut to fit or with secrets taken out, so they wouldn't run again as they ran. pub(crate) fn kept(params: &Value) -> (Value, bool) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c65bb6deed..572bf8ea82 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28938,6 +28938,21 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( s.run("script.run", &json!({"script": "map.new {\"name\": \"M\", \"secretAccessKey\": \"S3CRET\", \"secretAccessKey\": \"\"}"})); let twice = last(&s); assert!(!twice.params.to_string().contains("S3CRET") && twice.partial, "{twice:?}"); + // Nor with its name escaped, nor a key a plain name blanks only for its value, nor deeper in. + for script in [ + r#"map.new {"name": "M", "\u0074oken": "S3CRET", "\u0074oken": ""}"#, + r#"map.new {"name": "M", "key": "AKIAIOSFODNN7S3CRET", "key": ""}"#, + r#"map.new {"name": "M", "style": {"token": "S3CRET", "token": ""}}"#, + ] { + let _ = s.run("script.run", &json!({"script": script})); + let e = last(&s); + assert!(!e.params.to_string().contains("S3CRET") && e.partial, "{script}: {e:?}"); + } + // A name past the bound is cut, and says so. + s.project.name = "n".repeat(crate::cmd::MAX_NAME + 5); + s.run("map.new", &json!({"name": "Long"})).unwrap(); + assert_eq!(last(&s).project, format!("{}…", "n".repeat(crate::cmd::MAX_NAME))); + s.project.name = "Atlas".into(); // A script past the log's bound is cut: partial, so it isn't run again as a part. let long = format!("# {}", "x".repeat(crate::project_log::LOG_PARAMS_BYTES * 2)); s.run("script.run", &json!({"script": long})).unwrap(); From 4025ce4211eda45eebce3ad34dab9ed5021c658a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 7 Nov 2026 23:08:53 -0500 Subject: [PATCH 3/9] fix(ui): copying a partial entry's parameters says so too; each redaction case checks its own entry (#1579) --- crates/engine/src/tests.rs | 2 ++ crates/ui-egui/src/sessionlog.rs | 11 +++++++++-- docs/user-guide/workspace.md | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 572bf8ea82..44eccb5c8a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28944,8 +28944,10 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( r#"map.new {"name": "M", "key": "AKIAIOSFODNN7S3CRET", "key": ""}"#, r#"map.new {"name": "M", "style": {"token": "S3CRET", "token": ""}}"#, ] { + let before = s.log.len(); let _ = s.run("script.run", &json!({"script": script})); let e = last(&s); + assert_eq!((s.log.len(), e.command.as_str()), (before + 1, "script.run"), "{script}: its own entry"); assert!(!e.params.to_string().contains("S3CRET") && e.partial, "{script}: {e:?}"); } // A name past the bound is cut, and says so. diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 18207ab241..abe6022126 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -201,7 +201,7 @@ fn script_of(e: &LogEntry) -> Option<&str> { enum Picked { /// Open in Script Pane, with this script. Open(String), - /// Copy Command, of parameters the log cut short or took secrets out of: said. + /// Copy Command or Copy Parameters, of parameters the log cut short or took secrets out of: said. CopiedPartial, } @@ -246,6 +246,7 @@ fn row(ui: &mut Ui, item: &Row, t: &Tokens, running: bool) -> Option { r.response.context_menu(|ui| { if ui.add_enabled(!params.is_empty(), egui::Button::new(tl!("Copy Parameters"))).clicked() { ui.ctx().copy_text(params.to_string()); + picked = e.partial.then_some(Picked::CopiedPartial); ui.close(); } if let Some(script) = script_of(e) { @@ -680,7 +681,13 @@ mod tests { h.run(); assert_eq!(pick(&mut h, "edit.undo", "Copy Command"), ["edit.undo"]); assert_eq!(pick(&mut h, "map.new", "Copy Command"), [r#"map.new {"name":"S…"}"#]); - assert!(h.state().session.notices.iter().any(|n| n.text.contains("may not run as it ran")), "{:?}", h.state().session.notices); + let said = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.state().session.notices.iter().filter(|n| n.text.contains("may not run as it ran")).count() + }; + assert_eq!(said(&h), 1, "{:?}", h.state().session.notices); + // Its parameters alone, copied, say it too. + assert_eq!(pick(&mut h, "map.new", "Copy Parameters"), [r#"{"name":"S…"}"#]); + assert_eq!(said(&h), 2, "{:?}", h.state().session.notices); h.get_by_label("notebook.run").click_secondary(); h.run(); assert!(h.get_by_label("Copy Command").accesskit_node().is_disabled()); diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 767857e62b..90b652324a 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -98,8 +98,8 @@ A right-click on an entry offers **Copy Parameters** and **Copy Command**, the e the Script pane (`layer.buffer {"distance": 10}`; undo and redo as themselves). A script run offers **Copy Script** and **Open in Script Pane** instead, which puts the script in the Script pane in place of its own (Ctrl+Z, ⌘+Z on a Mac, brings that back; not while the pane runs one). Where the -log cut an entry's parameters short or took secrets out of them, copying its command says so, as -it may not run as it ran, and its script can be neither copied nor opened: it would run only in +log cut an entry's parameters short or took secrets out of them, copying its command or its +parameters says so, as it may not run as it ran, and its script can be neither copied nor opened: it would run only in part. **Save Log As…** writes the whole log as CSV or JSON Lines, as the name's extension says (CSV without one; in the browser it is downloaded as CSV, and the download isn't itself an entry in the log, as a saved file is). **Clear Log** empties it and From bd1985e3c9de51d31fe5b32c0db6ca76dd5cead4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 7 Nov 2026 23:19:29 -0500 Subject: [PATCH 4/9] docs(ui): rename the Session log's filter check and rewrap its comments and guide (#1579) --- crates/ui-egui/src/sessionlog.rs | 12 +++++++----- docs/user-guide/workspace.md | 15 ++++++++------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index abe6022126..050a46f79b 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -86,7 +86,7 @@ pub fn tabs(app: &mut RustGisApp, ui: &mut Ui) -> bool { /// Whether entry `e` is one the filters keep: `query` already in lower case; `project`, the /// project its entries are the only ones kept ([`rustgis_engine::Session::opened`]). -fn kept(e: &LogEntry, query: &str, failed: bool, project: Option) -> bool { +fn listed(e: &LogEntry, query: &str, failed: bool, project: Option) -> bool { (!failed || !e.ok) && (query.is_empty() || e.command.to_lowercase().contains(query)) && project.is_none_or(|p| e.opened == p) } @@ -109,7 +109,7 @@ pub fn pane(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let same = cache.as_ref().is_some_and(|(k, ..)| k.0 == log.changes() && k.1 == raw && k.2 == *failed && k.3 == project); if !same { let lower = raw.to_lowercase(); - let (shown, count, total) = log.select(|e| kept(e, &lower, *failed, project), SHOWN); + let (shown, count, total) = log.select(|e| listed(e, &lower, *failed, project), SHOWN); let rows = shown.into_iter().map(|e| Row::of(e, registry)).collect(); *cache = Some(((log.changes(), raw.to_string(), *failed, project), rows, count, total)); } @@ -201,7 +201,8 @@ fn script_of(e: &LogEntry) -> Option<&str> { enum Picked { /// Open in Script Pane, with this script. Open(String), - /// Copy Command or Copy Parameters, of parameters the log cut short or took secrets out of: said. + /// Copy Command or Copy Parameters, of parameters the log cut short or took secrets out of: + /// said. CopiedPartial, } @@ -662,8 +663,9 @@ mod tests { } /// Undo copies as itself (the log keeps its step's label, no parameter); a command that can't - /// run in a script (refused there, or a plugin's) isn't copied as a line; parameters the log cut or took secrets out of say - /// so when copied, and such a script is neither copied nor opened. + /// run in a script (refused there, or a plugin's) isn't copied as a line; parameters the log + /// cut or took secrets out of say so when copied, and such a script is neither copied nor + /// opened. #[test] fn partial_and_unscriptable_entries_are_copied_as_they_can_run() { use egui_kittest::kittest::NodeT; diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 90b652324a..3974c6b206 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -99,10 +99,10 @@ the Script pane (`layer.buffer {"distance": 10}`; undo and redo as themselves). **Copy Script** and **Open in Script Pane** instead, which puts the script in the Script pane in place of its own (Ctrl+Z, ⌘+Z on a Mac, brings that back; not while the pane runs one). Where the log cut an entry's parameters short or took secrets out of them, copying its command or its -parameters says so, as it may not run as it ran, and its script can be neither copied nor opened: it would run only in -part. **Save Log As…** writes the whole log as CSV or JSON Lines, as -the name's extension says (CSV without one; in the browser it is downloaded as CSV, and the -download isn't itself an entry in the log, as a saved file is). **Clear Log** empties it and +parameters says so, as it may not run as it ran, and its script can be neither copied nor opened: +it would run only in part. **Save Log As…** writes the whole log as CSV or JSON Lines, as the +name's extension says (CSV without one; in the browser it is downloaded as CSV, and the download +isn't itself an entry in the log, as a saved file is). **Clear Log** empties it and **Log Commands** turns it off or on. - **What goes in:** each command that changes the project, and each that names a file, folder, @@ -141,9 +141,10 @@ From scripts: `project.log {"since"?, "until"?, "command"?, "failed"?, "limit"?} newest last (`command` is an id, or the start of one ending in a dot, `layer.`; `limit` is a whole number, 100 by default and at most 1,000, with `count` saying how many match), and `project.exportLog {"path": "log.csv"}` writes it out as CSV (one row an entry, the parameters as a -JSON column, the project last) or JSON Lines (`.jsonl` or `.ndjson`), as the path's extension says; any other -extension (a `.json`, a project) is refused, whatever `format` is given. `project.clearLog` empties -it (leaving its own entry) and `project.logCommands {"on": false}` stops it (what is there stays). +JSON column, the project last) or JSON Lines (`.jsonl` or `.ndjson`), as the path's extension says; +any other extension (a `.json`, a project) is refused, whatever `format` is given. +`project.clearLog` empties it (leaving its own entry) and `project.logCommands {"on": false}` stops +it (what is there stays). ### GeoLibre projects From a3e6825e713c076ad3e2c844dfd176a47a800f92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 7 Nov 2026 23:45:48 -0500 Subject: [PATCH 5/9] test: check the address case's own entry and This project with two projects of one name (#1579) --- crates/engine/src/tests.rs | 4 +++- crates/ui-egui/src/sessionlog.rs | 16 +++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 44eccb5c8a..cb3a0643b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28961,7 +28961,9 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( assert!(last(&s).partial); // An address without its token: partial too. let _ = s.run("service.layers", &json!({"url": "https://x.org/wms?token=S3CRET&layers=a", "text": "not a capabilities document"})); - assert!(last(&s).partial, "{:?}", last(&s)); + let service = last(&s); + assert_eq!(service.command, "service.layers", "{service:?}"); + assert!(!service.params.to_string().contains("S3CRET") && service.partial, "{service:?}"); // Saved: the project's name last in a CSV row; in JSON, the name, and `partial` only when so. let mut csv = Vec::new(); s.log.write(&mut csv, true).unwrap(); diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 050a46f79b..2c2eba6626 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -84,8 +84,8 @@ pub fn tabs(app: &mut RustGisApp, ui: &mut Ui) -> bool { app.ui.session_log.open } -/// Whether entry `e` is one the filters keep: `query` already in lower case; `project`, the -/// project its entries are the only ones kept ([`rustgis_engine::Session::opened`]). +/// Whether entry `e` is one the filters keep: `query` already in lower case; `project`, when +/// only one project's entries are listed, that project ([`rustgis_engine::Session::opened`]). fn listed(e: &LogEntry, query: &str, failed: bool, project: Option) -> bool { (!failed || !e.ok) && (query.is_empty() || e.command.to_lowercase().contains(query)) && project.is_none_or(|p| e.opened == p) } @@ -582,23 +582,25 @@ mod tests { assert!(h.query_by_label("Copy Command").is_some()); } - /// Each row says the project it ran in; This project lists only the project open now's. + /// Each row says the project it ran in; This project lists only the project open now's, not + /// another of the same name. #[test] fn each_entry_names_its_project_and_this_project_lists_the_open_ones() { let mut app = RustGisApp::with_sample(); app.session.log.clear(); + app.run("project.rename", json!({"name": "Same"})).unwrap(); app.run("map.new", json!({"name": "Before"})).unwrap(); - app.run("project.new", json!({"name": "Second project"})).unwrap(); + app.run("project.new", json!({"name": "Same"})).unwrap(); app.run("map.new", json!({"name": "After"})).unwrap(); app.ui.session_log.open = true; let mut h = harness(app); h.run(); - assert!(h.query_by_label("3 entries").is_some()); - assert_eq!(h.query_all_by_label_contains("UTC · Second project").count(), 2, "the open and what came after"); + assert!(h.query_by_label("4 entries").is_some()); + assert_eq!(h.query_all_by_label_contains("UTC · Same").count(), 4, "both projects, by one name"); h.get_by_label("This project").click(); h.run(); assert!(h.state().ui.session_log.this_project); - assert!(h.query_by_label("2 of 3 entries").is_some()); + assert!(h.query_by_label("2 of 4 entries").is_some(), "the open and what came after, not the other Same"); assert!(h.query_by_label(r#"{"name":"Before"}"#).is_none() && h.query_by_label(r#"{"name":"After"}"#).is_some()); } From 12944d8b6a98a7c3623c34d87ec4f8f2c6b1efe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 8 Nov 2026 05:19:04 -0500 Subject: [PATCH 6/9] refactor(engine): name the log's checks UniqueKeys and kept_and_partial; test partial in project.log and This project across a switch (#1579) --- crates/engine/src/cmd/exports.rs | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/project_log.rs | 22 +++++++++++----------- crates/engine/src/tests.rs | 3 +++ crates/ui-egui/src/sessionlog.rs | 7 +++++++ 5 files changed, 23 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 0889076270..7a2810a60f 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -268,7 +268,7 @@ pub fn export_land(s: &mut Session, started: Started, done: Result (serde_json::json!({"step": label}), false), - None => project_log::kept(params), + None => project_log::kept_and_partial(params), }; let e = project_log::entry(self, id, params, partial, &res, at, start.elapsed()); if joins && res.is_ok() { self.log.join_last(e) } else { self.log.push(e) } diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 71fbfd54ac..2550fe01f8 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -260,16 +260,16 @@ fn embedded_redacted(v: &Value, depth: usize) -> Value { /// JSON whose every object has each of its keys once, as its text is read: deserializing one with /// a key written twice (at any depth) fails. -struct OnceEach; +struct UniqueKeys; -impl<'de> Deserialize<'de> for OnceEach { +impl<'de> Deserialize<'de> for UniqueKeys { fn deserialize>(d: D) -> Result { - d.deserialize_any(OnceEach) + d.deserialize_any(UniqueKeys) } } -impl<'de> serde::de::Visitor<'de> for OnceEach { - type Value = OnceEach; +impl<'de> serde::de::Visitor<'de> for UniqueKeys { + type Value = UniqueKeys; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("JSON") @@ -293,7 +293,7 @@ impl<'de> serde::de::Visitor<'de> for OnceEach { Ok(self) } fn visit_seq>(self, mut items: A) -> Result { - while items.next_element::()?.is_some() {} + while items.next_element::()?.is_some() {} Ok(self) } fn visit_map>(self, mut keys: A) -> Result { @@ -302,7 +302,7 @@ impl<'de> serde::de::Visitor<'de> for OnceEach { if !seen.insert(key) { return Err(serde::de::Error::custom("a key written twice")); } - keys.next_value::()?; + keys.next_value::()?; } Ok(self) } @@ -329,7 +329,7 @@ pub(crate) fn json_in_text_redacted(t: &str) -> String { // (a secret's first, its last left empty, its name escaped or not). let kept = crate::cmd::history::redacted(&v); let written = from.get(..end).unwrap_or(""); - if kept == v && serde_json::from_str::(written).is_ok() { + if kept == v && serde_json::from_str::(written).is_ok() { out.push_str(written); } else { out.push_str(&serde_json::to_string(&kept).unwrap_or_default()); @@ -490,8 +490,8 @@ fn clip(v: &Value, chars: usize, items: usize, depth: usize) -> Value { /// The entry of command `id`, which started at `at` and took `took`; its error without secrets, /// clipped to [`LOG_ERROR_CHARS`]. -/// `partial`: its parameters aren't all as given ([`kept`]). It is the entry of the project open -/// in `s` as it ended: the one a command that opens a project opened. +/// `partial`: its parameters aren't all as given ([`kept_and_partial`]). It is the entry of the +/// project open in `s` as it ended: the one a command that opens a project opened. pub(crate) fn entry(s: &Session, id: &str, params: Value, partial: bool, res: &CmdResult, at: u64, took: web_time::Duration) -> LogEntry { let error = res.as_ref().err().map(|e| kept_error(e)); LogEntry { @@ -516,7 +516,7 @@ fn kept_name(name: &str) -> String { /// `params` as the log keeps them ([`kept_params`]), and whether that is less than they were: /// cut to fit or with secrets taken out, so they wouldn't run again as they ran. -pub(crate) fn kept(params: &Value) -> (Value, bool) { +pub(crate) fn kept_and_partial(params: &Value) -> (Value, bool) { let kept = kept_params(params); let partial = kept != *params; (kept, partial) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cb3a0643b8..dc0ebaf76d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28964,6 +28964,9 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( let service = last(&s); assert_eq!(service.command, "service.layers", "{service:?}"); assert!(!service.params.to_string().contains("S3CRET") && service.partial, "{service:?}"); + // And `project.log` says so: `partial` is in its answer. + let answer = s.run("project.log", &json!({"command": "service.layers", "limit": 1})).unwrap(); + assert_eq!(answer["entries"][0]["partial"], json!(true), "{answer}"); // Saved: the project's name last in a CSV row; in JSON, the name, and `partial` only when so. let mut csv = Vec::new(); s.log.write(&mut csv, true).unwrap(); diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 2c2eba6626..7fd54337a7 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -602,6 +602,13 @@ mod tests { assert!(h.state().ui.session_log.this_project); assert!(h.query_by_label("2 of 4 entries").is_some(), "the open and what came after, not the other Same"); assert!(h.query_by_label(r#"{"name":"Before"}"#).is_none() && h.query_by_label(r#"{"name":"After"}"#).is_some()); + // Another project opened with logging off (the log unchanged): the list follows it. + h.state_mut().run("project.logCommands", json!({"on": false})).unwrap(); + h.run(); + assert!(h.query_by_label("3 of 5 entries").is_some(), "the switch's own entry"); + h.state_mut().run("project.new", json!({"name": "Third"})).unwrap(); + h.run(); + assert!(h.query_by_label("No command matches").is_some()); } /// Right-clicks row `row` and picks `item` in its menu: the text it put on the clipboard. From 1ec3e204fafb451956d88dc914c2a1b094f01f81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 8 Nov 2026 05:47:29 -0500 Subject: [PATCH 7/9] fix(engine): log a background export under the project it started in (#1579) --- crates/engine/src/cmd/exports.rs | 12 +++++++++--- crates/engine/src/project_log.rs | 2 +- crates/engine/src/tests.rs | 9 +++++++++ docs/user-guide/workspace.md | 2 +- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 7a2810a60f..a3567b3a22 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -190,6 +190,9 @@ pub struct Started { pub(crate) start: web_time::Instant, /// The admitted invocation; cloned metadata never selects replacement authority. pub(crate) owner: crate::policy::Continuation, + /// The project it started in, its name as the log keeps it and its `Session::opened`: the + /// log's entry names that one, not one opened while it ran. + pub(crate) project: (String, u64), } #[cfg(not(target_arch = "wasm32"))] @@ -235,7 +238,8 @@ pub(crate) fn export_start_raw(s: &mut Session, op: crate::policy::Authorized) -> CmdResult { - let Started { command, params, at, start, owner } = started; + let Started { command, params, at, start, owner, project } = started; let before = s.diagnostic_source.replace(command); let mark = s.notice_mark(); let landed: CmdResult = (|| { @@ -269,7 +273,9 @@ pub fn export_land(s: &mut Session, started: Started, done: Result String { +pub(crate) fn kept_name(name: &str) -> String { let max = crate::cmd::MAX_NAME; if name.chars().nth(max).is_some() { format!("{}…", name.chars().take(max).collect::()) } else { name.to_string() } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 44525e673e..cbc02e2419 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -32112,6 +32112,15 @@ fn exports_run_on_another_thread() { let missing: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("in the file")).map(|n| n.text.clone()).collect(); assert!(missing.len() == 1 && missing[0].contains("2 layers aren't in the file"), "{missing:?}"); s.map_mut().layers[li].source = None; + // One that lands after another project opened is logged under the project it started in. + let (name, opened) = (s.project.name.clone(), s.opened); + let run = export_start(&mut s, "share.exportMap", &json!({"path": at("before_new.png"), "width": 64, "height": 48})).unwrap(); + let started = run.started(); + let wrote = run.run(&Control::new()); + s.run("project.new", &json!({"name": "Opened meanwhile"})).unwrap(); + let _ = export_land(&mut s, started, wrote); + let e = s.log.entries().last().cloned().unwrap(); + assert_eq!((e.command.as_str(), e.project.as_str(), e.opened), ("share.exportMap", name.as_str(), opened), "{e:?}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index e319263e37..ee728be2e1 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -97,7 +97,7 @@ and says how many there are; type part of a command's id (`layer.`, `export`) to name are told apart), or tick **Failed only**. A right-click on an entry offers **Copy Parameters** and **Copy Command**, the entry as a line for -the Script pane (`layer.buffer {"distance": 10}`; undo and redo as themselves). A script run offers +the Script pane (`layer.buffer {"distance":10}`; undo and redo as themselves). A script run offers **Copy Script** and **Open in Script Pane** instead, which puts the script in the Script pane in place of its own (Ctrl+Z, ⌘+Z on a Mac, brings that back; not while the pane runs one). Where the log cut an entry's parameters short or took secrets out of them, copying its command or its From 276c574ed0f74cfd4d742e611572c1aef535daed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 8 Nov 2026 09:55:45 -0500 Subject: [PATCH 8/9] fix(engine): blank log-only keys in a script's JSON; entry takes its project (#1579) A JSON object inside a logged text now goes through the log's own redaction, so a key only logs leave out (passphrase, username) isn't kept as written, and the entry is partial. project_log::entry takes the project instead of reading the Session, so an export passes the one it started in. Renames the Session log pane's local count to on_screen. --- crates/engine/src/cmd/exports.rs | 4 +--- crates/engine/src/lib.rs | 3 ++- crates/engine/src/project_log.rs | 21 ++++++++++++++++----- crates/engine/src/tests.rs | 7 +++++-- crates/ui-egui/src/sessionlog.rs | 6 +++--- 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index a3567b3a22..89d2555314 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -273,10 +273,8 @@ pub fn export_land(s: &mut Session, started: Started, done: Result (serde_json::json!({"step": label}), false), None => project_log::kept_and_partial(params), }; - let e = project_log::entry(self, id, params, partial, &res, at, start.elapsed()); + let project = (project_log::kept_name(&self.title()), self.opened); + let e = project_log::entry(project, id, params, partial, &res, at, start.elapsed()); if joins && res.is_ok() { self.log.join_last(e) } else { self.log.push(e) } } })); diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index ded9016e00..c3ced5f3e3 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -327,7 +327,8 @@ pub(crate) fn json_in_text_redacted(t: &str) -> String { // is the one run, and isn't said to be partial for its spacing. Only one with no // key written twice: it is read as its last value, and its text keeps the others // (a secret's first, its last left empty, its name escaped or not). - let kept = crate::cmd::history::redacted(&v); + // The log's own rule, as for its parameters: a key only logs leave out too. + let kept = redacted(&v); let written = from.get(..end).unwrap_or(""); if kept == v && serde_json::from_str::(written).is_ok() { out.push_str(written); @@ -491,8 +492,18 @@ fn clip(v: &Value, chars: usize, items: usize, depth: usize) -> Value { /// The entry of command `id`, which started at `at` and took `took`; its error without secrets, /// clipped to [`LOG_ERROR_CHARS`]. /// `partial`: its parameters aren't all as given ([`kept_and_partial`]). It is the entry of the -/// project open in `s` as it ended: the one a command that opens a project opened. -pub(crate) fn entry(s: &Session, id: &str, params: Value, partial: bool, res: &CmdResult, at: u64, took: web_time::Duration) -> LogEntry { +/// project given, its name as the log keeps it ([`kept_name`]) and its `Session::opened`: the one +/// open as the command ended (the one it opened, for one that opens a project), or for an export, +/// the one it started in. +pub(crate) fn entry( + project: (String, u64), + id: &str, + params: Value, + partial: bool, + res: &CmdResult, + at: u64, + took: web_time::Duration, +) -> LogEntry { let error = res.as_ref().err().map(|e| kept_error(e)); LogEntry { at, @@ -501,8 +512,8 @@ pub(crate) fn entry(s: &Session, id: &str, params: Value, partial: bool, res: &C ok: res.is_ok(), error, millis: u64::try_from(took.as_millis()).unwrap_or(u64::MAX), - project: kept_name(&s.title()), - opened: s.opened, + project: project.0, + opened: project.1, partial, } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cbc02e2419..b66d3b9a57 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -29276,8 +29276,10 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( s.run("script.run", &json!({"script": "map.new {\"name\": \"M\", \"secretAccessKey\": \"S3CRET\", \"secretAccessKey\": \"\"}"})); let twice = last(&s); assert!(!twice.params.to_string().contains("S3CRET") && twice.partial, "{twice:?}"); - // Nor with its name escaped, nor a key a plain name blanks only for its value, nor deeper in. + // Nor with its name escaped, nor a key a plain name blanks only for its value, nor deeper in; + // and a key only logs leave out (`passphrase`) isn't kept either. for script in [ + r#"map.new {"name": "M", "passphrase": "S3CRET"}"#, r#"map.new {"name": "M", "\u0074oken": "S3CRET", "\u0074oken": ""}"#, r#"map.new {"name": "M", "key": "AKIAIOSFODNN7S3CRET", "key": ""}"#, r#"map.new {"name": "M", "style": {"token": "S3CRET", "token": ""}}"#, @@ -32112,7 +32114,8 @@ fn exports_run_on_another_thread() { let missing: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("in the file")).map(|n| n.text.clone()).collect(); assert!(missing.len() == 1 && missing[0].contains("2 layers aren't in the file"), "{missing:?}"); s.map_mut().layers[li].source = None; - // One that lands after another project opened is logged under the project it started in. + // One that lands (or is refused) after another project opened is logged under the project it + // started in. let (name, opened) = (s.project.name.clone(), s.opened); let run = export_start(&mut s, "share.exportMap", &json!({"path": at("before_new.png"), "width": 64, "height": 48})).unwrap(); let started = run.started(); diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 7fd54337a7..e1da7c333e 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -113,13 +113,13 @@ pub fn pane(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let rows = shown.into_iter().map(|e| Row::of(e, registry)).collect(); *cache = Some(((log.changes(), raw.to_string(), *failed, project), rows, count, total)); } - let (count, total, listed) = cache.as_ref().map_or((0, 0, 0), |(_, rows, matched, all)| (*matched, *all, rows.len())); + let (count, total, on_screen) = cache.as_ref().map_or((0, 0, 0), |(_, rows, matched, all)| (*matched, *all, rows.len())); let note = if total == 0 { tl!("Commands that change the project, or that name a file, folder or address, appear here.").to_string() } else if count == 0 { tl!("No command matches").to_string() - } else if count > listed { - crate::i18n::fmt("The newest {shown} of {count} entries", &[("shown", &listed.to_string()), ("count", &count.to_string())]) + } else if count > on_screen { + crate::i18n::fmt("The newest {shown} of {count} entries", &[("shown", &on_screen.to_string()), ("count", &count.to_string())]) } else if count < total { crate::i18n::fmt("{count} of {total} entries", &[("count", &count.to_string()), ("total", &total.to_string())]) } else if count == 1 { From 1929250a9d593a430ee92689d5c1fd8963636a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 8 Nov 2026 12:58:56 -0500 Subject: [PATCH 9/9] fix(engine): leave out a logged script's JSON past eight levels (#1579) JSON read from a logged text wasn't clipped, so what lay past the redaction's eight levels was kept as written, a passphrase too. It is now left out as clip does, and the entry is partial. open_script does nothing while a script runs, not only its button. Rewords the comment on keeping an object as written. --- crates/engine/src/project_log.rs | 16 ++++++++++------ crates/engine/src/tests.rs | 3 ++- crates/ui-egui/src/analysispane.rs | 6 +++++- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index c3ced5f3e3..fc91d8f0bf 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -247,13 +247,16 @@ fn embedded_redacted(v: &Value, depth: usize) -> Value { o.iter() .map(|(k, x)| { // Preserve History's plain-key refinement; the log-only fields share diagnostics' - // canonical list. Clipping already bounds recursion and text before this pass. + // canonical list. let sensitive = rustgis_data::address::normalized_name(k).as_deref() != Some("key") && rustgis_data::address::log_sensitive(k); (k.clone(), if sensitive { Value::String(String::new()) } else { embedded_redacted(x, depth + 1) }) }) .collect(), ), + // Past eight levels, left out, as `clip` does: JSON read from a text wasn't clipped, and + // what is that deep isn't looked at. + Value::Array(_) | Value::Object(_) => Value::String("…".into()), other => other.clone(), } } @@ -323,11 +326,12 @@ pub(crate) fn json_in_text_redacted(t: &str) -> String { match objects.next() { Some(Ok(v @ Value::Object(_))) => { let end = objects.byte_offset(); - // Nothing taken out: the object as written, so a script copied back from the log - // is the one run, and isn't said to be partial for its spacing. Only one with no - // key written twice: it is read as its last value, and its text keeps the others - // (a secret's first, its last left empty, its name escaped or not). - // The log's own rule, as for its parameters: a key only logs leave out too. + // Redacted by the log's own rule, as its parameters are. When that takes nothing + // out, the object is kept as written: a script copied back from the log is the + // one that ran, and its spacing doesn't make it partial. Not when a key is written + // twice, though: the value read is the last one, but the text still holds the + // first (a secret, perhaps, under an escaped name), so that object is written + // out again from what was read. let kept = redacted(&v); let written = from.get(..end).unwrap_or(""); if kept == v && serde_json::from_str::(written).is_ok() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dbd6bfcc58..287fa5b0a3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -29504,9 +29504,10 @@ fn session_log_entries_name_their_project_and_say_when_their_params_are_partial( let twice = last(&s); assert!(!twice.params.to_string().contains("S3CRET") && twice.partial, "{twice:?}"); // Nor with its name escaped, nor a key a plain name blanks only for its value, nor deeper in; - // and a key only logs leave out (`passphrase`) isn't kept either. + // and a key only logs leave out (`passphrase`) isn't kept either, nor one past eight levels. for script in [ r#"map.new {"name": "M", "passphrase": "S3CRET"}"#, + r#"map.new {"name": "M", "a": [[[[[[[[[{"passphrase": "S3CRET"}]]]]]]]]]}"#, r#"map.new {"name": "M", "\u0074oken": "S3CRET", "\u0074oken": ""}"#, r#"map.new {"name": "M", "key": "AKIAIOSFODNN7S3CRET", "key": ""}"#, r#"map.new {"name": "M", "style": {"token": "S3CRET", "token": ""}}"#, diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index b098b27fb0..0d3add75d3 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1603,8 +1603,12 @@ pub(crate) fn script_running(app: &RustGisApp) -> bool { /// Opens `script` in the Script pane (the session log's Open in Script Pane), in place of the /// pane's script and results, as Clear empties them: the script that was there comes back with /// Ctrl+Z, even one left from a project since replaced (kept first, then the pane started over, -/// so that doesn't empty it when it next shows). +/// so that doesn't empty it when it next shows). Nothing while a run is under way +/// ([`script_running`]). pub(crate) fn open_script(app: &mut RustGisApp, ctx: &egui::Context, script: String) { + if script_running(app) { + return; + } let box_id = egui::Id::unique("script_text"); keep_for_undo(app, ctx, box_id); start_over_in_another_project(app);