From 0f70d0749a355eab67240c9d16f1ff68881d279f Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 20:31:17 -0600 Subject: [PATCH 1/5] fix(raster): identify full-resolution pixels in place --- crates/assistant/src/agent.rs | 140 ++++++++++ crates/assistant/src/mcp.rs | 3 +- crates/assistant/src/tools.rs | 10 +- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/design.rs | 15 + crates/engine/src/cmd/imagery.rs | 13 + crates/engine/src/cmd/raster.rs | 5 +- crates/engine/src/cmd/reads.rs | 92 ++++++- crates/engine/src/cmd/select.rs | 61 ++++- crates/engine/src/cmd/select_point.rs | 346 ++++++++++++++++++++++++ crates/engine/src/policy/dispatch.rs | 7 +- crates/engine/src/policy/effects.rs | 14 + crates/engine/src/tests/cancellation.rs | 11 + crates/tiles/src/cog.rs | 187 +++++++++++++ crates/ui-egui/src/assistant.rs | 50 ++++ crates/ui-egui/src/lib.rs | 10 +- crates/ui-egui/src/mapview.rs | 186 ++++++++++++- crates/ui-egui/src/readjob.rs | 3 +- docs/user-guide/data-formats.md | 6 +- 19 files changed, 1134 insertions(+), 27 deletions(-) create mode 100644 crates/engine/src/cmd/select_point.rs diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index d73a994f53..a0db11323e 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -52,6 +52,8 @@ pub enum Step { Confirm, /// Wait this long, then call [`Agent::retry`]: the request failed in a way worth trying again. Retry(core::time::Duration), + /// Run the admitted read from `Agent::take_read`, then call `Agent::finish_read`. + Read, /// Nothing until the user writes again. Done, } @@ -127,6 +129,7 @@ pub struct Agent { /// Exact operations approved for the rest of this conversation and project generation. always: Vec, pending_policy: Option, + pending_read: Option<(ToolCall, Option)>, conversation: u64, live: Arc, system: String, @@ -236,6 +239,7 @@ impl Agent { replies: 0, always: Vec::new(), pending_policy: None, + pending_read: None, conversation: CONVERSATIONS.fetch_add(1, Ordering::Relaxed), live: Arc::new(tools::Live::default()), system: base_system.clone() + &skills::catalog(&skills), @@ -431,6 +435,9 @@ impl Agent { /// The call waiting for the user's approval: (summary, reason, whether it may be allowed for /// the rest of the conversation). pub fn pending(&self, s: &Session) -> Option<(String, String, bool)> { + if self.pending_read.is_some() { + return None; + } if let Some(child) = &self.child { return child.pending(s).map(|(what, why, always)| (format!("Subagent: {what}"), why, always)); } @@ -466,6 +473,9 @@ impl Agent { /// answer given to an approval no longer waiting (a second tap, a card drawn frames before) /// is refused. pub fn asking(&self) -> Option { + if self.pending_read.is_some() { + return None; + } let State::Calls(q, done) = &self.state else { return None }; let call = q.front()?; let child = match &self.child { @@ -550,6 +560,7 @@ impl Agent { self.last_context.clear(); self.always.clear(); self.pending_policy = None; + self.pending_read = None; self.live.0.store(false, Ordering::SeqCst); self.live = Arc::new(tools::Live::default()); self.conversation = CONVERSATIONS.fetch_add(1, Ordering::Relaxed); @@ -1024,6 +1035,9 @@ impl Agent { /// Runs the waiting calls until one needs approval or none are left. fn drain(&mut self, s: &mut Session) -> Step { loop { + if self.pending_read.is_some() { + return Step::Read; + } let State::Calls(q, _) = &self.state else { return Step::Done }; let Some(call) = q.front().cloned() else { break }; // Before anything is asked of the user: a call this subagent may not make is refused. @@ -1083,6 +1097,40 @@ impl Agent { self.send() } + /// Takes the current call's admitted read once, including a delegated child's read. + pub fn take_read(&mut self) -> Option { + if let Some(child) = &mut self.child { + return child.take_read(); + } + self.pending_read.as_mut()?.1.take() + } + + /// Completes only this run's pending call, then resumes its batch. Stopped conversations + /// discard late reads before landing; the engine rechecks the original ingress owner. + pub fn finish_read(&mut self, generation: u64, read: Result, s: &mut Session) -> Step { + self.guard(|a| { + if generation != a.generation { + return Step::Done; + } + if let Some(child) = &mut a.child { + let step = child.finish_read(child.generation(), read, s); + return a.after_child(step, s); + } + let Some((call, _)) = a.pending_read.take() else { + return Step::Done; + }; + let completion = tools::CommandCompletion::capture(s); + let answer = read.and_then(|read| rustgis_engine::cmd::reads::read_land(s, read)); + let answer = completion.finish_with_budget(s, answer, a.config.tool_output_token_limit); + let (content, error) = match answer { + Ok(text) => (text, false), + Err(text) => (text, true), + }; + a.record(call, content.clone(), content, error, Vec::new()); + a.drain(s) + }) + } + /// Runs (or declines) the first waiting call and records its result. fn run_front(&mut self, s: &mut Session, allow: bool) { let tokens = self.config.tool_output_token_limit; @@ -1090,6 +1138,23 @@ impl Agent { let State::Calls(q, _) = &mut self.state else { return }; let Some(call) = q.pop_front() else { return }; let permit = self.pending_policy.take().filter(|_| allow).map(Pending::allow); + // Identify's source reads retain this exact scope and permit. The adapter waits for + // their real completion; neither the model nor the UI receives a pending pixel as data. + if allow + && call.name == "run_command" + && call.args.get("command").and_then(serde_json::Value::as_str).map(str::trim) == Some("identify") + && call.args.get("params").and_then(|p| p.get("defer")).and_then(serde_json::Value::as_bool) != Some(true) + && s.map().layers.iter().any(|l| l.raster.as_ref().is_some_and(|r| r.reads_in_place())) + { + let ahead = tools::policy_call(&call) + .and_then(|c| c.ok_or_else(|| "missing identify call".to_string())) + .and_then(|engine| s.start_scoped_archive_read(self.scope(), &engine, permit)); + match ahead { + Ok(ahead) => self.pending_read = Some((call, Some(ahead))), + Err(error) => self.record(call, error.clone(), error, true, Vec::new()), + } + return; + } let was_on = s.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id); let (content, error, images) = if allow { match self.run_tool(s, &call, tokens, permit) { @@ -1360,6 +1425,7 @@ impl Agent { pub fn stop(&mut self) { self.live.0.store(false, Ordering::SeqCst); self.pending_policy = None; + self.pending_read = None; // A paused run is ended too: Continue doesn't come back for it. self.paused = false; if !self.busy() { @@ -1426,6 +1492,7 @@ impl Agent { fn halt(&mut self, why: Entry, queued: &str, interrupted: &str) { self.live.0.store(false, Ordering::SeqCst); self.pending_policy = None; + self.pending_read = None; if let Some(child) = self.child.take() { self.usage.add(child.usage); } @@ -1605,6 +1672,13 @@ pub fn run_blocking_with>( let r = send(&req); agent.receive_result(g, r.map_err(Into::into), s) } + Step::Read => { + let result = agent + .take_read() + .ok_or_else(|| "the read was already taken".to_string()) + .and_then(|read| read.run(&rustgis_engine::analysis::control::Control::new())); + agent.finish_read(agent.generation(), result, s) + } Step::Confirm => { let allow = agent.pending(s).is_some_and(|(what, why, access)| confirm(&what, &why, access)); match agent.asking() { @@ -1640,6 +1714,72 @@ mod tests { c } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn identify_waits_for_its_admitted_read_before_running_the_batch_suffix() { + use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster}; + for stop in [false, true] { + let mut s = Session::new(Project::default()); + let raster = Raster::new( + "pixel", + 1, + 1, + vec![vec![7.]], + GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 1., pixel_height: -1. }, + Crs::LonLat, + None, + ColorHint::Gray, + "Float32", + ) + .unwrap(); + let mut layer = rustgis_engine::map::raster::RasterLayer::from_path(raster, "/nonexistent-rustgis-point/pixel.tif"); + layer.in_place = true; + s.map_mut().add_raster("pixel", layer); + let mut a = Agent::new(test_cfg(), &s); + assert!(matches!(a.ask("identify", &s), Step::Send(_))); + let tool = |id: &str, name: &str, args: serde_json::Value| json!({"id":id,"type":"function","function":{"name":name,"arguments":args.to_string()}}); + let response = json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[ + tool("pixel","run_command",json!({"command":"identify","params":{"lon":10.5,"lat":45.5}})), + tool("suffix","list_layers",json!({})) + ]}}]}); + let step = a.receive( + a.generation(), + Ok(HttpResponse { status: 200, body: response.to_string().into_bytes(), headers: vec![] }), + &mut s, + ); + assert_eq!(step, Step::Confirm, "a source read needs the original file approval"); + let asked = a.asking().unwrap(); + assert_eq!(a.decide(&asked, true, false, &mut s), Some(Step::Read)); + assert!(!a.transcript.iter().any(|entry| matches!(entry, Entry::Tool { .. }))); + let ahead = a.take_read().unwrap(); + if stop { + a.stop(); + } + let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); + let step = a.finish_read(a.generation(), answer, &mut s); + if stop { + assert_eq!(step, Step::Done); + assert!( + !a.transcript + .iter() + .any(|entry| matches!(entry,Entry::Tool { name,result,.. } if name=="list_layers" && !result.contains("Stopped"))) + ); + } else { + assert!(matches!(step, Step::Send(_))); + let tools: Vec<_> = a + .transcript + .iter() + .filter_map(|entry| match entry { + Entry::Tool { name, result, .. } => Some((name.as_str(), result.as_str())), + _ => None, + }) + .collect(); + assert_eq!(tools.iter().map(|(name, _)| *name).collect::>(), ["run_command", "list_layers"]); + assert!(tools[0].1.contains("pixelState") && tools[0].1.contains("failed")); + } + } + } + /// An agent thread's report goes on with the run it belongs to, so a chain of reports and /// follow-ups still pauses where the run's steps run out. #[test] diff --git a/crates/assistant/src/mcp.rs b/crates/assistant/src/mcp.rs index f6df82592b..296a7713fd 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -162,7 +162,8 @@ impl ArchiveBatch { || !matches!( args.get("command").and_then(Value::as_str).map(str::trim), Some( - "map.reloadTiles" + "identify" + | "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "data.similar" diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 6ba7b40fa6..6a1d285245 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -509,20 +509,22 @@ impl From<&str> for Failure { /// Adapter-owned presentation state for one already-admitted archive command. Execution /// authority stays in the engine's ReadAhead/Read, never in this result formatter. -#[cfg(not(target_arch = "wasm32"))] pub(crate) struct CommandCompletion { before: Vec<(String, Vec)>, said: Said, } -#[cfg(not(target_arch = "wasm32"))] impl CommandCompletion { pub(crate) fn capture(s: &Session) -> Self { Self { before: layer_snap(s), said: Said::now(s) } } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn finish(self, s: &mut Session, result: Result) -> Result { + self.finish_with_budget(s, result, DEFAULT_OUTPUT_TOKENS) + } + pub(crate) fn finish_with_budget(self, s: &mut Session, result: Result, tokens: usize) -> Result { result - .map(|value| command_result(s, value, &self.before, &self.said, DEFAULT_OUTPUT_TOKENS)) - .map_err(|e| error_with_notices(e, s, &self.said, DEFAULT_OUTPUT_TOKENS)) + .map(|value| command_result(s, value, &self.before, &self.said, tokens)) + .map_err(|e| error_with_notices(e, s, &self.said, tokens)) } } diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index cee173fd23..7d057e9b22 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -176,7 +176,7 @@ group.scaleRange group min? max? group.set group name? visible? transparency? group.setParent group parent before? group.ungroup group -identify lon lat tolerancePx? mode? +identify lon lat tolerancePx? defer? mode? identify.featureInfo layer lon? lat? text? url? capabilities? request? imagery.hostedImagery layer path minZoom? maxZoom? imagery.mesh layer path? step? diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0494af599a..ee30be8c5f 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -161,6 +161,12 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: } _ => None, }; + let overview_surface = match &elevation { + Elevation::Surface(name) if !new_rows.is_empty() => { + surface_layer(s, name).filter(|l| l.raster.as_ref().is_some_and(|r| r.reads_in_place())).map(|l| l.name.clone()) + } + _ => None, + }; let z_of = |s: &Session, g: &Geometry| -> Result, String> { match &elevation { Elevation::None => Ok(None), @@ -310,6 +316,15 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: archive.drain(..drop); } } + if let Some(name) = overview_surface { + s.notify_text( + crate::notice_text::NoticeText::format( + "{layer}: surface elevation for {count} added features uses the overview's values, not full-resolution samples", + [("layer", name.into()), ("count", zs.len().to_string().into())], + ), + false, + ); + } let e = s.edit_counts.entry(id).or_default(); e.added += counts.added; e.modified += counts.modified; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 0de1ae403e..a482e65702 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1423,6 +1423,19 @@ fn spectral(s: &mut Session, p: &Value) -> CmdResult { (false, false) => None, }; let v = spectral_read(s, p, &r, zone)?; + if s.map().layer(s.layer_id(p)?).is_some_and(|l| l.raster.as_ref().is_some_and(|r| r.reads_in_place())) { + let kind = if zone.is_some() { "spectral zone" } else { "spectral point" }; + s.notify_text( + crate::notice_text::NoticeText::format( + "{layer}: 1 {kind} read uses the overview's values, not full-resolution samples", + [ + ("layer", s.map().layer(s.layer_id(p)?).map(|l| l.name.clone()).unwrap_or_else(|| r.name.clone()).into()), + ("kind", crate::notice_text::NoticeText::term(kind)), + ], + ), + false, + ); + } if let Some(what) = left_out { let read = if zone.is_some() { "the zone's mean is read" } else { "points are read" }; s.notify(format!("{}: {what} left out: {read}", r.name), false); diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 8f474a32c3..f4ac387ff0 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1902,7 +1902,7 @@ fn geotiff_note(r: &Raster, bi: usize, cog: bool, band_hint: &str) -> Result String { +pub(super) fn pixel_text(v: f32) -> String { if v == 0.0 || (1e-5..1e16).contains(&v.abs()) { v.to_string() } else { format!("{v:e}") } } @@ -1926,6 +1926,9 @@ pub fn pixels_at(s: &Session, lon: f64, lat: f64, keep: impl Fn(&rustgis_map::La let pixels = drawn.filter(|(_, l)| l.is_raster() && keep(l) && map.draws_at(l, scale)).filter_map(|(i, l)| { let r = l.raster.as_ref()?.data.as_ref()?; let (col, row) = r.pixel_at(c)?; + if l.raster.as_ref().is_some_and(|r| r.reads_in_place()) { + return Some((i, json!({"layer": l.name, "layerId": l.id, "raster": true, "pixelState": "pending"}))); + } let vals: Vec> = (0..r.band_count()).map(|b| r.value(b, col, row)).collect(); if vals.iter().all(Option::is_none) { return None; diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 28a294a04d..9690756c52 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -39,7 +39,25 @@ pub struct Read { pub(crate) struct ReadWork { name: &'static str, key: String, - work: Box Box + Send>, + work: Work, +} + +type Answer = Box; +#[cfg(target_arch = "wasm32")] +type AsyncWork = Box) + Send>; +enum Work { + Blocking(Box Answer + Send>), + #[cfg(target_arch = "wasm32")] + Async(AsyncWork), +} +impl Work { + fn run(self) -> Result { + match self { + Self::Blocking(work) => Ok(work()), + #[cfg(target_arch = "wasm32")] + Self::Async(_) => Err("use the asynchronous read path in the browser".into()), + } + } } #[cfg(not(target_arch = "wasm32"))] @@ -165,6 +183,33 @@ impl ReadAhead { rustgis_data::raster::crs::waiting_for_grids(|| self.run(control)) } + /// Runs an asynchronous admitted read without holding the browser thread. The callback + /// returns the same owned read record as `run`; landing still validates its original owner. + #[cfg(target_arch = "wasm32")] + pub fn run_async(self, then: Box) + Send>) { + let ReadAhead { op, owner, source, work, room, reservation, .. } = self; + if let Err(error) = owner.check() { + then(Err(error)); + return; + } + let Some(ReadWork { key, work, .. }) = work else { + then(Ok(Read { op, owner, source, ready: None, inputs: Vec::new(), room, reservation })); + return; + }; + let Work::Async(work) = work else { + then(Err("this read has no asynchronous browser path".into())); + return; + }; + let current = owner.clone(); + let still = std::sync::Arc::new(move || current.check().is_ok()); + let done = Box::new(move |value| { + let result = + owner.check().map(|_| Read { op, owner, source, ready: Some(Ready { key, value }), inputs: Vec::new(), room, reservation }); + then(result); + }); + crate::render::rustgis_tiles::cache::with_still(still, || work(done)); + } + /// Reads, blocking until it's done; `control` stops it and counts its progress (see /// [`rustgis_analysis::control`]). A read that fails gives its failure to the command, which /// says it as it would have; only a cancelled run (or a bug in a reader) is an error here. @@ -179,14 +224,16 @@ impl ReadAhead { let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { crate::render::rustgis_tiles::cache::with_still(still, || { rustgis_analysis::run_under(name, control, || { - ready = work.map(|ReadWork { key, work, .. }| { - // History set aside for this edit is freed just before it copies. - let value = match &room { - Some(room) => rustgis_data::before_rows_copy(room.free_on_copy(), work).0, - None => work(), - }; - Ready { key, value } - }); + ready = work + .map(|ReadWork { key, work, .. }| { + // History set aside for this edit is freed just before it copies. + let value = match &room { + Some(room) => rustgis_data::before_rows_copy(room.free_on_copy(), || work.run()).0, + None => work.run(), + }?; + Ok::<_, String>(Ready { key, value }) + }) + .transpose()?; Ok(()) }) }) @@ -255,6 +302,7 @@ pub fn read_ahead_scanned(s: &mut Session, p: &Value, scan: super::qgis::ImportS /// (`edit::TABLE_EDITS`). The cancel tests (`tests/cancellation.rs`) exercise every one, or name /// why not. pub(crate) const IN_BACKGROUND: &[(&str, &str)] = &[ + ("identify", "Read Full-resolution Pixels"), ("service.layers", "List Service Layers"), ("service.add", "Add Service Layer"), ("layer.addData", "Add Data"), @@ -299,6 +347,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu let CommandOp::Registered { spec, params } = op.op() else { return Err("not a registered read command".into()) }; let name = in_background(spec.id).ok_or_else(|| not_in_background(spec.id))?; let (work, source) = match spec.id { + "identify" => (super::select::identify_ahead(s, params)?, None), "service.layers" => { #[cfg(not(target_arch = "wasm32"))] let work = super::service::listing_ahead(s, params)?; @@ -409,7 +458,14 @@ pub fn archive_target(s: &Session, p: &Value) -> Option<(usize, rustgis_map::Til /// `work` as a read for the command to take under `key`. pub(crate) fn ahead(name: &'static str, key: String, work: impl FnOnce() -> T + Send + 'static) -> ReadWork { - ReadWork { name, key, work: Box::new(move || Box::new(work()) as Box) } + let still = crate::render::rustgis_tiles::cache::current_still(); + ReadWork { + name, + key, + work: Work::Blocking(Box::new(move || { + crate::render::rustgis_tiles::cache::with_optional_still(still, || Box::new(work()) as Answer) + })), + } } #[cfg(not(target_arch = "wasm32"))] @@ -422,6 +478,22 @@ pub(crate) fn taking(s: &mut Session, key: &str, value: T, ru result.unwrap_or_else(|panic| std::panic::resume_unwind(panic)) } +#[cfg(target_arch = "wasm32")] +pub(crate) fn ahead_async( + name: &'static str, + key: String, + start: impl FnOnce(Box) + Send + 'static, +) -> ReadWork { + let still = crate::render::rustgis_tiles::cache::current_still(); + ReadWork { + name, + key, + work: Work::Async(Box::new(move |done| { + crate::render::rustgis_tiles::cache::with_optional_still(still, || start(Box::new(move |answer| done(Box::new(answer))))) + })), + } +} + /// The read placed for `key`, taken: `None` when none was, so the caller reads here. pub(crate) fn take(s: &mut Session, key: &str) -> Option { if s.read_ahead.as_ref().is_none_or(|r| r.key != key) { diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index d65307e743..ee5cbfac51 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -88,8 +88,8 @@ pub fn commands() -> Vec { Ok(json!({"layer": nid})) }).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?: name|id (default: the active layer, which need not be the layer last selected in)}"#) .when(need_selection), - C::new("identify", "Identify", "Home › Inspect", identify).roles(&[]).effects(crate::policy::Effects::NONE).view().params( - r#"{"lon", "lat", "tolerancePx"?, "mode"?: "topmost"|"visible"|"selectable"|"selectedInContents"|"none" (the map's pop-up mode when omitted; the mode picks the layers, and every feature under the point in them, up to 100, is in "results"; topmost and visible take each raster's pixel there too (with "raster": true), ranked with the features by the drawing order, so a raster drawn over a polygon answers for it (a pixel found alone answers without "results"), while selectable and selectedInContents give the topmost raster's pixel only when no feature is found; topmost and visible take vector tile layers' features too, with "tileLayer" and "sourceLayer", from the tiles drawn there: one not loaded yet is asked for, and its features come on a later identify; and they list in "featureInfo" the WMS layers drawn there to ask, each {tileLayer, url} (its GetFeatureInfo request) or {tileLayer, capabilities} (its service's, when the layer doesn't know its request): identify.featureInfo reads what they answer; selectedInContents does both for the tile layer picked in the Layers pane (map.selectTiles) alone, whichever it is, a basemap or MapLibre style too)}"#, + C::new("identify", "Identify", "Home › Inspect", identify).inputs(identify_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view().params( + r#"{"lon", "lat", "tolerancePx"?, "defer"?: bool (default false: wait for level-zero values of all bands of in-place rasters; pixelState is value, no-data or failed, rounded counts bands rounded to f32; true returns pending candidates without numbers or file reads, for an admitted asynchronous identify read), "mode"?: "topmost"|"visible"|"selectable"|"selectedInContents"|"none" (the map's pop-up mode when omitted; the mode picks the layers, and every feature under the point in them, up to 100, is in "results"; topmost and visible take each raster's pixel there too (with "raster": true), ranked with the features by the drawing order, so a raster drawn over a polygon answers for it (a pixel found alone answers without "results"), while selectable and selectedInContents give the topmost raster's pixel only when no feature is found; topmost and visible take vector tile layers' features too, with "tileLayer" and "sourceLayer", from the tiles drawn there: one not loaded yet is asked for, and its features come on a later identify; and they list in "featureInfo" the WMS layers drawn there to ask, each {tileLayer, url} (its GetFeatureInfo request) or {tileLayer, capabilities} (its service's, when the layer doesn't know its request): identify.featureInfo reads what they answer; selectedInContents does both for the tile layer picked in the Layers pane (map.selectTiles) alone, whichever it is, a basemap or MapLibre style too)}"#, ), C::new("map.popupMode", "Pop-up Mode", "Home › Navigate", popup_mode).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"mode": "topmost"|"visible"|"selectable"|"selectedInContents"|"none"}"#), @@ -361,7 +361,64 @@ fn at_point(s: &mut Session, p: &Value) -> CmdResult { /// The most features one identify reports, so a click on a dense spot stays quick. const MAX_IDENTIFIED: usize = 100; +fn identify_inputs(s: &super::InputContext<'_>, p: &Value) -> Result { + if ps(p, "mode").and_then(PopupMode::from_code).unwrap_or(s.map().popup_mode) == PopupMode::None { + return Ok(super::Inputs::layers(std::iter::empty())); + } + let point = Coord::new(f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); + let map = s.map(); + Ok(super::Inputs::layers( + map.layers + .iter() + .filter(|l| { + map.draws_at(l, s.scale()) + && (!l.is_raster() || l.raster.as_ref().and_then(|r| r.data.as_ref()).is_some_and(|r| r.pixel_at(point).is_some())) + }) + .map(|l| (map, l)), + )) +} + fn identify(s: &mut Session, p: &Value) -> CmdResult { + if super::b(p, "defer") == Some(true) { + return identify_candidates(s, p); + } + let prepared = match super::reads::take::>(s, &point::key(p)) { + Some(prepared) => prepared?, + None => { + let plan = point::prepare(s, p)?; + #[cfg(not(target_arch = "wasm32"))] + if plan.needs_read() && s.statistics_window_thread == Some(std::thread::current().id()) { + return Err("full-resolution identify needs the desktop background read queue; run identify directly instead of inside this command".into()); + } + plan.read()? + } + }; + prepared.land(s) +} + +pub(crate) fn identify_ahead(s: &mut Session, p: &Value) -> Result, String> { + if super::b(p, "defer") == Some(true) { + return Ok(None); + } + let plan = point::prepare(s, p)?; + if !plan.needs_read() { + return Ok(None); + } + let key = point::key(p); + #[cfg(not(target_arch = "wasm32"))] + { + Ok(Some(super::reads::ahead("Read Full-resolution Pixels", key, move || plan.read()))) + } + #[cfg(target_arch = "wasm32")] + { + Ok(Some(super::reads::ahead_async("Read Full-resolution Pixels", key, move |done| plan.read_async(done)))) + } +} + +#[path = "select_point.rs"] +mod point; + +fn identify_candidates(s: &mut Session, p: &Value) -> CmdResult { let mode = match ps(p, "mode") { Some(m) => PopupMode::from_code(m).ok_or_else(|| format!("unknown pop-up mode '{m}'"))?, None => s.map().popup_mode, diff --git a/crates/engine/src/cmd/select_point.rs b/crates/engine/src/cmd/select_point.rs new file mode 100644 index 0000000000..b16cf4d249 --- /dev/null +++ b/crates/engine/src/cmd/select_point.rs @@ -0,0 +1,346 @@ +//! Full-resolution identify reads retain their source identity across background completion. +use super::*; +use crate::image_grid::Source; +use crate::render::rustgis_tiles::cog; + +pub(super) fn key(p: &Value) -> String { + format!("identify:{p}") +} + +pub(super) struct Prepared { + info: Value, + sources: Vec, +} +struct Pick { + id: u32, + path: String, + names: Vec, +} +pub(super) struct Plan { + prepared: Prepared, + picks: Vec, + at: Coord, +} + +pub(super) fn prepare(s: &mut Session, p: &Value) -> Result { + let info = identify_candidates(s, p)?; + let mut picks = Vec::new(); + let mut sources = Vec::new(); + let results = info.get("results").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_else(|| std::slice::from_ref(&info)); + for value in results { + if value["pixelState"] != "pending" { + continue; + } + let id = value["layerId"].as_u64().and_then(|i| u32::try_from(i).ok()).ok_or("no pixel layer")?; + let layer = s.map().layer(id).ok_or("no pixel layer")?; + let raster = layer.raster.as_ref().ok_or("no raster")?; + picks.push(Pick { + id, + path: crate::service_logins::fetch_url( + s.web_logins.is_anonymous(), + raster.path.as_deref().ok_or("the in-place raster has no source file")?, + ), + names: raster.data.as_ref().map(|r| r.bands.iter().map(|b| b.name.clone()).collect()).unwrap_or_default(), + }); + sources.push(Source::capture(s, id)?); + } + Ok(Plan { prepared: Prepared { info, sources }, picks, at: Coord::new(f(p, "lon").unwrap_or(0.), f(p, "lat").unwrap_or(0.)) }) +} + +impl Prepared { + pub(super) fn land(self, s: &mut Session) -> CmdResult { + if self.sources.iter().any(|source| !source.current(s)) { + return Err("the identified raster changed while its pixel was being read; identify again".into()); + } + let values = + self.info.get("results").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_else(|| std::slice::from_ref(&self.info)); + let count: u64 = values.iter().filter_map(|v| v["rounded"].as_u64()).sum(); + if count > 0 { + let layers = values + .iter() + .filter(|v| v["rounded"].as_u64().unwrap_or(0) > 0) + .filter_map(|v| v["layer"].as_str()) + .collect::>() + .join(", "); + s.notify_loss( + rustgis_data::loss::LossCode::ChangedRounded, + NoticeText::format( + "{count} full-resolution band values rounded to f32 at the identified point in {layers}", + [("count", count.to_string().into()), ("layers", layers.into())], + ), + ); + } + Ok(self.info) + } + fn answer(&mut self, pick: &Pick, answer: Result, String>) { + fn set(value: &mut Value, pick: &Pick, answer: &Result, String>) { + if value["layerId"].as_u64() != Some(u64::from(pick.id)) || value["pixelState"] != "pending" { + return; + } + match answer { + Ok(Some(point)) => { + value["pixelState"] = json!(if point.values.iter().all(Option::is_none) { "no-data" } else { "value" }); + let mut attrs = serde_json::Map::new(); + for (i, v) in point.values.iter().enumerate() { + let name = pick.names.get(i).cloned().unwrap_or_else(|| format!("Band {}", i + 1)); + attrs.insert(name, json!(v.map(super::super::raster::pixel_text).unwrap_or_else(|| "NoData".into()))); + } + attrs.insert("Pixel".into(), json!(format!("{}, {}", point.col, point.row))); + value["attributes"] = Value::Object(attrs); + value["rounded"] = json!(point.rounded.iter().filter(|r| **r).count()); + } + Ok(None) => { + value["pixelState"] = json!("no-data"); + } + Err(error) => { + value["pixelState"] = json!("failed"); + value["pixelError"] = json!(error); + } + } + } + set(&mut self.info, pick, &answer); + if let Some(results) = self.info.get_mut("results").and_then(Value::as_array_mut) { + for value in results { + set(value, pick, &answer); + } + } + } +} +impl Plan { + pub(super) fn needs_read(&self) -> bool { + !self.picks.is_empty() + } + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn read(mut self) -> Result { + rustgis_data::progress::begin(self.picks.len()); + for pick in &self.picks { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let answer = cog::point_from_file_blocking(pick.path.clone(), self.at); + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; + self.prepared.answer(pick, answer); + } + Ok(self.prepared) + } + #[cfg(target_arch = "wasm32")] + pub(super) fn read(self) -> Result { + if self.picks.is_empty() { + Ok(self.prepared) + } else { + Err("full-resolution identify must use the asynchronous read path in the browser".into()) + } + } + #[cfg(target_arch = "wasm32")] + pub(super) fn read_async(mut self, done: Box) + Send>) { + let Some(pick) = self.picks.pop() else { + done(Ok(self.prepared)); + return; + }; + let path = pick.path.clone(); + let at = self.at; + cog::point_from_file( + path, + at, + Box::new(move |answer| { + self.prepared.answer(&pick, answer); + self.read_async(done); + }), + ); + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, cogwrite}; + use rustgis_map::raster::RasterLayer; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + struct File(std::path::PathBuf); + impl Drop for File { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + fn fixture() -> Result<(Session, u32, File), String> { + let file = File(std::env::temp_dir().join(format!( + "rustgis-identify-point-{}-{}.tif", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ))); + let full = Raster::new( + "image", + 4, + 4, + (0..3).map(|b| (0..16).map(|i| if i == 0 { -999. } else { 10600. + (i + b * 100) as f32 }).collect()).collect(), + GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 0.01, pixel_height: -0.01 }, + Crs::LonLat, + Some(-999.), + ColorHint::Rgb { alpha: false }, + "Float32", + ) + .map_err(|e| e.to_string())?; + std::fs::write(&file.0, cogwrite::write(&full, 0).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + let overview = Raster::new( + "overview", + 2, + 2, + vec![vec![7., -999., 8., 9.]; 3], + GeoTransform { pixel_width: 0.02, pixel_height: -0.02, ..full.transform }, + Crs::LonLat, + Some(-999.), + ColorHint::Rgb { alpha: false }, + "Float32", + ) + .map_err(|e| e.to_string())?; + let mut layer = RasterLayer::from_path(overview, file.0.display().to_string()); + layer.in_place = true; + let mut s = Session::new(crate::Project::default()); + let id = s.map_mut().add_raster("image", layer); + Ok((s, id, file)) + } + #[test] + fn full_resolution_identify_ignores_the_overviews_values_and_holes() { + let (mut s, id, _file) = fixture().unwrap(); + let depth = s.undo_depth(); + for (lon, lat, state, value, pixel) in [(10.005, 45.995, "no-data", "NoData", "0, 0"), (10.025, 45.995, "value", "10602", "2, 0")] { + let params = json!({"lon":lon,"lat":lat}); + let mut deferred = params.clone(); + deferred["defer"] = json!(true); + let pending = s.run("identify", &deferred).unwrap(); + assert_eq!(pending["pixelState"], "pending"); + assert!(pending.get("attributes").is_none()); + let answer = s.run("identify", ¶ms).unwrap(); + assert_eq!(answer["layerId"], id); + assert!(answer.get("results").is_none(), "a single answer has no results wrapper"); + assert_eq!(answer["pixelState"], state); + assert_eq!(answer["attributes"]["Band 1"], value); + assert_eq!(answer["attributes"]["Pixel"], pixel); + assert_eq!(answer["rounded"], 0); + } + assert_eq!(s.undo_depth(), depth); + let raster = s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap(); + raster.in_place = false; + assert!(s.run("identify", &json!({"lon":10.025,"lat":45.995})).unwrap().is_null()); + assert_eq!(s.run("identify", &json!({"lon":10.005,"lat":45.995})).unwrap()["attributes"]["Band 1"], "7"); + } + #[test] + fn full_resolution_identify_read_ahead_keeps_its_request_ceiling() { + let (mut s, _, _file) = fixture().unwrap(); + let params = json!({"lon":10.025,"lat":45.995}); + assert_eq!(s.run("identify", ¶ms).unwrap()["attributes"]["Band 1"], "10602"); + let ahead = + crate::render::rustgis_tiles::cache::held_to_public(true, || crate::cmd::reads::read_ahead(&mut s, "identify", ¶ms)) + .unwrap(); + let done = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + let value = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(value["pixelState"], "failed"); + assert!(value.get("attributes").is_none()); + assert_eq!(s.run("identify", ¶ms).unwrap()["attributes"]["Band 1"], "10602"); + } + + #[test] + fn full_resolution_identify_refuses_unprepared_io_on_the_window_thread() { + let (mut s, _, _file) = fixture().unwrap(); + s.statistics_need_read_ahead(true); + let params = json!({"lon":10.025,"lat":45.995}); + let error = s.run("identify", ¶ms).unwrap_err(); + assert!(error.contains("background read queue"), "{error}"); + let ahead = crate::cmd::reads::read_ahead(&mut s, "identify", ¶ms).unwrap(); + let done = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + assert_eq!(crate::cmd::reads::read_land(&mut s, done).unwrap()["attributes"]["Band 1"], "10602"); + } + + #[test] + fn deferred_identify_cannot_start_file_reads_through_read_ahead() { + let (mut s, _, _file) = fixture().unwrap(); + let params = json!({"lon":10.025,"lat":45.995,"defer":true}); + let ahead = crate::cmd::reads::read_ahead(&mut s, "identify", ¶ms).unwrap(); + assert!(!ahead.reads(), "defer has no file effect and must prepare no source I/O"); + let answer = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + let value = crate::cmd::reads::read_land(&mut s, answer).unwrap(); + assert_eq!(value["pixelState"], "pending"); + assert!(value.get("attributes").is_none()); + } + + #[test] + fn full_resolution_identify_failure_never_uses_the_overview() { + let (mut s, id, file) = fixture().unwrap(); + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().path = Some(format!("{}.missing.tif", file.0.display())); + let answer = s.run("identify", &json!({"lon":10.005,"lat":45.995})).unwrap(); + assert_eq!(answer["pixelState"], "failed"); + assert!(answer["pixelError"].as_str().is_some()); + assert!(answer.get("attributes").is_none()); + } + #[test] + fn full_resolution_identify_read_ahead_rejects_replaced_sources() { + let (mut s, id, _file) = fixture().unwrap(); + let params = json!({"lon":10.025,"lat":45.995}); + let ahead = crate::cmd::reads::read_ahead(&mut s, "identify", ¶ms).unwrap(); + let done = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = None; + assert!(crate::cmd::reads::read_land(&mut s, done).is_err()); + } + #[test] + fn spectral_overview_notices_are_counted_and_absent_for_whole_layers() { + let (mut s, id, _file) = fixture().unwrap(); + for in_place in [true, false] { + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().in_place = in_place; + let mark = s.notice_mark(); + s.run("raster.spectral", &json!({"layer":id,"lon":10.005,"lat":45.995})).unwrap(); + let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("overview's values")).collect(); + assert_eq!(notices.len(), usize::from(in_place)); + if in_place { + assert!(notices[0].text.contains("image: 1 spectral point read")); + } + } + } + #[test] + fn spectral_zone_and_surface_elevation_say_when_they_use_overviews() { + for in_place in [true, false] { + let (mut s, id, _file) = fixture().unwrap(); + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().in_place = in_place; + s.run("layer.template", &json!({"template":"polygons","name":"zone"})).unwrap(); + s.run("edit.addFeature", &json!({"layer":"zone","geometry":{"type":"Polygon","coordinates":[[[10.,46.],[10.04,46.],[10.04,45.96],[10.,45.96],[10.,46.]]]}})).unwrap(); + let mark = s.notice_mark(); + s.run("raster.spectral", &json!({"layer":id,"zone":"zone"})).unwrap(); + let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("overview's values")).collect(); + assert_eq!(notices.len(), usize::from(in_place)); + if in_place { + assert!(notices[0].text.contains("image: 1 spectral zone read")); + } + s.run("layer.template", &json!({"template":"points","name":"points"})).unwrap(); + s.run("edit.elevation", &json!({"mode":"surface","surface":"image"})).unwrap(); + let mark = s.notice_mark(); + s.run("edit.addFeature", &json!({"layer":"points","geometry":{"type":"Point","coordinates":[10.005,45.995]}})).unwrap(); + let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("overview's values")).collect(); + assert_eq!(notices.len(), usize::from(in_place)); + if in_place { + assert!(notices[0].text.contains("image: surface elevation for 1 added features")); + } + let points = s.map().layer_by_name("points").unwrap(); + assert_eq!(points.dataset.value(0, points.dataset.field_index("z").unwrap()).as_f64(), Some(7.)); + } + } + #[test] + fn full_resolution_identify_keeps_visible_layers_in_draw_order() { + let (mut s, id, _file) = fixture().unwrap(); + let layer = s.map().layer(id).unwrap().raster.clone().unwrap(); + let second = s.map_mut().add_raster("second", layer); + s.run("layer.priority", &json!({"layer":id,"value":100})).unwrap(); + let answer = s.run("identify", &json!({"lon":10.025,"lat":45.995,"mode":"visible"})).unwrap(); + let found: Vec<_> = answer["results"].as_array().unwrap().iter().map(|v| v["layerId"].as_u64().unwrap() as u32).collect(); + let drawn: Vec<_> = s + .map() + .draw_order() + .iter() + .filter_map(|d| match d { + rustgis_map::Drawn::Layer(i) => Some(s.map().layers[*i].id), + _ => None, + }) + .collect(); + assert_eq!(found, drawn); + assert!(found.contains(&second)); + for value in answer["results"].as_array().unwrap() { + assert_eq!(value["attributes"]["Band 1"], "10602"); + } + } +} diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 79743d6af6..b2810d8278 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -123,12 +123,13 @@ impl Session { } let CallKind::Command { id, params } = &call.kind else { return Err( - "only standalone archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() + "only standalone identify, archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() ); }; if !matches!( id.as_str(), - "map.reloadTiles" + "identify" + | "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "data.similar" @@ -138,7 +139,7 @@ impl Session { | "layer.sizeBy" ) { return Err( - "only standalone archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() + "only standalone identify, archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() ); } let capture = |s: &mut Session| s.capture_read(id, params); diff --git a/crates/engine/src/policy/effects.rs b/crates/engine/src/policy/effects.rs index b8f2725ae0..0db6c3ec44 100644 --- a/crates/engine/src/policy/effects.rs +++ b/crates/engine/src/policy/effects.rs @@ -141,6 +141,20 @@ pub(super) fn command(s: &crate::cmd::InputContext<'_>, spec: &CommandSpec, para } } } + if spec.id == "identify" + && params.get("defer").and_then(Value::as_bool) != Some(true) + && let Some(select) = spec.inputs + && let Ok(inputs) = select(s, params) + { + for (map, id) in inputs.layers { + if let Some(layer) = s.project.maps.iter().find(|m| m.instance_id() == map).and_then(|m| m.layer(id)) + && layer.raster.as_ref().is_some_and(|r| r.reads_in_place()) + && let Some(path) = layer.raster.as_ref().and_then(|r| r.path.as_deref()) + { + effects = effects.with(if rustgis_data::source::is_remote_name(path) { Effect::Network } else { Effect::Files }); + } + } + } if spec.id == "layer.loadAll" && let Some(source) = layer.and_then(|layer| layer.source.as_ref()) { diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 518cb6d83a..dd0fe2896e 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -246,6 +246,17 @@ pub(super) fn long_commands(boundaries: bool) { } // Original TIFF headers share the read queue and both cancellation sweeps. read(&s, "raster.imageGrid", &json!({"layer": dem})); + { + let mut point = Session::new(s.project.clone()); + let id = point.map().layers.iter().find(|l| l.name == dem).unwrap().id; + let layer = point.map_mut().layer_mut(id).unwrap(); + let raster = layer.raster.as_mut().unwrap(); + raster.in_place = true; + raster.path = Some(out("tile.tif")); + let r = raster.data.as_ref().unwrap(); + let at = r.crs.transformer().unwrap().to_lonlat(r.transform.to_world(0.5, 0.5)).unwrap(); + read(&point, "identify", &json!({"lon": at.x, "lat": at.y, "mode": "visible"})); + } // A PDF's page is read on the same queue: the file, then its drawing, Cancel looked at between // (#2336). // A small page: the sweep draws, measures and compares all its pixels at each check. At 50 mm it diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index d08c3ba21b..fb42565921 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1040,6 +1040,129 @@ fn with_stretch(info: Arc, file: String, look: Look, then: StretchThen) { ); } +/// A level-zero pixel, all bands in file order. Missing samples are `None`; precision lost +/// converting a stored sample to f32 is marked on that band. Unrepresentable samples are errors. +#[derive(Clone, Debug, PartialEq)] +pub struct Point { + pub col: u32, + pub row: u32, + pub values: Vec>, + pub rounded: Vec, +} + +/// Opens a point's source and reads it without blocking the caller, including in the browser. +pub fn point_from_file(file: String, lonlat: Coord, then: Box, String>) + Send>) { + let path = file.clone(); + with_any_info( + &path, + Box::new(move |answer| match answer { + Ok(info) => read_point(info, file, lonlat, then), + Err(error) => then(Err(error)), + }), + ); +} + +/// Reads one point asynchronously, on desktop or in the browser. It fetches each required +/// chunk once, including files whose band planes are stored separately. The callback receives +/// `None` only outside the full-resolution grid; an in-grid no-data pixel still has a Point. +pub fn read_point(info: Arc, file: String, lonlat: Coord, then: Box, String>) + Send>) { + let Some(level) = info.layout.levels.first() else { + then(Err("no full-resolution grid".into())); + return; + }; + let Some(world) = info.transformer.from_lonlat(lonlat) else { + then(Err("the point cannot be transformed to the image coordinate system".into())); + return; + }; + let (mut col, row) = info.layout.transform.to_pixel(world); + if info.transformer.is_geographic() && !(0.0..f64::from(level.width)).contains(&col) { + let turn = 360.0 / info.layout.transform.pixel_width.abs(); + let wrapped = col.rem_euclid(turn); + if wrapped < f64::from(level.width) { + col = wrapped; + } + } + let (col, row) = (col.floor(), row.floor()); + if !(col >= 0.0 && row >= 0.0 && col < f64::from(level.width) && row < f64::from(level.height)) { + then(Ok(None)); + return; + } + let (col, row) = (col as u32, row as u32); + let (tw, th) = (level.tile_width.max(1), level.tile_height.max(1)); + let samples = u64::from(tw).saturating_mul(u64::from(th)).saturating_mul(info.layout.bands.max(1) as u64); + let limit = rustgis_data::memory::planned(4 << 20, 64 << 20, 8) as u64; + if samples > limit { + then(Err(format!( + "the point needs {samples} decoded tile samples; this memory budget allows {limit}; use a file with smaller tiles" + ))); + return; + } + let Some(tile) = (row / th).checked_mul(level.across()).and_then(|t| t.checked_add(col / tw)) else { + then(Err("the point's tile index is too large".into())); + return; + }; + let index = (row % th) as usize * tw as usize + (col % tw) as usize; + let bands = (0..info.layout.bands.max(1)).collect(); + let nodata = info.layout.nodata.map(|v| v as f32); + fetch_bands( + info, + split(&file).0.to_string(), + 0, + vec![tile], + bands, + Box::new(move |answer| { + then(answer.and_then(|picked| { + let picked = picked.first().ok_or("the point's tile was not read")?; + let mut values = Vec::with_capacity(picked.len()); + let mut rounded = Vec::with_capacity(picked.len()); + for (chunk, band) in picked { + let value = *chunk.get(*band).and_then(|v| v.get(index)).ok_or("the point's sample was not read")?; + if !value.is_finite() && chunk.rounded_at(*band, index) { + return Err( + "the point has a sample outside f32 range or masked by rounding onto no-data; its value cannot be shown".into(), + ); + } + values.push((value.is_finite() && Some(value) != nodata).then_some(value)); + rounded.push(chunk.rounded_at(*band, index)); + } + Ok(Some(Point { col, row, values, rounded })) + })); + }), + ); +} + +/// Opens a point's source and waits on a worker, checking Cancel during the header read too. +#[cfg(not(target_arch = "wasm32"))] +pub fn point_from_file_blocking(file: String, lonlat: Coord) -> Result, String> { + wait_for_point(|done| point_from_file(file, lonlat, done)) +} + +/// Waits for [`read_point`] on a worker. Cancel is checked while waiting; a single chunk's +/// decode cannot be interrupted. The browser uses the callback API instead of blocking. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_point_blocking(info: Arc, file: String, lonlat: Coord) -> Result, String> { + wait_for_point(|done| read_point(info, file, lonlat, done)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_point(start: impl FnOnce(Box, String>) + Send>)) -> Result, String> { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let (tx, rx) = std::sync::mpsc::channel(); + start(Box::new(move |answer| { + let _ = tx.send(answer); + })); + let started = Instant::now(); + loop { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + match rx.recv_timeout(Duration::from_millis(50)) { + Ok(answer) => return answer, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return Err("the point read ended without an answer".into()), + Err(_) if started.elapsed() >= Duration::from_secs(120) => return Err("the point was not read in two minutes".into()), + Err(_) => {} + } + } +} + /// The bands of a tile a look shows: for each, the decoded chunk holding it and its place there. type Picked = Vec<(Bands, usize)>; @@ -2189,6 +2312,70 @@ fn read_strips( #[cfg(test)] mod tests { + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn full_resolution_points_read_all_band_planes_and_mark_precision() { + let _turn = crate::cache::turn(); + for (planar, wide) in [(false, false), (true, false), (false, true), (true, true)] { + let file = Arc::new(cog::example_with(&cog::Example { size: 64, tile: 16, bands: 3, planar, wide, ..cog::Example::default() })); + let bytes = file.clone(); + crate::cache::set_fetcher(move |url, done| { + let (a, b) = crate::cache::split_range(&url).1.unwrap(); + done(Ok(bytes[a as usize..((b + 1) as usize).min(bytes.len())].to_vec())); + }); + let url = format!("https://point-reader.example/{planar}-{wide}.tif"); + let info = info_blocking(&url).unwrap(); + let at = info.transformer.to_lonlat(info.layout.transform.to_world(1.5, 0.5)).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + read_point(info.clone(), url.clone(), at, Box::new(move |answer| tx.send(answer).unwrap())); + let point = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap().unwrap(); + assert_eq!((point.col, point.row), (1, 0)); + assert_eq!( + point.values, + if wide { vec![Some(16_777_216.), Some(16_777_228.), Some(16_777_236.)] } else { vec![Some(1.), Some(11.), Some(21.)] } + ); + assert_eq!(point.rounded, vec![wide; 3]); + let clean_at = info.transformer.to_lonlat(info.layout.transform.to_world(2.5, 0.5)).unwrap(); + let clean = read_point_blocking(info.clone(), url.clone(), clean_at).unwrap().unwrap(); + assert_eq!(clean.rounded, vec![false; 3]); + assert!(read_point_blocking(info, url.clone(), Coord::new(0., 0.)).unwrap().is_none()); + forget_file(&url); + } + crate::cache::clear_fetcher(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn full_resolution_points_distinguish_no_data_from_values_lost_in_f32() { + let _turn = crate::cache::turn(); + let mut file = cog::example_with(&cog::Example { size: 32, tile: 16, wide: true, int8: true, ..cog::Example::default() }); + // Replace the example's no-data tag with the exact even Int32 value. Adjacent odd + // samples round onto it: the decoder marks that loss separately from real no-data. + let ifd = u32::from_le_bytes(file[4..8].try_into().unwrap()) as usize; + let n = u16::from_le_bytes(file[ifd..ifd + 2].try_into().unwrap()) as usize; + let tag = (0..n).map(|i| ifd + 2 + i * 12).find(|i| u16::from_le_bytes(file[*i..*i + 2].try_into().unwrap()) == 42113).unwrap(); + let marker = b"16777424\0"; + let at = file.len() as u32; + file[tag + 4..tag + 8].copy_from_slice(&(marker.len() as u32).to_le_bytes()); + file[tag + 8..tag + 12].copy_from_slice(&at.to_le_bytes()); + file.extend_from_slice(marker); + let file = Arc::new(file); + serve_strips(file, Arc::new(AtomicU64::new(u64::MAX)), 0); + let url = "https://point-reader.example/precision-no-data.tif"; + let info = info_blocking(url).unwrap(); + let at = |x| info.transformer.to_lonlat(info.layout.transform.to_world(x, 0.5)).unwrap(); + let error = read_point_blocking(info.clone(), url.into(), at(1.5)).unwrap_err(); + assert!(error.contains("f32"), "{error}"); + let missing = read_point_blocking(info.clone(), url.into(), at(2.5)).unwrap().unwrap(); + assert_eq!(missing.values, vec![None]); + assert_eq!(missing.rounded, vec![false]); + let clean = read_point_blocking(info.clone(), url.into(), at(4.5)).unwrap().unwrap(); + assert_eq!(clean.values, vec![Some(16_777_426.)]); + assert_eq!(clean.rounded, vec![false]); + forget_file(url); + crate::cache::clear_fetcher(); + } + /// Serves `file` by range to the reads of this test, counting the bytes and requests served; /// the first `drops` requests from `from` on are dropped by the fetch queue. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 17f896b02f..fac429037e 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -24,6 +24,8 @@ use crate::{RustGisApp, Slot}; pub use crate::assistantpane::{approval_details, error, reply}; /// Where a response lands. +type PointRead = (u64, Slot>, std::sync::Arc); + pub(crate) type Reply = Slot>; /// A streamed reply's pieces, as they arrive. pub(crate) type Chunks = std::sync::Arc>>; @@ -54,6 +56,7 @@ pub struct AssistantState { pub(crate) late_pictures: usize, /// The request out: its generation and where its response lands. pub(crate) inflight: Option<(u64, Reply)>, + point_read: Option, /// The pieces of the request out's reply, as they stream in (desktop). pub(crate) chunks: Option<(u64, Chunks)>, /// The settings form is open. @@ -758,6 +761,9 @@ pub(crate) fn apply_config(app: &mut RustGisApp, cfg: Config) { /// Forgets the request out: its response, the pieces of it and a retry waiting. fn drop_request(state: &mut AssistantState) { + if let Some((_, _, control)) = state.point_read.take() { + control.cancel(); + } state.inflight = None; state.chunks = None; state.retry = None; @@ -828,6 +834,38 @@ pub(crate) fn follow(app: &mut RustGisApp, step: Step, ctx: &egui::Context) { if !app.session.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) { return; } + if step == Step::Read { + let Some(agent) = &mut app.assistant.agent else { + return; + }; + let generation = agent.generation(); + let Some(ahead) = agent.take_read() else { + return; + }; + let control = rustgis_engine::analysis::control::Control::stoppable(); + let slot = Slot::default(); + let out = slot.clone(); + #[cfg(not(target_arch = "wasm32"))] + { + let ctl = control.clone(); + let diagnostics = app.session.diagnostics.capture(); + crate::work_off_frame("assistant-identify", &slot, move || { + let _diagnostics = diagnostics.enter(); + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(ahead.run(&ctl)); + }); + } + #[cfg(target_arch = "wasm32")] + { + let wake = ctx.clone(); + ahead.run_async(Box::new(move |answer| { + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(answer); + wake.request_repaint(); + })); + } + app.assistant.point_read = Some((generation, slot, control)); + ctx.request_repaint(); + return; + } if let Step::Retry(after) = step { let generation = app.assistant.agent.as_ref().map_or(0, Agent::generation); app.assistant.retry = Some((generation, web_time::Instant::now() + after)); @@ -983,6 +1021,18 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { app.session.notify(tl!("The assistant is busy; stop it or wait for it to finish."), true); } } + if let Some((generation, slot, _)) = &app.assistant.point_read { + let generation = *generation; + let answer = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(answer) = answer { + app.assistant.point_read = None; + if let Some(step) = with_agent(app, |agent, s| agent.finish_read(generation, answer, s)) { + follow(app, step, ctx); + } + } else { + ctx.request_repaint(); + } + } // The reply's text so far, as it streams in. if let Some((generation, chunks)) = &app.assistant.chunks { let generation = *generation; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f9f581bc56..f048d127be 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3755,6 +3755,10 @@ impl RustGisApp { #[cfg(not(target_arch = "wasm32"))] self.session.statistics_need_read_ahead(self.reads_off_frame); #[cfg(not(target_arch = "wasm32"))] + if id == "identify" && self.reads_off_frame && params.get("defer").and_then(Value::as_bool) != Some(true) { + return readjob::run(self, "identify", params); + } + #[cfg(not(target_arch = "wasm32"))] if self.reads_off_frame { if id == "service.layers" { return readjob::run(self, "service.layers", params); @@ -4957,10 +4961,14 @@ impl RustGisApp { "ui.identify" => { // The engine checks the coordinates; the popup reuses them. let (lon, lat) = (p.get("lon").cloned().unwrap_or(Value::Null), p.get("lat").cloned().unwrap_or(Value::Null)); - let v = self.session.run("identify", &json!({"lon": lon, "lat": lat, "tolerancePx": 5}))?; + let params = json!({"lon": lon, "lat": lat, "tolerancePx": 5}); + let mut deferred = params.clone(); + deferred["defer"] = json!(true); + let v = self.session.run("identify", &deferred)?; if let (false, Some(lon), Some(lat)) = (v.is_null(), lon.as_f64(), lat.as_f64()) { let map = self.session.project.active_map; self.map.popup = Some(mapview::Popup::new(v, rustgis_engine::geom::Coord::new(lon, lat), map, self.session.opened)); + mapview::start_pixel_read(self, ¶ms); } else { self.map.popup = None; } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index dd6acff8b0..5a00ddec76 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -94,6 +94,8 @@ pub struct Popup { pub asks: Vec, /// When it opened: it waits for the WMS layers' answers up to [`ASK_WAIT`] from then. since: web_time::Instant, + pixel_read: Option>>, + pixel_control: std::sync::Arc, } /// How long a pop-up waits for the WMS layers asked before it shows what was found: then their @@ -156,7 +158,17 @@ impl Popup { let request = Some(url.to_string()); asks.push(Ask { layer, also: Vec::new(), capabilities, request, slot }); } - Popup { info, at, index: 0, map, opened, asks, since: web_time::Instant::now() } + Popup { + info, + at, + index: 0, + map, + opened, + asks, + since: web_time::Instant::now(), + pixel_read: None, + pixel_control: rustgis_engine::analysis::control::Control::stoppable(), + } } /// Whether it waits for the WMS layers asked, to show their answers and what was found @@ -167,6 +179,105 @@ impl Popup { } } +impl Drop for Popup { + fn drop(&mut self) { + self.pixel_control.cancel(); + } +} + +pub(crate) fn start_pixel_read(app: &mut RustGisApp, params: &Value) { + let Some(popup) = &mut app.map.popup else { + return; + }; + if !results_of(&popup.info).iter().any(|v| v["pixelState"] == "pending") { + return; + } + let slot = crate::Slot::default(); + let out = slot.clone(); + let ahead = match rustgis_engine::cmd::reads::read_ahead(&mut app.session, "identify", params) { + Ok(ahead) => ahead, + Err(error) => { + fail_pixels(&mut popup.info, &error); + return; + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + let control = popup.pixel_control.clone(); + let diagnostics = app.session.diagnostics.capture(); + crate::work_off_frame("identify-pixels", &slot, move || { + let _diagnostics = diagnostics.enter(); + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(ahead.run(&control)); + }); + } + #[cfg(target_arch = "wasm32")] + ahead.run_async(Box::new(move |answer| { + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(answer); + cache::notify(); + })); + popup.pixel_read = Some(slot); +} + +fn fail_pixels(info: &mut Value, error: &str) { + if info["pixelState"] == "pending" { + info["pixelState"] = json!("failed"); + info["pixelError"] = json!(error); + } + if let Some(results) = info.get_mut("results").and_then(Value::as_array_mut) { + for value in results { + fail_pixels(value, error); + } + } +} + +fn follow_pixels(app: &mut RustGisApp, ctx: &egui::Context) { + let Some(popup) = &mut app.map.popup else { + return; + }; + let Some(slot) = &popup.pixel_read else { + return; + }; + let answer = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + let Some(answer) = answer else { + ctx.request_repaint(); + return; + }; + popup.pixel_read = None; + if popup.opened != app.session.opened || popup.map != app.session.project.active_map { + return; + } + let answer = answer.and_then(|read| rustgis_engine::cmd::reads::read_land(&mut app.session, read)); + match answer { + Ok(info) => { + // WMS answers may have arrived while the pixels were read. Replace only the + // placeholders, preserving those answers and their ordering. + let values = info.get("results").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_else(|| std::slice::from_ref(&info)); + let replace = |value: &mut Value| { + if value["pixelState"] == "pending" + && let Some(answer) = values.iter().find(|v| v["layerId"] == value["layerId"]) + { + let results = value.as_object_mut().and_then(|o| o.remove("results")); + let asks = value.as_object_mut().and_then(|o| o.remove("featureInfo")); + *value = answer.clone(); + if let Some(results) = results { + value["results"] = results; + } + if let Some(asks) = asks { + value["featureInfo"] = asks; + } + } + }; + replace(&mut popup.info); + if let Some(results) = popup.info.get_mut("results").and_then(Value::as_array_mut) { + for value in results { + replace(value); + } + } + } + Err(error) => fail_pixels(&mut popup.info, &error), + } +} + /// Whether a popup's value is a feature or pixel found, not only WMS layers still being asked. fn is_found(v: &Value) -> bool { v.get("layer").is_some() || v.get("attributes").is_some() @@ -3601,7 +3712,10 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect } } Tool::Explore => { - let r = app.session.run("identify", &json!({"lon": c.x, "lat": c.y, "tolerancePx": 5})); + let params = json!({"lon": c.x, "lat": c.y, "tolerancePx": 5}); + let mut deferred = params.clone(); + deferred["defer"] = json!(true); + let r = app.session.run("identify", &deferred); app.map.popup = match r { Ok(v) if !v.is_null() => { select_first_found(app, &v); @@ -3612,6 +3726,7 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect None } }; + start_pixel_read(app, ¶ms); } Tool::Select => { let mode = ui.input(|i| { @@ -4523,6 +4638,7 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { } fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { + follow_pixels(app, ui.ctx()); follow_asks(app, ui.ctx()); follow_popup(app); let Some(pp) = &app.map.popup else { return }; @@ -4534,6 +4650,8 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { } // Waiting for the WMS layers' answers, it shows none of the results yet. let asking = pp.asking(); + #[cfg(not(target_arch = "wasm32"))] + let pixel_control = pp.pixel_read.is_some().then(|| pp.pixel_control.clone()); let results = if asking { 0 } else { pp.info["results"].as_array().map_or(0, Vec::len) }; let index = pp.index.min(results.saturating_sub(1)); let info = if asking { @@ -4558,6 +4676,21 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { info["layer"].as_str().unwrap_or("").to_string() }; let mut attrs = info["attributes"].as_object().cloned().unwrap_or_default(); + match info["pixelState"].as_str() { + Some("pending") => { + attrs.insert(tl!("Status").into(), json!(tl!("Reading full-resolution pixel…"))); + } + Some("failed") => { + attrs.insert(tl!("Read failed").into(), json!(info["pixelError"].as_str().unwrap_or(tl!("The pixel could not be read")))); + } + Some("no-data") => { + attrs.insert(tl!("Status").into(), json!(tl!("NoData at full resolution"))); + } + _ => {} + } + if info["rounded"].as_u64().unwrap_or(0) > 0 { + attrs.insert(tl!("Precision").into(), json!(tl!("Values rounded to f32"))); + } // A picture value (a photo's thumbnail) shows as the picture, not as its text. let picture_key = attrs.iter().find(|(_, v)| v.as_str().is_some_and(is_picture)).map(|(k, _)| k.clone()); let picture = picture_key.and_then(|k| attrs.remove(&k)).and_then(|v| v.as_str().map(|s| picture_texture(app, ui.ctx(), s))); @@ -4628,6 +4761,12 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { if ui.add(egui::Button::new(tl!("×")).frame(false)).clicked() { close = true; } + #[cfg(not(target_arch = "wasm32"))] + if let Some(control) = &pixel_control + && ui.button(tl!("Cancel")).clicked() + { + control.cancel(); + } // A pixel of several bands: add it to the spectral profile. if spectral.is_some() { let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click()); @@ -5882,6 +6021,49 @@ fn clear_selection_quietly(app: &mut RustGisApp) { mod tests { use super::*; + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn full_resolution_pixel_completion_keeps_later_wms_answers() { + use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let raster = Raster::new( + "pixel", + 1, + 1, + vec![vec![7.]], + GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 1., pixel_height: -1. }, + Crs::LonLat, + None, + ColorHint::Gray, + "Float32", + ) + .unwrap(); + let mut layer = rustgis_engine::map::raster::RasterLayer::from_path(raster, "/nonexistent-rustgis-point/pixel.tif"); + layer.in_place = true; + app.session.map_mut().add_raster("pixel", layer); + let params = json!({"lon":10.5,"lat":45.5}); + let pending = app.session.run("identify", &json!({"lon":10.5,"lat":45.5,"defer":true})).unwrap(); + assert_eq!(pending["pixelState"], "pending"); + assert!(pending.get("attributes").is_none()); + let ahead = rustgis_engine::cmd::reads::read_ahead(&mut app.session, "identify", ¶ms).unwrap(); + let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); + let remote = json!({"tileLayer":"remote","attributes":{"name":"Later answer"}}); + let mut info = pending.clone(); + info["results"] = json!([pending, remote]); + let mut popup = Popup::new(info, Coord::new(10.5, 45.5), app.session.project.active_map, app.session.opened); + let slot = crate::Slot::default(); + *slot.lock().unwrap() = Some(answer); + popup.pixel_read = Some(slot); + app.map.popup = Some(popup); + follow_pixels(&mut app, &egui::Context::default()); + let info = &app.map.popup.as_ref().unwrap().info; + assert_eq!(info["pixelState"], "failed"); + assert_eq!(info["results"][0]["pixelState"], "failed"); + assert_eq!(info["results"][1], remote); + assert_eq!(info["results"].as_array().unwrap().len(), 2); + assert!(info.get("attributes").is_none()); + } + /// The graphics card running out of memory doesn't close the app (#1777): it's noted, and /// the map then leaves the GPU for the CPU with a notice, its GPU resources let go. Once: /// turned on again, running out again falls back again. With the map already on the CPU, diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index b71832370f..fa6d647a75 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -566,7 +566,8 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result Date: Wed, 2 Dec 2026 20:38:42 -0600 Subject: [PATCH 2/5] fix(engine): remove obsolete wasm lint expectation --- crates/engine/src/service_logins.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index b12b78afa3..3fe6c7b1bd 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -948,7 +948,6 @@ pub fn open_connection(s: &mut Session, c: &Connection) -> Result<(), String> { /// Marks an outbound fetch address anonymous when `anonymous` is set, preventing implicit S3 /// signing and Earthdata/Copernicus/ArcGIS sign-in tokens on that request without altering the /// plain URL kept in layers or parameters. -#[cfg_attr(target_arch = "wasm32", expect(dead_code, reason = "blocking fetches are desktop only"))] pub(crate) fn fetch_url(anonymous: bool, url: &str) -> String { if anonymous { crate::render::rustgis_tiles::s3::anonymous_once(url) } else { url.to_string() } } From ed45a57e8867397e4d41536a0980fb7ec97ff09e Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 20:47:21 -0600 Subject: [PATCH 3/5] fix(ui): remove private cache wake call in browser --- crates/ui-egui/src/mapview.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 5a00ddec76..b610ef6a5d 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -213,7 +213,6 @@ pub(crate) fn start_pixel_read(app: &mut RustGisApp, params: &Value) { #[cfg(target_arch = "wasm32")] ahead.run_async(Box::new(move |answer| { *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(answer); - cache::notify(); })); popup.pixel_read = Some(slot); } From f4c57a8c47fab1ae6868634901caa98644fbe958 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 23:32:44 -0600 Subject: [PATCH 4/5] fix(raster): preserve identify read ownership and notices Interrupt suspended Assistant batches when their project or active map changes, including delegated batches. Preserve preparation notices separately from unrelated wait-time work and bound setup errors. Align source effects with deferred and selected-vector Identify, normalize cube paths, retry dropped headers, and reject changed local files. Close stale popups and poll pending reads at 100 ms. --- crates/assistant/src/agent.rs | 317 ++++++++++++++++++++++------ crates/assistant/src/tools.rs | 28 ++- crates/engine/src/policy/effects.rs | 66 +++++- crates/tiles/src/cog.rs | 82 ++++++- crates/ui-egui/src/assistant.rs | 21 +- crates/ui-egui/src/mapview.rs | 33 ++- 6 files changed, 476 insertions(+), 71 deletions(-) diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index a0db11323e..e67d1d6337 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -113,6 +113,14 @@ pub struct Asking { child: Option>, } +struct PendingRead { + call: ToolCall, + ahead: Option, + completion: tools::CommandCompletion, + opened: u64, + map: u64, +} + pub struct Agent { pub config: Config, turns: Vec, @@ -129,7 +137,7 @@ pub struct Agent { /// Exact operations approved for the rest of this conversation and project generation. always: Vec, pending_policy: Option, - pending_read: Option<(ToolCall, Option)>, + pending_read: Option, conversation: u64, live: Arc, system: String, @@ -1102,7 +1110,7 @@ impl Agent { if let Some(child) = &mut self.child { return child.take_read(); } - self.pending_read.as_mut()?.1.take() + self.pending_read.as_mut()?.ahead.take() } /// Completes only this run's pending call, then resumes its batch. Stopped conversations @@ -1112,14 +1120,18 @@ impl Agent { if generation != a.generation { return Step::Done; } + if a.read_owner().is_some_and(|(opened, map)| opened != s.opened || map != s.map().instance_id()) { + a.interrupt_read_batch(); + return Step::Done; + } if let Some(child) = &mut a.child { let step = child.finish_read(child.generation(), read, s); return a.after_child(step, s); } - let Some((call, _)) = a.pending_read.take() else { + let Some(PendingRead { call, mut completion, .. }) = a.pending_read.take() else { return Step::Done; }; - let completion = tools::CommandCompletion::capture(s); + completion.resume(s); let answer = read.and_then(|read| rustgis_engine::cmd::reads::read_land(s, read)); let answer = completion.finish_with_budget(s, answer, a.config.tool_output_token_limit); let (content, error) = match answer { @@ -1131,6 +1143,28 @@ impl Agent { }) } + fn read_owner(&self) -> Option<(u64, u64)> { + self.child + .as_ref() + .and_then(|child| child.read_owner()) + .or_else(|| self.pending_read.as_ref().map(|pending| (pending.opened, pending.map))) + } + + fn interrupt_read_batch(&mut self) { + let why = "Interrupted: the project or active map changed while Identify was reading."; + if let Some(child) = &mut self.child { + child.interrupt_read_batch(); + } + self.show_child(); + if let Some(pending) = self.pending_read.take() { + self.record(pending.call, why.into(), why.into(), true, Vec::new()); + } + while matches!(&self.state, State::Calls(q, _) if !q.is_empty()) { + self.record_front(why.into(), why.into(), true); + } + self.halt(Entry::Note(Note::new(why)), why, why); + } + /// Runs (or declines) the first waiting call and records its result. fn run_front(&mut self, s: &mut Session, allow: bool) { let tokens = self.config.tool_output_token_limit; @@ -1143,15 +1177,26 @@ impl Agent { if allow && call.name == "run_command" && call.args.get("command").and_then(serde_json::Value::as_str).map(str::trim) == Some("identify") - && call.args.get("params").and_then(|p| p.get("defer")).and_then(serde_json::Value::as_bool) != Some(true) + && call.args.get("params").and_then(|p| p.get("defer")).and_then(rustgis_engine::cmd::bool_value) != Some(true) && s.map().layers.iter().any(|l| l.raster.as_ref().is_some_and(|r| r.reads_in_place())) { + let mut completion = tools::CommandCompletion::capture(s); let ahead = tools::policy_call(&call) .and_then(|c| c.ok_or_else(|| "missing identify call".to_string())) .and_then(|engine| s.start_scoped_archive_read(self.scope(), &engine, permit)); match ahead { - Ok(ahead) => self.pending_read = Some((call, Some(ahead))), - Err(error) => self.record(call, error.clone(), error, true, Vec::new()), + Ok(ahead) => { + if ahead.reads() { + completion.prepared(s); + } + self.pending_read = + Some(PendingRead { call, ahead: Some(ahead), completion, opened: s.opened, map: s.map().instance_id() }); + } + Err(error) => { + let error = completion.finish_with_budget(s, Err(error), tokens).unwrap_or_else(|error| error); + let content = tools::bounded_json(&serde_json::json!({"error": error}), tokens); + self.record(call, content.clone(), content, true, Vec::new()); + } } return; } @@ -1717,69 +1762,217 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn identify_waits_for_its_admitted_read_before_running_the_batch_suffix() { - use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster}; - for stop in [false, true] { - let mut s = Session::new(Project::default()); - let raster = Raster::new( - "pixel", - 1, - 1, - vec![vec![7.]], - GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 1., pixel_height: -1. }, - Crs::LonLat, - None, - ColorHint::Gray, - "Float32", - ) - .unwrap(); - let mut layer = rustgis_engine::map::raster::RasterLayer::from_path(raster, "/nonexistent-rustgis-point/pixel.tif"); - layer.in_place = true; - s.map_mut().add_raster("pixel", layer); - let mut a = Agent::new(test_cfg(), &s); - assert!(matches!(a.ask("identify", &s), Step::Send(_))); - let tool = |id: &str, name: &str, args: serde_json::Value| json!({"id":id,"type":"function","function":{"name":name,"arguments":args.to_string()}}); - let response = json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[ - tool("pixel","run_command",json!({"command":"identify","params":{"lon":10.5,"lat":45.5}})), - tool("suffix","list_layers",json!({})) - ]}}]}); - let step = a.receive( - a.generation(), - Ok(HttpResponse { status: 200, body: response.to_string().into_bytes(), headers: vec![] }), - &mut s, + identify_batch("finish"); + identify_batch("stop"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn identify_interrupts_batch_after_map_or_project_change() { + identify_batch("map"); + identify_batch("project"); + identify_batch("child-map"); + } + + #[cfg(not(target_arch = "wasm32"))] + fn identify_batch(change: &str) { + let mut s = identify_session(); + if change == "finish" { + add_refused_wms(&mut s); + } + let mut a = Agent::new(test_cfg(), &s); + assert!(matches!(a.ask("identify", &s), Step::Send(_))); + let tool = |id: &str, name: &str, args: serde_json::Value| json!({"id":id,"type":"function","function":{"name":name,"arguments":args.to_string()}}); + let response = json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[ + tool("pixel","run_command",json!({"command":"identify","params":{"lon":10.5,"lat":45.5,"mode":"visible"}})), + tool("suffix","list_layers",json!({})) + ]}}]}); + let step = + a.receive(a.generation(), Ok(HttpResponse { status: 200, body: response.to_string().into_bytes(), headers: vec![] }), &mut s); + assert_eq!(step, Step::Confirm, "a source read needs the original file approval"); + let asked = a.asking().unwrap(); + let mark = s.notice_mark(); + assert_eq!(a.decide(&asked, true, false, &mut s), Some(Step::Read)); + assert!(!a.transcript.iter().any(|entry| matches!(entry, Entry::Tool { .. }))); + let preparation: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + if change == "finish" { + assert_eq!(preparation.len(), 1, "one WMS reach refusal"); + } + s.notify("unrelated while reading", false); + if change == "finish" { + let mut unrelated = rustgis_engine::map::Layer::new( + 0, + rustgis_engine::data::Dataset::new("unrelated layer", rustgis_engine::data::GeometryType::Point, vec![]), ); - assert_eq!(step, Step::Confirm, "a source read needs the original file approval"); - let asked = a.asking().unwrap(); - assert_eq!(a.decide(&asked, true, false, &mut s), Some(Step::Read)); - assert!(!a.transcript.iter().any(|entry| matches!(entry, Entry::Tool { .. }))); - let ahead = a.take_read().unwrap(); - if stop { - a.stop(); + unrelated.visible = false; + s.map_mut().add_layer(unrelated); + } + if change == "child-map" { + let mut parent = Agent::new(test_cfg(), &s); + parent.state = State::Calls( + std::collections::VecDeque::from([ToolCall { id: "parent-suffix".into(), name: "list_layers".into(), args: json!({}) }]), + vec![], + ); + parent.child = Some(Box::new(a)); + a = parent; + } + let ahead = a.take_read().unwrap(); + if change == "stop" { + a.stop(); + } + if matches!(change, "map" | "child-map") { + s.project.maps.push(rustgis_engine::map::Map::new("other")); + s.project.active_map = 1; + } + if change == "project" { + s.opened += 1; + } + let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); + let step = a.finish_read(a.generation(), answer, &mut s); + if change != "finish" { + assert_eq!(step, Step::Done); + if change != "stop" { + assert!(a.transcript.iter().any(|entry| matches!(entry, Entry::Tool { name, result, error, .. } if name == "list_layers" && *error && result.contains("Interrupted")))); } - let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); - let step = a.finish_read(a.generation(), answer, &mut s); - if stop { - assert_eq!(step, Step::Done); - assert!( + assert!( !a.transcript .iter() - .any(|entry| matches!(entry,Entry::Tool { name,result,.. } if name=="list_layers" && !result.contains("Stopped"))) + .any(|entry| matches!(entry,Entry::Tool { name,result,.. } if name=="list_layers" && !result.contains("Stopped") && !result.contains("Interrupted"))) ); - } else { - assert!(matches!(step, Step::Send(_))); - let tools: Vec<_> = a - .transcript - .iter() - .filter_map(|entry| match entry { - Entry::Tool { name, result, .. } => Some((name.as_str(), result.as_str())), - _ => None, - }) - .collect(); - assert_eq!(tools.iter().map(|(name, _)| *name).collect::>(), ["run_command", "list_layers"]); - assert!(tools[0].1.contains("pixelState") && tools[0].1.contains("failed")); - } + } else { + assert!(matches!(step, Step::Send(_))); + let tools: Vec<_> = a + .transcript + .iter() + .filter_map(|entry| match entry { + Entry::Tool { name, result, .. } => Some((name.as_str(), result.as_str())), + _ => None, + }) + .collect(); + assert_eq!(tools.iter().map(|(name, _)| *name).collect::>(), ["run_command", "list_layers"]); + assert!(!tools[0].1.contains("unrelated while reading")); + assert!(!tools[0].1.contains("layersAdded")); + assert!(tools[0].1.contains(&preparation[0]), "{}", tools[0].1); + assert!(tools[0].1.contains("pixelState") && tools[0].1.contains("failed")); + } + } + + fn add_refused_wms(s: &mut Session) { + let mut wms = rustgis_engine::map::tiles::TileLayer::new( + "refused WMS", + rustgis_engine::map::tiles::TileKind::Raster, + "https://point-reader.example/wms", + ); + wms.feature_info = Some(rustgis_engine::data::ogc::FeatureInfo { + url: "http://127.0.0.1:9/wms".into(), + layer: "refused".into(), + formats: vec!["application/json".into()].into(), + ..Default::default() + }); + wms.feature_info_public = true; + s.map_mut().tiles.push(wms); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn identify_without_pixel_io_reports_preparation_refusals_once() { + let mut s = identify_session(); + add_refused_wms(&mut s); + let mut a = Agent::new(test_cfg(), &s); + assert!(matches!(a.ask("identify", &s), Step::Send(_))); + let response = json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[ + {"id":"outside","type":"function","function":{"name":"run_command","arguments":json!({"command":"identify","params":{"lon":0,"lat":0,"mode":"visible"}}).to_string()}} + ]}}]}); + assert_eq!( + a.receive(a.generation(), Ok(HttpResponse { status: 200, body: response.to_string().into_bytes(), headers: vec![] }), &mut s), + Step::Read + ); + let ahead = a.take_read().unwrap(); + assert!(!ahead.reads(), "the click is outside the raster"); + let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); + a.finish_read(a.generation(), answer, &mut s); + let result = a + .transcript + .iter() + .find_map(|entry| match entry { + Entry::Tool { result, error: false, .. } => Some(result), + _ => None, + }) + .unwrap(); + let result: serde_json::Value = serde_json::from_str(result).unwrap(); + let notices = result["notices"].as_array().unwrap(); + assert_eq!(notices.len(), 1, "{result}"); + let text = notices[0].as_str().unwrap(); + assert!(text.contains("refused WMS wasn't asked what is here:") && text.contains("127.0.0.1"), "{text}"); + } + + fn identify_session() -> Session { + use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let mut s = Session::new(Project::default()); + let raster = Raster::new( + "pixel", + 1, + 1, + vec![vec![7.]], + GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 1., pixel_height: -1. }, + Crs::LonLat, + None, + ColorHint::Gray, + "Float32", + ) + .unwrap(); + let mut layer = rustgis_engine::map::raster::RasterLayer::from_path(raster, "/nonexistent-rustgis-point/pixel.tif"); + layer.in_place = true; + s.map_mut().add_raster("pixel", layer); + s + } + + #[test] + fn identify_deferred_boolean_aliases_stay_synchronous() { + let mut s = identify_session(); + for defer in [json!(true), json!("true"), json!("yes"), json!("on"), json!("1"), json!(1)] { + let mut a = Agent::new(test_cfg(), &s); + a.state = State::Calls( + std::collections::VecDeque::from([ToolCall { + id: "defer".into(), + name: "run_command".into(), + args: json!({"command":"identify","params":{"lon":10.5,"lat":45.5,"defer":defer}}), + }]), + vec![], + ); + a.run_front(&mut s, true); + assert!(a.pending_read.is_none(), "{defer}"); + assert!( + matches!(a.transcript.last(), Some(Entry::Tool { result, error:false, .. }) if result.contains("pending")), + "{defer}: {:?}", + a.transcript + ); } } + #[test] + fn identify_setup_errors_obey_the_tool_output_budget() { + let mut s = identify_session(); + let mut a = Agent::new(test_cfg(), &s); + a.config.tool_output_token_limit = 100; + let call = ToolCall { + id: "bad-mode".into(), + name: "run_command".into(), + args: json!({"command":"identify","params":{"lon":10.5,"lat":45.5,"mode":"x".repeat(1000)}}), + }; + let engine = tools::policy_call(&call).unwrap().unwrap(); + let rustgis_engine::policy::Outcome::NeedsApproval(pending) = s.review(&a.scope(), &engine) else { + panic!("expected file approval") + }; + a.pending_policy = Some(pending); + a.state = State::Calls(std::collections::VecDeque::from([call]), vec![]); + a.run_front(&mut s, true); + let Entry::Tool { result, error, .. } = a.transcript.last().unwrap() else { panic!("missing error result") }; + assert!(*error); + assert!(result.len() <= 400, "{} bytes: {result}", result.len()); + assert!(result.contains("error")); + } + /// An agent thread's report goes on with the run it belongs to, so a chain of reports and /// follow-ups still pauses where the run's steps run out. #[test] diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 6a1d285245..5208737810 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -517,6 +517,16 @@ impl CommandCompletion { pub(crate) fn capture(s: &Session) -> Self { Self { before: layer_snap(s), said: Said::now(s) } } + /// Retains preparation notices before a wait; unrelated notices during the wait are excluded. + pub(crate) fn prepared(&mut self, s: &Session) { + self.said.earlier_notices = self.said.notices(s); + self.said.earlier_losses = losses_since(s, &self.said); + } + pub(crate) fn resume(&mut self, s: &Session) { + self.before = layer_snap(s); + self.said.mark = s.notice_mark(); + self.said.given = s.losses_given().to_vec(); + } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn finish(self, s: &mut Session, result: Result) -> Result { self.finish_with_budget(s, result, DEFAULT_OUTPUT_TOKENS) @@ -651,7 +661,7 @@ fn public_metadata(value: Value, depth: usize, withheld: &mut Withheld) -> Value fn command_result(s: &mut Session, value: Value, before: &[(String, Vec)], said: &Said, tokens: usize) -> String { let mut withheld = Withheld::default(); let value = public_addresses(value, 0, &mut withheld); - let value = with_notices(with_new_layers(value, s, before), s, said.mark); + let value = with_notice_text(with_new_layers(value, s, before), said.notices(s).into_iter().map(public_text).collect()); // Added after cleaning: its keys and codes are fixed, and its text was cleaned on its own. let losses = losses_since(s, said); finish_with_losses(s, value, losses, tokens, withheld, false) @@ -883,6 +893,10 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per /// were added, a file's warnings), which the status bar shows in the app. fn with_notices(r: Value, s: &Session, mark: u64) -> Value { let said: Vec = s.notices_since(mark).iter().map(|n| public_text(n.text.clone())).collect(); + with_notice_text(r, said) +} + +fn with_notice_text(r: Value, said: Vec) -> Value { if said.is_empty() { return r; } @@ -899,11 +913,18 @@ fn with_notices(r: Value, s: &Session, mark: u64) -> Value { struct Said { mark: u64, given: Vec<(rustgis_engine::data::loss::LossCode, u64)>, + earlier_notices: Vec, + earlier_losses: Vec, } impl Said { fn now(s: &Session) -> Self { - Self { mark: s.notice_mark(), given: s.losses_given().to_vec() } + Self { mark: s.notice_mark(), given: s.losses_given().to_vec(), earlier_notices: Vec::new(), earlier_losses: Vec::new() } + } + fn notices(&self, s: &Session) -> Vec { + let mut notices = self.earlier_notices.clone(); + notices.extend(s.notices_since(self.mark).iter().map(|n| n.text.clone())); + notices } } @@ -926,6 +947,7 @@ fn losses_since(s: &Session, said: &Said) -> Vec { e }) .collect(); + out.splice(0..0, said.earlier_losses.clone()); out.extend(kept.into_iter().map(|(code, text)| entry(code, text))); out } @@ -1082,7 +1104,7 @@ fn clip_bytes(text: &str, max: usize) -> String { /// list fits, a `lossesTrimmed: true` line says the codes were left out. fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> String { let told = rustgis_engine::data::diagnostics::redact(&e); - let notices: Vec<&str> = s.notices_since(said.mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); + let notices: Vec = said.notices(s).into_iter().filter(|t| *t != e && *t != told).collect(); let Some(losses) = loss_summary(&losses_since(s, said)) else { // Preserve the original 8,000-character diagnostic assembly cap for MCP errors; // the agent additionally applies its serialized output budget. diff --git a/crates/engine/src/policy/effects.rs b/crates/engine/src/policy/effects.rs index 0db6c3ec44..34b94103ca 100644 --- a/crates/engine/src/policy/effects.rs +++ b/crates/engine/src/policy/effects.rs @@ -142,7 +142,10 @@ pub(super) fn command(s: &crate::cmd::InputContext<'_>, spec: &CommandSpec, para } } if spec.id == "identify" - && params.get("defer").and_then(Value::as_bool) != Some(true) + && params.get("defer").and_then(crate::cmd::bool_value) != Some(true) + && !(params.get("mode").and_then(Value::as_str).and_then(rustgis_map::PopupMode::from_code).unwrap_or(s.map().popup_mode) + == rustgis_map::PopupMode::SelectedInContents + && s.active_layer.and_then(|id| s.map().layer(id)).is_some_and(|layer| !layer.is_raster())) && let Some(select) = spec.inputs && let Ok(inputs) = select(s, params) { @@ -202,3 +205,64 @@ pub(super) fn imported(command: &str, params: &Value) -> bool { || id == "raster.mosaic" || crate::cmd::items::names_place(&crate::cmd::items::layer_name_left_out(command, params), KEYS, 0) } + +#[cfg(test)] +mod identify_tests { + use serde_json::json; + fn point_session() -> crate::Session { + let raster = rustgis_data::raster::Raster::new( + "pixel", + 1, + 1, + vec![vec![7.]], + rustgis_data::raster::GeoTransform { origin_x: 10., origin_y: 46., pixel_width: 1., pixel_height: -1. }, + rustgis_data::raster::Crs::LonLat, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + let mut layer = rustgis_map::raster::RasterLayer::from_path(raster, "/point.tif"); + layer.in_place = true; + let mut s = crate::Session::new(crate::Project::default()); + s.map_mut().add_raster("pixel", layer); + s + } + + #[test] + fn identify_deferred_effects_use_the_handlers_boolean_parser() { + use crate::cmd::InputSource; + use crate::policy::Effect; + let s = point_session(); + let spec = s.registry.get("identify").unwrap(); + for defer in [json!(true), json!("true"), json!("yes"), json!("on"), json!("1"), json!(1)] { + let params = json!({"lon":10.025,"lat":45.995,"defer":defer}); + let reach = super::command(&s.input_context(), spec, ¶ms, None); + assert!(!reach.contains(Effect::Files), "{defer}: {reach:?}"); + } + } + + #[test] + fn identify_selected_vector_needs_no_raster_file_effect() { + use crate::cmd::InputSource; + use crate::policy::Effect; + let mut s = point_session(); + let id = s + .map_mut() + .add_layer(rustgis_map::Layer::new(0, rustgis_data::Dataset::new("vector", rustgis_data::GeometryType::Point, vec![]))); + s.active_layer = Some(id); + s.map_mut().popup_mode = rustgis_map::PopupMode::SelectedInContents; + for mode in [None, Some("selectedInContents")] { + let mut params = json!({"lon":10.025,"lat":45.995}); + if let Some(mode) = mode { + params["mode"] = json!(mode); + } + let spec = s.registry.get("identify").unwrap(); + let reach = super::command(&s.input_context(), spec, ¶ms, None); + assert!(!reach.contains(Effect::Files), "{mode:?}: {reach:?}"); + } + s.active_layer = None; + let reach = super::command(&s.input_context(), s.registry.get("identify").unwrap(), &json!({"lon":10.025,"lat":45.995}), None); + assert!(reach.contains(Effect::Files)); + } +} diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index fb42565921..ad1adc9f03 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1052,7 +1052,8 @@ pub struct Point { /// Opens a point's source and reads it without blocking the caller, including in the browser. pub fn point_from_file(file: String, lonlat: Coord, then: Box, String>) + Send>) { - let path = file.clone(); + let path = split(&file).0.to_string(); + ask_again_if_dropped(&path); with_any_info( &path, Box::new(move |answer| match answer { @@ -1104,6 +1105,8 @@ pub fn read_point(info: Arc, file: String, lonlat: Coord, then: Box, file: String, lonlat: Coord, then: Box {} + (Some(_), Some(_)) => return Err(format!("{path}: the file changed while its pixel was read: identify again")), + _ => { + return Err(format!( + "{path}: its modification details can't be read, so its pixel can't be checked: identify again" + )); + } + } + } let picked = picked.first().ok_or("the point's tile was not read")?; let mut values = Vec::with_capacity(picked.len()); let mut rounded = Vec::with_capacity(picked.len()); @@ -2376,6 +2392,70 @@ mod tests { crate::cache::clear_fetcher(); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn point_identify_retries_only_dropped_headers() { + let _turn = crate::cache::turn(); + let asked = Arc::new(AtomicU64::new(0)); + let n = asked.clone(); + let bytes = cog::example(32, 16); + crate::cache::set_fetcher(move |url, done| { + n.fetch_add(1, Ordering::SeqCst); + let (a, b) = crate::cache::split_range(&url).1.unwrap(); + done(Ok(bytes[a as usize..((b + 1) as usize).min(bytes.len())].to_vec())); + }); + let file = "https://point-reader.example/retry.tif"; + let dropped = crate::failure::with_drops("io: Peer disconnected", 5); + for (why, retries) in [("http status: 503 (retry after 20 s)", false), (dropped.as_str(), true)] { + forget_file(file); + infos().lock().unwrap().insert(file.into(), State::Failed(why.into(), Instant::now(), crate::cache::ceiling_for(file))); + let answer = point_from_file_blocking(file.into(), Coord::new(0., 0.)); + assert_eq!(answer.is_ok(), retries, "{answer:?}"); + assert_eq!(asked.load(Ordering::SeqCst) > 0, retries); + } + forget_file(file); + crate::cache::clear_fetcher(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn point_identify_strips_local_cube_look() { + let _turn = crate::cache::turn(); + let path = std::env::temp_dir().join(format!("rustgis-point-cube-{}.tif", std::process::id())); + std::fs::write(&path, cog::example(32, 16)).unwrap(); + let url = path.display().to_string(); + let info = info_blocking(&url).unwrap(); + let at = info.transformer.to_lonlat(info.layout.transform.to_world(1.5, 0.5)).unwrap(); + let expected = point_from_file_blocking(url.clone(), at).unwrap().unwrap(); + forget_file(&url); + let actual = point_from_file_blocking(format!("{url}#cube=1"), at); + forget_file(&url); + std::fs::remove_file(path).unwrap(); + assert_eq!(actual.unwrap().unwrap(), expected); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn point_identify_rejects_rewritten_local_file() { + let _turn = crate::cache::turn(); + for cached in [false, true] { + let path = std::env::temp_dir().join(format!("rustgis-point-rewrite-{}-{cached}.tif", std::process::id())); + std::fs::write(&path, cog::example(32, 16)).unwrap(); + let url = path.display().to_string(); + let info = info_blocking(&url).unwrap(); + let at = info.transformer.to_lonlat(info.layout.transform.to_world(1.5, 0.5)).unwrap(); + if cached { + assert_eq!(read_point_blocking(info.clone(), url.clone(), at).unwrap().unwrap().values, [Some(1.)]); + } + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, cog::example(64, 16)).unwrap(); + let answer = read_point_blocking(info, url.clone(), at); + forget_file(&url); + std::fs::remove_file(path).unwrap(); + assert!(answer.is_err_and(|e| e.contains("changed")), "stale header, cached tile: {cached}"); + } + } + /// Serves `file` by range to the reads of this test, counting the bytes and requests served; /// the first `drops` requests from `from` on are dropped by the fetch queue. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index fac429037e..b2fd91e7ee 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -1030,7 +1030,7 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { follow(app, step, ctx); } } else { - ctx.request_repaint(); + ctx.request_repaint_after(web_time::Duration::from_millis(100)); } } // The reply's text so far, as it streams in. @@ -1743,3 +1743,22 @@ pub(crate) fn peer_replaced(app: &mut RustGisApp) { app.assistant.hold(); app.assistant.always = false; } + +#[cfg(test)] +mod point_read_tests { + use super::*; + + #[test] + fn identify_pending_point_read_uses_bounded_polling() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.assistant.point_read = Some((0, crate::Slot::default(), rustgis_engine::analysis::control::Control::stoppable())); + let ctx = egui::Context::default(); + let mut delay = std::time::Duration::ZERO; + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| poll(&mut app, ui.ctx())); + output.textures_delta.clear(); + delay = output.viewport_output[&egui::ViewportId::ROOT].repaint_delay; + } + assert!(delay >= std::time::Duration::from_millis(50) && delay <= std::time::Duration::from_millis(100), "{delay:?}"); + } +} diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index b610ef6a5d..3165f9647b 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -238,11 +238,12 @@ fn follow_pixels(app: &mut RustGisApp, ctx: &egui::Context) { }; let answer = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); let Some(answer) = answer else { - ctx.request_repaint(); + ctx.request_repaint_after(web_time::Duration::from_millis(100)); return; }; popup.pixel_read = None; if popup.opened != app.session.opened || popup.map != app.session.project.active_map { + app.map.popup = None; return; } let answer = answer.and_then(|read| rustgis_engine::cmd::reads::read_land(&mut app.session, read)); @@ -6021,8 +6022,7 @@ mod tests { use super::*; #[cfg(not(target_arch = "wasm32"))] - #[test] - fn full_resolution_pixel_completion_keeps_later_wms_answers() { + fn pixel_app() -> RustGisApp { use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster}; let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let raster = Raster::new( @@ -6040,6 +6040,13 @@ mod tests { let mut layer = rustgis_engine::map::raster::RasterLayer::from_path(raster, "/nonexistent-rustgis-point/pixel.tif"); layer.in_place = true; app.session.map_mut().add_raster("pixel", layer); + app + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn full_resolution_pixel_completion_keeps_later_wms_answers() { + let mut app = pixel_app(); let params = json!({"lon":10.5,"lat":45.5}); let pending = app.session.run("identify", &json!({"lon":10.5,"lat":45.5,"defer":true})).unwrap(); assert_eq!(pending["pixelState"], "pending"); @@ -6063,6 +6070,26 @@ mod tests { assert!(info.get("attributes").is_none()); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn identify_stale_project_closes_pending_pixel_popup() { + let mut app = pixel_app(); + let id = app.session.map().layers[0].id; + let mut popup = Popup::new( + json!({"pixelState":"pending","layerId":id}), + Coord::new(0., 0.), + app.session.project.active_map, + app.session.opened, + ); + let slot = crate::Slot::default(); + *slot.lock().unwrap() = Some(Err("late read".into())); + popup.pixel_read = Some(slot); + app.map.popup = Some(popup); + app.session.opened += 1; + follow_pixels(&mut app, &egui::Context::default()); + assert!(app.map.popup.is_none()); + } + /// The graphics card running out of memory doesn't close the app (#1777): it's noted, and /// the map then leaves the GPU for the CPU with a notice, its GPU resources let go. Once: /// turned on again, running out again falls back again. With the map already on the CPU, From a5064ff37563276d4604ac5f98f3760b2b42a8ea Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 3 Dec 2026 01:09:30 -0600 Subject: [PATCH 5/5] fix(assistant): bound identify completion errors --- crates/assistant/src/agent.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index e67d1d6337..0570d22595 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -1136,7 +1136,7 @@ impl Agent { let answer = completion.finish_with_budget(s, answer, a.config.tool_output_token_limit); let (content, error) = match answer { Ok(text) => (text, false), - Err(text) => (text, true), + Err(text) => (tools::bounded_json(&serde_json::json!({"error": text}), a.config.tool_output_token_limit), true), }; a.record(call, content.clone(), content, error, Vec::new()); a.drain(s) @@ -1973,6 +1973,34 @@ mod tests { assert!(result.contains("error")); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn identify_completion_errors_obey_the_tool_output_budget() { + let mut s = identify_session(); + let mut a = Agent::new(test_cfg(), &s); + a.config.tool_output_token_limit = 10; + let call = ToolCall { + id: "changed-source".into(), + name: "run_command".into(), + args: json!({"command":"identify","params":{"lon":10.5,"lat":45.5}}), + }; + let engine = tools::policy_call(&call).unwrap().unwrap(); + let rustgis_engine::policy::Outcome::NeedsApproval(pending) = s.review(&a.scope(), &engine) else { + panic!("expected file approval") + }; + a.pending_policy = Some(pending); + a.state = State::Calls(std::collections::VecDeque::from([call]), vec![]); + a.run_front(&mut s, true); + let ahead = a.take_read().unwrap(); + let answer = ahead.run(&rustgis_engine::analysis::control::Control::new()); + s.map_mut().layers[0].raster.as_mut().unwrap().path = Some("/changed-source.tif".into()); + a.finish_read(a.generation(), answer, &mut s); + let Entry::Tool { result, error, .. } = a.transcript.last().unwrap() else { panic!("missing error result") }; + assert!(*error); + assert!(result.len() <= 40, "{} bytes: {result}", result.len()); + assert!(serde_json::from_str::(result).is_ok(), "{result}"); + } + /// An agent thread's report goes on with the run it belongs to, so a chain of reports and /// follow-ups still pauses where the run's steps run out. #[test]