Skip to content
Merged
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
6 changes: 4 additions & 2 deletions apps/rustgis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,11 +477,13 @@ impl eframe::App for App {

#[cfg(target_os = "macos")]
impl App {
/// The menu bar: built once the app runs, again for a new language or shortcut; its items
/// The menu bar: built once the app runs, again for a new language, shortcut or extension
/// choice; its items
/// greyed out as their commands are; the commands chosen from it run, unless a dialog (Save
/// changes?) has the keys, as the keymap's do.
fn menus(&mut self, ctx: &egui::Context) {
// The shortcuts shown can only change with the language or the keymap.
// The items and shortcuts shown can only change with the language, the keymap or the
// extensions that are on.
let seen = (self.0.chosen_lang(), self.0.shortcuts_fingerprint());
if self.2.seen != Some(seen) {
self.2.seen = Some(seen);
Expand Down
25 changes: 23 additions & 2 deletions apps/rustgis/src/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,18 @@ fn shortcut(app: &RustGisApp, action: Action, fixed: Option<(Key, bool)>) -> Opt
app.shortcuts_of(command).into_iter().find(|k| k.modifiers.command && !matches!(k.logical_key, Key::Z | Key::Y))
}

/// The app's own items, in order, with their shortcuts now.
/// Whether an item's command belongs to an extension that is off: the menus leave it out.
fn hidden(app: &RustGisApp, action: Action) -> bool {
matches!(action, Command(id, _) if app.command_hidden(id))
}

/// The app's own items shown now, in order, with their shortcuts.
fn own_items(app: &RustGisApp) -> impl Iterator<Item = (String, &'static str, Action, Option<KeyboardShortcut>)> + '_ {
MENUS.iter().enumerate().flat_map(move |(m, (_, rows))| {
rows.iter().enumerate().filter_map(move |(r, row)| match *row {
Item(label, action, fixed) => Some((format!("rustgis.{m}.{r}"), label, action, shortcut(app, action, fixed))),
Item(label, action, fixed) if !hidden(app, action) => {
Some((format!("rustgis.{m}.{r}"), label, action, shortcut(app, action, fixed)))
}
_ => None,
})
})
Expand Down Expand Up @@ -353,6 +360,7 @@ impl MenuBar {
let sub = Submenu::new(label(lang, title), true);
for row in *rows {
match *row {
Item(_, action, _) if hidden(app, action) => {}
Item(..) => {
let (id, text, action, shortcut) = own.next().ok_or("the menu's items are out of step")?;
let enabled = enabled_now(app, action, false);
Expand Down Expand Up @@ -544,6 +552,19 @@ mod tests {
assert_eq!(command_of(Command("ui.tab", r#"{"tab":"Settings"}"#)).map(|c| c.1["tab"].clone()), Some(Value::from("Settings")));
}

/// The AI Assistant's item leaves the menus while its extension is off, and the bar is built
/// again for it.
#[test]
fn the_items_of_an_extension_that_is_off_are_left_out() {
let mut app = RustGisApp::new(Session::new(Project::default()));
let offered = |app: &RustGisApp| own_items(app).any(|(_, label, ..)| label == "AI Assistant");
assert!(offered(&app));
let before = signature(&app);
assert!(app.run("extension.disable", serde_json::json!({"id": "assistant"})).is_ok());
assert!(!offered(&app));
assert_ne!(signature(&app), before);
}

const UNDO: Action = Keys { command: "edit.undo", fallback: (Key::Z, false) };
const REDO: Action = Keys { command: "edit.redo", fallback: (Key::Z, true) };

Expand Down
42 changes: 38 additions & 4 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,19 @@ pub struct Agent {
/// Delegations for the app to start ([`Agent::take_delegations`]).
delegations: Vec<Delegation>,
/// Threads' reports waiting for the assistant to be free ([`Agent::deliver`]).
reports: Vec<(String, String, String, bool)>,
reports: Vec<Report>,
}

/// A thread's report waiting for the model, and the line the transcript shows for it, each cut
/// from the report as written so that what a cut says counts what the thread wrote.
struct Report {
thread: String,
label: String,
/// For the model: at most [`tools::MAX_RESULT`] characters.
text: String,
/// For the transcript: shorter, and saying when the thread failed.
note: String,
error: bool,
}

/// An agent thread on this computer: an ACP session that works in the background and takes
Expand Down Expand Up @@ -262,7 +274,9 @@ impl Agent {
let Some(t) = self.threads.iter_mut().find(|t| t.id == thread) else { return };
t.working = false;
let label = t.agent.label.to_string();
self.reports.push((thread.to_string(), label, tools::clip(&report, tools::MAX_RESULT), error));
let failed = if error { " failed" } else { "" };
let note = format!("{thread} ({label}){failed}: {}", tools::clip(&report, 600));
self.reports.push(Report { thread: thread.to_string(), label, text: tools::clip(&report, tools::MAX_RESULT), note, error });
}

/// A thread ended (stopped, closed, or its process exited): it takes no more follow-ups.
Expand All @@ -280,8 +294,8 @@ impl Agent {
let mut message = String::from(
"(Not from the user: agent threads working in the background have reported. Tell the user briefly what came of it.)",
);
for (id, label, report, error) in std::mem::take(&mut a.reports) {
a.transcript.push(Entry::Note(Note::text(format!("{id} ({label}): {}", tools::clip(&report, 600)))));
for Report { thread: id, label, text: report, note, error } in std::mem::take(&mut a.reports) {
a.transcript.push(Entry::Note(Note::text(note)));
let quoted = report.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
let quoted = tools::bounded_json(&serde_json::json!({"report":quoted}), a.config.tool_output_token_limit);
message.push_str(&format!(
Expand Down Expand Up @@ -917,6 +931,7 @@ 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);
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) {
Ok((c, images)) => (c, false, images),
Expand All @@ -927,6 +942,13 @@ impl Agent {
};
let shown = if allow { content.clone() } else { "Declined".to_string() };
self.record(call, content, shown, error, images);
// A call that turned the AI Assistant off ends its reply: the calls after it aren't run.
if was_on && !s.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) {
let why = "Not run: an earlier call turned the AI Assistant off.";
while matches!(&self.state, State::Calls(q, _) if !q.is_empty()) {
self.record_front(why.to_string(), why.to_string(), true);
}
}
}

/// Takes the first waiting call off the queue with its result (and what the transcript shows).
Expand Down Expand Up @@ -1152,6 +1174,18 @@ impl Agent {
self.halt(Entry::Note(Note::new("Stopped.")), "Stopped by the user.", "Stopped by the user.");
}

/// Ends everything that would go on by itself, keeping the conversation: the run stops, and
/// the agent threads are forgotten. Reports waiting for the model stay in the transcript and
/// aren't sent to it.
pub fn suspend(&mut self) {
self.stop();
self.threads.clear();
self.delegations.clear();
for report in std::mem::take(&mut self.reports) {
self.transcript.push(Entry::Note(Note::text(report.note)));
}
}

/// Runs one step of the conversation. A bug in RustGIS that panics while reading a reply or
/// running its calls ends the turn with an error in the transcript instead of taking the app
/// down with it (the commands it runs are guarded the same way by `Session::run`). As there,
Expand Down
44 changes: 44 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,30 @@ fn always_allow_is_per_command_and_never_for_reserved_actions() {
}
}

/// A call that turns the AI Assistant off, approved, ends its reply: a call after it that needs
/// no approval isn't run, and says why.
#[test]
fn calls_after_one_turning_the_assistant_off_are_not_run() {
let mut s = sample();
let mut a = Agent::new(cfg("openai"), &s);
let Step::Send(_) = a.ask("x", &s) else { panic!("expected a request") };
let before = s.map().center_lonlat();
let run = |command: &str, params: Value| json!({"command": command, "params": params}).to_string();
let reply = json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [
{"id": "c0", "type": "function", "function": {"name": "run_command", "arguments": run("extension.disable", json!({"id": "assistant"}))}},
{"id": "c1", "type": "function", "function": {"name": "run_command", "arguments": run("map.goToXY", json!({"lon": 2.35, "lat": 48.85, "scale": 5000000}))}}
]}, "finish_reason": "tool_calls"}]});
assert_eq!(a.receive(a.generation(), ok(reply), &mut s), Step::Confirm);
assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("extension.disable")));
// Nothing left to ask about or run: the results go back.
assert!(matches!(a.decide(true, false, &mut s), Step::Send(_)));
assert!(!s.extensions().is_on("assistant"));
let after = s.map().center_lonlat();
assert!((after.x - before.x).abs() < 1e-9 && (after.y - before.y).abs() < 1e-9, "the map moved to {after:?}");
let not_run = |e: &Entry| matches!(e, Entry::Tool { result, error: true, .. } if result.contains("turned the AI Assistant off"));
assert_eq!(a.transcript.iter().filter(|e| not_run(e)).count(), 1, "{:?}", a.transcript);
}

#[test]
fn stopping_a_request_drops_its_message() {
let s = sample();
Expand Down Expand Up @@ -3895,6 +3919,26 @@ fn the_assistant_hands_tasks_to_agent_threads_in_the_background() {
assert_eq!(a.threads()[0].id, "claude-code-2", "thread ids aren't reused");
a.clear();
assert!(a.threads().is_empty() && a.take_delegations().is_empty());
// Suspended (the app turned the assistant off): a report waiting stays in the transcript and
// is never sent.
assert!(matches!(a.ask("once more", &s), Step::Send(_)));
let call = calls("delegate", json!({"task": "w", "agent": "claude-code"}));
assert!(matches!(a.receive(a.generation(), ok(call), &mut s), Step::Send(_)));
let thread = a.threads()[0].id.clone();
// A long report from a thread that failed: the transcript says it failed, and its cut counts
// what the thread wrote.
let long = "x".repeat(tools::MAX_RESULT + 100);
a.thread_report(&thread, long, true);
a.suspend();
assert!(!a.busy() && a.threads().is_empty() && a.take_delegations().is_empty());
assert!(a.deliver(&s).is_none(), "not sent to the model");
let said = format!("{thread} (Claude Code) failed: ");
let cut = format!("(cut: {} characters in all)", tools::MAX_RESULT + 100);
assert!(
a.transcript.iter().any(|e| matches!(e, Entry::Note(n) if n.to_string().starts_with(&said) && n.to_string().ends_with(&cut))),
"{:?}",
a.transcript.last()
);
// The command line offers no agents: such a delegation is refused.
let mut c = Agent::new(cfg("openai"), &s);
let mut replies = VecDeque::from(vec![ok(calls("delegate", json!({"task": "z", "agent": "codex"}))), ok(say("Couldn't."))]);
Expand Down
45 changes: 40 additions & 5 deletions crates/engine/src/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ pub struct Extension {
pub name: &'static str,
/// One sentence on what it adds.
pub description: &'static str,
/// The caption of its own ribbon tab (`extension:<id>`), or `None` for a group on the Plugins
/// tab.
/// The caption of its own ribbon tab (`extension:<id>`), or `None` for one without a tab:
/// its buttons are at `place`, or in a group on the Plugins tab.
pub tab: Option<&'static str>,
/// Where its buttons are, for one that adds them to RustGIS's own tabs (`Tab › Group`).
pub place: Option<&'static str>,
/// Whether the desktop and web apps start with it on until the user says otherwise.
pub default_on: bool,
/// The command ids it owns.
/// The command ids it owns: the engine's, and the front end's `ui.*` ones, which the front
/// end refuses while it is off.
pub commands: &'static [&'static str],
}

Expand All @@ -42,6 +45,7 @@ pub const IMAGERY: Extension = Extension {
name: "Imagery",
description: "Ortho and reality mapping, georeferencing, image analysis and classification, deep learning, mensuration and hosted imagery, on a tab of its own.",
tab: Some("Imagery"),
place: None,
default_on: false,
commands: &[
"imagery.workspace",
Expand All @@ -67,8 +71,21 @@ pub const IMAGERY: Extension = Extension {
],
};

/// The AI Assistant: the chat pane, its buttons and the local agents it starts. The MCP server
/// (`rustgis-cli mcp` and the desktop app's MCP Relay), for agents the user runs, and
/// `rustgis-cli ask` are no part of it.
pub const ASSISTANT: Extension = Extension {
id: "assistant",
name: "AI Assistant",
description: "A chat pane that answers questions about your data and acts on the map, using the AI model you choose.",
tab: None,
place: Some("Analyze › AI"),
default_on: true,
commands: &["ui.pane.assistant"],
};

/// Every extension, in the order the Extensions window lists them.
pub const ALL: &[Extension] = &[IMAGERY];
pub const ALL: &[Extension] = &[IMAGERY, ASSISTANT];

/// The most entries the setting keeps (a hand-edited or hostile one can't grow without bound).
const MAX_ENTRIES: usize = 256;
Expand Down Expand Up @@ -222,7 +239,8 @@ mod tests {
for e in ALL {
assert!(e.id.chars().all(|c| c.is_ascii_lowercase() || c == '-'), "{}", e.id);
for c in e.commands {
assert!(registry.iter().any(|s| s.id == *c), "{} owns {c}, which isn't a command", e.id);
// `ui.*` commands are the front end's, which checks them against its own.
assert!(c.starts_with("ui.") || registry.iter().any(|s| s.id == *c), "{} owns {c}, which isn't a command", e.id);
assert_eq!(owner(c).map(|o| o.id), Some(e.id), "{c} is owned twice");
}
}
Expand All @@ -240,6 +258,23 @@ mod tests {
assert!(chosen.is_on("imagery"));
}

#[test]
fn the_assistant_is_on_until_the_user_turns_it_off() {
const { assert!(ASSISTANT.default_on) };
let (apps, _) = State::from_setting(None);
assert!(apps.is_on("assistant"));
assert_eq!(apps.blocks("ui.pane.assistant"), None);
let (mut off, said) = State::from_setting(Some(r#"{"assistant": false}"#));
assert_eq!(said, None);
let why = off.blocks("ui.pane.assistant").unwrap_or_default();
assert!(why.contains("AI Assistant extension, which is off"), "{why}");
// The relay is for agents the user runs: no extension owns it.
assert_eq!(off.blocks("ui.mcpRelay"), None);
assert!(off.set("assistant", true).is_ok());
assert_eq!(off.blocks("ui.pane.assistant"), None);
assert!(off.to_setting().is_some_and(|t| t.contains("\"assistant\":true")));
}

/// Clip, resample, mosaic, project and rasterize serve any raster (#2823): no extension owns them.
#[test]
fn general_raster_commands_are_in_no_extension() {
Expand Down
5 changes: 5 additions & 0 deletions crates/ui-egui/src/agentthreads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ pub struct Threads {
}

impl Threads {
/// How many threads there are, working or waiting for a follow-up.
pub(crate) fn count(&self) -> usize {
self.runs.len()
}

/// Publish the shared approval setting synchronously to every live ACP session.
pub(crate) fn set_auto(&self, auto: bool) {
for t in &self.runs {
Expand Down
Loading
Loading