Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
361 changes: 361 additions & 0 deletions crates/assistant/src/agent.rs

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion crates/assistant/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
38 changes: 31 additions & 7 deletions crates/assistant/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,20 +509,32 @@ 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<u32>)>,
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) }
}
/// 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<Value, String>) -> Result<String, String> {
self.finish_with_budget(s, result, DEFAULT_OUTPUT_TOKENS)
}
pub(crate) fn finish_with_budget(self, s: &mut Session, result: Result<Value, String>, tokens: usize) -> Result<String, String> {
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))
}
}

Expand Down Expand Up @@ -649,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<u32>)], 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)
Expand Down Expand Up @@ -881,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<String> = 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<String>) -> Value {
if said.is_empty() {
return r;
}
Expand All @@ -897,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<String>,
earlier_losses: Vec<Value>,
}

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<String> {
let mut notices = self.earlier_notices.clone();
notices.extend(s.notices_since(self.mark).iter().map(|n| n.text.clone()));
notices
}
}

Expand All @@ -924,6 +947,7 @@ fn losses_since(s: &Session, said: &Said) -> Vec<Value> {
e
})
.collect();
out.splice(0..0, said.earlier_losses.clone());
out.extend(kept.into_iter().map(|(code, text)| entry(code, text)));
out
}
Expand Down Expand Up @@ -1080,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<String> = 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.
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
15 changes: 15 additions & 0 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(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<Option<f64>, String> {
match &elevation {
Elevation::None => Ok(None),
Expand Down Expand Up @@ -310,6 +316,15 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(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;
Expand Down
13 changes: 13 additions & 0 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading an overview in place where full resolution exists is an approximation of the data. AGENTS.md ("Never silent") says that should carry a LossCode through notify_loss, so --strict, Python and MCP see it. LossCode::Approximated already exists for this. A plain notify_text(…, false) is for what isn't a loss. The same applies to the surface-elevation notice in crates/engine/src/cmd/design.rs (around line 320). The tests only match the text, so they wouldn't catch the missing code.

Category: agents-md

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);
Expand Down
5 changes: 4 additions & 1 deletion crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1902,7 +1902,7 @@ fn geotiff_note(r: &Raster, bi: usize, cog: bool, band_hint: &str) -> Result<Str
/// A pixel's value in full, as the shortest text that reads back the same `f32`: not a legend's
/// rounded number, which gave 10602 as "11K" (#2761). One too large or too small to read as plain
/// digits has an exponent.
fn pixel_text(v: f32) -> 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}") }
}

Expand All @@ -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<Option<f32>> = (0..r.band_count()).map(|b| r.value(b, col, row)).collect();
if vals.iter().all(Option::is_none) {
return None;
Expand Down
92 changes: 82 additions & 10 deletions crates/engine/src/cmd/reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,25 @@ pub struct Read {
pub(crate) struct ReadWork {
name: &'static str,
key: String,
work: Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>,
work: Work,
}

type Answer = Box<dyn Any + Send>;
#[cfg(target_arch = "wasm32")]
type AsyncWork = Box<dyn FnOnce(Box<dyn FnOnce(Answer) + Send>) + Send>;
enum Work {
Blocking(Box<dyn FnOnce() -> Answer + Send>),
#[cfg(target_arch = "wasm32")]
Async(AsyncWork),
}
impl Work {
fn run(self) -> Result<Answer, String> {
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"))]
Expand Down Expand Up @@ -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<dyn FnOnce(Result<Read, String>) + 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.
Expand All @@ -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(())
})
})
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -299,6 +347,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized<CommandOp>, 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)?;
Expand Down Expand Up @@ -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<T: Send + 'static>(name: &'static str, key: String, work: impl FnOnce() -> T + Send + 'static) -> ReadWork {
ReadWork { name, key, work: Box::new(move || Box::new(work()) as Box<dyn Any + Send>) }
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"))]
Expand All @@ -422,6 +478,22 @@ pub(crate) fn taking<T: Send + 'static>(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<T: Send + 'static>(
name: &'static str,
key: String,
start: impl FnOnce(Box<dyn FnOnce(T) + Send>) + 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<T: 'static>(s: &mut Session, key: &str) -> Option<T> {
if s.read_ahead.as_ref().is_none_or(|r| r.key != key) {
Expand Down
Loading
Loading