diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0717ef9ad8..490878c61c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,7 +106,7 @@ jobs: if grep -q 'data-cargo-profile=' apps/rustgis-web/index.html; then echo "::error::apps/rustgis-web/index.html still names a Cargo profile" >&2; exit 1; fi (cd apps/rustgis-web && "$RUNNER_TEMP/bin/trunk" build --locked --cargo-profile dev) cargo xtask web-pwa dist/web - node apps/rustgis-web/smoke/run.mjs --dist dist/web --chrome "$(command -v google-chrome)" + node apps/rustgis-web/smoke/run.mjs --dist dist/web --chrome google-chrome # The iOS app (apps/rustgis-mobile, #1902): linted for devices and built for the Simulator, # where macOS is tested (pushes to main, a manual run on every platform, a pull request labelled diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index a32d71a83e..dfb971a43f 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -1426,10 +1426,10 @@ mod tests { } #[test] - fn every_option_read_with_opt_is_checked_by_check_values() { + fn every_option_read_with_opt_num_or_side_is_checked_by_check_values() { let source = include_str!("main.rs"); let mut missing = Vec::new(); - for call in ["opt(&args, \"", "opt(args, \""] { + for call in ["opt(&args, \"", "opt(args, \"", "num(&args, \"", "num(args, \"", "side(&mut s, &args, \""] { for part in source.split(call).skip(1) { let flag = format!("--{}", part.trim_start_matches('-').split('"').next().unwrap_or("")); if !VALUE_FLAGS.contains(&flag.as_str()) { @@ -1437,7 +1437,7 @@ mod tests { } } } - assert!(missing.is_empty(), "read with opt but not in VALUE_FLAGS: {missing:?}"); + assert!(missing.is_empty(), "read with opt, num or side but not in VALUE_FLAGS: {missing:?}"); } /// An environment with no keys. diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index 007cb7ab19..0eb92657c8 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -705,7 +705,8 @@ public void copyText(final String text) { } } catch (RuntimeException e) { // Too large for Android to pass on, say: the Rust side's own clipboard still has it. - add("copy-failed\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())); + String why = e.getMessage(); + add("copy-failed\t" + oneField(why == null || why.isEmpty() ? e.getClass().getSimpleName() : why)); } finally { answered(); } diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java index 047eb2b1bf..27b0c1882e 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -98,7 +98,13 @@ static synchronized String delete(android.content.Context context, String accoun if (version(before) > VERSION) { return NEWER; } - return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN; + // A save cut short between writing the part and renaming it leaves the part, which + // holds the secret too: it goes with the entry. + java.io.File folder = file.getParentFile(); + java.io.File part = folder == null ? null : new java.io.File(folder, file.getName() + ".part"); + boolean partGone = part == null || part.delete() || !part.exists(); + boolean entryGone = before == null || file.delete() || !file.exists(); + return partGone && entryGone ? "ok" : UNWRITTEN; } catch (java.io.IOException | RuntimeException e) { return "failed\terror\t" + reason(e); } diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index b165cc8af6..4c140176c7 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -1133,6 +1133,54 @@ mod tests { assert_eq!(window.poll, Some(5000)); } + /// The window around `app`, reading its events from `phone`. + fn window_on(app: RustGisApp, phone: Rc) -> App { + App { + app, + pushed: Vec::new(), + poll: None, + locating: false, + keeping: false, + keyboard: None, + typing: None, + back: false, + bars_light: None, + phone: Some(phone), + inbox: Inbox::default(), + refusals: Refusals::default(), + asked: Asked::default(), + kept: Rc::default(), + refused_picker: Rc::default(), + waiting: Vec::new(), + problems: Problems::default(), + reading: Arc::default(), + } + } + + /// A text box the system couldn't open is said once, with its reason; one that closed after + /// opening says nothing. + #[test] + fn a_text_box_that_could_not_open_is_said() { + use rustgis_engine::platform::Typed; + let _held = settings_notices_held(); + let typed = |failed: Option<&str>| Event::Typed(Typed::Closed { id: "note".into(), failed: failed.map(str::to_string) }); + for (failed, expected) in [(Some("no keyboard service"), 1), (None, 0)] { + let app = RustGisApp::with_sample(); + let mark = app.session.notice_mark(); + let phone = Rc::new(FakePhone::default()); + phone.1.borrow_mut().push(typed(failed)); + let mut window = window_on(app, phone); + window.take_phone_events(&egui::Context::default(), &mut egui::RawInput::default()); + let said: Vec<_> = + window.app.session.notices_since(mark).iter().filter(|n| n.text.contains("text box")).map(|n| n.text.clone()).collect(); + assert_eq!(said.len(), expected, "{failed:?}: {said:?}"); + if let Some(why) = failed { + assert!(said[0].contains(why), "{said:?}"); + } + assert_eq!(window.app.typed.len(), 1, "the form still gets the close"); + } + } + /// A copy the phone couldn't be asked to take is said once; one it took says nothing. #[test] fn a_copy_that_cannot_reach_the_clipboard_is_said() { diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index ed8b4e7545..17524ec978 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -53,7 +53,8 @@ class DataLossWarning(UserWarning): Raised through :mod:`warnings` for each notice that carries a loss code, so ``warnings.filterwarnings("error", category=rustgis.DataLossWarning)`` turns a loss into - an exception. The notice also stays in :meth:`Session.notices`. + an exception. The notice also stays in :meth:`Session.notices`. Losses whose notices the + session no longer keeps (past its last 200) are warned once per code, with their count. Attributes: code: The loss code, such as ``"dropped.ring"``: never translated, renamed or reused. diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 4b15504169..4fefa93562 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -121,23 +121,18 @@ struct Losses { } impl Losses { - /// Sets aside the losses `session` gave since the last call, for the calling thread, while - /// their notices are still in its queue (after every call, so before `take_notices` drains - /// it). One the queue no longer keeps (past its last 200) is set aside as one entry per code - /// that says how many. + /// Sets aside the losses `session` gave since the last call, for the calling thread. It runs + /// after each native call; the notice mark and the counts taken then keep the tally right + /// whatever has drained the queue since. One the queue no longer keeps (past its last 200) is + /// set aside as one entry per code that says how many ([`Session::losses_not_kept`]). fn collect(&mut self, session: &Session) { let thread = std::thread::current().id(); let kept: Vec<(LossCode, String)> = session.notices_since(self.mark).iter().filter_map(|n| n.loss().map(|code| (code, n.text.clone()))).collect(); - for &(code, given) in session.losses_given() { - let was = self.given.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); - let held = kept.iter().filter(|(c, _)| *c == code).count() as u64; - let lost = given.saturating_sub(was).saturating_sub(held); - if lost > 0 { - let spec = code.spec(); - let text = format!("{lost} further {} notice(s) were not kept", spec.id); - self.pending.push((thread, (spec.kind.id().into(), spec.id.into(), text))); - } + for (code, lost) in session.losses_not_kept(self.mark, &self.given) { + let spec = code.spec(); + let text = format!("{lost} further {} notice(s) were not kept", spec.id); + self.pending.push((thread, (spec.kind.id().into(), spec.id.into(), text))); } self.pending.extend(kept.into_iter().map(|(code, text)| (thread, (code.spec().kind.id().into(), code.spec().id.into(), text)))); self.mark = session.notice_mark(); diff --git a/apps/rustgis-web/smoke/run.mjs b/apps/rustgis-web/smoke/run.mjs index b0018a3e38..b1524fcf97 100644 --- a/apps/rustgis-web/smoke/run.mjs +++ b/apps/rustgis-web/smoke/run.mjs @@ -258,6 +258,9 @@ const search = async (name) => { // Gives `files` to the file picker that `trigger` opens. The app's picker opens the browser's // chooser while the key that asked counts as the user's action; past that (a loaded machine can // take seconds to handle the key) it shows its own panel to choose them in, as a user then does. +// The ids and class come from the `rfd` crate's wasm backend (0.18.0, `src/backend/wasm.rs`): its +// panel is `#rfd-overlay`, with the file input `#rfd-input`, and it carries the `hidden` class when +// the chooser could open at once. Check them again when `rfd` is bumped. const PANEL = "#rfd-overlay:not(.hidden) #rfd-input"; const pick = async (what, trigger, files) => { // Watched only while picking: no wait is left behind when the panel takes the files. diff --git a/crates/assistant/src/audit.rs b/crates/assistant/src/audit.rs index 873170d5ba..9094970948 100644 --- a/crates/assistant/src/audit.rs +++ b/crates/assistant/src/audit.rs @@ -261,16 +261,47 @@ fn redact_script(script: &str) -> String { if omitted > 0 { format!("# [{omitted} further script line(s) not recorded]\n{output}") } else { output } } +/// The least room past [`MAX_ARGS`] that a long text is cut to before it is scrubbed, enough for +/// a capability wrapper's head; [`scrub_margin`] widens it to the longest active login. +const SCRUB_MARGIN: usize = 4_096; + +/// Room past [`MAX_ARGS`] that a long text is cut to before it is scrubbed: at least as long as +/// every active login, so one crossing the bound is still whole when it is taken out. +fn scrub_margin() -> usize { + SCRUB_MARGIN.max(rustgis_engine::render::rustgis_tiles::logins::longest_redaction()) +} + /// `v` without what would give someone else the user's access: values under keys that name a /// secret, the passwords, keys and tokens in addresses ([`rustgis_engine::sources::redact`]), /// and the same inside a script's lines. fn redact(v: Value, depth: usize) -> Value { let redact_bounded = |s: &str| { if s.len() > MAX_ARGS { - // Scrub wrappers and active logins before clipping so a secret crossing MAX_ARGS - // cannot leave a recognizable prefix behind. - let scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(&rustgis_engine::sources::scrub_s3_wrappers(s)); - redact_string_inner(&crate::tools::clip(&scrubbed, MAX_ARGS)) + // Only the first MAX_ARGS characters are kept, so only what starts there is scrubbed + // and kept ([`logins::scrub_until`]): a secret that starts there is taken out whole, + // as the head scrubbed runs [`scrub_margin`] past it, and nothing after it (a secret + // cut at the head's end) can reach what is kept, whatever the redactions before it + // do to the length. A login activated in between by another session, longer than + // the margin read first, widens it and the head is scrubbed again. Capability + // wrappers come out after, from what is kept: one cut at its end can't be read and + // is redacted whole. A multi-megabyte argument costs little. + use rustgis_engine::render::rustgis_tiles::logins; + let mut margin = scrub_margin(); + let scrubbed = loop { + let head: String = s.chars().take(MAX_ARGS.saturating_add(margin)).collect(); + let stop = head.char_indices().nth(MAX_ARGS).map_or(head.len(), |(i, _)| i); + let (scrubbed, longest) = logins::scrub_until(&head, stop); + if longest <= margin { + break rustgis_engine::sources::scrub_s3_wrappers(&scrubbed); + } + margin = longest; + }; + let kept = if s.chars().nth(MAX_ARGS).is_some() || scrubbed.chars().nth(MAX_ARGS).is_some() { + format!("{}… (cut: {} characters in all)", scrubbed.chars().take(MAX_ARGS).collect::(), s.chars().count()) + } else { + scrubbed + }; + redact_string_inner(&kept) } else { redact_string(s) } @@ -590,5 +621,36 @@ mod tests { assert!(!redacted.contains(&active_secret[..8]), "redacted leaked active login prefix: {redacted}"); assert!(!redacted.contains("rustgis-s3:"), "redacted leaked s3 wrapper in key: {redacted}"); assert!(!redacted.contains("RGSYNTH_s3_tok_9921"), "redacted leaked wrapped token in key: {redacted}"); + + // A string of a few megabytes is scrubbed only up to the clip plus a margin, and a secret + // starting just inside MAX_ARGS still leaves no prefix of itself behind. + let huge = format!("{}{active_secret}{}", "y".repeat(MAX_ARGS - 4), "z".repeat(3_000_000)); + let redacted = redact(json!({"long": huge}), 0).to_string(); + assert!(!redacted.contains(&active_secret[..4]), "redacted leaked active login prefix: {redacted:.200}"); + assert!( + redacted.contains(&format!("(cut: {} characters in all)", huge.chars().count())), + "{:.200}", + &redacted[redacted.len().saturating_sub(200)..] + ); + + // Many whole copies before the clip shrink as they are redacted: the copy cut at the end of + // the scrubbed head isn't pulled into what is kept. + // (Back to back, a copy is cut wherever the head ends.) + let shrinking = format!("{}tail", active_secret.repeat(1_000)); + let redacted = redact(json!({"long": shrinking}), 0).to_string(); + assert!(!redacted.contains(&active_secret[..4]), "redacted leaked active login prefix: {redacted:.200}"); + assert!(redacted.contains("(cut: "), "{redacted:.200}"); + + // A capability wrapper straddling the clip, or cut at the end of the scrubbed head, leaves + // no part of its binding behind. + for at in [MAX_ARGS - 20, MAX_ARGS - 2, MAX_ARGS + scrub_margin() - 30] { + let long = format!("{}{wrapped}/{}", "x".repeat(at), "p".repeat(5_000)); + let redacted = redact(json!({"long": long}), 0).to_string(); + assert!( + !redacted.contains("0123456789abcdef") && !redacted.contains("rustgis-s3:"), + "{at}: {:.300}", + &redacted[redacted.len().saturating_sub(300)..] + ); + } } } diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 3b7df60eaa..b826fafe6a 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -739,6 +739,7 @@ impl Note { /// Every [`Note`] template RustGIS writes (the interface's catalogs translate each). pub const NOTE_TEMPLATES: &[&str] = &[ "The reply contains {count} content parts of type {kind} that aren't displayed.", + "The reply contains {count} content parts of {types} further type(s) that aren't displayed.", "OpenRouter found no endpoint matching your data policy. Check Private routing in the Assistant settings or your OpenRouter privacy settings.", "The reply reached its length limit.", "The provider's content filter stopped the reply.", @@ -975,7 +976,9 @@ fn openai_assembled(events: &[Value]) -> Value { } } } - if content.as_str() == Some("") { + // Empty-text deltas are never stored, but an all-empty array (`"content": []`) is: it is no + // content, and replayed as `[]` it would ride along in every later request. + if content.as_str() == Some("") || content.as_array().is_some_and(Vec::is_empty) { content = Value::Null; } let mut message = json!({"role": "assistant", "content": content}); @@ -1331,25 +1334,50 @@ fn openai_content_text(content: Option<&Value>) -> String { /// Counts unsupported display parts once per type. Thinking is native replay metadata; /// other non-text parts remain native too, but their omission from the answer must be visible. fn openai_content_notes(content: Option<&Value>) -> Vec { - let mut counts = std::collections::BTreeMap::<&str, usize>::new(); + let mut counts = std::collections::BTreeMap::::new(); for part in content.and_then(Value::as_array).into_iter().flatten() { let kind = part.get("type").and_then(Value::as_str).unwrap_or("unknown"); if kind == "thinking" || (kind == "text" && part.get("text").is_some_and(Value::is_string)) { continue; } - *counts.entry(kind).or_default() += 1; - } - counts - .into_iter() + *counts.entry(kind.to_string()).or_default() += 1; + } + // The server names the type: shown with control characters as spaces, and cut when long, so + // a note stays a line. Types are counted as sent, so two that look alike stay two. + let shown = |kind: &str| { + let kind: String = kind.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + if kind.chars().nth(MAX_KIND_CHARS).is_some() { + format!("{}…", kind.chars().take(MAX_KIND_CHARS).collect::()) + } else { + kind + } + }; + let mut notes: Vec = counts + .iter() + .take(MAX_KIND_NOTES) .map(|(kind, count)| { Note::with( "The reply contains {count} content parts of type {kind} that aren't displayed.", - [("count", count.to_string()), ("kind", kind.to_string())], + [("count", count.to_string()), ("kind", shown(kind))], ) }) - .collect() + .collect(); + // Past a few types, the rest share one note, so a server can't fill the transcript. + let others: Vec = counts.values().skip(MAX_KIND_NOTES).copied().collect(); + if !others.is_empty() { + notes.push(Note::with( + "The reply contains {count} content parts of {types} further type(s) that aren't displayed.", + [("count", others.iter().sum::().to_string()), ("types", others.len().to_string())], + )); + } + notes } +/// The most characters of a server's content-part type a note names. +const MAX_KIND_CHARS: usize = 40; +/// The most content-part types named in a note each; the rest share one note. +const MAX_KIND_NOTES: usize = 5; + /// Reads Chat Completions, retaining native typed content for the next request. fn openai_reply(v: &Value) -> Result { let choice = v.get("choices").and_then(|c| c.get(0)).ok_or("the reply has no choices")?; diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 20e811e291..8468f44ed5 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -5731,3 +5731,57 @@ fn typed_reply_notices_count_unsupported_parts_and_keep_the_native_content() { assert_eq!(native["content"], content); } } + +#[test] +fn a_streamed_empty_content_array_is_no_content() { + let reply = parse_reply( + Api::OpenAi, + &streamed(&[ + json!({"choices":[{"delta":{"role":"assistant", "content":[]}}]}), + json!({"choices":[{"delta":{"tool_calls":[{"index":0, "id":"c1", "type":"function", "function":{"name":"list_layers", "arguments":"{}"}}]}, "finish_reason":"tool_calls"}]}), + ]), + ) + .unwrap(); + assert_eq!(reply.native["content"], Value::Null); + // Content that has parts keeps them. + let reply = parse_reply( + Api::OpenAi, + &streamed(&[json!({"choices":[{"delta":{"content":[{"type":"text","text":"Hi"}]}, "finish_reason":"stop"}]})]), + ) + .unwrap(); + assert_eq!(reply.native["content"], json!([{"type":"text","text":"Hi"}])); +} + +#[test] +fn content_part_notes_are_bounded() { + let notes_for = |content: Value| { + let whole = HttpResponse { + status: 200, + headers: vec![], + body: json!({"choices":[{"message":{"role":"assistant", "content":content}, "finish_reason":"stop"}]}).to_string().into_bytes(), + }; + parse_reply(Api::OpenAi, &whole).unwrap().notes + }; + // A 500-character type is cut. + let notes = notes_for(json!([{"type":"text", "text":"Answer"}, {"type":"k".repeat(500)}])); + assert_eq!(notes.len(), 1); + let kind = ¬es[0].args[1].1; + assert_eq!(kind.chars().count(), 41, "{kind}"); + assert!(kind.ends_with('…')); + // Twenty distinct types give five notes and one for the rest. + let parts: Vec = (0..20).map(|i| json!({"type": format!("kind{i:02}")})).collect(); + let notes = notes_for(json!(parts)); + assert_eq!(notes.len(), 6); + let last = ¬es[5]; + assert_eq!(last.template, "The reply contains {count} content parts of {types} further type(s) that aren't displayed."); + assert_eq!(last.args, [("count", "15".to_string()), ("types", "15".to_string())]); + // Types that look alike once shown are still counted apart; a line break shows as a space. + let parts: Vec = ["a", "b", "c", "d", "e", "z\n", "z "].iter().map(|t| json!({"type": t})).collect(); + let notes = notes_for(json!(parts)); + assert_eq!(notes[5].args, [("count", "2".to_string()), ("types", "2".to_string())]); + let notes = notes_for(json!([{"type":"x\ny"}])); + assert_eq!(notes[0].args[1].1, "x y"); + // A few types give a note each and no fold. + let notes = notes_for(json!([{"type":"a"}, {"type":"b"}])); + assert_eq!(notes.len(), 2); +} diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index bb824f2bff..f8fa0200b4 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -907,17 +907,12 @@ fn losses_since(s: &Session, said: &Said) -> Vec { }; let kept: Vec<_> = s.notices_since(said.mark).iter().filter_map(|n| Some((n.loss()?, public_text(n.text.clone())))).collect(); let mut out: Vec = s - .losses_given() - .iter() - .filter_map(|&(code, given)| { - let was = said.given.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); - let held = kept.iter().filter(|(c, _)| *c == code).count() as u64; - let lost = given.saturating_sub(was).saturating_sub(held); - (lost > 0).then(|| { - let mut e = entry(code, format!("{lost} further {} notice(s) were not kept", code.spec().id)); - e["count"] = json!(lost); - e - }) + .losses_not_kept(said.mark, &said.given) + .into_iter() + .map(|(code, lost)| { + let mut e = entry(code, format!("{lost} further {} notice(s) were not kept", code.spec().id)); + e["count"] = json!(lost); + e }) .collect(); out.extend(kept.into_iter().map(|(code, text)| entry(code, text))); @@ -1090,8 +1085,8 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str // Within the 8,000-character cap, and the agent's `{"error": …}` within its output budget, // the error giving way first and then the list ([`loss_forms`]). let fits = |t: &str| t.chars().count() <= 8000 && json!({"error": t}).to_string().len() <= output_bytes(tokens); - let raw: Vec = losses.as_array().cloned().unwrap_or_default(); - let lines = loss_forms(&raw).into_iter().skip(2).map(|(list, _)| format!("\nlosses: {list}")); + let list: Vec = losses.as_array().cloned().unwrap_or_default(); + let lines = loss_forms(&list).into_iter().skip(2).map(|(list, _)| format!("\nlosses: {list}")); // The first line that fits alone, for a budget with no room for any of the error. let mut alone = None; for line in lines.chain(["\nlossesTrimmed: true".to_string()]) { diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 8f12728d39..086017b4d1 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -246,11 +246,12 @@ const MAX_ADDRESS_SCAN_ADDRESSES: usize = 4096; const MAX_ADDRESS_SCAN_ELEMENTS: usize = 1_000_000; /// The web addresses among a command's own parameters, not inside the contents of a file it -/// gives (`data`, `text`). Walks nested arrays and objects iteratively, bounding total scanned -/// JSON values at [`MAX_ADDRESS_SCAN_ELEMENTS`] (1,000,000) and discovered web address strings at -/// [`MAX_ADDRESS_SCAN_ADDRESSES`] (4,096); payloads past either limit are refused rather than -/// skipped so large non-address inputs (inline geometries, feature collections, ID lists) pass -/// while every string inside them is still inspected. +/// gives (its top-level `data` and `text` keys; nested keys of those names are scanned). Walks +/// nested arrays and objects iteratively, bounding total scanned JSON values at +/// [`MAX_ADDRESS_SCAN_ELEMENTS`] (1,000,000) and discovered web address strings at +/// [`MAX_ADDRESS_SCAN_ADDRESSES`] (4,096). Inputs under those limits (inline geometries, feature +/// collections, ID lists) pass with every string inside them inspected; past either limit they +/// are refused, never skipped. fn web_addresses(params: &Value) -> Result, String> { web_addresses_within(params, MAX_ADDRESS_SCAN_ELEMENTS, MAX_ADDRESS_SCAN_ADDRESSES) } diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 40a6089860..119f485383 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -732,7 +732,8 @@ impl Bridge<'_> { // Without `network`, no command may bring in a tile address (a map file read from text // carries its tile layers), or introduce a new legend address on an existing tile layer // (clearing or removing legends requires no network). On violation, each pre-existing map's - // tiles are restored from its snapshot rather than dropping modified layers. Where a layer + // whole tile set rolls back to its snapshot, so the command's other tile edits (visibility, + // opacity) are undone with the address that broke the rule. Where a layer // fetches from is decided by its address, kind, subdomains, row order and legend addresses. // Its name, attribution and opacity never reach a server, and its tile size reaches one // only as `{width}`/`{height}` (256 or 512). @@ -771,7 +772,7 @@ impl Bridge<'_> { m.tiles.retain(allowed); } } - res = Err(format!("{} needs the 'network' permission to add tile layers", self.plugin.manifest.name)); + res = Err(format!("{} needs the 'network' permission to add tile layers or legend addresses", self.plugin.manifest.name)); } } self.s.fix_active_layer(); diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 354c51f54c..53bd1cc8a0 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -563,9 +563,12 @@ fn add_layer( Source::Archive { path, kind, vector, zoom: (zmin, zmax) } => { // RustGIS opens an MBTiles file on this computer, and an archive on a network share // by no address. - // (A share's path, `\\server\share\…` or `//server/share/…`, is refused before the - // file is looked for: looking reaches the server.) - let share = path.starts_with("file://") || path.starts_with("\\\\") || path.starts_with("//"); + // (A share's path, any that starts with two separators of either kind as Windows reads + // it: `\\server\share\…`, `//server/share/…`, `/\server\share\…`, is refused before + // the file is looked for: looking reaches the server, as `rustgis_map::tiles::check_path` + // refuses it.) + let sep = |b: Option<&u8>| matches!(b, Some(b'/' | b'\\')); + let share = path.starts_with("file://") || (sep(path.as_bytes().first()) && sep(path.as_bytes().get(1))); if share || (*kind == "mbtiles" && path.contains("://")) { let at = if share { "on a network share" } else { "at a web address" }; report.lost( diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 75b1010a97..09d8e1d1dc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3887,6 +3887,28 @@ impl Session { &self.losses_given } + /// The losses given since `since_mark` (a [`Session::notice_mark`]) whose notices the queue no + /// longer keeps, with how many for each code: `given_before` is [`Session::losses_given`] as it + /// was when the mark was taken. Each code's count is what was given since, less the notices + /// still kept ([`Session::notices_since`]), so a front end that reports those notices and + /// these counts reports each loss once. + pub fn losses_not_kept( + &self, + since_mark: u64, + given_before: &[(rustgis_data::loss::LossCode, u64)], + ) -> Vec<(rustgis_data::loss::LossCode, u64)> { + let kept = self.notices_since(since_mark); + self.losses_given + .iter() + .filter_map(|&(code, given)| { + let was = given_before.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); + let held = kept.iter().filter(|n| n.loss() == Some(code)).count() as u64; + let lost = given.saturating_sub(was).saturating_sub(held); + (lost > 0).then_some((code, lost)) + }) + .collect() + } + /// The notices given since `mark` was taken (those still kept): what a command said beside its /// result, for front ends without a status bar (the CLI, the MCP server, the AI Assistant). pub fn notices_since(&self, mark: u64) -> &[Notice] { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13d763f9ca..19f1bedf99 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -774,6 +774,27 @@ fn losses_given_counts_what_the_notice_queue_no_longer_keeps() { assert_eq!(s.losses_given(), &[(LossCode::DroppedRing, 1), (LossCode::DroppedValue, 0)]); } +#[test] +fn losses_not_kept_counts_only_the_notices_the_queue_let_go() { + use rustgis_data::loss::LossCode; + let mut s = Session::new(Project::default()); + let (mark, given) = (s.notice_mark(), s.losses_given().to_vec()); + s.notify_loss(LossCode::DroppedRing, String::from("ring 1").into()); + s.notify_loss(LossCode::DroppedRing, String::from("ring 2").into()); + // Both notices are still kept: none is counted as not kept. + assert_eq!(s.losses_not_kept(mark, &given), []); + for i in 0..300 { + s.notify(format!("notice {i}"), false); + } + // Both left the queue; a loss given after them is kept and not counted. + s.notify_loss(LossCode::DroppedRing, String::from("ring 3").into()); + s.notify_loss(LossCode::DroppedValue, String::from("a value").into()); + assert_eq!(s.losses_not_kept(mark, &given), [(LossCode::DroppedRing, 2)]); + // From a later mark, only what was given since counts. + let (mark, given) = (s.notice_mark(), s.losses_given().to_vec()); + assert_eq!(s.losses_not_kept(mark, &given), []); +} + #[test] fn a_standalone_table_is_edited_with_the_edit_commands() { let mut s = world(); @@ -4913,6 +4934,11 @@ fn qgis_sources_import_as_their_layers() { layer("raster archive", "raster", "wms", "type=xyz&url=.%2Fnone.pmtiles"), // A network share's archive, by its Windows path. layer("unc share", "vector-tile", "mbtilesvectortiles", "type=mbtiles&url=%5C%5Cserver%5Cshare%5Ct.mbtiles"), + // Paths Windows reads as a share too, with a slash and a backslash, and a drive's + // working folder, which names no one file. + layer("mixed share", "raster", "wms", "type=xyz&url=%2F%5Cserver%5Cshare%5Cx.pmtiles"), + layer("mixed share 2", "raster", "wms", "type=xyz&url=%5C%2Fserver%2Fshare%2Fx.pmtiles"), + layer("drive folder", "raster", "wms", "type=xyz&url=C:x.pmtiles"), // Two tile layers on the same tiles, of the name of a file layer added before them. layer("dup_1", "raster", "wms", "type=xyz&url=https://dup.invalid/%7Bz%7D/%7Bx%7D/%7By%7D.png").replace("dup_1<", "dup<"), layer("dup_2", "raster", "wms", "type=xyz&url=https://dup.invalid/%7Bz%7D/%7Bx%7D/%7By%7D.png").replace("dup_2<", "dup<"), @@ -4997,6 +5023,10 @@ fn qgis_sources_import_as_their_layers() { out["notes"].as_array().unwrap().iter().any(|n| n["layer"] == layer && n["text"].as_str().unwrap().contains(text)) }; assert!(said("unc share", "the tile archive on a network share"), "{notes}"); + assert!(said("mixed share", "the tile archive on a network share"), "{notes}"); + assert!(said("mixed share 2", "the tile archive on a network share"), "{notes}"); + assert!(!notes.contains("x.pmtiles: no file there"), "a share isn't looked for: {notes}"); + assert!(said("drive folder", "the file C:x.pmtiles, relative to a drive's working directory"), "{notes}"); assert!(s.project.maps[mine].tiles.iter().any(|t| t.name == "mine"), "{notes}"); assert!(said("zm", "its geometry's Z and M values: RustGIS keeps x and y"), "{notes}"); assert!(said("zm", "its fields of a name an earlier field has (1)"), "{notes}"); diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 40f4424777..0e28d20b7c 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1030,6 +1030,9 @@ fn load( let object = if matches!(ext.as_str(), "tif" | "tiff" | "json" | "geojson") { json_not_tiff(bytes) } else { None }; let layer = matches!(ext.as_str(), "tif" | "tiff" | "json") && object.is_some_and(is_geojson); let renamed; + // The name the tool wrote: the reader's errors and notes say it, not the renamed one the user + // never sees (which only picks the reader's format). + let original = file_name; let (file_name, bytes) = match object { Some(json) if matches!(ext.as_str(), "tif" | "tiff") => { ext = if layer { "json" } else { "txt" }.into(); @@ -1058,6 +1061,12 @@ fn load( } }, "geojson" | "json" | "shp" | "csv" => { + // Only the name a message starts with, as the readers name the file: the same text + // elsewhere in it (a `crs` name, a value) is the file's own and kept. + let as_written = |text: String| match text.strip_prefix(file_name) { + Some(rest) if file_name != original => format!("{original}{rest}"), + _ => text, + }; let read = match (ext.as_str(), dir) { ("shp", Some(d)) => rustgis_data::io::read_path(&d.join(file_name)), _ => rustgis_data::io::read_bytes(file_name, bytes), @@ -1068,7 +1077,7 @@ fn load( // What the reader left out or assumed (features without a geometry it reads, Z // values, a `crs` it doesn't know) is said, as when the file is added. for note in report.messages { - let note = note.prefixed(layer_name); + let note = note.map_text(as_written).prefixed(layer_name); match note.loss { Some(code) => losses.push(LossMessage { code, text: note.text }), None => messages.push(note.text), @@ -1122,7 +1131,7 @@ fn load( None } Err(e) => { - messages.push(format!("{layer_name}: {e}")); + messages.push(format!("{layer_name}: {}", as_written(e.to_string()))); None } } diff --git a/crates/geolibre/src/runner.rs b/crates/geolibre/src/runner.rs index c44978caff..5b6736346e 100644 --- a/crates/geolibre/src/runner.rs +++ b/crates/geolibre/src/runner.rs @@ -401,6 +401,16 @@ fn stop_reason(live: &dyn Fn() -> Result<(), String>) -> Option { mod tests { use super::*; + /// The desktop's pinned release, the browser's `geolibre-wasm` version and the user guide's + /// release link move together. + #[test] + fn the_release_pins_agree() { + let web = include_str!("../../../apps/rustgis-web/src/geolibre.rs"); + let guide = include_str!("../../../docs/user-guide/analysis.md"); + assert!(web.contains(&format!("geolibre-wasm@{RELEASE}\"")), "apps/rustgis-web/src/geolibre.rs isn't on {RELEASE}"); + assert!(guide.contains(&format!("/releases/tag/v{RELEASE})")), "docs/user-guide/analysis.md doesn't link {RELEASE}"); + } + /// Discovery passes over a runner outside the supported range for the next supported one, /// and says why; with only an unsupported one, there is no runner but the reason is given. #[test] diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index d88b9e7e7d..8dd86c6546 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -800,6 +800,26 @@ fn a_default_sent_back_as_text_is_left_to_the_runner() { ); } +/// A `.tif` output that holds JSON is read under another name, but what the reader says names the +/// file the tool wrote, not the renamed one the user never sees. +#[test] +fn a_json_read_from_a_tif_is_named_as_written() { + let job = Job { + tool: "longest_flowpath".into(), + name: "Longest Flowpath".into(), + files: Vec::new(), + args: Vec::new(), + outputs: vec![("output.tif".into(), "Flowpaths".into())], + crs: Crs::from_epsg(32632).unwrap(), + notes: Vec::new(), + }; + let city = br#"{"type":"CityJSON","version":"2.0","CityObjects":{},"vertices":[]}"#; + let r = finish(&job, &[("output.tif".into(), city.to_vec())], &[], None); + let said: Vec<&String> = r.messages.iter().chain(r.losses.iter().map(|l| &l.text)).collect(); + assert!(said.iter().any(|m| m.contains("output.tif") && m.contains("transform")), "{said:?}"); + assert!(said.iter().all(|m| !m.contains("output.json")), "{said:?}"); +} + /// Longest Flowpath's manifest calls its output a raster, so it is asked for a `.tif`, and the /// tool writes GeoJSON lines into it: they come back as a vector layer, not as a GeoTIFF that /// fails to read (#2762). A real GeoTIFF named `.tif` is still read as one. diff --git a/crates/map/src/paths.rs b/crates/map/src/paths.rs index 0d3ab1b79b..4ebc407914 100644 --- a/crates/map/src/paths.rs +++ b/crates/map/src/paths.rs @@ -30,11 +30,14 @@ pub fn is_local(p: &str) -> bool { !first.contains(':') || (first.len() == 2 && drive(first) && p.as_bytes().get(2).is_some_and(|b| matches!(b, b'/' | b'\\'))) } -/// Absolute POSIX or drive path, excluding network shares. +/// Absolute POSIX or drive path, excluding network shares (`//server`, and `/\server`, which +/// Windows reads as one). On every platform, as for `//`: a project moves between systems, and a +/// path left out here is only kept as written on save, never rewritten relative. pub fn is_absolute_local(p: &str) -> bool { let b = local_path(p); is_local(p) - && ((b.starts_with('/') && !b.starts_with("//")) || (drive(b) && b.as_bytes().get(2).is_some_and(|c| matches!(c, b'/' | b'\\')))) + && ((b.starts_with('/') && !matches!(b.as_bytes().get(1), Some(b'/' | b'\\'))) + || (drive(b) && b.as_bytes().get(2).is_some_and(|c| matches!(c, b'/' | b'\\')))) } /// A linked path that needs the project's containing folder. @@ -103,6 +106,16 @@ pub fn unknown_folder(path: &str) -> String { mod tests { use super::*; + /// A path Windows reads as a network share, with any mix of slashes, is not a local one. + #[test] + fn a_share_with_mixed_separators_is_not_absolute_local() { + assert!(!is_absolute_local(r"/\server\share\x")); + assert!(!is_absolute_local("//server/share/x")); + assert!(!is_absolute_local(r"\\server\share\x")); + assert!(is_absolute_local("/data/x")); + assert!(is_absolute_local(r"C:\data\x")); + } + #[test] fn paths_relative_and_round_trip() { for (d, p, expected, normalized) in [ @@ -123,6 +136,7 @@ mod tests { assert_eq!(relative_to(r"C:\p", r"D:\d\x.tif"), None); assert_eq!(relative_to("/p", r"\\server\x"), None); assert_eq!(relative_to("/p", "//server/x"), None); + assert_eq!(relative_to("/p", r"/\server\share\x"), None); assert_eq!(resolve("/p", "../../../x").as_deref(), Some("/x")); } diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 232ed83664..4630f4581c 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1119,6 +1119,9 @@ fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result String { scrub_patterns(text, &patterns) } +/// [`scrub`] of what starts in the first `stop` bytes of `text`: a match or wrapper that starts +/// there is taken out whole (when `text` holds it whole), and nothing that starts at or past +/// `stop` is in the result. Also gives the length in bytes of the longest active pattern in the +/// same snapshot of the logins (0 with none), matched or not: a caller that cut `text` short +/// checks that it kept at least that much past `stop`, as [`longest_redaction`] read earlier may +/// miss a login activated since, so that no credential crossing `stop` was cut. +pub fn scrub_until(text: &str, stop: usize) -> (String, usize) { + let entries = entries(); + let longest = longest_in(&entries); + let mut patterns: Vec<_> = entries.values().flat_map(|entry| &entry.redactions).collect(); + patterns.sort_unstable_by_key(|pattern| std::cmp::Reverse(pattern.value.expose().len())); + (scrub_patterns_until(text, &patterns, stop), longest) +} + /// The length in bytes of the longest pattern [`scrub`] takes out now (0 with no active login). /// A caller that cuts a text before scrubbing it keeps at least this much past its bound, so a /// credential that crosses the bound is still whole when it is matched. pub fn longest_redaction() -> usize { - entries().values().flat_map(|entry| &entry.redactions).map(|pattern| pattern.value.expose().len()).max().unwrap_or(0) + longest_in(&entries()) +} + +/// The length in bytes of the longest pattern among `entries` (0 with none). +fn longest_in(entries: &BTreeMap) -> usize { + entries.values().flat_map(|entry| &entry.redactions).map(|pattern| pattern.value.expose().len()).max().unwrap_or(0) } /// Cleans generated error text before active values can obscure its address syntax. @@ -518,10 +537,15 @@ pub fn scrub_error(text: &str) -> String { /// Removes runtime capability headers and the supplied active patterns in one pass. fn scrub_patterns(text: &str, patterns: &[&Redaction]) -> String { + scrub_patterns_until(text, patterns, text.len()) +} + +/// [`scrub_patterns`] of what starts before byte `stop` of `text` ([`scrub_until`]). +fn scrub_patterns_until(text: &str, patterns: &[&Redaction], stop: usize) -> String { // Strip capabilities even after revocation, when there are no active credential patterns. - let mut result = String::with_capacity(text.len()); + let mut result = String::with_capacity(text.len().min(stop)); let mut rest = text; - while !rest.is_empty() { + while !rest.is_empty() && text.len().saturating_sub(rest.len()) < stop { if let Some(wrapper) = rest.strip_prefix(rustgis_data::login_address::PREFIX) { // The hex token and length-prefixed origin precede the ordinary URL. let url = wrapper @@ -575,6 +599,26 @@ fn encoded_matches(actual: &[u8], expected: &[u8]) -> bool { mod tests { use super::*; + /// Only what starts before `stop` is in the result: a match starting there comes out whole, + /// and a credential cut at the text's end stays out, however redactions change the length. + #[test] + fn scrubbing_until_a_stop_keeps_nothing_past_it() { + let long = format!("{}{}{}", "C".repeat(1_000), "a".repeat(2_000), "B".repeat(1_000)); + let (long_r, short_r) = + (Redaction { value: Secret::new(long.clone()), encoded: false }, Redaction { value: Secret::new("a"), encoded: false }); + let patterns = [&long_r, &short_r]; + // Two whole values, x's, then a value cut at the end of the text: 1,000 C's and 1,096 a's. + let text = format!("{long}{long}{}{}{}", "x".repeat(2_000), "C".repeat(1_000), "a".repeat(1_096)); + let stop = 10_000; + let out = scrub_patterns_until(&text, &patterns, stop); + assert_eq!(out, format!("[redacted][redacted]{}", "x".repeat(2_000))); + // A match that starts before the stop and ends past it is taken out whole. + let crossing = format!("{}{long}tail", "x".repeat(10)); + assert_eq!(scrub_patterns_until(&crossing, &patterns, 20), format!("{}[redacted]", "x".repeat(10))); + // With the stop at the end, it is the whole scrub. + assert_eq!(scrub_patterns_until(&crossing, &patterns, crossing.len()), scrub_patterns(&crossing, &patterns)); + } + #[test] fn canonical_origins() { for (url, expected) in [ diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index aa5194ed06..77ebb5256a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -218,6 +218,22 @@ fn assistant_note_translations_are_real_when_available() { } } +/// Provider preset descriptions reach `tl!` as variables, so no literal flags them: when a catalog +/// has one, it is a translation, not the English kept. Labels are left out: most are product +/// names (Google Gemini, OpenRouter), which stay in English. +#[test] +fn assistant_preset_translations_are_real_when_available() { + for l in &LANGUAGES[1..] { + let (m, _) = parse(l.source); + for preset in rustgis_assistant::provider::PRESETS { + let key = preset.description; + if let Some(tr) = m.get(key) { + assert_ne!(tr, key, "{}: {key:?} isn't translated", l.code); + } + } + } +} + #[test] fn skills_controls_are_in_every_catalog() { let keys = [ diff --git a/crates/ui-touch/src/copies.rs b/crates/ui-touch/src/copies.rs index 6e7b6b8111..c0752945c3 100644 --- a/crates/ui-touch/src/copies.rs +++ b/crates/ui-touch/src/copies.rs @@ -132,6 +132,12 @@ pub(crate) type WriteProject<'a> = &'a dyn Fn(&mut dyn Write) -> Result<(), serd /// picks and as the project is written out. The project is scanned as it is written: only a /// buffer of its text is held at a time, never all of it (see [`Names`]). pub(crate) fn unused(picked: &Path, project: WriteProject, cancelled: &AtomicBool) -> Result { + unused_then(picked, project, cancelled, &|| {}) +} + +/// [`unused`], running `after_scan` once the project has been scanned (a test presses Cancel +/// there). +fn unused_then(picked: &Path, project: WriteProject, cancelled: &AtomicBool, after_scan: &dyn Fn()) -> Result { let entries = std::fs::read_dir(picked).map_err(|e| format!("{}: {e}", picked.display()))?; let mut found = Unused::default(); let mut picks = Vec::new(); @@ -151,7 +157,10 @@ pub(crate) fn unused(picked: &Path, project: WriteProject, cancelled: &AtomicBoo } let mut files = Vec::new(); // A pick not read in full may hold a file the project names: kept. - if !gather(&pick, DEPTH, &mut files) { + if !gather(&pick, DEPTH, &mut files, cancelled) { + if cancelled.load(Ordering::Relaxed) { + return Err(tl!("Stopped.").to_string()); + } found.unreadable += 1; found.unreadable_picks.push(pick); continue; @@ -172,21 +181,53 @@ pub(crate) fn unused(picked: &Path, project: WriteProject, cancelled: &AtomicBoo let rests: HashSet> = candidates.iter().flat_map(|(_, files)| files).filter_map(|(file, _)| rest_of(&prefix, file)).collect(); // No file to look for (none of their paths can be told from the folder's): all are kept. let named = if rests.is_empty() { HashSet::new() } else { scan(project, Names::new(prefix.clone(), rests, cancelled))? }; + after_scan(); for (pick, files) in candidates { // A file whose path can't be told apart from the folder's is kept, never judged unused. if files.iter().any(|(file, _)| rest_of(&prefix, file).is_none_or(|rest| named.contains(&rest))) { continue; } + if cancelled.load(Ordering::Relaxed) { + return Err(tl!("Stopped.").to_string()); + } + // Looked at again after the scan (a long wait on a large project), so the count the user + // is asked about is what is there: one no longer read in full is unreadable, and one + // copied into or otherwise changed meanwhile (files added, emptied, resized) is busy, + // its new files not judged. Remove Them looks again regardless. + let mut now = Vec::new(); + if !gather(&pick, DEPTH, &mut now, cancelled) { + if cancelled.load(Ordering::Relaxed) { + return Err(tl!("Stopped.").to_string()); + } + found.unreadable += 1; + found.unreadable_picks.push(pick); + continue; + } + let mut before = files.clone(); + before.sort(); + now.sort(); + if now != before || now.iter().any(|(file, _)| in_flight(file)) { + found.busy_picks.push(pick); + continue; + } found.files += files.len(); found.bytes += files.iter().map(|(_, size)| size).sum::(); found.picks.push(pick); } + // Cancelled during the last pick's look: stopped, not a count to ask about. + if cancelled.load(Ordering::Relaxed) { + return Err(tl!("Stopped.").to_string()); + } Ok(found) } /// The files at or under `path` (itself, if it is one), with their sizes, `depth` levels down at -/// most. Links aren't followed. Returns whether everything there could be read. -fn gather(path: &Path, depth: usize, files: &mut Vec<(PathBuf, u64)>) -> bool { +/// most. Links aren't followed. Returns whether everything there could be read; a walk stopped by +/// `cancelled` (looked at for each entry) wasn't, and its caller says it stopped. +fn gather(path: &Path, depth: usize, files: &mut Vec<(PathBuf, u64)>, cancelled: &AtomicBool) -> bool { + if cancelled.load(Ordering::Relaxed) { + return false; + } let Ok(meta) = std::fs::symlink_metadata(path) else { return false }; if meta.is_file() { files.push((path.to_path_buf(), meta.len())); @@ -201,7 +242,7 @@ fn gather(path: &Path, depth: usize, files: &mut Vec<(PathBuf, u64)>) -> bool { let mut complete = true; for entry in entries { match entry { - Ok(entry) => complete &= gather(&entry.path(), depth - 1, files), + Ok(entry) => complete &= gather(&entry.path(), depth - 1, files, cancelled), Err(_) => complete = false, } } @@ -331,7 +372,7 @@ impl Write for Names<'_> { return Err(std::io::Error::other("stopped")); } // A machine short of memory gets an error, not an abort. - self.carry.try_reserve(piece.len()).map_err(|_| std::io::Error::other("out of memory"))?; + self.carry.try_reserve(piece.len()).map_err(|_| std::io::Error::other(tl!("out of memory").to_string()))?; self.carry.extend_from_slice(piece); self.look(false); } @@ -380,7 +421,9 @@ fn remove_unused(picked: &Path, found: &Unused, project: WriteProject, cancelled Ok(removed) } -/// Removes `picks` (folders or files), looking for `cancelled` between them. +/// Removes `picks` (folders or files), looking for `cancelled` between them. The walk inside one +/// pick, which counts what its removal takes, doesn't look at Cancel: the counts said must be +/// whole for what is removed. fn remove(picks: &[PathBuf], cancelled: &AtomicBool) -> Removed { let (mut files, mut bytes, mut failed) = (0usize, 0u64, Vec::new()); for pick in picks { @@ -388,7 +431,7 @@ fn remove(picks: &[PathBuf], cancelled: &AtomicBool) -> Removed { break; } let mut held = Vec::new(); - gather(pick, DEPTH, &mut held); + gather(pick, DEPTH, &mut held, &AtomicBool::new(false)); let gone = if pick.is_dir() { std::fs::remove_dir_all(pick) } else { std::fs::remove_file(pick) }; // What is gone is counted, also when the removal stopped partway through a pick. let removed: Vec<&(PathBuf, u64)> = @@ -665,6 +708,47 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// A pick copied into while the project is scanned, after its files were gathered, is busy, + /// not counted among the unused ones. + #[test] + fn a_pick_copied_into_during_the_scan_is_busy() { + let root = std::env::temp_dir().join(format!("rustgis-copies-during-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let picked = root.join("picked"); + for pick in ["8/0", "9/0"] { + std::fs::create_dir_all(picked.join(pick)).unwrap(); + } + std::fs::write(picked.join("8/0/roads.gpkg"), b"whole").unwrap(); + std::fs::write(picked.join("9/0/rivers.gpkg"), b"whole").unwrap(); + let part = picked.join("8/0/parcels.gpkg.part"); + // The project is written out after the picks are gathered: a copy starts in pick 8 then. + let project = |out: &mut dyn Write| { + let _ = std::fs::write(&part, b"half"); + serde_json::to_writer(out, &json!({})) + }; + let found = unused(&picked, &project, &AtomicBool::new(false)).unwrap(); + assert_eq!(found.picks, [picked.join("9")]); + assert_eq!(found.busy_picks, [picked.join("8")]); + assert_eq!(found.files, 1); + std::fs::remove_dir_all(&root).unwrap(); + } + + /// Cancel pressed after the scan, while the picks are looked at again, ends the look with + /// Stopped, not a count to ask about. + #[test] + fn cancel_during_the_recheck_stops() { + let root = std::env::temp_dir().join(format!("rustgis-copies-cancel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let picked = root.join("picked"); + std::fs::create_dir_all(picked.join("3/0")).unwrap(); + std::fs::write(picked.join("3/0/roads.gpkg"), b"whole").unwrap(); + let cancelled = AtomicBool::new(false); + assert!(unused_then(&picked, &of(json!({})), &cancelled, &|| {}).is_ok_and(|f| f.picks.len() == 1)); + let stopped = unused_then(&picked, &of(json!({})), &cancelled, &|| cancelled.store(true, Ordering::Relaxed)); + assert_eq!(stopped, Err(tl!("Stopped.").to_string())); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn an_old_active_batch_between_documents_stays_protected_until_completion() { let root = std::env::temp_dir().join(format!("rustgis-copies-owner-{}", std::process::id())); diff --git a/docs/i18n.md b/docs/i18n.md index d1cdf6d680..83446f6253 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -90,6 +90,11 @@ require translations for some established interface strings: cargo test -p rustgis-ui-egui i18n ``` +Some keys are not `tl!` literals, so a search for `tl!("…")` misses them: the AI Assistant's notes +(`NOTE_TEMPLATES` in `crates/assistant/src/provider.rs`) and its provider presets +(`rustgis_assistant::PRESETS`, each preset's `label` and `description`). Translate them from +those lists. + ### Context for ambiguous words Existing two-column catalogs keep their meaning. For a word used in different senses, an diff --git a/docs/mcp.md b/docs/mcp.md index 3e2a9973b8..dd4ac225ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -344,7 +344,7 @@ These behavioral tests in `crates/assistant/src/relay.rs` check the requirements | `view_map` | The map as a PNG image at the current view; `width` and `height` default to 1024 × 640, each clamped to 64–2048 pixels. A picture over 3.75 MiB (a satellite basemap near 2048 pixels) is drawn again smaller, and its caption gives the size drawn and the size asked. `layout` (a layout's name) draws its page instead, fitted to `width` (and `height` when given); `region` draws part of either at full detail: `[x, y, w, h]` in mm on a layout (up to 600 dpi), `[west, south, east, north]` in degrees on the map. What drawing it said (texts cut off, layers without their cast shadows) follows the caption | | `snapshot` | The map as a PNG with JSON metadata: `mode`, `width`, `height`, `extent` (longitude/latitude), `center`, `scale`, `projection`, `render_settled`, `saved` and `note`. `mode: "screen"` captures the RustGIS window through the relay, once the map has finished drawing or after `wait_s` seconds (default 5, clamped to 0–30); `overlays: false` leaves out the map's controls, scale bar, north arrow and sketches. `mode: "render"` draws offscreen at `max_width` (default 1024, clamped to 64–2048 pixels); height follows the view's shape, with each side capped at 2048. It works while the window is hidden. `mode: "auto"` (default) takes the screen when the map is on it. Unavailable screen captures fall back to render. `save_path` also writes the PNG to a file, which needs file access | | `search_commands` | Finds RustGIS commands by words: their ids, ribbon locations and parameters | -| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data with a [loss code](user-guide/loss-codes.md) is also in `losses`, as `{code, kind, text, action}`, so an agent can match the code: for an `assumed.*` code it can ask instead of guessing. A loss that has no code yet is only in `notices`. When the list doesn't fit the output budget beside the result, it is shortened (each entry's `code` and `kind`, then one entry per code with its `count`, then the codes alone) and `lossesTrimmed` is `true`; with the tightest budgets `losses` is left out and only `lossesTrimmed` says so. A failed command's error ends with a `losses:` line of JSON: one entry per code with its `action` and `count`, then the counts alone, then the codes alone, or `lossesTrimmed: true` | +| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data with a [loss code](user-guide/loss-codes.md) is also in `losses`, as `{code, kind, text, action}`, so an agent can match the code: for an `assumed.*` code it can ask instead of guessing. A loss that has no code yet is only in `notices`. When the list doesn't fit the output budget beside the result, it is shortened (each entry's `code` and `kind`, then one entry per code with its `count`, then the codes alone) and `lossesTrimmed` is `true`; with the tightest budgets `losses` is left out and only `lossesTrimmed` says so. A failed command's error ends with a `losses:` line of JSON: one entry per code with its `kind`, `action` and `count`, then the counts alone, then the codes alone, or `lossesTrimmed: true` | | `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | | `search_tools` | Finds geoprocessing tools by words | | `describe_tool` | A geoprocessing tool's parameters | diff --git a/docs/python.md b/docs/python.md index 03311095d4..2826d2feee 100644 --- a/docs/python.md +++ b/docs/python.md @@ -223,7 +223,7 @@ losses into errors and allow the ones it expects: import warnings warnings.filterwarnings("error", category=rustgis.DataLossWarning) -warnings.filterwarnings("ignore", category=rustgis.DroppedWarning, message=r".*\[dropped\.ring\]") +warnings.filterwarnings("ignore", category=rustgis.DroppedWarning, message=r"(?s).*\[dropped\.ring\]") s.add_data("storms.rss") # raises on any other loss ``` diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 83c185e3e4..421619529e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1549,7 +1549,10 @@ You can install the tools again at any time. In the browser, **Remove** unloads the tools and stops loading them when RustGIS starts. An existing desktop runner is kept when RustGIS updates. To update a runner installed by RustGIS -in place, run `gp.installGeolibre` from the command line in the updated RustGIS build. It downloads +in place, run `gp.installGeolibre` from the command line in the updated RustGIS build, as the +same user as the desktop app and with the same `RUSTGIS_APP_DATA_DIR` (and on Linux +`XDG_DATA_HOME`), or none when the app uses the default folder; another folder installs a second +runner the app doesn't use. It downloads and checks the replacement before changing the installed program, so a download or verification failure leaves the installed runner in place. Restart the desktop app afterwards to reload its tools. For a runner you located yourself, download the new release and use **Locate…**. diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 662d184714..45877092aa 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -154,7 +154,9 @@ Changing this setting stops the current run, including a delegated subagent, so requests use the new policy. A request already sent may still finish at the provider. The setting is saved for OpenRouter alone. On the command line, set `RUSTGIS_OPENROUTER_DATA_COLLECTION=allow` to turn the filter off; other values keep it on. -Other providers' requests are unaffected. +Other providers' requests are unaffected. The filter goes with the OpenRouter preset, also when +its **Address** is changed: a server other than OpenRouter that refuses unknown fields may reject +requests; turn Private routing off for it. ### Signing in with ChatGPT