diff --git a/README.md b/README.md index 42428ea..d646bd2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ m4code is a native desktop app, written in Rust with [GPUI](https://gpui.rs), th ## What it does -Each session is a conversation with Claude Code, Codex, OpenCode or Google Antigravity in m4code's own chat view. m4code talks to each agent through the [Agent Client Protocol](https://agentclientprotocol.com) (ACP), and sign-in stays with the agent. Settings → General picks the default model for new sessions across all enabled harnesses. Claude Code sessions run through Anthropic's [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) with your own `claude`, and need Node and npm. The first one installs the SDK into m4code's data folder. Anthropic's [terms](https://code.claude.com/docs/en/legal-and-compliance) don't allow third-party apps built on the Agent SDK to use a Claude Free, Pro, Max or Ultra sign-in without Anthropic's approval, and Anthropic may enforce that without notice. m4code uses whatever sign-in your `claude` has, so with a subscription sign-in you use Claude Code sessions in m4code at your own risk. An API key, or a cloud provider such as Bedrock or Vertex, is allowed. Codex sessions need Node, because m4code runs Codex through its ACP adapter from npm. The chat view takes Claude Code's keyboard shortcuts, such as Esc to interrupt, Esc twice to edit your last message, Shift+Tab to change mode and Up for earlier messages. Shift+Enter starts a new line in either message box. While the agent works, a Working line with a spinner shows at the bottom of the chat. Settings → General decides what a message you send meanwhile does. Steer, the default, gives it to the agent in the turn it is working on. Claude Code reads it once its current step is done, and until then it waits above the message box. Codex, OpenCode and Antigravity stop their turn and start again with it. Queue makes it wait for the turn to end, in a list above the message box, where you can edit or remove it before m4code sends it. Cmd/Ctrl+Enter does the other one for a single message, and slash commands always wait. When an agent asks a question, the arrow keys or the mouse highlight an option, and Enter picks it. For Claude Code's questions, you can type your own answer in the message box instead. Your own messages show their Markdown formatting in the chat. Settings → Keyboard lists every keyboard shortcut; they can't be changed yet. Pick up a session here, in a project's menu, lists the default agent's sessions in that folder, including ones started in a terminal, and opens the one you choose. Quit it in the terminal first. The welcome screen is the message box for a new session. Home and chat share a Send button on the right. Empty or whitespace-only drafts cannot be sent, including with Enter. Its chips pick the model from any enabled harness, the project, the effort level and the branch or worktree. The branch list explains deletion restrictions and shows the paths of external worktrees too. A missing worktree folder stays listed and cannot be selected. A chat's message box has the same chips, the branch chip included. The branch chip's dropdown starts work in a new worktree in one click. Type a name in its search box, or leave it blank for a random name, then choose New worktree to branch from main, or from current to branch from the checkout you are in. A typed name that isn't a branch also gets a Create branch row. Inside a chat, click the model pill (or press Alt+P / Option+P) to search and pick any model across enabled harnesses or drag the effort bar, and click the permission pill to open the permission mode dropdown; Escape or clicking outside closes either dropdown. The permission dropdown lists Auto mode whenever Claude Code offers it for your account. Picking a model served by another harness hands off the conversation in place when you send your next message, after the current turn ends. Returning to a harness resumes its saved provider session and sends the intervening conversation. A failed handoff restores the original session and the unsent draft. When you ask an agent to switch models, it does so with m4code's set_model tool, and list_models gives it the model names. A switch to a model on another harness hands the conversation to that harness when the turn ends. m4code's tools that open, read or link sessions, switch models or move a session to another worktree never ask you to confirm: the agent calls them only when you asked for what they do. An agent can open a new session in a project with a model and effort of its choosing; the new session takes your default permission mode. Settings → Harnesses enables or disables Claude Code, Codex, OpenCode and Antigravity. Each harness's popup lists its models. The model picker shows the ticked models. Every model starts ticked, and the last one can't be unticked. Claude Code's popup also holds its account switcher and the Claude in Chrome switch for new sessions. m4code starts each Claude Code session without the tools meant for the claude.ai app, such as scheduled tasks, push notifications and the claude.ai connectors. It removes them for that session only, so Claude Code in a terminal keeps them. The slash command menu leaves out commands m4code's own controls cover, such as /model and Codex's /approvals. Every harness popup has the same subagent and edit controls and uses the same status format. Antigravity shows its terms warning directly under the subagent toggle. With the toggle on, each ticked model can run as a subagent. Codex and OpenCode subagents default to enabled with edits allowed when those settings have not been saved. Existing off and read-only choices stay as they are. Antigravity stays opt-in for Claude Code's native integration. The sidebar footer shows usage limits only for connected harnesses that have a limits adapter. Settings → Skills browses `skills.sh`, installs single `SKILL.md` packages or whole GitHub repositories, and symlinks enabled skills globally or per project into each active harness. Installed skills are grouped by the GitHub repository they came from. Update fetches the latest version of one skill, Update repo does it for every skill from that repository, and Update all does it for every installed skill. Toggles stay as they were. With a project picked as the scope, the page also lists the skills that project's repository ships in its own folders, such as `.claude/skills`. m4code only reads those folders. Before each message in a git repository, m4code saves the working tree. Review changes, under the message box, then shows what changed since your last message, hunk by hunk. Each hunk can be kept or reverted. A comment on a line goes back to the agent as `@path#L12: comment`, and Cmd/Ctrl+Enter in a comment sends all of them. In editor mode, a button beside the selected lines, or beside the line under the mouse, opens the same comment box. Enter adds `@path#L12-30: comment` to the message box on a line of its own, and Cmd/Ctrl+Enter sends it. The sidebar starts with the project selector and Settings on its right. Drag the right sidebar's cards into any order, and m4code keeps it. Around the chat, m4code adds a sidebar of running and recent sessions (Ctrl+Z, or Cmd+Z on macOS, reopens the last one you closed), notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E) that also works on Home for the selected project, preserving each project's tabs and unsaved edits, usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, a `skills.sh` browser and toggle panel (Settings → Skills) that installs `SKILL.md` packages and symlinks enabled skills globally or per project into each active agent's skills folder, and cross-agent subagents configured in Settings → Harnesses. Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, Antigravity subagents need the Antigravity CLI (`agy`) installed and signed in, and with Allow edits on, each acts without Claude Code's permission rules. Read-only Antigravity runs from its own folder in m4code's data, whose hook refuses every tool but reading and searching, so your own Antigravity rules, skills and MCP servers don't load there. Google's [Antigravity terms](https://antigravity.google/terms) and [FAQ](https://antigravity.google/docs/faq) forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does, so turn Antigravity subagents on at your own risk. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which m4code reads from the session logs in `~/.codex`; with Antigravity subagents on, it shows Antigravity's limits for each group of models, from `agy`'s own `/usage`, asked every five minutes at no token cost. Their last saved readings show at launch and refresh in the background. Settings lists the rest. +Each session is a conversation with Claude Code, Codex, OpenCode or Google Antigravity in m4code's own chat view. m4code talks to each agent through the [Agent Client Protocol](https://agentclientprotocol.com) (ACP), and sign-in stays with the agent. Settings → General picks the default model for new sessions across all enabled harnesses. Claude Code sessions run through Anthropic's [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) with your own `claude`, and need Node and npm. The first one installs the SDK into m4code's data folder. Anthropic's [terms](https://code.claude.com/docs/en/legal-and-compliance) don't allow third-party apps built on the Agent SDK to use a Claude Free, Pro, Max or Ultra sign-in without Anthropic's approval, and Anthropic may enforce that without notice. m4code uses whatever sign-in your `claude` has, so with a subscription sign-in you use Claude Code sessions in m4code at your own risk. An API key, or a cloud provider such as Bedrock or Vertex, is allowed. Codex sessions need Node, because m4code runs Codex through its ACP adapter from npm. The chat view takes Claude Code's keyboard shortcuts, such as Esc to interrupt, Esc twice to edit your last message, Shift+Tab to change mode and Up for earlier messages. Shift+Enter starts a new line in either message box. While the agent works, a Working line with a spinner shows at the bottom of the chat. Settings → General decides what a message you send meanwhile does. Steer, the default, gives a follow-up to the running turn. Claude Code reads it after its current step. Codex uses native steering when its adapter supports it. Other adapters stop the current turn and start the follow-up first. Queue waits for the turn to finish. Queued messages appear above the composer with controls to edit in place, remove, or send now. Cmd/Ctrl+Enter, or Cmd/Ctrl-click on the send button, swaps Queue and Steer for one message. Slash commands wait for a new turn. Interrupting a turn or restarting the app holds the queue. Press Resume or send a new message to continue. The composer shows which action is available. When an agent asks a question, the arrow keys or the mouse highlight an option, and Enter picks it. For Claude Code's questions, you can type your own answer in the message box instead. When several requests arrive together, the chat shows them in order. Claude Code background shells appear above the composer with Output and Stop buttons. The finished command shows the available output in the chat. Your own messages show their Markdown formatting in the chat. Settings → Keyboard lists every keyboard shortcut; they can't be changed yet. Pick up a session here, in a project's menu, lists the default agent's sessions in that folder, including ones started in a terminal, and opens the one you choose. Quit it in the terminal first. The welcome screen is the message box for a new session. Home and chat share a Send button on the right. Empty or whitespace-only drafts cannot be sent, including with Enter. Its chips pick the model from any enabled harness, the project, the effort level and the branch or worktree. The branch list explains deletion restrictions and shows the paths of external worktrees too. A missing worktree folder stays listed and cannot be selected. A chat's message box has the same chips, the branch chip included. The branch chip's dropdown starts work in a new worktree in one click. Type a name in its search box, or leave it blank for a random name, then choose New worktree to branch from main, or from current to branch from the checkout you are in. A typed name that isn't a branch also gets a Create branch row. Inside a chat, click the model pill (or press Alt+P / Option+P) to search and pick any model across enabled harnesses or drag the effort bar, and click the permission pill to open the permission mode dropdown; Escape or clicking outside closes either dropdown. The permission dropdown lists Auto mode whenever Claude Code offers it for your account. Picking a model served by another harness hands off the conversation in place when you send your next message, after the current turn ends. Returning to a harness resumes its saved provider session and sends the intervening conversation. A failed handoff restores the original session and the unsent draft. When you ask an agent to switch models, it does so with m4code's set_model tool, and list_models gives it the model names. A switch to a model on another harness hands the conversation to that harness when the turn ends. m4code's tools that open, read or link sessions, switch models or move a session to another worktree never ask you to confirm: the agent calls them only when you asked for what they do. An agent can open a new session in a project with a model and effort of its choosing; the new session takes your default permission mode. Settings → Harnesses enables or disables Claude Code, Codex, OpenCode and Antigravity. Each harness's popup lists its models. The model picker shows the ticked models. Every model starts ticked, and the last one can't be unticked. Claude Code's popup also holds its account switcher and the Claude in Chrome switch for new sessions. m4code starts each Claude Code session without the tools meant for the claude.ai app, such as scheduled tasks, push notifications and the claude.ai connectors. It removes them for that session only, so Claude Code in a terminal keeps them. The slash command menu leaves out commands m4code's own controls cover, such as /model and Codex's /approvals. Every harness popup has the same subagent and edit controls and uses the same status format. Antigravity shows its terms warning directly under the subagent toggle. With the toggle on, each ticked model can run as a subagent. Codex and OpenCode subagents default to enabled with edits allowed when those settings have not been saved. Existing off and read-only choices stay as they are. Antigravity stays opt-in for Claude Code's native integration. The sidebar footer shows usage limits only for connected harnesses that have a limits adapter. Settings → Skills browses `skills.sh`, installs single `SKILL.md` packages or whole GitHub repositories, and symlinks enabled skills globally or per project into each active harness. Installed skills are grouped by the GitHub repository they came from. Update fetches the latest version of one skill, Update repo does it for every skill from that repository, and Update all does it for every installed skill. Toggles stay as they were. With a project picked as the scope, the page also lists the skills that project's repository ships in its own folders, such as `.claude/skills`. m4code only reads those folders. Before each message in a git repository, m4code saves the working tree. Review changes, under the message box, then shows what changed since your last message, hunk by hunk. Each hunk can be kept or reverted. A comment on a line goes back to the agent as `@path#L12: comment`, and Cmd/Ctrl+Enter in a comment sends all of them. In editor mode, a button beside the selected lines, or beside the line under the mouse, opens the same comment box. Enter adds `@path#L12-30: comment` to the message box on a line of its own, and Cmd/Ctrl+Enter sends it. The sidebar starts with the project selector and Settings on its right. Drag the right sidebar's cards into any order, and m4code keeps it. Around the chat, m4code adds a sidebar of running and recent sessions (Ctrl+Z, or Cmd+Z on macOS, reopens the last one you closed), notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E) that also works on Home for the selected project, preserving each project's tabs and unsaved edits, usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, a `skills.sh` browser and toggle panel (Settings → Skills) that installs `SKILL.md` packages and symlinks enabled skills globally or per project into each active agent's skills folder, and cross-agent subagents configured in Settings → Harnesses. Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, Antigravity subagents need the Antigravity CLI (`agy`) installed and signed in, and with Allow edits on, each acts without Claude Code's permission rules. Read-only Antigravity runs from its own folder in m4code's data, whose hook refuses every tool but reading and searching, so your own Antigravity rules, skills and MCP servers don't load there. Google's [Antigravity terms](https://antigravity.google/terms) and [FAQ](https://antigravity.google/docs/faq) forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does, so turn Antigravity subagents on at your own risk. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which m4code reads from the session logs in `~/.codex`; with Antigravity subagents on, it shows Antigravity's limits for each group of models, from `agy`'s own `/usage`, asked every five minutes at no token cost. Their last saved readings show at launch and refresh in the background. Settings lists the rest. Claude Code, Codex and OpenCode sessions share m4code's `spawn_subagent`, `list_subagents`, `send_subagent_message`, `wait_subagent` and `stop_subagent` MCP tools. Children run in the parent's working folder without taking focus. When a child's turn ends, m4code sends its report to the parent, which shows it folded among the thinking and tool steps. Click the step to read the report, or Open to show the child. `wait_subagent` is only for a parent that must have the report before it can go on. A subagent's chat has a bar above it with a link back to its parent, the child's provider and its state. The right sidebar lists a session's subagents with their provider logos and states, and folds the finished ones into one row. The list includes the harness's own subagents, such as Claude Code's Agent tool and its `m4code:` types; clicking one unfolds its step in the chat and scrolls there. Follow-ups use the same child session, including after stopping it. Stopping a parent stops its children. A read-only parent cannot grant edits to a child, and user questions still need an answer. Claude Code's native subagent integration remains available. Enabled Codex and OpenCode providers register a default-model subagent even before their model catalogs load. The shared MCP instructions name every subagent tool so each supported provider can discover them. The shared tools exclude Antigravity for now. In the Home editor, line comments go into the new-session composer; Cmd/Ctrl+Enter sends them and starts the session. diff --git a/bridge/background-shells.mjs b/bridge/background-shells.mjs new file mode 100644 index 0000000..5d6e6c6 --- /dev/null +++ b/bridge/background-shells.mjs @@ -0,0 +1,83 @@ +import { constants } from "node:fs"; +import { open, readdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const OUTPUT_LIMIT = 16 * 1024; + +export async function readOutput(file) { + if (!file) return null; + try { + const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK); + try { + const info = await handle.stat(); + if (!info.isFile()) return null; + const buffer = Buffer.alloc(Math.min(info.size, OUTPUT_LIMIT)); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, info.size - buffer.length); + return buffer.toString("utf8", 0, bytesRead); + } finally { + await handle.close(); + } + } catch { + return null; + } +} + +export async function liveOutput(cwd, sessionId, taskId) { + if (typeof process.getuid !== "function" || ![sessionId, taskId].every((id) => /^[a-z0-9_-]+$/i.test(id))) { + return null; + } + // Claude's live output directory is private to the CLI. The final notification supplies its own path. + const base = process.env.CLAUDE_CODE_TMPDIR?.trim() || (process.platform === "darwin" ? "/tmp" : tmpdir()); + const root = resolve(cwd, base, `claude-${process.getuid()}`); + const projects = await readdir(root, { withFileTypes: true }).catch(() => []); + for (const project of projects) { + if (!project.isDirectory()) continue; + const output = await readOutput(join(root, project.name, sessionId, "tasks", `${taskId}.output`)); + if (output !== null) return output; + } + return null; +} + +export class BackgroundShells { + tasks = new Map(); + active = new Map(); + + update(message) { + const id = message.task_id; + if (message.subtype === "background_tasks_changed") { + this.active = new Map(); + for (const task of message.tasks) { + if (task.task_type !== "local_bash" || task.ambient) continue; + const shell = { id: task.task_id, label: task.description, run: task.run_id, backgrounded: true }; + this.tasks.set(shell.id, shell); + this.active.set(shell.id, shell); + } + return true; + } + if (!id) return false; + const known = this.tasks.get(id); + if (known?.run && message.run_id && message.run_id < known.run) return false; + if (message.subtype === "task_started" && message.task_type === "local_bash" && !message.ambient) { + const shell = { id, label: message.description, run: message.run_id, backgrounded: message.is_backgrounded || known?.backgrounded === true }; + this.tasks.set(id, shell); + if (message.is_backgrounded) this.active.set(id, shell); + return message.is_backgrounded === true; + } + if (message.subtype === "task_updated" && known && message.patch.is_backgrounded) { + known.backgrounded = true; + this.active.set(id, known); + return true; + } + return false; + } + + finish(message) { + const id = message.task_id; + const shell = this.tasks.get(id); + if (!shell || (shell.run && message.run_id && shell.run !== message.run_id)) return null; + this.tasks.delete(id); + this.active.delete(id); + return shell; + } +} diff --git a/bridge/background-shells.test.mjs b/bridge/background-shells.test.mjs new file mode 100644 index 0000000..8d62a43 --- /dev/null +++ b/bridge/background-shells.test.mjs @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { BackgroundShells, readOutput } from "./background-shells.mjs"; + +test("a shell that moves to the background retains its identity through completion", () => { + const shells = new BackgroundShells(); + const start = { subtype: "task_started", task_id: "shell", task_type: "local_bash", run_id: "2", description: "Tests" }; + assert.equal(shells.update(start), false); + assert.equal(shells.active.size, 0); + assert.equal(shells.update({ subtype: "task_updated", task_id: "shell", run_id: "2", patch: { is_backgrounded: true } }), true); + assert.equal(shells.active.get("shell").label, "Tests"); + assert.equal(shells.finish({ task_id: "shell", run_id: "1" }), null); + assert.equal(shells.active.size, 1); + assert.equal(shells.update({ subtype: "background_tasks_changed", tasks: [] }), true); + assert.equal(shells.active.size, 0); + assert.equal(shells.finish({ task_id: "shell", run_id: "2" }).backgrounded, true); +}); + +test("the roster excludes ambient tasks and tasks other than shells", () => { + const shells = new BackgroundShells(); + shells.update({ subtype: "background_tasks_changed", tasks: [ + { task_id: "one", task_type: "local_bash", description: "Build" }, + { task_id: "two", task_type: "local_bash", ambient: true }, + { task_id: "three", task_type: "local_agent" }, + ] }); + assert.deepEqual([...shells.active.keys()], ["one"]); +}); + +test("output is bounded to the latest 16 KiB of a regular file", async () => { + const dir = await mkdtemp(join(tmpdir(), "m4code-shell-output-")); + try { + const file = join(dir, "shell.output"); + await writeFile(file, `header${"x".repeat(16 * 1024 - 4)}tail`); + const output = await readOutput(file); + assert.equal(output.length, 16 * 1024); + assert.equal(output.slice(-4), "tail"); + assert.equal(await readOutput(dir), null); + assert.equal(await readOutput(join(dir, "missing")), null); + } finally { + await rm(dir, { recursive: true }); + } +}); diff --git a/bridge/claude.mjs b/bridge/claude.mjs index 9811fbe..8c0e7b8 100644 --- a/bridge/claude.mjs +++ b/bridge/claude.mjs @@ -9,6 +9,7 @@ import { randomUUID } from "node:crypto"; import { createInterface } from "node:readline"; +import { BackgroundShells, liveOutput, readOutput } from "./background-shells.mjs"; import { getSessionMessages, listSessions, query } from "@anthropic-ai/claude-agent-sdk"; @@ -279,7 +280,14 @@ async function finishTurn(session, result) { if (turn) { const failed = result.is_error && !session.cancelled; if (failed) turn.reject(new Error(result.result || (result.errors ?? []).join("\n") || "Claude Code stopped with an error.")); - else turn.resolve({ stopReason: stopReason(session, result), ...steersBack(session, turn, receipt) }); + else { + if (session.cancelled) { + for (const uuid of receipt?.still_queued ?? []) { + if (turn.steers.has(uuid) && !turn.shown.has(uuid)) session.dropping.add(uuid); + } + } + turn.resolve({ stopReason: stopReason(session, result) }); + } } // The context size is only shown, so the turn ends without waiting for it. session.query @@ -288,35 +296,45 @@ async function finishTurn(session, result) { .catch(() => {}); } -/** - * The steers the turn ends without having answered, in the reply's `_meta.m4code`. `unread` are those Claude had not - * read when the user stopped the turn: Claude Code keeps them and would run them as a turn of their own, which the - * user just asked to stop, so the bridge stops that turn too (`dropping`) and m4code puts their text back in the - * message box. `resend` are those Claude dropped unread on its own, which m4code sends as the next turn. - */ -function steersBack(session, turn, receipt) { - const stillQueued = new Set(receipt?.still_queued ?? []); - const unread = [...turn.waiting].filter((uuid) => turn.steers.has(uuid) && !turn.shown.has(uuid) && stillQueued.has(uuid)); - for (const uuid of unread) session.dropping.add(uuid); - const back = {}; - if (unread.length) back.unread = unread.map((uuid) => turn.steers.get(uuid)); - if (turn.dropped.length) back.resend = turn.dropped; - return Object.keys(back).length ? { _meta: { m4code: back } } : {}; -} - /** Claude Code says it took a steer off its queue without reading it (the states t3code treats the same way). */ function steerDropped(session, m) { const turn = session.turn; if (!turn || session.cancelled || !["cancelled", "discarded", "refused"].includes(m.state) || !turn.steers.has(m.command_uuid)) return; if (!turn.waiting.delete(m.command_uuid)) return; - turn.dropped.push(turn.steers.get(m.command_uuid)); + turn.steers.delete(m.command_uuid); if (turn.waiting.size === 0 && turn.held) return finishTurn(session, turn.held); } +function publishShells(session) { + const shells = [...session.shells.active.values()].map(({ id, label }) => ({ id, label })); + update(session.id, { sessionUpdate: "_m4code/background_shells", shells }); +} + +async function finishShell(session, message) { + const shell = session.shells.finish(message); + if (!shell?.backgrounded) return; + publishShells(session); + const output = await readOutput(message.output_file); + update(session.id, { + sessionUpdate: "tool_call", + toolCallId: `background-shell-${shell.id}`, + kind: "execute", + _meta: { m4code: { backgroundShell: true } }, + title: shell.label, + status: message.status === "completed" ? "completed" : "failed", + content: [{ type: "content", content: { type: "text", text: [message.summary, output].filter(Boolean).join("\n\n") } }], + }); +} + /** The session's messages from the SDK, as updates to m4code, until the session ends. */ async function pump(session) { + let errorText; try { for await (const m of session.query) { + if (m.type === "system") { + if (session.shells.update(m)) publishShells(session); + if (m.subtype === "task_notification") await finishShell(session, m); + } if (session.dropping.size && !session.turn) { if (m.type === "result") { for (const uuid of answeredBy(m) ?? [...session.dropping]) session.dropping.delete(uuid); @@ -371,6 +389,7 @@ async function pump(session) { } } } catch (error) { + errorText = error?.message ?? String(error); session.turn?.reject(error); session.turn = null; } @@ -378,12 +397,13 @@ async function pump(session) { session.turn?.reject(new Error("Claude Code stopped before it finished the turn.")); session.turn = null; sessions.delete(session.id); + update(session.id, { sessionUpdate: "_m4code/session_ended", error: errorText }); } async function open(params, resume) { const id = resume ?? randomUUID(); const extra = params._meta?.claudeCode?.options ?? {}; - const session = { id, cwd: params.cwd, inbox: new Inbox(), tools: new Map(), streamed: new Set(), turn: null, cancelled: false, interrupted: null, dropping: new Set(), dropInterrupted: false, dropsDone: null, mode: "default", model: "", effort: "medium", models: [] }; + const session = { id, cwd: params.cwd, inbox: new Inbox(), tools: new Map(), streamed: new Set(), shells: new BackgroundShells(), turn: null, cancelled: false, interrupted: null, dropping: new Set(), dropInterrupted: false, dropsDone: null, mode: "default", model: "", effort: "medium", models: [] }; session.query = query({ prompt: session.inbox, options: { @@ -457,14 +477,17 @@ const handlers = { "session/prompt": async (p) => { const s = sessions.get(p.sessionId); if (!s) throw new Error("That session has ended."); - if (s.turn) throw new Error("A turn is already running."); + if (s.turn || s.preparing) throw new Error("A turn is already running."); s.cancelled = false; + s.preparing = true; // Steers the user stopped still run in Claude Code first; this message waits until they are gone, so their // output and result can't be taken for its own. await afterDropped(s); + s.preparing = false; + if (s.cancelled) return { stopReason: "cancelled" }; const text = (p.prompt ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n"); const uuid = randomUUID(); - const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), shown: new Set(), dropped: [], held: null })); + const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), shown: new Set(), held: null })); s.inbox.push(userMessage(s, text, uuid)); return done; }, @@ -472,13 +495,22 @@ const handlers = { const s = sessions.get(p.sessionId); if (!s) throw new Error("That session has ended."); if (!s.turn || s.cancelled) throw new Error("No turn is running."); - const uuid = randomUUID(); + const uuid = p.id; s.turn.waiting.add(uuid); s.turn.steers.set(uuid, p.text); // "next" waits for the tool calls running to finish; "now" would cancel them, as t3code found. s.inbox.push(userMessage(s, p.text, uuid, "next")); return {}; }, + "_m4code/background_shell": async (p) => { + const session = sessions.get(p.sessionId); + if (!session?.shells.active.has(p.taskId)) throw new Error("That background shell has ended."); + if (p.action === "stop") { + await session.query.stopTask(p.taskId); + return {}; + } + return { output: await liveOutput(session.cwd, session.id, p.taskId) }; + }, "session/set_mode": async (p) => { const s = sessions.get(p.sessionId); await s.query.setPermissionMode(p.modeId); @@ -530,7 +562,7 @@ function showSteer(session, uuid) { const text = turn?.steers.get(uuid); if (text === undefined || turn.shown.has(uuid)) return; turn.shown.add(uuid); - update(session.id, { sessionUpdate: "user_message_chunk", content: { type: "text", text }, _meta: { m4code: { steer: true } } }); + update(session.id, { sessionUpdate: "user_message_chunk", content: { type: "text", text }, _meta: { m4code: { steer: uuid } } }); } /** Every steer not shown yet, oldest first: Claude is about to answer them, or just did. */ @@ -540,8 +572,9 @@ function showWaitingSteers(session, only) { function cancel(p) { const s = sessions.get(p.sessionId); - if (!s?.turn) return; + if (!s || (!s.turn && !s.preparing)) return; s.cancelled = true; + if (!s.turn) return; s.interrupted = s.query.interrupt().catch(() => undefined); } diff --git a/justfile b/justfile index 822c9df..8ccc34f 100644 --- a/justfile +++ b/justfile @@ -23,6 +23,10 @@ test-app: lint: cargo clippy --locked --all-targets -- -D warnings +# Test the Claude bridge's handling of background shells. +test-bridge: + node bridge/background-shells.test.mjs + # ---- Mod (Claude Code plugin in mod/) ------------------------------------------------------------- # Tests for the mod: the *.test.ts files in mod/hooks. Needs the `claude` CLI on PATH. @@ -50,7 +54,7 @@ web-preview: # ---- Everything ----------------------------------------------------------------------------------- # Every test: the app and the mod. -test: test-app test-mod +test: test-app test-bridge test-mod # What CI checks, plus the mod and the web build. -ci: build test-app web-build test-mod +ci: build test-app test-bridge web-build test-mod diff --git a/src/app/agent_handoff.rs b/src/app/agent_handoff.rs index 0ce622a..e6aa0b0 100644 --- a/src/app/agent_handoff.rs +++ b/src/app/agent_handoff.rs @@ -128,8 +128,13 @@ impl Workspace { target.update(cx, |view, _| view.relinquish_record()); } self.live.retain(|live| live.id != id); - if let (Some(source), Some(draft)) = (pending.source.view.thread(), pending.draft) { - source.update(cx, |view, cx| view.paste_text(&draft, window, cx)); + if let Some(source) = pending.source.view.thread() { + source.update(cx, |view, cx| { + view.restore_queue_after_handoff(cx); + if let Some(draft) = pending.draft { + view.paste_text(&draft, window, cx); + } + }); } self.live.push(pending.source); self.toast(format!("Handoff failed; the original session is still open. {error}"), true, cx); @@ -145,7 +150,7 @@ impl Workspace { target.update(cx, |view, _| view.relinquish_record()); } if let Some(source) = pending.source.view.thread() { - source.read(cx).stop(); + source.update(cx, |view, _| view.stop()); } } } diff --git a/src/app/headless/agents.rs b/src/app/headless/agents.rs index de16493..11b8f83 100644 --- a/src/app/headless/agents.rs +++ b/src/app/headless/agents.rs @@ -669,7 +669,7 @@ fn handing_a_session_to_another_agent() { ); ws.read_with(&cx, |ws, _| { let rec = ws.store.session(&first).unwrap(); - assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Codex, &cwd)); + assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Claude, &cwd)); }); wait(&mut cx, "the hand-off message", &|_, _| { std::fs::read_to_string(&prompts).is_ok_and(|p| { @@ -678,6 +678,10 @@ fn handing_a_session_to_another_agent() { && p.contains("User's next message:\nimplement step 2") }) }); + ws.read_with(&cx, |ws, _| { + let rec = ws.store.session(&first).unwrap(); + assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Codex, &cwd)); + }); } /// A session of each agent through ACP (Claude Code through the SDK bridge): it starts, names itself, and answers a message in the thread. diff --git a/src/app/layout.rs b/src/app/layout.rs index fd1ed08..6688f17 100644 --- a/src/app/layout.rs +++ b/src/app/layout.rs @@ -74,8 +74,11 @@ impl Workspace { if let Some(err) = view.read(cx).start_error() { ws.toast(format!("Could not start the shell: {err}"), true, cx); } + let shell_had_focus = view.focus_handle(cx).is_focused(window); ws.shells.remove(&owner); - ws.focus_active(window, cx); + if shell_had_focus { + ws.focus_active(window, cx); + } cx.notify(); } }); diff --git a/src/app/mod.rs b/src/app/mod.rs index 3e02c26..95da6bd 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -900,16 +900,14 @@ impl Workspace { /// Answer (or decline when `choice` is `None`) a session's pending question directly from the sidebar popover /// without switching the active view to that session. - pub fn answer_session_question(&mut self, id: &str, choice: Option, cx: &mut Context) { - if let Some(thread) = self.live_view(id).and_then(|v| v.thread()).cloned() { - thread.update(cx, |v, cx| match choice { - Some(ix) => v.answer(Some(ix), cx), - None => v.decline(cx), - }); + pub fn answer_session_question(&mut self, id: &str, question: uuid::Uuid, choice: Option, cx: &mut Context) { + let Some(thread) = self.live_view(id).and_then(|v| v.thread()).cloned() else { return }; + if !thread.update(cx, |v, cx| v.answer_question(question, choice, cx)) { + return; } self.question_popover = None; self.question_popover_hovered = false; - if self.activity.get(id) == Some(&Activity::Waiting) { + if self.activity.get(id) == Some(&Activity::Waiting) && !thread.read(cx).is_waiting() { self.activity.insert(id.to_string(), Activity::Working); } cx.notify(); diff --git a/src/app/sessions.rs b/src/app/sessions.rs index bb0bd26..a213fca 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -547,7 +547,11 @@ impl Workspace { /// A Claude session that never produced a transcript (opened and closed without a prompt) has nothing /// to resume. Remove m4code's own record of it; Claude Code's data is never touched. fn drop_if_empty(&mut self, id: &str) { - if self.ephemeral.remove(id) { + let ephemeral = self.ephemeral.remove(id); + if crate::thread::has_saved_queue(id) { + return; + } + if ephemeral { self.store.data.sessions.retain(|s| s.id != id); if self.selected.as_deref() == Some(id) { self.selected = None; @@ -671,7 +675,7 @@ impl Workspace { } let was_active = self.active_id().is_some_and(|a| a == id); if let Some(thread) = self.live_view(id).and_then(|view| view.thread()) { - thread.read(cx).stop(); + thread.update(cx, |view, _| view.stop()); } self.live.retain(|l| l.id != id); // dropping the view drops the Terminal, which closes the PTY self.shells.remove(id); diff --git a/src/harness/claude.rs b/src/harness/claude.rs index 37deaf2..2ee9272 100644 --- a/src/harness/claude.rs +++ b/src/harness/claude.rs @@ -12,8 +12,9 @@ use super::{Adapter, Reopen, Server}; /// The bridge's files, embedded in the binary. The lockfile pins the SDK, so an SDK change reaches users only with a /// m4code release. -const FILES: [(&str, &str); 3] = [ +const FILES: [(&str, &str); 4] = [ ("claude.mjs", include_str!("../../bridge/claude.mjs")), + ("background-shells.mjs", include_str!("../../bridge/background-shells.mjs")), ("package.json", include_str!("../../bridge/package.json")), ("package-lock.json", include_str!("../../bridge/package-lock.json")), ]; diff --git a/src/panels/overlays.rs b/src/panels/overlays.rs index 6143263..2d2a4f9 100644 --- a/src/panels/overlays.rs +++ b/src/panels/overlays.rs @@ -231,6 +231,7 @@ impl Workspace { let id = pop.id.clone(); let thread = self.live_view(&id)?.thread()?; let question = thread.read(cx).pending_question()?; + let question_id = question.id; let session_title = self.store.session(&id).map(|r| r.display_title().to_string()).unwrap_or_else(|| "Session".into()); let viewport = window.viewport_size(); @@ -245,7 +246,7 @@ impl Workspace { let primary = opt.kind == "allow_once" && i == 0; let answer_id = id.clone(); let row = div() - .id(gpui::SharedString::from(format!("sidebar-q-opt-{i}"))) + .id(gpui::SharedString::from(format!("sidebar-q-opt-{question_id}-{i}"))) .w_full() .px(px(10.0)) .py(px(7.0)) @@ -262,7 +263,7 @@ impl Workspace { .children(opt.description.clone().map(|desc| div().text_size(scaled(11.0)).text_color(hsla(theme::TEXT_DIM)).child(desc))) .on_click(cx.listener(move |ws, _: &ClickEvent, _w, cx| { cx.stop_propagation(); - ws.answer_session_question(&answer_id, Some(i), cx); + ws.answer_session_question(&answer_id, question_id, Some(i), cx); })); options = options.child(row); } @@ -325,7 +326,7 @@ impl Workspace { .child( button("sidebar-q-decline", "Decline", false).h(px(24.0)).on_click(cx.listener(move |ws, _: &ClickEvent, _w, cx| { cx.stop_propagation(); - ws.answer_session_question(&decline_id, None, cx); + ws.answer_session_question(&decline_id, question_id, None, cx); })), ) .child( diff --git a/src/thread/mod.rs b/src/thread/mod.rs index ea072c8..22a8695 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -3,6 +3,7 @@ //! included (`keys`); what differs between them is in `harness`. mod keys; +mod queue; mod render; mod review; @@ -18,6 +19,9 @@ use futures::StreamExt; use gpui::{App, AppContext, Bounds, Context, Entity, EventEmitter, FocusHandle, Focusable, FollowMode, KeystrokeEvent, ListAlignment, ListState, Pixels, Subscription, Window, px}; use gpui_kit::component::input::{InputEvent, InputState, TextareaState}; use serde_json::{Value, json}; +use uuid::Uuid; + +use self::queue::Queued; use crate::harness::acp::{self, Connection, Event, Launch}; use crate::harness::thread::{Entry, Thread}; @@ -47,6 +51,18 @@ pub struct BackgroundTask { pub waiting: bool, } +struct ProviderShell { + id: String, + label: String, + stopping: bool, +} + +struct ShellOutput { + task_id: String, + text: String, + loading: bool, +} + /// What the message box's branch chip shows; the workspace keeps it current (`Workspace::sync_git_chips`). #[derive(Clone, Debug, PartialEq)] pub struct GitChip { @@ -129,6 +145,7 @@ pub struct QuestionOption { /// Public read-only view of a pending question, for rendering outside the chat (e.g. sidebar hover popover). #[derive(Clone, Debug, PartialEq, Eq)] pub struct PendingQuestion { + pub id: Uuid, pub title: String, pub options: Vec, } @@ -147,6 +164,7 @@ enum QuestionReply { /// A permission or multiple-choice question the agent is waiting for. struct Question { + id: Uuid, reply: QuestionReply, title: String, options: Vec, @@ -156,17 +174,6 @@ struct Question { takes_own_answer: bool, } -struct Queued { - text: String, - compact: bool, - /// Typed by the user, who can edit or remove it while it waits; m4code's own messages (subagent reports) cannot. - by_user: bool, - /// Steered into a turn that stops for it (`steer`): it goes before the messages queued behind that turn. - ahead: bool, - /// Already appended to `thread.entries` so a new session shows the user's message while the agent starts. - shown: bool, -} - #[derive(Clone, Copy, PartialEq, Eq)] enum Phase { Starting, @@ -185,6 +192,8 @@ pub struct ThreadView { pub git: Option, /// Running child subagents / workspace background tasks attached to this session. pub background: Vec, + provider_shells: Vec, + shell_output: Option, /// Model from another harness staged for dynamic handoff on the next message. pub pending_model: Option, /// A hand-off the agent asked for with `set_model` and the user approved: the model, its effort and the first @@ -208,7 +217,13 @@ pub struct ThreadView { last_update: Option, /// Messages typed during a turn, sent one at a time after it. queue: VecDeque, - question: Option, + queue_held: bool, + queue_edit: Option, + preparing: Option, + restarting_for_steer: bool, + interrupting: bool, + queue_save_error: bool, + questions: VecDeque, pub composer: Entity, /// Where Up has got to among the messages sent before, and what was typed before it started. history_at: Option, @@ -226,10 +241,7 @@ pub struct ThreadView { /// Messages steered into the running turn that the agent hasn't read yet, oldest first. They join the /// conversation where the agent reads them (a `user_message_chunk` marked `_meta.m4code.steer`), because what it /// was still writing when they were sent comes before them. - steering: VecDeque, - /// Counts changes to `queue` that move its messages, so a waiting message's buttons get new ids when one ahead of - /// it leaves: a click pressed on one row can't land on the row that slid into its place. - pub(super) queue_changes: u64, + steering: VecDeque, /// The running turn is a slash command (such as `/compact`), which a steer would cut short. running_command: bool, /// What a message sent while the agent works does (Settings → General). @@ -238,6 +250,7 @@ pub struct ThreadView { pub(crate) canonical_history: bool, persist_on_drop: bool, pub capabilities: Value, + agent_meta: Value, /// Ctrl+T: the plan. pub plan_open: bool, /// Active compact picker dropdown above the composer (Alt+P for Model/Provider/Effort, or click Permission). @@ -315,7 +328,13 @@ impl ThreadView { let _ = this.update(cx, |v, cx| v.intercept(ev, window, cx)); })); let mut thread = Thread { entries: start.prior_entries.clone(), ..Default::default() }; - let mut queue = VecDeque::new(); + let mut queue = queue::load(&start.record_id); + for item in &mut queue { + item.order = queue::next_order(); + item.ahead = false; + item.shown &= matches!(start.prior_entries.last(), Some(Entry::User(text)) if text == &item.text); + } + let queue_held = !queue.is_empty(); if let Some(prompt) = start.prompt.clone() { // Show a new session's first message immediately instead of a blank screen while the agent starts. // A resumed session replays history during startup, so keep its prompt queued until open finishes. @@ -323,7 +342,7 @@ impl ThreadView { if shown { thread.sent(prompt.clone()); } - queue.push_back(Queued { text: prompt, shown, compact: false, by_user: false, ahead: false }); + queue.push_front(Queued { startup: true, shown, ..Queued::new(prompt, start.prior_entries.is_empty()) }); } let rows = thread.entries.len(); let list = ListState::new(rows, ListAlignment::Top, px(600.0)); @@ -339,6 +358,8 @@ impl ThreadView { picked: start.picked.clone(), git: None, background: vec![], + provider_shells: vec![], + shell_output: None, pending_model: None, handoff_after_turn: None, pending_effort: start.options.iter().find(|(k, _)| *k == "thought_level").map(|(_, v)| v.clone()), @@ -353,7 +374,13 @@ impl ThreadView { working: false, last_update: None, queue, - question: None, + queue_held, + queue_edit: None, + preparing: None, + restarting_for_steer: false, + interrupting: false, + queue_save_error: false, + questions: VecDeque::new(), composer, history_at: None, draft: String::new(), @@ -363,13 +390,13 @@ impl ThreadView { subagent_edits: None, markdown: HashMap::new(), steering: VecDeque::new(), - queue_changes: 0, running_command: false, follow_up: crate::store::FollowUp::default(), compaction: Default::default(), canonical_history: false, persist_on_drop: true, capabilities: Value::Null, + agent_meta: Value::Null, plan_open: false, picker: None, picker_at: crate::panels::widgets::Dropdown::at(gpui::point(px(0.0), px(0.0))), @@ -394,6 +421,9 @@ impl ThreadView { review: None, _subscriptions: subscriptions, }; + if start.prompt.is_some() { + view.queue_changed(); + } view.start(start, cx); view } @@ -459,7 +489,7 @@ impl ThreadView { /// The session is open, or failed to open. Returns whether to go on listening. fn opened(&mut self, opened: Result, start: &Start, cx: &mut Context) -> bool { - let Opened { session_id, result, capabilities, replayed } = match opened { + let Opened { session_id, result, capabilities, agent_meta, replayed } = match opened { Ok(o) => o, Err(why) => { self.ended(Some(why), cx); @@ -467,6 +497,7 @@ impl ThreadView { } }; self.capabilities = capabilities; + self.agent_meta = agent_meta; self.cached_replay = replayed && !start.prior_entries.is_empty(); self.thread.apply_session(&result); if let Some(model_opt) = self.thread.option("model") @@ -506,6 +537,25 @@ impl ThreadView { fn on_event(&mut self, event: Event, cx: &mut Context) { match event { Event::Update(update) => { + if update["sessionUpdate"] == "_m4code/session_ended" { + self.ended(update["error"].as_str().map(String::from), cx); + return; + } + if update["sessionUpdate"] == "_m4code/background_shells" { + let mut previous = std::mem::take(&mut self.provider_shells); + self.provider_shells = update["shells"].as_array().into_iter().flatten().filter_map(|task| { + let id = task["id"].as_str()?.to_string(); + let label = task["label"].as_str().unwrap_or("Shell command").to_string(); + let stopping = previous.iter().position(|shell| shell.id == id) + .is_some_and(|at| previous.swap_remove(at).stopping); + Some(ProviderShell { id, label, stopping }) + }).collect(); + if self.shell_output.as_ref().is_some_and(|output| !self.provider_shells.iter().any(|task| task.id == output.task_id)) { + self.shell_output = None; + } + cx.notify(); + return; + } if self.cached_replay && !self.working && is_conversation_update(&update) { if self.canonical_history { return; } self.cached_replay = false; @@ -519,16 +569,17 @@ impl ThreadView { let title = self.thread.title.clone(); let prev_ctx = self.thread.context; // A steer arrives whole, and is a message of its own even right after another one. - let steer = update.pointer("/_meta/m4code/steer").and_then(Value::as_bool) == Some(true); - let at = if steer { - self.steering.pop_front(); - self.thread.sent(update.pointer("/content/text").and_then(Value::as_str).unwrap_or_default()) + let at = if let Some(id) = update.pointer("/_meta/m4code/steer").and_then(Value::as_str).and_then(|id| id.parse().ok()) { + self.accept_steer(id) } else { self.thread.apply(&update) }; if let Some(at) = at { self.remeasure(at); } + if update.pointer("/_meta/m4code/backgroundShell").and_then(Value::as_bool) == Some(true) { + self.persist_entries(); + } if self.thread.title != title && let Some(t) = self.thread.title.clone() { @@ -543,6 +594,12 @@ impl ThreadView { self.report_chosen(cx); } Event::Permission { id, params } => { + if self.interrupting || self.restarting_for_steer { + if let Some(connection) = &self.connection { + connection.respond(id, acp::permission_outcome(None)); + } + return; + } // m4code's own tools act only on what the user asked for, so their prompts are answered yes. The // request may leave the title out and name a call the chat already shows. let call = params.pointer("/toolCall/toolCallId").and_then(Value::as_str).and_then(|call| self.thread.tool_at(call)); @@ -575,9 +632,15 @@ impl ThreadView { .collect(); let title = params.pointer("/toolCall/title").and_then(Value::as_str).unwrap_or("The agent asks for permission").to_string(); let takes_own_answer = acp::takes_own_answer(¶ms); - self.question = Some(Question { reply: QuestionReply::Acp(id), title, options, highlight: 0, takes_own_answer }); + self.questions.push_back(Question { id: Uuid::new_v4(), reply: QuestionReply::Acp(id), title, options, highlight: 0, takes_own_answer }); } Event::Elicitation { id, params } => { + if self.interrupting || self.restarting_for_steer { + if let Some(connection) = &self.connection { + connection.respond(id, acp::elicitation_cancel()); + } + return; + } let mut fields: VecDeque = acp::parse_elicitation(¶ms).into(); if let Some(first) = fields.pop_front() { let options = first @@ -590,7 +653,8 @@ impl ThreadView { kind: "allow_once".into(), }) .collect(); - self.question = Some(Question { + self.questions.push_back(Question { + id: Uuid::new_v4(), reply: QuestionReply::Elicitation { id, field: first.field, @@ -629,19 +693,60 @@ impl ThreadView { } self.phase = Phase::Ended; self.handover = None; - if let Some(Question { reply: QuestionReply::Bridge(req_id), .. }) = self.question.take() { - crate::claude::bridge::respond(&req_id, false, "The session ended before the user answered."); - } + self.preserve_handoff_message(); + self.cancel_questions(); self.error = why; - for text in std::mem::take(&mut self.steering) { - let at = self.thread.notice(format!("The agent stopped before reading your message, so it was not sent: {text}"), false); - self.remeasure(at); + if let Some(item) = self.preparing.take() { + self.queue.push_front(item); } + let ids = self.steering.iter().map(|item| item.id).collect::>(); + self.requeue_steers(ids); self.connection = None; cx.emit(ThreadEvent::Exited(if self.error.is_some() { Some(1) } else { Some(0) })); cx.notify(); } + fn background_shell_action(&mut self, task_id: &str, stop: bool, cx: &mut Context) { + let (Some(connection), Some(session)) = (&self.connection, &self.session_id) else { return }; + let Some(shell) = self.provider_shells.iter_mut().find(|shell| shell.id == task_id) else { return }; + if stop { + if shell.stopping { return; } + shell.stopping = true; + } else { + if self.shell_output.as_ref().is_some_and(|output| output.task_id == task_id && output.loading) { + return; + } + self.shell_output = Some(ShellOutput { task_id: task_id.to_string(), text: "Loading output…".into(), loading: true }); + } + let task_id = task_id.to_string(); + let action = if stop { "stop" } else { "output" }; + let reply = connection.request("_m4code/background_shell", json!({"sessionId": session, "taskId": task_id, "action": action})); + cx.spawn(async move |this, cx| { + let result = reply.await; + let _ = this.update(cx, |v, cx| { + if stop { + if let Err(why) = result && let Some(shell) = v.provider_shells.iter_mut().find(|shell| shell.id == task_id) { + shell.stopping = false; + let at = v.thread.notice(format!("Could not stop background shell: {why}"), true); + v.remeasure(at); + } + } else if let Some(output) = v.shell_output.as_mut().filter(|output| output.task_id == task_id) { + output.text = match result { + Ok(body) => match body["output"].as_str() { + Some("") => "The shell has produced no output yet.".into(), + Some(text) => text.to_string(), + None => "Live output is unavailable. Open the finished command to see its output.".into(), + }, + Err(why) => why, + }; + output.loading = false; + } + cx.notify(); + }); + }).detach(); + cx.notify(); + } + /// Pick a model from the aggregated catalog: switches live on the same harness, or stages a dynamic in-chat /// handoff when the model belongs to another harness. pub fn pick_model(&mut self, model: CatalogModel, cx: &mut Context) { @@ -668,12 +773,19 @@ impl ThreadView { /// Send what is typed; `the_other_way` (Cmd/Ctrl+Enter) queues it when the setting steers, and steers when it /// queues. fn submit_with(&mut self, the_other_way: bool, window: &mut Window, cx: &mut Context) { + if self.queue_edit.is_some() { + self.finish_queue_edit(true, window, cx); + return; + } let text = self.composer.read(cx).value().trim().to_string(); if !crate::panels::composer::can_send(&text) { + if self.queue_held && !self.working && self.questions.is_empty() { + self.resume_queue(cx); + } return; } self.composer.update(cx, |c, cx| c.set_value("", window, cx)); - if self.question.as_ref().is_some_and(|q| q.takes_own_answer) { + if self.questions.front().is_some_and(|q| q.takes_own_answer) { self.answer_in_own_words(&text, cx); return; } @@ -688,54 +800,96 @@ impl ThreadView { fn can_steer(&self, text: &str, follow_up: crate::store::FollowUp) -> bool { follow_up == crate::store::FollowUp::Steer && self.working + && !self.queue_held + && self.preparing.is_none() + && self.handoff_after_turn.is_none() + && self.questions.is_empty() && self.phase == Phase::Ready && !self.compaction.running && !self.running_command && !text.starts_with('/') } - /// Give `text` to the agent in the turn it is working on. Claude Code reads it between tool calls; an agent that - /// can't stops its turn, and the message goes first once it has stopped. - fn steer(&mut self, text: String, cx: &mut Context) { + fn native_codex_steering(&self) -> bool { + self.harness == Harness::Codex + && self.agent_meta.pointer("/steering/supported").and_then(Value::as_bool) == Some(true) + } + + fn steer(&mut self, mut item: Queued, cx: &mut Context) { let (Some(connection), Some(session)) = (self.connection.clone(), self.session_id.clone()) else { - self.queue.push_back(Queued { text, shown: false, compact: false, by_user: true, ahead: false }); + self.queue.push_back(item); + self.queue_changed(); cx.notify(); return; }; - if !self.harness.adapter().steers { - // After any message steered in before it, so they go in the order they were sent. + let codex = self.native_codex_steering(); + if !self.harness.adapter().steers && !codex { let at = self.queue.iter().take_while(|q| q.ahead).count(); - self.queue.insert(at, Queued { text, shown: false, compact: false, by_user: true, ahead: true }); - self.queue_changes += 1; - connection.notify("session/cancel", json!({"sessionId": session})); - // ACP says a client that cancels answers every open permission question as cancelled. - self.answer(None, cx); + item.ahead = true; + self.queue.insert(at, item); + self.queue_changed(); + if !std::mem::replace(&mut self.restarting_for_steer, true) { + connection.notify("session/cancel", json!({"sessionId": session})); + self.cancel_questions(); + } cx.notify(); return; } - self.steering.push_back(text.clone()); - let reply = connection.request("_m4code/steer", json!({"sessionId": session, "text": text})); + let id = item.id; + let text = item.text.clone(); + self.steering.push_back(item); + self.queue_changed(); + let reply = if codex { + connection.request("_session/steering", json!({ + "sessionId": session, + "prompt": [{"type": "text", "text": text}], + "_meta": {"steering": {"idleBehavior": "promptRequired"}} + })) + } else { + connection.request("_m4code/steer", json!({"sessionId": session, "text": text, "id": id.to_string()})) + }; cx.spawn(async move |this, cx| { - if reply.await.is_err() { - // The turn ended before the message reached it, so it is the next message instead. - let _ = this.update(cx, |v, cx| { - if let Some(at) = v.steering.iter().position(|t| *t == text) { - v.steering.remove(at); + let result = reply.await; + let _ = this.update(cx, |v, cx| { + if codex && result.as_ref().is_ok_and(|r| r["outcome"] == "injected") { + if let Some(at) = v.accept_steer(id) { + v.remeasure(at); + v.persist_entries(); } - v.queue.push_front(Queued { text, shown: false, compact: false, by_user: true, ahead: false }); - v.send_next(cx); - cx.notify(); - }); - } + } else if codex || result.is_err() { + v.requeue_steers([id]); + } + v.send_next(cx); + cx.notify(); + }); }) .detach(); cx.notify(); } + fn accept_steer(&mut self, id: Uuid) -> Option { + let at = self.steering.iter().position(|item| item.id == id)?; + let item = self.steering.remove(at)?; + self.queue_changed(); + self.thread.sent(item.text) + } + + fn requeue_steers(&mut self, ids: impl IntoIterator) { + for id in ids { + if let Some(at) = self.steering.iter().position(|item| item.id == id) { + let item = self.steering.remove(at).unwrap(); + let at = self.queue.iter().position(|waiting| !waiting.ahead && waiting.order > item.order) + .unwrap_or(self.queue.len()); + self.queue.insert(at, item); + } + } + self.queue_changed(); + } + /// A message m4code sends on the session's behalf, such as a subagent's report. It waits for the current turn /// like the user's own, but never starts or joins a hand-off the user set up in the model picker. pub fn deliver(&mut self, text: String, cx: &mut Context) { - self.queue.push_back(Queued { text, shown: false, compact: false, by_user: false, ahead: false }); + self.queue.push_back(Queued::new(text, false)); self.send_next(cx); cx.notify(); } @@ -761,77 +915,85 @@ impl ThreadView { cx.notify(); return; } - if self.working && let Some((_, _, message, by_agent)) = self.handoff_after_turn.as_mut() - && !*by_agent - { - message.push_str("\n\n"); - message.push_str(&text); - cx.notify(); - return; - } if self.can_steer(&text, follow_up) { - self.steer(text, cx); + self.steer(Queued::new(text, true), cx); return; } - let shown = self.phase == Phase::Starting && self.session_id.is_none(); - if shown && let Some(at) = self.thread.sent(text.clone()) { - self.remeasure(at); + self.queue.push_back(Queued::new(text, true)); + self.queue_changed(); + if self.queue_held && !self.working { + self.resume_queue(cx); + } else { + self.send_next(cx); } - self.queue.push_back(Queued { text, shown, compact: false, by_user: true, ahead: false }); - self.send_next(cx); cx.notify(); } fn send_next(&mut self, cx: &mut Context) { - if self.working || self.phase != Phase::Ready { + if self.working || self.phase != Phase::Ready || !self.steering.is_empty() || !self.questions.is_empty() { return; } let (Some(connection), Some(session), Some(events)) = (self.connection.clone(), self.session_id.clone(), self.events.clone()) else { return }; let command = self.harness.adapter().compact_command.filter(|name| self.thread.commands.iter().any(|c| c.name == *name)); - let next = if self.compaction.take_due(self.thread.context, command.is_some()) { + let next = if !self.queue_held && self.compaction.take_due(self.thread.context, command.is_some()) { let at = self.thread.notice("Compacting context…", false); self.remeasure(at); - Queued { text: format!("/{}", command.unwrap()), shown: true, compact: true, by_user: false, ahead: false } + Queued { shown: true, compact: true, ..Queued::new(format!("/{}", command.unwrap()), false) } } else { - let Some(next) = self.queue.pop_front() else { return }; - next + let Some(next) = self.queue.front() else { return }; + if (self.queue_held && !next.startup) || self.queue_edit.as_ref().is_some_and(|edit| edit.id == next.id) { + return; + } + self.queue.pop_front().unwrap() }; - if !next.shown && !next.compact - && let Some(at) = self.thread.sent(next.text.clone()) - { - self.remeasure(at); - } - self.cached_replay = false; - self.queue_changes += 1; - self.running_command = next.text.starts_with('/'); - let text = next.text; + let id = next.id; let compact = next.compact; - self.persist_entries(); - self.list.scroll_to_end(); + self.preparing = Some(next); self.working = true; self.changed = None; + self.queue_changed(); let cwd = self.cwd.clone(); cx.spawn(async move |this, cx| { - // The snapshot comes first, so the review sees what this turn changed. Outside a repository it fails, and the - // message goes anyway. let snapshot = if !compact { let session = session.clone(); - Some(cx.background_executor().spawn(async move { crate::git::snapshot::take(&cwd, &session) }).await) + cx.background_executor().spawn(async move { crate::git::snapshot::take(&cwd, &session) }).await.ok() } else { None }; - if let Some(Ok(id)) = snapshot { - let _ = this.update(cx, |v, _| v.snapshots.push(id)); + let prompt = this.update(cx, |v, cx| { + let next = v.take_prepared(id)?; + if let Some(snapshot) = snapshot { + v.snapshots.push(snapshot); + } + if !next.shown && !next.compact && let Some(at) = v.thread.sent(next.text.clone()) { + v.remeasure(at); + } + v.cached_replay = false; + v.running_command = next.text.starts_with('/'); + v.persist_entries(); + v.list.scroll_to_end(); + let request = connection.request("session/prompt", json!({"sessionId": session, "prompt": [{"type": "text", "text": next.text}]})); + v.queue_changed(); + cx.notify(); + Some(request) + }); + if let Ok(Some(prompt)) = prompt { + let _ = events.unbounded_send(Event::TurnEnded(prompt.await)); } - let turn = connection.request("session/prompt", json!({"sessionId": session, "prompt": [{"type": "text", "text": text}]})); - let result = turn.await; - let _ = events.unbounded_send(Event::TurnEnded(result)); }) .detach(); } + fn take_prepared(&mut self, id: Uuid) -> Option { + if self.phase != Phase::Ready { + return None; + } + self.preparing.take_if(|next| next.id == id) + } + fn turn_ended(&mut self, result: Result, cx: &mut Context) { self.working = false; + self.interrupting = false; self.last_update = None; let compacted = self.compaction.running; if std::mem::take(&mut self.compaction.running) { @@ -844,7 +1006,7 @@ impl ThreadView { } else { self.check_changes(cx); } - self.question = None; + self.cancel_questions(); let notice = match &result { Ok(r) => match r["stopReason"].as_str() { Some("cancelled") => Some(("Interrupted".to_string(), false)), @@ -865,42 +1027,16 @@ impl ThreadView { let at = self.thread.notice(text, error); self.remeasure(at); } - let steers_back = |kind: &str| -> Vec { - let list = result.as_ref().ok().and_then(|r| r.pointer(&format!("/_meta/m4code/{kind}"))).and_then(Value::as_array); - list.into_iter().flatten().filter_map(Value::as_str).map(String::from).collect() - }; - // Steers the agent never read: those it dropped by itself go as the next message, and those the user stopped - // are written out so nothing they typed is lost. - let (resend, unread) = (steers_back("resend"), steers_back("unread")); - self.steering.retain(|t| !resend.contains(t) && !unread.contains(t)); - for text in resend.into_iter().rev() { - self.queue.push_front(Queued { text, shown: false, compact: false, by_user: true, ahead: false }); - } - if !self.queue.is_empty() { - self.queue_changes += 1; - } - for text in unread { - let at = self.thread.notice(format!("The agent stopped before reading your message, so it was not sent: {text}"), false); - self.remeasure(at); + let restarting = std::mem::take(&mut self.restarting_for_steer); + if outcome == "failed" || (outcome == "interrupted" && !restarting) { + self.queue_held = true; } - // Steers still waiting were neither read nor given back, as when the turn failed: written out, like the - // unread ones, so nothing the user typed is lost. - for text in std::mem::take(&mut self.steering) { - let at = self.thread.notice(format!("The agent stopped before reading your message, so it was not sent: {text}"), false); - self.remeasure(at); + if self.harness.adapter().steers { + let ids = self.steering.iter().map(|item| item.id).collect::>(); + self.requeue_steers(ids); } self.persist_entries(); - if let Some((target, effort, mut message, mut by_agent)) = self.handoff_after_turn.take() { - let queued = self.queue.drain(..).map(|q| q.text).collect::>().join("\n\n"); - if !queued.is_empty() { - if by_agent { - self.thread.entries.push(Entry::Agent(message)); - message = queued; - by_agent = false; - } else { - message = format!("{message}\n\n{queued}"); - } - } + if !self.queue_held && let Some((target, effort, message, by_agent)) = self.handoff_after_turn.take() { let model = (!target.id.is_empty()).then_some(target.id); cx.emit(ThreadEvent::Handoff { to: target.harness, model, message, effort, by_agent }); cx.notify(); @@ -908,7 +1044,7 @@ impl ThreadView { } // Decided before `send_next`, which may start an automatic compaction: the turn's work is done all the same, // and its report is the reply above, not what the compaction says. - let idle = self.queue.is_empty() && !compacted; + let idle = (self.queue.is_empty() || self.queue_held) && !compacted; self.send_next(cx); if idle { cx.emit(ThreadEvent::Idle(outcome)); @@ -955,28 +1091,78 @@ impl ThreadView { } fn interrupt(&mut self, cx: &mut Context) { - self.queue.clear(); - if let (Some(c), Some(s)) = (&self.connection, &self.session_id) { + self.queue_held = true; + self.restarting_for_steer = false; + if let Some(mut item) = self.preparing.take() { + item.startup = false; + if item.compact { + self.compaction.running = false; + } else { + if item.shown && matches!(self.thread.entries.last(), Some(Entry::User(text)) if text == &item.text) { + let at = self.thread.entries.len() - 1; + self.thread.entries.pop(); + item.shown = false; + self.remeasure(at); + } + self.queue.push_front(item); + } + self.working = false; + self.queue_changed(); + self.cancel_questions(); + cx.notify(); + return; + } + self.cancel_questions(); + if !self.interrupting && let (Some(c), Some(s)) = (&self.connection, &self.session_id) { + self.interrupting = true; c.notify("session/cancel", json!({"sessionId": s})); } - // ACP says a client that cancels answers every open permission question as cancelled. - self.answer(None, cx); + cx.notify(); } /// Show a multiple-choice question from m4code's MCP `ask_user` tool (works on every harness, including ones /// whose native question tool isn't bridged over ACP). pub fn ask_bridge_question(&mut self, req_id: String, title: String, options: Vec, cx: &mut Context) { - if let Some(Question { reply: QuestionReply::Bridge(prev), .. }) = self.question.take() { - crate::claude::bridge::respond(&prev, false, "Replaced by a newer question."); + if self.interrupting || self.restarting_for_steer { + crate::claude::bridge::respond(&req_id, false, "The turn was interrupted."); + return; } - // `ask_user` answers with text, so the user's own words are an answer too. - self.question = Some(Question { reply: QuestionReply::Bridge(req_id), title, options, highlight: 0, takes_own_answer: true }); + self.questions.push_back(Question { id: Uuid::new_v4(), reply: QuestionReply::Bridge(req_id), title, options, highlight: 0, takes_own_answer: true }); cx.notify(); } + fn cancel_questions(&mut self) { + for question in self.questions.drain(..) { + match question.reply { + QuestionReply::Bridge(id) => crate::claude::bridge::respond(&id, false, "The user dismissed the question."), + QuestionReply::Acp(id) => { + if let Some(c) = &self.connection { + c.respond(id, acp::permission_outcome(None)); + } + } + QuestionReply::Elicitation { id, .. } => { + if let Some(c) = &self.connection { + c.respond(id, acp::elicitation_cancel()); + } + } + } + } + } + + pub(crate) fn answer_question(&mut self, id: Uuid, choice: Option, cx: &mut Context) -> bool { + if self.questions.front().is_none_or(|question| question.id != id) { + return false; + } + match choice { + Some(ix) => self.answer(Some(ix), cx), + None => self.decline(cx), + } + true + } + /// Answer the open permission/ask question with option `index` (from 0), or turn it down. pub fn answer(&mut self, index: Option, cx: &mut Context) { - let Some(q) = self.question.take() else { return }; + let Some(q) = self.questions.pop_front() else { return }; let chosen = index.and_then(|i| q.options.get(i)); match q.reply { QuestionReply::Acp(id) => { @@ -994,7 +1180,8 @@ impl ThreadView { .into_iter() .map(|o| QuestionOption { id: o.value, name: o.label, description: o.description, kind: "allow_once".into() }) .collect(); - self.question = Some(Question { + self.questions.push_front(Question { + id: Uuid::new_v4(), reply: QuestionReply::Elicitation { id, field: next.field, kind: next.kind, answers, remaining }, title: next.title, options, @@ -1013,12 +1200,14 @@ impl ThreadView { None => crate::claude::bridge::respond(&req_id, false, "The user dismissed the question."), }, } + self.send_next(cx); cx.notify(); } /// Answer the open question with what the user typed rather than one of its options. fn answer_in_own_words(&mut self, text: &str, cx: &mut Context) { - let Some(q) = self.question.take_if(|q| q.takes_own_answer) else { return }; + if !self.questions.front().is_some_and(|q| q.takes_own_answer) { return; } + let Some(q) = self.questions.pop_front() else { return }; match q.reply { QuestionReply::Acp(id) => { if let Some(c) = &self.connection { @@ -1029,12 +1218,13 @@ impl ThreadView { // Never marked as taking the user's own words (`takes_own_answer`). QuestionReply::Elicitation { .. } => {} } + self.send_next(cx); cx.notify(); } /// Move the open question's highlight to option `index`, as the mouse does. pub(super) fn highlight_option(&mut self, index: usize, cx: &mut Context) { - if let Some(q) = self.question.as_mut() + if let Some(q) = self.questions.front_mut() && q.highlight != index { q.highlight = index; @@ -1044,7 +1234,7 @@ impl ThreadView { /// Turn the question down with its own reject option when it has one. pub fn decline(&mut self, cx: &mut Context) { - let reject = self.question.as_ref().and_then(|q| q.options.iter().position(|o| o.kind == "reject_once")); + let reject = self.questions.front().and_then(|q| q.options.iter().position(|o| o.kind == "reject_once")); self.answer(reject, cx); } @@ -1185,7 +1375,7 @@ impl ThreadView { let state = keys::State { picker_open: self.picker.is_some(), working: self.working, - question: self.question.as_ref().map_or(0, |q| q.options.len()), + question: self.questions.front().map_or(0, |q| q.options.len()), draft_empty: draft.trim().is_empty(), in_history: self.history_at.is_some(), escape_just_pressed: self.last_escape.is_some_and(|t| t.elapsed() < keys::DOUBLE_PRESS), @@ -1193,6 +1383,11 @@ impl ThreadView { commands: self.matching_commands(cx).len(), }; let is_escape = ev.keystroke.key == "escape"; + if is_escape && self.queue_edit.is_some() && self.questions.is_empty() && self.picker.is_none() { + self.finish_queue_edit(false, window, cx); + cx.stop_propagation(); + return; + } let Some(key) = keys::key(&ev.keystroke, state) else { self.last_escape = is_escape.then(Instant::now); return; @@ -1209,11 +1404,11 @@ impl ThreadView { keys::Key::Decline => self.decline(cx), keys::Key::Choose(n) => self.answer(Some(n - 1), cx), keys::Key::ChooseHighlighted => { - let at = self.question.as_ref().map(|q| q.highlight); + let at = self.questions.front().map(|q| q.highlight); self.answer(at, cx); } keys::Key::OptionUp | keys::Key::OptionDown => { - if let Some(q) = self.question.as_mut() { + if let Some(q) = self.questions.front_mut() { let last = q.options.len().saturating_sub(1); q.highlight = match (key == keys::Key::OptionDown, q.highlight.min(last)) { (true, at) if at >= last => 0, @@ -1378,7 +1573,7 @@ impl ThreadView { pub(super) fn matching_commands(&self, cx: &App) -> Vec<&crate::harness::thread::Command> { let draft = self.composer.read(cx).value(); // What is typed answers the open question, so it is never a command to complete. - if self.question.as_ref().is_some_and(|q| q.takes_own_answer) { + if self.queue_edit.is_some() || self.questions.front().is_some_and(|q| q.takes_own_answer) { return vec![]; } let Some(typed) = draft.strip_prefix('/').filter(|t| !t.contains(char::is_whitespace)) else { return vec![] }; @@ -1415,35 +1610,6 @@ impl ThreadView { self.set_draft(&text, window, cx); } - /// Replace what the composer holds, with the cursor after it so typing carries on from the end. - /// Messages steered into the running turn that the agent hasn't read yet. - pub(super) fn unread_steers(&self) -> impl Iterator { - self.steering.iter().map(String::as_str) - } - - /// The user's messages waiting for the turn to end, with their place in `queue`. - pub(super) fn waiting_messages(&self) -> Vec<(usize, &str)> { - self.queue.iter().enumerate().filter(|(_, q)| q.by_user && !q.shown).map(|(i, q)| (i, q.text.as_str())).collect() - } - - /// Take a waiting message out of the queue; it is never sent. - pub(super) fn unqueue(&mut self, at: usize, cx: &mut Context) -> Option { - let waiting = self.queue.get(at).is_some_and(|q| q.by_user && !q.shown); - let text = waiting.then(|| self.queue.remove(at)).flatten().map(|q| q.text); - self.queue_changes += 1; - cx.notify(); - text - } - - /// Take a waiting message back into the message box to change it, after anything already typed there. - pub(super) fn edit_queued(&mut self, at: usize, window: &mut Window, cx: &mut Context) { - let Some(text) = self.unqueue(at, cx) else { return }; - let draft = self.composer.read(cx).value().to_string(); - let joined = if draft.trim().is_empty() { text } else { format!("{draft}\n\n{text}") }; - self.set_draft(&joined, window, cx); - self.focus_composer(window, cx); - } - fn set_draft(&mut self, text: &str, window: &mut Window, cx: &mut Context) { let text = text.to_string(); let end = text.len(); @@ -1495,7 +1661,9 @@ impl ThreadView { "80% between turns" } - pub fn stop(&self) { + pub fn stop(&mut self) { + self.preserve_handoff_message(); + self.cancel_questions(); if let Some(connection) = &self.connection { if let Some(session) = &self.session_id { connection.notify("session/cancel", json!({"sessionId": session})); @@ -1519,16 +1687,16 @@ impl ThreadView { /// Waiting for the user to answer a permission or ask question. pub fn is_waiting(&self) -> bool { - self.question.is_some() + !self.questions.is_empty() } /// Snapshot of the pending question, if any, so the sidebar popover can render and answer it. pub fn pending_question(&self) -> Option { - self.question.as_ref().map(|q| PendingQuestion { title: q.title.clone(), options: q.options.clone() }) + self.questions.front().map(|q| PendingQuestion { id: q.id, title: q.title.clone(), options: q.options.clone() }) } pub fn pending_question_title(&self) -> Option { - self.question.as_ref().map(|q| q.title.clone()) + self.questions.front().map(|q| q.title.clone()) } /// What the message box says while the agent starts, so the wait after a hand-off is visible. @@ -1595,18 +1763,20 @@ struct Opened { session_id: String, result: Value, capabilities: Value, + agent_meta: Value, replayed: bool, } async fn open(c: &Connection, harness: Harness, start: &Start) -> Result { let initialized = c.request("initialize", acp::initialize_params()).await.map_err(|e| format!("{} didn't start: {e}", harness.name()))?; let capabilities = initialized["agentCapabilities"].clone(); + let agent_meta = initialized["_meta"].clone(); let mut params = json!({"cwd": start.cwd, "mcpServers": start.mcp_servers, "_meta": start.meta}); match &start.session_id { None => { let result = c.request("session/new", params).await.map_err(|e| format!("{} couldn't start a session: {e}", harness.name()))?; let id = result["sessionId"].as_str().ok_or("the agent named no session")?.to_string(); - Ok(Opened { session_id: id, result, capabilities, replayed: false }) + Ok(Opened { session_id: id, result, capabilities, agent_meta, replayed: false }) } Some(id) => { params["sessionId"] = json!(id); @@ -1616,16 +1786,13 @@ async fn open(c: &Connection, harness: Harness, start: &Start) -> Result "session/resume", }; let result = c.request(method, params).await.map_err(|e| format!("{} couldn't open the session: {e}", harness.name()))?; - Ok(Opened { session_id: id.clone(), result, capabilities, replayed: reopen == Reopen::Load }) + Ok(Opened { session_id: id.clone(), result, capabilities, agent_meta, replayed: reopen == Reopen::Load }) } } } impl Drop for ThreadView { fn drop(&mut self) { - if let Some(Question { reply: QuestionReply::Bridge(req_id), .. }) = self.question.take() { - crate::claude::bridge::respond(&req_id, false, "The session closed before the user answered."); - } self.stop(); if self.persist_on_drop { self.persist_entries(); @@ -1641,6 +1808,10 @@ fn is_conversation_update(update: &Value) -> bool { } /// `comment` after the text typed so far, on a line of its own, so several comments read as a list. +pub(crate) fn has_saved_queue(record_id: &str) -> bool { + !queue::load(record_id).is_empty() +} + pub(crate) fn with_comment(typed: &str, comment: &str) -> String { let typed = typed.trim_end(); if typed.is_empty() { comment.to_string() } else { format!("{typed}\n{comment}") } @@ -1655,6 +1826,95 @@ mod tests { use super::with_comment; use crate::harness::{Harness, thread::Entry}; + fn test_start(cwd: std::path::PathBuf, harness: Harness) -> super::Start { + super::Start { + record_id: String::new(), harness, all_models: vec![], picked: vec![], cwd, + env: vec![], mcp_servers: vec![], meta: serde_json::Value::Null, session_id: None, mode: None, + options: vec![], prompt: None, prior_entries: vec![], + server: Some(("definitely-not-a-real-program-m4code".into(), vec![])), + } + } + + #[gpui::test] + fn interrupt_before_dispatch_preserves_the_queue_and_cancels_each_request(cx: &mut gpui::TestAppContext) { + use std::io::{BufRead, BufReader}; + use serde_json::{Value, json}; + use super::{Connection, Event, Phase, Queued, ThreadView}; + + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let (view, cx) = cx.add_window_view(|window, cx| ThreadView::new(test_start(dir.path().into(), Harness::Claude), window, cx)); + let (from_agent, to_client) = std::io::pipe().unwrap(); + let (from_client, to_agent) = std::io::pipe().unwrap(); + std::mem::forget(to_client); + let (tx, _events) = futures::channel::mpsc::unbounded(); + let connection = Connection::connect(from_agent, to_agent, None::, tx); + view.update(cx, |v, cx| { + v.connection = Some(std::rc::Rc::new(connection)); + v.session_id = Some("s".into()); + v.phase = Phase::Ready; + v.working = true; + let first = Queued::new("first".into(), true); + let id = first.id; + v.preparing = Some(first); + v.send_as("second".into(), crate::store::FollowUp::Queue, cx); + + for (request, title) in [(7, "first approval"), (8, "second approval")] { + v.on_event(Event::Permission { id: json!(request), params: json!({ + "toolCall": {"title": title, "kind": "execute"}, + "options": [{"optionId": "allow", "name": "Allow", "kind": "allow_once"}] + }) }, cx); + } + assert_eq!(v.pending_question_title().as_deref(), Some("first approval")); + let shown = v.pending_question().unwrap().id; + assert!(v.answer_question(shown, Some(0), cx)); + assert_eq!(v.pending_question_title().as_deref(), Some("second approval")); + assert!(!v.answer_question(shown, Some(0), cx), "a click from the old question cannot approve the next"); + v.interrupt(cx); + assert!(!v.is_waiting()); + assert!(v.queue_held); + assert!(v.take_prepared(id).is_none(), "the snapshot completion can no longer dispatch this prompt"); + assert_eq!(v.waiting_messages().map(|(_, text)| text).collect::>(), ["first", "second"]); + }); + + let mut replies = BufReader::new(from_client).lines(); + let approved: Value = serde_json::from_str(&replies.next().unwrap().unwrap()).unwrap(); + let cancelled: Value = serde_json::from_str(&replies.next().unwrap().unwrap()).unwrap(); + assert_eq!(approved["id"], 7); + assert_eq!(approved["result"]["outcome"]["optionId"], "allow"); + assert_eq!(cancelled["id"], 8); + assert_eq!(cancelled["result"]["outcome"]["outcome"], "cancelled"); + } + + #[gpui::test] + fn codex_uses_the_advertised_steering_extension_without_cancelling(cx: &mut gpui::TestAppContext) { + use std::io::{BufRead, BufReader}; + use serde_json::{Value, json}; + use super::{Connection, Phase, ThreadView}; + + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let (view, cx) = cx.add_window_view(|window, cx| ThreadView::new(test_start(dir.path().into(), Harness::Codex), window, cx)); + let (from_agent, to_client) = std::io::pipe().unwrap(); + let (from_client, to_agent) = std::io::pipe().unwrap(); + std::mem::forget(to_client); + let (tx, _events) = futures::channel::mpsc::unbounded(); + let connection = Connection::connect(from_agent, to_agent, None::, tx); + view.update(cx, |v, cx| { + v.connection = Some(std::rc::Rc::new(connection)); + v.session_id = Some("s".into()); + v.phase = Phase::Ready; + v.working = true; + v.agent_meta = json!({"steering": {"supported": true}}); + v.send_as("change focus".into(), crate::store::FollowUp::Steer, cx); + assert_eq!(v.unread_steers().collect::>(), ["change focus"]); + }); + let request: Value = serde_json::from_str(&BufReader::new(from_client).lines().next().unwrap().unwrap()).unwrap(); + assert_eq!(request["method"], "_session/steering"); + assert_eq!(request["params"]["prompt"][0]["text"], "change focus"); + assert_eq!(request["params"]["_meta"]["steering"]["idleBehavior"], "promptRequired"); + } + #[test] fn a_comment_goes_on_its_own_line_after_what_was_typed() { assert_eq!(with_comment("", "@a.rs#L1: why"), "@a.rs#L1: why"); @@ -1703,7 +1963,7 @@ mod tests { } #[gpui::test] - fn a_waiting_message_can_be_taken_back_but_m4codes_own_cannot(cx: &mut gpui::TestAppContext) { + fn queue_edits_keep_the_draft_and_queue_position(cx: &mut gpui::TestAppContext) { cx.update(gpui_kit::init); let dir = tempfile::tempdir().unwrap(); let start = super::Start { @@ -1725,16 +1985,25 @@ mod tests { let (view, cx) = cx.add_window_view(|window, cx| super::ThreadView::new(start, window, cx)); view.update_in(cx, |v, window, cx| { v.queue.clear(); - v.queue.push_back(super::Queued { text: "report".into(), shown: false, compact: false, by_user: false, ahead: false }); - v.queue.push_back(super::Queued { text: "first\nmore".into(), shown: false, compact: false, by_user: true, ahead: false }); - v.queue.push_back(super::Queued { text: "second".into(), shown: false, compact: false, by_user: true, ahead: false }); - assert_eq!(v.waiting_messages(), [(1, "first\nmore"), (2, "second")]); - assert_eq!(v.unqueue(0, cx), None, "a subagent's report is not the user's to remove"); + v.queue.push_back(super::Queued::new("report".into(), false)); + v.queue.push_back(super::Queued::new("first\nmore".into(), true)); + v.queue.push_back(super::Queued::new("second".into(), true)); + let id = v.queue[1].id; + assert_eq!(v.waiting_messages().map(|(_, text)| text).collect::>(), ["first\nmore", "second"]); + assert!(v.unqueue(v.queue[0].id, cx).is_none(), "a report is not the user's to remove"); v.set_draft("typed", window, cx); - v.edit_queued(1, window, cx); - assert_eq!(v.composer.read(cx).value().as_ref(), "typed\n\nfirst\nmore"); - assert_eq!(v.unqueue(1, cx).as_deref(), Some("second")); - assert_eq!(v.queue.len(), 1, "only the report is left"); + v.edit_queued(id, window, cx); + assert_eq!(v.draft(cx), "first\nmore"); + v.set_draft("changed", window, cx); + v.finish_queue_edit(false, window, cx); + assert_eq!(v.draft(cx), "typed"); + assert_eq!(v.queue[1].text, "first\nmore"); + v.edit_queued(id, window, cx); + v.set_draft("changed", window, cx); + v.finish_queue_edit(true, window, cx); + assert_eq!(v.draft(cx), "typed"); + assert_eq!((v.queue[1].id, v.queue[1].text.as_str()), (id, "changed")); + assert_eq!(v.unqueue(v.queue[2].id, cx).unwrap().text, "second"); }); } @@ -1776,7 +2045,7 @@ mod tests { // With no agent to reach, the message waits rather than being lost. v.queue.clear(); v.send_as("hi".into(), FollowUp::Steer, cx); - assert_eq!(v.waiting_messages(), [(0, "hi")]); + assert_eq!(v.waiting_messages().map(|(_, text)| text).collect::>(), ["hi"]); }); } @@ -1857,7 +2126,7 @@ mod tests { // What the agent was still writing when the steer went out. v.on_event(Event::Update(chunk("agent_message_chunk", "ld.")), cx); let mut read = chunk("user_message_chunk", "stop"); - read["_meta"] = json!({"m4code": {"steer": true}}); + read["_meta"] = json!({"m4code": {"steer": v.steering.front().unwrap().id.to_string()}}); v.on_event(Event::Update(read), cx); v.on_event(Event::Update(chunk("agent_message_chunk", "Stopping.")), cx); assert_eq!(v.thread.entries, [Entry::Agent("Hello world.".into()), Entry::User("stop".into()), Entry::Agent("Stopping.".into())]); @@ -1867,19 +2136,17 @@ mod tests { v.send_as("do Y".into(), FollowUp::Steer, cx); for text in ["do X", "do Y"] { let mut read = chunk("user_message_chunk", text); - read["_meta"] = json!({"m4code": {"steer": true}}); + read["_meta"] = json!({"m4code": {"steer": v.steering.front().unwrap().id.to_string()}}); v.on_event(Event::Update(read), cx); } assert_eq!(v.thread.entries[3..], [Entry::User("do X".into()), Entry::User("do Y".into())]); - // A steer the turn ends without reading, as when it fails, is written out rather than lost. + v.send_as("older".into(), FollowUp::Queue, cx); v.send_as("unread".into(), FollowUp::Steer, cx); + v.send_as("later".into(), FollowUp::Queue, cx); v.turn_ended(Err("Claude Code stopped.".into()), cx); assert_eq!(v.unread_steers().count(), 0); - assert!( - v.thread.entries.iter().any(|e| matches!(e, Entry::Notice { text, .. } if text.ends_with(": unread"))), - "{:?}", - v.thread.entries - ); + assert!(v.queue_held); + assert_eq!(v.waiting_messages().map(|(_, text)| text).collect::>(), ["older", "unread", "later"]); }); } diff --git a/src/thread/queue.rs b/src/thread/queue.rs new file mode 100644 index 0000000..10b57fe --- /dev/null +++ b/src/thread/queue.rs @@ -0,0 +1,206 @@ +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use gpui::{Context, Window}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use super::{ThreadEvent, ThreadView}; + +#[derive(Deserialize, Serialize)] +pub(super) struct Queued { + pub id: Uuid, + #[serde(skip)] + pub order: u64, + #[serde(skip)] + pub startup: bool, + pub text: String, + pub compact: bool, + // Reports and initial prompts have their own owners and are not restored from the user queue. + pub by_user: bool, + pub ahead: bool, + pub shown: bool, +} + +impl Queued { + pub fn new(text: String, by_user: bool) -> Self { + Self { id: Uuid::new_v4(), order: next_order(), startup: false, text, compact: false, by_user, ahead: false, shown: false } + } +} + +pub(super) fn next_order() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(0); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +pub(super) struct Edit { + pub id: Uuid, + pub draft: String, +} + +fn path(record: &str) -> PathBuf { + crate::datadir::data_dir().join("queues").join(format!("{}.json", crate::datadir::safe_file_stem(record))) +} + +pub(super) fn load(record: &str) -> VecDeque { + if record.is_empty() { + return VecDeque::new(); + } + load_from(&path(record)) +} + +fn load_from(path: &std::path::Path) -> VecDeque { + std::fs::read(path).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default() +} + +pub(super) fn save<'a>(record: &str, messages: impl Iterator) -> std::io::Result<()> { + if record.is_empty() { + return Ok(()); + } + save_at(&path(record), messages) +} + +fn save_at<'a>(path: &std::path::Path, messages: impl Iterator) -> std::io::Result<()> { + let messages = messages.filter(|item| item.by_user).collect::>(); + if messages.is_empty() { + return match std::fs::remove_file(path) { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + result => result, + }; + } + crate::datadir::write_atomic(path, &serde_json::to_string(&messages)?) +} + +impl ThreadView { + pub(super) fn queue_changed(&mut self) { + let mut waiting = self.queue.iter().collect::>(); + for item in &self.steering { + let at = waiting.iter().position(|queued| !queued.ahead && queued.order > item.order) + .unwrap_or(waiting.len()); + waiting.insert(at, item); + } + let pending = self.preparing.iter().chain(waiting); + let error = save(&self.record_id, pending).err(); + if let Some(error) = &error && !self.queue_save_error { + let at = self.thread.notice(format!("Could not save queued messages: {error}"), true); + self.remeasure(at); + } + self.queue_save_error = error.is_some(); + } + + pub(super) fn unread_steers(&self) -> impl Iterator { + self.steering.iter().map(|item| item.text.as_str()) + } + + pub(super) fn waiting_messages(&self) -> impl Iterator { + self.queue.iter().filter(|item| item.by_user).map(|item| (item.id, item.text.as_str())) + } + + pub(super) fn unqueue(&mut self, id: Uuid, cx: &mut Context) -> Option { + let at = self.queue.iter().position(|item| item.by_user && item.id == id)?; + let item = self.queue.remove(at)?; + cx.notify(); + Some(item) + } + + pub(super) fn edit_queued(&mut self, id: Uuid, window: &mut Window, cx: &mut Context) { + if !self.questions.is_empty() || self.queue_edit.is_some() { + return; + } + if let Some(item) = self.queue.iter().find(|item| item.by_user && item.id == id) { + let text = item.text.clone(); + self.queue_edit = Some(Edit { id, draft: self.draft(cx) }); + self.set_draft(&text, window, cx); + self.focus_composer(window, cx); + cx.notify(); + } + } + + pub(super) fn finish_queue_edit(&mut self, save: bool, window: &mut Window, cx: &mut Context) { + let text = self.draft(cx); + if save && (!crate::panels::composer::can_send(&text) || !self.questions.is_empty()) { + return; + } + let Some(edit) = self.queue_edit.take() else { return }; + if save && let Some(item) = self.queue.iter_mut().find(|item| item.id == edit.id) { + item.text = text.trim().to_string(); + item.shown = false; + self.queue_changed(); + } + self.set_draft(&edit.draft, window, cx); + self.focus_composer(window, cx); + self.send_next(cx); + cx.notify(); + } + + pub(super) fn send_queued_now(&mut self, id: Uuid, cx: &mut Context) { + if self.interrupting || !self.questions.is_empty() || self.queue_edit.as_ref().is_some_and(|edit| edit.id == id) { + return; + } + let Some(mut item) = self.unqueue(id, cx) else { return }; + if self.can_steer(&item.text, crate::store::FollowUp::Steer) { + self.steer(item, cx); + } else { + item.ahead = true; + self.queue.push_front(item); + self.queue_held = false; + self.queue_changed(); + self.send_next(cx); + cx.notify(); + } + } + + pub(crate) fn restore_queue_after_handoff(&mut self, cx: &mut Context) { + self.queue.retain(|item| !item.by_user); + let saved = load(&self.record_id); + self.queue_held |= !saved.is_empty(); + self.queue.extend(saved.into_iter().map(|mut item| { + item.order = next_order(); + item.ahead = false; + item.shown = false; + item + })); + cx.notify(); + } + + pub(super) fn preserve_handoff_message(&mut self) { + if let Some((_, _, text, false)) = self.handoff_after_turn.take() { + self.queue.push_back(Queued::new(text, true)); + self.queue_changed(); + } + } + + pub(super) fn resume_queue(&mut self, cx: &mut Context) { + self.queue_held = false; + if !self.working && self.steering.is_empty() + && let Some((target, effort, message, by_agent)) = self.handoff_after_turn.take() + { + let model = (!target.id.is_empty()).then_some(target.id); + cx.emit(ThreadEvent::Handoff { to: target.harness, model, message, effort, by_agent }); + } else { + self.send_next(cx); + } + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::{Queued, load_from, save_at}; + + #[test] + fn waiting_user_messages_survive_restart_in_dispatch_order() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("queue.json"); + let first = Queued::new("first".into(), true); + let last = Queued::new("last".into(), true); + let report = Queued::new("report".into(), false); + save_at(&path, [&first, &report, &last].into_iter()).unwrap(); + let restored = load_from(&path); + assert_eq!(restored.iter().map(|q| q.text.as_str()).collect::>(), ["first", "last"]); + assert_eq!(restored[0].id, first.id); + save_at(&path, std::iter::empty()).unwrap(); + assert!(load_from(&path).is_empty()); + } +} diff --git a/src/thread/render.rs b/src/thread/render.rs index c8edd29..3069bc0 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -18,7 +18,7 @@ use crate::harness::CatalogModel; use crate::harness::thread::{Entry, SubagentReport, ToolCall, ToolContent, ToolStatus, diff_lines, parse_subagent_report}; use crate::panels::{composer, logos, picker, scale}; use crate::panels::theme::{self, hsla}; -use crate::panels::widgets::{EffortPick, Trigger, effort_slider, icon, icon_button, key_badge, spinner}; +use crate::panels::widgets::{EffortPick, Trigger, button, button_disabled, effort_slider, icon, icon_button, key_badge, spinner}; use crate::visual::ui::Scope; /// Lines of a tool's output shown while it is folded (Ctrl+O shows all). @@ -625,7 +625,7 @@ impl ThreadView { }) .collect() }; - if self.background.is_empty() && bg_tools.is_empty() { + if self.background.is_empty() && self.provider_shells.is_empty() && bg_tools.is_empty() { return None; } let mut pills = div().flex().flex_wrap().items_center().gap(px(6.0)).flex_1().min_w_0(); @@ -675,6 +675,25 @@ impl ThreadView { .child(div().max_w(px(220.0)).overflow_hidden().whitespace_nowrap().text_ellipsis().child(name)), ); } + for shell in &self.provider_shells { + let read_id = shell.id.clone(); + let stop_id = shell.id.clone(); + let stopping = shell.stopping; + pills = pills.child( + div().flex().items_center().gap(px(6.0)).p(px(3.0)) + .child(spinner(format!("provider-shell-{}", shell.id), 10.0)) + .child(div().max_w(px(220.0)).overflow_hidden().text_ellipsis().whitespace_nowrap() + .text_size(scale::px(11.5)).child(shell.label.clone())) + .child(button(SharedString::from(format!("shell-output-{}", shell.id)), "Output", false) + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| v.background_shell_action(&read_id, false, cx)))) + .child(if stopping { + button_disabled(SharedString::from(format!("shell-stop-{}", shell.id)), "Stopping…") + } else { + button(SharedString::from(format!("shell-stop-{}", shell.id)), "Stop", false) + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| v.background_shell_action(&stop_id, true, cx))) + }), + ); + } let bar = div() .w_full() .max_w(px(COLUMN_MAX_W)) @@ -689,16 +708,28 @@ impl ThreadView { .gap(px(8.0)) .child(div().flex_none().text_size(scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child("Running in background")) .child(pills); - Some(div().w_full().px(px(22.0)).mb(px(6.0)).flex().justify_center().child(bar)) + let output = self.shell_output.as_ref().map(|output| { + div().id("thread-shell-output").w_full().max_h(px(180.0)).overflow_y_scroll() + .rounded(px(6.0)).bg(hsla(theme::SURFACE_ELEVATED)).p(px(8.0)) + .child(div().flex().justify_end() + .child(button("thread-shell-output-close", "Close output", false).on_click(cx.listener(|v, _: &ClickEvent, _, cx| { + v.shell_output = None; + cx.notify(); + })))) + .child(div().font_family(crate::platform::monospace_font()).text_size(scale::px(11.5)).child(output.text.clone())) + }); + Some(div().w_full().px(px(22.0)).mb(px(6.0)).flex().justify_center() + .child(div().w_full().max_w(px(COLUMN_MAX_W)).flex().flex_col().gap(px(4.0)).child(bar).children(output))) } fn render_question(&self, cx: &mut Context) -> Option
{ - let q = self.question.as_ref()?; + let q = self.questions.front()?; + let question_id = q.id; let mut options = div().flex().flex_col().gap(px(6.0)).w_full(); for (i, opt) in q.options.iter().enumerate() { let lit = i == q.highlight; let row = div() - .id(SharedString::from(format!("thread-perm-{i}"))) + .id(SharedString::from(format!("thread-perm-{question_id}-{i}"))) .w_full() .px(px(10.0)) .py(px(8.0)) @@ -737,7 +768,7 @@ impl ThreadView { .child(desc) })), ) - .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| v.answer(Some(i), cx))); + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| { v.answer_question(question_id, Some(i), cx); })); options = options.child(row); } // Inside the message box, above where you type: a long list of options scrolls on its own. @@ -753,6 +784,7 @@ impl ThreadView { .flex_col() .gap(px(8.0)) .child(div().font_weight(FontWeight::SEMIBOLD).child(q.title.clone())) + .when(self.questions.len() > 1, |card| card.child(div().text_size(scale::px(11.5)).text_color(hsla(theme::TEXT_DIM)).child(format!("{} more requests", self.questions.len() - 1)))) .child(div().id("thread-question-options").max_h(px(240.0)).overflow_y_scroll().child(options)) .child( div() @@ -898,7 +930,7 @@ impl ThreadView { )) } - fn render_composer(&self, window: &mut Window, cx: &mut Context) -> Div { + fn render_composer(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let mut inner = div().w_full().max_w(px(COLUMN_MAX_W)).flex().flex_col().gap(px(6.0)); let commands = self.matching_commands(cx); @@ -983,7 +1015,7 @@ impl ThreadView { .on_mouse_down(MouseButton::Left, cx.listener(|v, _, window, cx| v.composer.update(cx, |c, cx| c.focus(window, cx)))) .child(Textarea::new(&self.composer).appearance(false)) .into_any_element(); - let dock = composer::render(self.composer_parts(focused, input, cx)); + let dock = composer::render(self.composer_parts(focused, input, window.modifiers().secondary(), cx)); div() .flex_none() @@ -993,13 +1025,15 @@ impl ThreadView { .pt(px(4.0)) .flex() .justify_center() + .id("thread-composer-dock") + .on_modifiers_changed(cx.listener(|_, _: &gpui::ModifiersChangedEvent, _, cx| cx.notify())) .child(inner.children(self.render_waiting(cx)).child(dock)) } /// The user's messages waiting for the turn to end, above the message box, each one editable or removable /// before it is sent. fn render_waiting(&self, cx: &mut Context) -> Option
{ - let waiting = self.waiting_messages(); + let waiting = self.waiting_messages().collect::>(); let steering: Vec = self.unread_steers().map(first_line).collect(); if waiting.is_empty() && steering.is_empty() { return None; @@ -1017,9 +1051,9 @@ impl ThreadView { .child(div().flex_none().text_size(scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child("Read after the current step")) }); let waiting_empty = waiting.is_empty(); - let changes = self.queue_changes; - let rows = waiting.into_iter().map(|(at, text)| { - let first_line = first_line(text); + let rows = waiting.into_iter().map(|(id, text)| { + let editing = self.queue_edit.as_ref().is_some_and(|edit| edit.id == id); + let can_act = !editing && !self.interrupting && self.questions.is_empty(); div() .w_full() .flex() @@ -1027,20 +1061,32 @@ impl ThreadView { .gap(px(8.0)) .px(px(10.0)) .py(px(4.0)) + .when(editing, |row| row.bg(hsla(theme::SURFACE_HOVER))) .child(icon(IconName::Clock, 12.0).text_color(hsla(theme::TEXT_FAINT))) - .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(scale::px(12.5)).text_color(hsla(theme::TEXT_DIM)).child(first_line)) - .child( - icon_button(SharedString::from(format!("queued-edit-{changes}-{at}")), IconName::Pencil) - .on_click(cx.listener(move |v, _: &ClickEvent, window, cx| v.edit_queued(at, window, cx))), - ) - .child( - icon_button(SharedString::from(format!("queued-remove-{changes}-{at}")), IconName::X) - .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| drop(v.unqueue(at, cx)))), - ) + .child(div().flex_1().min_w_0().overflow_hidden().text_size(scale::px(12.5)).text_color(hsla(theme::TEXT_DIM)).child(text.to_string())) + .when(can_act, |row| { + row.child(button(SharedString::from(format!("queued-send-{id}")), "Send now", false) + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| v.send_queued_now(id, cx)))) + .when(self.queue_edit.is_none(), |row| row.child( + icon_button(SharedString::from(format!("queued-edit-{id}")), IconName::Pencil) + .on_click(cx.listener(move |v, _: &ClickEvent, window, cx| v.edit_queued(id, window, cx))), + )) + .child( + icon_button(SharedString::from(format!("queued-remove-{id}")), IconName::X) + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| { + if v.unqueue(id, cx).is_some() { + v.queue_changed(); + } + })), + ) + }) }); Some( - div() + div().child(div() + .id("thread-queue") .w_full() + .max_h(px(180.0)) + .overflow_y_scroll() .py(px(4.0)) .rounded(px(10.0)) .bg(hsla(theme::SURFACE_ELEVATED)) @@ -1049,14 +1095,14 @@ impl ThreadView { .flex() .flex_col() .children(steering_rows) - .when(!waiting_empty, |d| d.child(div().px(px(10.0)).pt(px(2.0)).text_size(scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child("Queued for after this turn"))) - .children(rows), + .when(!waiting_empty, |d| d.child(div().px(px(10.0)).pt(px(2.0)).text_size(scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(if self.queue_held { "Queue paused" } else { "Queued for after this turn" }))) + .children(rows)), ) } /// Assemble the shared message box parts: model, permission mode, branch, review and send. What the agent is /// doing shows in the chat (`render_activity`) and what waits shows above the box (`render_waiting`). - fn composer_parts(&self, focused: bool, input: AnyElement, cx: &mut Context) -> composer::Composer { + fn composer_parts(&self, focused: bool, input: AnyElement, alternate: bool, cx: &mut Context) -> composer::Composer { let active_harness = self.pending_model.as_ref().map_or(self.harness, |m| m.harness); let (_, effort_labels, effort_ix, _) = self.effort_choices(); let effort_badge = effort_labels.get(effort_ix).cloned(); @@ -1105,13 +1151,57 @@ impl ThreadView { }; extra_actions.push(chip.child("Review changes").into_any_element()); } - let can_send = composer::can_send(self.composer.read(cx).value().as_ref()); - let send = composer::send_button("thread-send", can_send) - .when(can_send, |d| d.on_click(cx.listener(|v, _: &ClickEvent, window, cx| v.submit(window, cx)))) - .into_any_element(); + let draft = self.composer.read(cx).value(); + let has_text = composer::can_send(draft.as_ref()); + let editing = self.queue_edit.is_some(); + let idle_for_resume = !self.working && self.queue_held && self.questions.is_empty() + && (self.waiting_messages().next().is_some() || self.handoff_after_turn.is_some()); + let answering = self.questions.front().is_some_and(|q| q.takes_own_answer); + let follow_up = if alternate { self.follow_up.other() } else { self.follow_up }; + let label = if editing { + extra_actions.push(button("thread-cancel-edit", "Cancel", false) + .on_click(cx.listener(|v, _: &ClickEvent, window, cx| v.finish_queue_edit(false, window, cx))) + .into_any_element()); + "Save" + } else if answering { + "Answer" + } else if !has_text && self.interrupting { + "Stopping…" + } else if !has_text && self.working { + "Interrupt" + } else if !has_text && idle_for_resume { + "Resume" + } else if self.can_steer(draft.trim(), follow_up) { + "Steer" + } else if self.working || self.phase == super::Phase::Starting { + "Queue" + } else { + "Send" + }; + let enabled = if editing { + has_text && self.questions.is_empty() + } else if answering { + has_text + } else { + has_text || (self.working && !self.interrupting) || idle_for_resume + }; + let send = if enabled { + button("thread-send", label, true) + .on_click(cx.listener(|v, ev: &ClickEvent, window, cx| { + if v.queue_edit.is_some() || composer::can_send(&v.draft(cx)) { + v.submit_with(ev.modifiers().secondary(), window, cx); + } else if v.working { + v.interrupt(cx); + } else if v.queue_held && v.questions.is_empty() { + v.resume_queue(cx); + } + })) + } else { + button_disabled("thread-send", label) + }.h(px(26.0)).px(px(12.0)).into_any_element(); composer::Composer { - lit: focused || self.question.is_some(), + lit: focused || !self.questions.is_empty(), top: self.render_question(cx).map(IntoElement::into_any_element), input, model,