diff --git a/README.md b/README.md index 4db98b4..a47b1e6 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,17 @@ # Claudiu -Claudiu is a native desktop app, written in Rust with [Rune](https://github.com/anomalyco/rune), that runs several [Claude Code](https://code.claude.com) sessions in one window on Windows, macOS and Linux. It is a personal project with rough edges. Issues and pull requests are welcome. +Claudiu is a native desktop app, written in Rust with [Rune](https://github.com/anomalyco/rune), that runs several [Claude Code](https://code.claude.com) sessions in one window on Windows, macOS and Linux. It is a personal project with rough edges: macOS and Linux are lightly tested, and the macOS build isn't notarized. Issues and pull requests are welcome. > **Claudiu is an independent project. It is not affiliated with, endorsed by or sponsored by Anthropic.** Claude and Claude Code are trademarks of Anthropic. ## What it does -Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. It also has an optional switch that turns off six Claude Code features that add tokens to every request and that coding rarely uses, such as Artifacts and bundled skills. Settings → Claude Code tools shows each switch as high, medium or low savings. Settings has a Check setup button to open it again. A sidebar lists your running sessions, with the rest in a Recent list at its bottom that opens and scrolls. Settings → Projects adds, renames, reorders and removes projects. Removing one keeps its sessions, and the notice that follows has an Undo button. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. - -Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login (Claude attaches the ones it works on to the right sidebar, from this project or another repository), defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration: settings, `CLAUDE.md`, keybindings, MCP servers, folder trust and the options `/config` saves, with your main `~/.claude` too. An account with a running session takes a changed `/config` option once its sessions have ended. You name a session yourself, from its right-click menu, by regenerating its title, or with `/rename` in Claude Code, which Claudiu's sidebar follows. When a reply needs a table, chart or diagram, Claude draws it as a card inside the terminal, under the tool call, and the card scrolls with the transcript. Cards can hold buttons that send a message for you, collapsible sections, tabs and charts, and they come back when you reopen a session. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there (a session that has no conversation yet starts over in the new folder). Claude can switch the session itself with the `switch_worktree` tool, after you approve it and once its turn ends. In the menu, the hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. - -Ctrl+Shift (Cmd+Shift on macOS) plus a letter drives the app. Everything else reaches Claude Code. Editor mode finds `rust-analyzer`, `tsc --lsp` and `gleam` on your PATH and installs nothing. - -To reduce background rendering, an inactive window updates streaming terminal output at most four times a second, with a final update when output stops. Returning to the window restores the normal frame rate. Busy sidebar icons stop animating while the window is inactive, the sidebar is hidden, or editor mode hides it. When a session finishes or asks a question while the window is in the background, Claudiu sends a system notification. +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. Settings lists the rest. ## What it touches -Claudiu never deletes a transcript. It writes to Claude Code's own data only to change the settings you switch in Claudiu, as `/config` does, to sync shared files between accounts, and to append one line to a transcript when a session that `claude --worktree` put in a worktree moves to another folder, so Claude Code knows it has left that worktree. Nothing is uploaded and terminal contents are never logged. The only network use is GitHub: the update check (off with `"settings": { "update_url": "" }` in `state.json`) and the GitHub pane. State lives in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows, `~/Library/Application Support/Claudiu` on macOS and `~/.local/share/claudiu` on Linux, and crashes go to `crash.log` there. - -## Known gaps - -- macOS is lightly tested, and the build isn't notarized, so Gatekeeper complains on first launch. -- Linux is new and lightly tested. -- Quitting ends running PTYs. Sessions stay resumable, but live processes don't survive a restart. +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. ## Development -You need stable Rust. On Windows you also need Visual Studio Build Tools (C++) and the Windows SDK. On Linux you need the headers Rune builds against; on Debian or Ubuntu: - -```sh -sudo apt install libwayland-dev libxkbcommon-dev libvulkan1 zlib1g-dev -``` - -Tasks go through [just](https://just.systems); run `just` to list them. - -```sh -just run # dev build: shows stderr, never checks for updates -just test # app tests and mod tests (the mod tests need the claude CLI) -just lint # clippy -just ci # what CI checks, plus the mod and the web build -``` - -The repository has three parts: - -- `src/` is the app, including the MCP server that each session connects to. -- `mod/` is the Claude Code plugin each session loads, which writes the usage snapshots. -- `web/` is the Astro site. - -`CLAUDE.md` has the conventions for contributing. Releases use [Velopack](https://velopack.io) and GitHub Releases: bump `version` in `Cargo.toml`, then `git tag vX.Y.Z && git push --tags`. `scripts\package.ps1` builds a local installer. The Linux release is an AppImage. +You need stable Rust, plus Visual Studio Build Tools on Windows or the headers Rune builds against on Linux, and [just](https://just.systems): `just run`, `just test`, `just ci`. `src/` is the app, `mod/` is the Claude Code plugin each session loads, and `web/` is the site. `CLAUDE.md` has the conventions. To release, bump `version` in `Cargo.toml` and push a `vX.Y.Z` tag. diff --git a/mod/hooks/register.js b/mod/hooks/register.js index 41409b8..3366e32 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -18,6 +18,9 @@ // 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 +// 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. // ---- Constants ---------------------------------------------------------------------------------------------------- @@ -33,6 +36,7 @@ const PROMPT_MAX = 20000 // characters of a message Claudiu asks the session to const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] const ASK_MODELS = ['haiku', 'sonnet', 'opus'] const VISUAL_TOOL = 'mcp__claudiu__show_visual' +const HANDBACK_TOOL = 'SubagentHandback' // The /config row for background compaction ("Precompute compaction"). Claude Code lists it only while a server-side // flag enables the feature; without the row the setting does nothing, so Claudiu offers the switch only with it. const PRECOMPUTE_ROW = 'precomputeCompactionEnabled' @@ -49,6 +53,10 @@ 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 customRuns = new Map() // agent id -> { type, prompt, turnId, report } of each custom subagent started const published = new Set() // call ids whose card file this process wrote from the transcript let rowsPoll // watches the heights Claudiu measures let visualChain = Promise.resolve() // visual writes in order, without holding up the stream @@ -337,6 +345,130 @@ async function watchSessionName($) { }) } +// ---- Custom subagents --------------------------------------------------------------------------------------------- + +// Registers the custom agent types Claudiu listed for this session (`claude/subagents.rs`); Claude Code names each +// `Claudiu:`. Interactive Claude Code ignores `claude --agents`, so this is where they are defined. A missing or +// broken list registers none. +async function registerSubagents($) { + customTypes.clear() + const listed = await $.env.get('CLAUDIU_SUBAGENTS') + if (!listed || !(await $.env.get('CLAUDIU_EXE'))) return + let agents + try { + agents = JSON.parse(listed) + } catch { + return + } + for (const agent of Object.keys(AGENT_NAMES)) { + 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 })) + .catch(() => {}) + } + } +} + +// Notes the task of each custom subagent as it starts; its turns are answered by customStep. +async function onAgentSpawn($, e, next) { + const r = await next(e) + if (r.agentId && customTypes.has(e.subagentType)) { + customRuns.set(r.agentId, { type: e.subagentType, prompt: e.prompt, turnId: null, report: null, handedBack: 0 }) + } + return r +} + +// The custom run of a subagent, or undefined for any other agent. A reload of this module forgets the runs it noted, +// so an agent of a custom type not noted is taken up from the agent list, with its newest message as the task. +async function customRun($, agentId) { + if (customRuns.has(agentId) || customTypes.size === 0) return customRuns.get(agentId) + const agent = (await $.agent.list().catch(() => [])).find(a => a.id === agentId) + if (!agent || !customTypes.has(agent.type)) return undefined + const run = { type: agent.type, prompt: null, turnId: null, report: null, handedBack: 0 } + customRuns.set(agentId, run) + return run +} + +// The task for this turn: the Agent call's prompt on the first turn, the newest message to the agent after that +// (a message sent to a finished subagent starts a turn of its own). +async function customTask($, run, agentId) { + if (run.turnId === null && run.prompt !== null) return run.prompt + const messages = await $.session.messages({ agentId }).catch(() => []) + const last = Array.isArray(messages) ? messages.filter(m => m.role === 'user' && m.text?.trim()).at(-1) : undefined + return last?.text ?? run.prompt ?? '' +} + +// Answers one step of a custom subagent: runs the task in its agent, streams what the agent writes and does as the +// subagent's own text (saved in its transcript, which only the person reads), and hands back the agent's last message +// as the report. The agent runs once per turn; a later step of the same turn (a refused hand-back) +// hands back the same report once more, then ends the turn with the report as plain text so a hand-back that keeps +// being refused can't loop. +async function* customStep($, e, next, run) { + if (run.turnId !== e.turnId || run.report === null) { + const prompt = await customTask($, run, e.agentId) + run.turnId = e.turnId + run.handedBack = 0 + const { agent, model, edits } = customTypes.get(run.type) + const name = AGENT_NAMES[agent] + yield { kind: 'text', index: 0, text: `${name} on ${model}, ${edits ? 'edits allowed' : 'read-only'}\n\n` } + run.report = null + for await (const event of helperEvents($, { agent, model, edits, cwd: await $.session.cwd(), prompt }, next.signal)) { + if (event.kind === 'text') yield { kind: 'text', index: 0, text: event.text } + else if (event.kind === 'step') yield { kind: 'text', index: 0, text: `\n▸ ${event.text}\n` } + else if (event.kind === 'report') run.report = event.text + else if (event.kind === 'failed') run.report = `${name} failed: ${event.reason}` + } + if (next.signal?.aborted) return + run.report ??= `${name} failed: the helper stopped without an answer.` + } + if (run.handedBack >= 2) { + yield { kind: 'text', index: 1, text: run.report } + yield { kind: 'stop', stopReason: 'end_turn', usage: null } + return { turnId: e.turnId, index: e.index, answer: run.report, toolUses: [], stopReason: 'end_turn', usage: null } + } + run.handedBack += 1 + const input = { message: run.report } + yield { kind: 'tool', index: 1, id: `toolu_custom_${e.turnId}_${e.index}`, name: HANDBACK_TOOL } + yield { kind: 'input', index: 1, json: JSON.stringify(input) } + yield { kind: 'stop', stopReason: 'tool_use', usage: null } + return { turnId: e.turnId, index: e.index, answer: '', toolUses: [{ name: HANDBACK_TOOL, input }], stopReason: 'tool_use', usage: null } +} + +// The helper's events, one per line of its output. Stops early, ending the helper and the agent, when the turn is +// interrupted. +async function* helperEvents($, request, signal) { + const exe = await $.env.get('CLAUDIU_EXE') + let pending = '' + try { + for await (const chunk of $.process.spawn({ argv: [exe, '--acp'], input: JSON.stringify(request) })) { + if (signal?.aborted) return + if (chunk.stream !== 'stdout') continue + pending += chunk.text + const lines = pending.split('\n') + pending = lines.pop() + for (const line of lines) { + const event = parseEvent(line) + if (event) yield event + } + } + } catch (err) { + yield { kind: 'failed', reason: 'the helper could not run (' + String(err?.message ?? err).slice(0, 200) + ')' } + } +} + +function parseEvent(line) { + try { + const event = JSON.parse(line) + return typeof event?.kind === 'string' ? event : null + } catch { + return null + } +} + // ---- Hook handlers ------------------------------------------------------------------------------------------------ async function onMeasure($, e, next) { @@ -438,8 +570,10 @@ async function onShowVisual($, e) { } // Applies the saved model and effort to this turn's steps, and streams a show_visual call to its card while the model -// writes it. Sub-agent steps are left alone. +// writes it. A custom subagent's steps are answered by customStep; other subagents' steps are left alone. async function* onTurnStep($, e, next) { + const run = e.agentId ? await customRun($, e.agentId) : undefined + if (run) return yield* customStep($, e, next, run) const step = !e.agentId && (want.model || want.effort) ? { ...e, model: want.model ?? e.model, effort: want.effort ?? e.effort } : e @@ -514,6 +648,7 @@ async function onSessionStart($, e, next) { rowsPoll?.cancel() rowsPoll = $.clock.every(200, () => readCardRows($)) await watchSessionName($) + await registerSubagents($) return r } @@ -527,5 +662,6 @@ export function register(on) { on('ui.render', { component: 'ToolUse' }, onVisualRow) on('ui.render', { component: 'ToolGroup' }, onVisualGroup) on('turn.step', onTurnStep) + on('agent.spawn', onAgentSpawn) on('session.start', onSessionStart) } diff --git a/mod/hooks/subagents.test.ts b/mod/hooks/subagents.test.ts new file mode 100644 index 0000000..93c9a58 --- /dev/null +++ b/mod/hooks/subagents.test.ts @@ -0,0 +1,141 @@ +import { expect, mock, test } from 'claude-code/testing' + +// What `claude/subagents.rs` lists for a type. +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')] } }) + +// 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. +function engine(on: any, helper: string[], requests: unknown[], subagents = SUBAGENTS) { + mock.env(on, { CLAUDIU_SUBAGENTS: subagents, CLAUDIU_EXE: '/apps/claudiu' }) + mock.clock(on) + on('fs.read', () => ({ value: '' })) + on('fs.write', () => ({ value: undefined })) + on('session.id', () => ({ value: 's1' })) + on('session.model', () => ({ value: 'claude-haiku-5-5' })) + on('session.cwd', () => ({ value: '/work/sub' })) + on('config.list', () => ({ value: [] })) + on('settings.read', () => ({ value: {} })) + on('session.start', (_$: any, e: any) => ({ cwd: e.cwd })) + const registered: any[] = [] + on('agent.register', (_$: any, e: any) => { + registered.push(e) + return { value: undefined } + }) + on('agent.spawn', () => ({ model: 'haiku', agentId: 'a1' })) + on('process.spawn', async function* (_$: any, e: any) { + requests.push({ argv: e.argv, input: JSON.parse(e.input) }) + // Pieces cut mid-line, as a pipe delivers them. + const out = helper.join('\n') + '\n' + yield { stream: 'stdout', text: out.slice(0, 7) } + yield { stream: 'stdout', text: out.slice(7) } + return { value: { code: 0, signal: null } } + }) + // Claude, for any agent the mod leaves alone. + on('turn.step', async function* (_$: any, e: any) { + yield { kind: 'text', index: 0, text: 'Claude answered' } + return { turnId: e.turnId, index: e.index, answer: 'Claude answered', toolUses: [], stopReason: 'end_turn', usage: null } + }) + return registered +} + +async function step($: any, turnId: string, index: number, agentId?: string) { + const chunks: any[] = [] + const stream = $.turn.step({ turnId, index, model: 'haiku', messageCount: 1, agentId }) + for await (const c of stream) chunks.push(c) + return chunks +} + +test('a Codex subagent runs the task in Codex and hands back its last message', async ($, on) => { + const requests: any[] = [] + const registered = engine(on, [ + JSON.stringify({ kind: 'text', text: 'Looking.' }), + JSON.stringify({ kind: 'step', text: 'Read src/a.rs' }), + JSON.stringify({ kind: 'report', text: 'The bug is on line 12.' }), + ], requests) + + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + // Registered as Claudiu lists it; Claude Code names it Claudiu:codex-gpt-5-5. + expect(registered).toEqual([{ name: 'codex-gpt-5-5', description: 'Runs the task on gpt-5.5.', prompt: 'Say the mod lost track.', model: 'haiku', tools: [] }]) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + + expect(requests).toEqual([{ argv: ['/apps/claudiu', '--acp'], input: { agent: 'codex', model: 'gpt-5.5', edits: false, cwd: '/work/sub', prompt: 'Find the bug' } }]) + // What Codex writes and does is the agent's own text, which its transcript keeps; Claude gets only the report. + const text = chunks.filter(c => c.kind === 'text').map(c => c.text).join('') + expect(text).toBe('Codex on gpt-5.5, read-only\n\nLooking.\n▸ Read src/a.rs\n') + const tool = chunks.find(c => c.kind === 'tool') + expect(tool.name).toBe('SubagentHandback') + const input = chunks.filter(c => c.kind === 'input').map(c => c.json).join('') + expect(JSON.parse(input)).toEqual({ message: 'The bug is on line 12.' }) + + // A second step of the same turn (a refused hand-back) hands back the same report without running Codex again. + const again = await step($, 't1', 1, 'a1') + expect(requests.length).toBe(1) + expect(JSON.parse(again.filter(c => c.kind === 'input').map(c => c.json).join(''))).toEqual({ message: 'The bug is on line 12.' }) + + // A hand-back refused again ends the turn with the report as text instead of asking forever. + const last = await step($, 't1', 2, 'a1') + expect(last.some(c => c.kind === 'tool')).toBe(false) + expect(last.filter(c => c.kind === 'text').map(c => c.text).join('')).toBe('The bug is on line 12.') + expect(requests.length).toBe(1) +}) + +test('an OpenCode subagent runs the task in OpenCode and names it', async ($, on) => { + const requests: any[] = [] + const subagents = JSON.stringify({ + codex: { edits: false, types: [type('codex-gpt-5-5', 'gpt-5.5')] }, + opencode: { edits: true, types: [type('opencode-openai-gpt-6-1-sol', 'openai/gpt-6.1-sol')] }, + }) + engine(on, [JSON.stringify({ kind: 'failed', reason: 'opencode was not found on PATH. OpenCode subagents need OpenCode installed.' })], requests, subagents) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:opencode-openai-gpt-6-1-sol', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + + expect(requests.map(r => r.input)).toEqual([{ agent: 'opencode', model: 'openai/gpt-6.1-sol', edits: true, cwd: '/work/sub', prompt: 'Find the bug' }]) + expect(chunks.filter(c => c.kind === 'text').map(c => c.text).join('')).toBe('OpenCode on openai/gpt-6.1-sol, edits allowed\n\n') + const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) + expect(input.message).toBe('OpenCode failed: opencode was not found on PATH. OpenCode subagents need OpenCode installed.') +}) + +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 }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) + expect(input.message).toBe("Codex failed: Codex isn't signed in. Run `codex login`, then try again.") +}) + +test('a helper that ends without an answer is a failure too', async ($, on) => { + engine(on, ['not json'], []) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) + expect(input.message).toBe('Codex failed: the helper stopped without an answer.') +}) + +test('other subagents still run on Claude', async ($, on) => { + const requests: unknown[] = [] + engine(on, [], requests) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'general-purpose', prompt: 'Look around' }) + const chunks = await step($, 't1', 0, 'a1') + expect(chunks.map(c => c.kind)).toEqual(['text']) + expect(requests).toEqual([]) +}) + +test('without a list from Claudiu, nothing is registered and an agent named like a Codex type still runs on Claude', async ($, on) => { + const requests: unknown[] = [] + const registered = engine(on, [], requests, '') // an empty list reads as none, like a missing one + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + expect(registered).toEqual([]) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + expect(chunks.map(c => c.kind)).toEqual(['text']) + expect(requests).toEqual([]) +}) diff --git a/src/app/headless.rs b/src/app/headless.rs index ae32e30..5fd26fb 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -2283,3 +2283,176 @@ fn the_projects_page_moves_renames_and_removes_projects() { assert_eq!(names(&h), ["beta", "alpha two"], "Undo puts it back in its place"); assert_eq!(h.ws().store.session(&session).unwrap().project_id.as_ref(), Some(&beta), "with its session"); } + +/// A card scrolled partly past the top edge, as Claude Code redraws its transcript a line at a time, stays drawn as it +/// was: nothing of it fades, and only one copy of it is on screen. +#[test] +fn a_card_scrolling_past_the_top_does_not_fade_or_double() { + let mut h = Harness::new(|_| vec![]); + let cwd = h.work.clone(); + h.step(|ws| ws.new_claude(cwd)); + let id = h.ws().active.clone().unwrap(); + // The stand-in's own output (the console's first paint) comes first; after it the terminal is quiet. + let t = Instant::now(); + while t.elapsed() < Duration::from_secs(3) { + std::thread::sleep(Duration::from_millis(50)); + h.pump(); + } + // The screen as Claude Code draws it: the card's 12 reserved rows from screen row `top`, which may be above the edge. + let screen = |top: i32| -> String { + let mut out = String::from("\x1b[H\x1b[2J"); + for y in 0..20 { + let row = y - top; + out += &format!("\x1b[{};1H", y + 1); + out += &if (0..12).contains(&row) { format!("\x1b]8;;claudiu://visual/c1/{row}\x1b\\{}\x1b]8;;\x1b\\", " ".repeat(16)) } else { format!("line {y}") }; + } + out + }; + let feed = |h: &mut Harness, bytes: String| h.step(|ws| ws.terminal_mut(&id).unwrap().feed(&bytes)); + feed(&mut h, screen(4)); + let stem = datadir::safe_file_stem(&id); + let card = crate::visual::Card { call: "c1".into(), content: "# Title\n\nSome words in the card.\n\n- one\n- two\n- three".into() }; + h.step(|ws| ws.apply_visuals(vec![(stem, card)])); + h.settle(); + let card_parts = |h: &Harness| -> Vec { h.rt.elements().into_iter().filter(|e| e.path.contains("/slot-") || e.key.as_deref().is_some_and(|k| k.contains("/slot-"))).collect() }; + assert!(!card_parts(&h).is_empty(), "the card is drawn"); + for top in [3, 2, 1, 0, -1, -2, -3] { + feed(&mut h, screen(top)); + let moving = |e: &rune::ElementInfo| e.exiting || e.opacity < 1.0 || e.rect.iter().zip(e.target).any(|(a, b)| (a - b).abs() > 0.01); + let fading: Vec = card_parts(&h).iter().filter(|e| moving(e)).map(|e| format!("{} {:?} exiting {} {:?}->{:?}", e.path, e.opacity, e.exiting, e.rect, e.target)).collect(); + assert!(fading.is_empty(), "with the card from row {top}, parts of it fade or move: {fading:#?}"); + let slots = h.keys().into_iter().filter(|k| k.contains("/slot-")).count(); + assert_eq!(slots, 1, "with the card from row {top}, one copy is drawn"); + } +} + +/// A model with a long name keeps its switch inside its row, on the page and in the picker. +#[test] +fn a_long_model_name_keeps_the_switch_in_its_row() { + use crate::claude::subagents::{Agent, AgentModel}; + let mut h = Harness::new(|_| vec![]); + h.step(|ws| { + ws.model_lookups.list = |_, _| Ok(vec![AgentModel { id: "openrouter/a-very-long-model".into(), name: "openrouter/A Very Long Model Name That Goes On And On Past Any Reasonable Width For A Row".into() }]); + ws.act(Act::OpenSettings); + ws.set_settings_page(SettingsPage::CustomSubagents); + }); + 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] + }; + 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"); +} + +/// 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. +#[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 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")], + }) + }; + 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"); + 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.settle(); + h.click("model-picker-gpt-6.1-sol"); + 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"); + + // OpenCode's picker 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.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"); + h.press(rune::Key::Enter, |_| {}); + h.settle(); + assert!(!h.drawn("model-picker"), "Enter in the search closes the picker"); + 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)); + + // 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.settle(); + h.click("settings-codex-choose"); + 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"); + h.click("model-picker-gpt-6.1-sol"); + h.click("model-picker-done"); + h.settle(); + assert!(!h.drawn("settings-codex-model-gpt-6.1-sol"), "switched off, it leaves the page"); + 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" }; + std::fs::write(&printer, script).unwrap(); + #[cfg(unix)] + std::fs::set_permissions(&printer, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); + let cwd = h.work.clone(); + h.step(|ws| { + ws.claude_exe = Some(printer); + ws.new_claude(cwd); + }); + let id = h.ws().active.clone().expect("a session is shown"); + 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."#) + }); +} diff --git a/src/app/input.rs b/src/app/input.rs index b4acb43..5b89fa8 100644 --- a/src/app/input.rs +++ b/src/app/input.rs @@ -198,6 +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" 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 8b673de..734d2d7 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -16,6 +16,7 @@ use crate::panels::sidebar::{SIDEBAR_MAX, SIDEBAR_MIN, SIDEBAR_W}; use crate::github::view::{GhEvent, GithubView}; use crate::claude::defaults::{Effort, PermissionMode, Starter}; use crate::claude::mcp; +use crate::claude::subagents::Agent; use crate::git::worktree::Base; use crate::platform::{self, Editor}; use crate::{claude::usage, datadir}; @@ -70,7 +71,7 @@ pub use editing::Conflict; pub use file_ops::NameFor; pub use editor_mode::{EditorCommand, EditorPane}; pub use lifecycle::{saved_window_geom, set_main_window, show_main_window}; -pub use settings::SettingsPage; +pub use settings::{Lookup, SettingsPage}; pub use setup::open_first_setup; /// Every user-triggerable operation, so buttons, menus and shortcuts share one code path. @@ -301,10 +302,45 @@ pub enum Modal { hints: [String; 4], /// The project being renamed on the Projects page, and the name typed so far. renaming: Option<(Id, TextEdit)>, + /// The Custom subagents page. + subagents: SubagentsForm, }, } -/// A field of the open modal, by its place: the dialog's only field is 0; Settings' are shell, claude, model, skills. +/// 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 picking: Option<(Agent, TextEdit)>, +} + +/// One agent's part of the Custom subagents page. +pub struct AgentForm { + pub on: bool, + /// The ids of the models switched on. + pub models: Vec, + pub edits: bool, +} + +impl SubagentsForm { + pub fn get(&self, agent: Agent) -> &AgentForm { + match agent { + Agent::Codex => &self.codex, + Agent::OpenCode => &self.opencode, + } + } + + pub fn get_mut(&mut self, agent: Agent) -> &mut AgentForm { + match agent { + Agent::Codex => &mut self.codex, + Agent::OpenCode => &mut self.opencode, + } + } +} + +/// 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. 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), @@ -313,6 +349,7 @@ pub fn modal_field(modal: &mut Option, n: usize) -> Option<&mut TextEdit> (Modal::Settings { model, .. }, 2) => Some(model), (Modal::Settings { skills_field, .. }, 3) => Some(skills_field), (Modal::Settings { renaming: Some((_, name)), .. }, 4) => Some(name), + (Modal::Settings { subagents: SubagentsForm { picking: Some((_, search)), .. }, .. }, 5) => Some(search), _ => None, } } @@ -443,6 +480,8 @@ pub struct Workspace { pub settings_page: SettingsPage, /// What the Worktrees page of Settings shows. Not saved to disk. 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, pub menu: Option, pub menu_serial: u64, pub toast: Option, @@ -536,6 +575,7 @@ impl Workspace { modal_serial: 0, settings_page: SettingsPage::default(), worktrees_page: Default::default(), + model_lookups: Default::default(), menu: None, menu_serial: 0, toast: None, @@ -749,8 +789,12 @@ impl Workspace { let skills_field = modal::field(&self.store.data.settings.limits.text(), false); let hints = [platform::default_shell(None).0, claude_hint, "Claude Code default".into(), "none, e.g. dataviz, claude-api".into()]; 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 }; + 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); - 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 }); self.modal_serial += 1; } Act::PickEffort(choice) => { diff --git a/src/app/modal.rs b/src/app/modal.rs index d4010af..6d75678 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -94,7 +94,7 @@ impl Workspace { } } } - Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }) => { + Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }) => { let clean = |s: &str| s.trim().trim_matches('"').to_string(); let (shell_t, claude_t) = (clean(&shell.text), clean(&claude.text)); let model_name = claude::defaults::parse_model(&model.text); @@ -109,7 +109,7 @@ impl Workspace { let bad_limits = limits.as_ref().err().map(|why| (SettingsPage::ClaudeTools, 3, why.clone())); if let Some((page, field, msg)) = paths.or(bad_model).or(bad_limits) { self.settings_page = page; - self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }); + self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }); if let Some(f) = modal_field(&mut self.modal, field) { f.focused = true; } @@ -150,16 +150,26 @@ 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 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; s.limits = limits; s.claudiu_tools_off = claudiu_off; + s.custom_subagents = custom_subagents; crate::panels::scale::set(scale); self.shell = platform::default_shell(s.shell.as_deref()); self.claude_exe = claude::discover(s.claude_path.as_deref()); self.store.mark_dirty(); if let Some(e) = trim_error { self.toast(format!("Settings saved, but Claude Code's settings.json could not be changed ({e}), so the tool trims stay as they were."), true); + } else if subagents_changed && !tools_changed { + self.toast("Settings saved. Custom subagents apply to new and resumed sessions.", false); } else if tools_changed { self.toast("Settings saved. Tool changes apply to new sessions; resumed sessions keep the old instructions until their next compaction.", false); } else { diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 9f90523..b491bc2 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -36,6 +36,13 @@ impl Workspace { spec.env.push((usage::CTL_ENV.into(), usage::ctl_file(record_id).to_string_lossy().into_owned())); spec.env.push((crate::visual::VISUAL_ENV.into(), crate::visual::prefix(record_id).to_string_lossy().into_owned())); spec.env.push((crate::claude::ask::ASK_ENV.into(), crate::claude::ask::request_file(record_id).to_string_lossy().into_owned())); + // The mod registers the agent types and answers their turns, so they go only where it loads. + if let Some(subagents) = settings.custom_subagents.env() + && let Ok(exe) = std::env::current_exe() + { + spec.env.push((crate::claude::subagents::ENV.into(), subagents)); + spec.env.push((crate::claude::subagents::EXE_ENV.into(), exe.to_string_lossy().into_owned())); + } } if chrome { spec.args.push("--chrome".into()); diff --git a/src/app/settings.rs b/src/app/settings.rs index 2507437..87c0b35 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -1,6 +1,7 @@ //! The pages of the Settings dialog and its keyboard handling. use super::*; +use crate::claude::subagents::Agent; use crate::terminal::keys::Keystroke; /// A category in the Settings dialog's list, in display order. @@ -12,12 +13,13 @@ pub enum SettingsPage { Projects, ClaudeTools, ClaudiuTools, + CustomSubagents, Worktrees, About, } impl SettingsPage { - pub const ALL: [SettingsPage; 7] = [Self::General, Self::Sessions, Self::Projects, Self::ClaudeTools, Self::ClaudiuTools, Self::Worktrees, Self::About]; + pub const ALL: [SettingsPage; 8] = [Self::General, Self::Sessions, Self::Projects, Self::ClaudeTools, Self::ClaudiuTools, Self::CustomSubagents, Self::Worktrees, Self::About]; pub fn label(self) -> &'static str { match self { @@ -26,6 +28,7 @@ impl SettingsPage { Self::Projects => "Projects", Self::ClaudeTools => "Claude Code tools", Self::ClaudiuTools => "Claudiu tools", + Self::CustomSubagents => "Custom subagents", Self::Worktrees => "Worktrees", Self::About => "About", } @@ -44,10 +47,104 @@ impl SettingsPage { } } +/// One agent's model lookup for the Custom subagents page. +#[derive(Default)] +pub struct Lookup { + pub loading: bool, + /// Why the last lookup failed. + pub error: Option, +} + +/// The Custom subagents page's lookups of each agent's models. +pub struct ModelLookups { + codex: Lookup, + opencode: Lookup, + /// 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 } + } +} + +impl ModelLookups { + pub fn get(&self, agent: Agent) -> &Lookup { + match agent { + Agent::Codex => &self.codex, + Agent::OpenCode => &self.opencode, + } + } + + fn get_mut(&mut self, agent: Agent) -> &mut Lookup { + match agent { + Agent::Codex => &mut self.codex, + Agent::OpenCode => &mut self.opencode, + } + } +} + impl Workspace { + /// Asks each agent switched on for its models in the background while the Custom subagents page shows. The list + /// the page showed last stays until the answer comes; a failure keeps it and says why. + pub(crate) fn load_models(&mut self) { + if self.settings_page != SettingsPage::CustomSubagents { + return; + } + let Some(Modal::Settings { subagents, .. }) = &self.modal else { return }; + let wanted: Vec = Agent::ALL.into_iter().filter(|a| subagents.get(*a).on && !self.model_lookups.get(*a).loading).collect(); + for agent in wanted { + self.model_lookups.get_mut(agent).loading = true; + let list = self.model_lookups.list; + let folder = crate::datadir::data_dir(); + self.rt.spawn( + move || list(agent, &folder), + move |ws: &mut Workspace, found| { + let lookup = ws.model_lookups.get_mut(agent); + lookup.loading = false; + match found { + Ok(models) => { + lookup.error = None; + let catalog = &mut ws.store.data.settings.custom_subagents.get_mut(agent).catalog; + if *catalog != models { + *catalog = models; + ws.store.mark_dirty(); + } + } + Err(why) => lookup.error = Some(why), + } + }, + ); + } + } + + /// 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) { + 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) { + if let Some(Modal::Settings { subagents, .. }) = self.modal.as_mut() { + subagents.picking = None; + } + self.blur = true; + } + + pub(crate) fn model_picker_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() { + return false; + } let fields: &[usize] = match self.settings_page { SettingsPage::General => &[0, 1], SettingsPage::Sessions => &[2], @@ -88,7 +185,8 @@ mod tests { #[test] fn next_and_prev_walk_the_list_and_stop_at_the_ends() { assert_eq!(General.next(), Sessions); - assert_eq!(ClaudiuTools.next(), Worktrees); + assert_eq!(ClaudiuTools.next(), CustomSubagents); + assert_eq!(CustomSubagents.next(), Worktrees); assert_eq!(Worktrees.next(), About); assert_eq!(About.next(), About); assert_eq!(About.prev(), Worktrees); diff --git a/src/app/worktrees.rs b/src/app/worktrees.rs index 132949a..4f08fbc 100644 --- a/src/app/worktrees.rs +++ b/src/app/worktrees.rs @@ -35,6 +35,7 @@ impl Workspace { if page == SettingsPage::Worktrees { self.load_stored_worktrees(); } + self.load_models(); } pub(super) fn load_stored_worktrees(&mut self) { diff --git a/src/claude/acp.rs b/src/claude/acp.rs new file mode 100644 index 0000000..ca7ebe5 --- /dev/null +++ b/src/claude/acp.rs @@ -0,0 +1,697 @@ +//! Runs one task in Codex or OpenCode for a custom subagent (`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 +//! child's stdin only once, and ACP is a conversation in both directions, so the conversation happens here. Progress +//! goes to stdout as JSON lines (`Event`), ending with the report or the reason it failed. +//! +//! Codex runs through `npx codex-acp`, which uses the user's own `codex login`; OpenCode runs as the user's own +//! `opencode acp`, with their providers. The agent's stdin is a pipe from this process, so when the mod stops this +//! helper (the user interrupted the subagent), the pipe closes and the agent exits with it. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::thread::JoinHandle; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::claude::subagents::{Agent, AgentModel}; + +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. +const STDERR_LINES: usize = 5; +/// How long the settings page waits for the agent's models; Codex's first run downloads codex-acp through npx. +const MODELS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + +/// What the mod asks for. +#[derive(Debug, Deserialize)] +pub struct Request { + /// The agent that runs the task. A mod from before OpenCode sends none, and means Codex. + #[serde(default)] + pub agent: Agent, + /// The agent's model; none for the agent's own default. + pub model: Option, + /// Whether the agent may edit files and run commands, or only read. + pub edits: bool, + /// The folder the agent works in. + pub cwd: PathBuf, + /// The task, as Claude wrote it. + pub prompt: String, +} + +/// One line of stdout. +#[derive(Debug, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Event { + /// A piece of a message the agent is writing. + Text { text: String }, + /// A tool call the agent started: a command, a read, an edit. + Step { text: String }, + /// The last message the agent wrote: the subagent's report. + Report { text: String }, + Failed { reason: String }, +} + +pub fn run() -> i32 { + let mut out = std::io::stdout().lock(); + let mut emit = |event: Event| { + if let Ok(line) = serde_json::to_string(&event) { + let _ = writeln!(out, "{line}"); + let _ = out.flush(); + } + }; + let mut input = String::new(); + let request = std::io::stdin().read_to_string(&mut input).map_err(|e| e.to_string()).and_then(|_| serde_json::from_str::(&input).map_err(|e| e.to_string())); + let request = match request { + Ok(r) => r, + Err(e) => { + emit(Event::Failed { reason: format!("the task could not be read ({e})") }); + return 1; + } + }; + let finished = run_task(&request, &mut emit); + emit(match finished { + Ok(text) => Event::Report { text }, + Err(reason) => Event::Failed { reason }, + }); + 0 +} + +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(model) = &request.model { + env.push(("CODEX_CONFIG", json!({ "model": model }).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 result = converse(connection.from_agent, connection.to_agent, request, emit); + connection.process.finish(result) +} + +/// The tools OpenCode may use read-only: reading and searching files. Everything else, the shell included, is denied, +/// since OpenCode has no sandbox that would let a command run without changing anything. +fn opencode_read_only() -> Value { + json!({ "*": "deny", "read": "allow", "glob": "allow", "grep": "allow", "list": "allow" }) +} + +/// The config OpenCode gets on top of the user's own. Read-only pins the `build` agent and denies under it too, +/// because an agent's own permissions in a project's or the user's opencode.json beat the top-level ones. +fn opencode_config(model: Option<&str>, edits: bool) -> Value { + let mut config = json!({}); + if let Some(model) = model { + config["model"] = json!(model); + } + if !edits { + config["default_agent"] = json!("build"); + config["permission"] = opencode_read_only(); + config["agent"] = json!({ "build": { "permission": opencode_read_only() } }); + } + config +} + +/// 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 { 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. + std::thread::spawn(move || { + let _ = tx.send(list_models(agent, from_agent, to_agent, &folder)); + }); + let result = rx.recv_timeout(MODELS_TIMEOUT).unwrap_or_else(|_| Err(format!("{} didn't answer within {} seconds", server(agent), MODELS_TIMEOUT.as_secs()))); + process.finish(result) +} + +/// 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", + } +} + +fn exited(agent: Agent) -> String { + format!("{} exited before {} answered", server(agent), agent.name()) +} + +/// A running agent: its pipes, and the process with its stderr. +struct Connection { + to_agent: ChildStdin, + from_agent: BufReader, + process: Process, +} + +struct Process { + agent: Agent, + child: Child, + /// The last lines of stderr, collected on a thread so a full stderr pipe can't stall the agent. + errors: JoinHandle, +} + +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 = which::which(program).map_err(|_| missing.to_string())?; + let mut command = Command::new(program); + command.args(args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + for (key, value) in env { + command.env(key, value); + } + let name = server(agent); + let mut child = command.spawn().map_err(|e| format!("{name} could not start ({e})"))?; + let (Some(to_agent), Some(from_agent), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take()) else { + let _ = child.kill(); + return Err(format!("{name} could not start (no pipes)")); + }; + let errors = std::thread::spawn(move || { + let mut last: Vec = vec![]; + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if !line.trim().is_empty() { + last.push(line); + if last.len() > STDERR_LINES { + last.remove(0); + } + } + } + last.join("\n") + }); + Ok(Connection { to_agent, from_agent: BufReader::new(from_agent), process: Process { agent, child, errors } }) + } +} + +impl Process { + /// Ends the agent once the conversation is over (its stdin is already closed) and returns `result`, with + /// stderr's last lines added when the agent exited early. + fn finish(mut self, result: Result) -> Result { + let _ = self.child.kill(); + let _ = self.child.wait(); + // Only an early exit needs stderr's last lines. Waiting for stderr to close otherwise could hold up the answer + // while something the agent started still has it open. + let exited = exited(self.agent); + match result { + Err(reason) if reason == exited => { + let stderr = self.errors.join().unwrap_or_default(); + Err(if stderr.is_empty() { reason } else { format!("{exited}: {stderr}") }) + } + other => other, + } + } +} + +fn initialize() -> Value { + json!({ "jsonrpc": "2.0", "id": 0, "method": "initialize", "params": { + "protocolVersion": 1, + "clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false }, + "clientInfo": { "name": "claudiu", "version": env!("CARGO_PKG_VERSION") }, + }}) +} + +fn new_session(cwd: &Path) -> Value { + json!({ "jsonrpc": "2.0", "id": 1, "method": "session/new", "params": { "cwd": cwd, "mcpServers": [] } }) +} + +/// Opens a session only to read its model picker: the config option whose category is `model`. OpenCode keeps every +/// session in its history, so it deletes this empty one again. +fn list_models(agent: Agent, from_agent: impl BufRead, mut to_agent: impl Write, cwd: &Path) -> Result, String> { + let mut lines = from_agent.lines(); + let mut send = |message: Value| writeln!(to_agent, "{message}").and_then(|_| to_agent.flush()).map_err(|_| exited(agent)); + let mut reply = |id: i64| -> Result { + for line in lines.by_ref() { + let msg: Value = serde_json::from_str(&line.map_err(|_| exited(agent))?).unwrap_or_default(); + if msg.get("method").is_none() && msg["id"].as_i64() == Some(id) { + return match msg.get("error") { + Some(error) => Err(error_reason(agent, error)), + None => Ok(msg["result"].clone()), + }; + } + } + Err(exited(agent)) + }; + send(initialize())?; + reply(0)?; + send(new_session(cwd))?; + let session = reply(1)?; + let options = session["configOptions"].as_array().into_iter().flatten(); + let picker = options.filter(|o| o["category"] == "model").find_map(|o| o["options"].as_array()); + let models: Vec = picker + .into_iter() + .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 + && 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() + { + let _ = reply(2); + } + if models.is_empty() { Err(format!("{} listed no models", server(agent))) } else { Ok(models) } +} + +/// The ACP conversation for one task: start, open a session in the task's folder, send the task, and follow the +/// session's updates until the agent answers. Returns the last message the agent wrote. +fn converse(from_agent: impl BufRead, mut to_agent: impl Write, request: &Request, emit: &mut impl FnMut(Event)) -> Result { + let agent = request.agent; + let name = agent.name(); + let mut lines = from_agent.lines(); + let send = |to_agent: &mut dyn Write, message: Value| -> Result<(), String> { writeln!(to_agent, "{message}").and_then(|_| to_agent.flush()).map_err(|_| exited(agent)) }; + let mut messages = Messages::default(); + // What read-only refused last: codex-acp offers only "cancel" for some commands, which ends Codex's turn. + let mut refused: Option = None; + // Waits for the answer to request `id`, handling what the agent sends meanwhile. Only updates of `session` count: + // OpenCode also reports the sessions of its own subagents, whose messages are not this task's report. + let mut answer = |to_agent: &mut dyn Write, id: i64, session: Option<&str>, messages: &mut Messages, emit: &mut dyn FnMut(Event)| -> Result { + for line in lines.by_ref() { + let line = line.map_err(|_| exited(agent))?; + let Ok(msg) = serde_json::from_str::(&line) else { continue }; + if msg.get("method").is_none() && msg["id"].as_i64() == Some(id) { + return match msg.get("error") { + Some(error) => Err(error_reason(agent, error)), + None => Ok(msg["result"].clone()), + }; + } + match msg["method"].as_str() { + Some("session/update") => { + if session.is_some_and(|s| msg["params"]["sessionId"] == s) { + messages.update(&msg["params"]["update"], emit); + } + } + Some("session/request_permission") => { + let outcome = permission(&msg["params"]["options"], request.edits); + if !request.edits { + refused = Some(msg["params"]["toolCall"]["title"].as_str().unwrap_or("an action").to_string()); + } + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "result": { "outcome": outcome } }))?; + } + // A request this client doesn't serve: it offered no file or terminal access. + Some(_) if msg.get("id").is_some() => { + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "error": { "code": -32601, "message": "method not found" } }))?; + } + _ => {} + } + } + Err(exited(agent)) + }; + + send(&mut to_agent, initialize())?; + answer(&mut to_agent, 0, None, &mut messages, emit)?; + + send(&mut to_agent, new_session(&request.cwd))?; + let session = answer(&mut to_agent, 1, None, &mut messages, emit)?; + let session_id = session["sessionId"].as_str().ok_or(format!("{} opened no session", server(agent)))?.to_string(); + + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": 2, "method": "session/prompt", "params": { + "sessionId": session_id, + "prompt": [{ "type": "text", "text": request.prompt }], + }}))?; + let done = answer(&mut to_agent, 2, Some(&session_id), &mut messages, emit)?; + let stop = done["stopReason"].as_str().unwrap_or("end_turn"); + match (stop, messages.last()) { + ("end_turn", Some(text)) => Ok(text), + ("end_turn", None) => Err(format!("{name} finished without writing a report")), + ("cancelled", _) => Err(match refused { + Some(action) => format!("{name} stopped when read-only mode refused `{action}`. Turn on Allow edits in Settings → Custom subagents to let it."), + None => format!("{name}'s turn was cancelled"), + }), + ("refusal", _) => Err(format!("{name} refused the task")), + // Out of tokens or turns: what the agent wrote last is still the best report there is. + (_, Some(text)) => Ok(text), + (other, None) => Err(format!("{name} stopped ({other}) without writing a report")), + } +} + +/// The messages the agent wrote in this run, as their pieces arrive. A message ends where a tool call starts or +/// another message begins. +#[derive(Default)] +struct Messages { + current: String, + current_id: Option, + last: Option, +} + +impl Messages { + fn update(&mut self, update: &Value, emit: &mut dyn FnMut(Event)) { + match update["sessionUpdate"].as_str() { + Some("agent_message_chunk") => { + let Some(text) = update["content"]["text"].as_str() else { return }; + let id = update["messageId"].as_str().map(String::from); + if id.is_some() && id != self.current_id { + self.close(); + self.current_id = id; + } + self.current.push_str(text); + emit(Event::Text { text: text.to_string() }); + } + Some("tool_call") => { + self.close(); + let title = update["title"].as_str().unwrap_or("a tool"); + emit(Event::Step { text: title.to_string() }); + } + _ => {} + } + } + + /// Ends the message being written; a blank one doesn't replace the last. + fn close(&mut self) { + let text = std::mem::take(&mut self.current); + if !text.trim().is_empty() { + self.last = Some(text); + } + self.current_id = None; + } + + fn last(&mut self) -> Option { + self.close(); + self.last.clone() + } +} + +/// The answer to a permission request: an allowing option when edits are on, a refusing one when they are off. +/// codex-acp offers two refusals of the same kind: `decline` lets Codex carry on without the action, `cancel` ends its +/// turn, so `decline` comes first. Without a fitting option the request is answered as cancelled, which refuses it too. +fn permission(options: &Value, edits: bool) -> Value { + let options: Vec<&Value> = options.as_array().into_iter().flatten().collect(); + let of_kind = |kinds: &[&str]| options.iter().copied().find(|o| o["kind"].as_str().is_some_and(|k| kinds.contains(&k))); + let chosen = if edits { + of_kind(&["allow_once", "allow_always"]) + } else { + options.iter().copied().find(|o| o["optionId"] == "decline").or_else(|| of_kind(&["reject_once", "reject_always"])) + }; + match chosen.and_then(|o| o["optionId"].as_str()) { + Some(id) => json!({ "outcome": "selected", "optionId": id }), + None => json!({ "outcome": "cancelled" }), + } +} + +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(), + }; + } + let server = server(agent); + match error["message"].as_str() { + Some(message) => format!("{server}: {message}"), + None => format!("{server}: {error}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(agent: Agent, edits: bool) -> Request { + Request { agent, model: Some("gpt-5.5".into()), edits, cwd: PathBuf::from("/work"), prompt: "Find the bug".into() } + } + + fn update(update: Value) -> Value { + json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "sessionId": "s1", "update": update } }) + } + + fn chunk(id: &str, text: &str) -> Value { + update(json!({ "sessionUpdate": "agent_message_chunk", "messageId": id, "content": { "type": "text", "text": text } })) + } + + fn reply(id: i64, result: Value) -> Value { + json!({ "jsonrpc": "2.0", "id": id, "result": result }) + } + + /// 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) { + let script: String = agent_says.iter().map(|m| format!("{m}\n")).collect(); + let mut sent = Vec::new(); + let mut events = vec![]; + let result = converse(script.as_bytes(), &mut sent, &request(agent, edits), &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) + } + + fn talk(agent_says: &[Value], edits: bool) -> (Result, Vec, Vec) { + talk_to(Agent::Codex, agent_says, edits) + } + + fn opening() -> Vec { + vec![reply(0, json!({ "protocolVersion": 1 })), reply(1, json!({ "sessionId": "s1" }))] + } + + #[test] + fn the_report_is_the_last_message_and_every_piece_streams() { + let mut says = opening(); + says.extend([ + chunk("m1", "Looking at "), + chunk("m1", "the parser."), + update(json!({ "sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Read src/parse.rs", "kind": "read", "status": "pending" })), + chunk("m2", "The bug is on line 12."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (result, sent, events) = talk(&says, false); + assert_eq!(result, Ok("The bug is on line 12.".into())); + assert_eq!( + events, + vec![ + Event::Text { text: "Looking at ".into() }, + Event::Text { text: "the parser.".into() }, + Event::Step { text: "Read src/parse.rs".into() }, + Event::Text { text: "The bug is on line 12.".into() }, + ] + ); + assert_eq!(sent.iter().map(|m| m["method"].as_str().unwrap()).collect::>(), ["initialize", "session/new", "session/prompt"]); + assert_eq!(sent[1]["params"]["cwd"], "/work"); + assert_eq!(sent[2]["params"]["sessionId"], "s1"); + assert_eq!(sent[2]["params"]["prompt"][0]["text"], "Find the bug"); + assert_eq!(sent[0]["params"]["clientCapabilities"]["terminal"], false); + } + + #[test] + fn messages_without_ids_split_at_tool_calls() { + let mut says = opening(); + says.extend([ + update(json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "First." } })), + update(json!({ "sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Ran ls" })), + update(json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "Second." } })), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + assert_eq!(talk(&says, false).0, Ok("Second.".into())); + } + + #[test] + fn a_child_session_message_is_not_the_report() { + let mut says = opening(); + says.extend([ + chunk("m1", "Asked a helper."), + json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "sessionId": "child", "update": { + "sessionUpdate": "agent_message_chunk", "messageId": "c1", "content": { "type": "text", "text": "Helper notes." } } } }), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (result, _, events) = talk_to(Agent::OpenCode, &says, true); + assert_eq!(result, Ok("Asked a helper.".into())); + assert_eq!(events, vec![Event::Text { text: "Asked a helper.".into() }]); + } + + fn asks_permission() -> Vec { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 7, "method": "session/request_permission", "params": { "sessionId": "s1", "toolCall": { "toolCallId": "c1" }, "options": [ + { "optionId": "yes", "name": "Allow once", "kind": "allow_once" }, + { "optionId": "no", "name": "Reject", "kind": "reject_once" }, + ]}}), + chunk("m1", "Done."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + says + } + + #[test] + fn a_turn_ended_by_a_refusal_says_what_was_refused() { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 0, "method": "session/request_permission", "params": { "sessionId": "s1", + "toolCall": { "toolCallId": "c1", "title": "printf hi > made.txt" }, + "options": [{ "optionId": "allow_once", "kind": "allow_once" }, { "optionId": "cancel", "kind": "reject_once" }] } }), + reply(2, json!({ "stopReason": "cancelled" })), + ]); + let (result, sent, _) = talk(&says, false); + assert_eq!( + result, + Err("Codex stopped when read-only mode refused `printf hi > made.txt`. Turn on Allow edits in Settings → Custom subagents to let it.".into()) + ); + assert_eq!(sent.last().unwrap()["result"]["outcome"]["optionId"], "cancel"); + } + + #[test] + fn read_only_refuses_permission_requests() { + let (_, sent, _) = talk(&asks_permission(), false); + let answer = sent.iter().find(|m| m["id"] == 7).unwrap(); + assert_eq!(answer["result"]["outcome"], json!({ "outcome": "selected", "optionId": "no" })); + } + + #[test] + fn with_edits_on_permission_requests_are_allowed() { + let (_, sent, _) = talk(&asks_permission(), true); + let answer = sent.iter().find(|m| m["id"] == 7).unwrap(); + assert_eq!(answer["result"]["outcome"], json!({ "outcome": "selected", "optionId": "yes" })); + } + + #[test] + fn read_only_declines_rather_than_ending_codex_turn() { + let options = json!([ + { "optionId": "allow_once", "kind": "allow_once" }, + { "optionId": "cancel", "kind": "reject_once" }, + { "optionId": "decline", "kind": "reject_once" }, + ]); + assert_eq!(permission(&options, false), json!({ "outcome": "selected", "optionId": "decline" })); + } + + #[test] + fn opencode_permission_options_are_answered_by_kind() { + // What opencode 2.3 offers. + let options = json!([ + { "optionId": "once", "kind": "allow_once", "name": "Allow once" }, + { "optionId": "always", "kind": "allow_always", "name": "Always allow" }, + { "optionId": "reject", "kind": "reject_once", "name": "Reject" }, + ]); + assert_eq!(permission(&options, false), json!({ "outcome": "selected", "optionId": "reject" })); + assert_eq!(permission(&options, true), json!({ "outcome": "selected", "optionId": "once" })); + } + + #[test] + fn a_permission_request_with_no_refusing_option_is_cancelled() { + let options = json!([{ "optionId": "yes", "kind": "allow_once" }]); + assert_eq!(permission(&options, false), json!({ "outcome": "cancelled" })); + } + + #[test] + fn file_and_terminal_requests_are_refused() { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 9, "method": "fs/write_text_file", "params": { "sessionId": "s1", "path": "/etc/x", "content": "" } }), + chunk("m1", "Done."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (result, sent, _) = talk(&says, true); + assert_eq!(result, Ok("Done.".into())); + assert_eq!(sent.iter().find(|m| m["id"] == 9).unwrap()["error"]["code"], -32601); + } + + #[test] + fn signed_out_says_how_to_sign_in() { + let says = vec![ + reply(0, json!({ "protocolVersion": 1 })), + json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": "Authentication required" } }), + ]; + assert_eq!(talk(&says, false).0, Err("Codex isn't signed in. Run `codex login`, then try again.".into())); + assert_eq!(talk_to(Agent::OpenCode, &says, false).0, Err("OpenCode isn't signed in. Run `opencode auth login`, then try again.".into())); + } + + #[test] + fn an_agent_that_exits_midway_fails() { + let mut says = opening(); + says.push(chunk("m1", "Starting")); + assert_eq!(talk(&says, false).0, Err("codex-acp exited before Codex answered".into())); + assert_eq!(talk_to(Agent::OpenCode, &says, false).0, Err("opencode exited before OpenCode answered".into())); + } + + #[test] + fn a_turn_without_a_message_fails() { + let mut says = opening(); + says.push(reply(2, json!({ "stopReason": "end_turn" }))); + assert_eq!(talk(&says, false).0, Err("Codex finished without writing a report".into())); + assert_eq!(talk_to(Agent::OpenCode, &says, false).0, Err("OpenCode finished without writing a report".into())); + } + + #[test] + fn running_out_of_tokens_still_reports_the_last_message() { + let mut says = opening(); + says.extend([chunk("m1", "Partial findings."), reply(2, json!({ "stopReason": "max_tokens" }))]); + assert_eq!(talk(&says, false).0, Ok("Partial findings.".into())); + } + + #[test] + fn read_only_opencode_denies_all_but_reading_even_in_its_build_agent() { + let read_only = json!({ "*": "deny", "read": "allow", "glob": "allow", "grep": "allow", "list": "allow" }); + assert_eq!( + opencode_config(Some("openai/gpt-6.1-sol"), false), + json!({ "model": "openai/gpt-6.1-sol", "default_agent": "build", "permission": read_only, "agent": { "build": { "permission": read_only } } }) + ); + assert_eq!(opencode_config(Some("openai/gpt-6.1-sol"), true), json!({ "model": "openai/gpt-6.1-sol" })); + assert_eq!(opencode_config(None, true), json!({})); + } + + #[test] + fn a_request_without_an_agent_is_for_codex() { + let r: Request = serde_json::from_value(json!({ "model": "gpt-5.5", "edits": false, "cwd": "/w", "prompt": "x" })).unwrap(); + assert_eq!(r.agent, Agent::Codex); + let r: Request = serde_json::from_value(json!({ "agent": "opencode", "model": "openai/gpt-5.5", "edits": false, "cwd": "/w", "prompt": "x" })).unwrap(); + assert_eq!(r.agent, Agent::OpenCode); + } + + fn picker_session() -> Value { + reply(1, json!({ "sessionId": "s1", "configOptions": [ + { "id": "mode", "category": "mode", "options": [{ "value": "read-only", "name": "Read-only" }] }, + { "id": "model", "category": "model", "options": [ + { "value": "gpt-6.1-sol", "name": "6.1 Sol" }, + { "value": "gpt-5.6-luna", "name": "5.6 Luna" }, + ]}, + ]})) + } + + fn list(agent: Agent, says: &[Value]) -> (Result, String>, Vec) { + let script: String = says.iter().map(|m| format!("{m}\n")).collect(); + let mut sent = Vec::new(); + let models = list_models(agent, script.as_bytes(), &mut sent, Path::new("/work")); + (models, String::from_utf8(sent).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect()) + } + + #[test] + fn the_models_come_from_the_session_model_picker() { + let says = [reply(0, json!({ "protocolVersion": 1 })), update(json!({ "sessionUpdate": "available_commands_update", "availableCommands": [] })), picker_session()]; + let (models, sent) = list(Agent::Codex, &says); + assert_eq!( + models.unwrap(), + vec![AgentModel { id: "gpt-6.1-sol".into(), name: "6.1 Sol".into() }, AgentModel { id: "gpt-5.6-luna".into(), name: "5.6 Luna".into() }] + ); + 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 opencode_deletes_the_session_it_read_the_models_from() { + let says = [reply(0, json!({ "protocolVersion": 1 })), picker_session(), reply(2, json!({}))]; + let (models, sent) = list(Agent::OpenCode, &says); + assert_eq!(models.unwrap().len(), 2); + assert_eq!(sent.iter().map(|m| m["method"].as_str().unwrap()).collect::>(), ["initialize", "session/new", "session/delete"]); + assert_eq!(sent[2]["params"]["sessionId"], "s1"); + // A delete opencode refuses, or never answers before exiting, still gives the models. + let says = [reply(0, json!({ "protocolVersion": 1 })), picker_session()]; + assert_eq!(list(Agent::OpenCode, &says).0.unwrap().len(), 2); + } + + #[test] + fn no_model_picker_is_an_error() { + let says = [reply(0, json!({})), reply(1, json!({ "sessionId": "s1" }))]; + assert_eq!(list(Agent::Codex, &says).0, Err("codex-acp listed no models".into())); + assert_eq!(list(Agent::OpenCode, &says).0, Err("opencode listed no models".into())); + } + + #[test] + fn events_are_json_lines_the_mod_reads() { + assert_eq!(serde_json::to_value(Event::Step { text: "Ran ls".into() }).unwrap(), json!({ "kind": "step", "text": "Ran ls" })); + assert_eq!(serde_json::to_value(Event::Failed { reason: "x".into() }).unwrap(), json!({ "kind": "failed", "reason": "x" })); + } +} diff --git a/src/claude/mcp.rs b/src/claude/mcp.rs index 2250235..4becb29 100644 --- a/src/claude/mcp.rs +++ b/src/claude/mcp.rs @@ -112,9 +112,11 @@ Claude Code session (the user says so, or you recognise it), find it with search call unlink_session when a link no longer fits. Both are silent."; /// What makes the model call `show_visual` (the tool's own description teaches the dialect, and stays deferred). -const VISUAL_INSTRUCTIONS: &str = " Visual: show_visual draws a card inside this terminal, under the call. Most replies need \ -none. When a reply does need a visual (a table, comparison, flow, architecture, before/after, status board or chart), prefer \ -show_visual over drawing it in text, unasked (private, no approval), and reply in a few lines."; +const VISUAL_INSTRUCTIONS: &str = " Visual: show_visual draws a card inside this terminal, under the call. Call it unasked \ +whenever a reply would contain a table, a comparison, three or more items that each have details, steps or a flow, an \ +architecture, a before/after, a status board or numbers worth a chart. A card is easier to read than the same thing typed \ +as text, and it is private and needs no approval. Put that part in the card and keep the typed reply to a few lines. A \ +short answer, a one-line fact or a code change needs no card."; const ARTIFACT_INSTRUCTIONS: &str = " Artifacts are for pages to share."; diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 839090b..2856d9e 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -9,6 +9,7 @@ //! per-session config) and `plugin` (the mod Claudiu ships). pub mod accounts; +pub mod acp; pub mod ask; pub mod bridge; pub mod config_sync; @@ -16,6 +17,7 @@ pub mod costly; pub mod defaults; pub mod mcp; pub mod plugin; +pub mod subagents; pub mod trim; pub mod usage; diff --git a/src/claude/subagents.rs b/src/claude/subagents.rs new file mode 100644 index 0000000..6e2c686 --- /dev/null +++ b/src/claude/subagents.rs @@ -0,0 +1,308 @@ +//! Custom subagents: agent types that run a task in another coding agent instead of Claude (Settings → Custom +//! subagents): OpenAI Codex and OpenCode. +//! +//! 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 serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; + +/// The agent types the mod answers for, as JSON. Absent when no custom subagent is on. +pub const ENV: &str = "CLAUDIU_SUBAGENTS"; +/// The path of this executable, which the mod runs as ` --acp`. +pub const EXE_ENV: &str = "CLAUDIU_EXE"; + +/// Claude Code takes up to 64 characters in an agent type's name, before the plugin's `Claudiu:`. +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. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Agent { + #[default] + Codex, + OpenCode, +} + +impl Agent { + pub const ALL: [Agent; 2] = [Agent::Codex, Agent::OpenCode]; + + /// The name the settings page and the subagent's text use. + pub fn name(self) -> &'static str { + match self { + Agent::Codex => "Codex", + Agent::OpenCode => "OpenCode", + } + } + + /// The key in `CLAUDIU_SUBAGENTS` and the start of every agent type name. + pub fn key(self) -> &'static str { + match self { + Agent::Codex => "codex", + Agent::OpenCode => "opencode", + } + } + + /// 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}."), + } + } + + /// The mod answers these agents' turns, so Claude runs for one only if the mod lost track of it (a reload, and + /// the agent gone from the agent list). It then says so rather than attempt the task. + fn stub_prompt(self) -> String { + let name = self.name(); + format!("Reply with exactly this and nothing else: {name} couldn't run this task because Claudiu's mod lost track of this agent. Start a new {name} subagent.") + } +} + +/// A model an agent offers: its id, which the agent is given, and the name its model picker shows. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AgentModel { + pub id: String, + pub name: String, +} + +/// What the settings page holds for one agent. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AgentChoice { + pub on: bool, + /// The ids of the models switched on, each one agent type. + pub models: Vec, + /// The agent may edit files and run commands; otherwise it only reads. + pub edits: bool, + /// The models the agent offered when the page last asked, shown while it asks again. + 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 }, + } + } +} + +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, + } + } +} + +/// One agent type: its name in Claude Code and the model the agent runs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AgentType { + pub name: String, + pub model: String, +} + +/// The agent type name of a model: the agent's key and the id, dots and slashes turned into dashes because type names +/// can hold neither (`gpt-6.1-sol` → `codex-gpt-6-1-sol`, `openai/gpt-6.1-sol` → `opencode-openai-gpt-6-1-sol`). +/// None for an id no type name can carry. +pub fn type_name(agent: Agent, model: &str) -> Option { + let allowed = !model.is_empty() && model.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')); + let name = format!("{}-{}", agent.key(), model.replace(['.', '/'], "-")); + (allowed && name.len() <= TYPE_NAME_MAX).then_some(name) +} + +/// The agent types of the models switched on. A model whose type name an earlier one took gives none. +pub fn agent_types(agent: Agent, models: &[String]) -> Vec { + let mut types: Vec = vec![]; + for model in models { + if let Some(name) = type_name(agent, model) + && !types.iter().any(|t| t.name == name) + { + types.push(AgentType { name, model: model.clone() }); + } + } + types +} + +impl CustomSubagents { + pub fn get(&self, agent: Agent) -> &AgentChoice { + match agent { + Agent::Codex => &self.codex, + Agent::OpenCode => &self.opencode, + } + } + + pub fn get_mut(&mut self, agent: Agent) -> &mut AgentChoice { + match agent { + Agent::Codex => &mut self.codex, + Agent::OpenCode => &mut self.opencode, + } + } + + /// Each agent switched on that has a type, with its types. + fn types(&self) -> Vec<(Agent, Vec)> { + Agent::ALL + .into_iter() + .filter(|a| self.get(*a).on) + .map(|a| (a, agent_types(a, &self.get(a).models))) + .filter(|(_, types)| !types.is_empty()) + .collect() + } + + /// What the mod reads from `CLAUDIU_SUBAGENTS`, each type as the mod registers it; `None` when no type is on. + pub fn env(&self) -> Option { + let types = self.types(); + if types.is_empty() { + return None; + } + let mut env = Map::new(); + for (agent, types) in types { + let types: Vec = types + .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 })); + } + Some(Value::Object(env).to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } + + fn on(models: &[&str], edits: bool) -> AgentChoice { + AgentChoice { on: true, models: ids(models), edits, catalog: vec![] } + } + + #[test] + fn dots_become_dashes_and_codex_gets_the_real_id() { + assert_eq!( + agent_types(Agent::Codex, &ids(&["gpt-6.1-sol", "gpt-5.6-luna"])), + vec![ + AgentType { name: "codex-gpt-6-1-sol".into(), model: "gpt-6.1-sol".into() }, + AgentType { name: "codex-gpt-5-6-luna".into(), model: "gpt-5.6-luna".into() }, + ] + ); + } + + #[test] + fn opencode_provider_slashes_become_dashes() { + assert_eq!( + agent_types(Agent::OpenCode, &ids(&["openai/gpt-6.1-sol", "github-copilot/claude-opus-4.8-fast", "opencode-go/qwen4-max"])), + vec![ + AgentType { name: "opencode-openai-gpt-6-1-sol".into(), model: "openai/gpt-6.1-sol".into() }, + AgentType { name: "opencode-github-copilot-claude-opus-4-8-fast".into(), model: "github-copilot/claude-opus-4.8-fast".into() }, + AgentType { name: "opencode-opencode-go-qwen4-max".into(), model: "opencode-go/qwen4-max".into() }, + ] + ); + } + + #[test] + fn ids_no_type_name_can_carry_and_repeats_give_no_type() { + let long = "g".repeat(59); // "codex-" plus 59 is 65 characters + let types = agent_types(Agent::Codex, &ids(&["gpt 5", "gpt-5.5", "gpt-5-5", "", &long, "o3"])); + assert_eq!(types.iter().map(|t| t.name.as_str()).collect::>(), ["codex-gpt-5-5", "codex-o3"]); + let fits = "g".repeat(55); // "opencode-" plus 55 is 64 characters + let types = agent_types(Agent::OpenCode, &ids(&[&format!("{fits}x"), &fits, "a/b.c", "a.b/c"])); + assert_eq!(types.iter().map(|t| t.name.clone()).collect::>(), [format!("opencode-{fits}"), "opencode-a-b-c".into()]); + } + + #[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; + assert_eq!(off.env(), None); + let none = CustomSubagents { codex: on(&[], false), opencode: 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 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))); + let names: Vec<&str> = env["codex"]["types"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["codex-gpt-6-1-sol", "codex-gpt-5-6-luna"]); + assert_eq!( + env["codex"]["types"][0], + json!({ + "name": "codex-gpt-6-1-sol", + "model": "gpt-6.1-sol", + "description": "Runs the task in OpenAI Codex on gpt-6.1-sol. Use only when the user asks for Codex, GPT or gpt-6.1-sol.", + "prompt": "Reply with exactly this and nothing else: Codex couldn't run this task because Claudiu's mod lost track of this agent. Start a new Codex subagent.", + }) + ); + let open = &env["opencode"]["types"][0]; + assert_eq!((&open["name"], &open["model"]), (&json!("opencode-openai-gpt-6-1-sol"), &json!("openai/gpt-6.1-sol"))); + assert_eq!(open["description"], "Runs the task in OpenCode on openai/gpt-6.1-sol. Use only when the user asks for OpenCode or openai/gpt-6.1-sol."); + assert!(open["prompt"].as_str().unwrap().contains("OpenCode couldn't run this task")); + } + + #[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 env: Value = serde_json::from_str(&codex_only.env().unwrap()).unwrap(); + assert_eq!(env.as_object().unwrap().keys().collect::>(), ["codex"]); + } + + #[test] + fn a_state_file_from_before_opencode_keeps_its_codex_settings() { + let saved = r#"{"codex":true,"codex_models":["gpt-6.1-sol"],"codex_edits":true,"codex_catalog":[{"id":"gpt-6.1-sol","name":"6.1 Sol"}]}"#; + 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(), + } + ); + let again: CustomSubagents = serde_json::from_str(&serde_json::to_string(&loaded).unwrap()).unwrap(); + assert_eq!(again, loaded); + } +} diff --git a/src/main.rs b/src/main.rs index 6dd23f0..ccd15c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,6 +71,10 @@ fn main() { if std::env::args().nth(1).as_deref() == Some(claude::mcp::FLAG) { std::process::exit(claude::mcp::run()); } + // Hidden helper mode: runs one task in Codex for a custom subagent (see claude/acp.rs). + if std::env::args().nth(1).as_deref() == Some(claude::acp::FLAG) { + std::process::exit(claude::acp::run()); + } install_crash_log(); #[cfg(windows)] priority::restore_own_priority(); diff --git a/src/panels/overlays.rs b/src/panels/overlays.rs index 727a334..c8035a0 100644 --- a/src/panels/overlays.rs +++ b/src/panels/overlays.rs @@ -57,6 +57,10 @@ impl Workspace { if let Some(m) = self.render_modal() { out.push(m); } + // Above Settings: the last modal mounted takes Escape and clicks outside it. + if let Some(m) = self.model_picker() { + out.push(m); + } if let Some(m) = self.render_menu() { out.push(m); } diff --git a/src/panels/settings_view.rs b/src/panels/settings_view.rs index ff679e5..221e079 100644 --- a/src/panels/settings_view.rs +++ b/src/panels/settings_view.rs @@ -3,13 +3,14 @@ use rune::tok::motion; use rune::{Color, Cursor, El, ScrollSpec, Tx, col, el, row}; -use crate::app::{Act, MenuAnchor, MenuItem, Modal, SettingsPage, Workspace}; +use crate::app::{Act, AgentForm, Lookup, MenuAnchor, MenuItem, Modal, SettingsPage, Workspace}; +use crate::claude::subagents::{Agent, AgentModel, type_name}; use crate::claude::defaults::{Effort, PermissionMode}; use crate::claude::mcp::Feature; use crate::claude::trim::Trim; use crate::panels::overlays::{modal_input, modal_input_submitting}; use crate::panels::theme::{self, rgb}; -use crate::panels::widgets::{button, button_disabled, danger_button, label, section_label, tick}; +use crate::panels::widgets::{button, button_disabled, danger_button, font, label, section_label, tick}; fn faint(t: impl Into) -> El { label(t, 11.0, theme::TEXT_FAINT).wrap() @@ -40,16 +41,18 @@ fn switch(on: bool) -> El { /// An On/Off row that runs `flip` on the workspace when clicked, with an optional faint `tag` after the label. fn switch_row(key: String, title: &str, tag: Option<&str>, on: bool, flip: impl Fn(&mut Workspace) + 'static) -> El { - let mut left = row().center_y().gap(8.0).child(label(title.to_string(), 13.0, theme::TEXT)); + // A long name (a model's, say) gives way and is cut short, so the switch keeps its place at the right. + let mut left = row().grow(1.0).shrink().pr(10.0).center_y().gap(8.0).child(label(title.to_string(), 13.0, theme::TEXT).shrink().truncate()); if let Some(t) = tag { - left = left.child(label(t.to_string(), 11.0, theme::TEXT_FAINT)); + left = left.child(label(t.to_string(), 11.0, theme::TEXT_FAINT).shrink().truncate()); } + let knob = format!("{key}-switch"); setting_row(key) .cursor(Cursor::Pointer) .role("switch") .hover(Color::WHITE.alpha(0.02)) .child(left) - .child(switch(on)) + .child(switch(on).key(knob)) .on_press_tx(move |ws: &mut Workspace, tx: &mut Tx| { flip(ws); ws.after_input(tx); @@ -65,6 +68,122 @@ 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, +} + +/// 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.", + ), + } +} + +/// The models to list: those the agent offers, then any switched on that it no longer offers, so they can be +/// switched off. The flag says whether the agent still offers the model. +fn model_rows(catalog: &[AgentModel], on: &[String]) -> Vec<(AgentModel, bool)> { + let gone = on.iter().filter(|id| !catalog.iter().any(|m| &m.id == *id)).map(|id| AgentModel { id: id.clone(), name: id.clone() }); + catalog.iter().cloned().map(|m| (m, true)).chain(gone.map(|m| (m, false))).collect() +} + +/// How many of the models the agent offers are switched on, as "2 of 107 on". A model switched on that the agent no +/// longer offers isn't one of them. +fn on_count(catalog: &[AgentModel], on: &[String]) -> String { + format!("{} of {} on", catalog.iter().filter(|m| on.contains(&m.id)).count(), catalog.len()) +} + +/// Whether `model` fits what was typed in the picker's search: every word, in its name or its id, ignoring case. +fn model_matches(query: &str, model: &AgentModel) -> bool { + let haystack = format!("{} {}", model.name, model.id).to_lowercase(); + query.to_lowercase().split_whitespace().all(|word| haystack.contains(word)) +} + +/// A model's switch, keyed `key`, on the page or in the picker; it flips the model in the agent's form. +fn model_switch(key: String, agent: Agent, model: &AgentModel, offered: bool, on: bool) -> Option { + let name = type_name(agent, &model.id)?; + let tag = if offered { name } else { format!("{name} · no longer offered") }; + let id = model.id.clone(); + Some(switch_row(key, &model.name, Some(&tag), on, move |ws| { + if let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() { + flip(&mut subagents.get_mut(agent).models, id.clone()); + } + })) +} + +/// Where the agent's model lookup stands, when there is something to say. +fn lookup_status(agent: Agent, catalog: &[AgentModel], lookup: &Lookup) -> Option { + let name = agent.name(); + if lookup.loading && catalog.is_empty() { + Some(faint(format!("Loading {name}'s models…"))) + } else { + lookup.error.as_ref().map(|why| label(format!("Couldn't load {name}'s models: {why}"), 11.0, theme::WARN).wrap()) + } +} + +/// 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"; @@ -114,8 +233,64 @@ 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 { + let Some(Modal::Settings { subagents, .. }) = &self.modal else { return None }; + let (agent, search) = subagents.picking.as_ref()?; + let agent = *agent; + 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; + } + } + 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)) + .padding(20.0) + .gap(12.0) + .radius(12.0) + .fill(rgb(0x151517)) + .border(1.0, rgb(0x2c2c30)) + .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); + })), + ); + Some( + row() + .key("model-picker-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()) + .child(card), + ) + } + pub(crate) fn settings_body(&self) -> El { - let Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }) = &self.modal else { + let Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }) = &self.modal else { return el(); }; let page = self.settings_page; @@ -197,6 +372,16 @@ impl Workspace { } list } + 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.", + )); + 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 + } SettingsPage::Projects => self.projects_page(renaming.as_ref()), SettingsPage::Worktrees => self.worktrees_page(), SettingsPage::About => col().child(faint(format!( @@ -385,3 +570,35 @@ impl Workspace { list } } + +#[cfg(test)] +mod tests { + use super::*; + + fn model(id: &str, name: &str) -> AgentModel { + AgentModel { id: id.into(), name: name.into() } + } + + #[test] + fn every_word_of_the_search_must_match_the_name_or_the_id() { + let sol = model("openai/gpt-6.1-sol", "openai/GPT-6.1 Sol"); + assert!(model_matches("", &sol)); + assert!(model_matches(" GPT sol ", &sol)); + assert!(model_matches("openai 6.1", &sol)); + assert!(!model_matches("gpt luna", &sol)); + assert!(!model_matches("anthropic", &sol)); + } + + #[test] + fn the_count_leaves_out_models_no_longer_offered() { + let catalog = [model("a", "A"), model("b", "B")]; + let on = ["a".to_string(), "gone-1".into(), "gone-2".into()]; + assert_eq!(on_count(&catalog, &on), "1 of 2 on"); + } + + #[test] + fn models_no_longer_offered_come_last_and_marked() { + let rows = model_rows(&[model("a", "A")], &["gone".to_string(), "a".into()]); + assert_eq!(rows, vec![(model("a", "A"), true), (model("gone", "gone"), false)]); + } +} diff --git a/src/store.rs b/src/store.rs index cf8797a..660ff09 100644 --- a/src/store.rs +++ b/src/store.rs @@ -308,6 +308,9 @@ pub struct Settings { /// Output caps and turned-off skills for Claude Code (`claude/trim.rs`); empty leaves Claude Code's own behavior. #[serde(default)] pub limits: crate::claude::trim::Limits, + /// Agent types that run a task in another coding agent (Settings → Custom subagents); all off by default. + #[serde(default)] + pub custom_subagents: crate::claude::subagents::CustomSubagents, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/src/terminal/view/cards.rs b/src/terminal/view/cards.rs index 545dd4b..65870ef 100644 --- a/src/terminal/view/cards.rs +++ b/src/terminal/view/cards.rs @@ -83,6 +83,13 @@ impl TerminalView { self.cards.shown.contains_key(call) } + /// Takes `bytes` in as if the program had written them. + #[cfg(test)] + pub fn feed(&self, bytes: &str) { + use alacritty_terminal::vte::ansi::{Processor, StdSyncHandler}; + Processor::::new().advance(&mut *self.terminal.term.lock(), bytes.as_bytes()); + } + /// What the user has done in this terminal's cards. pub fn card_ui(&mut self) -> &mut CardUi { self.dirty = true; @@ -122,8 +129,15 @@ impl TerminalView { let margin = m.cell_w * MARGIN_COLS; let line_h = m.line_h; let mut out = vec![]; + let mut pieces: HashMap = HashMap::new(); for slot in self.visible_slots() { let Some(Shown { card, .. }) = self.cards.shown.get(&slot.call) else { continue }; + // Keyed by the card and which of its pieces on screen this is, not by the card row it starts at: that + // changes with each line the card scrolls under the top edge, and a new key fades a new copy in over the + // old one fading out. + let piece = pieces.entry(slot.call.clone()).or_default(); + let slot_key = format!("{}/slot-{}-{piece}", self.key, slot.call); + *piece += 1; let scope = Scope { call: card.call.clone(), terminal: self.key.clone() }; let (call, term) = (card.call.clone(), self.key.clone()); let clear = self.key.clone(); @@ -138,7 +152,7 @@ impl TerminalView { }) .child(crate::visual::ui::markdown(&format!("{}/card-{}", self.key, card.call), &card.content, &scope, &self.cards.ui)); out.push( - el().key(format!("{}/slot-{}-{}", self.key, slot.call, slot.first)) + el().key(slot_key) // Follows the scroll at once, as the rows around it do. .instant_changes() .absolute(0.0, line_h * slot.row as f32 + shift) diff --git a/web/src/pages/index.astro b/web/src/pages/index.astro index 920c23d..4788ba5 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
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, and your own OpenCode providers for OpenCode subagents
Uploadsnone
After a restartrunning sessions come back
Download Windows, macOS and Linux