diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index fbe7053bd2..67b716ba33 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -676,6 +676,17 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen } let pictures = ask_pictures(args)?; eprintln!("[{} ยท {}]", cfg.provider, cfg.model); + if let Ok(asked) = std::env::var(provider::PAUSE_ENV) + && !asked.trim().is_empty() + && !provider::Pause::understood(&asked) + { + // A notice, as the app gives it, printed here. + let mark = s.notice_mark(); + s.notify(format!("{} is {asked:?}, not a number of steps (1 to 10000) or off: the default is used", provider::PAUSE_ENV), true); + for n in s.notices_since(mark) { + eprintln!("rustgis-cli: {}", n.text); + } + } let yes = args.iter().any(|a| a == "--yes"); let trace_key = cfg.key.clone(); let mut a = Agent::new(cfg, s); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 968ee83d91..69167c1f31 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -2,7 +2,7 @@ //! what came back ([`Agent::receive`]), runs the model's tool calls against the session, and //! stops for the user's approval when a call needs it ([`Step::Confirm`]). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use crate::attach::Picture; use crate::provider::{self, Config, HttpRequest, HttpResponse, Note, ToolCall, ToolImage, ToolResult, Turn}; @@ -15,8 +15,9 @@ use std::sync::{ }; static CONVERSATIONS: AtomicU64 = AtomicU64::new(1); -/// Model requests per user message before the agent stops and reports back. -pub const MAX_STEPS: u32 = 16; +/// How many times the same call, with the same arguments, may fail in one run before the run +/// pauses: a model stuck on it would otherwise spend requests on it until the user notices. +pub const SAME_FAILURES: u32 = 3; /// What the main assistant is told about subagents, after RustGIS's own instructions. const DELEGATE_PROMPT: &str = "\n\nSubagents: hand multi-step work whose details needn't stay in this conversation (exploring a \ @@ -35,7 +36,7 @@ then end with a short report of what you did and found (layer names, numbers, id all the main assistant sees. Don't ask questions; where something is unclear, make a sensible choice and say which."; /// Retries per provider request (see [`provider::retry_delay`]), reset after an accepted response. -/// This is not a whole-conversation/run allowance; [`MAX_STEPS`] separately bounds a user run. +/// This is not a whole-conversation/run allowance; [`Config::pause_after`] separately pauses a user run. pub const MAX_RETRIES: u32 = 3; /// What the caller does next. @@ -166,8 +167,13 @@ pub struct Agent { allowed: Vec, /// The agents on this computer the model may delegate to ([`acp`]). harnesses: Vec<&'static acp::AgentSpec>, - /// Model requests left for this message (a subagent shares its parent's budget). - max_steps: u32, + /// A subagent's model requests: what was left of its parent's for this message, if those are + /// limited. The main assistant's limit is its settings' ([`Config::pause_after`]). + budget: Option, + /// The run paused ([`Agent::can_continue`]). + paused: bool, + /// The calls that failed in this run and haven't worked since, and how often. + failures: HashMap<(String, String), u32>, /// Agent threads on this computer, working or waiting for a follow-up. threads: Vec, threads_started: u32, @@ -248,7 +254,9 @@ impl Agent { threads_started: 0, delegations: Vec::new(), reports: Vec::new(), - max_steps: MAX_STEPS, + budget: None, + paused: false, + failures: HashMap::new(), } } @@ -304,7 +312,8 @@ impl Agent { /// When the assistant is free and threads have reported: their reports, as a message the /// model answers (it tells the user what came of the work). pub fn deliver(&mut self, s: &Session) -> Option { - if self.busy() || self.reports.is_empty() { + // A paused run goes on when the user says so, not when a thread reports. + if self.busy() || self.paused || self.reports.is_empty() { return None; } Some(self.guard(|a| { @@ -335,7 +344,7 @@ impl Agent { } _ => a.turns.push(Turn::User(message, Vec::new())), } - a.steps = 0; + a.begin_run(); a.retries = 0; a.overflow_compacted = false; a.send() @@ -353,7 +362,8 @@ impl Agent { child.no_reasoning = self.no_reasoning.clone(); child.no_images = self.no_images.clone(); // The budget is the main assistant's: what's left of it for this message. - child.max_steps = self.max_steps.saturating_sub(self.steps).max(1); + // The reply that delegates is a step too, counted once its calls are answered. + child.budget = self.limit().map(|n| n.saturating_sub(self.steps.saturating_add(1))); child.base_system = system_prompt(s) + SUBAGENT_PROMPT; child.set_skills(self.skills.clone()); child @@ -465,6 +475,42 @@ impl Agent { Scope::assistant(self.conversation, self.live.clone()) } + /// Whether the run paused and can go on ([`Agent::resume`]). + pub fn can_continue(&self) -> bool { + // The next request answers the results waiting for the model, or their summary when the + // conversation was compacted meanwhile. + self.paused && !self.busy() && matches!(self.turns.last(), Some(Turn::Results(_) | Turn::User(..))) + } + + /// Goes on with a paused run as if it hadn't paused, for as many steps again. Does nothing + /// when there is none. + pub fn resume(&mut self, s: &Session) -> Step { + if !self.can_continue() { + return Step::Done; + } + self.guard(|a| { + a.always.retain(|r| r.belongs_to_generation(s.project_generation())); + if !a.live.0.load(Ordering::SeqCst) { + a.live = Arc::new(tools::Live::default()); + } + a.begin_run(); + a.overflow_compacted = false; + a.send() + }) + } + + /// Steps and failures are counted afresh. + fn begin_run(&mut self) { + self.steps = 0; + self.paused = false; + self.failures.clear(); + } + + /// The steps after which this run pauses; `None` for no limit. + fn limit(&self) -> Option { + if self.depth == 0 { self.config.pause_after() } else { self.budget } + } + /// Changes in the generation tell a caller its response is stale. pub fn generation(&self) -> u64 { self.generation @@ -477,7 +523,7 @@ impl Agent { self.turns.clear(); self.transcript.clear(); self.state = State::Idle; - self.steps = 0; + self.begin_run(); self.last_context.clear(); self.always.clear(); self.pending_policy = None; @@ -577,7 +623,7 @@ impl Agent { } _ => self.turns.push(Turn::User(message, pictures)), } - self.steps = 0; + self.begin_run(); self.retries = 0; self.overflow_compacted = false; self.send() @@ -979,11 +1025,21 @@ impl Agent { let State::Calls(_, results) = std::mem::replace(&mut self.state, State::Idle) else { return Step::Done }; self.turns.push(Turn::Results(results)); self.steps += 1; - if self.steps >= self.max_steps { - self.transcript.push(Entry::Note(Note::with( - "Stopped after {steps} steps; say \"continue\" to go on.", - [("steps", self.max_steps.to_string())], - ))); + if let Some(((name, args), n)) = self.failures.iter().find(|(_, n)| **n >= SAME_FAILURES) { + let note = Note::with( + "Paused: the same action failed {n} times ({action}).", + [("n", n.to_string()), ("action", tools::clip(&format!("{name} {args}"), 80))], + ); + self.transcript.push(Entry::Note(note)); + self.paused = true; + return Step::Done; + } + if self.limit().is_some_and(|most| self.steps >= most) { + // A subagent's steps are its parent's, which pauses in its turn and says so. + if self.depth == 0 { + self.transcript.push(Entry::Note(Note::with("Paused after {steps} steps.", [("steps", self.steps.to_string())]))); + } + self.paused = true; return Step::Done; } self.send() @@ -1006,7 +1062,15 @@ impl Agent { ("The user declined this action. Don't retry it; ask what they'd like instead.".to_string(), true, Vec::new()) }; let shown = if allow { content.clone() } else { "Declined".to_string() }; + let key = (call.name.clone(), call.args.to_string()); self.record(call, content, shown, error, images); + // The user declining it isn't the call failing. + if !allow && let Some(n) = self.failures.get_mut(&key) { + *n = n.saturating_sub(1); + if *n == 0 { + self.failures.remove(&key); + } + } // 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."; @@ -1025,6 +1089,12 @@ impl Agent { /// A call's result, for the transcript and the next request. fn record(&mut self, call: ToolCall, content: String, shown: String, error: bool, images: Vec) { + let key = (call.name.clone(), call.args.to_string()); + if error { + *self.failures.entry(key).or_default() += 1; + } else { + self.failures.remove(&key); + } self.transcript.push(Entry::Tool { name: call.name.clone(), summary: tools::summary(&call), result: shown, error }); if let State::Calls(_, results) = &mut self.state { results.push(ToolResult { id: call.id, name: call.name, content, error, images }); @@ -1111,6 +1181,11 @@ impl Agent { self.record_front(e.clone(), e, true); return self.drain(s); } + if self.limit().is_some_and(|n| self.steps.saturating_add(1) >= n) { + let e = "this message's steps ran out before the subagent could start".to_string(); + self.record_front(e.clone(), e, true); + return self.drain(s); + } let mut child = Box::new(self.subagent(s, allowed)); let step = child.ask(&task, s); self.child = Some(child); @@ -1172,6 +1247,13 @@ impl Agent { /// A subagent's report: its last reply, or what stopped it. fn report(&self) -> (String, bool) { + if self.paused { + let why = match self.failures.iter().find(|(_, n)| **n >= SAME_FAILURES) { + Some(((name, args), n)) => format!("the same call failed {n} times: {}", tools::clip(&format!("{name} {args}"), 200)), + None => "this message's steps ran out".to_string(), + }; + return (format!("The subagent stopped before it finished ({why}). What it had done stays."), true); + } match self.transcript.iter().rev().find(|e| matches!(e, Entry::Assistant(_) | Entry::Error(_))) { Some(Entry::Assistant(text)) => (text.clone(), false), Some(Entry::Error(e)) => (format!("The subagent stopped: {e}"), true), @@ -1224,6 +1306,7 @@ impl Agent { pub fn project_replaced(&mut self) { self.stop(); self.state = State::Idle; + self.paused = false; self.always.clear(); self.last_context.clear(); self.preview = None; @@ -1238,6 +1321,8 @@ impl Agent { pub fn stop(&mut self) { self.live.0.store(false, Ordering::SeqCst); self.pending_policy = None; + // A paused run is ended too: Continue doesn't come back for it. + self.paused = false; if !self.busy() { return; } diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 526545b966..9e25067953 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -236,6 +236,55 @@ pub struct Config { pub openrouter_private: bool, /// Requested tool output token estimate (default 10,000); the 24,000-token hard limit still applies. pub tool_output_token_limit: usize, + /// When a run pauses to ask whether to go on ([`Config::pause_after`]). + pub pause: Pause, +} + +/// The steps (replies that call tools) after which a run pauses when each request is billed. +pub const METERED_STEPS: u32 = 50; + +/// The environment variable that sets when runs pause. +pub const PAUSE_ENV: &str = "RUSTGIS_ASSISTANT_PAUSE_AFTER"; + +/// The most steps a pause may be set to. +pub const MAX_PAUSE: u32 = 10_000; + +/// When a run pauses to ask whether to go on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Pause { + /// After [`METERED_STEPS`] where requests are billed, never on a plan or a local model. + #[default] + ByBilling, + Never, + /// After this many steps. + After(u32), +} + +impl Pause { + /// The choice as the preferences keep it, and as `RUSTGIS_ASSISTANT_PAUSE_AFTER` gives it: a + /// number of steps, `off` or `default`. Anything else is the default too. + pub fn from_pref(text: Option<&str>) -> Pause { + match text.map(str::trim) { + Some("off") => Pause::Never, + Some(n) => n.parse().ok().filter(|n| (1..=MAX_PAUSE).contains(n)).map_or(Pause::ByBilling, Pause::After), + None => Pause::ByBilling, + } + } + + /// Whether `text` is a choice [`Pause::from_pref`] reads, not one it falls back from. + pub fn understood(text: &str) -> bool { + matches!(text.trim(), "off" | "default") || Pause::from_pref(Some(text)) != Pause::ByBilling + } + + /// The choice in the form the preferences keep. + pub fn to_pref(self) -> String { + match self { + // Not empty: an empty preference counts as unset, so the environment's would win. + Pause::ByBilling => "default".into(), + Pause::Never => "off".into(), + Pause::After(n) => n.to_string(), + } + } } impl std::fmt::Debug for Config { @@ -271,6 +320,22 @@ impl Config { .and_then(|s| s.parse().ok()) .filter(|n| *n > 0) .unwrap_or(crate::tools::DEFAULT_OUTPUT_TOKENS), + pause: Pause::from_pref(env(PAUSE_ENV).as_deref()), + } + } + + /// Whether each request is billed: not those on a ChatGPT plan, nor to a server on this + /// computer or its network. + pub fn metered(&self) -> bool { + !self.login() && !local_url(&self.base_url) + } + + /// The steps after which a run pauses to ask whether to go on; `None` for never. + pub fn pause_after(&self) -> Option { + match self.pause { + Pause::ByBilling => self.metered().then_some(METERED_STEPS), + Pause::Never => None, + Pause::After(n) => Some(n.max(1)), } } @@ -589,9 +654,18 @@ pub fn allowed_url(url: &str) -> bool { if authority.is_empty() || authority.contains('@') { return false; } - if https { - return true; - } + https || local_authority(authority) +} + +/// Whether `url` is a server on this computer or the local network. +fn local_url(url: &str) -> bool { + let url = url.trim(); + let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://")); + rest.and_then(|r| r.split(['/', '?', '#']).next()).is_some_and(|a| !a.contains('@') && local_authority(a)) +} + +/// Whether an address's host (and port) is this computer or the local network. +fn local_authority(authority: &str) -> bool { let host = if let Some(v6) = authority.strip_prefix('[') { v6.split(']').next().unwrap_or("") } else { @@ -771,7 +845,8 @@ pub const NOTE_TEMPLATES: &[&str] = &[ "Pictures you attached don't go to {agent}: it gets the task's text only.", "{name}: the picture can't be encoded ({why})", "{name}: the picture is too heavy to send, even drawn small", - "Stopped after {steps} steps; say \"continue\" to go on.", + "Paused after {steps} steps.", + "Paused: the same action failed {n} times ({action}).", "Stopped.", ]; diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index cdc7803ba7..72ba0aaa5b 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use rustgis_engine::{Project, Session}; use serde_json::{Value, json}; -use crate::agent::{Agent, Entry, INTERNAL_ERROR, MAX_RETRIES, MAX_STEPS, Step, run_blocking}; +use crate::agent::{Agent, Entry, INTERNAL_ERROR, MAX_RETRIES, SAME_FAILURES, Step, run_blocking}; use crate::chatgpt; use crate::provider::*; use crate::tools; @@ -56,6 +56,7 @@ fn cfg(provider: &str) -> Config { reasoning: None, openrouter_private: true, tool_output_token_limit: crate::tools::DEFAULT_OUTPUT_TOKENS, + pause: Pause::ByBilling, } } @@ -983,7 +984,7 @@ fn steps_are_bounded_and_stop_works() { }, |_, _, _| true, ); - assert_eq!(n, MAX_STEPS as usize); + assert_eq!(n, METERED_STEPS as usize); assert!(matches!(a.transcript.last(), Some(Entry::Note(_)))); // A stale response (after a stop) is dropped. let Step::Send(_) = a.ask("again", &s) else { panic!("expected a request") }; @@ -993,6 +994,118 @@ fn steps_are_bounded_and_stop_works() { assert!(!a.transcript.iter().any(|e| matches!(e, Entry::Assistant(t) if t == "late"))); } +#[test] +fn runs_pause_by_steps_only_where_requests_are_billed_unless_set() { + let after = |provider: &str, url: &str| { + let mut c = cfg(provider); + if !url.is_empty() { + c.base_url = url.into(); + } + c.pause_after() + }; + let billed = Some(METERED_STEPS); + assert_eq!(after("anthropic", ""), billed); + assert_eq!(after("custom", "https://llm.example/v1"), billed); + assert_eq!(after("custom", "https://localhost.example/v1"), billed); + assert_eq!(after("custom", "http://localhost@llm.example/v1"), billed); + for url in ["", "http://127.0.0.1:1234/v1", "https://studio.local/v1", "http://192.168.1.4/v1", "http://[::1]:80/v1"] { + assert_eq!(after("custom", url), None, "{url}"); + } + assert_eq!((after("ollama", ""), after("chatgpt", "")), (None, None)); + let set = |text| Config { pause: Pause::from_pref(Some(text)), ..cfg("anthropic") }.pause_after(); + assert_eq!((set("off"), set("7")), (None, Some(7))); + // What isn't a choice leaves the default. + assert_eq!((set(""), set("0"), set("-1"), set("10001"), set("soon")), (billed, billed, billed, billed, billed)); + assert!(Pause::understood("default") && Pause::understood(" 9 ") && !Pause::understood("soon") && !Pause::understood("0")); + for p in [Pause::ByBilling, Pause::Never, Pause::After(12)] { + assert!(!p.to_pref().is_empty(), "an empty preference would be taken for unset"); + assert_eq!(Pause::from_pref(Some(&p.to_pref())), p); + } +} + +#[test] +fn a_paused_run_continues_from_its_results_and_a_subagent_shares_its_steps() { + let mut s = sample(); + let mut a = Agent::new(Config { pause: Pause::After(2), ..cfg("openai") }, &s); + let step = |id: &str| ok(call(id, "list_layers", json!({}))); + let next = |a: &mut Agent, r, s: &mut Session| a.receive(a.generation(), r, s); + assert_eq!(a.resume(&s), Step::Done, "nothing to go on with"); + a.ask("look", &s); + assert!(matches!(next(&mut a, step("1"), &mut s), Step::Send(_)) && !a.can_continue()); + assert_eq!(next(&mut a, step("2"), &mut s), Step::Done); + assert!(a.can_continue()); + let Step::Send(req) = a.resume(&s) else { panic!("expected a request") }; + let messages = body(&req)["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.last().map(|m| m["role"].clone()), Some(json!("tool")), "no message of the user's is made up"); + assert!(!a.can_continue()); + // A subagent has what is left of the steps; its work ends with them, which the pause says once. + let delegate = ok(call("3", "delegate", json!({"task": "look around"}))); + assert!(matches!(next(&mut a, delegate, &mut s), Step::Send(_))); + assert_eq!(next(&mut a, step("4"), &mut s), Step::Done); + assert!(matches!(a.transcript.last(), Some(Entry::Note(n)) if n.to_string() == "Paused after 2 steps."), "no step over"); + let reported = a.transcript.iter().rev().find_map(|e| match e { + Entry::Tool { name, result, error, .. } if name == "delegate" => Some((result.clone(), *error)), + _ => None, + }); + assert!(reported.is_some_and(|(r, error)| error && r.contains("steps ran out"))); + let pauses = a.transcript.iter().filter(|e| matches!(e, Entry::Note(n) if n.template == "Paused after {steps} steps.")).count(); + assert_eq!(pauses, 2); + // With no step left beside the reply's own, none starts, however many are asked for. + let two = json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": (0..2).map(|i| json!({"id": format!("t{i}"), + "type": "function", "function": {"name": "delegate", "arguments": json!({"task": format!("look {i}")}).to_string()}})).collect::>()}}]}); + a.resume(&s); + assert!(matches!(next(&mut a, step("6"), &mut s), Step::Send(_))); + assert_eq!(next(&mut a, ok(two), &mut s), Step::Done); + let refused = + a.transcript.iter().filter(|e| matches!(e, Entry::Tool { result, .. } if result.contains("before the subagent could start"))); + assert_eq!(refused.count(), 2); + // Compacted while paused, it goes on from the summary. + assert!(matches!(a.compact(), Step::Send(_))); + assert_eq!(next(&mut a, ok(say("Looked at the layers; the study is left to do.")), &mut s), Step::Done); + assert!(a.can_continue()); + let Step::Send(req) = a.resume(&s) else { panic!("expected a request") }; + assert!(body(&req).to_string().contains("the study is left to do")); + for id in ["7", "8"] { + next(&mut a, step(id), &mut s); + } + // A stop ends a paused run, and so does a message instead of Continue. + assert!(a.can_continue()); + a.stop(); + assert!(!a.can_continue() && a.resume(&s) == Step::Done); + a.ask("something else", &s); + assert!(!a.can_continue()); +} + +#[test] +fn a_run_without_a_limit_pauses_when_the_same_call_keeps_failing() { + let mut s = sample(); + let mut a = Agent::new(cfg("ollama"), &s); + let bad = |id: &str, layer: &str| ok(call(id, "read_features", json!({"layer": layer}))); + let next = |a: &mut Agent, r, s: &mut Session| a.receive(a.generation(), r, s); + a.ask("read", &s); + // Different calls that fail, however many, aren't a loop. + for i in 0..METERED_STEPS + 10 { + assert!(matches!(next(&mut a, bad(&format!("d{i}"), &format!("none {i}")), &mut s), Step::Send(_)), "{i}"); + } + for i in 1..SAME_FAILURES { + assert!(matches!(next(&mut a, bad(&format!("s{i}"), "none"), &mut s), Step::Send(_))); + // Something that works in between doesn't hide it. + assert!(matches!(next(&mut a, ok(call(&format!("l{i}"), "list_layers", json!({}))), &mut s), Step::Send(_))); + } + assert_eq!(next(&mut a, bad("last", "none"), &mut s), Step::Done); + assert!(matches!(a.transcript.last(), Some(Entry::Note(n)) if n.to_string().contains("failed 3 times (read_features "))); + // Continue gives it as many tries again. + assert!(matches!(a.resume(&s), Step::Send(_))); + assert!(matches!(next(&mut a, bad("again", "none"), &mut s), Step::Send(_))); + // Declining isn't failing. + a.ask("export it", &s); + let export = || ok(call("x", "run_command", json!({"command": "share.exportMap", "params": {"path": "no-dir/declined.png"}}))); + for _ in 0..SAME_FAILURES { + assert_eq!(next(&mut a, export(), &mut s), Step::Confirm); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_)), "declined calls don't pause the run"); + } +} + #[test] fn missing_settings_are_reported() { let s = sample(); diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 026a51b973..5a96ee9568 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -258,6 +258,11 @@ pub(crate) fn save_pref(app: &RustGisApp, key: &str, value: &str) { } } +/// The preference that keeps when a provider's runs pause. +fn pause_pref(provider: &str) -> String { + format!("assistant_pause_{provider}") +} + /// A provider's settings: its defaults and the environment, then what the user saved. fn load_config(app: &mut RustGisApp, provider: &str, ctx: &egui::Context) -> Config { let mut c = Config::from_env(provider); @@ -270,6 +275,9 @@ fn load_config(app: &mut RustGisApp, provider: &str, ctx: &egui::Context) -> Con if provider == "openrouter" { c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).as_deref() != Some("off"); } + if let Some(pause) = pref(app, &pause_pref(provider)) { + c.pause = provider::Pause::from_pref(Some(&pause)); + } if !c.login() { let legacy = pref(app, &format!("assistant_key_{provider}")); #[cfg(not(target_arch = "wasm32"))] @@ -328,6 +336,19 @@ pub(crate) fn ensure_loaded(app: &mut RustGisApp, ctx: &egui::Context) { } let mut agent = Agent::new(cfg, &app.session); app.assistant.local_agents = pref(app, "assistant_local_agents").as_deref() == Some("on"); + // A pause set in the environment that isn't one is said, as the command line says it. + if let Ok(asked) = std::env::var(provider::PAUSE_ENV) + && !asked.trim().is_empty() + && !provider::Pause::understood(&asked) + { + app.session.notify( + crate::i18n::fmt( + "{name} is {value}, not a number of steps or off: the default is used.", + &[("name", provider::PAUSE_ENV), ("value", &asked)], + ), + true, + ); + } #[cfg(not(target_arch = "wasm32"))] { app.assistant.agents_auto = pref(app, "assistant_agents_auto").as_deref() == Some("on"); @@ -510,6 +531,10 @@ pub(crate) fn save_config(app: &mut RustGisApp, c: &Config, ctx: &egui::Context) if c.provider == "openrouter" { save_pref(app, provider::OPENROUTER_PRIVATE_PREF, provider::remember_key_value(c.openrouter_private)); } + // The environment's choice stays there, unless another was made here. + if c.pause != Config::from_env(&c.provider).pause || pref(app, &pause_pref(&c.provider)).is_some() { + save_pref(app, &pause_pref(&c.provider), &c.pause.to_pref()); + } // A key from the environment stays there; a sign-in's tokens live in their own file. let from_env = Config::from_env(&c.provider).key; if c.login() { @@ -1121,6 +1146,40 @@ pub fn stop(app: &mut RustGisApp) { app.assistant.hold(); } +/// Whether the run paused and [`resume`] goes on with it. +pub fn can_continue(app: &RustGisApp) -> bool { + app.assistant.agent.as_ref().is_some_and(Agent::can_continue) && !key_loading(app) +} + +/// Goes on with a paused run. With `never`, the provider's runs no longer pause by their steps, +/// which is remembered. A message being written stays in the box. +pub fn resume(app: &mut RustGisApp, never: bool, ctx: &egui::Context) { + if !can_continue(app) { + return; + } + if never && let Some(agent) = app.assistant.agent.as_mut() { + agent.config.pause = provider::Pause::Never; + let name = pause_pref(&agent.config.provider); + save_pref(app, &name, &provider::Pause::Never.to_pref()); + } + if let Some(step) = with_agent(app, |a, s| a.resume(s)) { + follow(app, step, ctx); + } +} + +/// The steps after which the provider's runs pause, as a settings form changes it; `None` for +/// never. +pub fn pause_choice(cfg: &mut Config, after: Option) { + // The default chosen again stays the default, which follows the provider's billing. + if after == cfg.metered().then_some(provider::METERED_STEPS) { + cfg.pause = provider::Pause::ByBilling; + return; + } + if cfg.pause_after() != after { + cfg.pause = after.map_or(provider::Pause::Never, provider::Pause::After); + } +} + /// Puts a message that isn't being sent into the input box: as the draft when the box is empty /// or already holds it, above newer typing otherwise. A message of pictures alone adds no line. fn to_box(state: &mut AssistantState, text: &str) { diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 2c13221779..3fa9290826 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -244,6 +244,7 @@ fn provider_settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, cfg: &mut Co } ui.end_row(); }); + pause_row(ui, cfg); let preset = provider::preset(&cfg.provider); if cfg.provider == "openrouter" { ui.checkbox(&mut cfg.openrouter_private, tl!("Private routing")) @@ -280,6 +281,45 @@ fn provider_settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, cfg: &mut Co } } +/// After how many steps a run pauses, if it does. +fn pause_row(ui: &mut Ui, cfg: &mut Config) { + ui.horizontal_wrapped(|ui| { + let after = cfg.pause_after(); + let mut on = after.is_some(); + let hint = tl!( + "A step is one reply of the model's that uses tools. By default, runs pause only where the provider bills each request, not on a ChatGPT plan or a model on this computer or its network." + ); + let mut steps = after.unwrap_or(provider::METERED_STEPS); + let label = ui.checkbox(&mut on, tl!("Pause long runs, after this many steps:")).on_hover_text(hint); + ui.add_enabled(on, egui::DragValue::new(&mut steps).range(1..=provider::MAX_PAUSE)).labelled_by(label.id); + assistant::pause_choice(cfg, on.then_some(steps)); + if cfg.pause != provider::Pause::ByBilling && ui.small_button(tl!("Default")).on_hover_text(hint).clicked() { + cfg.pause = provider::Pause::ByBilling; + } + }); +} + +/// The way on from a paused run. +fn paused(app: &mut RustGisApp, ui: &mut Ui, ctx: &egui::Context) { + if !assistant::can_continue(app) { + return; + } + let limited = app.assistant.config().is_some_and(|c| c.pause_after().is_some()); + ui.horizontal_wrapped(|ui| { + if crate::widgets::primary_button(ui, tl!("Continue"), true, vec2(84.0, 26.0)).clicked() { + assistant::resume(app, false, ctx); + } + if limited + && ui + .button(tl!("Continue and don't pause again")) + .on_hover_text(tl!("Runs with this provider no longer pause by their steps. The settings turn it back on.")) + .clicked() + { + assistant::resume(app, true, ctx); + } + }); +} + /// Where the ChatGPT sign-in is kept, as truthfully as is known. fn sign_in_storage_note(account: Option<&chatgpt::Account>) -> String { match account.map(|a| a.kept) { @@ -829,6 +869,7 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context } } } + paused(app, ui, ctx); if app.assistant.waiting() { // The reply so far, as it streams in. if let Some(text) = app.assistant.preview() { @@ -1771,6 +1812,7 @@ pub(crate) mod tests { reasoning: None, openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, + pause: rustgis_assistant::provider::Pause::ByBilling, }; let mut agent = Agent::new(config, &app.session); assert!(matches!(agent.ask("Review only", &app.session), Step::Send(_))); @@ -2255,6 +2297,7 @@ pub(crate) mod tests { reasoning: None, openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, + pause: rustgis_assistant::provider::Pause::ByBilling, }; app.assistant.agent = Some(Agent::new(cfg.clone(), &app.session)); let c = chatgpt::Credentials { access_token: "synthetic-chatgpt-token".into(), ..Default::default() }; @@ -2277,6 +2320,7 @@ pub(crate) mod tests { reasoning: None, openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, + pause: rustgis_assistant::provider::Pause::ByBilling, }; let mut agent = Agent::new(cfg.clone(), &app.session); assert!(matches!(agent.ask("hello", &app.session), Step::Send(_))); diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index ad8f1387e9..17aebf651c 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -525,6 +525,7 @@ mod tests { reasoning: None, openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, + pause: rustgis_assistant::provider::Pause::ByBilling, }; app.assistant.agent = Some(rustgis_assistant::Agent::new(cfg, &app.session)); let layers = app.session.map().layers.len(); diff --git a/crates/ui-egui/src/localagents.rs b/crates/ui-egui/src/localagents.rs index 54e4508886..b86fdbda31 100644 --- a/crates/ui-egui/src/localagents.rs +++ b/crates/ui-egui/src/localagents.rs @@ -685,6 +685,7 @@ mod tests { reasoning: None, openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, + pause: rustgis_assistant::provider::Pause::ByBilling, }; let app = h.state_mut(); let mut a = Agent::new(config, &app.session); diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e3fbf1d6a7..c15ee52efd 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -396,6 +396,16 @@ fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) egui::ScrollArea::vertical().id_salt("touch_assistant_messages").auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); messages(app, ui, t); + if assistant::can_continue(app) { + let ctx = ui.ctx().clone(); + if action(ui, t, tl!("Continue"), ui.available_width(), true, true) { + assistant::resume(app, false, &ctx); + } + let limited = app.assistant.config().is_some_and(|c| c.pause_after().is_some()); + if limited && action(ui, t, tl!("Continue and don't pause again"), ui.available_width(), false, true) { + assistant::resume(app, true, &ctx); + } + } }); } @@ -667,6 +677,24 @@ fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat } } } + label(ui, t, tl!("Pause long runs after this many steps")); + let after = cfg.pause_after(); + // A number set elsewhere is offered among the usual ones. + let mut steps = vec![10, provider::METERED_STEPS, 200, 1000]; + steps.extend(after); + steps.sort_unstable(); + steps.dedup(); + let mut list = vec![("off".to_string(), tl!("Never").to_string())]; + list.extend(steps.iter().map(|n| (n.to_string(), n.to_string()))); + let mut chosen = after.map_or("off".to_string(), |n| n.to_string()); + super::chips(ui, t, "touch_assistant_pause", &list, &mut chosen); + // A tap on the one chosen gives an empty value: the default, which follows the + // provider's billing. + if chosen.is_empty() { + cfg.pause = provider::Pause::ByBilling; + } else { + assistant::pause_choice(&mut cfg, chosen.parse().ok()); + } if let Some(why) = cfg.missing() { ui.label(RichText::new(tl!(why)).size(14.0).color(t.amber)); } else if action(ui, t, if started { tl!("Done") } else { tl!("Start") }, ui.available_width(), true, true) { @@ -1085,6 +1113,38 @@ mod tests { assert_eq!(held.app.assistant.input, "", "Enter sent it, adding no line"); } + #[test] + fn a_paused_run_goes_on_from_the_sheet() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let ctx = held.ctx.clone(); + let mut cfg = held.app.assistant.config().cloned().unwrap(); + let before = (cfg.clone(), held.app.assistant.remember_key()); + assistant::pause_choice(&mut cfg, Some(1)); + assistant::apply_settings(&mut held.app, cfg, before, &ctx); + let step = |id| command(id, "map.zoomIn", json!({})); + answering(&mut held, vec![step("a"), step("b"), step("c"), say("Done zooming.")]); + raise(&held.ctx, Height::Full); + held.app.assistant.input = "Zoom in".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + held.frame(Vec::new()); + assert!(held.find("Paused after 1 steps.").is_some()); + let on = held.find("Continue").unwrap().center(); + held.touch(&[on]); + held.frame(Vec::new()); + // Paused again, until told not to. + assert!(assistant::can_continue(&held.app)); + let on = held.find("Continue and don't pause again").unwrap().center(); + held.touch(&[on]); + for _ in 0..4 { + held.frame(Vec::new()); + } + assert_eq!(held.app.assistant.config().unwrap().pause_after(), None); + assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::Assistant(t) if t == "Done zooming."))); + assert!(held.find("Continue").is_none()); + } + #[test] fn stop_ends_the_run_from_the_sheet_and_from_the_strip_left_while_it_works() { let mut held = Held::new(); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index d9f0166b7b..04b63b0faa 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -141,6 +141,20 @@ field changes the endpoint for providers other than ChatGPT; use the OpenAI-comp path (usually `/v1`) for local servers. Models that call tools well give the best results; small local models may stop early or skip steps. +### Long runs + +A step is one reply of the model's that uses tools. Where the provider bills each request, a run +pauses after 50 steps, with **Continue** and **Continue and don't pause again**. On a ChatGPT plan, +or with a model on this computer or its network, it goes on until it finishes or you press +**Stop**. **Pause long runs** in the settings changes this for each provider, and **Default** goes back to +pausing by billing. A subagent's steps +count as the assistant's. Any run also pauses when the same call, with the same arguments, fails +three times without working in between. Declining one isn't a failure. + +On the command line, a run that pauses ends there. `RUSTGIS_ASSISTANT_PAUSE_AFTER` sets the number +of steps (1 to 10,000), `off` or `default`, for every provider; in the app, a choice in the settings +wins. A value that isn't one of these is said, and the default is used. + ### OpenRouter private routing **Private routing** is on by default for OpenRouter. Every chat request, including summaries