diff --git a/src/app/act.rs b/src/app/act.rs index ccc3d32..4475918 100644 --- a/src/app/act.rs +++ b/src/app/act.rs @@ -347,7 +347,7 @@ impl Workspace { let auto_handoff_model = s.auto_handoff_model.clone(); let default_model = s.default_model(); let text_generation_model = s.text_generation_model.clone(); - let claude_hint = self.claude_exe.as_ref().map_or("not found".to_string(), |p| p.to_string_lossy().into_owned()); + let claude_hint = self.executable(Harness::Claude).map_or("not found".to_string(), |p| p.to_string_lossy().into_owned()); let defaults = s.new_session.clone(); self.executable_errors.clear(); let claude = self.executable_input(&claude_t, &claude_hint, window, cx); diff --git a/src/app/agent_handoff.rs b/src/app/agent_handoff.rs index d0d7275..c6dd209 100644 --- a/src/app/agent_handoff.rs +++ b/src/app/agent_handoff.rs @@ -3,6 +3,7 @@ //! sending the transcript + the user's new message as the first turn. use super::*; +use crate::harness::capabilities::{self, Initiator}; use crate::harness::thread::NoticeKind; /// Entries read from the end before the cut, so a long session is not turned into text whole. @@ -45,11 +46,17 @@ impl Workspace { return; } let Some(mut rec) = self.store.session(id).cloned() else { return }; - if !self.store.data.settings.harness_enabled(to) { + let initiator = if by_agent { Initiator::Automatic } else { Initiator::User }; + let refusal = if !self.store.data.settings.harness_enabled(to) { + Some(format!("{} is unavailable for this session.", to.name())) + } else { + capabilities::handoff(thread.read(cx).harness, to, initiator).refusal().map(String::from) + }; + if let Some(refusal) = refusal { if !by_agent { thread.update(cx, |v, cx| v.paste_text(&message, window, cx)); } - thread.update(cx, |v, cx| v.fail_handoff(format!("{} is unavailable for this session.", to.name()), cx)); + thread.update(cx, |v, cx| v.fail_handoff(refusal, cx)); return; } let cwd = rec.cwd.clone(); @@ -130,7 +137,7 @@ impl Workspace { } } - pub(super) fn reconnect_antigravity_permission(&mut self, id: &str, permission: Permission, window: &mut Window, cx: &mut Context) { + pub(super) fn reconnect_full_access_permission(&mut self, id: &str, permission: Permission, window: &mut Window, cx: &mut Context) { if self.pending_handoffs.contains_key(id) { return; } if self.switching_worktree.contains_key(id) { self.toast("Wait for the worktree switch to finish.", cx); @@ -183,6 +190,15 @@ impl Workspace { self.toast(reason, cx); return; } + let from = thread.read(cx).harness; + let refusal = from.adapter().capabilities.rewind.refusal().or_else(|| { + target_model.as_ref().and_then(|target| capabilities::handoff(from, target.harness, Initiator::User).refusal()) + }); + if let Some(refusal) = refusal { + thread.update(cx, |v, cx| v.paste_text(&message, window, cx)); + self.toast(refusal, cx); + return; + } let Some(mut rec) = self.store.session(id).cloned() else { return }; let cwd = rec.cwd.clone(); let mut meta = rec.agent.clone().unwrap_or_default(); @@ -398,7 +414,7 @@ impl Workspace { pub(super) fn compact_session(&mut self, id: &str, transcript: String, instructions: Option, window: &mut Window, cx: &mut Context) { let Some(thread) = self.live_view(id).and_then(|v| v.thread()).cloned() else { return }; if self.compacting.contains_key(id) || self.pending_handoffs.contains_key(id) || self.switching_worktree.contains_key(id) - || thread.read(cx).has_active_turn() + || thread.read(cx).has_active_turn() || !thread.read(cx).harness.adapter().capabilities.compaction_fallback.allowed() { thread.update(cx, |v, cx| v.cancel_compaction(cx)); return; @@ -413,13 +429,8 @@ impl Workspace { return; }; let meta = rec.agent.clone().unwrap_or_default(); - let gen_model = self.store.data.settings.text_generation_model.clone().unwrap_or_else(|| { - crate::store::TextGenerationModel { - harness: meta.harness, - id: meta.chosen_model.clone().unwrap_or_default(), - } - }); - let env = self.harness_model_env(gen_model.harness).ok(); + let generator = self.summary_model(meta.harness, meta.chosen_model.clone()) + .and_then(|model| Some((self.harness_model_env(model.harness).ok()?, model))); let system = match instructions { Some(ref extra) if !extra.trim().is_empty() => format!( "Summarize the following coding-session conversation concisely so work can continue in a fresh context window. \ @@ -431,7 +442,7 @@ impl Workspace { let session_id = id.to_string(); let fallback = condensed_transcript(&transcript, 6000); cx.spawn_in(window, async move |this, cx| { - let summary = if let Some(env) = env { + let summary = if let Some((env, gen_model)) = generator { let timeout = cx.background_executor().timer(std::time::Duration::from_secs(60)); match crate::harness::text_generation::complete(&gen_model, env, &system, &transcript, timeout).await { Ok(text) if !text.trim().is_empty() => text.trim().to_string(), diff --git a/src/app/background.rs b/src/app/background.rs index 4ac1708..565a340 100644 --- a/src/app/background.rs +++ b/src/app/background.rs @@ -157,28 +157,28 @@ impl Workspace { ) } - /// Once a second: derive each Claude session's `Activity` from its terminal output. When one stops working + /// Once a second: derive each terminal session's `Activity` from its agent's own status or its output. When one stops working /// while the user isn't looking at it, mark it for attention, and if the whole window is in the /// background as well, send a system notification. pub(super) fn start_activity_poll(&mut self, window: &Window, cx: &mut Context) { cx.spawn_in(window, async move |this, cx| { - let mut seen = claude::StatusFiles::default(); loop { cx.background_executor().timer(Duration::from_secs(1)).await; - let (statuses, requests, back) = cx + let (statuses, requests) = cx .background_executor() .spawn(async move { - let statuses = Harness::Claude.is_registered().then(claude::claude_home).flatten() - .map(|h| claude::session_statuses(&h, &mut seen)).unwrap_or_default(); - (statuses, crate::mcp::bridge::take_requests(), seen) + let statuses: HashMap = Harness::registered() + .filter_map(|harness| harness.adapter().native_sessions.as_ref()) + .flat_map(|native| (native.statuses)()) + .collect(); + (statuses, crate::mcp::bridge::take_requests()) }) .await; - seen = back; let update = this.update_in(cx, |ws, window, cx| { ws.serve_requests(requests, window, cx); ws.run_pending_switches(&statuses, window, cx); ws.check_open_files(window, cx); - ws.claude_statuses = statuses; + ws.native_statuses = statuses; ws.update_activity(window, cx) }); if update.is_err() { @@ -190,11 +190,11 @@ impl Workspace { } /// Work out each session's row state and alert on a finished turn or a new question. Runs on the activity poll, - /// and at once when a thread's turn ends. A terminal session reads Claude Code's own busy/idle/waiting from the - /// last poll (`claude_statuses`); one it doesn't list (older Claude Code, no registry file) falls back to the - /// terminal-output heuristic. + /// and at once when a thread's turn ends. A terminal session reads its agent's own busy/idle/waiting from the + /// last poll (`native_statuses`); one it doesn't list (an agent that keeps no status, or an older version of one) + /// falls back to the terminal-output heuristic. pub(super) fn update_activity(&mut self, window: &mut Window, cx: &mut Context) { - let statuses = std::mem::take(&mut self.claude_statuses); + let statuses = std::mem::take(&mut self.native_statuses); let window_active = window.is_window_active(); let editing = self.editing(); let shown = self.active_id().cloned(); @@ -260,7 +260,7 @@ impl Workspace { next.insert(l.id.clone(), now); } } - self.claude_statuses = statuses; + self.native_statuses = statuses; self.idle_since.retain(|id, _| next.get(id) == Some(&Activity::Working)); if next != self.activity { self.activity = next; @@ -275,25 +275,25 @@ impl Workspace { for text in toast_notices { self.toast(text, cx); } - self.sync_claude_names(); + self.sync_native_names(); } - /// Claude Code keeps its own session name (`/resume`, Remote Control, the mobile apps). `--name` covers - /// launches; for a running session the name goes to its name file and the mod runs `/rename` once Claude - /// Code is idle. Nothing is typed into the PTY. - fn sync_claude_names(&mut self) { + /// An agent that keeps its own session names (Claude Code's `/resume`, Remote Control, the mobile apps) gets the + /// chosen title. A launch passes it as a flag; for a running session the adapter writes it where the agent picks + /// it up. Nothing is typed into the PTY. + fn sync_native_names(&mut self) { for l in &mut self.live { - let Some((cid, w)) = self + let Some((write_name, cid, w)) = self .store .session(&l.id) - .filter(|r| r.agent.as_ref().is_some_and(|m| m.harness == Harness::Claude)) - .and_then(|r| Some((r.provider_session_id()?, r.chosen_title()?))) - .filter(|(_, w)| l.claude_name.as_deref() != Some(*w)) + .and_then(|r| Some((r.agent.as_ref()?.harness.adapter().native_sessions.as_ref()?.write_name, r))) + .and_then(|(write_name, r)| Some((write_name, r.provider_session_id()?, r.chosen_title()?))) + .filter(|(_, _, w)| l.native_name.as_deref() != Some(*w)) else { continue; }; - l.claude_name = Some(w.to_string()); - claude::write_name(cid, Some(w)); + l.native_name = Some(w.to_string()); + write_name(cid, Some(w)); } } @@ -305,7 +305,7 @@ impl Workspace { self.sync_attached(cx); self.refresh_if_stale(cx); self.refresh_marks(cx); - self.raise_claude_priority(cx); + self.raise_agent_priority(cx); self.refresh_pending(cx); // The steps above redraw when they change something. The sidebar's "5m ago" and the reset countdowns count // in minutes, so they need a redraw only when the minute turns. @@ -316,19 +316,19 @@ impl Workspace { } } - /// Windows: run the Claude sessions above the builds and tests they start. - fn raise_claude_priority(&self, cx: &mut Context) { + /// Windows: run the agent sessions above the builds and tests they start. + fn raise_agent_priority(&self, cx: &mut Context) { #[cfg(windows)] { // Only a session still drawn in a terminal has a process id here. Agents now run as ACP processes, // whose ids the chat view doesn't expose yet, so they keep the normal priority until it does. - let claude_pids: Vec = self + let agent_pids: Vec = self .live .iter() .filter(|l| self.store.session(&l.id).is_some_and(|r| r.kind == SessionKind::Agent)) .filter_map(|l| l.view.terminal()?.read(cx).terminal.process_id()) .collect(); - cx.background_executor().spawn(async move { crate::priority::raise_claude_priority(&claude_pids) }).detach(); + cx.background_executor().spawn(async move { crate::priority::raise_agent_priority(&agent_pids) }).detach(); } #[cfg(not(windows))] let _ = cx; diff --git a/src/app/cross.rs b/src/app/cross.rs index e9aa9c7..e98197d 100644 --- a/src/app/cross.rs +++ b/src/app/cross.rs @@ -205,20 +205,21 @@ impl Workspace { Ok(()) } - /// Start the switches whose session has ended its turn. Looks at Claude Code's own status, as a switch from - /// the menu does, so the call that asked is finished and answered first. + /// Start the switches whose session has ended its turn. Looks at the agent's own status where it keeps one, as a + /// switch from the menu does, so the call that asked is finished and answered first. pub(super) fn run_pending_switches(&mut self, statuses: &std::collections::HashMap, window: &mut Window, cx: &mut Context) { let now = crate::store::now(); let pending = std::mem::take(&mut self.pending_switches); for p in pending { - let claude_id = self.store.session(&p.id) - .filter(|r| r.agent.as_ref().is_some_and(|meta| meta.harness == Harness::Claude)) + let native_id = self.store.session(&p.id) + .filter(|r| r.agent.as_ref().is_some_and(|meta| meta.harness.adapter().native_sessions.is_some())) .and_then(|r| r.provider_session_id()); - // Without a registry entry (older Claude Code) the terminal's own activity decides, as in `switch::inspect`. + // Without a status (an older Claude Code keeps no registry) the view's own activity decides, as in + // `switch::inspect`. let idle = !self.switching_worktree.contains_key(&p.id) && !self.pending_handoffs.contains_key(&p.id) && self.live_view(&p.id).and_then(|v| v.thread()).is_none_or(|t| t.read(cx).can_move_workspace()) - && match claude_id.and_then(|c| statuses.get(c)) { + && match native_id.and_then(|c| statuses.get(c)) { Some(status) => status == "idle", None => self.live_view(&p.id).is_some_and(|v| !v.is_working(cx)), }; @@ -347,6 +348,10 @@ impl Workspace { let effort = effort_for(req.args["effort"].as_str(), model.is_some()); match model { Some(model) if req.args["cross"].as_bool() == Some(true) => { + let from = thread.read(cx).harness; + if let Some(refusal) = crate::harness::capabilities::handoff(from, model.harness, crate::harness::capabilities::Initiator::Automatic).refusal() { + return Err(refusal.into()); + } let message = req.args["message"].as_str().map(str::trim).filter(|m| !m.is_empty()).map_or_else(|| "Carry on with the task from where the conversation left off.".into(), String::from); let name = model.name.clone(); thread.update(cx, |t, cx| t.hand_off_after_turn(model, effort, message, cx)); diff --git a/src/app/fresh_session.rs b/src/app/fresh_session.rs index dcbe515..41e5a96 100644 --- a/src/app/fresh_session.rs +++ b/src/app/fresh_session.rs @@ -30,6 +30,10 @@ impl Workspace { }; { let t = thread.read(cx); + if let Some(refusal) = t.harness.adapter().capabilities.continue_fresh.refusal() { + self.toast(refusal, cx); + return; + } if t.has_active_turn() { self.toast("Wait for the current turn to finish before continuing in a fresh session.", cx); return; @@ -91,18 +95,13 @@ impl Workspace { self.toast("Summarizing session for fresh linked thread…", cx); cx.notify(); - let gen_model = self.store.data.settings.text_generation_model.clone().unwrap_or_else(|| { - crate::store::TextGenerationModel { - harness: snapshot.harness, - id: snapshot.model.clone().unwrap_or_default(), - } - }); - let env = self.harness_model_env(gen_model.harness).ok(); + let generator = self.summary_model(snapshot.harness, snapshot.model.clone()) + .and_then(|model| Some((self.harness_model_env(model.harness).ok()?, model))); let system = "Summarize the following coding-session conversation concisely as a handoff brief for a fresh linked session. \ Preserve the user's goal, key decisions, modified or relevant file paths, symbol names, errors/blockers, and clear next steps."; let session_id = id.to_string(); cx.spawn_in(window, async move |this, cx| { - let summary = if let Some(env) = env { + let summary = if let Some((env, gen_model)) = generator { let timeout = cx.background_executor().timer(std::time::Duration::from_secs(60)); match crate::harness::text_generation::complete(&gen_model, env, system, &transcript, timeout).await { Ok(text) if !text.trim().is_empty() => text.trim().to_string(), diff --git a/src/app/github_pane.rs b/src/app/github_pane.rs index 2aee4eb..03f07b9 100644 --- a/src/app/github_pane.rs +++ b/src/app/github_pane.rs @@ -132,15 +132,10 @@ impl Workspace { } pub(crate) fn sign_in_to_harness(&mut self, harness: Harness, window: &mut Window, cx: &mut Context) { - let (program, args): (&str, &[&str]) = match harness { - Harness::Claude => ("claude", &["auth", "login"]), - Harness::Codex => ("codex", &["login"]), - Harness::OpenCode => ("opencode", &["auth", "login"]), - Harness::Antigravity => ("agy", &[]), - }; - let configured = (harness == Harness::Claude).then(|| self.claude_exe.clone()).flatten(); + let crate::harness::SignIn { program, locate, args, .. } = harness.adapter().sign_in; + let configured = self.executable(harness).map(std::path::Path::to_path_buf); cx.spawn_in(window, async move |this, cx| { - let executable = cx.background_executor().spawn(async move { configured.or_else(|| crate::harness::find(program)) }).await; + let executable = cx.background_executor().spawn(async move { locate(configured.as_deref()) }).await; let _ = this.update_in(cx, |ws, window, cx| { let Some(executable) = executable else { ws.show_toast(format!("{program} was not found. Install its CLI to sign in."), Some(("Check setup".into(), Act::OpenSetup)), cx); diff --git a/src/app/headless.rs b/src/app/headless.rs index c26cee0..64835f7 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -72,7 +72,7 @@ mod skills; impl Workspace { pub(crate) fn start_screenshot_session(&mut self, cwd: PathBuf, window: &mut Window, cx: &mut Context) { self.acp_server = Some(fake_agent(&cwd)); - self.claude_exe = Some("offline-screenshot-agent".into()); + *self.executables.get_mut(crate::harness::Harness::Claude) = Some("offline-screenshot-agent".into()); self.new_session_from_home(Harness::Claude, None, cwd, None, None, None, window, cx); if let Some(id) = self.active_id().cloned() { if let Some(record) = self.store.session_mut(&id) { diff --git a/src/app/headless/agents.rs b/src/app/headless/agents.rs index 1e67564..aae2b06 100644 --- a/src/app/headless/agents.rs +++ b/src/app/headless/agents.rs @@ -61,7 +61,7 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} // Keep deferred restore_open from restoring one of their adapters into this fixture. ws.store = crate::store::Store::load(state.path().join("state.json")); ws.acp_server = Some(server_for("claude")); - ws.claude_exe = Some("unused-by-the-fake-agent".into()); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some("unused-by-the-fake-agent".into()); assert!(ws.new_session_from_home(Harness::Claude, None, work.path().to_path_buf(), Some("initial task".into()), None, Some(Permission::Auto), window, cx)); }); let id = ws.read_with(&cx, |ws, _| ws.active_id().unwrap().clone()); @@ -168,7 +168,7 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} step(&mut cx, &|ws, window, cx| { let meta = ws.store.session(&id).unwrap().agent.as_ref().unwrap(); assert_eq!(meta.session_id, "fake-session"); - assert_eq!(meta.antigravity_full_access, permission == Permission::FullAccess); + assert_eq!(meta.launched_full_access, permission == Permission::FullAccess); let view = ws.live_view(&id).unwrap().thread().unwrap().clone(); assert_eq!(view.read(cx).permission(), Some(permission)); assert_eq!(view.read(cx).draft(cx), "keep this draft"); @@ -295,7 +295,7 @@ fn restart_reuses_provider_session_respects_capabilities_and_records_cache_usage step(&mut cx, &|ws, window, cx| { ws.store = crate::store::Store::load(state.path().join("state.json")); ws.acp_server = Some(server.clone()); - ws.claude_exe = Some("unused-by-the-fake-agent".into()); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some("unused-by-the-fake-agent".into()); ws.new_session_from_home(Harness::Claude, None, work.path().to_path_buf(), Some("first turn".into()), None, None, window, cx); }); let id = ws.read_with(&cx, |ws, _| ws.active_id().unwrap().clone()); @@ -442,7 +442,7 @@ fn interrupted_handoff_preserves_source_session_and_history() { step(&mut cx, &|ws, window, cx| { ws.store = crate::store::Store::load(state.path().join("state.json")); ws.acp_server = Some(server.clone()); - ws.claude_exe = Some("unused-by-the-fake-agent".into()); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some("unused-by-the-fake-agent".into()); ws.new_session_from_home(Harness::Claude, None, work.path().to_path_buf(), Some("before handoff".into()), None, None, window, cx); }); let id = ws.read_with(&cx, |ws, _| ws.active_id().unwrap().clone()); @@ -629,7 +629,7 @@ fn shared_subagents_keep_their_parent_focus_permissions_and_conversation() { }; step(&mut cx, &|ws, _, _| { ws.acp_server = Some(fake_agent(work.path())); - ws.claude_exe = Some(PathBuf::from("unused-by-the-fake-agent")); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some(PathBuf::from("unused-by-the-fake-agent")); ws.store.data.settings.enabled_harnesses = None; ws.store.data.settings.custom_subagents = Default::default(); ws.store.data.settings.claude_picked = vec!["haiku".into()]; @@ -783,7 +783,7 @@ fn home_does_not_launch_without_a_message() { for creating in [false, true] { for text in ["", " \n\t "] { cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| { - ws.claude_exe = None; + *ws.executables.get_mut(crate::harness::Harness::Claude) = None; ws.home.creating = creating.then(|| PathBuf::from("/pending-worktree")); ws.home.prompt.update(cx, |p, cx| p.set_value(text, window, cx)); ws.act(Act::HomeLaunch, window, cx); @@ -810,7 +810,7 @@ fn a_missing_claude_offers_the_setup_window() { cx.update_window(window, |_, window, app| { ws.update(app, |ws, cx| { - ws.claude_exe = None; + *ws.executables.get_mut(crate::harness::Harness::Claude) = None; ws.new_session(work.path().to_path_buf(), window, cx); }) }) @@ -1288,7 +1288,7 @@ fn a_session_opens_another_with_its_model_and_effort_without_asking() { // tests that share the throwaway data folder as Claude Code's catalog. ws.store = crate::store::Store::load(state.path().join("state.json")); ws.acp_server = Some(server.clone()); - ws.claude_exe = Some(PathBuf::from("unused-by-the-fake-agent")); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some(PathBuf::from("unused-by-the-fake-agent")); ws.store.data.settings.enabled_harnesses = None; ws.store.data.settings.set_harness_models(Harness::Codex, vec![crate::harness::subagents::AgentModel { id: "gpt-6".into(), name: "GPT-6".into() }]); ws.new_session_from_home(Harness::Claude, None, work.path().to_path_buf(), Some("parent".into()), None, None, window, cx); diff --git a/src/app/headless/pickers.rs b/src/app/headless/pickers.rs index c813b69..c2eb936 100644 --- a/src/app/headless/pickers.rs +++ b/src/app/headless/pickers.rs @@ -31,7 +31,7 @@ fn dropdowns_switch_on_one_click_and_load_all_harness_models() { // Inject a uniform lister for all harnesses (including Claude Code) and trigger background model loading. ws.update(&mut cx, |ws, cx| { - ws.claude_exe = Some(PathBuf::from("/fake/claude")); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some(PathBuf::from("/fake/claude")); ws.store.data.settings.enabled_harnesses = Some(vec![Harness::Claude, Harness::Codex]); ws.model_lookups.list = |harness, _cwd, _env| match harness { Harness::Claude => Ok(crate::harness::HarnessCatalog { diff --git a/src/app/headless/worktrees.rs b/src/app/headless/worktrees.rs index 43615b6..4b25aa1 100644 --- a/src/app/headless/worktrees.rs +++ b/src/app/headless/worktrees.rs @@ -54,7 +54,7 @@ fn switching_between_worktrees_in_the_workspace() { #[cfg(unix)] std::fs::set_permissions(&fake, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); ws.update(&mut cx, |ws, _| { - ws.claude_exe = Some(fake.clone()); + *ws.executables.get_mut(crate::harness::Harness::Claude) = Some(fake.clone()); ws.acp_server = Some(fake_agent(work.path())); }); diff --git a/src/app/ingest.rs b/src/app/ingest.rs index 23588cf..f483325 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -1,20 +1,19 @@ -//! Taking in what other processes left in the data folder: the per-process mod's usage snapshots (limits, context, -//! settings), and the links and GitHub items sessions asked for. Reading the files is +//! Taking in what other processes left in the data folder: the reports agents write outside ACP (limits, context, +//! settings; Claude Code's mod writes them), and the links and GitHub items sessions asked for. Reading the files is //! off the UI thread; applying them is a handful of small, separately testable steps. use std::time::{Duration, Instant}; use super::*; -use crate::harness::claude::usage::Snapshot; -use crate::harness::limits::{Pool, has_expired_window, merge_pools, merge_usage}; -use crate::store::{RateLimit, UsageLimits}; +use crate::harness::capabilities::{Initiator, handoff}; +use crate::harness::SessionReport; +use crate::harness::limits::{Pool, has_expired_window}; +use crate::store::UsageLimits; /// Retry delay after a failed usage-limits probe, matching t3code's 30s recovery backoff. const FAILED_RETRY_DELAY: Duration = Duration::from_secs(30); /// Minimum gap between automatic probes triggered by a window crossing its `resets_at` boundary. const RESET_RETRY_DELAY: Duration = Duration::from_secs(30); -/// Fast local check cadence for Codex rollout logs (zero network / zero subprocesses). -const CODEX_LOG_POLL: Duration = Duration::from_secs(3); /// Per-harness background probe state for usage limits. #[derive(Clone, Debug, Default)] @@ -38,12 +37,18 @@ impl Workspace { pub(super) fn ingest_usage(&mut self, cx: &mut Context) { if !cfg!(test) { self.ingest_limits(cx); - self.ingest_codex_logs(cx); + self.ingest_live_usage(cx); } self.in_background( - || (usage::read_snapshots(&usage::snapshot_dir()), mcp::read_attached()), - |ws, (snaps, items), cx| { - let mut changed = snaps.iter().fold(false, |c, snap| ws.apply_snapshot(snap, cx) | c); + || { + let reports: Vec<(Harness, SessionReport)> = Harness::registered() + .filter_map(|harness| Some((harness, harness.adapter().reports?))) + .flat_map(|(harness, read)| read().into_iter().map(move |report| (harness, report))) + .collect(); + (reports, mcp::read_attached()) + }, + |ws, (reports, items), cx| { + let mut changed = reports.iter().fold(false, |c, (harness, report)| ws.apply_report(*harness, report, cx) | c); changed |= items.into_iter().fold(false, |c, (stem, item)| ws.apply_attachment(&stem, item) | c); if changed { ws.store.mark_dirty(); @@ -61,36 +66,34 @@ impl Workspace { /// Whether any stored window for `harness` has crossed its `resets_at` boundary. fn harness_has_expired_window(&self, harness: Harness, now: i64) -> bool { - match harness { - Harness::Claude => has_expired_window(&self.store.data.claude_usage, now), - Harness::Codex | Harness::Antigravity => { - let Some(key) = harness.agent().map(|a| a.provider().key) else { return false }; - self.store - .data - .subagent_limits - .get(key) - .is_some_and(|pools| pools.iter().any(|p| has_expired_window(&p.usage, now))) - } - Harness::OpenCode => false, + harness.adapter().usage.is_some() && self.stored_pools(harness).iter().any(|p| has_expired_window(&p.usage, now)) + } + + /// The stored limits for `harness`. + fn stored_pools(&self, harness: Harness) -> Vec { + self.store.data.usage_pools(harness) + } + + /// Merges `pools` into the stored limits for `harness`. Returns whether anything changed: a report is read again + /// every tick, so an unconditional save would rewrite state.json every few seconds. + fn store_pools(&mut self, harness: Harness, pools: Vec) -> bool { + let changed = self.store.data.merge_usage_pools(harness, pools); + if changed { + self.store.mark_dirty(); } + changed } - /// Active zero-token probes for Claude, Codex, and Antigravity. + /// Active zero-token probes, on each adapter's own cadence. fn ingest_limits(&mut self, cx: &mut Context) { let now_instant = Instant::now(); let now_unix = crate::store::now(); - for harness in [Harness::Claude, Harness::Codex, Harness::Antigravity] { + for harness in Harness::registered() { + let Some(usage) = &harness.adapter().usage else { continue }; if !self.limits_harness_active(harness) { continue; } - let every = match harness { - Harness::Claude => crate::harness::claude::limits::REFRESH_EVERY, - Harness::Codex | Harness::Antigravity => { - let Some(limits) = harness.agent().and_then(|a| a.provider().limits.as_ref()) else { continue }; - limits.every - } - Harness::OpenCode => continue, - }; + let every = usage.every; let state = self.limits_state.get(harness); if state.loading || state.authentication_required { continue; @@ -107,60 +110,41 @@ impl Workspace { } } - /// Fast zero-cost local watcher for Codex rollout logs so mid-turn updates appear within seconds. - fn ingest_codex_logs(&mut self, cx: &mut Context) { - if !self.limits_harness_active(Harness::Codex) { - return; - } - if self.codex_logs_asked.is_some_and(|at| at.elapsed() < CODEX_LOG_POLL) { - return; + /// The adapters' cheap local readings, such as Codex's rollout logs, so mid-turn updates appear within seconds. + fn ingest_live_usage(&mut self, cx: &mut Context) { + for harness in Harness::registered() { + let Some(crate::harness::LiveUsage { read, every }) = harness.adapter().usage.as_ref().and_then(|usage| usage.live) else { continue }; + if !self.limits_harness_active(harness) || self.live_usage_asked.get(harness).is_some_and(|at| at.elapsed() < every) { + continue; + } + *self.live_usage_asked.get_mut(harness) = Some(Instant::now()); + self.in_background( + read, + move |ws, usage, cx| { + if let Some(usage) = usage { + ws.apply_live_limits(harness, usage, cx); + } + }, + cx, + ); } - self.codex_logs_asked = Some(Instant::now()); - self.in_background( - || crate::harness::codex::limits::codex_home().and_then(|home| crate::harness::codex::limits::read(&home)), - |ws, usage, cx| { - if let Some(usage) = usage { - ws.apply_live_limits(Harness::Codex, usage, cx); - } - }, - cx, - ); } fn spawn_limits_probe(&mut self, harness: Harness, cx: &mut Context) { + let Some(usage) = &harness.adapter().usage else { return }; + let read = usage.read; let state = self.limits_state.get_mut(harness); state.loading = true; state.queued = false; state.last_asked = Some(Instant::now()); state.retry_after = None; cx.notify(); - - match harness { - Harness::Claude => { - let Some(claude_exe) = self.claude_exe.clone() else { - self.finish_limits_probe(Harness::Claude, Err("Could not find the `claude` CLI on PATH.".into()), cx); - return; - }; - self.in_background( - move || { - let usage = crate::harness::claude::limits::read(&claude_exe)?; - Ok(vec![Pool { name: "Claude".into(), usage }]) - }, - |ws, read, cx| ws.finish_limits_probe(Harness::Claude, read, cx), - cx, - ); - } - Harness::Codex | Harness::Antigravity => { - let Some(agent) = harness.agent() else { return }; - let Some(limits) = &agent.provider().limits else { return }; - self.in_background( - limits.read, - move |ws, read, cx| ws.finish_limits_probe(harness, read, cx), - cx, - ); - } - Harness::OpenCode => {} - } + let executable = self.executable(harness).map(std::path::Path::to_path_buf); + self.in_background( + move || read(executable.as_deref()), + move |ws, read, cx| ws.finish_limits_probe(harness, read, cx), + cx, + ); } fn finish_limits_probe(&mut self, harness: Harness, read: Result, String>, cx: &mut Context) { @@ -173,24 +157,12 @@ impl Workspace { state.error = None; state.authentication_required = false; state.retry_after = None; - match harness { - Harness::Claude => { - if let Some(pool) = pools.into_iter().next() { - self.merge_claude_usage(pool.usage.five_hour, pool.usage.seven_day); - } - } - Harness::Codex | Harness::Antigravity => { - if let Some(key) = harness.agent().map(|a| a.provider().key) { - self.apply_subagent_limits(key, Ok(pools)); - } - } - Harness::OpenCode => {} - } + self.store_pools(harness, pools); self.notify_threads_usage(harness, cx); } Err(err) => { state.authentication_required = crate::harness::acp::looks_like_auth_error(&err); - state.error = Some(if state.authentication_required { format!("Usage is stale. {}", crate::harness::acp::login_hint(harness)) } else { err }); + state.error = Some(if state.authentication_required { format!("Usage is stale. {}", harness.adapter().sign_in.session_hint) } else { err }); state.retry_after = (!state.authentication_required).then(|| Instant::now() + FAILED_RETRY_DELAY); } } @@ -202,72 +174,36 @@ impl Workspace { /// Merge live streamed limits (e.g. from `bridge/claude.mjs` or Codex rollout logs) immediately. pub(crate) fn apply_live_limits(&mut self, harness: Harness, usage: UsageLimits, cx: &mut Context) { - let changed = match harness { - Harness::Claude => self.merge_claude_usage(usage.five_hour, usage.seven_day), - Harness::Codex => { - let current = self.store.data.subagent_limits.get("codex").cloned().unwrap_or_default(); - let merged = merge_pools(¤t, vec![Pool { name: "Codex".into(), usage }]); - if merged != current { - self.store.data.subagent_limits.insert("codex".into(), merged); - self.store.mark_dirty(); - true - } else { - false - } - } - _ => false, - }; - if changed { - let state = self.limits_state.get_mut(harness); - state.error = None; - state.authentication_required = false; - state.retry_after = None; - self.notify_threads_usage(harness, cx); - cx.notify(); + if harness.adapter().usage.is_none() || !self.store_pools(harness, vec![Pool { name: harness.name().into(), usage }]) { + return; } + let state = self.limits_state.get_mut(harness); + state.error = None; + state.authentication_required = false; + state.retry_after = None; + self.notify_threads_usage(harness, cx); + cx.notify(); } - /// The stored usage limits for `harness` (and optional `model_id` for multi-pool providers like Antigravity). + /// The stored usage limits for `harness`, for an adapter that reports them. `_model_id` picks the pool for one model + /// once an adapter splits its limits by model. pub(crate) fn usage_for_harness_model(&self, harness: Harness, _model_id: Option<&str>) -> Option { - match harness { - Harness::Claude => Some(self.store.data.claude_usage.clone()), - Harness::Codex => self.store.data.subagent_limits.get("codex")?.first().map(|p| p.usage.clone()), - /* Temporarily ignore cached Antigravity limits while polling is disabled. - Harness::Antigravity => { - let pools = self.store.data.subagent_limits.get("antigravity")?; - if let Some(model) = _model_id.map(str::to_ascii_lowercase) { - let wants_claude = model.contains("claude") || model.contains("gpt") || model.contains("opus") || model.contains("sonnet"); - if let Some(pool) = pools.iter().find(|p| { - let name = p.name.to_ascii_lowercase(); - if wants_claude { - name.contains("claude") || name.contains("gpt") - } else { - name.contains("gemini") - } - }) { - return Some(pool.usage.clone()); - } - } - pools.first().map(|p| p.usage.clone()) - } - */ - Harness::OpenCode | Harness::Antigravity => None, - } + harness.adapter().usage.as_ref()?; + self.stored_pools(harness).into_iter().next().map(|pool| pool.usage) } fn harness_probably_available(&self, harness: Harness) -> bool { if !harness.is_registered() { return false; } - match harness { - Harness::Claude => self.claude_exe.is_some(), - Harness::Codex | Harness::OpenCode | Harness::Antigravity => { - // Available if we have a cached model catalog or usage reading for it, or its CLI is on PATH. - let has_models = self.store.data.settings.aggregated_models().iter().any(|m| m.harness == harness && !m.id.is_empty()); - let has_limits = harness.agent().is_some_and(|a| self.store.data.subagent_limits.contains_key(a.provider().key)); - has_models || has_limits - } + // An adapter whose executable Settings can point at is found before anything runs, so its answer is final. + // The others are found in the background, so until then a cached model catalog or usage reading counts. + if harness.adapter().custom_path || self.executable(harness).is_some() { + return self.executable(harness).is_some(); } + let has_models = self.store.data.settings.aggregated_models().iter().any(|m| m.harness == harness && !m.id.is_empty()); + let has_limits = self.store.data.subagent_limits.contains_key(harness.key()); + has_models || has_limits } /// Pick the best available fallback model from another enabled harness that is not at its usage limit. @@ -288,8 +224,9 @@ impl Workspace { }) .unwrap_or(0.0) }; + let may_take_over = |h: Harness| h != excluded && handoff(excluded, h, Initiator::Automatic).allowed(); if let Some(pref) = &self.store.data.settings.auto_handoff_model - && pref.harness != excluded + && may_take_over(pref.harness) && enabled.contains(&pref.harness) && self.harness_probably_available(pref.harness) && max_util(pref.harness, (!pref.id.is_empty()).then_some(pref.id.as_str())) < 0.95 @@ -302,7 +239,7 @@ impl Workspace { } let mut candidates: Vec<(f32, crate::harness::CatalogModel)> = enabled .into_iter() - .filter(|&h| h != excluded && self.harness_probably_available(h)) + .filter(|&h| may_take_over(h) && self.harness_probably_available(h)) .filter_map(|h| { let model = all.iter().find(|m| m.harness == h).cloned().unwrap_or_else(|| { crate::harness::CatalogModel { harness: h, id: String::new(), name: h.name().into() } @@ -340,7 +277,7 @@ impl Workspace { /// Request a fresh usage-limits probe for `harness` (e.g. after a turn finishes). pub(crate) fn request_limits_refresh(&mut self, harness: Harness, cx: &mut Context) { if self.limits_state.get(harness).authentication_required { return; } - if !matches!(harness, Harness::Claude | Harness::Codex) || !self.limits_harness_active(harness) { + if !harness.adapter().usage.as_ref().is_some_and(|usage| usage.after_turn) || !self.limits_harness_active(harness) { return; } if self.limits_state.get(harness).loading { @@ -352,10 +289,10 @@ impl Workspace { /// Manual refresh triggered from the sidebar usage footer. pub(crate) fn refresh_all_limits(&mut self, cx: &mut Context) { - for harness in [Harness::Claude, Harness::Codex, Harness::Antigravity] { + for harness in Harness::registered() { self.limits_state.get_mut(harness).authentication_required = false; } - for harness in [Harness::Claude, Harness::Codex] { + for harness in Harness::registered().filter(|harness| harness.adapter().usage.is_some()) { if !self.limits_harness_active(harness) { continue; } @@ -367,31 +304,21 @@ impl Workspace { } } - pub(super) fn apply_subagent_limits(&mut self, key: &str, read: Result, String>) { - if let Ok(pools) = read { - let current = self.store.data.subagent_limits.get(key).cloned().unwrap_or_default(); - let merged = merge_pools(¤t, pools); - if merged != current { - self.store.data.subagent_limits.insert(key.into(), merged); - self.store.mark_dirty(); - } - } - } - - /// One mod report: Claude's limits, and the session's own figures and settings. - fn apply_snapshot(&mut self, snap: &Snapshot, cx: &mut Context) -> bool { - let mut changed = self.merge_claude_usage(snap.five_hour.clone(), snap.seven_day.clone()); + /// One report from `harness`: its limits, and the session's own figures and settings. + fn apply_report(&mut self, harness: Harness, report: &SessionReport, cx: &mut Context) -> bool { + let usage = UsageLimits { five_hour: report.five_hour.clone(), seven_day: report.seven_day.clone() }; + let mut changed = self.store_pools(harness, vec![Pool { name: harness.name().into(), usage }]); if changed { - self.notify_threads_usage(Harness::Claude, cx); + self.notify_threads_usage(harness, cx); } let id = self.store.data.sessions.iter().find(|s| { - s.agent.as_ref().is_some_and(|meta| meta.harness == Harness::Claude && meta.session_id == snap.session_id) + s.agent.as_ref().is_some_and(|meta| meta.harness == harness && meta.session_id == report.session_id) }).map(|s| s.id.clone()); if let Some(id) = id { if let Some(meta) = self.store.session_mut(&id).and_then(|s| s.agent.as_mut()) { - changed |= apply_to_meta(meta, snap); + changed |= apply_to_meta(meta, report); } - if let Some(native) = snap.auto_compact + if let Some(native) = report.auto_compact && let Some(view) = self.live_view(&id).and_then(|v| v.thread()) { view.update(cx, |view, cx| { @@ -404,21 +331,10 @@ impl Workspace { } changed } - - /// Keep the newest reading per window. Returns whether anything changed (the same snapshot is re-read - /// every tick, so an unconditional save would rewrite state.json every few seconds). - pub(super) fn merge_claude_usage(&mut self, five: Option, seven: Option) -> bool { - let incoming = UsageLimits { five_hour: five, seven_day: seven }; - let changed = merge_usage(&mut self.store.data.claude_usage, &incoming); - if changed { - self.store.mark_dirty(); - } - changed - } } -/// Copy a snapshot's figures onto the session's record; true when anything differed. -fn apply_to_meta(meta: &mut AgentMeta, snap: &Snapshot) -> bool { +/// Copy a report's figures onto the session's record; true when anything differed. +fn apply_to_meta(meta: &mut AgentMeta, snap: &SessionReport) -> bool { let mut changed = false; if snap.context_fraction.is_some() && (meta.context_fraction != snap.context_fraction || meta.context_window != snap.context_window) { meta.context_fraction = snap.context_fraction; @@ -468,7 +384,7 @@ fn apply_to_meta(meta: &mut AgentMeta, snap: &Snapshot) -> bool { mod tests { use super::*; - fn snap(json: &str) -> Snapshot { + fn snap(json: &str) -> SessionReport { serde_json::from_str(json).unwrap() } diff --git a/src/app/lifecycle.rs b/src/app/lifecycle.rs index 63d22db..bca1e1c 100644 --- a/src/app/lifecycle.rs +++ b/src/app/lifecycle.rs @@ -1,7 +1,6 @@ //! Ending and starting m4code: the quit question, remembering what was open, and bringing it back. use super::*; -use crate::harness::claude::{trim, usage}; use crate::mcp; use crate::store::WindowGeom; use gpui::{Bounds, WindowBounds, point, px, size}; @@ -11,19 +10,19 @@ fn running_file() -> PathBuf { datadir::data_dir().join("running.json") } -/// Start-up housekeeping: delete the old per-session files each folder's owner no longer reads. Nothing here touches -/// Claude Code's own data. +/// Start-up housekeeping: delete the old per-session files each folder's owner no longer reads, and let each adapter +/// do the same for its own. Nothing here touches an agent's own data. pub fn tidy_leftovers() { let data = datadir::data_dir(); let [mcp_configs, titles, names, attached] = mcp::cleanup_dirs(); datadir::prune(names, 7 * 86_400); datadir::prune(attached, 7 * 86_400); datadir::prune(mcp_configs, 7 * 86_400); - datadir::prune(trim::settings_dir(), 7 * 86_400); // Nothing writes titles any more; the old files go. datadir::prune(titles, 7 * 86_400); - datadir::prune(usage::snapshot_dir(), 30 * 86_400); - datadir::prune(usage::ctl_dir(), 7 * 86_400); + for harness in crate::harness::Harness::registered() { + (harness.adapter().tidy)(); + } datadir::prune(data.join("visual"), 7 * 86_400); datadir::prune(data.join("mcp-ready"), 86_400); datadir::prune(data.join("screens"), 30 * 86_400); diff --git a/src/app/mod.rs b/src/app/mod.rs index 5caf491..1cd9a48 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -393,8 +393,9 @@ pub struct Live { pub id: Id, pub view: SessionView, pub _sub: Subscription, - /// The session name Claude Code was last given (`--name` or `/rename`), so a changed title is sent once. - pub claude_name: Option, + /// The session name the agent's own records were last given (Claude Code's `--name` or `/rename`), so a changed + /// title is sent once. + pub native_name: Option, } /// What a session is drawn as: a harness session's conversation, or the terminal of a shell tab (a sign-in). @@ -535,7 +536,8 @@ pub struct QuestionPopover { pub struct Workspace { pub store: Store, - pub claude_exe: Option, + /// Each agent's executable, as its adapter found it (`discover_executables`). + pub executables: harness::HarnessMap>, /// The ACP server every harness session starts, in place of the harness's own. Tests stand in a fake agent. pub acp_server: Option<(PathBuf, Vec)>, pub shell: (String, Vec), @@ -615,7 +617,8 @@ pub struct Workspace { /// Per-harness usage limits probe state (in-flight flag, last error, backoff, queued refresh). pub limits_state: crate::harness::HarnessMap, /// Last time Codex's fast local rollout-log watcher ran. - pub codex_logs_asked: Option, + /// When each adapter's cheap local usage reading was last taken. + pub live_usage_asked: harness::HarnessMap>, pub editors: Vec<(Editor, bool)>, pub window_title: String, /// The session being dragged in the sidebar (lifted in place while its ghost follows the cursor). @@ -671,8 +674,8 @@ pub struct Workspace { pub(crate) idle_since: HashMap, /// Last `ThreadView::turn_seq` for which a "finished" notification already fired, so one turn notifies at most once. pub(crate) notified_turn: HashMap, - /// Claude Code's own busy/idle/waiting per session id, from the last activity poll. - pub(crate) claude_statuses: HashMap, + /// Each agent's own busy/idle/waiting per session id (`NativeSessions::statuses`), from the last activity poll. + pub(crate) native_statuses: HashMap, pub git_busy: Option, /// Sessions currently switching into a target worktree folder; shown as a spinner in the branch switcher chip. pub switching_worktree: HashMap, @@ -690,7 +693,6 @@ impl Workspace { ) -> Self { let store = Store::load(Store::default_path()); crate::panels::scale::set(store.data.settings.scale.unwrap_or(100)); - let claude_exe = (Harness::Claude.adapter().discover)(store.data.settings.claude_path.as_deref()); let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search sessions and projects").clean_on_escape()); cx.subscribe_in(&search_input, window, |ws: &mut Self, input, ev: &InputEvent, window, cx| { @@ -714,7 +716,7 @@ impl Workspace { let home_effort = store.data.settings.new_session.effort; let home_permission = store.data.settings.new_session.permission_mode; let mut ws = Self { - claude_exe, + executables: Default::default(), acp_server: None, shell: platform::default_shell(store.data.settings.shell.as_deref()), live: vec![], @@ -778,7 +780,7 @@ impl Workspace { closed: vec![], model_lookups: Default::default(), limits_state: Default::default(), - codex_logs_asked: None, + live_usage_asked: Default::default(), editors: Editor::ALL .iter() .map(|e| (*e, e.locate().is_some())) @@ -822,7 +824,7 @@ impl Workspace { activity: HashMap::new(), idle_since: HashMap::new(), notified_turn: HashMap::new(), - claude_statuses: HashMap::new(), + native_statuses: HashMap::new(), git_busy: None, switching_worktree: HashMap::new(), pending: None, @@ -840,6 +842,7 @@ impl Workspace { for path in initial_projects { ws.store.add_project(&path); } + ws.discover_executables(cx); ws.refresh_git_async(cx); cx.background_executor().spawn(async { lifecycle::tidy_leftovers() }).detach(); ws.ingest_usage(cx); diff --git a/src/app/modal.rs b/src/app/modal.rs index 9507ede..d6b7c13 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -297,8 +297,8 @@ impl Workspace { crate::panels::scale::set(scale); self.shell = platform::default_shell(s.shell.as_deref()); - self.claude_exe = (Harness::Claude.adapter().discover)(s.claude_path.as_deref()); self.store.mark_dirty(); + self.discover_executables(cx); if default_model_changed { self.home.model = None; } diff --git a/src/app/palette.rs b/src/app/palette.rs index af98da7..8b912a3 100644 --- a/src/app/palette.rs +++ b/src/app/palette.rs @@ -105,6 +105,10 @@ impl Workspace { if blocked { return; } + if let Some(refusal) = crate::harness::capabilities::handoff(cur, harness, crate::harness::capabilities::Initiator::User).refusal() { + self.toast(refusal, cx); + return; + } if cur == harness { if let Some(opt_id) = thread.read(cx).thread.option("model").map(|o| o.id.clone()) { thread.update(cx, |t, cx| t.set_option(opt_id, model_id, cx)); diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 84af750..daa4f24 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -148,6 +148,9 @@ impl Workspace { if !adapter.fallback_question { plan.off.push("ask_user"); } + if !adapter.capabilities.spawns_subagents.allowed() { + plan.off.extend(mcp::SUBAGENT_TOOLS); + } let (mut permission, options) = match session_id { None => { // Only inherit the default model id when starting on the harness that serves it. @@ -163,7 +166,7 @@ impl Workspace { (permission, harness::defaults::config_options(&defaults)) } Some(_) => ( - meta.permission.or_else(|| (adapter.full_access_relaunch && meta.antigravity_full_access).then_some(Permission::FullAccess)), + meta.permission.or_else(|| (adapter.full_access_relaunch && meta.launched_full_access).then_some(Permission::FullAccess)), resume_options(meta), ), }; @@ -171,7 +174,13 @@ impl Workspace { permission = Some(Permission::ReadOnly); } let child_edits = meta.parent_session.as_ref().map(|_| meta.subagent_edits); - if child_edits.is_some() { + if let Some(parent) = &meta.parent_session { + // A resumed or handed-off subagent asks again, as a new one does. + let parent = self.store.session(parent).and_then(SessionRecord::harness); + if let Some(refusal) = harness::capabilities::subagent(parent, meta.harness).refusal() { + self.toast(refusal, cx); + return None; + } permission = None; } let input = harness::SessionInput { @@ -181,7 +190,7 @@ impl Workspace { name, child_edits, settings, - executable_override: self.claude_exe.as_deref(), + executable_override: self.executable(meta.harness), chrome: meta.chrome, }; if let Err(error) = (adapter.prepare)(&input, &mut plan) { @@ -189,7 +198,8 @@ impl Workspace { return None; } let targets: Vec<_> = settings.enabled_harnesses_list().into_iter() - .filter(|h| settings.subagent_access(*h).on).map(Harness::key).collect(); + .filter(|h| settings.subagent_access(*h).on && harness::capabilities::subagent(meta.harness, *h).allowed()) + .map(Harness::key).collect(); let project = self.store.project_for_cwd(cwd).and_then(|id| self.store.project(&id)).map(|p| p.path.as_path()); let tools = match mcp::session::SessionTools::new(record_id, cwd, project, &plan.off, &targets) { Ok(tools) => tools, @@ -386,12 +396,12 @@ impl Workspace { match ev { ThreadEvent::Ready(session) => { ws.commit_handoff(&sub_id, session, window, cx); - let full_access = view.read(cx).antigravity_full_access(); + let full_access = view.read(cx).launched_full_access(); if let Some(meta) = ws.store.session_mut(&sub_id).and_then(|r| r.agent.as_mut()) - && (meta.read_only_pending || meta.antigravity_full_access != full_access) + && (meta.read_only_pending || meta.launched_full_access != full_access) { meta.read_only_pending = false; - meta.antigravity_full_access = full_access; + meta.launched_full_access = full_access; ws.store.mark_dirty(); } } @@ -516,7 +526,7 @@ impl Workspace { } ThreadEvent::Select(child) => ws.act(Act::Select(child.clone()), window, cx), ThreadEvent::Handoff { to, model, message, effort, by_agent } => ws.dynamic_handoff(&sub_id, *to, model.clone(), message.clone(), *by_agent, effort.clone(), window, cx), - ThreadEvent::ReconnectPermission(permission) => ws.reconnect_antigravity_permission(&sub_id, *permission, window, cx), + ThreadEvent::ReconnectPermission(permission) => ws.reconnect_full_access_permission(&sub_id, *permission, window, cx), ThreadEvent::NewSession(prompt) => { let (harness, cwd) = ws .store @@ -553,6 +563,10 @@ impl Workspace { let Some(mut record) = self.store.session(source).cloned() else { return }; let Some(thread) = self.live_view(source).and_then(|view| view.thread()).cloned() else { return }; let view = thread.read(cx); + if let Some(refusal) = view.harness.adapter().capabilities.fork.refusal() { + self.toast(refusal, cx); + return; + } let Some(entries) = view.thread.entries.get(..end) else { self.toast("The original turn is unavailable in this transcript.", cx); return; @@ -602,12 +616,15 @@ impl Workspace { /// Keep the new view among the live sessions and show it. #[allow(clippy::too_many_arguments)] - fn adopt_live(&mut self, id: Id, view: SessionView, sub: Subscription, claude_name: Option, foreground: bool, window: &mut Window, cx: &mut Context) { - // The mod reads the launch name first and leaves it alone; a stale file would otherwise rename the session. - if let Some(cid) = self.store.session(&id).and_then(|r| r.provider_session_id()) { - claude::write_name(cid, claude_name.as_deref()); + fn adopt_live(&mut self, id: Id, view: SessionView, sub: Subscription, native_name: Option, foreground: bool, window: &mut Window, cx: &mut Context) { + // The agent reads the launch name first and leaves it alone; a stale name would otherwise rename the session. + if let Some(rec) = self.store.session(&id) + && let Some(native) = rec.agent.as_ref().and_then(|meta| meta.harness.adapter().native_sessions.as_ref()) + && let Some(cid) = rec.provider_session_id() + { + (native.write_name)(cid, native_name.as_deref()); } - self.live.push(Live { id: id.clone(), view, _sub: sub, claude_name }); + self.live.push(Live { id: id.clone(), view, _sub: sub, native_name }); self.remember(&id); if !foreground { cx.notify(); @@ -862,13 +879,13 @@ fn resume_options(meta: &AgentMeta) -> Vec<(&'static str, String)> { .collect() } -/// Whether Claude Code has a conversation for the session: one it listed on a scan, or a transcript on disk. A -/// session nobody has written to has none, and `claude --resume` ends at once on it. +/// Whether the agent has a conversation for the session: one it listed on a scan, or a transcript on disk. A +/// session nobody has written to has none, and resuming it (`claude --resume`) ends at once. fn has_conversation(record_id: &str, meta: &AgentMeta) -> bool { crate::harness::thread::has_saved_conversation(record_id) || meta.external != ExternalState::Unknown || meta.transcript.is_some() - || claude::claude_home().and_then(|h| claude::find_transcript(&h, &meta.session_id)).is_some() + || meta.harness.adapter().native_sessions.as_ref().is_some_and(|native| (native.has_transcript)(&meta.session_id)) } #[cfg(test)] diff --git a/src/app/settings.rs b/src/app/settings.rs index b0630f3..ee7bde2 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -120,9 +120,30 @@ impl Workspace { } } + /// `harness`'s executable, as its adapter last found it. + pub fn executable(&self, harness: Harness) -> Option<&std::path::Path> { + self.executables.get(harness).as_deref() + } + + /// Finds each agent's executable again, at start and after its path in Settings changed. One whose path Settings + /// holds is found at once, since sessions need it before anything else runs; the others are found in the + /// background, where looking can mean starting a login shell to read its PATH. + pub(super) fn discover_executables(&mut self, cx: &mut Context) { + for harness in Harness::registered() { + let adapter = harness.adapter(); + if adapter.custom_path { + *self.executables.get_mut(harness) = (adapter.discover)(self.store.data.settings.executable_path(harness)); + } else if !cfg!(test) { + // Tests stand in a fake agent for these and shouldn't look at the machine's PATH. + let discover = adapter.discover; + self.in_background(move || discover(None), move |ws, found, _| *ws.executables.get_mut(harness) = found, cx); + } + } + } + /// Environment passed to `harness`'s ACP server when probing its available models. pub(super) fn harness_model_env(&self, harness: Harness) -> Result, String> { - (harness.adapter().probe_env)(self.claude_exe.as_deref()) + (harness.adapter().probe_env)(self.executable(harness)) } /// Refreshes model catalogs in the background for every enabled harness (Claude Code, Codex, OpenCode, diff --git a/src/app/setup.rs b/src/app/setup.rs index da24813..d359912 100644 --- a/src/app/setup.rs +++ b/src/app/setup.rs @@ -390,7 +390,7 @@ impl Workspace { /// launch the save also creates the state file and enables whichever harnesses were found. pub fn apply_setup(&mut self, claude_path: Option, enabled: Vec, cx: &mut Context) { self.store.data.settings.claude_path = claude_path; - self.claude_exe = (Harness::Claude.adapter().discover)(self.store.data.settings.claude_path.as_deref()); + self.discover_executables(cx); if self.store.data.settings.enabled_harnesses.is_none() && !enabled.is_empty() { self.store.data.settings.harness = enabled[0]; self.store.data.settings.enabled_harnesses = Some(enabled); diff --git a/src/app/subagents.rs b/src/app/subagents.rs index 61d769d..2215e5a 100644 --- a/src/app/subagents.rs +++ b/src/app/subagents.rs @@ -195,6 +195,7 @@ impl Workspace { if !settings.harness_enabled(harness) || !access.on { return Err(format!("{} subagents are disabled in Settings.", harness.name())); } + crate::harness::capabilities::subagent(parent.harness(), harness).refusal().map_or(Ok(()), |refusal| Err(refusal.to_string()))?; let parent_read_only = self.live_view(&parent.id).and_then(|view| view.thread()).is_some_and(|view| { view.read(cx).permission() == Some(crate::harness::permission::Permission::ReadOnly) }); @@ -295,6 +296,10 @@ impl Workspace { self.toast(format!("{} is disabled in Settings.", model.harness.name()), cx); return; } + if let Some(refusal) = crate::harness::capabilities::subagent(parent.harness(), model.harness).refusal() { + self.toast(refusal, cx); + return; + } let id = new_id(); let chosen_model = (!model.id.is_empty()).then(|| model.id.clone()); let meta = AgentMeta { diff --git a/src/app/switch.rs b/src/app/switch.rs index d024b08..2999556 100644 --- a/src/app/switch.rs +++ b/src/app/switch.rs @@ -189,7 +189,7 @@ impl Workspace { ( v.thread.option("model").map(|o| o.current.clone()), v.thread.option("thought_level").map(|o| o.current.clone()), - v.antigravity_full_access(), + v.launched_full_access(), ) }) .unwrap_or((None, None, false)); @@ -200,7 +200,7 @@ impl Workspace { if let Some(m) = chosen_model { meta.chosen_model = Some(m); } if let Some(e) = chosen_effort { meta.chosen_effort = Some(e); } meta.read_only_pending = false; - meta.antigravity_full_access = full_access; + meta.launched_full_access = full_access; } } self.store.mark_dirty(); @@ -324,23 +324,12 @@ impl Workspace { let Some(rec) = self.store.session(id).cloned() else { return }; let Some(git) = rec.project_id.as_ref().and_then(|p| self.store.project(p)).and_then(|p| p.git.clone()) else { return }; - if native_changed && rec.agent.as_ref().is_some_and(|m| m.harness == Harness::Claude) { + if native_changed && let Some(followed) = rec.harness().and_then(|harness| harness.adapter().worktree.followed) { let Some(session_id) = rec.provider_session_id().map(str::to_string) else { return }; let main = git.main_checkout().to_path_buf(); let id = id.to_string(); cx.spawn_in(window, async move |this, cx| { - let target = cx - .background_executor() - .spawn(async move { - let home = crate::harness::claude::claude_home()?; - let transcript = crate::harness::claude::find_transcript(&home, &session_id)?; - match crate::harness::claude::worktree_session_state(&transcript).ok()?? { - crate::harness::claude::WorktreeState::Entered(Some(path)) if path.is_dir() => Some(path), - crate::harness::claude::WorktreeState::Exited if main.is_dir() => Some(main), - _ => None, - } - }) - .await; + let target = cx.background_executor().spawn(async move { followed(&session_id, &main) }).await; if let Some(folder) = target { let _ = this.update_in(cx, |ws, window, cx| ws.follow_native_worktree(&id, folder, window, cx)); } diff --git a/src/app/titles.rs b/src/app/titles.rs index 086ac65..b998a0e 100644 --- a/src/app/titles.rs +++ b/src/app/titles.rs @@ -5,9 +5,20 @@ type TextGenerator = Box Result + Send>; const TITLE_PROMPT: &str = "Write a short title for the session described by this message. Reply with a single title of at most 60 characters. Use no quotes or preamble."; impl Workspace { + /// The model that writes a summary of a session on `harness` (running `model`): the one picked in Settings, else the + /// session's own, when its adapter answers m4code's prompts. `None` means a local summary. + pub(super) fn summary_model(&self, harness: Harness, model: Option) -> Option { + let chosen = self.store.data.settings.text_generation_model.clone() + .unwrap_or(crate::store::TextGenerationModel { harness, id: model.unwrap_or_default() }); + chosen.harness.adapter().capabilities.text_generation.allowed().then_some(chosen) + } + pub(super) fn text_generator(&self, cx: &App) -> Result, String> { let settings = &self.store.data.settings; let Some(model) = settings.text_generation_model.clone() else { return Ok(None) }; + if let Some(refusal) = model.harness.adapter().capabilities.text_generation.refusal() { + return Err(format!("{refusal} Pick another text generation model in Settings → General.")); + } if !settings.harness_enabled(model.harness) { return Err(format!("{} is disabled. Pick a text generation model in Settings → General.", model.harness.name())); } diff --git a/src/harness/acp.rs b/src/harness/acp.rs index 1c331d2..41572da 100644 --- a/src/harness/acp.rs +++ b/src/harness/acp.rs @@ -41,14 +41,6 @@ pub fn looks_like_auth_error(message: &str) -> bool { ["authentication required", "authentication_error", "invalid api key", "run /login", "not logged in", "not logged into", "not authenticated", "not signed in", "isn't signed in", "please log in", "please login", "please sign in", "token expired", "token has expired", "expired token", "invalid_grant", "refresh token", "unauthorized", "http 401", "status 401"].iter().any(|part| message.contains(part)) } -pub fn login_hint(harness: super::Harness) -> &'static str { - match harness { - super::Harness::Claude => "Sign in with `claude auth login`, then retry the session.", - super::Harness::Codex => "Sign in with `codex login`, then retry the session.", - super::Harness::OpenCode => "Sign in with `opencode auth login`, then retry the session.", - super::Harness::Antigravity => "Run `agy` and sign in, then retry the session.", - } -} /// What the agent sends without being asked. #[derive(Debug)] diff --git a/src/harness/antigravity/mod.rs b/src/harness/antigravity/mod.rs index 74d38e9..374b6b8 100644 --- a/src/harness/antigravity/mod.rs +++ b/src/harness/antigravity/mod.rs @@ -6,6 +6,9 @@ pub mod limits; pub mod read_only; +use super::subagents::Provider; +use crate::panels::logos; + #[cfg(feature = "adapter-antigravity")] use super::subagents::Agent; @@ -40,6 +43,7 @@ pub const ADAPTER: Adapter = Adapter { native_compaction_managed: false, fallback_question: false, discover: |_| super::runner::locate(Agent::Antigravity), + custom_path: false, probe_env: super::no_probe_env, config_root: |home| home.join(".gemini").join("config"), project_skills: ".agents/skills", @@ -49,6 +53,32 @@ pub const ADAPTER: Adapter = Adapter { background: Some(super::BackgroundHooks { from_update: background_update, finished: task_finished, live_execute_tools: true }), ..super::ProtocolHooks::DEFAULT }, + sign_in: super::SignIn { + program: "agy", + locate: |_| super::find("agy"), + args: &[], + session_hint: "Run `agy` and sign in, then retry the session.", + run_hint: "Antigravity isn't signed in. Run `agy` and sign in, then try again.", + }, + // Off pending clarification of Google's terms for usage polling. Back on, it reads: + // usage: Some(super::UsageSource { + // read: |_| limits::read(&super::runner::locate(Agent::Antigravity).ok_or("agy was not found")?, &crate::datadir::data_dir()), + // every: limits::REFRESH_EVERY, + // after_turn: false, + // live: None, + // }), + usage: None, + text_generation_launch: |launch, data| { + let folder = read_only::prepare_text_generation(data).map_err(|e| format!("Could not disable Antigravity tools: {e}"))?; + launch.args.extend(["--gemini-dir".into(), folder.to_string_lossy().into_owned()]); + Ok(serde_json::Value::Null) + }, + probe_session_meta: None, + copies_skills: true, + capabilities: super::capabilities::Capabilities::ALL, + reports: None, + native_sessions: None, + tidy: || {}, }; #[cfg(feature = "adapter-antigravity")] @@ -100,3 +130,30 @@ mod background { } } + +/// How this agent runs as a custom subagent (`harness/subagents.rs`). +pub const PROVIDER: Provider = Provider { + dashboard_url: Some("https://antigravity.google.com/remote?settingsOpen=true&settingsScreen=Models"), + color: |t| t.antigravity, + marks: logos::antigravity_marks, + name: "Antigravity", + key: "antigravity", + task_name: "Google Antigravity", + triggers: "Antigravity, Gemini", + program: "agy", + args: &["acp"], + windows_fallback: Some("agy/bin/agy.exe"), + server: "agy", + missing: "agy was not found. Antigravity subagents need the Antigravity CLI installed.", + // Google's FAQ names Claude Code among the third-party software barred from Antigravity logins, under Section 6 of + // the Antigravity Additional Terms (https://antigravity.google/docs/faq, https://antigravity.google/terms). + warning: Some("Google's Antigravity terms forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does. Switch this on at your own risk."), + task_args: super::runner::antigravity_args, + environment: super::runner::no_env, + config_options: super::runner::antigravity_options, + inbox_without_steering: false, + steering_prompt_required: false, + deferred_tool_target: false, + // agy gives a command about ten seconds, then moves it to the background and ends the turn. + resumes_after_background: true, +}; diff --git a/src/harness/capabilities.rs b/src/harness/capabilities.rs new file mode 100644 index 0000000..69e5edc --- /dev/null +++ b/src/harness/capabilities.rs @@ -0,0 +1,141 @@ +//! What an adapter lets m4code do with its agent. The core asks here before every action that reaches the agent, and +//! never names a harness itself: a refused action stays visible but disabled, with the adapter's reason as its +//! tooltip, and the same answer refuses it when a tool call or an automatic step asks for it. + +/// Whether one action is allowed, and why not. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Capability { + Allowed, + /// Shown to the user as is, so it reads as a whole sentence. + Refused(&'static str), +} + +impl Capability { + pub fn allowed(self) -> bool { + self == Self::Allowed + } + + pub fn refusal(self) -> Option<&'static str> { + match self { + Self::Allowed => None, + Self::Refused(reason) => Some(reason), + } + } +} + +/// Who may move a conversation onto, or off, a harness. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Handoff { + /// The user, the agent (`set_model`) and auto-handoff on a usage limit. + Any, + Never(&'static str), +} + +/// Who asks for a handoff. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Initiator { + User, + /// The agent through `set_model`, or m4code itself, as auto-handoff on a usage limit does. + Automatic, +} + +impl Handoff { + /// `by` is part of the question so a rule that tells the user from the agent needs no change at the call sites. + pub fn allows(self, _by: Initiator) -> Capability { + match self { + Self::Any => Capability::Allowed, + Self::Never(reason) => Capability::Refused(reason), + } + } +} + +/// The actions an adapter allows. Every field is one button or automatic step in the app. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Capabilities { + /// Rewind (and edit & rewind) to an earlier message, which starts a new session seeded with the conversation + /// before it. + pub rewind: Capability, + /// Fork a session from a message into a new one seeded with the conversation up to it. + pub fork: Capability, + /// Continue in a fresh linked session, seeded with a summary of this one. + pub continue_fresh: Capability, + /// m4code's own compaction for a session whose agent doesn't list its compact command: a summary, then a new + /// session seeded with it. + pub compaction_fallback: Capability, + /// Answering m4code's own prompts: session titles, commit messages and summaries. + pub text_generation: Capability, + /// Moving a conversation from another harness onto this one. + pub handoff_in: Handoff, + /// Moving a conversation from this harness onto another one. + pub handoff_out: Handoff, + /// Running as a subagent that another session started. + pub subagent: Capability, + /// Its sessions starting subagents. + pub spawns_subagents: Capability, +} + +impl Capabilities { + pub const ALL: Self = Self { + rewind: Capability::Allowed, + fork: Capability::Allowed, + continue_fresh: Capability::Allowed, + compaction_fallback: Capability::Allowed, + text_generation: Capability::Allowed, + handoff_in: Handoff::Any, + handoff_out: Handoff::Any, + subagent: Capability::Allowed, + spawns_subagents: Capability::Allowed, + }; + + /// For an adapter this build leaves out. + pub const NONE: Self = { + const GONE: &str = "This adapter is unavailable in this build."; + Self { + rewind: Capability::Refused(GONE), + fork: Capability::Refused(GONE), + continue_fresh: Capability::Refused(GONE), + compaction_fallback: Capability::Refused(GONE), + text_generation: Capability::Refused(GONE), + handoff_in: Handoff::Never(GONE), + handoff_out: Handoff::Never(GONE), + subagent: Capability::Refused(GONE), + spawns_subagents: Capability::Refused(GONE), + } + }; +} + +/// Whether a conversation may move from `from` to `to`: the first refusal, the source's before the target's. +pub fn handoff(from: super::Harness, to: super::Harness, by: Initiator) -> Capability { + if from == to { + return Capability::Allowed; + } + let out = from.adapter().capabilities.handoff_out.allows(by); + if out.allowed() { to.adapter().capabilities.handoff_in.allows(by) } else { out } +} + +/// Whether a session on `parent` may start a subagent on `child`. A parent that isn't an agent session asks only the +/// child. +pub fn subagent(parent: impl Into>, child: super::Harness) -> Capability { + let out = parent.into().map_or(Capability::Allowed, |parent| parent.adapter().capabilities.spawns_subagents); + if out.allowed() { child.adapter().capabilities.subagent } else { out } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_refused_handoff_gives_its_reason_to_whoever_asks() { + for by in [Initiator::User, Initiator::Automatic] { + assert_eq!(Handoff::Never("No.").allows(by).refusal(), Some("No.")); + assert!(Handoff::Any.allows(by).allowed()); + } + } + + #[test] + fn staying_on_one_harness_is_never_a_handoff() { + for harness in super::super::Harness::ALL { + assert!(handoff(harness, harness, Initiator::Automatic).allowed()); + } + } +} diff --git a/src/harness/claude/mod.rs b/src/harness/claude/mod.rs index 9f272ca..464c424 100644 --- a/src/harness/claude/mod.rs +++ b/src/harness/claude/mod.rs @@ -59,6 +59,7 @@ pub const ADAPTER: Adapter = Adapter { native_compaction_managed: false, fallback_question: false, discover, + custom_path: true, probe_env: |exe| exe.map(probe_env).ok_or_else(|| "Could not find the Claude Code CLI.".into()), config_root: |home| home.join(".claude"), project_skills: ".claude/skills", @@ -72,9 +73,57 @@ pub const ADAPTER: Adapter = Adapter { can_resume: |transcript| worktree_recorded(transcript).map(|recorded| !recorded) .map_err(|e| format!("could not read the conversation: {e}")), has_history: |_, transcript| transcript, + followed: Some(followed_worktree), + }, + sign_in: super::SignIn { + program: "claude", + locate: |configured| configured.map(Path::to_path_buf).or_else(|| super::find("claude")), + args: &["auth", "login"], + session_hint: "Sign in with `claude auth login`, then retry the session.", + run_hint: "Sign in to Claude Code (`claude auth login`) first.", + }, + usage: Some(super::UsageSource { + read: |exe| { + let exe = exe.ok_or("Could not find the `claude` CLI on PATH.")?; + Ok(vec![super::limits::Pool { name: "Claude Code".into(), usage: limits::read(exe)? }]) + }, + every: limits::REFRESH_EVERY, + after_turn: true, + live: None, + }), + text_generation_launch: |_, _| Ok(serde_json::json!({"claudeCode": {"options": { + "tools": [], + "settingSources": [], + "persistSession": false, + "permissionMode": "dontAsk", + "strictMcpConfig": true + }}})), + probe_session_meta: Some(|| serde_json::json!({ "claudeCode": { "options": { "persistSession": false } } })), + copies_skills: false, + capabilities: super::capabilities::Capabilities::ALL, + reports: Some(|| usage::read_snapshots(&usage::snapshot_dir())), + native_sessions: Some(super::NativeSessions { + statuses: native_statuses, + write_name, + has_transcript: |session_id| claude_home().and_then(|home| find_transcript(&home, session_id)).is_some(), + }), + tidy: || { + crate::datadir::prune(trim::settings_dir(), 7 * 86_400); + crate::datadir::prune(usage::snapshot_dir(), 30 * 86_400); + crate::datadir::prune(usage::ctl_dir(), 7 * 86_400); }, }; +/// Where Claude Code's own `EnterWorktree` or `ExitWorktree` took session `session_id`, read from its transcript. +fn followed_worktree(session_id: &str, main: &Path) -> Option { + let transcript = find_transcript(&claude_home()?, session_id)?; + match worktree_session_state(&transcript).ok()?? { + WorktreeState::Entered(Some(path)) if path.is_dir() => Some(path), + WorktreeState::Exited if main.is_dir() => Some(main.to_path_buf()), + _ => None, + } +} + fn prepare_launch(input: &super::SessionInput<'_>, plan: &mut super::SessionPlan) -> Result<(), String> { let exe = input.executable_override.ok_or("Could not find the Claude Code CLI. Install it or set its path in Settings.")?; plan.off.extend(trimmed_mcp_tools()); @@ -186,7 +235,9 @@ pub fn prepare_session( env.push((usage::USAGE_DIR_ENV.into(), usage::snapshot_dir().to_string_lossy().into_owned())); env.push((usage::CTL_ENV.into(), usage::ctl_file(record_id).to_string_lossy().into_owned())); // The mod registers the agent types and answers their turns, so they go only where it loads. - if let Some(subagents) = settings.custom_subagents.env_for_edits(&settings.enabled_harnesses_list(), allow_subagent_edits) + let targets: Vec<_> = settings.enabled_harnesses_list().into_iter() + .filter(|h| super::capabilities::subagent(super::Harness::Claude, *h).allowed()).collect(); + if let Some(subagents) = settings.custom_subagents.env_for_edits(&targets, allow_subagent_edits) && let Ok(exe) = crate::platform::own_exe() { env.push((super::subagents::ENV.into(), subagents)); @@ -312,6 +363,13 @@ type StatusRecord = (Option, u64, Option<(String, i64, St #[derive(Default)] pub struct StatusFiles(std::collections::HashMap); +/// `session_statuses` for Claude Code's own folder, keeping what it read between polls. +fn native_statuses() -> std::collections::HashMap { + static SEEN: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); + let Some(home) = claude_home() else { return Default::default() }; + session_statuses(&home, &mut SEEN.lock().unwrap_or_else(|e| e.into_inner())) +} + /// Claude Code's own per-process registry (`sessions/.json`) says whether each session is `busy`, `idle` /// or `waiting`. Read-only; returns session id -> status, newest record winning (dead processes leave stale files). pub fn session_statuses(home: &Path, seen: &mut StatusFiles) -> std::collections::HashMap { diff --git a/src/harness/claude/usage.rs b/src/harness/claude/usage.rs index 504e0f3..121d2b0 100644 --- a/src/harness/claude/usage.rs +++ b/src/harness/claude/usage.rs @@ -7,10 +7,6 @@ use std::path::{Path, PathBuf}; -use serde::{Deserialize, Serialize}; - -use crate::store::RateLimit; - /// Env var holding the directory the mod writes its snapshot into. pub const USAGE_DIR_ENV: &str = "M4CODE_USAGE_DIR"; @@ -45,34 +41,7 @@ pub fn send_ctl(file: &Path, key: &str, value: serde_json::Value) { } /// What the mod reports (no paths, no costs, no prompts). -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Snapshot { - pub session_id: String, - pub five_hour: Option, - pub seven_day: Option, - /// 0.0..=1.0 (tokens over the window). - pub context_fraction: Option, - pub context_tokens: Option, - pub context_window: Option, - pub model: Option, - pub captured_at: i64, - /// The `/config` auto-compact switch. - #[serde(default)] - pub auto_compact: Option, - /// The `/config` "Precompute compaction" switch (background compaction); `None` while Claude Code does not offer it. - #[serde(default)] - pub precompute_compact: Option, - /// The `advisorModel` setting (`opus`, `sonnet`, ...); `None` when the advisor is off. - #[serde(default)] - pub advisor: Option, - /// The advisor the current conversation declared; it follows `advisor` on `/clear` or `/compact` and when the - /// advisor is switched off or on, but not when only the model changes mid-conversation. - #[serde(default)] - pub advisor_active: Option, - /// Tokens at which auto-compaction runs; `None` while it is off or not yet known. - #[serde(default)] - pub compact_at: Option, -} +pub type Snapshot = crate::harness::SessionReport; pub fn snapshot_dir() -> PathBuf { crate::datadir::data_dir().join("usage") diff --git a/src/harness/codex/mod.rs b/src/harness/codex/mod.rs index ffcea5c..f00fb48 100644 --- a/src/harness/codex/mod.rs +++ b/src/harness/codex/mod.rs @@ -3,6 +3,9 @@ pub mod limits; +use super::limits::Pool; +use super::subagents::Provider; +use crate::panels::logos; use super::subagents::Agent; use super::{Adapter, Reopen}; @@ -111,6 +114,20 @@ fn ignore_update(update: &Value) -> bool { && text.contains(" but is resuming with ") && text.contains("Consider switching back to ") } +/// A text-generation run: no web search, shell, apps, hooks or subagents, and read-only. +fn text_generation_launch(launch: &mut super::acp::Launch, _: &std::path::Path) -> Result { + let mut config = super::text_generation::inline_config("CODEX_CONFIG")?; + config.insert("web_search".into(), json!("disabled")); + let features = config.entry("features").or_insert_with(|| json!({})); + let features = features.as_object_mut().ok_or("Codex features configuration must be an object.")?; + for feature in ["shell_tool", "apps", "hooks", "multi_agent"] { + features.insert(feature.into(), json!(false)); + } + launch.env.push(("CODEX_CONFIG".into(), json!(config).to_string())); + launch.env.push(("INITIAL_AGENT_MODE".into(), "read-only".into())); + Ok(Value::Null) +} + pub const ADAPTER: Adapter = Adapter { name: "Codex", @@ -145,6 +162,7 @@ pub const ADAPTER: Adapter = Adapter { let codex = crate::platform::find_executable("codex")?; crate::platform::find_executable("npx").map(|_| codex) }), + custom_path: false, probe_env: super::no_probe_env, config_root: |home| home.join(".codex"), project_skills: ".codex/skills", @@ -160,6 +178,30 @@ pub const ADAPTER: Adapter = Adapter { ignore_update, ..super::ProtocolHooks::DEFAULT }, + sign_in: super::SignIn { + program: "codex", + locate: |_| super::find("codex"), + args: &["login"], + session_hint: "Sign in with `codex login`, then retry the session.", + run_hint: "Codex isn't signed in. Run `codex login`, then try again.", + }, + usage: Some(super::UsageSource { + read: |_| Ok(vec![Pool { name: "Codex".into(), usage: limits::probe()? }]), + every: limits::REFRESH_EVERY, + after_turn: true, + // Rollout logs are read again only after Codex writes to them: no network and no subprocess. + live: Some(super::LiveUsage { + read: || limits::codex_home().and_then(|home| limits::read(&home)), + every: std::time::Duration::from_secs(3), + }), + }), + text_generation_launch, + probe_session_meta: None, + copies_skills: false, + capabilities: super::capabilities::Capabilities::ALL, + reports: None, + native_sessions: None, + tidy: || {}, }; /// How Codex (`codex-acp`) reports background work over ACP: @@ -318,6 +360,31 @@ fn configure_mcp(tools: &crate::mcp::session::SessionTools, plan: &mut super::Se Ok(()) } +/// How this agent runs as a custom subagent (`harness/subagents.rs`). +pub const PROVIDER: Provider = Provider { + dashboard_url: None, + color: |t| t.codex, + marks: logos::codex_marks, + name: "Codex", + key: "codex", + task_name: "OpenAI Codex", + triggers: "Codex, GPT", + program: "npx", + // Pinned so an upstream adapter change reaches users only with a m4code release. + args: &["-y", "@agentclientprotocol/codex-acp@2.6.0"], + windows_fallback: None, + server: "codex-acp", + missing: "npx was not found on PATH. Codex subagents need Node.js.", + warning: None, + task_args: super::runner::no_args, + environment: super::runner::codex_env, + config_options: super::runner::no_options, + inbox_without_steering: true, + steering_prompt_required: true, + deferred_tool_target: false, + resumes_after_background: false, +}; + #[cfg(test)] mod tests { use super::*; diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 7742bbf..2f25e03 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -4,12 +4,12 @@ pub mod acp; pub mod antigravity; +pub mod capabilities; pub mod claude; pub mod codex; pub mod compaction; pub mod defaults; pub mod limits; -#[cfg(feature = "adapter-opencode")] pub mod opencode; pub mod permission; pub mod runner; @@ -96,13 +96,103 @@ pub struct Adapter { pub full_access_relaunch: bool, pub native_compaction_managed: bool, pub fallback_question: bool, + /// Finds the agent's executable, given the path set in Settings for an adapter with `custom_path`. pub discover: fn(Option<&Path>) -> Option, + /// Whether Settings has a field for the executable's path. Such an executable is found before any session starts; + /// the others are found in the background. + pub custom_path: bool, pub probe_env: fn(Option<&Path>) -> Result, pub config_root: fn(&Path) -> PathBuf, pub project_skills: &'static str, pub hidden_commands: &'static [&'static str], pub worktree: WorktreeHooks, pub protocol: ProtocolHooks, + pub sign_in: SignIn, + pub usage: Option, + /// Readies a text-generation run, which answers with no tools: changes to its launch, and its session's `_meta`. + pub text_generation_launch: fn(&mut acp::Launch, &Path) -> Result, + /// `_meta` for the session opened only to list models and modes. + pub probe_session_meta: Option Value>, + /// Whether skills are copied into its folders rather than linked, for an agent whose scan skips links. + pub copies_skills: bool, + /// The actions the core may take with this agent (`capabilities.rs`). + pub capabilities: capabilities::Capabilities, + /// Reads the figures its sessions report outside ACP, such as the files Claude Code's mod writes. + pub reports: Option Vec>, + /// The agent's own record of its running sessions, for an agent that keeps one. + pub native_sessions: Option, + /// Start-up housekeeping: deletes the old files the adapter left in m4code's data folder. + pub tidy: fn(), +} + +/// What an agent keeps about its own sessions outside ACP. +pub struct NativeSessions { + /// Each session's status (`busy`, `idle` or `waiting`) by its agent session id. Runs off the UI thread once a + /// second. + pub statuses: fn() -> std::collections::HashMap, + /// Gives a running session its name in the agent's own records, or takes it away with `None`. + pub write_name: fn(&str, Option<&str>), + /// Whether the agent saved a conversation under this session id. + pub has_transcript: fn(&str) -> bool, +} + +/// One session's figures, as its agent reported them outside ACP. A missing figure keeps the one stored before. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionReport { + pub session_id: String, + pub five_hour: Option, + pub seven_day: Option, + /// 0.0..=1.0 (tokens over the window). + pub context_fraction: Option, + pub context_tokens: Option, + pub context_window: Option, + pub model: Option, + pub captured_at: i64, + /// Whether the agent compacts on its own. + #[serde(default)] + pub auto_compact: Option, + /// Whether the agent compacts in the background; `None` while it does not offer it. + #[serde(default)] + pub precompute_compact: Option, + /// The advisor model setting (`opus`, `sonnet`, ...); `None` when the advisor is off. + #[serde(default)] + pub advisor: Option, + /// The advisor the current conversation declared; it follows `advisor` on `/clear` or `/compact` and when the + /// advisor is switched off or on, but not when only the model changes mid-conversation. + #[serde(default)] + pub advisor_active: Option, + /// Tokens at which auto-compaction runs; `None` while it is off or not yet known. + #[serde(default)] + pub compact_at: Option, +} + +/// Where an agent's 5-hour and weekly limits come from. No reading costs tokens. +pub struct UsageSource { + /// Asks the agent's CLI, given the executable set in Settings. + pub read: fn(Option<&Path>) -> Result, String>, + pub every: std::time::Duration, + /// Whether the end of a turn asks again. + pub after_turn: bool, + pub live: Option, +} + +/// A local reading cheap enough to take every few seconds, such as Codex's rollout logs. +#[derive(Clone, Copy)] +pub struct LiveUsage { + pub read: fn() -> Option, + pub every: std::time::Duration, +} + +/// How the user signs in to an agent's CLI, and what m4code says when the agent is signed out. +pub struct SignIn { + pub program: &'static str, + /// The sign-in CLI, given the executable set in Settings. + pub locate: fn(Option<&Path>) -> Option, + pub args: &'static [&'static str], + /// When an open session finds the agent signed out. + pub session_hint: &'static str, + /// When a one-shot run (listing models, a subagent's task) finds it signed out. + pub run_hint: &'static str, } pub struct SessionInput<'a> { @@ -238,6 +328,9 @@ pub struct WorktreeHooks { pub inspect: fn(&str) -> (Option, Option), pub can_resume: fn(&Path) -> Result, pub has_history: fn(Option<&str>, bool) -> bool, + /// For an agent that moves into worktrees itself: after it did, the folder session `.0` is in now, given the main + /// checkout `.1`. + pub followed: Option Option>, } impl WorktreeHooks { @@ -245,6 +338,7 @@ impl WorktreeHooks { inspect: |_| (None, None), can_resume: |_| Ok(true), has_history: |id, _| id.is_some(), + followed: None, }; } @@ -286,12 +380,28 @@ static UNAVAILABLE_ADAPTER: Adapter = Adapter { native_compaction_managed: false, fallback_question: false, discover: |_| None, + custom_path: false, probe_env: no_probe_env, config_root: Path::to_path_buf, project_skills: "", hidden_commands: &[], worktree: WorktreeHooks::DEFAULT, protocol: ProtocolHooks::DEFAULT, + sign_in: SignIn { + program: "unavailable", + locate: |_| None, + args: &[], + session_hint: "This adapter is unavailable in this build.", + run_hint: "This adapter is unavailable in this build.", + }, + text_generation_launch: |_, _| Err("This adapter is unavailable in this build.".into()), + usage: None, + probe_session_meta: None, + copies_skills: false, + capabilities: capabilities::Capabilities::NONE, + reports: None, + native_sessions: None, + tidy: || {}, }; /// Default single placeholder model for an adapter before its ACP server reports a live catalog. diff --git a/src/harness/opencode.rs b/src/harness/opencode.rs index 0cafcc1..b9b6361 100644 --- a/src/harness/opencode.rs +++ b/src/harness/opencode.rs @@ -1,5 +1,6 @@ //! OpenCode, which speaks ACP itself (`opencode acp`), on the providers the user set up in OpenCode. +use super::subagents::Provider; use super::subagents::Agent; use super::{Adapter, Reopen}; @@ -32,6 +33,16 @@ pub fn managed_compaction_config(inherited: Option<&str>, session: Option<&str>) } Ok(Value::Object(config).to_string()) } +/// A text-generation run, with every permission denied. +fn text_generation_launch(launch: &mut super::acp::Launch, _: &Path) -> Result { + let mut config = super::text_generation::inline_config("OPENCODE_CONFIG_CONTENT")?; + config.insert("default_agent".into(), json!("build")); + config.insert("permission".into(), json!({"*": "deny"})); + config.insert("agent".into(), json!({"build": {"permission": {"*": "deny"}}})); + launch.env.push(("OPENCODE_CONFIG_CONTENT".into(), json!(config).to_string())); + Ok(Value::Null) +} + pub const ADAPTER: Adapter = Adapter { name: "OpenCode", @@ -51,12 +62,28 @@ pub const ADAPTER: Adapter = Adapter { native_compaction_managed: true, fallback_question: true, discover: |_| crate::platform::find_executable("opencode"), + custom_path: false, probe_env: super::no_probe_env, config_root, project_skills: ".opencode/skills", hidden_commands: &["models", "connect", "share", "unshare", "sessions"], worktree: super::WorktreeHooks::DEFAULT, protocol: super::ProtocolHooks::DEFAULT, + sign_in: super::SignIn { + program: "opencode", + locate: |_| super::find("opencode"), + args: &["auth", "login"], + session_hint: "Sign in with `opencode auth login`, then retry the session.", + run_hint: "OpenCode isn't signed in. Run `opencode auth login`, then try again.", + }, + usage: None, + text_generation_launch, + probe_session_meta: None, + copies_skills: false, + capabilities: super::capabilities::Capabilities::ALL, + reports: None, + native_sessions: None, + tidy: || {}, }; fn prepare_launch(input: &super::SessionInput<'_>, plan: &mut super::SessionPlan) -> Result<(), String> { @@ -68,6 +95,30 @@ fn prepare_launch(input: &super::SessionInput<'_>, plan: &mut super::SessionPlan Ok(()) } +/// How this agent runs as a custom subagent (`harness/subagents.rs`). +pub const PROVIDER: Provider = Provider { + dashboard_url: Some("https://opencode.ai/console"), + color: |t| t.foreground, + marks: |name| (&[], Some(name.to_uppercase())), + name: "OpenCode", + key: "opencode", + task_name: "OpenCode", + triggers: "OpenCode", + program: "opencode", + args: &["acp"], + windows_fallback: None, + server: "opencode", + missing: "opencode was not found on PATH. OpenCode subagents need OpenCode installed.", + warning: None, + task_args: super::runner::no_args, + environment: super::runner::opencode_env, + config_options: super::runner::no_options, + inbox_without_steering: false, + steering_prompt_required: false, + deferred_tool_target: true, + resumes_after_background: false, +}; + #[cfg(test)] mod tests { use super::*; diff --git a/src/harness/runner.rs b/src/harness/runner.rs index a37431a..ef730f3 100644 --- a/src/harness/runner.rs +++ b/src/harness/runner.rs @@ -179,6 +179,8 @@ fn run_task(request: &Request, emit: &mut impl FnMut(Event)) -> Result Value { } fn new_model_probe_session(harness: crate::harness::Harness, cwd: &Path) -> Value { - if harness == crate::harness::Harness::Claude { - json!({ - "jsonrpc": "2.0", - "id": 1, - "method": "session/new", - "params": { - "cwd": cwd, - "mcpServers": [], - "_meta": { "claudeCode": { "options": { "persistSession": false } } } - } - }) - } else { - new_session(cwd) + let mut session = new_session(cwd); + if let Some(meta) = harness.adapter().probe_session_meta { + session["params"]["_meta"] = meta(); } + session } /// Opens a session only to read its model picker (`configOptions[category == "model"]`) and permission modes @@ -561,10 +554,7 @@ pub(crate) fn permission(options: &Value, edits: bool) -> Value { fn harness_error_reason(harness: crate::harness::Harness, error: &Value) -> String { if error["code"].as_i64() == Some(AUTH_REQUIRED) { - return match harness.agent() { - Some(agent) => agent.provider().sign_in.into(), - None => "Sign in to Claude Code (`claude auth login`) first.".into(), - }; + return harness.adapter().sign_in.run_hint.into(); } let server = harness.adapter().server_name; match error["message"].as_str() { diff --git a/src/harness/subagents.rs b/src/harness/subagents.rs index 72078ee..8cf6007 100644 --- a/src/harness/subagents.rs +++ b/src/harness/subagents.rs @@ -1,14 +1,11 @@ //! Custom subagents: agent types that run a task in another coding agent instead of Claude (Settings → Custom -//! subagents). What differs from one agent to the next lives in its `Provider`. +//! subagents). What differs from one agent to the next lives in its `Provider`, in the agent's adapter. //! //! m4code lists the agent types in `M4CODE_SUBAGENTS`, and the mod registers them, so Claude Code names them //! `m4code:`. Interactive Claude Code ignores `claude --agents` (only `-p` reads it), so the mod is the one way //! to define them per session. The mod answers each turn of those agents through the `m4code --acp` helper //! (`harness/runner.rs`). -use std::time::Duration; - -use super::limits::Pool; use crate::panels::{logos, theme::Theme}; use gpui::Hsla; @@ -24,7 +21,7 @@ pub const EXE_ENV: &str = "M4CODE_EXE"; const TYPE_NAME_MAX: usize = 64; /// A coding agent a custom subagent runs the task in. Its serde name is the key the mod reads in `M4CODE_SUBAGENTS` -/// and the prefix of its agent types. Adding one takes a variant here, its place in `ALL`, and a `Provider`. +/// and the prefix of its agent types. Adding one takes a variant here, its place in `ALL`, and a `Provider` in its adapter. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Agent { @@ -34,16 +31,8 @@ pub enum Agent { Antigravity, } -/// How a provider reads its limits and how often it asks again. -pub struct Limits { - pub read: fn() -> Result, String>, - pub every: Duration, -} - -/// Everything m4code knows about one agent, including its ACP server and usage limits. +/// How an agent runs as a custom subagent and shows in the sidebar. Each adapter holds its own. pub struct Provider { - /// The limits reader and refresh cadence, absent when the provider has no limits to show. - pub limits: Option, /// External usage dashboard URL shown in the sidebar when live limits polling is unavailable. pub dashboard_url: Option<&'static str>, /// The color of its sidebar limits. @@ -55,9 +44,9 @@ pub struct Provider { /// The key in `M4CODE_SUBAGENTS` and in the state file, and the start of every agent type name. pub key: &'static str, /// The name Claude reads in the agent type's description. - task_name: &'static str, + pub task_name: &'static str, /// What the user asks for, besides the model, when Claude should pick this agent. - triggers: &'static str, + pub triggers: &'static str, /// The ACP server: a program on the PATH and its arguments. pub program: &'static str, pub args: &'static [&'static str], @@ -67,8 +56,6 @@ pub struct Provider { pub server: &'static str, /// The failure when `program` can't be found. pub missing: &'static str, - /// The failure when the agent answers that it isn't signed in. - pub sign_in: &'static str, /// A risk the settings page shows before the agent is switched on, such as a sign-in its maker's terms forbid here. pub warning: Option<&'static str>, /// Arguments after `args` for one task's server, made ready here. @@ -89,93 +76,6 @@ pub struct Provider { pub resumes_after_background: bool, } -const CODEX: Provider = Provider { - limits: Some(Limits { read: || { - let usage = super::codex::limits::probe()?; - Ok(vec![Pool { name: "Codex".into(), usage }]) - }, every: super::codex::limits::REFRESH_EVERY }), - dashboard_url: None, - color: |t| t.codex, - marks: logos::codex_marks, - name: "Codex", - key: "codex", - task_name: "OpenAI Codex", - triggers: "Codex, GPT", - program: "npx", - // Pinned so an upstream adapter change reaches users only with a m4code release. - args: &["-y", "@agentclientprotocol/codex-acp@2.6.0"], - windows_fallback: None, - server: "codex-acp", - missing: "npx was not found on PATH. Codex subagents need Node.js.", - sign_in: "Codex isn't signed in. Run `codex login`, then try again.", - warning: None, - task_args: super::runner::no_args, - environment: super::runner::codex_env, - config_options: super::runner::no_options, - inbox_without_steering: true, - steering_prompt_required: true, - deferred_tool_target: false, - resumes_after_background: false, -}; - -const OPENCODE: Provider = Provider { - limits: None, - dashboard_url: Some("https://opencode.ai/console"), - color: |t| t.foreground, - marks: |name| (&[], Some(name.to_uppercase())), - name: "OpenCode", - key: "opencode", - task_name: "OpenCode", - triggers: "OpenCode", - program: "opencode", - args: &["acp"], - windows_fallback: None, - server: "opencode", - missing: "opencode was not found on PATH. OpenCode subagents need OpenCode installed.", - sign_in: "OpenCode isn't signed in. Run `opencode auth login`, then try again.", - warning: None, - task_args: super::runner::no_args, - environment: super::runner::opencode_env, - config_options: super::runner::no_options, - inbox_without_steering: false, - steering_prompt_required: false, - deferred_tool_target: true, - resumes_after_background: false, -}; - -const ANTIGRAVITY: Provider = Provider { - // Temporarily disabled pending clarification of Google's terms for usage polling. - // limits: Some(Limits { read: || { - // let agy = super::runner::locate(Agent::Antigravity).ok_or("agy was not found")?; - // super::antigravity::limits::read(&agy, &crate::datadir::data_dir()) - // }, every: super::antigravity::limits::REFRESH_EVERY }), - limits: None, - dashboard_url: Some("https://antigravity.google.com/remote?settingsOpen=true&settingsScreen=Models"), - color: |t| t.antigravity, - marks: logos::antigravity_marks, - name: "Antigravity", - key: "antigravity", - task_name: "Google Antigravity", - triggers: "Antigravity, Gemini", - program: "agy", - args: &["acp"], - windows_fallback: Some("agy/bin/agy.exe"), - server: "agy", - missing: "agy was not found. Antigravity subagents need the Antigravity CLI installed.", - sign_in: "Antigravity isn't signed in. Run `agy` and sign in, then try again.", - // Google's FAQ names Claude Code among the third-party software barred from Antigravity logins, under Section 6 of - // the Antigravity Additional Terms (https://antigravity.google/docs/faq, https://antigravity.google/terms). - warning: Some("Google's Antigravity terms forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does. Switch this on at your own risk."), - task_args: super::runner::antigravity_args, - environment: super::runner::no_env, - config_options: super::runner::antigravity_options, - inbox_without_steering: false, - steering_prompt_required: false, - deferred_tool_target: false, - // agy gives a command about ten seconds, then moves it to the background and ends the turn. - resumes_after_background: true, -}; - /// One value per agent, such as each agent's part of the settings. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AgentMap([T; Agent::ALL.len()]); @@ -206,9 +106,9 @@ impl Agent { pub fn provider(self) -> &'static Provider { match self { - Agent::Codex => &CODEX, - Agent::OpenCode => &OPENCODE, - Agent::Antigravity => &ANTIGRAVITY, + Agent::Codex => &super::codex::PROVIDER, + Agent::OpenCode => &super::opencode::PROVIDER, + Agent::Antigravity => &super::antigravity::PROVIDER, } } @@ -442,7 +342,7 @@ mod tests { fn every_limits_provider_has_visible_marks_and_a_color() { for agent in Agent::ALL { let provider = agent.provider(); - if provider.limits.is_some() { + if crate::harness::Harness::from_agent(agent).adapter().usage.is_some() { assert_ne!((provider.color)(crate::panels::theme::theme()), crate::panels::theme::theme().background, "{}", provider.name); for pool in ["Codex", "Gemini Models", "Claude and GPT models", "Some New models"] { let (marks, name) = (provider.marks)(pool); diff --git a/src/harness/text_generation.rs b/src/harness/text_generation.rs index a4206a4..c3c06a4 100644 --- a/src/harness/text_generation.rs +++ b/src/harness/text_generation.rs @@ -1,10 +1,9 @@ -use std::{future::Future, path::Path}; +use std::future::Future; use futures::{FutureExt, StreamExt, channel::mpsc, pin_mut, select}; use serde_json::{Value, json}; use super::{ - Harness, acp::{self, Connection, Event, Launch}, thread::Thread, }; @@ -22,7 +21,8 @@ pub async fn complete( std::fs::create_dir_all(&cwd).map_err(|e| format!("Could not create the text generation folder: {e}"))?; let (program, args) = (model.harness.adapter().server)()?; let launch = Launch { program, args, cwd, env }; - let (launch, meta) = configure(launch, model.harness, &data)?; + let mut launch = launch; + let meta = (model.harness.adapter().text_generation_launch)(&mut launch, &data)?; let (events, incoming) = mpsc::unbounded(); let connection = Connection::start(&launch, events)?; let params = json!({"cwd": launch.cwd, "mcpServers": [], "_meta": meta}); @@ -79,46 +79,8 @@ async fn run( } } -fn configure(mut launch: Launch, harness: Harness, data: &Path) -> Result<(Launch, Value), String> { - let mut meta = Value::Null; - match harness { - Harness::Claude => { - meta = json!({"claudeCode": {"options": { - "tools": [], - "settingSources": [], - "persistSession": false, - "permissionMode": "dontAsk", - "strictMcpConfig": true - }}}); - } - Harness::Codex => { - let mut config = inline_config("CODEX_CONFIG")?; - config.insert("web_search".into(), json!("disabled")); - let features = config.entry("features").or_insert_with(|| json!({})); - let features = features.as_object_mut().ok_or("Codex features configuration must be an object.")?; - for feature in ["shell_tool", "apps", "hooks", "multi_agent"] { - features.insert(feature.into(), json!(false)); - } - launch.env.push(("CODEX_CONFIG".into(), json!(config).to_string())); - launch.env.push(("INITIAL_AGENT_MODE".into(), "read-only".into())); - } - Harness::OpenCode => { - let mut config = inline_config("OPENCODE_CONFIG_CONTENT")?; - config.insert("default_agent".into(), json!("build")); - config.insert("permission".into(), json!({"*": "deny"})); - config.insert("agent".into(), json!({"build": {"permission": {"*": "deny"}}})); - launch.env.push(("OPENCODE_CONFIG_CONTENT".into(), json!(config).to_string())); - } - Harness::Antigravity => { - let folder = super::antigravity::read_only::prepare_text_generation(data) - .map_err(|e| format!("Could not disable Antigravity tools: {e}"))?; - launch.args.extend(["--gemini-dir".into(), folder.to_string_lossy().into_owned()]); - } - } - Ok((launch, meta)) -} - -fn inline_config(variable: &str) -> Result, String> { +/// The JSON object in environment variable `variable`, for an adapter that adds its text-generation settings to it. +pub(super) fn inline_config(variable: &str) -> Result, String> { serde_json::from_str(&std::env::var(variable).unwrap_or_else(|_| "{}".into())) .map_err(|e| format!("Invalid {variable}: {e}")) } @@ -174,6 +136,7 @@ fn collect(connection: &Connection, session_id: &str, event: Event, text: &mut S #[cfg(test)] mod tests { use super::*; + use crate::harness::Harness; use std::io::{BufRead, BufReader, Write}; fn exchange(tool_call: bool) -> Result { diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs index a30fbf8..67db104 100644 --- a/src/panels/inspector.rs +++ b/src/panels/inspector.rs @@ -322,7 +322,12 @@ impl Workspace { actions = actions.child(dim_row("find-in-session", IconName::Search, "Find in session")); } if let Some(sid) = id.filter(|id| self.live_view(id).and_then(|v| v.thread()).is_some()).cloned() { - if self.continuing_fresh.contains_key(&sid) { + let refusal = self.live_view(&sid).and_then(|v| v.thread()) + .and_then(|t| t.read(cx).harness.adapter().capabilities.continue_fresh.refusal()); + if let Some(refusal) = refusal { + actions = actions.child(dim_row("continue-fresh-session", IconName::CornerDownRight, "Continue in fresh session") + .tooltip(crate::panels::ui::tooltip::tooltip(refusal))); + } else if self.continuing_fresh.contains_key(&sid) { actions = actions.child(dim_row("continue-fresh-session", IconName::LoaderCircle, "Continuing in fresh session…")); } else { actions = actions.child( diff --git a/src/panels/picker.rs b/src/panels/picker.rs index c0a7c22..93c0d25 100644 --- a/src/panels/picker.rs +++ b/src/panels/picker.rs @@ -236,6 +236,7 @@ pub fn model_list_body( max_h: Pixels, is_selected: impl Fn(&CatalogModel) -> bool, harness_badge: impl Fn(Harness) -> Option<&'static str>, + refusal: impl Fn(Harness) -> Option<&'static str>, on_pick: impl Fn(&mut V, CatalogModel, &mut Window, &mut Context) + 'static, window: &mut Window, cx: &mut Context, @@ -265,6 +266,7 @@ pub fn model_list_body( }); previous = Some(model.harness); let selected = is_selected(model); + let refused = refusal(model.harness); let choice = model.clone(); let on_pick = on_pick.clone(); let logo = logos::draw( @@ -277,15 +279,19 @@ pub fn model_list_body( SharedString::from(format!("{row_prefix}-{n}")), Some(logo), model.name.clone(), - None, + refused.map(String::from), None, selected, - false, + refused.is_some(), ) .role(gpui::Role::ListBoxOption) .aria_selected(selected) .debug_selector(move || format!("{row_prefix}-{n}")); - let row = choices.add(row, move |v, window, cx| on_pick(v, choice.clone(), window, cx), cx); + let row = if refused.is_some() { + row.into_any_element() + } else { + choices.add(row, move |v, window, cx| on_pick(v, choice.clone(), window, cx), cx) + }; list = list.child(div().flex_none().flex().flex_col().children(heading).child(row)); } if filtered.is_empty() { @@ -314,6 +320,7 @@ pub fn model_dropdown_overlay( nav: &command::Nav, models: Vec, harness_badge: impl Fn(Harness) -> Option<&'static str>, + refusal: impl Fn(Harness) -> Option<&'static str>, on_pick: impl Fn(&mut V, CatalogModel, &mut Window, &mut Context) + 'static, on_close: impl Fn(&mut V, &mut Window, &mut Context) + 'static, window: &mut Window, @@ -328,6 +335,7 @@ pub fn model_dropdown_overlay( px(260.0), |_| false, harness_badge, + refusal, on_pick, window, cx, diff --git a/src/panels/settings_pages.rs b/src/panels/settings_pages.rs index 46c19e2..3c8edd9 100644 --- a/src/panels/settings_pages.rs +++ b/src/panels/settings_pages.rs @@ -276,14 +276,15 @@ impl Workspace { let Some(Modal::Settings { subagents, .. }) = &self.modal else { return div() }; let access = subagents.access(harness); let key = harness.key(); + let refusal = harness.adapter().capabilities.subagent.refusal(); let mut controls = div().flex().flex_col().gap(px(8.0)).child(switch_row( SharedString::from(format!("agent-dialog-{key}-on")), "Allow subagent delegation", - Some("Let other sessions delegate background tasks to this harness".into()), - access.on, + Some(refusal.unwrap_or("Let other sessions delegate background tasks to this harness").into()), + access.on && refusal.is_none(), move |ws, _, cx| flip_subagent(ws, harness, cx), cx, - )); + ).disabled(refusal.is_some())); if let Some(warning) = harness.agent().and_then(|agent| agent.provider().warning) { controls = controls.child(warn(warning)); } diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index 68b1fca..ebbf255 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -847,7 +847,7 @@ impl Workspace { let t = now(); let settings = &self.store.data.settings; let display = settings.usage_display; - let usage = &self.store.data.claude_usage; + let usage = self.store.data.usage_pools(Harness::Claude).into_iter().next().map(|pool| pool.usage).unwrap_or_default(); // A reset time stays true however old the reading is, so it shows whenever it is still ahead, including for a // reading saved before launch. Without one, the reading's age says how far to trust it. @@ -893,9 +893,7 @@ impl Workspace { div().flex().items_center().gap(gap).child(who).child(five).child(seven) }; let divider = || div().h(px(1.0)).w_full().my(px(2.0)).bg(theme().border); - let any_loading = [Harness::Claude, Harness::Codex, Harness::Antigravity] - .into_iter() - .any(|h| self.limits_state.get(h).loading); + let any_loading = Harness::registered().any(|h| self.limits_state.get(h).loading); let refresh_btn = div() .id("limits-refresh") .flex_none() @@ -945,7 +943,7 @@ impl Workspace { if provider.dashboard_url.is_some() && !settings.harness_enabled(harness) { continue; } - if provider.limits.is_none() { + if harness.adapter().usage.is_none() { if let Some(url) = provider.dashboard_url { if !rows.is_empty() { rows.push(divider()); @@ -1025,7 +1023,7 @@ impl Workspace { None => {} } } - for harness in [Harness::Claude, Harness::Codex, Harness::Antigravity] { + for harness in Harness::registered() { if settings.harness_enabled(harness) && self.limits_state.get(harness).authentication_required { rows.push(div().flex().flex_wrap().items_center().gap(px(6.0)) .child(div().text_size(crate::panels::scale::px(11.0)).text_color(theme().warning).child(format!("{} usage is stale.", harness.name()))) diff --git a/src/panels/workspace_pickers.rs b/src/panels/workspace_pickers.rs index 05a8b35..188af32 100644 --- a/src/panels/workspace_pickers.rs +++ b/src/panels/workspace_pickers.rs @@ -462,11 +462,23 @@ impl Workspace { } crate::app::SettingsModelTarget::Default => Act::PickDefaultModel(m.clone()), }; + let capabilities = m.harness.adapter().capabilities; + let refusal = match target { + crate::app::SettingsModelTarget::TextGeneration => capabilities.text_generation.refusal(), + crate::app::SettingsModelTarget::AutoHandoff => { + capabilities.handoff_in.allows(crate::harness::capabilities::Initiator::Automatic).refusal() + } + crate::app::SettingsModelTarget::Default => None, + }; let logo = logos::draw(logos::for_harness(m.harness), 11.5, if selected { accent } else { theme().subtle_foreground }).into_any_element(); - let row = command::row(gpui::SharedString::from(format!("settings-model-opt-{n}")), Some(logo), m.name.clone(), None, None, selected, false) + let row = command::row(gpui::SharedString::from(format!("settings-model-opt-{n}")), Some(logo), m.name.clone(), refusal.map(String::from), None, selected, refusal.is_some()) .role(gpui::Role::ListBoxOption) .aria_selected(selected); - list = list.child(choices.add(row, move |ws, window, cx| ws.act(choice.clone(), window, cx), cx)); + list = list.child(if refusal.is_some() { + row.into_any_element() + } else { + choices.add(row, move |ws, window, cx| ws.act(choice.clone(), window, cx), cx) + }); shown += 1; } if shown == 0 { diff --git a/src/priority.rs b/src/priority.rs index 37df0c1..7b58f0c 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -1,18 +1,18 @@ -//! Windows only: run the `claude` processes at above normal priority, so a heavy build in one session cannot slow -//! the sessions down. Only `claude` itself is raised. Windows gives a child the normal class unless its parent is +//! Windows only: run the agent processes at above normal priority, so a heavy build in one session cannot slow +//! the sessions down. Only the agent itself is raised. Windows gives a child the normal class unless its parent is //! below normal, so bash, cargo and rustc start at normal priority and stay as they are. -/// Raise the given `claude` processes to above normal priority. A process that already runs at another class was set +/// Raise the given agent processes to above normal priority. A process that already runs at another class was set /// by the user or another tool and is left alone. #[cfg(windows)] -pub fn raise_claude_priority(claude_pids: &[u32]) { +pub fn raise_agent_priority(agent_pids: &[u32]) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{ ABOVE_NORMAL_PRIORITY_CLASS, GetPriorityClass, NORMAL_PRIORITY_CLASS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_INFORMATION, SetPriorityClass, }; - for &pid in claude_pids { + for &pid in agent_pids { // SAFETY: the handle is checked for null before use and closed after. unsafe { let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_INFORMATION, 0, pid); diff --git a/src/skills/mod.rs b/src/skills/mod.rs index f3c8b63..05f98ed 100644 --- a/src/skills/mod.rs +++ b/src/skills/mod.rs @@ -324,7 +324,7 @@ const MANAGED_COPY_MARKER: &str = ".m4code-skill-managed"; /// Whether `harness` discovers skills with a non-symlink-following directory scan (e.g. Go's `os.ReadDir` + /// `entry.IsDir()`), requiring real copied directories rather than symlinks/junctions. fn uses_copied_skills(harness: Harness) -> bool { - harness == Harness::Antigravity + harness.adapter().copies_skills } /// Sibling m4code app folder names under the shared vendor directory (`m4rocks/`) so dev and release builds diff --git a/src/store/data.rs b/src/store/data.rs index 991a68f..35c48de 100644 --- a/src/store/data.rs +++ b/src/store/data.rs @@ -6,7 +6,7 @@ pub struct Data { pub projects: Vec, pub sessions: Vec, /// Last Claude Code 5-hour and 7-day usage reading, shown at launch while the next reading runs. - /// Serialized as `"account"` so older m4code versions can still load `state.json`. + /// Serialized as `"account"` so older m4code versions can still load `state.json`. Read it through `usage_pools`. #[serde(default, rename = "account", alias = "claude_usage")] pub claude_usage: UsageLimits, /// The last limits reading per provider key, shown at launch while the next reading runs. @@ -15,3 +15,30 @@ pub struct Data { pub layout: Layout, pub settings: Settings, } + +impl Data { + /// The last limits reading for `harness`. The host agent's (Claude Code's) is saved as `account`, the key older + /// versions read; every other agent's is saved under its key. + pub fn usage_pools(&self, harness: crate::harness::Harness) -> Vec { + match harness.agent() { + None => vec![crate::harness::limits::Pool { name: harness.name().into(), usage: self.claude_usage.clone() }], + Some(_) => self.subagent_limits.get(harness.key()).cloned().unwrap_or_default(), + } + } + + /// Merges `pools` into the stored reading for `harness`, keeping the newer reading of each window. Returns whether + /// anything changed; the caller marks the store dirty. + pub fn merge_usage_pools(&mut self, harness: crate::harness::Harness, pools: Vec) -> bool { + use crate::harness::limits::{merge_pools, merge_usage}; + if harness.agent().is_none() { + return pools.into_iter().next().is_some_and(|pool| merge_usage(&mut self.claude_usage, &pool.usage)); + } + let current = self.usage_pools(harness); + let merged = merge_pools(¤t, pools); + if merged == current { + return false; + } + self.subagent_limits.insert(harness.key().into(), merged); + true + } +} diff --git a/src/store/sessions.rs b/src/store/sessions.rs index 79aacab..4f875d8 100644 --- a/src/store/sessions.rs +++ b/src/store/sessions.rs @@ -53,8 +53,10 @@ pub struct AgentMeta { /// The harness the session runs in. Sessions from before there was a choice ran in Claude Code. #[serde(default)] pub harness: crate::harness::Harness, - #[serde(default)] - pub antigravity_full_access: bool, + /// The session's agent started with full access on its command line, for an adapter that relaunches to change it. + /// Saved under its first name, which older builds read. + #[serde(default, rename = "antigravity_full_access")] + pub launched_full_access: bool, /// Retry Read-only startup if the adapter stopped before confirming the mode. #[serde(default)] pub read_only_pending: bool, @@ -180,6 +182,11 @@ impl SessionRecord { pub fn provider_session_id(&self) -> Option<&str> { self.agent.as_ref().map(|c| c.session_id.as_str()).filter(|id| !id.is_empty()) } + + /// The harness an agent session runs on; a terminal session has none. + pub fn harness(&self) -> Option { + self.agent.as_ref().map(|meta| meta.harness) + } } fn yes() -> bool { diff --git a/src/store/settings.rs b/src/store/settings.rs index bb85be9..cca659a 100644 --- a/src/store/settings.rs +++ b/src/store/settings.rs @@ -64,7 +64,8 @@ fn default_auto_compact_threshold() -> u64 { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Settings { - /// Explicit path to the `claude` executable; discovery is used when empty. + /// Explicit path to the executable of the adapter with `custom_path` (Claude Code's); discovery is used when empty. + /// Read it through `executable_path`. #[serde(default)] pub claude_path: Option, /// Program for new terminal sessions (a path or a name on PATH); the platform default shell when empty. @@ -211,6 +212,12 @@ impl FollowUp { } impl Settings { + /// The executable path set for `harness`. Only an adapter with `custom_path` has one; it is saved as + /// `claude_path`, the key older versions read. + pub fn executable_path(&self, harness: crate::harness::Harness) -> Option<&std::path::Path> { + self.claude_path.as_deref().filter(|_| harness.adapter().custom_path) + } + pub fn subagent_access(&self, harness: crate::harness::Harness) -> crate::harness::SubagentAccess { match harness.agent() { None => self.claude_subagents, diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 500de16..e25110c 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -466,7 +466,7 @@ pub struct ThreadView { pub detail: bool, pub(crate) subagent_edits: Option, pub(super) initial_permission: Option, - antigravity_full_access: bool, + launched_full_access: bool, auto_fallback: bool, /// Each message's parsed markdown, by entry. The chat keeps it rather than the frame: a row that scrolls out of /// the list would otherwise drop it and parse again when it comes back, and a long message (over 4 KB) parses @@ -731,7 +731,7 @@ impl ThreadView { detail: false, subagent_edits: None, initial_permission: start.permission, - antigravity_full_access: false, + launched_full_access: false, auto_fallback: false, markdown: HashMap::new(), user_md_len: HashMap::new(), @@ -907,7 +907,7 @@ impl ThreadView { } break (connection, incoming, opened); }; - let _ = this.update(cx, |v, _| v.antigravity_full_access = full_access); + let _ = this.update(cx, |v, _| v.launched_full_access = full_access); let Some(sid) = this.update(cx, |v, cx| v.opened(opened, cx)).ok().flatten() else { return; }; @@ -1243,7 +1243,7 @@ impl ThreadView { } v.capabilities = opened.capabilities; v.agent_meta = opened.agent_meta; - v.antigravity_full_access = full_access; + v.launched_full_access = full_access; v.auto_fallback = auto_fallback; v.session_id = Some(sid.clone()); v.thread.modes = probe.modes; @@ -1659,7 +1659,7 @@ impl ThreadView { fn needs_login(&mut self, cx: &mut Context) { self.authentication_required = true; self.queue_held = true; - self.error = Some(acp::login_hint(self.harness).into()); + self.error = Some(self.harness.adapter().sign_in.session_hint.into()); cx.notify(); } @@ -1683,7 +1683,7 @@ impl ThreadView { self.cancel_questions(); self.asks = Default::default(); if why.as_deref().is_some_and(acp::looks_like_auth_error) { self.authentication_required = true; } - self.error = if self.authentication_required { Some(acp::login_hint(self.harness).into()) } else { why }; + self.error = if self.authentication_required { Some(self.harness.adapter().sign_in.session_hint.into()) } else { why }; if let Some(item) = self.preparing.take() { self.queue.push_front(item); } @@ -1830,7 +1830,7 @@ impl ThreadView { let id = opt.id.clone(); self.set_option(id, model.id, cx); } - } else { + } else if self.handoff_refusal(model.harness).is_none() { self.pending_model = Some(model); } self.picker = None; @@ -1930,6 +1930,12 @@ impl ThreadView { cx.notify(); return true; } + if let Some(refusal) = self.capabilities().compaction_fallback.refusal() { + let at = self.thread.notice(refusal, false); + self.remeasure(at); + cx.notify(); + return true; + } if self.has_active_turn() { let at = self.thread.notice("Wait for the current turn to finish before compacting.", false); self.remeasure(at); @@ -2784,7 +2790,7 @@ impl ThreadView { } pub(crate) fn permission(&self) -> Option { - if self.antigravity_full_access { + if self.launched_full_access { Some(Permission::FullAccess) } else { Permission::of(self.harness, self.thread.mode.as_deref()?) @@ -2835,15 +2841,15 @@ impl ThreadView { return Some(Permission::ReadOnly); } let permission = self.permission()?; - if self.antigravity_full_access || permission.native(self.harness) == self.thread.mode.as_deref() { + if self.launched_full_access || permission.native(self.harness) == self.thread.mode.as_deref() { self.handoff_permission() } else { None } } - pub(crate) fn antigravity_full_access(&self) -> bool { - self.antigravity_full_access + pub(crate) fn launched_full_access(&self) -> bool { + self.launched_full_access } pub(crate) fn permission_error(&mut self, why: String, cx: &mut Context) { @@ -2865,7 +2871,7 @@ impl ThreadView { let Some(permission) = wanted.resolve(&self.permissions()) else { return }; let Some(mode) = permission.listed(self.harness, &self.thread.modes) else { return }; let (Some(connection), Some(session)) = (self.connection.clone(), self.session_id.clone()) else { return }; - if self.harness.adapter().full_access_relaunch && self.antigravity_full_access != (permission == Permission::FullAccess) { + if self.harness.adapter().full_access_relaunch && self.launched_full_access != (permission == Permission::FullAccess) { self.require_read_only(wanted, cx); cx.emit(ThreadEvent::ReconnectPermission(wanted)); return; diff --git a/src/thread/render.rs b/src/thread/render.rs index 8a33e55..ae1bad8 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -17,6 +17,7 @@ use gpui::{AppContext, Entity}; use super::{ThreadEvent, ThreadPicker, ThreadView, elements}; use crate::harness::CatalogModel; +use crate::harness::capabilities::{Initiator, handoff}; use crate::harness::permission::Permission; use super::timeline::{self, RunKind}; use crate::harness::thread::{Entry, SubagentReport, ToolCall, ToolContent, ToolStatus, parse_subagent_report}; @@ -1133,6 +1134,7 @@ impl ThreadView { None => m.harness == current_harness && current_id.as_deref() == Some(m.id.as_str()), }, |_| None, + move |h| handoff(current_harness, h, Initiator::User).refusal(), |v, choice, window, cx| { v.pick_model(choice, cx); v.close_picker(window, cx); diff --git a/src/thread/review.rs b/src/thread/review.rs index 63846ab..034c9e4 100644 --- a/src/thread/review.rs +++ b/src/thread/review.rs @@ -686,6 +686,7 @@ impl ThreadView { &self.picker_nav, models, move |h| (h == current_harness && has_other_harness).then_some("current"), + move |h| crate::harness::capabilities::subagent(current_harness, h).refusal(), |v, choice, _, cx| v.start_cross_model_review(choice, cx), |v, _, cx| v.close_review_model_picker(cx), window, @@ -777,8 +778,11 @@ impl ThreadView { .child(div().flex_1().text_color(theme().muted_foreground).child(if review.snapshot.is_some() { "Changes since your last message" } else { "Changes captured at the end of this turn" })) .when_some(turn, |footer, turn| { let (id, end) = (turn.id, turn.end); + let fork_refusal = self.capabilities().fork.refusal(); footer.when(!review.restoring, |footer| footer.child( btn::text("review-fork", "Fork Thread", false) + .disabled(fork_refusal.is_some()) + .when_some(fork_refusal, |button, refusal| gpui::StatefulInteractiveElement::tooltip(button, crate::panels::ui::tooltip::tooltip(refusal))) .on_click(cx.listener(move |_, _: &ClickEvent, _, cx| cx.emit(ThreadEvent::Fork(end)))), )).when(!review.restoring && review.files.is_some() && review.error.is_none() && self.can_restore(turn), |footer| { footer.child(btn::text("review-restore", "Restore checkpoint", false).debug_selector(|| "review-restore".into()) diff --git a/src/thread/user_actions.rs b/src/thread/user_actions.rs index e8fec26..b6fb1dc 100644 --- a/src/thread/user_actions.rs +++ b/src/thread/user_actions.rs @@ -11,7 +11,8 @@ use uuid::Uuid; use super::{Phase, Queued, ThreadEvent, ThreadView, queue, review}; use crate::git::snapshot; -use crate::harness::{CatalogModel, thread::Entry}; +use crate::harness::capabilities::{Capabilities, Initiator, handoff}; +use crate::harness::{CatalogModel, Harness, thread::Entry}; use crate::panels::{picker, scale}; use crate::panels::theme::theme; use crate::panels::ui::{button as btn, tooltip::tooltip}; @@ -481,6 +482,15 @@ impl ThreadView { self.latest_visible_user_row() == Some(row) } + pub(super) fn capabilities(&self) -> Capabilities { + self.harness.adapter().capabilities + } + + /// Why the user can't move this conversation to `to`, if they can't. + pub(super) fn handoff_refusal(&self, to: Harness) -> Option<&'static str> { + handoff(self.harness, to, Initiator::User).refusal() + } + /// Shared gate for per-message actions that mutate files or restart the session. fn rewind_block_reason(&self) -> Option<&'static str> { if self.retrying_turn || self.pending_retry.is_some() { @@ -596,7 +606,9 @@ impl ThreadView { // 2. Rewind conversation (and file checkpoints) to this message let rewind_block = self.rewind_block_reason(); - let (rewind_tip, rewind_enabled) = if active_row { + let (rewind_tip, rewind_enabled) = if let Some(reason) = self.capabilities().rewind.refusal() { + (reason.to_string(), false) + } else if active_row { ("Wait for the current turn to finish".to_string(), false) } else if let Some(reason) = rewind_block { (reason.to_string(), false) @@ -704,7 +716,9 @@ impl ThreadView { } // 6. Fork session from here - let (fork_tip, fork_enabled) = if active_row { + let (fork_tip, fork_enabled) = if let Some(reason) = self.capabilities().fork.refusal() { + (reason.to_string(), false) + } else if active_row { ("Wait for the current turn to finish".to_string(), false) } else if self.phase != Phase::Ready || self.workspace_switching { (block.unwrap_or("Session is not ready").to_string(), false) @@ -762,7 +776,7 @@ impl ThreadView { /// Stage a true rewind to `row`: loads the message into the composer and shows a warning banner above it. /// Sending the message executes the rewind (restoring checkpoints and deleting everything from `row` onward). pub(super) fn stage_rewind(&mut self, row: usize, window: &mut Window, cx: &mut Context) { - if self.rewind_block_reason().is_some() || self.is_active_user_row(row) { + if !self.capabilities().rewind.allowed() || self.rewind_block_reason().is_some() || self.is_active_user_row(row) { return; } let Some(Entry::User(prompt)) = self.thread.entries.get(row) else { return }; @@ -791,12 +805,14 @@ impl ThreadView { effort: Option, cx: &mut Context, ) { - if let Some(reason) = self.rewind_block_reason() { + let refusal = self.capabilities().rewind.refusal() + .or_else(|| target_model.as_ref().and_then(|target| self.handoff_refusal(target.harness))); + if let Some(reason) = refusal.or_else(|| self.rewind_block_reason()) { self.pending_rewind = Some(rewind); self.pending_model = target_model; self.pending_effort = effort; self.pending_edit_draft = Some(message); - let at = self.thread.notice(format!("Could not rewind: {reason}."), true); + let at = self.thread.notice(format!("Could not rewind: {}.", reason.trim_end_matches('.')), true); self.remeasure(at); cx.notify(); return; @@ -875,7 +891,7 @@ impl ThreadView { pub(super) fn select_retry_model(&mut self, row: usize, target: CatalogModel, window: &mut Window, cx: &mut Context) { self.retry_model_picker = None; - if self.retry_block_reason().is_some() || self.is_active_user_row(row) { + if self.handoff_refusal(target.harness).is_some() || self.retry_block_reason().is_some() || self.is_active_user_row(row) { self.focus_composer(window, cx); cx.notify(); return; @@ -896,7 +912,7 @@ impl ThreadView { } pub(super) fn request_fork_from_row(&mut self, row: usize, cx: &mut Context) { - if self.phase != Phase::Ready || self.workspace_switching || self.is_active_user_row(row) { + if !self.capabilities().fork.allowed() || self.phase != Phase::Ready || self.workspace_switching || self.is_active_user_row(row) { return; } if !self.thread.entries.get(row).is_some_and(is_visible_user_entry) { @@ -1368,6 +1384,7 @@ impl ThreadView { &self.picker_nav, models, move |h| (h != current_harness).then_some("handoff"), + move |h| handoff(current_harness, h, Initiator::User).refusal(), move |v, target, window, cx| v.select_retry_model(row, target, window, cx), |v, window, cx| v.close_retry_model_picker(window, cx), window,