diff --git a/README.md b/README.md index 7c19037..7fa1980 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,15 @@ Claudiu is a native desktop app, written in Rust with [Rune](https://github.com/ ## What it does -Each session is your own `claude` process in a real terminal, and sign-in stays with Claude Code. Around it, Claudiu adds a sidebar of running and recent sessions, notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E), usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, and Codex and OpenCode subagents (Settings → Custom subagents). Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, and with Allow edits on, either acts without Claude Code's permission rules. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which Claudiu reads from the session logs in `~/.codex`. Settings lists the rest. +Each session is your own `claude` process in a real terminal, and sign-in stays with Claude Code. Around it, Claudiu adds a sidebar of running and recent sessions, notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E), usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, and Codex, OpenCode and Google Antigravity subagents (Settings → Custom subagents). Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, Antigravity subagents need the Antigravity CLI (`agy`) installed and signed in, and with Allow edits on, each acts without Claude Code's permission rules. Read-only Antigravity runs from its own folder in Claudiu's data, whose hook refuses every tool but reading and searching, so your own Antigravity rules, skills and MCP servers don't load there. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which Claudiu reads from the session logs in `~/.codex`; with Antigravity subagents on, it shows Antigravity's limits for each group of models, from `agy`'s own `/usage`, asked every five minutes at no token cost. Their last saved readings show at launch and refresh in the background. Settings lists the rest. While a custom subagent works, its own view in Claude Code's tasks list streams its messages, reasoning, plan and tool steps and command output. The main conversation stays as it is until the subagent hands back its report. The first Codex run takes longer while npm downloads the adapter. Claude can choose a Codex subagent's effort when it starts one (`max` runs as Codex's `xhigh`); otherwise Codex uses the effort in `~/.codex/config.toml`. -A message Claude sends a running Codex subagent reaches it in the task it is working on, and its answer streams like the rest. OpenCode takes such messages too if its version supports them. Otherwise, and once the subagent has finished, Claude Code sends the message as a follow-up. +A message Claude sends a running Codex subagent reaches it in the task it is working on, and its answer streams like the rest. OpenCode takes such messages too if its version supports them. Antigravity and older OpenCode versions get the message as a follow-up once the current turn ends, as does a subagent that has already finished. Antigravity takes the effort Claude asks for, capped at the highest thinking level its model offers. ## What it touches -Claudiu never calls the Anthropic API or deletes a transcript, and it changes Claude Code's settings only when you flip a switch. Its network use is GitHub (the update check and the GitHub pane), plus npm and OpenAI once you turn on Codex subagents, and the providers you set up in OpenCode once you turn on OpenCode subagents. Terminal contents are never logged. +Claudiu never calls the Anthropic API or deletes a transcript, and it changes Claude Code's settings only when you flip a switch. Its network use is GitHub (the update check and the GitHub pane), plus npm and OpenAI once you turn on Codex subagents, the providers you set up in OpenCode once you turn on OpenCode subagents, and Google once you turn on Antigravity subagents. Terminal contents are never logged. ## Development diff --git a/assets/LICENSE-LOBE-ICONS b/assets/LICENSE-LOBE-ICONS new file mode 100644 index 0000000..1dd53d2 --- /dev/null +++ b/assets/LICENSE-LOBE-ICONS @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 LobeHub + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/mod/hooks/register.js b/mod/hooks/register.js index 5017cce..59b4cf3 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -18,7 +18,7 @@ // paints the live card over them. Claudiu's measured height comes back in `CLAUDIU_VISUAL_PREFIX.rows`. // - One-shot completions: runs requests from `CLAUDIU_ASK_FILE` (commit messages, session titles) with // `$.model.complete`, on this session's own client, so Claudiu needs no `claude -p`. -// - Custom subagents: registers the Codex and OpenCode agent types `CLAUDIU_SUBAGENTS` lists. Claude never runs for +// - Custom subagents: registers the provider agent types `CLAUDIU_SUBAGENTS` lists. Claude never runs for // those agents: each turn is answered here with what the agent writes through `CLAUDIU_EXE --acp`, and its last // message is handed back with SubagentHandback. @@ -56,9 +56,8 @@ let askPoll // watches CLAUDIU_ASK_FILE let askSeen = null // id of the last request looked at let asking = false // a completion is running; a poll that finds another request waits for it const cardRows = new Map() // show_visual call id -> rows reserved for its card -const AGENT_NAMES = { codex: 'Codex', opencode: 'OpenCode' } // the agents of `claude/subagents.rs`, by their key const AGENT_PREFIX = 'Claudiu:' // what Claude Code puts before an agent type this plugin registers -const customTypes = new Map() // agent type name -> { agent, model, edits } of each custom agent type Claudiu defined +const customTypes = new Map() // agent type name -> { agent, model, edits, name } of each custom agent type Claudiu defined const customRuns = new Map() // agent id -> { type, prompt, effort, turnId, report, steps } of each custom subagent started const agentCalls = new Map() // Agent call id -> { type, description, effort } of each running call that asked for an effort const published = new Set() // call ids whose card file this process wrote from the transcript @@ -364,14 +363,14 @@ async function registerSubagents($) { } catch { return } - for (const agent of Object.keys(AGENT_NAMES)) { + for (const agent of Object.keys(agents ?? {})) { const listing = agents?.[agent] for (const { name, model, description, prompt } of listing?.types ?? []) { if (![name, model, description, prompt].every(v => typeof v === 'string')) continue // Claude never runs for this agent (customStep answers its turns) unless this module lost track of it; the // prompt then says so. await $.agent.register({ name, description, prompt, model: 'haiku', tools: [] }) - .then(() => customTypes.set(AGENT_PREFIX + name, { agent, model, edits: listing.edits === true })) + .then(() => customTypes.set(AGENT_PREFIX + name, { agent, model, edits: listing.edits === true, name: typeof listing.name === 'string' ? listing.name : agent })) .catch(() => {}) } } @@ -417,7 +416,7 @@ async function customRun($, agentId) { // The task for this turn: the newest message to the agent, read from its transcript. A message sent to a finished // subagent starts a turn of its own, and Claude Code spawns the agent again for it, so the run noted at spawn knows only -// that message. Each turn also starts Codex or OpenCode afresh, so a follow-up carries the first task and the last +// that message. Each turn also starts the provider afresh, so a follow-up carries the first task and the last // report handed back before it. async function customTask($, run, agentId) { const messages = await $.session.messages({ agentId }).catch(() => []) @@ -436,14 +435,14 @@ async function customTask($, run, agentId) { // The report with the steps the agent took added under it. Claude Code counts none of them as the subagent's tool // calls, so without this list the caller can't tell a report written from the files from one written from the task -// alone. +// alone. The heading says so too: a caller that saw a tool count of 0 has asked for the whole task again. function withSteps(report, name, steps) { if (steps.length === 0) return `${report}\n\n---\n${name} ran no steps.` // A step can be a multi-line command; on one line it can't be mistaken for report text or a step of its own. const oneLine = steps.map(s => s.replace(/\s+/g, ' ').trim()) const listed = oneLine.slice(0, STEPS_LISTED).map(s => '- ' + (s.length > STEP_CHARS ? s.slice(0, STEP_CHARS - 1) + '…' : s)) if (steps.length > STEPS_LISTED) listed.push(`- and ${steps.length - STEPS_LISTED} more`) - return `${report}\n\n---\nSteps ${name} ran (${steps.length}):\n${listed.join('\n')}` + return `${report}\n\n---\nSteps ${name} ran (${steps.length}), outside Claude Code, which counts them as 0 tool uses:\n${listed.join('\n')}` } function displayText(text) { @@ -491,8 +490,7 @@ async function* customStep($, e, next, run) { run.turnId = e.turnId run.handedBack = 0 run.steps = [] - const { agent, model, edits } = customTypes.get(run.type) - const name = AGENT_NAMES[agent] + const { agent, model, edits, name } = customTypes.get(run.type) yield { kind: 'text', index: 0, text: `${name} on ${model}, ${edits ? 'edits allowed' : 'read-only'}\n\n` } run.report = null let previousKind @@ -545,7 +543,7 @@ async function* customStep($, e, next, run) { if (next.signal?.aborted) return run.report ??= `${name} failed: the helper stopped without an answer.` } - const message = withSteps(run.report, AGENT_NAMES[customTypes.get(run.type).agent], run.steps) + const message = withSteps(run.report, customTypes.get(run.type).name, run.steps) if (run.handedBack >= 2) { yield { kind: 'text', index: 1, text: message } yield { kind: 'stop', stopReason: 'end_turn', usage: null } diff --git a/mod/hooks/subagents.test.ts b/mod/hooks/subagents.test.ts index e6a9219..e310d72 100644 --- a/mod/hooks/subagents.test.ts +++ b/mod/hooks/subagents.test.ts @@ -5,7 +5,7 @@ function type(name: string, model: string) { return { name, model, description: `Runs the task on ${model}.`, prompt: 'Say the mod lost track.' } } -const SUBAGENTS = JSON.stringify({ codex: { edits: false, types: [type('codex-gpt-5-5', 'gpt-5.5')] } }) +const SUBAGENTS = JSON.stringify({ codex: { name: 'Codex', edits: false, types: [type('codex-gpt-5-5', 'gpt-5.5')] } }) // What the engine answers beneath the mod for a session with Codex on. `helper` is what `claudiu --acp` writes; // `requests` collects what the mod sent it. @@ -65,7 +65,7 @@ test('activity streams in the subagent and leaves the main conversation alone', expect(text).toContain('Thinking\nChecking the parser.') expect(text).toContain('▸ Run tests · failed') expect(text).toContain('Tool output\ntest failed') - expect(JSON.parse(chunks.find(c => c.kind === 'input').json).message).toBe('Parser test failed.\n\n---\nSteps Codex ran (1):\n- Run tests') + expect(JSON.parse(chunks.find(c => c.kind === 'input').json).message).toBe('Parser test failed.\n\n---\nSteps Codex ran (1), outside Claude Code, which counts them as 0 tool uses:\n- Run tests') }) async function step($: any, turnId: string, index: number, agentId?: string) { @@ -187,7 +187,7 @@ test('a Codex subagent runs the task in Codex and hands back its last message', const tool = chunks.find(c => c.kind === 'tool') expect(tool.name).toBe('SubagentHandback') // The report names the steps, since Claude Code counts none of Codex's tool calls as the subagent's. - const report = 'The bug is on line 12.\n\n---\nSteps Codex ran (1):\n- Read src/a.rs' + const report = 'The bug is on line 12.\n\n---\nSteps Codex ran (1), outside Claude Code, which counts them as 0 tool uses:\n- Read src/a.rs' const input = chunks.filter(c => c.kind === 'input').map(c => c.json).join('') expect(JSON.parse(input)).toEqual({ message: report }) @@ -260,7 +260,7 @@ test('a report with many steps lists the first ones, each cut short', async ($, await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) const chunks = await step($, 't1', 0, 'a1') const lines = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')).message.split('\n') - expect(lines.slice(0, 6)).toEqual(['Done.', '', '---', 'Steps Codex ran (32):', '- ' + 'x'.repeat(119) + '…', '- bash cat < { + const requests: any[] = [] + const registered = engine(on, [JSON.stringify({ kind: 'report', text: 'Done.' })], requests, JSON.stringify({ + antigravity: { name: 'Antigravity', edits: false, types: [type('antigravity-gemini-4-neon', 'gemini-4-neon')] }, + })) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + expect(registered.map(r => r.name)).toEqual(['antigravity-gemini-4-neon']) + await $.agent.spawn({ subagentType: 'Claudiu:antigravity-gemini-4-neon', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + expect(requests[0].input.agent).toBe('antigravity') + expect(chunks.filter(c => c.kind === 'text').map(c => c.text).join('')).toBe('Antigravity on gemini-4-neon, read-only\n\n') + expect(JSON.parse(chunks.find(c => c.kind === 'input').json).message).toContain('Antigravity ran no steps.') +}) + +test('a provider without a display name falls back to its key', async ($, on) => { + engine(on, [JSON.stringify({ kind: 'report', text: 'Done.' })], [], JSON.stringify({ + fourth: { edits: false, types: [type('fourth-model', 'model')] }, + })) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:fourth-model', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + expect(chunks.filter(c => c.kind === 'text').map(c => c.text).join('')).toBe('fourth on model, read-only\n\n') + expect(JSON.parse(chunks.find(c => c.kind === 'input').json).message).toContain('fourth ran no steps.') +}) + test('a failure is handed back as the report', async ($, on) => { engine(on, [JSON.stringify({ kind: 'failed', reason: "Codex isn't signed in. Run `codex login`, then try again." })], []) await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) diff --git a/src/app/headless.rs b/src/app/headless.rs index f7f0b42..0a4cace 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -47,14 +47,22 @@ fn git(dir: &Path, args: &[&str]) -> std::process::Output { impl Harness { /// The workspace in a 1600×900 window, with the projects `initial` makes in the work folder registered. fn new(initial: impl FnOnce(&Path) -> Vec) -> Self { + Self::with_store(initial, |store, _| store) + } + + fn with_store(initial: impl FnOnce(&Path) -> Vec, prepare: impl FnOnce(Store, &Path) -> Store) -> Self { let turn = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let (_, home) = datadir::use_throwaway_folders(); let dirs = [tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()]; let work = dunce::canonicalize(dirs[1].path()).unwrap(); - let store = Store::load(dirs[0].path().join("state.json")); + let path = dirs[0].path().join("state.json"); + let store = prepare(Store::load(path.clone()), &path); let mut ws = Workspace::with_store(initial(&work), store); ws.claude_exe = Some(fake_claude(&work)); + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); + let asked = ws.limits_asked.clone(); ws.start(); + assert_eq!(ws.limits_asked, asked, "saved readings draw before any provider read starts"); let mut rt = rune::Runtime::new(ws, crate::panels::workspace_view::view, (1600.0, 900.0), rune::Env::new(true, 2.0)); // What `main` hands the app: keys no element took. rt.on_key = Some(|ws: &mut Workspace, ev: &rune::KeyEvent, tx: &mut Tx| ws.on_key(ev, tx)); @@ -83,6 +91,7 @@ impl Harness { /// One frame: background answers and terminal output are taken in, then the view is drawn. fn pump(&mut self) { self.rt.update(|ws, tx| { + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); ws.poll(tx); }); self.rt.frame(1.0 / 60.0); @@ -214,14 +223,139 @@ fn the_workspace_draws_and_its_controls_answer() { assert!(h.ws().is_running(&id)); } +#[test] +fn saved_subagent_limits_draw_at_launch_before_any_read() { + use crate::claude::{limits::Pool, subagents::Agent}; + let h = Harness::with_store(|_| vec![], |mut store, path| { + let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; + for agent in Agent::ALL { + if agent.provider().limits.is_some() { + store.data.settings.custom_subagents.get_mut(agent).on = true; + store.data.subagent_limits.insert(agent.key().into(), vec![Pool { name: agent.name().into(), usage: crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit.clone()) } }]); + } + } + store.save(); + Store::load(path.to_path_buf()) + }); + for agent in Agent::ALL { + if agent.provider().limits.is_some() { + assert!(h.drawn(&format!("meter-{}-0-5h", agent.key())), "{}: {:?}", agent.name(), h.keys()); + } + } +} + +#[test] +fn failed_and_unchanged_subagent_limits_keep_the_saved_reading_without_a_redraw() { + use crate::claude::limits::Pool; + let mut h = Harness::new(|_| vec![]); + let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; + let pools = vec![Pool { name: "Codex".into(), usage: crate::store::AccountUsage { five_hour: Some(limit), seven_day: None } }]; + h.step(|ws| { + ws.rt.dirty = false; + ws.apply_subagent_limits("codex", Ok(pools.clone())); + assert!(ws.rt.dirty, "a changed reading redraws"); + ws.rt.dirty = false; + ws.apply_subagent_limits("codex", Ok(pools.clone())); + assert!(!ws.rt.dirty, "the same reading needs no redraw"); + ws.apply_subagent_limits("codex", Err("no reading yet".into())); + assert!(!ws.rt.dirty, "a failed read needs no redraw"); + assert_eq!(ws.store.data.subagent_limits.get("codex"), Some(&pools)); + }); +} + #[test] fn codex_limits_show_only_with_codex_subagents_on() { let mut h = Harness::new(|_| vec![]); let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; - h.step(|ws| ws.codex_usage = Some(crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit) })); - assert!(h.drawn("meter-5h") && !h.drawn("meter-codex-5h"), "Codex subagents are off: {:?}", h.keys()); - h.step(|ws| ws.store.data.settings.custom_subagents.codex.on = true); - assert!(h.drawn("meter-codex-5h") && h.drawn("meter-codex-7d"), "Codex's row draws under Claude's: {:?}", h.keys()); + h.step(|ws| { + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); + ws.store.data.subagent_limits.insert("codex".into(), vec![crate::claude::limits::Pool { name: "Codex".into(), usage: crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit) } }]); + }); + assert!(h.drawn("meter-5h") && !h.drawn("meter-codex-0-5h"), "Codex subagents are off: {:?}", h.keys()); + h.step(|ws| ws.store.data.settings.custom_subagents.get_mut(crate::claude::subagents::Agent::Codex).on = true); + assert!(h.drawn("meter-codex-0-5h") && h.drawn("meter-codex-0-7d"), "Codex's row draws under Claude's: {:?}", h.keys()); +} + +#[test] +fn a_reading_saved_hours_ago_still_counts_down_to_its_reset() { + use crate::claude::limits::Pool; + use crate::claude::subagents::Agent; + let mut h = Harness::new(|_| vec![]); + let saved = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3630), seen_at: now() - 3 * 3600 }; + h.step(|ws| { + ws.store.data.settings.custom_subagents.get_mut(Agent::Codex).on = true; + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); + ws.store.data.subagent_limits.insert("codex".into(), vec![Pool { name: "Codex".into(), usage: crate::store::AccountUsage { five_hour: Some(saved), seven_day: None } }]); + }); + let texts: Vec = h.rt.elements().into_iter().filter_map(|e| e.text).collect(); + assert!(texts.iter().any(|t| t == "1h 0m") && !texts.iter().any(|t| t.ends_with(" ago")), "{texts:?}"); +} + +#[test] +fn limit_meters_line_up_in_one_compact_grid_for_every_provider() { + use crate::claude::limits::Pool; + use crate::claude::subagents::Agent; + let mut h = Harness::new(|_| vec![]); + let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; + let both = crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit.clone()) }; + h.step(|ws| { + ws.store.data.accounts = vec![crate::store::Account { id: crate::store::MAIN_ACCOUNT.into(), usage: both.clone(), ..Default::default() }]; + ws.store.data.subagent_limits.insert("codex".into(), vec![Pool { name: "Codex".into(), usage: both.clone() }]); + ws.store.data.settings.custom_subagents.get_mut(Agent::Codex).on = true; + ws.store.data.settings.custom_subagents.get_mut(Agent::Antigravity).on = true; + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); + ws.store.data.subagent_limits.insert("antigravity".into(), vec![Pool { name: "Gemini Models".into(), usage: both.clone() }, Pool { name: "Claude and GPT models".into(), usage: both.clone() }, Pool { name: "Gemini 4 Argon".into(), usage: crate::store::AccountUsage { five_hour: None, seven_day: Some(limit.clone()) } }]); + }); + h.settle(); + let elements = h.rt.elements(); + let rect = |key: &str| -> [f32; 4] { elements.iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting).unwrap_or_else(|| panic!("{key} is not drawn: {:?}", h.keys())).rect }; + let five = ["meter-5h", "meter-codex-0-5h", "meter-antigravity-0-5h", "meter-antigravity-1-5h"]; + let seven = ["meter-7d", "meter-codex-0-7d", "meter-antigravity-0-7d", "meter-antigravity-1-7d", "meter-antigravity-2-7d"]; + assert!(!h.drawn("meter-antigravity-2-5h"), "Argon has no five-hour window"); + for column in [&five[..], &seven[..]] { + let first = rect(column[0]); + for key in column { + let r = rect(key); + assert!((r[0] - first[0]).abs() <= 1.0 && (r[2] - first[2]).abs() <= 1.0, "{key} is not aligned with {}: {r:?} vs {first:?}", column[0]); + assert!(r[3] <= 22.0, "{key} is too tall: {r:?}"); + assert!(elements.iter().any(|e| e.text.as_deref().is_some_and(|t| t.contains("24%")) && e.rect[0] >= r[0] - 1.0 && e.rect[1] >= r[1] - 1.0 && e.rect[0] + e.rect[2] <= r[0] + r[2] + 1.0 && e.rect[1] + e.rect[3] <= r[1] + r[3] + 1.0), "{key} has no percent text inside its bar: {r:?}"); + } + } + for key in ["meter-row-claude", "meter-row-codex-0", "meter-row-antigravity-0", "meter-row-antigravity-1", "meter-row-antigravity-2"] { + let r = rect(key); + assert!(r[3] <= 24.0, "{key} is too tall: {r:?}"); + } + let grid = rect("meter-limits"); + assert!(grid[3] < 170.0, "the grid is too tall: {grid:?}"); + let headers = elements.iter().filter(|e| e.text.as_deref().is_some_and(|t| t.contains("5 HOUR"))).count(); + assert_eq!(headers, 1, "5 HOUR should appear once"); + // Rows are told apart by their logos; only a named Gemini model adds a short name. + for source in ["claude", "codex-0", "antigravity-0", "antigravity-1", "antigravity-2"] { + let (logo, row) = (rect(&format!("meter-logo-{source}")), rect(&format!("meter-row-{source}"))); + assert!(logo[0] >= row[0] - 1.0 && logo[1] >= row[1] - 1.0 && logo[1] + logo[3] <= row[1] + row[3] + 1.0, "{source}'s logo starts its row: {logo:?} in {row:?}"); + } + let texts: Vec<&str> = elements.iter().filter_map(|e| e.text.as_deref()).collect(); + assert!(!texts.contains(&"CLAUDE") && !texts.contains(&"CODEX") && !texts.contains(&"GEMINI") && !texts.contains(&"CLAUDE/GPT") && texts.contains(&"Ar"), "{texts:?}"); +} + +#[test] +fn antigravity_limits_show_one_row_per_pool_only_with_antigravity_subagents_on() { + use crate::claude::limits::Pool; + use crate::claude::subagents::Agent; + let mut h = Harness::new(|_| vec![]); + let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; + let gemini = Pool { name: "Gemini Models".into(), usage: crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit.clone()) } }; + let argon = Pool { name: "Gemini 4 Argon".into(), usage: crate::store::AccountUsage { five_hour: None, seven_day: Some(limit) } }; + // Asked just now, so the test's own `agy`, if any, isn't run. + h.step(|ws| { + ws.limits_asked = crate::claude::subagents::AgentMap::from_fn(|_| Some(Instant::now())); + ws.store.data.subagent_limits.insert("antigravity".into(), vec![gemini, argon]); + }); + assert!(!h.drawn("meter-antigravity-0-5h"), "Antigravity subagents are off: {:?}", h.keys()); + h.step(|ws| ws.store.data.settings.custom_subagents.get_mut(Agent::Antigravity).on = true); + assert!(h.drawn("meter-antigravity-0-5h") && h.drawn("meter-antigravity-0-7d"), "Gemini's row draws under Claude's: {:?}", h.keys()); + assert!(h.drawn("meter-antigravity-1-7d") && !h.drawn("meter-antigravity-1-5h"), "a pool shows only the windows it has"); + assert!(h.drawn("meter-logo-antigravity-0") && h.drawn("meter-logo-antigravity-1"), "each pool's row starts with its logos"); } /// Sessions and the shell under them, the sidebars' widths, cards and the GitHub view, with a stand-in `claude`. @@ -2386,7 +2520,7 @@ fn a_card_scrolling_past_the_top_does_not_fade_or_double() { } } -/// A model with a long name keeps its switch inside its row, on the page and in the picker. +/// A model with a long name keeps its switch inside its row in the agent's dialog, and its card keeps its switch. #[test] fn a_long_model_name_keeps_the_switch_in_its_row() { use crate::claude::subagents::{Agent, AgentModel}; @@ -2399,106 +2533,110 @@ fn a_long_model_name_keeps_the_switch_in_its_row() { h.settle(); h.click("settings-opencode"); h.wait("the models", |ws| !ws.store.data.settings.custom_subagents.get(Agent::OpenCode).catalog.is_empty()); - let (x, y) = h.rt.find("settings-page-Custom subagents").unwrap(); - h.rt.wheel(x, y, -1200.0); - h.settle(); - h.click("settings-opencode-choose"); h.settle(); - let inside = |h: &Harness, row: &str| { - let (r, _) = h.rt.presented(row).unwrap_or_else(|| panic!("{row} is not drawn")); - let (s, _) = h.rt.presented(&format!("{row}-switch")).unwrap(); - // [x, y, w, h] - s[0] >= r[0] && s[0] + s[2] <= r[0] + r[2] + // [x, y, w, h] + let inside = |h: &Harness, outer: &str, inner: &str| { + let (o, _) = h.rt.presented(outer).unwrap_or_else(|| panic!("{outer} is not drawn")); + let (i, _) = h.rt.presented(inner).unwrap_or_else(|| panic!("{inner} is not drawn")); + i[0] >= o[0] && i[0] + i[2] <= o[0] + o[2] }; - assert!(inside(&h, "model-picker-openrouter/a-very-long-model"), "the picker's switch stays in its row"); - let (card, _) = h.rt.presented("model-picker").unwrap(); - let (row, _) = h.rt.presented("model-picker-openrouter/a-very-long-model").unwrap(); - assert!(row[0] + row[2] <= card[0] + card[2], "the row stays in the picker"); - h.click("model-picker-openrouter/a-very-long-model"); - h.click("model-picker-done"); - h.settle(); - assert!(inside(&h, "settings-opencode-model-openrouter/a-very-long-model"), "the page's switch stays in its row"); + let row = "agent-dialog-model-openrouter/a-very-long-model"; + assert!(inside(&h, row, &format!("{row}-switch")), "the dialog's switch stays in its row"); + assert!(inside(&h, "agent-dialog", row), "the row stays in the dialog"); + h.click(row); + h.click("agent-dialog-done"); + h.settle(); + assert!(inside(&h, "settings-opencode-card", "settings-opencode-switch"), "the card's switch stays in the card"); + + // In the smallest window the dialog fits, and its body scrolls above Done. + h.rt.set_viewport((720.0, 420.0), 1.0); + h.click("settings-opencode-open"); + h.settle(); + let (dialog, _) = h.rt.presented("agent-dialog").unwrap(); + let (done, _) = h.rt.presented("agent-dialog-done").unwrap(); + assert!(dialog[1] >= 0.0 && dialog[1] + dialog[3] <= 420.0, "the dialog fits the window: {dialog:?}"); + assert!(done[1] + done[3] <= dialog[1] + dialog[3], "Done stays in the dialog: {done:?}"); } -/// Settings → Custom subagents: turning an agent on shows a Choose models button whose picker lists the models the -/// agent offers, with a search; Save keeps the ones switched on, and a new session hands the mod one agent type for -/// each. +/// Settings → Custom subagents: each agent is a card with a switch. Switching one on with no model opens its dialog, +/// which lists the models the agent offers, with a search, and holds Allow edits; the card sums up what Claude gets. +/// Save keeps the models switched on, and a new session hands the mod one agent type for each. #[test] fn custom_subagents_reach_new_sessions() { use crate::claude::subagents::{Agent, AgentModel}; fn model(id: &str, name: &str) -> AgentModel { AgentModel { id: id.into(), name: name.into() } } + let drawn_text = |h: &Harness| -> Vec { h.rt.elements().into_iter().filter_map(|e| e.text).collect() }; let mut h = Harness::new(|_| vec![]); h.step(|ws| { ws.model_lookups.list = |agent, _| { - Ok(match agent { - Agent::Codex => vec![model("gpt-6.1-sol", "6.1 Sol"), model("gpt-5.6-luna", "5.6 Luna")], - Agent::OpenCode => vec![model("openai/gpt-6.1-sol", "openai/GPT-6.1 Sol"), model("opencode/beam-free", "opencode/Beam Free"), model("github-copilot/grok-4.7", "github-copilot/Grok 4.7")], - }) + let catalogs = [ + (Agent::Codex, vec![model("gpt-6.1-sol", "6.1 Sol"), model("gpt-5.6-luna", "5.6 Luna")]), + (Agent::OpenCode, vec![model("openai/gpt-6.1-sol", "openai/GPT-6.1 Sol"), model("opencode/beam-free", "opencode/Beam Free"), model("github-copilot/grok-4.7", "github-copilot/Grok 4.7")]), + ]; + Ok(catalogs.into_iter().find(|(a, _)| *a == agent).map(|(_, models)| models).unwrap_or_default()) }; ws.act(Act::OpenSettings); ws.set_settings_page(SettingsPage::CustomSubagents); }); h.settle(); - assert!(!h.drawn("settings-codex-choose"), "the models wait for the Codex switch"); + for agent in Agent::ALL { + assert!(h.drawn(&format!("settings-{}-card", agent.key())), "every agent has a card"); + } + assert!(!h.drawn("agent-dialog"), "no dialog until asked"); h.click("settings-codex"); - h.wait("the models codex-acp offers", |ws| ws.store.data.settings.custom_subagents.codex.catalog.len() == 2); - h.settle(); - assert!(!h.drawn("settings-codex-model-gpt-6.1-sol"), "the page lists only the models switched on"); - h.click("settings-codex-choose"); + h.wait("the models codex-acp offers", |ws| ws.store.data.settings.custom_subagents.get(Agent::Codex).catalog.len() == 2); h.settle(); - h.click("model-picker-gpt-6.1-sol"); + assert!(h.drawn("agent-dialog"), "switched on with no model, the dialog opens on the models"); + h.click("agent-dialog-model-gpt-6.1-sol"); + h.click("agent-dialog-codex-edits"); h.press(rune::Key::Escape, |_| {}); h.settle(); - assert!(!h.drawn("model-picker"), "Escape closes the picker"); - assert!(matches!(h.ws().modal, Some(Modal::Settings { .. })), "and only the picker"); - assert!(h.drawn("settings-codex-model-gpt-6.1-sol"), "the model switched on shows on the page"); - h.click("settings-codex-edits"); + assert!(!h.drawn("agent-dialog"), "Escape closes the dialog"); + assert!(matches!(h.ws().modal, Some(Modal::Settings { .. })), "and only the dialog"); + let text = drawn_text(&h); + assert!(text.iter().any(|t| t == "1 subagent · edits allowed") && text.iter().any(|t| t == "6.1 Sol"), "the card sums up what Claude gets: {text:?}"); - // OpenCode's picker narrows to what the search matches, by every word typed, in the name or the id. + // OpenCode's dialog narrows to what the search matches, by every word typed, in the name or the id. h.click("settings-opencode"); - h.wait("the models opencode offers", |ws| ws.store.data.settings.custom_subagents.opencode.catalog.len() == 3); - let (x, y) = h.rt.find("settings-page-Custom subagents").unwrap(); - h.rt.wheel(x, y, -1200.0); - h.settle(); - h.click("settings-opencode-choose"); + h.wait("the models opencode offers", |ws| ws.store.data.settings.custom_subagents.get(Agent::OpenCode).catalog.len() == 3); h.settle(); h.type_text("GPT sol"); h.settle(); - assert!(h.drawn("model-picker-openai/gpt-6.1-sol")); - assert!(!h.drawn("model-picker-opencode/beam-free"), "a model the search doesn't match is hidden"); - h.click("model-picker-openai/gpt-6.1-sol"); + assert!(h.drawn("agent-dialog-model-openai/gpt-6.1-sol")); + assert!(!h.drawn("agent-dialog-model-opencode/beam-free"), "a model the search doesn't match is hidden"); + h.click("agent-dialog-model-openai/gpt-6.1-sol"); h.press(rune::Key::Enter, |_| {}); h.settle(); - assert!(!h.drawn("model-picker"), "Enter in the search closes the picker"); + assert!(!h.drawn("agent-dialog"), "Enter in the search closes the dialog"); assert!(matches!(h.ws().modal, Some(Modal::Settings { .. })), "and leaves Settings open"); h.step(|ws| ws.submit_modal()); assert_eq!(h.ws().toast.as_ref().map(|t| t.text.as_str()), Some("Settings saved. Custom subagents apply to new and resumed sessions.")); let saved = &h.ws().store.data.settings.custom_subagents; - assert_eq!((saved.codex.on, saved.codex.models.clone(), saved.codex.edits), (true, vec!["gpt-6.1-sol".to_string()], true)); - assert_eq!((saved.opencode.on, saved.opencode.models.clone(), saved.opencode.edits), (true, vec!["openai/gpt-6.1-sol".to_string()], false)); + assert_eq!((saved.get(Agent::Codex).on, saved.get(Agent::Codex).models.clone(), saved.get(Agent::Codex).edits), (true, vec!["gpt-6.1-sol".to_string()], true)); + assert_eq!((saved.get(Agent::OpenCode).on, saved.get(Agent::OpenCode).models.clone(), saved.get(Agent::OpenCode).edits), (true, vec!["openai/gpt-6.1-sol".to_string()], false)); // Settings opens on the page it showed last, and asks again from there. h.step(|ws| { ws.model_lookups.list = |agent, _| Ok(vec![model(if agent == Agent::Codex { "gpt-7" } else { "openai/gpt-7" }, "7")]); ws.act(Act::OpenSettings); }); - h.wait("a fresh look at the models", |ws| ws.store.data.settings.custom_subagents.codex.catalog.iter().any(|m| m.id == "gpt-7")); + h.wait("a fresh look at the models", |ws| ws.store.data.settings.custom_subagents.get(Agent::Codex).catalog.iter().any(|m| m.id == "gpt-7")); h.settle(); - h.click("settings-codex-choose"); + h.click("settings-codex-open"); h.settle(); - assert!(h.drawn("model-picker-gpt-7")); - assert!(h.drawn("model-picker-gpt-6.1-sol"), "a model switched on that is no longer offered stays listed"); - let drawn: Vec = h.rt.elements().into_iter().filter_map(|e| e.text).collect(); - assert!(drawn.iter().any(|t| t == "Claudiu:codex-gpt-7"), "each model shows the type Claude Code names it: {drawn:?}"); - h.click("model-picker-gpt-6.1-sol"); - h.click("model-picker-done"); + assert!(h.drawn("agent-dialog-model-gpt-7")); + assert!(h.drawn("agent-dialog-model-gpt-6.1-sol"), "a model switched on that is no longer offered stays listed"); + let text = drawn_text(&h); + assert!(text.iter().any(|t| t == "Claudiu:codex-gpt-7"), "each model shows the type Claude Code names it: {text:?}"); + h.click("agent-dialog-model-gpt-6.1-sol"); + h.click("agent-dialog-done"); h.settle(); - assert!(!h.drawn("settings-codex-model-gpt-6.1-sol"), "switched off, it leaves the page"); + let text = drawn_text(&h); + assert!(text.iter().any(|t| t == "On, but no model is chosen, so Claude gets no subagent"), "the card warns that Codex gives Claude nothing: {text:?}"); h.press(rune::Key::Escape, |_| {}); - // A stand-in `claude` that prints its arguments and what the mod would read. let printer = h.work.join(if cfg!(windows) { "printer.cmd" } else { "printer" }); let script = if cfg!(windows) { "@echo off\r\necho %*\r\necho %CLAUDIU_SUBAGENTS%\r\nping -n 60 127.0.0.1 >nul\r\n" } else { "#!/bin/sh\necho \"$@\"\necho \"$CLAUDIU_SUBAGENTS\"\nsleep 60\n" }; @@ -2514,12 +2652,12 @@ fn custom_subagents_reach_new_sessions() { let shows = |ws: &Workspace, text: &str| ws.live_view(&id).is_some_and(|v| v.tail_text(4000).contains(text)); // The mod registers what it reads here; interactive Claude Code ignores `claude --agents`. h.wait("the agent types to reach the mod", |ws| { - shows(ws, r#"{"codex":{"edits":true,"types":[{"name":"codex-gpt-6-1-sol","model":"gpt-6.1-sol","description":"Runs the task in OpenAI Codex on gpt-6.1-sol."#) - && shows(ws, r#""opencode":{"edits":false,"types":[{"name":"opencode-openai-gpt-6-1-sol","model":"openai/gpt-6.1-sol","description":"Runs the task in OpenCode on openai/gpt-6.1-sol."#) + shows(ws, r#"{"codex":{"edits":true,"name":"Codex","types":[{"name":"codex-gpt-6-1-sol","model":"gpt-6.1-sol","description":"Runs the task in OpenAI Codex on gpt-6.1-sol."#) + && shows(ws, r#""opencode":{"edits":false,"name":"OpenCode","types":[{"name":"opencode-openai-gpt-6-1-sol","model":"openai/gpt-6.1-sol","description":"Runs the task in OpenCode on openai/gpt-6.1-sol."#) }); // A settings change reaches a running session only once it is resumed: its process keeps the types it started with. - h.step(|ws| ws.store.data.settings.custom_subagents.codex.models = vec!["gpt-7".into()]); + h.step(|ws| ws.store.data.settings.custom_subagents.get_mut(crate::claude::subagents::Agent::Codex).models = vec!["gpt-7".into()]); h.settle(); assert!(!shows(h.ws(), "codex-gpt-7"), "the running session keeps its types"); h.step(|ws| ws.restart_session(&id)); diff --git a/src/app/ingest.rs b/src/app/ingest.rs index 9c347a3..9cfd0b3 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -3,25 +3,18 @@ //! off the UI thread; applying them is a handful of small, separately testable steps. use super::*; -use crate::claude::codex_limits; +use crate::claude::subagents::Agent; +use crate::claude::limits::Pool; use crate::claude::usage::Snapshot; use crate::store::RateLimit; impl Workspace { /// Costs no tokens. The mod's files are tiny, and Codex's logs are read again only after Codex writes to them. pub(super) fn ingest_usage(&mut self) { - let codex_on = self.store.data.settings.custom_subagents.codex.on; + self.ingest_subagent_limits(); self.rt.spawn_quietly( - move || { - let codex = if codex_on { codex_limits::codex_home().and_then(|home| codex_limits::read(&home)) } else { None }; - (usage::read_snapshots(&usage::snapshot_dir()), mcp::read_attached(), codex) - }, - move |ws: &mut Workspace, (snaps, items, codex)| { - // A new Codex session has no reading until its first turn; the last one stays until then. - if codex.is_some() && ws.codex_usage != codex { - ws.codex_usage = codex; - ws.rt.dirty = true; - } + || (usage::read_snapshots(&usage::snapshot_dir()), mcp::read_attached()), + |ws: &mut Workspace, (snaps, items)| { let mut changed = snaps.iter().fold(false, |c, snap| ws.apply_snapshot(snap) | c); changed |= items.into_iter().fold(false, |c, (stem, item)| ws.apply_attachment(&stem, item) | c); if changed { @@ -32,6 +25,33 @@ impl Workspace { ); } + /// Each enabled provider refreshes on its own cadence. Failed reads keep the saved reading. + fn ingest_subagent_limits(&mut self) { + for agent in Agent::ALL { + let provider = agent.provider(); + let Some(limits) = &provider.limits else { continue }; + if !self.store.data.settings.custom_subagents.get(agent).on || self.limits_asked.get(agent).is_some_and(|at| at.elapsed() < limits.every) { + continue; + } + // Set before asking, so a slow answer isn't asked for twice. + *self.limits_asked.get_mut(agent) = Some(std::time::Instant::now()); + self.rt.spawn_quietly( + limits.read, + move |ws: &mut Workspace, read| ws.apply_subagent_limits(provider.key, read), + ); + } + } + + pub(super) fn apply_subagent_limits(&mut self, key: &str, read: Result, String>) { + if let Ok(pools) = read + && self.store.data.subagent_limits.get(key) != Some(&pools) + { + self.store.data.subagent_limits.insert(key.into(), pools); + self.store.mark_dirty(); + self.rt.dirty = true; + } + } + /// One mod report: the account's limits, and the session's own figures and settings. fn apply_snapshot(&mut self, snap: &Snapshot) -> bool { let account = snap.account.as_deref().unwrap_or(MAIN_ACCOUNT); diff --git a/src/app/input.rs b/src/app/input.rs index 5b89fa8..671d51d 100644 --- a/src/app/input.rs +++ b/src/app/input.rs @@ -198,8 +198,8 @@ impl Workspace { } if self.modal.is_some() { match ks.key.as_str() { - // Escape and Enter close only the model picker over Settings, so Settings keeps what was edited. - "escape" | "enter" if plain && self.model_picker_open() => self.close_model_picker(), + // Escape and Enter close only an agent's dialog over Settings, so Settings keeps what was edited. + "escape" | "enter" if plain && self.agent_dialog_open() => self.close_agent_dialog(), "escape" if plain => self.act(Act::Dismiss), "enter" if plain && tx.focused().is_none() => self.submit_modal(), _ if matches!(self.modal, Some(Modal::Settings { .. })) => return self.settings_key(ks), diff --git a/src/app/mod.rs b/src/app/mod.rs index ed68045..f0e14ab 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -312,9 +312,8 @@ pub enum Modal { /// The Custom subagents page of the Settings dialog, as edited so far. pub struct SubagentsForm { - pub codex: AgentForm, - pub opencode: AgentForm, - /// The agent whose models the picker over the page lists, and the search typed in it so far. + pub agents: claude::subagents::AgentMap, + /// The agent whose dialog is open over the page, and the model search typed in it so far. pub picking: Option<(Agent, TextEdit)>, } @@ -328,22 +327,16 @@ pub struct AgentForm { impl SubagentsForm { pub fn get(&self, agent: Agent) -> &AgentForm { - match agent { - Agent::Codex => &self.codex, - Agent::OpenCode => &self.opencode, - } + self.agents.get(agent) } pub fn get_mut(&mut self, agent: Agent) -> &mut AgentForm { - match agent { - Agent::Codex => &mut self.codex, - Agent::OpenCode => &mut self.opencode, - } + self.agents.get_mut(agent) } } /// A field of the open modal, by its place: the dialog's only field is 0; Settings' are shell, claude, model, skills, -/// the project being renamed and the model picker's search. +/// the project being renamed and the agent dialog's model search. pub fn modal_field(modal: &mut Option, n: usize) -> Option<&mut TextEdit> { match (modal.as_mut()?, n) { (Modal::Rename { input, .. } | Modal::NewBranch { input, .. } | Modal::NewWorktree { input, .. } | Modal::Advisor { input, .. } | Modal::GoToLine { input, .. } | Modal::FileName { input, .. }, 0) => Some(input), @@ -485,9 +478,8 @@ pub struct Workspace { pub worktrees_page: worktrees::WorktreesPage, /// Whether the Custom subagents page is asking each agent for its models. Not saved to disk. pub model_lookups: settings::ModelLookups, - /// Codex's own limits from its session logs (`claude/codex_limits.rs`); the sidebar shows them under Claude's. - /// Not saved to disk: the logs are read again on start. - pub codex_usage: Option, + /// When each provider's limits were last asked for; failed reads wait for its next refresh too. + pub limits_asked: crate::claude::subagents::AgentMap>, pub menu: Option, pub menu_serial: u64, pub toast: Option, @@ -582,7 +574,7 @@ impl Workspace { settings_page: SettingsPage::default(), worktrees_page: Default::default(), model_lookups: Default::default(), - codex_usage: None, + limits_asked: Default::default(), menu: None, menu_serial: 0, toast: None, @@ -798,7 +790,7 @@ impl Workspace { self.blur = true; let custom = &self.store.data.settings.custom_subagents; let form = |c: &claude::subagents::AgentChoice| AgentForm { on: c.on, models: c.models.clone(), edits: c.edits }; - let subagents = SubagentsForm { codex: form(&custom.codex), opencode: form(&custom.opencode), picking: None }; + let subagents = SubagentsForm { agents: claude::subagents::AgentMap::from_fn(|agent| form(custom.get(agent))), picking: None }; self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), skills_field, costly: claude::costly::scan(), hints, renaming: None, subagents }); // After the modal exists: a page that loads something reads the dialog's fields. self.set_settings_page(self.settings_page); diff --git a/src/app/modal.rs b/src/app/modal.rs index 6d75678..036f46f 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -151,11 +151,10 @@ impl Workspace { } } // The catalogs are what the agents last offered, kept as they are; the page edits the rest. - let choice = |form: AgentForm, saved: &claude::subagents::AgentChoice| claude::subagents::AgentChoice { on: form.on, models: form.models, edits: form.edits, catalog: saved.catalog.clone() }; - let custom_subagents = claude::subagents::CustomSubagents { - codex: choice(subagents.codex, &s.custom_subagents.codex), - opencode: choice(subagents.opencode, &s.custom_subagents.opencode), - }; + let custom_subagents = claude::subagents::CustomSubagents(claude::subagents::AgentMap::from_fn(|agent| { + let form = subagents.get(agent); + claude::subagents::AgentChoice { on: form.on, models: form.models.clone(), edits: form.edits, catalog: s.custom_subagents.get(agent).catalog.clone() } + })); let tools_changed = s.trimmed_tools != trimmed || s.limits != limits || s.claudiu_tools_off != claudiu_off; let subagents_changed = s.custom_subagents != custom_subagents; s.trimmed_tools = trimmed; diff --git a/src/app/settings.rs b/src/app/settings.rs index 87c0b35..9d6afc2 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -57,31 +57,24 @@ pub struct Lookup { /// The Custom subagents page's lookups of each agent's models. pub struct ModelLookups { - codex: Lookup, - opencode: Lookup, + agents: claude::subagents::AgentMap, /// How the page asks; tests answer without a real agent. pub list: fn(Agent, &std::path::Path) -> Result, String>, } impl Default for ModelLookups { fn default() -> Self { - Self { codex: Lookup::default(), opencode: Lookup::default(), list: claude::acp::models } + Self { agents: Default::default(), list: claude::acp::models } } } impl ModelLookups { pub fn get(&self, agent: Agent) -> &Lookup { - match agent { - Agent::Codex => &self.codex, - Agent::OpenCode => &self.opencode, - } + self.agents.get(agent) } fn get_mut(&mut self, agent: Agent) -> &mut Lookup { - match agent { - Agent::Codex => &mut self.codex, - Agent::OpenCode => &mut self.opencode, - } + self.agents.get_mut(agent) } } @@ -119,30 +112,30 @@ impl Workspace { } } - /// Opens the model picker over the Custom subagents page, with the keyboard in its search field. - pub(crate) fn open_model_picker(&mut self, agent: Agent) { + /// Opens an agent's dialog over the Custom subagents page, with the keyboard in its model search. + pub(crate) fn open_agent_dialog(&mut self, agent: Agent) { if let Some(Modal::Settings { subagents, .. }) = self.modal.as_mut() { subagents.picking = Some((agent, super::modal::field("", true))); } } - /// Closes the model picker, keeping what it switched; Settings' Save keeps it for good. - pub(crate) fn close_model_picker(&mut self) { + /// Closes the agent's dialog, keeping what it switched; Settings' Save keeps it for good. + pub(crate) fn close_agent_dialog(&mut self) { if let Some(Modal::Settings { subagents, .. }) = self.modal.as_mut() { subagents.picking = None; } self.blur = true; } - pub(crate) fn model_picker_open(&self) -> bool { + pub(crate) fn agent_dialog_open(&self) -> bool { matches!(&self.modal, Some(Modal::Settings { subagents: SubagentsForm { picking: Some(_), .. }, .. })) } /// Keys for the open Settings dialog that no text field took. Up and Down change the page and Enter saves while no /// field has the keyboard (the category list has it); Tab and Shift+Tab cycle the list and the page's text fields. pub(crate) fn settings_key(&mut self, ks: &Keystroke) -> bool { - // The picker over the page has only its search field, and no list of pages for Up and Down to move. - if self.model_picker_open() { + // The dialog over the page has only its search field, and no list of pages for Up and Down to move. + if self.agent_dialog_open() { return false; } let fields: &[usize] = match self.settings_page { diff --git a/src/claude/acp.rs b/src/claude/acp.rs index 286b321..92529c4 100644 --- a/src/claude/acp.rs +++ b/src/claude/acp.rs @@ -1,4 +1,4 @@ -//! Runs one task in Codex or OpenCode for a custom subagent (`claude/subagents.rs`), through the Agent Client +//! Runs one task in a custom subagent's provider (`claude/subagents.rs`), through the Agent Client //! Protocol: `claudiu --acp`. The Custom subagents settings page also asks the agent for its models here (`models`). //! //! The mod starts this once per subagent turn and writes the task to stdin as JSON (`Request`). A mod can write a @@ -25,8 +25,6 @@ use crate::claude::subagents::{Agent, AgentModel}; use crate::platform::{find_executable, reload_path}; pub const FLAG: &str = "--acp"; -/// Pinned so an upstream change reaches users only with a Claudiu release. -const CODEX_ACP: &str = "@agentclientprotocol/codex-acp@2.6.0"; /// ACP's error code for "authentication required". const AUTH_REQUIRED: i64 = -32000; /// Lines of the agent's stderr kept for a failure's reason. @@ -46,8 +44,7 @@ pub struct Request { pub agent: Agent, /// The agent's model; none for the agent's own default. pub model: Option, - /// The effort Claude's Agent call asked for; none for the agent's own default. OpenCode doesn't get it, since - /// its effort is an option of each provider's models rather than one setting. + /// The effort Claude's Agent call asked for; none for the agent's own default. The provider decides how to apply it. #[serde(default)] pub effort: Option, /// Whether the agent may edit files and run commands, or only read. @@ -85,8 +82,10 @@ pub enum Event { } pub fn run() -> i32 { - if std::env::args().nth(2).as_deref() == Some("--cleanup") { - return cleanup_inbox(); + match std::env::args().nth(2).as_deref() { + Some("--cleanup") => return cleanup_inbox(), + Some(super::antigravity_read_only::HOOK_FLAG) => return super::antigravity_read_only::run_hook(), + _ => {} } let mut out = std::io::stdout().lock(); let mut emit = |event: Event| { @@ -170,23 +169,91 @@ impl Drop for Inbox { } fn run_task(request: &Request, emit: &mut impl FnMut(Event)) -> Result { - let env = match request.agent { - Agent::Codex => { - let mut env = vec![("INITIAL_AGENT_MODE", (if request.edits { "workspace-write" } else { "read-only" }).to_string())]; - if let Some(config) = codex_config(request.model.as_deref(), request.effort.as_deref()) { - env.push(("CODEX_CONFIG", config.to_string())); - } - env - } - Agent::OpenCode => vec![("OPENCODE_CONFIG_CONTENT", opencode_config(request.model.as_deref(), request.edits).to_string())], - }; - let connection = Connection::start(request.agent, &request.cwd, &env)?; + let provider = request.agent.provider(); + let args = (provider.task_args)(request)?; + let env = (provider.environment)(request); + let connection = Connection::start(request.agent, &request.cwd, &args, &env)?; let id = Uuid::new_v4(); let inbox = request.live_messages.then(|| Inbox { id, path: inbox_path(id), seen: 0 }); let result = converse(connection.from_agent, connection.to_agent, request, inbox, emit); connection.process.finish(result) } +pub(super) fn codex_env(request: &Request) -> Vec<(&'static str, String)> { + let mut env = vec![("INITIAL_AGENT_MODE", (if request.edits { "workspace-write" } else { "read-only" }).to_string())]; + if let Some(config) = codex_config(request.model.as_deref(), request.effort.as_deref()) { + env.push(("CODEX_CONFIG", config.to_string())); + } + env +} + +pub(super) fn opencode_env(request: &Request) -> Vec<(&'static str, String)> { + vec![("OPENCODE_CONFIG_CONTENT", opencode_config(request.model.as_deref(), request.edits).to_string())] +} + +pub(super) fn no_args(_: &Request) -> Result, String> { + Ok(vec![]) +} + +/// Read-only Antigravity runs from a Gemini folder whose hook refuses every tool but reading +/// (`claude/antigravity_read_only.rs`). +pub(super) fn antigravity_args(request: &Request) -> Result, String> { + if request.edits { + return Ok(vec![]); + } + let claudiu = std::env::current_exe().map_err(|e| format!("Claudiu couldn't find itself to keep Antigravity read-only ({e})"))?; + let gemini = super::antigravity_read_only::prepare(&crate::datadir::data_dir(), &claudiu).map_err(|e| format!("Claudiu couldn't set up Antigravity's read-only folder ({e})"))?; + Ok(vec!["--gemini-dir".into(), gemini.to_string_lossy().into_owned()]) +} + +pub(super) fn no_env(_: &Request) -> Vec<(&'static str, String)> { + vec![] +} + +pub(super) fn no_options(_: &Request) -> Vec<(&'static str, String)> { + vec![] +} + +pub(super) fn antigravity_options(request: &Request) -> Vec<(&'static str, String)> { + let mut options = vec![]; + if let Some(model) = &request.model { + options.push(("model", model.clone())); + } + if let Some(effort) = effort_level(request.effort.as_deref()) { + options.push(("thought_level", effort.into())); + } + // Read-only keeps the default mode, where agy asks before each edit or command and Claudiu refuses. + if request.edits { + options.push(("mode", "accept-edits".into())); + } + options +} + +/// Thinking levels from least to most, as ACP agents name them. +const THOUGHT_LEVELS: [&str; 4] = ["low", "medium", "high", "xhigh"]; + +/// The value to set `config` to, given the options the agent `offered`. A thinking level the model doesn't offer +/// becomes the highest one it does below it, or none, which leaves the model's own default: Claude's effort is a hint, +/// not worth failing the task for. Anything else is sent as asked, so an unknown model fails with the agent's reason. +fn offered_value(offered: &Value, config: &str, wanted: &str) -> Option { + let choices: Option> = offered + .as_array() + .and_then(|options| options.iter().find(|o| o["id"] == config)) + .and_then(|option| option["options"].as_array()) + .map(|choices| choices.iter().filter_map(|c| c["value"].as_str()).collect()); + let Some(choices) = choices.filter(|_| config == "thought_level") else { return Some(wanted.into()) }; + let rank = THOUGHT_LEVELS.iter().position(|l| *l == wanted)?; + THOUGHT_LEVELS[..=rank].iter().rev().find(|l| choices.contains(l)).map(|l| l.to_string()) +} + +fn effort_level(effort: Option<&str>) -> Option<&str> { + match effort { + Some("max") => Some("xhigh"), + Some(level @ ("low" | "medium" | "high" | "xhigh")) => Some(level), + _ => None, + } +} + /// The config Codex gets on top of the user's own: the model and the reasoning effort, where given. Codex has no `max`, /// so `max` becomes its highest level, `xhigh`; a level Codex doesn't know is left to the user's config. fn codex_config(model: Option<&str>, effort: Option<&str>) -> Option { @@ -194,11 +261,7 @@ fn codex_config(model: Option<&str>, effort: Option<&str>) -> Option { if let Some(model) = model { config.insert("model".into(), json!(model)); } - let effort = match effort { - Some("max") => Some("xhigh"), - Some(level @ ("low" | "medium" | "high" | "xhigh")) => Some(level), - _ => None, - }; + let effort = effort_level(effort); if let Some(effort) = effort { config.insert("model_reasoning_effort".into(), json!(effort)); } @@ -229,7 +292,7 @@ fn opencode_config(model: Option<&str>, edits: bool) -> Value { /// The models `agent` offers this account, as the model picker of a new session lists them. Gives up after /// `MODELS_TIMEOUT`, so a stalled download or an agent that never answers can't leave the page loading for good. pub fn models(agent: Agent, cwd: &Path) -> Result, String> { - let connection = Connection::start(agent, cwd, &[])?; + let connection = Connection::start(agent, cwd, &[], &[])?; let (Connection { from_agent, to_agent, process }, folder) = (connection, cwd.to_path_buf()); let (tx, rx) = std::sync::mpsc::channel(); // Killing the agent on a timeout closes its pipes, which ends this thread too. @@ -242,10 +305,7 @@ pub fn models(agent: Agent, cwd: &Path) -> Result, String> { /// The program Claudiu starts for `agent`, as failures name it. fn server(agent: Agent) -> &'static str { - match agent { - Agent::Codex => "codex-acp", - Agent::OpenCode => "opencode", - } + agent.provider().server } fn exited(agent: Agent) -> String { @@ -275,15 +335,22 @@ fn locate_reloading(program: &str) -> Option { }) } +/// Where `agent`'s ACP server is: on the PATH, or where its Windows installer puts it, which a desktop launch's PATH +/// may not include yet. +pub fn locate(agent: Agent) -> Option { + let provider = agent.provider(); + locate_reloading(provider.program).or_else(|| { + let installed = provider.windows_fallback.filter(|_| cfg!(windows))?; + Some(PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join(installed)).filter(|path| path.is_file()) + }) +} + impl Connection { - fn start(agent: Agent, cwd: &Path, env: &[(&str, String)]) -> Result { - let (program, args, missing): (&str, &[&str], &str) = match agent { - Agent::Codex => ("npx", &["-y", CODEX_ACP], "npx was not found on PATH. Codex subagents need Node.js."), - Agent::OpenCode => ("opencode", &["acp"], "opencode was not found on PATH. OpenCode subagents need OpenCode installed."), - }; - let program = locate_reloading(program).ok_or_else(|| missing.to_string())?; + fn start(agent: Agent, cwd: &Path, task_args: &[String], env: &[(&str, String)]) -> Result { + let provider = agent.provider(); + let program = locate(agent).ok_or_else(|| provider.missing.to_string())?; let mut command = Command::new(program); - command.args(args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + command.args(provider.args).args(task_args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); crate::platform::no_window(&mut command); crate::platform::with_login_path(&mut command); for (key, value) in env { @@ -370,7 +437,7 @@ fn list_models(agent: Agent, from_agent: impl BufRead, mut to_agent: impl Write, .flatten() .filter_map(|o| Some(AgentModel { id: o["value"].as_str()?.to_string(), name: o["name"].as_str().unwrap_or_default().to_string() })) .collect(); - if agent == Agent::OpenCode + if agent.provider().delete_model_session && let Some(id) = session["sessionId"].as_str() // The models are known already, so a failed delete only leaves an empty session behind. && send(json!({ "jsonrpc": "2.0", "id": 2, "method": "session/delete", "params": { "sessionId": id } })).is_ok() @@ -446,7 +513,7 @@ fn converse(from_agent: impl BufRead + Send + 'static, mut to_agent: impl Write, let initialized = answer(&mut to_agent, 0, &mut messages, emit)?; let supports_steering = initialized["_meta"]["steering"]["supported"] == true; let mut steer = supports_steering; - if agent == Agent::OpenCode && !supports_steering { + if !agent.provider().inbox_without_steering && !supports_steering { inbox = None; // Claude Code keeps its usual queued delivery on older OpenCode versions. } @@ -459,8 +526,20 @@ fn converse(from_agent: impl BufRead + Send + 'static, mut to_agent: impl Write, let blocks: Vec<_> = texts.into_iter().map(|text| json!({ "type": "text", "text": text })).collect(); json!({ "jsonrpc": "2.0", "id": id, "method": "session/prompt", "params": { "sessionId": session_id, "prompt": blocks } }) }; - let mut prompt_id = 2; - let mut next_id = 3; + let mut next_id = 2; + // Each answer lists the options as they stand after the change: a new model can offer other thinking levels. + let mut offered = session["configOptions"].clone(); + for (config, wanted) in (agent.provider().config_options)(request) { + let Some(value) = offered_value(&offered, config, &wanted) else { continue }; + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": next_id, "method": "session/set_config_option", "params": { "sessionId": session_id, "configId": config, "value": value } }))?; + let changed = answer(&mut to_agent, next_id, &mut messages, emit).map_err(|reason| format!("{name} could not set {config}: {reason}"))?; + if changed["configOptions"].is_array() { + offered = changed["configOptions"].clone(); + } + next_id += 1; + } + let mut prompt_id = next_id; + next_id += 1; send(&mut to_agent, prompt(prompt_id, vec![request.prompt.clone()]))?; if let Some(inbox) = &inbox { emit(Event::Inbox { id: inbox.id.to_string(), path: inbox.path.clone() }); @@ -501,7 +580,7 @@ fn converse(from_agent: impl BufRead + Send + 'static, mut to_agent: impl Write, "sessionId": session_id, "prompt": [{ "type": "text", "text": text }], }); - if agent == Agent::Codex { + if agent.provider().steering_prompt_required { params["_meta"] = json!({ "steering": { "idleBehavior": "promptRequired" } }); } send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": next_id, "method": "_session/steering", "params": params }))?; @@ -576,7 +655,7 @@ struct ToolProgress { /// What a tool call acts on, from its input: the command, the pattern searched for, the address, or else the file. fn tool_target(input: &Value) -> Option<&str> { - ["command", "pattern", "query", "url", "path", "filePath"].iter().find_map(|key| input[key].as_str()).filter(|t| !t.is_empty()) + ["command", "pattern", "query", "url", "path", "Path", "filePath"].iter().find_map(|key| input[key].as_str()).filter(|t| !t.is_empty()) } impl Messages { @@ -629,7 +708,7 @@ impl Messages { let title = update["title"].as_str().filter(|title| !title.is_empty()).unwrap_or("a tool"); tool.title = title.into(); // OpenCode may start with only the tool name and supply its target in the first update. - tool.waiting_for_target = agent == Agent::OpenCode && !title.contains(' ') && target.is_none() && id.is_some(); + tool.waiting_for_target = agent.provider().deferred_tool_target && !title.contains(' ') && target.is_none() && id.is_some(); if !tool.waiting_for_target { if let Some(target) = target.filter(|_| !title.contains(' ')) { tool.title = format!("{title} {target}"); @@ -717,10 +796,7 @@ fn permission(options: &Value, edits: bool) -> Value { fn error_reason(agent: Agent, error: &Value) -> String { if error["code"].as_i64() == Some(AUTH_REQUIRED) { - return match agent { - Agent::Codex => "Codex isn't signed in. Run `codex login`, then try again.".into(), - Agent::OpenCode => "OpenCode isn't signed in. Run `opencode auth login`, then try again.".into(), - }; + return agent.provider().sign_in.into(); } let server = server(agent); match error["message"].as_str() { @@ -760,14 +836,100 @@ mod tests { /// Runs the conversation against what a fake agent says, in order. Returns the result, what was sent to the agent, /// and the events. fn talk_to(agent: Agent, agent_says: &[Value], edits: bool) -> (Result, Vec, Vec) { + talk_request(&request(agent, edits), agent_says) + } + + fn talk_request(request: &Request, agent_says: &[Value]) -> (Result, Vec, Vec) { let script: String = agent_says.iter().map(|m| format!("{m}\n")).collect(); let mut sent = Vec::new(); let mut events = vec![]; - let result = converse(std::io::Cursor::new(script), &mut sent, &request(agent, edits), None, &mut |e| events.push(e)); + let result = converse(std::io::Cursor::new(script), &mut sent, request, None, &mut |e| events.push(e)); let sent = String::from_utf8(sent).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); (result, sent, events) } + #[test] + fn antigravity_configures_each_option_before_prompting() { + for effort in ["low", "medium", "high", "xhigh", "max", "unknown"] { + for edits in [false, true] { + let mut request = request(Agent::Antigravity, edits); + request.model = Some("gemini-4-neon".into()); + request.effort = Some(effort.into()); + let mut expected = vec![("model", "gemini-4-neon")]; + if effort != "unknown" { expected.push(("thought_level", if effort == "max" { "xhigh" } else { effort })); } + if edits { expected.push(("mode", "accept-edits")); } + let mut says = opening(); + for i in 0..expected.len() { says.push(reply(2 + i as i64, json!({}))); } + says.push(chunk("m", "Done")); + says.push(reply(2 + expected.len() as i64, json!({ "stopReason": "end_turn" }))); + let (result, sent, _) = talk_request(&request, &says); + assert_eq!(result, Ok("Done".into())); + for (i, (config, value)) in expected.iter().enumerate() { + assert_eq!(sent[i + 2], json!({ "jsonrpc": "2.0", "id": i + 2, "method": "session/set_config_option", "params": { "sessionId": "s1", "configId": config, "value": value } })); + } + assert_eq!(sent.last().unwrap()["method"], "session/prompt"); + assert_eq!(sent.len(), expected.len() + 3); + } + } + } + + /// What agy 1.5.12 does: Gemini 3.8 Flash has no `xhigh`, and the answer to the model change says so. + #[test] + fn a_thinking_level_the_model_lacks_becomes_the_highest_it_offers() { + let levels = |values: &[&str]| json!([{ "id": "thought_level", "category": "thought_level", "options": values.iter().map(|v| json!({ "value": v })).collect::>() }]); + let mut request = request(Agent::Antigravity, false); + request.model = Some("gemini-3.8-flash".into()); + request.effort = Some("max".into()); + let says = [ + reply(0, json!({ "protocolVersion": 1 })), + reply(1, json!({ "sessionId": "s1", "configOptions": levels(&["low", "medium", "high", "xhigh"]) })), + reply(2, json!({ "configOptions": levels(&["low", "medium", "high"]) })), + reply(3, json!({})), + chunk("m", "Done"), + reply(4, json!({ "stopReason": "end_turn" })), + ]; + let (result, sent, _) = talk_request(&request, &says); + assert_eq!(result, Ok("Done".into())); + assert_eq!((&sent[3]["params"]["configId"], &sent[3]["params"]["value"]), (&json!("thought_level"), &json!("high"))); + assert_eq!(offered_value(&levels(&["medium", "high"]), "thought_level", "low"), None, "no level at or below: the model's default"); + assert_eq!(offered_value(&levels(&["low"]), "model", "x"), Some("x".into()), "other options go as asked"); + } + + #[test] + fn antigravity_config_failure_never_prompts() { + let mut says = opening(); + says.push(json!({ "id": 2, "error": { "code": -32602, "message": "unknown model" } })); + let (result, sent, _) = talk_to(Agent::Antigravity, &says, false); + assert_eq!(result, Err("Antigravity could not set model: agy: unknown model".into())); + assert!(sent.iter().all(|m| m["method"] != "session/prompt")); + } + + #[test] + fn antigravity_denies_string_permission_ids_and_keeps_queued_delivery() { + let dir = tempfile::tempdir().unwrap(); + let mut request = request(Agent::Antigravity, false); + request.model = None; + let mut says = opening(); + says.push(json!({ "jsonrpc": "2.0", "id": "1", "method": "session/request_permission", "params": { "options": [{ "optionId": "allow", "kind": "allow_once" }, { "optionId": "deny", "kind": "reject_once" }] } })); + says.push(chunk("m", "Read only")); + says.push(reply(2, json!({ "stopReason": "end_turn" }))); + let script: String = says.iter().map(|m| format!("{m}\n")).collect(); + let mut sent = vec![]; + let mut events = vec![]; + let result = converse(std::io::Cursor::new(script), &mut sent, &request, Some(test_inbox(dir.path())), &mut |e| events.push(e)); + assert_eq!(result, Ok("Read only".into())); + let sent: Vec = String::from_utf8(sent).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(sent[3]["id"], "1"); + assert_eq!(sent[3]["result"]["outcome"]["optionId"], "deny"); + assert!(!events.iter().any(|e| matches!(e, Event::Inbox { .. }))); + } + + #[test] + fn antigravity_file_targets_and_sign_in_hint() { + assert_eq!(tool_target(&json!({ "Path": "Cargo.toml" })), Some("Cargo.toml")); + assert_eq!(error_reason(Agent::Antigravity, &json!({ "code": AUTH_REQUIRED })), "Antigravity isn't signed in. Run `agy` and sign in, then try again."); + } + fn talk(agent_says: &[Value], edits: bool) -> (Result, Vec, Vec) { talk_to(Agent::Codex, agent_says, edits) } @@ -1243,6 +1405,22 @@ mod tests { assert_eq!(sent.iter().map(|m| m["method"].as_str().unwrap()).collect::>(), ["initialize", "session/new"], "no prompt, and Codex's session is left alone"); } + #[test] + fn antigravity_lists_its_model_config_option_without_prompting() { + let says = [reply(0, json!({ "protocolVersion": 1, "agentInfo": { "name": "Antigravity ACP Server" } })), reply(1, json!({ + "sessionId": "s1", + "configOptions": [ + { "id": "thought_level", "category": "thought_level", "options": [{ "value": "high", "name": "High" }] }, + { "id": "model", "category": "model", "options": [{ "value": "gemini-4-neon", "name": "Gemini 4 Neon" }] }, + { "id": "mode", "category": "mode", "options": [{ "value": "default", "name": "Default" }] } + ], + "_meta": { "antigravity": { "tier": { "name": "Google AI Pro" } } } + }))]; + let (models, sent) = list(Agent::Antigravity, &says); + assert_eq!(models.unwrap(), vec![AgentModel { id: "gemini-4-neon".into(), name: "Gemini 4 Neon".into() }]); + assert_eq!(sent.iter().map(|m| m["method"].as_str().unwrap()).collect::>(), ["initialize", "session/new"]); + } + #[test] fn opencode_deletes_the_session_it_read_the_models_from() { let says = [reply(0, json!({ "protocolVersion": 1 })), picker_session(), reply(2, json!({}))]; diff --git a/src/claude/antigravity_limits.rs b/src/claude/antigravity_limits.rs new file mode 100644 index 0000000..c6343e7 --- /dev/null +++ b/src/claude/antigravity_limits.rs @@ -0,0 +1,204 @@ +//! Antigravity's 5-hour and weekly limits, from the CLI's own `agy -p /usage --output-format json`. Since agy 1.1.11 +//! the CLI answers `/usage` itself, without a model turn, so a reading costs no tokens; it does ask Google's servers, +//! so the sidebar asks only every few minutes (`REFRESH_EVERY`). The JSON is agy's own and undocumented, so anything +//! that doesn't parse leaves the last reading in the sidebar. +//! +//! Antigravity splits its models into groups ("Gemini Models", "Claude and GPT models"), each with its own limits, so a +//! reading is one `Pool` per group. + +use std::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use crate::store::{AccountUsage, RateLimit}; +use super::limits::Pool; + +/// How often the sidebar asks again while Antigravity subagents are on. +pub const REFRESH_EVERY: Duration = Duration::from_secs(300); +/// `/usage` answers in well under a second; a CLI that hangs (an update, a sign-in prompt) is stopped. +const TIMEOUT: Duration = Duration::from_secs(30); +/// More than any reading needs, so a runaway child can't fill memory. +const OUTPUT_MAX: u64 = 1 << 20; + +/// The first agy that answers `/usage` itself. An older one sends it to the model, which spends a turn every ask. +const FIRST_WITH_USAGE: (u32, u32, u32) = (1, 1, 11); + +/// Runs `agy` for its limits, once its version shows it answers `/usage` itself. An error says why there is no +/// reading. +pub fn read(agy: &Path, cwd: &Path) -> Result, String> { + let version = output(agy, &["--version"], cwd)?; + if !version_has_usage(&version) { + return Err(format!("agy {} is older than {}.{}.{}, which first answers /usage without the model", version.trim(), FIRST_WITH_USAGE.0, FIRST_WITH_USAGE.1, FIRST_WITH_USAGE.2)); + } + let out = output(agy, &["-p", "/usage", "--output-format", "json"], cwd)?; + parse(&out, time::OffsetDateTime::now_utc().unix_timestamp()).ok_or_else(|| "agy's /usage gave no limits".into()) +} + +/// Whether `agy --version` (`1.5.12`) names a version that answers `/usage` itself. Anything unreadable doesn't. +fn version_has_usage(version: &str) -> bool { + let mut parts = version.trim().trim_start_matches('v').split('.').map(|p| p.parse::()); + match (parts.next(), parts.next(), parts.next()) { + (Some(Ok(major)), Some(Ok(minor)), Some(Ok(patch))) => (major, minor, patch) >= FIRST_WITH_USAGE, + _ => false, + } +} + +/// What `agy args` prints, given `TIMEOUT` to finish. +fn output(agy: &Path, args: &[&str], cwd: &Path) -> Result { + let mut command = Command::new(agy); + command + .args(args) + .current_dir(cwd) + // An update mid-read would leave the sidebar waiting; agy updates itself on its next interactive start. + .env("AGY_CLI_DISABLE_AUTO_UPDATE", "true") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + crate::platform::no_window(&mut command); + crate::platform::with_login_path(&mut command); + let mut child = command.spawn().map_err(|e| format!("agy could not start ({e})"))?; + let stdout = child.stdout.take().ok_or("agy could not start (no pipe)")?; + let reader = std::thread::spawn(move || { + let mut out = String::new(); + let _ = stdout.take(OUTPUT_MAX).read_to_string(&mut out); + out + }); + let started = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(_)) => break, + Ok(None) if started.elapsed() < TIMEOUT => std::thread::sleep(Duration::from_millis(100)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("agy didn't answer within {} seconds", TIMEOUT.as_secs())); + } + } + } + Ok(reader.join().unwrap_or_default()) +} + +/// The pools in agy's `/usage` JSON, each with the windows it reported, seen at `seen_at`. None when the answer isn't +/// a `/usage` reading or holds no window: an older agy that sent `/usage` to the model answers with text instead. +pub fn parse(json: &str, seen_at: i64) -> Option> { + let v: Value = serde_json::from_str(json.trim()).ok()?; + let command = v.get("command")?; + if command.get("name")?.as_str()? != "usage" { + return None; + } + let pools: Vec = command["data"]["groups"] + .as_array()? + .iter() + .filter_map(|group| { + let mut usage = AccountUsage::default(); + for bucket in group["buckets"].as_array().into_iter().flatten() { + let limit = RateLimit { + // An unknown fraction stays unknown rather than reading as empty or full. + utilization: bucket["remaining_fraction"].as_f64().filter(|f| (0.0..=1.0).contains(f)).map(|f| (1.0 - f) as f32), + resets_at: bucket["reset_time"].as_str().and_then(super::parse_rfc3339), + seen_at, + }; + match bucket["window"].as_str() { + Some("5h") => usage.five_hour = Some(limit), + Some("weekly") => usage.seven_day = Some(limit), + _ => {} + } + } + let name = group["name"].as_str()?.trim(); + (!name.is_empty() && (usage.five_hour.is_some() || usage.seven_day.is_some())).then(|| Pool { name: name.to_string(), usage }) + }) + .collect(); + (!pools.is_empty()).then_some(pools) +} + +/// What the sidebar marks a pool's row with, by the models in it. +#[derive(Debug, PartialEq)] +pub enum PoolMark { + /// `Gemini Models`. + Gemini, + /// `Claude and GPT models`. + ClaudeAndGpt, + /// A named Gemini model with limits of its own, by the first two letters of its name: `Gemini 4 Argon` → `Ar`. + GeminiNamed(String), + /// A pool Claudiu doesn't know, by its name shortened: `Some New models` → `SOME NEW`. + Other(String), +} + +pub fn mark(pool: &str) -> PoolMark { + let words: Vec<&str> = pool.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("models")).collect(); + let lower: Vec = words.iter().map(|w| w.to_lowercase()).collect(); + match lower.iter().map(String::as_str).collect::>().as_slice() { + ["gemini"] => PoolMark::Gemini, + ["claude", "and", "gpt"] => PoolMark::ClaudeAndGpt, + ["gemini", version, name] if version.parse::().is_ok() => PoolMark::GeminiNamed(symbol(name)), + _ => PoolMark::Other(words.join(" ").replace(" and ", "/").to_uppercase()), + } +} + +/// A name's first two letters, written like an element's symbol: `argon` → `Ar`. +fn symbol(name: &str) -> String { + let mut letters = name.chars(); + letters.next().map(|first| first.to_uppercase().chain(letters.take(1)).collect()).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + // What agy 1.5.12 answered, with the descriptions cut short. + const READING: &str = r#"{"conversation_id":"","status":"SUCCESS","response":"Gemini Models\tWeekly Limit Remaining\t100%\n","num_turns":0,"usage":{"input_tokens":0,"output_tokens":0},"command":{"name":"usage","data":{"description":"Within each group, models share a weekly limit and a 5-hour limit.","groups":[{"name":"Gemini Models","description":"Models within this group: Gemini 4 Neon","buckets":[{"id":"gemini-weekly","name":"Weekly Limit Remaining","window":"weekly","remaining_fraction":0.75,"reset_time":"2026-11-26T06:49:30Z"},{"id":"gemini-5h","name":"Five Hour Limit Remaining","window":"5h","remaining_fraction":0.5,"reset_time":"2026-11-19T11:49:30Z"}]},{"name":"Claude and GPT models","buckets":[{"id":"3p-weekly","window":"weekly","remaining_fraction":1,"reset_time":"2026-11-26T06:55:31Z"},{"id":"3p-5h","window":"5h","remaining_fraction":1,"reset_time":"2026-11-19T11:55:31Z"}]},{"name":"Gemini 4 Argon","buckets":[{"id":"gemini-argon-wtu-weekly","window":"weekly","remaining_fraction":1,"reset_time":"2026-11-26T06:55:31Z"}]}]}}}"#; + + #[test] + fn each_group_is_a_pool_with_its_windows_as_used_fractions() { + let pools = parse(READING, 100).unwrap(); + assert_eq!(pools.iter().map(|p| p.name.as_str()).collect::>(), ["Gemini Models", "Claude and GPT models", "Gemini 4 Argon"]); + let gemini = &pools[0].usage; + assert_eq!(gemini.five_hour, Some(RateLimit { utilization: Some(0.5), resets_at: super::super::parse_rfc3339("2026-11-19T11:49:30Z"), seen_at: 100 })); + assert_eq!(gemini.seven_day.as_ref().unwrap().utilization, Some(0.25)); + assert_eq!(pools[1].usage.five_hour.as_ref().unwrap().utilization, Some(0.0)); + assert_eq!((pools[2].usage.five_hour.is_none(), pools[2].usage.seven_day.is_some()), (true, true), "a pool with only a weekly limit"); + } + + #[test] + fn a_missing_or_odd_fraction_stays_unknown() { + let missing = READING.replace(r#""remaining_fraction":0.5,"#, "").replace(r#""remaining_fraction":0.75"#, r#""remaining_fraction":7"#); + let gemini = &parse(&missing, 0).unwrap()[0].usage; + assert_eq!(gemini.five_hour.as_ref().unwrap().utilization, None); + assert_eq!(gemini.seven_day.as_ref().unwrap().utilization, None); + } + + #[test] + fn an_answer_that_is_not_a_usage_reading_gives_none() { + // An agy older than 1.1.11 sends `/usage` to the model, which answers in prose. + assert_eq!(parse(r#"{"status":"SUCCESS","response":"I don't have access to your quota.","num_turns":1}"#, 0), None); + assert_eq!(parse(&READING.replace(r#""name":"usage""#, r#""name":"quota""#), 0), None); + assert_eq!(parse("not json", 0), None); + assert_eq!(parse(r#"{"command":{"name":"usage","data":{"groups":[{"name":"X","buckets":[{"window":"daily"}]}]}}}"#, 0), None, "no window Claudiu shows"); + } + + #[test] + fn only_an_agy_that_answers_usage_itself_is_asked() { + assert!(version_has_usage("1.5.12 +")); + assert!(version_has_usage("1.1.11")); + assert!(version_has_usage("2.0.0")); + assert!(!version_has_usage("1.1.10")); + assert!(!version_has_usage("1.0.99")); + assert!(!version_has_usage("agy version unknown")); + assert!(!version_has_usage("")); + } + + #[test] + fn each_pool_gets_the_mark_of_its_models() { + assert_eq!(mark("Gemini Models"), PoolMark::Gemini); + assert_eq!(mark("Claude and GPT models"), PoolMark::ClaudeAndGpt); + assert_eq!(mark("Gemini 4 Argon"), PoolMark::GeminiNamed("Ar".into())); + assert_eq!(mark("Gemini 5 XENON"), PoolMark::GeminiNamed("Xe".into())); + assert_eq!(mark("Gemini custom pool"), PoolMark::Other("GEMINI CUSTOM POOL".into())); + assert_eq!(mark("Other 4 Argon"), PoolMark::Other("OTHER 4 ARGON".into())); + assert_eq!(mark("Mistral and Llama models"), PoolMark::Other("MISTRAL/LLAMA".into())); + } +} diff --git a/src/claude/antigravity_read_only.rs b/src/claude/antigravity_read_only.rs new file mode 100644 index 0000000..65fd0b9 --- /dev/null +++ b/src/claude/antigravity_read_only.rs @@ -0,0 +1,179 @@ +//! Read-only Antigravity subagents. Antigravity has no read-only mode: in its default mode it writes files in the +//! workspace without asking, and `agy acp` takes no per-session settings. What it does honour is a PreToolUse hook +//! that answers `deny`, read from the `config/hooks.json` of its Gemini folder. So a read-only run starts agy with +//! `--gemini-dir` pointing at a folder in Claudiu's data, whose hook runs `claudiu --acp --read-only-hook`, which lets +//! through only the tools that read or search. Sign-in lives in the system keyring, so the run stays signed in; the +//! user's own Antigravity rules, skills and MCP servers, kept in their own Gemini folder, don't load. +//! +//! agy runs a hook that fails as if it had allowed the tool, so the hook script answers `deny` itself when Claudiu +//! can't be started. + +use std::io::Read; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +pub const HOOK_FLAG: &str = "--read-only-hook"; + +/// The tools that only read or search, by the names agy gives them. Anything else, the shell and every edit among +/// them, is denied, so a tool agy adds later is refused until it is listed here. +const READ_TOOLS: &[&str] = &[ + "read_file", + "view_file", + "view_file_outline", + "view_code_item", + "view_content_chunk", + "list_dir", + "list_directory", + "grep_search", + "find_by_name", + "code_search", + "codebase_search", + "find_all_references", + "search_web", + "web_search", + "read_url", + "read_url_content", +]; + +/// ASCII only: the script's fallback echoes it through cmd, whose code page could garble anything else into JSON agy +/// can't read, and agy runs a tool whose hook gave no answer. +const DENIED: &str = "Claudiu runs this Antigravity subagent read-only: it can read and search, but not change files or run commands. Turn on Allow edits in Settings > Custom subagents to let it."; + +/// The Gemini folder read-only runs use, made ready with the hook, which starts the Claudiu running now. +pub fn prepare(data_dir: &Path, claudiu: &Path) -> std::io::Result { + let gemini = data_dir.join("antigravity-read-only"); + let config = gemini.join("config"); + std::fs::create_dir_all(&config)?; + let script = config.join(if cfg!(windows) { "read-only-hook.cmd" } else { "read-only-hook.sh" }); + publish(&script, &hook_script(claudiu))?; + publish(&config.join("hooks.json"), &hooks_json(&script).to_string())?; + Ok(gemini) +} + +/// Writes `body` to `path` unless it is there already. Another read-only subagent may be running the hook at this +/// moment, and a hook file it reads half-written gives agy no answer, which agy takes as allowed. So the file is +/// written beside it and moved over it whole. +fn publish(path: &Path, body: &str) -> std::io::Result<()> { + if std::fs::read_to_string(path).is_ok_and(|old| old == body) { + return Ok(()); + } + let staged = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4())); + std::fs::write(&staged, body)?; + #[cfg(unix)] + std::fs::set_permissions(&staged, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + std::fs::rename(&staged, path).inspect_err(|_| { + let _ = std::fs::remove_file(&staged); + }) +} + +/// agy starts the hook from its own working folder, not the hook's, so the script is named by its full path, quoted +/// for a path with spaces. +fn hooks_json(script: &Path) -> Value { + let command = format!("\"{}\"", script.display()); + json!({ "claudiu-read-only": { "PreToolUse": [{ "matcher": "*", "hooks": [{ "command": command, "timeout": 10 }] }] } }) +} + +/// Runs Claudiu's check, and denies when Claudiu can't be started. +fn hook_script(claudiu: &Path) -> String { + let denied = json!({ "decision": "deny", "reason": DENIED }).to_string(); + if cfg!(windows) { + // cmd's echo prints quotes as they are; `^` keeps its own meaning off the characters it treats specially. + let echoed: String = denied.chars().flat_map(|c| if matches!(c, '&' | '|' | '<' | '>' | '^' | '(' | ')') { vec!['^', c] } else { vec![c] }).collect(); + format!("@echo off\r\n\"{}\" --acp {HOOK_FLAG} || echo {echoed}\r\n", claudiu.display()) + } else { + let quoted = |s: &str| format!("'{}'", s.replace('\'', r"'\''")); + format!("#!/bin/sh\n{} --acp {HOOK_FLAG} || echo {}\n", quoted(&claudiu.to_string_lossy()), quoted(&denied)) + } +} + +/// What the hook answers for a PreToolUse payload: allow a reading tool, deny the rest and anything unreadable. +pub fn decision(payload: &str) -> Value { + let tool = serde_json::from_str::(payload).ok().and_then(|p| p["toolCall"]["name"].as_str().map(str::to_owned)); + match tool { + Some(name) if READ_TOOLS.contains(&name.as_str()) => json!({ "decision": "allow" }), + _ => json!({ "decision": "deny", "reason": DENIED }), + } +} + +/// `claudiu --acp --read-only-hook`: one PreToolUse payload on stdin, the decision on stdout. +pub fn run_hook() -> i32 { + let mut payload = String::new(); + let _ = std::io::stdin().take(1 << 20).read_to_string(&mut payload); + println!("{}", decision(&payload)); + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn payload(tool: &str) -> String { + json!({ "hookEventName": "PreToolUse", "toolCall": { "id": "c1", "name": tool, "args": {} }, "cwd": "/work" }).to_string() + } + + #[test] + fn only_reading_tools_are_allowed() { + for tool in ["read_file", "grep_search", "list_dir"] { + assert_eq!(decision(&payload(tool))["decision"], "allow", "{tool}"); + } + for tool in ["write_file", "run_command", "replace_file_content", "delete_file", "browser_subagent", "some_future_tool"] { + assert_eq!(decision(&payload(tool))["decision"], "deny", "{tool}"); + } + assert_eq!(decision("not json")["decision"], "deny"); + assert_eq!(decision(r#"{"toolCall":{}}"#)["decision"], "deny"); + } + + #[test] + fn the_folder_holds_a_hook_that_runs_claudiu_by_its_full_path() { + let data = tempfile::tempdir().unwrap(); + let claudiu = Path::new(if cfg!(windows) { r"C:\Program Files\Claudiu\claudiu.exe" } else { "/opt/it's claudiu/claudiu" }); + let gemini = prepare(data.path(), claudiu).unwrap(); + assert_eq!(gemini, data.path().join("antigravity-read-only")); + let hooks: Value = serde_json::from_str(&std::fs::read_to_string(gemini.join("config/hooks.json")).unwrap()).unwrap(); + let group = &hooks["claudiu-read-only"]["PreToolUse"][0]; + assert_eq!(group["matcher"], "*", "every tool goes through the check"); + let command = group["hooks"][0]["command"].as_str().unwrap(); + let script = command.trim_matches('"'); + assert!(Path::new(script).is_absolute() && command.starts_with('"'), "{command}"); + let body = std::fs::read_to_string(script).unwrap(); + assert!(body.contains(&format!("--acp {HOOK_FLAG} || echo ")), "the script denies when Claudiu fails: {body}"); + if cfg!(windows) { + assert!(body.contains(r#""C:\Program Files\Claudiu\claudiu.exe" --acp"#), "{body}"); + } else { + assert!(body.contains(r"'/opt/it'\''s claudiu/claudiu' --acp"), "{body}"); + } + // A second run finds the files as they should be and leaves them alone, since a running hook may read them. + let written = std::fs::metadata(script).unwrap().modified().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(prepare(data.path(), claudiu).unwrap(), gemini); + assert_eq!(std::fs::metadata(script).unwrap().modified().unwrap(), written); + // A Claudiu that moved writes a new script, whole. + prepare(data.path(), &data.path().join("moved")).unwrap(); + assert!(std::fs::read_to_string(script).unwrap().contains("moved")); + let left: Vec<_> = std::fs::read_dir(gemini.join("config")).unwrap().flatten().filter(|e| e.path().to_string_lossy().ends_with(".tmp")).collect(); + assert!(left.is_empty(), "no staged file is left behind"); + } + + #[test] + #[cfg(windows)] + fn the_script_denies_when_claudiu_is_missing() { + let data = tempfile::tempdir().unwrap(); + let gemini = prepare(data.path(), &data.path().join("gone.exe")).unwrap(); + let mut command = std::process::Command::new("cmd"); + command.arg("/c").arg(gemini.join("config").join("read-only-hook.cmd")); + let out = command.stdin(std::process::Stdio::null()).output().unwrap(); + let answer: Value = serde_json::from_str(String::from_utf8_lossy(&out.stdout).trim()).unwrap(); + assert_eq!(answer["decision"], "deny"); + } + + #[test] + #[cfg(unix)] + fn the_script_denies_when_claudiu_is_missing() { + let data = tempfile::tempdir().unwrap(); + let gemini = prepare(data.path(), &data.path().join("gone")).unwrap(); + let out = std::process::Command::new(gemini.join("config").join("read-only-hook.sh")).stdin(std::process::Stdio::null()).output().unwrap(); + let answer: Value = serde_json::from_str(String::from_utf8_lossy(&out.stdout).trim()).unwrap(); + assert_eq!(answer["decision"], "deny"); + } +} diff --git a/src/claude/codex_limits.rs b/src/claude/codex_limits.rs index c72bc8b..91ed362 100644 --- a/src/claude/codex_limits.rs +++ b/src/claude/codex_limits.rs @@ -1,7 +1,7 @@ //! Codex's 5-hour and 7-day limits, read from the session logs Codex writes under `$CODEX_HOME/sessions` (default //! `~/.codex`). Each turn Codex logs a `token_count` event carrying its current `rate_limits`; the newest one is the //! reading. Read-only, no network, no tokens. The log format is Codex's own and undocumented, so anything that doesn't -//! parse is skipped and the sidebar shows no Codex row. +//! parse is skipped and the sidebar keeps its last reading. use std::path::{Path, PathBuf}; use std::collections::HashMap; diff --git a/src/claude/limits.rs b/src/claude/limits.rs new file mode 100644 index 0000000..5462adc --- /dev/null +++ b/src/claude/limits.rs @@ -0,0 +1,10 @@ +//! Usage limits shared by subagent providers, saved as one reading per group of models. + +use crate::store::AccountUsage; + +/// One group of models that share limits, by the name the provider gives it. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Pool { + pub name: String, + pub usage: AccountUsage, +} diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 77ffaa8..06fab79 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -7,16 +7,19 @@ //! Channels between Claudiu and the sessions it runs: `accounts` (alt config folders), `usage` (the mod's snapshots), //! `ask` (one-shot completions through the mod), `bridge` (requests from a session), `mcp` (the tab-title server and the //! per-session config) and `plugin` (the mod Claudiu ships). `codex_limits` reads Codex's own usage limits from its -//! session logs. +//! session logs, and `antigravity_limits` asks the Antigravity CLI for its own. pub mod accounts; pub mod acp; +pub mod antigravity_limits; +pub mod antigravity_read_only; pub mod ask; pub mod bridge; pub mod codex_limits; pub mod config_sync; pub mod costly; pub mod defaults; +pub mod limits; pub mod mcp; pub mod plugin; pub mod subagents; diff --git a/src/claude/subagents.rs b/src/claude/subagents.rs index 78ad7ef..a157144 100644 --- a/src/claude/subagents.rs +++ b/src/claude/subagents.rs @@ -1,11 +1,16 @@ //! Custom subagents: agent types that run a task in another coding agent instead of Claude (Settings → Custom -//! subagents): OpenAI Codex and OpenCode. +//! subagents). What differs from one agent to the next lives in its `Provider`. //! //! Claudiu lists the agent types in `CLAUDIU_SUBAGENTS`, and the mod registers them, so Claude Code names them //! `Claudiu:`. 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 `claudiu --acp` helper //! (`claude/acp.rs`). +use std::time::Duration; + +use super::limits::Pool; +use crate::panels::{logos, theme}; + use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; @@ -18,40 +23,208 @@ pub const EXE_ENV: &str = "CLAUDIU_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 `CLAUDIU_SUBAGENTS` -/// and the prefix of its agent types. +/// and the prefix of its agent types. Adding one takes a variant here, its place in `ALL`, and a `Provider`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Agent { #[default] Codex, OpenCode, + Antigravity, } -impl Agent { - pub const ALL: [Agent; 2] = [Agent::Codex, Agent::OpenCode]; +/// How a provider reads its limits and how often it asks again. +pub struct Limits { + pub read: fn() -> Result, String>, + pub every: Duration, +} +/// Everything Claudiu knows about one agent, including its ACP server and usage limits. +pub struct Provider { + /// The limits reader and refresh cadence, absent when the provider has no limits to show. + pub limits: Option, + /// The color of its sidebar limits. + pub color: u32, + /// The logos and optional short label that identify a pool in the sidebar. + pub marks: fn(&str) -> (&'static [&'static rune::Icon], Option), /// The name the settings page and the subagent's text use. - pub fn name(self) -> &'static str { + pub name: &'static str, + /// The key in `CLAUDIU_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, + /// What the user asks for, besides the model, when Claude should pick this agent. + triggers: &'static str, + /// The ACP server: a program on the PATH and its arguments. + pub program: &'static str, + pub args: &'static [&'static str], + /// Where the installer puts `program` on Windows, under `%LOCALAPPDATA%`, for when it isn't on the PATH. + pub windows_fallback: Option<&'static str>, + /// The program as failures name it. + 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, + /// The settings page's text: what the agent runs on and needs, and what Allow edits on and off let it do. + pub about: &'static str, + pub edits_on: &'static str, + pub edits_off: &'static str, + /// Arguments after `args` for one task's server, made ready here. + pub task_args: fn(&super::acp::Request) -> Result, String>, + /// The environment the server starts with, for agents that take the model, effort and edits that way. + pub environment: fn(&super::acp::Request) -> Vec<(&'static str, String)>, + /// ACP config options (`session/set_config_option`) set before the task, for agents that take them that way. + pub config_options: fn(&super::acp::Request) -> Vec<(&'static str, String)>, + /// Whether messages Claude sends mid-task go through this helper even when the agent can't steer: they then follow + /// up in the same session. Otherwise Claude Code queues them itself. + pub inbox_without_steering: bool, + /// Whether a steer asks the agent to answer `promptRequired`, rather than start a turn of its own, when idle. + pub steering_prompt_required: bool, + /// Whether the session opened only to list models is deleted again, since the agent keeps every session. + pub delete_model_session: bool, + /// Whether a tool call can start with only the tool's name, its target arriving in the first update. + pub deferred_tool_target: bool, +} + +const CODEX: Provider = Provider { + limits: Some(Limits { read: || { + let usage = super::codex_limits::codex_home().and_then(|home| super::codex_limits::read(&home)).ok_or("Codex has no limits reading yet")?; + Ok(vec![Pool { name: "Codex".into(), usage }]) + }, every: Duration::from_secs(3) }), + color: theme::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 Claudiu 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.", + about: "Runs the task in OpenAI Codex through codex-acp. Needs Node (npx) and a `codex login`; the first run downloads codex-acp from npm.", + edits_on: "Claudiu accepts everything Codex asks for: editing files, running commands, writing outside the folder and using the network. None of it goes through Claude Code's permission rules or hooks.", + edits_off: "Codex runs read-only: it can read and search, but not change files.", + task_args: super::acp::no_args, + environment: super::acp::codex_env, + config_options: super::acp::no_options, + inbox_without_steering: true, + steering_prompt_required: true, + delete_model_session: false, + deferred_tool_target: false, +}; + +const OPENCODE: Provider = Provider { + limits: None, + color: theme::TEXT, + 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.", + about: "Runs the task in OpenCode (`opencode acp`), on the providers you set up in OpenCode. Needs `opencode` on PATH.", + edits_on: "Claudiu accepts everything OpenCode asks for, and OpenCode's own permission settings decide the rest: it can edit files, run commands and use the network. None of it goes through Claude Code's permission rules or hooks.", + edits_off: "OpenCode runs read-only: it can read, search and list files, but not change them or run any command, not even a read-only one.", + task_args: super::acp::no_args, + environment: super::acp::opencode_env, + config_options: super::acp::no_options, + inbox_without_steering: false, + steering_prompt_required: false, + delete_model_session: true, + deferred_tool_target: true, +}; + +const ANTIGRAVITY: Provider = Provider { + limits: Some(Limits { read: || { + let agy = super::acp::locate(Agent::Antigravity).ok_or("agy was not found")?; + super::antigravity_limits::read(&agy, &crate::datadir::data_dir()) + }, every: super::antigravity_limits::REFRESH_EVERY }), + color: theme::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.", + about: "Runs the task in Google Antigravity (`agy acp`), on the Gemini, Claude and GPT models your Google plan includes. Needs the Antigravity CLI, signed in through `agy`.", + edits_on: "Claudiu puts Antigravity in accept-edits mode and allows everything it asks for: editing files and running commands. None of it goes through Claude Code's permission rules or hooks.", + edits_off: "Antigravity runs read-only: it can read and search, but not change files or run commands. It runs from its own folder in Claudiu's data, so your Antigravity rules, skills and MCP servers don't load.", + task_args: super::acp::antigravity_args, + environment: super::acp::no_env, + config_options: super::acp::antigravity_options, + inbox_without_steering: false, + steering_prompt_required: false, + delete_model_session: false, + deferred_tool_target: false, +}; + +/// 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()]); + +impl AgentMap { + pub fn from_fn(mut f: impl FnMut(Agent) -> T) -> Self { + Self(std::array::from_fn(|i| f(Agent::ALL[i]))) + } + + pub fn get(&self, agent: Agent) -> &T { + &self.0[agent.index()] + } + + pub fn get_mut(&mut self, agent: Agent) -> &mut T { + &mut self.0[agent.index()] + } +} + +impl Default for AgentMap { + fn default() -> Self { + Self::from_fn(|_| T::default()) + } +} + +impl Agent { + /// In the order the settings page lists them. + pub const ALL: [Agent; 3] = [Agent::Codex, Agent::OpenCode, Agent::Antigravity]; + + pub fn provider(self) -> &'static Provider { match self { - Agent::Codex => "Codex", - Agent::OpenCode => "OpenCode", + Agent::Codex => &CODEX, + Agent::OpenCode => &OPENCODE, + Agent::Antigravity => &ANTIGRAVITY, } } - /// The key in `CLAUDIU_SUBAGENTS` and the start of every agent type name. + /// Its place in `ALL`. + fn index(self) -> usize { + Agent::ALL.iter().position(|a| *a == self).expect("every agent is in ALL") + } + + pub fn name(self) -> &'static str { + self.provider().name + } + pub fn key(self) -> &'static str { - match self { - Agent::Codex => "codex", - Agent::OpenCode => "opencode", - } + self.provider().key } /// What Claude reads to decide when to use an agent type of this agent. fn description(self, model: &str) -> String { - match self { - Agent::Codex => format!("Runs the task in OpenAI Codex on {model}. Use only when the user asks for Codex, GPT or {model}."), - Agent::OpenCode => format!("Runs the task in OpenCode on {model}. Use only when the user asks for OpenCode or {model}."), - } + let p = self.provider(); + format!("Runs the task in {} on {model}. Use only when the user asks for {} or {model}.", p.task_name, p.triggers) } /// The mod answers these agents' turns, so Claude runs for one only if the mod lost track of it (a reload, and @@ -81,56 +254,42 @@ pub struct AgentChoice { pub catalog: Vec, } -/// Saved as `Stored`, the flat shape state files already hold for Codex: a field that changed type would make the -/// whole state file fail to load, and the store moves such a file aside. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(from = "Stored", into = "Stored")] -pub struct CustomSubagents { - pub codex: AgentChoice, - pub opencode: AgentChoice, -} - -#[derive(Default, Serialize, Deserialize)] -struct Stored { - #[serde(default)] - codex: bool, - #[serde(default)] - codex_models: Vec, - #[serde(default)] - codex_edits: bool, - #[serde(default)] - codex_catalog: Vec, - #[serde(default)] - opencode: bool, - #[serde(default)] - opencode_models: Vec, - #[serde(default)] - opencode_edits: bool, - #[serde(default)] - opencode_catalog: Vec, -} - -impl From for CustomSubagents { - fn from(s: Stored) -> Self { - CustomSubagents { - codex: AgentChoice { on: s.codex, models: s.codex_models, edits: s.codex_edits, catalog: s.codex_catalog }, - opencode: AgentChoice { on: s.opencode, models: s.opencode_models, edits: s.opencode_edits, catalog: s.opencode_catalog }, +/// Keeps the flat provider keys used by existing state files. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CustomSubagents(pub AgentMap); + +impl Serialize for CustomSubagents { + fn serialize(&self, serializer: S) -> Result { + let mut stored = Map::new(); + for agent in Agent::ALL { + let choice = self.get(agent); + let key = agent.key(); + stored.insert(key.into(), json!(choice.on)); + stored.insert(format!("{key}_models"), json!(choice.models)); + stored.insert(format!("{key}_edits"), json!(choice.edits)); + stored.insert(format!("{key}_catalog"), json!(choice.catalog)); } + stored.serialize(serializer) } } -impl From for Stored { - fn from(c: CustomSubagents) -> Self { - Stored { - codex: c.codex.on, - codex_models: c.codex.models, - codex_edits: c.codex.edits, - codex_catalog: c.codex.catalog, - opencode: c.opencode.on, - opencode_models: c.opencode.models, - opencode_edits: c.opencode.edits, - opencode_catalog: c.opencode.catalog, +impl<'de> Deserialize<'de> for CustomSubagents { + fn deserialize>(deserializer: D) -> Result { + let mut stored = Map::::deserialize(deserializer)?; + fn field(stored: &mut Map, key: &str) -> Result { + stored.remove(key).map(serde_json::from_value).transpose().map(|v| v.unwrap_or_default()).map_err(E::custom) } + let mut result = Self::default(); + for agent in Agent::ALL { + let key = agent.key(); + *result.get_mut(agent) = AgentChoice { + on: field::<_, D::Error>(&mut stored, key)?, + models: field::<_, D::Error>(&mut stored, &format!("{key}_models"))?, + edits: field::<_, D::Error>(&mut stored, &format!("{key}_edits"))?, + catalog: field::<_, D::Error>(&mut stored, &format!("{key}_catalog"))?, + }; + } + Ok(result) } } @@ -170,17 +329,11 @@ pub fn agent_types(agent: Agent, models: &[String]) -> Vec { impl CustomSubagents { pub fn get(&self, agent: Agent) -> &AgentChoice { - match agent { - Agent::Codex => &self.codex, - Agent::OpenCode => &self.opencode, - } + self.0.get(agent) } pub fn get_mut(&mut self, agent: Agent) -> &mut AgentChoice { - match agent { - Agent::Codex => &mut self.codex, - Agent::OpenCode => &mut self.opencode, - } + self.0.get_mut(agent) } /// Each agent switched on that has a type, with its types. @@ -205,7 +358,7 @@ impl CustomSubagents { .iter() .map(|t| json!({ "name": t.name, "model": t.model, "description": agent.description(&t.model), "prompt": agent.stub_prompt() })) .collect(); - env.insert(agent.key().into(), json!({ "edits": self.get(agent).edits, "types": types })); + env.insert(agent.key().into(), json!({ "edits": self.get(agent).edits, "name": agent.name(), "types": types })); } Some(Value::Object(env).to_string()) } @@ -215,6 +368,28 @@ impl CustomSubagents { mod tests { use super::*; + #[test] + fn every_limits_provider_has_visible_marks_and_a_color() { + for agent in Agent::ALL { + let provider = agent.provider(); + if provider.limits.is_some() { + assert_ne!(provider.color, theme::PANEL_BG, "{}", provider.name); + for pool in ["Codex", "Gemini Models", "Claude and GPT models", "Gemini 4 Argon", "Some New models"] { + let (marks, name) = (provider.marks)(pool); + assert!(!marks.is_empty() || name.is_some_and(|name| !name.is_empty()), "{}: {pool}", provider.name); + assert!(marks.iter().all(|mark| !mark.body.is_empty()), "{}: {pool}", provider.name); + } + } + } + } + + fn choices(codex: AgentChoice, opencode: AgentChoice) -> CustomSubagents { + let mut choices = CustomSubagents::default(); + *choices.get_mut(Agent::Codex) = codex; + *choices.get_mut(Agent::OpenCode) = opencode; + choices + } + fn ids(list: &[&str]) -> Vec { list.iter().map(|s| s.to_string()).collect() } @@ -223,6 +398,25 @@ mod tests { AgentChoice { on: true, models: ids(models), edits, catalog: vec![] } } + #[test] + fn antigravity_round_trips_flat_state_and_supplies_mod_texts() { + let mut choices = CustomSubagents::default(); + *choices.get_mut(Agent::Antigravity) = AgentChoice { catalog: vec![AgentModel { id: "gemini-4-neon".into(), name: "Gemini 4 Neon".into() }], ..on(&["gemini-4-neon"], true) }; + let stored = serde_json::to_value(&choices).unwrap(); + assert_eq!(stored["antigravity"], true); + assert_eq!(stored["antigravity_models"], json!(["gemini-4-neon"])); + assert_eq!(stored["antigravity_edits"], true); + assert_eq!(stored["antigravity_catalog"][0]["name"], "Gemini 4 Neon"); + assert_eq!(serde_json::from_value::(stored).unwrap(), choices); + let env: Value = serde_json::from_str(&choices.env().unwrap()).unwrap(); + assert_eq!(env["antigravity"]["name"], "Antigravity"); + assert_eq!(env["antigravity"]["types"][0]["description"], "Runs the task in Google Antigravity on gemini-4-neon. Use only when the user asks for Antigravity, Gemini or gemini-4-neon."); + for agent in Agent::ALL { + assert_eq!(Agent::ALL[agent.index()], agent); + assert_eq!(agent.key(), serde_json::to_value(agent).unwrap().as_str().unwrap(), "the state file and the mod use the same key"); + } + } + #[test] fn dots_become_dashes_and_codex_gets_the_real_id() { assert_eq!( @@ -261,17 +455,17 @@ mod tests { #[test] fn nothing_reaches_the_session_while_every_agent_is_off_or_has_no_model_on() { - let mut off = CustomSubagents { codex: on(&["gpt-6.1-sol"], true), opencode: on(&["openai/gpt-6.1-sol"], true) }; - off.codex.on = false; - off.opencode.on = false; + let mut off = choices(on(&["gpt-6.1-sol"], true), on(&["openai/gpt-6.1-sol"], true)); + off.get_mut(Agent::Codex).on = false; + off.get_mut(Agent::OpenCode).on = false; assert_eq!(off.env(), None); - let none = CustomSubagents { codex: on(&[], false), opencode: on(&[], false) }; + let none = choices(on(&[], false), on(&[], false)); assert_eq!(none.env(), None); } #[test] fn the_mod_gets_each_agent_on_with_its_edit_switch_and_types() { - let both = CustomSubagents { codex: on(&["gpt-6.1-sol", "gpt-5.6-luna"], false), opencode: on(&["openai/gpt-6.1-sol"], true) }; + let both = choices(on(&["gpt-6.1-sol", "gpt-5.6-luna"], false), on(&["openai/gpt-6.1-sol"], true)); let env: Value = serde_json::from_str(&both.env().unwrap()).unwrap(); assert_eq!(env.as_object().unwrap().keys().collect::>(), ["codex", "opencode"]); assert_eq!((&env["codex"]["edits"], &env["opencode"]["edits"]), (&json!(false), &json!(true))); @@ -294,7 +488,7 @@ mod tests { #[test] fn an_agent_on_with_no_model_on_is_left_out() { - let codex_only = CustomSubagents { codex: on(&["gpt-6.1-sol"], false), opencode: on(&[], true) }; + let codex_only = choices(on(&["gpt-6.1-sol"], false), on(&[], true)); let env: Value = serde_json::from_str(&codex_only.env().unwrap()).unwrap(); assert_eq!(env.as_object().unwrap().keys().collect::>(), ["codex"]); } @@ -305,10 +499,7 @@ mod tests { let loaded: CustomSubagents = serde_json::from_str(saved).unwrap(); assert_eq!( loaded, - CustomSubagents { - codex: AgentChoice { on: true, models: ids(&["gpt-6.1-sol"]), edits: true, catalog: vec![AgentModel { id: "gpt-6.1-sol".into(), name: "6.1 Sol".into() }] }, - opencode: AgentChoice::default(), - } + choices(AgentChoice { on: true, models: ids(&["gpt-6.1-sol"]), edits: true, catalog: vec![AgentModel { id: "gpt-6.1-sol".into(), name: "6.1 Sol".into() }] }, AgentChoice::default()) ); let again: CustomSubagents = serde_json::from_str(&serde_json::to_string(&loaded).unwrap()).unwrap(); assert_eq!(again, loaded); diff --git a/src/panels/logos.rs b/src/panels/logos.rs new file mode 100644 index 0000000..d5be764 --- /dev/null +++ b/src/panels/logos.rs @@ -0,0 +1,28 @@ +//! Provider logos from Lobe Icons (MIT licence, see `assets/LICENSE-LOBE-ICONS`), as Rune icon bodies drawn in the +//! element's colour. Copied from `@lobehub/icons-static-svg` 1.104.0; add one by copying the paths of its mono SVG. + +use rune::Icon; + +pub static ANTIGRAVITY: Icon = Icon { name: "antigravity", view: 24.0, body: r#""# }; +pub static CLAUDE: Icon = Icon { name: "claude", view: 24.0, body: r#""# }; +pub static CODEX: Icon = Icon { name: "codex", view: 24.0, body: r#""# }; +pub static GEMINI: Icon = Icon { name: "gemini", view: 24.0, body: r#""# }; +pub static OPENAI: Icon = Icon { name: "openai", view: 24.0, body: r#""# }; + +pub fn codex_marks(_: &str) -> (&'static [&'static Icon], Option) { + static MARKS: [&Icon; 1] = [&CODEX]; + (&MARKS, None) +} + +pub fn antigravity_marks(pool: &str) -> (&'static [&'static Icon], Option) { + use crate::claude::antigravity_limits::{PoolMark, mark}; + static GEMINI_MARKS: [&Icon; 1] = [&GEMINI]; + static CLAUDE_AND_GPT_MARKS: [&Icon; 2] = [&CLAUDE, &OPENAI]; + static OTHER_MARKS: [&Icon; 1] = [&ANTIGRAVITY]; + match mark(pool) { + PoolMark::Gemini => (&GEMINI_MARKS, None), + PoolMark::ClaudeAndGpt => (&CLAUDE_AND_GPT_MARKS, None), + PoolMark::GeminiNamed(name) => (&GEMINI_MARKS, Some(name)), + PoolMark::Other(name) => (&OTHER_MARKS, Some(name)), + } +} diff --git a/src/panels/mod.rs b/src/panels/mod.rs index 21f0d52..9809f43 100644 --- a/src/panels/mod.rs +++ b/src/panels/mod.rs @@ -1,13 +1,14 @@ //! What Claudiu draws around the terminals. `workspace_view` is the root view (top bar, main area, shell panel), //! `sidebar` and `inspector` are the two side panels, `editor_pane` editor mode's files and tabs, `overlays` the menu, modal and toast above them, and //! `settings_view` the Settings dialog's pages. `widgets` holds the small shared pieces, `status_icon` the icon at -//! the start of a session row, `icons` the Lucide icons and `markdown` Claudiu's markdown style. `theme` and `scale` +//! the start of a session row, `icons` the Lucide icons, `logos` the providers' logos and `markdown` Claudiu's markdown style. `theme` and `scale` //! set the look, and `glide` does the terminal's smooth scrolling. pub mod editor_pane; pub mod glide; pub mod icons; pub mod inspector; +pub mod logos; pub mod markdown; pub mod overlays; pub mod scale; diff --git a/src/panels/overlays.rs b/src/panels/overlays.rs index c8035a0..1757c0d 100644 --- a/src/panels/overlays.rs +++ b/src/panels/overlays.rs @@ -58,7 +58,7 @@ impl Workspace { out.push(m); } // Above Settings: the last modal mounted takes Escape and clicks outside it. - if let Some(m) = self.model_picker() { + if let Some(m) = self.agent_dialog() { out.push(m); } if let Some(m) = self.render_menu() { diff --git a/src/panels/settings_view.rs b/src/panels/settings_view.rs index 3ca7e9f..dc12f27 100644 --- a/src/panels/settings_view.rs +++ b/src/panels/settings_view.rs @@ -68,29 +68,84 @@ fn settings_toggle(key: &str, title: &str, on: bool, field: fn(&mut Modal) -> Op }) } -/// One agent's part of the Custom subagents page, edited as `form`. -struct AgentSection<'a> { - agent: Agent, - form: &'a AgentForm, - /// The models the agent offered when the page last asked. - catalog: &'a [AgentModel], - lookup: &'a Lookup, +/// Flips an agent's switch. Switched on with no model chosen yet, its dialog opens on the models, since an agent with +/// none gives Claude no subagent. +fn flip_agent(ws: &mut Workspace, agent: Agent) { + let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() else { return }; + let form = subagents.get_mut(agent); + form.on = !form.on; + let choose = form.on && form.models.is_empty(); + ws.load_models(); + if choose && !ws.agent_dialog_open() { + ws.open_agent_dialog(agent); + } +} + +/// What an agent's card says under its name, and in which colour: off, missing a model, or what Claude gets. +fn agent_status(agent: Agent, form: &AgentForm, lookup: &Lookup) -> (String, u32) { + if !form.on { + return ("Off".into(), theme::TEXT_FAINT); + } + if lookup.error.is_some() { + return (format!("Couldn't load {}'s models", agent.name()), theme::WARN); + } + let access = if form.edits { "edits allowed" } else { "read-only" }; + match form.models.len() { + 0 => ("On, but no model is chosen, so Claude gets no subagent".into(), theme::WARN), + 1 => (format!("1 subagent · {access}"), theme::TEXT_DIM), + n => (format!("{n} subagents · {access}"), theme::TEXT_DIM), + } } -/// What the page says about an agent: what it runs on and needs, and what Allow edits on and off let it do. -fn agent_texts(agent: Agent) -> (&'static str, &'static str, &'static str) { - match agent { - Agent::Codex => ( - "Runs the task in OpenAI Codex through codex-acp. Needs Node (npx) and a `codex login`; the first run downloads codex-acp from npm.", - "Claudiu accepts everything Codex asks for: editing files, running commands, writing outside the folder and using the network. None of it goes through Claude Code's permission rules or hooks.", - "Codex runs read-only: it can read and search, but not change files.", - ), - Agent::OpenCode => ( - "Runs the task in OpenCode (`opencode acp`), on the providers you set up in OpenCode. Needs `opencode` on PATH.", - "Claudiu accepts everything OpenCode asks for, and OpenCode's own permission settings decide the rest: it can edit files, run commands and use the network. None of it goes through Claude Code's permission rules or hooks.", - "OpenCode runs read-only: it can read, search and list files, but not change them or run any command, not even a read-only one.", - ), +/// An agent's card on the Custom subagents page: its name, its status and the models switched on, which open its +/// dialog, and its switch beside them. +fn agent_card(agent: Agent, form: &AgentForm, catalog: &[AgentModel], lookup: &Lookup) -> El { + let key = agent.key(); + let (status, tone) = agent_status(agent, form, lookup); + let mut about = col().grow(1.0).shrink().min_w(0.0).gap(3.0).child(label(agent.name(), 13.0, theme::TEXT).font(font(13.0, 600.0))).child(label(status, 11.0, tone).wrap()); + if form.on && !form.models.is_empty() { + let names: Vec<&str> = form.models.iter().map(|id| catalog.iter().find(|m| &m.id == id).map_or(id.as_str(), |m| m.name.as_str())).collect(); + about = about.child(label(names.join(" · "), 11.0, theme::TEXT_FAINT).truncate()); } + let open = row() + .key(format!("settings-{key}-open")) + .grow(1.0) + .shrink() + .min_w(0.0) + .center_y() + .gap(10.0) + .cursor(Cursor::Pointer) + .role("button") + .child(about) + .child(label("Set up ›", 12.0, theme::TEXT_DIM)) + .on_press_tx(move |ws: &mut Workspace, tx: &mut Tx| { + ws.open_agent_dialog(agent); + ws.after_input(tx); + }); + let toggle = row() + .key(format!("settings-{key}")) + .pl(14.0) + .h_full() + .center_y() + .cursor(Cursor::Pointer) + .role("switch") + .child(switch(form.on).key(format!("settings-{key}-switch"))) + .on_press_tx(move |ws: &mut Workspace, tx: &mut Tx| { + flip_agent(ws, agent); + ws.after_input(tx); + }); + row() + .key(format!("settings-{key}-card")) + .w_full() + .px(12.0) + .py(10.0) + .center_y() + .radius(8.0) + .fill(rgb(0x111113)) + .border(1.0, rgb(if form.on { 0x3a302b } else { 0x242428 })) + .hover(Color::WHITE.alpha(0.02)) + .child(open) + .child(toggle) } /// The models to list: those the agent offers, then any switched on that it no longer offers, so they can be @@ -135,56 +190,6 @@ fn lookup_status(agent: Agent, catalog: &[AgentModel], lookup: &Lookup) -> Optio } } -/// An agent's switch and, once it is on, the models switched on, the button to the model picker, and whether it may -/// edit. -fn agent_section(s: AgentSection) -> El { - let AgentSection { agent, form, catalog, lookup } = s; - let (about, edits_on, edits_off) = agent_texts(agent); - let key = agent.key(); - let mut section = col() - .gap(8.0) - .child(section_label(agent.name().to_uppercase()).mt(4.0)) - .child(faint(about)) - .child(switch_row(format!("settings-{key}"), &format!("{} subagents", agent.name()), None, form.on, move |ws| { - if let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() { - let form = subagents.get_mut(agent); - form.on = !form.on; - } - ws.load_models(); - })); - if !form.on { - return section; - } - for (model, offered) in model_rows(catalog, &form.models).into_iter().filter(|(m, _)| form.models.contains(&m.id)) { - section = section.children(model_switch(format!("settings-{key}-model-{}", model.id), agent, &model, offered, true)); - } - if let Some(status) = lookup_status(agent, catalog, lookup) { - section = section.child(status); - } else if form.models.is_empty() { - section = section.child(faint(format!("Choose a model to give Claude a {} subagent for it.", agent.name()))); - } - let count = if catalog.is_empty() { String::new() } else { on_count(catalog, &form.models) }; - section - .child( - row() - .w_full() - .center_y() - .justify_between() - .child(button("Choose models…", false).key(format!("settings-{key}-choose")).on_press_tx(move |ws: &mut Workspace, tx: &mut Tx| { - ws.open_model_picker(agent); - ws.after_input(tx); - })) - .child(faint(count)), - ) - .child(switch_row(format!("settings-{key}-edits"), "Allow edits", None, form.edits, move |ws| { - if let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() { - let form = subagents.get_mut(agent); - form.edits = !form.edits; - } - })) - .child(faint(if form.edits { edits_on } else { edits_off })) -} - /// A row that opens a menu of `options` under itself; the first entry, "Claude Code default", clears the choice. fn picker_row(key: &'static str, title: &str, current: Option, options: &'static [T], name: fn(T) -> &'static str, pick: fn(Option) -> Act) -> El { const DEFAULT: &str = "Claude Code default"; @@ -234,33 +239,62 @@ fn scale_step(key: &'static str, sign: &'static str, by: i32) -> El { } impl Workspace { - /// The model picker over the Custom subagents page: a search field and a switch for every model the agent offers - /// that fits it. Its switches edit the page's form, so Settings' Save and Cancel decide what is kept. - pub(crate) fn model_picker(&self) -> Option { + /// An agent's dialog over the Custom subagents page: what it runs on, its switch, Allow edits, and a search over + /// the models it offers with a switch for each. It edits the page's form, so Settings' Save and Cancel decide what + /// is kept. + pub(crate) fn agent_dialog(&self) -> Option { let Some(Modal::Settings { subagents, .. }) = &self.modal else { return None }; let (agent, search) = subagents.picking.as_ref()?; let agent = *agent; + let provider = agent.provider(); + let key = agent.key(); let form = subagents.get(agent); let catalog = &self.store.data.settings.custom_subagents.get(agent).catalog; - let query = search.text.as_str(); - let mut list = col().gap(6.0); - let mut shown = 0; - for (model, offered) in model_rows(catalog, &form.models).into_iter().filter(|(m, _)| model_matches(query, m)) { - if let Some(row) = model_switch(format!("model-picker-{}", model.id), agent, &model, offered, form.models.contains(&model.id)) { - list = list.child(row); - shown += 1; + let lookup = self.model_lookups.get(agent); + let mut top = col() + .gap(8.0) + .w_full() + .child(rune::text(format!("{} subagents", provider.name)).font(font(15.0, 600.0)).color(rgb(theme::TEXT))) + .child(faint(provider.about)) + .child(switch_row(format!("agent-dialog-{key}-on"), &format!("Give Claude {} subagents", provider.name), None, form.on, move |ws| flip_agent(ws, agent))); + let mut models = col().key("agent-dialog-models").w_full().gap(8.0); + if form.on { + top = top + .child(switch_row(format!("agent-dialog-{key}-edits"), "Allow edits", None, form.edits, move |ws| { + if let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() { + let form = subagents.get_mut(agent); + form.edits = !form.edits; + } + })) + .child(faint(if form.edits { provider.edits_on } else { provider.edits_off })); + let query = search.text.as_str(); + let mut list = col().gap(6.0); + let mut shown = 0; + for (model, offered) in model_rows(catalog, &form.models).into_iter().filter(|(m, _)| model_matches(query, m)) { + if let Some(row) = model_switch(format!("agent-dialog-model-{}", model.id), agent, &model, offered, form.models.contains(&model.id)) { + list = list.child(row); + shown += 1; + } } + if let Some(status) = lookup_status(agent, catalog, lookup) { + list = list.child(status); + } else if shown == 0 { + list = list.child(faint(format!("No model matches “{}”.", query.trim()))); + } + let count = if catalog.is_empty() { String::new() } else { on_count(catalog, &form.models) }; + models = models + .child(row().w_full().mt(4.0).center_y().justify_between().child(section_label("MODELS")).child(faint(count))) + .child(faint(format!("Each model switched on is one subagent Claude can start, named as shown under it. Claude uses {} only when you ask for it.", provider.name))) + .child(modal_input_submitting(5, search, "Search models", Workspace::close_agent_dialog)) + .child(list.key("agent-dialog-list").w_full()); + } else { + models = models.child(faint(format!("Switch {} on to choose its models.", provider.name))); } - if let Some(status) = lookup_status(agent, catalog, self.model_lookups.get(agent)) { - list = list.child(status); - } else if shown == 0 { - list = list.child(faint(format!("No model matches “{}”.", query.trim()))); - } - let count = on_count(catalog, &form.models); let card = col() - .key("model-picker") - .w(crate::panels::scale::px(520.0)) - .h(crate::panels::scale::px(440.0)) + .key("agent-dialog") + // A small window or a large scale shrinks the dialog to fit, and its body scrolls as one above Done. + .w(crate::panels::scale::px(560.0).min(self.window_size.0 - 32.0)) + .h(crate::panels::scale::px(560.0).min(self.window_size.1 - 32.0)) .padding(20.0) .gap(12.0) .radius(12.0) @@ -269,23 +303,19 @@ impl Workspace { .shadow(16.0, 48.0, Color::BLACK.alpha(0.55)) .role("dialog") .transition(rune::Transition::scale(0.96).combined(rune::Transition::opacity())) - .child(rune::text(format!("{} models", agent.name())).font(font(15.0, 600.0)).color(rgb(theme::TEXT))) - .child(modal_input_submitting(5, search, "Search models", Workspace::close_model_picker)) - .child(col().key("model-picker-list").grow(1.0).shrink().min_h(0.0).w_full().scroll(ScrollSpec { stick_bottom: false }).child(list.w_full().pr(6.0))) - .child( - row().w_full().center_y().justify_between().child(faint(count)).child(button("Done", true).key("model-picker-done").on_press_tx(|ws: &mut Workspace, tx: &mut Tx| { - ws.close_model_picker(); - ws.after_input(tx); - })), - ); + .child(col().key("agent-dialog-body").grow(1.0).shrink().min_h(0.0).w_full().gap(12.0).scroll(ScrollSpec { stick_bottom: false }).child(top.pr(6.0)).child(models.pr(6.0))) + .child(row().w_full().justify_end().child(button("Done", true).key("agent-dialog-done").on_press_tx(|ws: &mut Workspace, tx: &mut Tx| { + ws.close_agent_dialog(); + ws.after_input(tx); + }))); Some( row() - .key("model-picker-backdrop") + .key("agent-dialog-backdrop") .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)) .center() .fill(Color::BLACK.alpha(0.4)) .transition(rune::Transition::opacity()) - .modal(true, |ws: &mut Workspace| ws.close_model_picker()) + .modal(true, |ws: &mut Workspace| ws.close_agent_dialog()) .child(card), ) } @@ -384,10 +414,10 @@ impl Workspace { SettingsPage::CustomSubagents => { let saved = &self.store.data.settings.custom_subagents; let mut page = col().gap(8.0).child(faint( - "Agent types that run a task in another coding agent instead of Claude. Claude uses one only when you ask for it. Applies to new and resumed sessions. Running sessions keep theirs.", + "Let Claude hand a task to another coding agent. Each model you switch on under a provider becomes one subagent, and Claude uses it only when you ask for it. Applies to new and resumed sessions; running sessions keep theirs.", )); for agent in Agent::ALL { - page = page.child(agent_section(AgentSection { agent, form: subagents.get(agent), catalog: &saved.get(agent).catalog, lookup: self.model_lookups.get(agent) })); + page = page.child(agent_card(agent, subagents.get(agent), &saved.get(agent).catalog, self.model_lookups.get(agent))); } page } diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index f46b741..97512ca 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -5,10 +5,10 @@ use rune::tok::motion; use rune::{Color, Cursor, El, Phase, PointerButton, ScrollSpec, Transition, Tx, col, el, row, text, text_input}; use crate::app::{Act, Activity, MenuAnchor, MenuItem, SideDrag, Workspace}; -use crate::panels::icons; +use crate::panels::{icons, logos, scale}; use crate::panels::status_icon::{SessionDot, status_icon}; use crate::panels::theme::{self, rgb}; -use crate::panels::widgets::{ago, avatar, clawd, countdown, font, icon, icon_button, key_hint, label, meter, METER_WARN_AT, section_label, shortcut, tick}; +use crate::panels::widgets::{ago, avatar, clawd, countdown, font, icon, icon_button, key_hint, label, limit_bar, section_label, shortcut, tick}; use crate::store::{ExternalState, Id, Project, SessionKind, SessionRecord, now}; pub const SIDEBAR_W: f32 = 284.0; @@ -671,48 +671,69 @@ impl Workspace { fn sidebar_footer(&self) -> El { let t = now(); let usage = self.store.active_account().map(|a| a.usage.clone()).unwrap_or_default(); - // Captions are short: two meters share a row. `calm` colors a bar that is not yet near its limit; near it, the - // meter's own warning colors win. - let limit = |key: &str, label: &str, l: &Option, calm: Option| -> El { - match l { - Some(l) => match (l.resets_at, l.utilization) { - (Some(reset), util) if reset > t => { - let mut caption = format!("resets {}", countdown(reset - t)); - if t - l.seen_at > 900 { - caption.push_str(&format!(" · {} ago", ago(l.seen_at, t))); - } - let tone = calm.filter(|_| util.is_none_or(|f| f < METER_WARN_AT)).map(rgb); - meter(key, label, util, caption, tone) - } - (Some(_), _) => meter(key, label, None, "reset · unknown".into(), None), - (None, util) => meter(key, label, util, format!("seen {} ago", ago(l.seen_at, t)), None), + // 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. + let limit = |key: &str, l: &Option, calm: u32| -> El { + let (fraction, right) = match l { + Some(l) => match l.resets_at { + Some(reset) if reset > t => (l.utilization, countdown(reset - t)), + Some(_) => (None, "—".into()), + None => (l.utilization, format!("{} ago", ago(l.seen_at, t))), }, - None => meter(key, label, None, "after first message".into(), None), + None => (None, "—".into()), + }; + let left = fraction.map(|f| format!("{:.0}%", (f * 100.0).round())).unwrap_or_else(|| "—".into()); + limit_bar(key, fraction, left, right, Some(rgb(calm))).w(0.0).grow(1.0).shrink() + }; + // Fits the widest marks: two logos, or a logo and a two-letter name. + let label_w = scale::px(30.0); + let gap = scale::px(6.0); + // Each row starts with the logos of whose limits it shows, and a short name where logos alone can't tell rows apart. + let source_row = |source: &str, marks: &[&'static rune::Icon], name: Option, color: u32, five: El, seven: El| -> El { + let mut who = row().key(format!("meter-logo-{source}")).gap(scale::px(4.0)).center_y(); + for logo in marks { + who = who.child(icon(logo, scale::px(12.0), color)); } + if let Some(name) = name { + who = who.child(label(name, 10.5, color).truncate().shrink()); + } + row().key(format!("meter-row-{source}")).gap(gap).center_y().child(row().w(label_w).child(who)).child(five).child(seven) }; - let mut footer = col() + let divider = || el().h(scale::px(1.0)).w_full().my(scale::px(2.0)).fill(rgb(theme::BORDER)); + let headers = row() + .gap(gap) + .child(el().w(label_w)) + .child(section_label("5 HOUR").w(0.0).grow(1.0).shrink()) + .child(section_label("7 DAY").w(0.0).grow(1.0).shrink()); + let claude = source_row("claude", &[&logos::CLAUDE], None, theme::ACCENT, limit("meter-5h", &usage.five_hour, theme::ACCENT), limit("meter-7d", &usage.seven_day, theme::ACCENT)); + let mut limits = col().key("meter-limits").gap(scale::px(3.0)).child(headers).child(claude); + let subagents = &self.store.data.settings.custom_subagents; + for agent in crate::claude::subagents::Agent::ALL { + let provider = agent.provider(); + if !subagents.get(agent).on { + continue; + } + let Some(pools) = self.store.data.subagent_limits.get(provider.key).filter(|pools| !pools.is_empty()) else { continue }; + limits = limits.child(divider()); + for (i, pool) in pools.iter().enumerate() { + let source = format!("{}-{i}", provider.key); + // Empty windows keep their column, without drawing a keyed meter. + let cell = |window: &str, l: &Option| match l { + Some(_) => limit(&format!("meter-{source}-{window}"), l, provider.color), + None => el().w(0.0).h(scale::px(16.0)).grow(1.0).shrink(), + }; + let (marks, name) = (provider.marks)(&pool.name); + limits = limits.child(source_row(&source, marks, name, provider.color, cell("5h", &pool.usage.five_hour), cell("7d", &pool.usage.seven_day))); + } + } + col() .gap(8.0) .px(14.0) .pt(6.0) .pb(8.0) .border_sides([1.0, 0.0, 0.0, 0.0], rgb(theme::BORDER)) .child(self.account_switcher()) - .child( - row() - .gap(12.0) - .child(limit("meter-5h", "5 HOUR", &usage.five_hour, None).grow(1.0).shrink()) - .child(limit("meter-7d", "7 DAY", &usage.seven_day, None).grow(1.0).shrink()), - ); - // Only with Codex subagents on and once Codex has logged a reading, so people who don't use Codex see no row. - if let Some(codex) = self.codex_usage.as_ref().filter(|_| self.store.data.settings.custom_subagents.codex.on) { - footer = footer.child( - row() - .gap(12.0) - .child(limit("meter-codex-5h", "CODEX 5 HOUR", &codex.five_hour, Some(theme::CODEX)).grow(1.0).shrink()) - .child(limit("meter-codex-7d", "CODEX 7 DAY", &codex.seven_day, Some(theme::CODEX)).grow(1.0).shrink()), - ); - } - footer + .child(limits) } } diff --git a/src/panels/theme.rs b/src/panels/theme.rs index 3659b83..eb73ac4 100644 --- a/src/panels/theme.rs +++ b/src/panels/theme.rs @@ -30,6 +30,8 @@ pub const DANGER: u32 = 0xe06c75; pub const SELECTION: u32 = 0x3d4a5c; /// Codex's usage bars, so they read apart from Claude's at a glance. The terminal palette's blue. pub const CODEX: u32 = 0x61afef; +/// Antigravity's usage bars, apart from Claude's and Codex's. The terminal palette's magenta. +pub const ANTIGRAVITY: u32 = 0xc678dd; /// Search matches in the editor, faint, and the current one stronger. pub const FOUND: u32 = 0xe5c07b; diff --git a/src/panels/widgets.rs b/src/panels/widgets.rs index 9d24291..0ec50d1 100644 --- a/src/panels/widgets.rs +++ b/src/panels/widgets.rs @@ -101,6 +101,37 @@ pub fn meter(key: &str, label: &str, fraction: Option, caption: String, ton .child(text(caption).font(font(10.5, 400.0)).color(rgb(theme::TEXT_FAINT))) } +/// Compact usage track, with the used fraction behind the percentage and reset countdown. +pub fn limit_bar(key: &str, fraction: Option, left: String, right: String, tone: Option) -> El { + let color = match fraction { + Some(f) if f >= 0.9 => rgb(theme::DANGER), + Some(f) if f >= METER_WARN_AT => rgb(theme::WARN), + _ => tone.unwrap_or_else(|| rgb(theme::ACCENT)), + }; + let height = scale::px(16.0); + // Faint enough that the text drawn over it stays readable. + let fill = el() + .key(format!("{key}-bar")) + .absolute(0.0, 0.0) + .h(height) + .w_frac(fraction.unwrap_or(0.0).clamp(0.0, 1.0)) + .radius(scale::px(3.0)) + .fill(color.alpha(0.32)) + .motion(motion::REFLOW); + let percent_color = if fraction.is_some() { theme::TEXT } else { theme::TEXT_FAINT }; + let texts = row() + .absolute(0.0, 0.0) + .w_full() + .h(height) + .px(scale::px(4.0)) + .gap(scale::px(3.0)) + .center_y() + .justify_between() + .child(text(left).font(font(10.5, 500.0).features("'tnum' 1")).color(rgb(percent_color))) + .child(text(right).font(font(10.5, 400.0).features("'tnum' 1")).color(rgb(theme::TEXT_DIM)).truncate().shrink()); + el().key(key.to_string()).h(height).radius(scale::px(3.0)).clip_rounded(scale::px(3.0)).fill(rgb(0x1c1c1c)).child(fill).child(texts) +} + struct Look { bg: u32, fg: u32, diff --git a/src/store.rs b/src/store.rs index 660ff09..752838a 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,6 +1,7 @@ //! Claudiu's own persisted state (projects, session history, cached usage, layout). //! Independent of the UI. Claude Code's data is only ever *read* (see `claude/`) and merged in here. +use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -322,6 +323,9 @@ pub struct Data { /// move) because older Claudiu versions require the field and would set state.json aside without it. #[serde(default)] pub account: AccountUsage, + /// The last limits reading per provider key, shown at launch while the next reading runs. + #[serde(default)] + pub subagent_limits: BTreeMap>, /// The main account first, then alts. Kept in `accounts.json`, not state.json: an older Claudiu still /// running would rewrite state.json without them. #[serde(skip)] @@ -804,6 +808,22 @@ mod tests { Project { id: id.into(), name: id.into(), path: PathBuf::from(path), git: None, collapsed: false, added_at: 0 } } + #[test] + fn the_last_antigravity_reading_is_there_after_a_restart() { + use crate::claude::limits::Pool; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("state.json"); + let mut s = Store::load(path.clone()); + let limit = RateLimit { utilization: Some(0.5), resets_at: Some(200), seen_at: 100 }; + s.data.subagent_limits.insert("antigravity".into(), vec![Pool { name: "Gemini 4 Argon".into(), usage: AccountUsage { five_hour: None, seven_day: Some(limit) } }]); + s.save(); + assert_eq!(Store::load(path).data.subagent_limits, s.data.subagent_limits); + // A state.json from before the field loads with no reading. + let old = dir.path().join("old.json"); + fs::write(&old, r#"{"version":1,"projects":[],"sessions":[]}"#).unwrap(); + assert!(Store::load(old).data.subagent_limits.is_empty()); + } + #[test] fn saves_land_in_the_order_made_and_a_failed_one_is_tried_again() { let dir = tempfile::tempdir().unwrap(); diff --git a/web/src/pages/index.astro b/web/src/pages/index.astro index 4788ba5..e2d949e 100644 --- a/web/src/pages/index.astro +++ b/web/src/pages/index.astro @@ -214,7 +214,7 @@ const calls = [
ClaudiuSpecifications
-

Specifications.

Claudiu owns the workspace. Claude Code owns the agent.

Built withRust and Rune, not a web wrapper
Terminalone real PTY per session; typed into only for the editor's @path#L reference
Anthropic APInever called by Claudiu
Claude Code datatranscripts never deleted; settings change only when you flip a switch
NetworkGitHub only, plus npm and OpenAI for Codex subagents, and your own OpenCode providers for OpenCode subagents
Uploadsnone
After a restartrunning sessions come back
Download Windows, macOS and Linux
+

Specifications.

Claudiu owns the workspace. Claude Code owns the agent.

Built withRust and Rune, not a web wrapper
Terminalone real PTY per session; typed into only for the editor's @path#L reference
Anthropic APInever called by Claudiu
Claude Code datatranscripts never deleted; settings change only when you flip a switch
NetworkGitHub only, plus npm and OpenAI for Codex subagents, your own OpenCode providers for OpenCode subagents, and Google for Antigravity subagents
Uploadsnone
After a restartrunning sessions come back
Download Windows, macOS and Linux