From 19b59c357b6b26f056dd5d0941dafb8ab906feb0 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 20:58:33 +0200 Subject: [PATCH 1/8] Fix Shift+Enter, show work and the queue in the chat, and let questions take your own answer - Shift+Enter starts a new line in Home and the chat: the textarea reports it as Enter too, so both now send only through `composer::sends`. - The working status moves from the message box to the foot of the chat. - Messages waiting for the turn to end show above the message box, where they can be edited or removed. - The user's messages render as Markdown and keep their line breaks. - A question's highlight follows the arrows and the mouse, and Enter picks it. Claude Code's questions take what is typed in the message box as the answer, through `_meta.m4code` on the permission request and its reply. --- README.md | 2 +- bridge/claude.mjs | 11 ++- src/app/mod.rs | 2 +- src/harness/acp.rs | 18 +++++ src/panels/composer.rs | 20 ++++++ src/thread/keys.rs | 20 ++++++ src/thread/mod.rs | 130 +++++++++++++++++++++++++++++++++-- src/thread/render.rs | 149 ++++++++++++++++++++++++++++++++++------- 8 files changed, 317 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 67e5551..7bc8876 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. 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. 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. Messages you send meanwhile wait in a list above the message box, where you can edit or remove them before m4code sends them. 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. 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/claude.mjs b/bridge/claude.mjs index e708c18..9ea6b89 100644 --- a/bridge/claude.mjs +++ b/bridge/claude.mjs @@ -213,11 +213,16 @@ async function permission(session, name, input, options) { return { behavior: "deny", message: "The user declined this.", interrupt: chosen === null }; } -/** Claude's questions to the user, one at a time, each with its options. A multiple-choice question takes one answer. */ +/** + * Claude's questions to the user, one at a time, each with its options. A multiple-choice question takes one answer. + * ACP has no free-text answer, so `_meta.m4code.freeText` tells m4code the user may type their own instead, and + * m4code sends those words back in the answer's `_meta.m4code.text`. + */ async function askQuestions(session, input, options) { const answers = {}; for (const q of input?.questions ?? []) { const answer = await ask("session/request_permission", { + _meta: { m4code: { freeText: true } }, sessionId: session.id, toolCall: { toolCallId: `${options.toolUseID}-${q.question}`, title: q.question, kind: "other", status: "pending" }, options: [ @@ -227,7 +232,9 @@ async function askQuestions(session, input, options) { }); const chosen = answer?.outcome?.outcome === "selected" ? answer.outcome.optionId : null; if (chosen === null) return { behavior: "deny", message: "The user dismissed the question.", interrupt: true }; - if (chosen !== "skip") answers[q.question] = q.options[Number(chosen)].label; + const own = answer?._meta?.m4code?.text; + if (typeof own === "string" && own.trim()) answers[q.question] = own.trim(); + else if (chosen !== "skip" && q.options[Number(chosen)]) answers[q.question] = q.options[Number(chosen)].label; } return { behavior: "allow", updatedInput: { ...input, answers } }; } diff --git a/src/app/mod.rs b/src/app/mod.rs index 2682039..c8b275c 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -668,7 +668,7 @@ impl Workspace { let home_prompt = cx.new(|cx| TextareaState::new(window, cx).auto_grow(2, 8).submit_on_enter(true).placeholder("Ask anything, or describe a task…")); cx.subscribe_in(&home_prompt, window, |ws: &mut Self, _, ev: &InputEvent, window, cx| { match ev { - InputEvent::PressEnter { .. } => ws.act(Act::HomeLaunch, window, cx), + ev if crate::panels::composer::sends(ev) => ws.act(Act::HomeLaunch, window, cx), InputEvent::Change => cx.notify(), _ => {} } diff --git a/src/harness/acp.rs b/src/harness/acp.rs index e9752e1..48d5c32 100644 --- a/src/harness/acp.rs +++ b/src/harness/acp.rs @@ -323,6 +323,16 @@ pub fn permission_outcome(option: Option<&str>) -> Value { } } +/// A question m4code's own Claude Code bridge asks can take the user's own words instead of one of its options. ACP has +/// no such answer, so the bridge marks the question and reads the words from the answer's `_meta` (`own_answer`). +pub fn takes_own_answer(params: &Value) -> bool { + params["_meta"]["m4code"]["freeText"].as_bool() == Some(true) +} + +pub fn own_answer(text: &str) -> Value { + json!({ "outcome": { "outcome": "selected", "optionId": "other" }, "_meta": { "m4code": { "text": text } } }) +} + pub fn is_tool_permission(params: &Value) -> bool { matches!(params["toolCall"]["kind"].as_str(), Some("read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "switch_mode")) } @@ -499,4 +509,12 @@ mod tests { assert_eq!(elicitation_cancel(), json!({"action": "cancel"})); assert_eq!(elicitation_decline(), json!({"action": "decline"})); } + + #[test] + fn only_a_marked_question_takes_the_users_own_words() { + assert!(takes_own_answer(&json!({"_meta": {"m4code": {"freeText": true}}, "options": []}))); + assert!(!takes_own_answer(&json!({"options": []})), "a plain ACP permission question"); + assert_eq!(own_answer("blue")["_meta"]["m4code"]["text"], "blue"); + assert_eq!(own_answer("blue")["outcome"]["outcome"], "selected"); + } } diff --git a/src/panels/composer.rs b/src/panels/composer.rs index eb6328c..a17df75 100644 --- a/src/panels/composer.rs +++ b/src/panels/composer.rs @@ -3,6 +3,7 @@ use gpui::{AnyElement, Div, ElementId, InteractiveElement, IntoElement, ParentElement, SharedString, Stateful, Styled, div, prelude::FluentBuilder, px}; use gpui_kit::assets::IconName; +use gpui_kit::component::input::InputEvent; use crate::harness::Harness; use crate::panels::{logos, picker, scale}; @@ -13,6 +14,12 @@ pub fn can_send(text: &str) -> bool { !text.trim().is_empty() } +/// Whether a key in the message box sends it. The textarea reports Shift+Enter as a press of Enter too, after it has +/// put the new line in, so only an Enter without Shift sends. +pub fn sends(event: &InputEvent) -> bool { + matches!(event, InputEvent::PressEnter { shift: false, .. }) +} + pub fn send_button(id: impl Into, enabled: bool) -> Stateful
{ let id = id.into(); let button = if enabled { button(id, "Send", true) } else { button_disabled(id, "Send") }; @@ -143,3 +150,16 @@ pub fn git_chip(id: impl Into, open: bool, primary: impl Into Option { "up" if plain && s.commands > 0 => Some(Key::MenuUp), "down" if plain && s.commands > 0 => Some(Key::MenuDown), "enter" if plain && s.commands > 0 => Some(Key::RunCommand), + "up" if plain && !s.picker_open && s.question > 0 && s.draft_empty => Some(Key::OptionUp), + "down" if plain && !s.picker_open && s.question > 0 && s.draft_empty => Some(Key::OptionDown), + "enter" if plain && !s.picker_open && s.question > 0 && s.draft_empty => Some(Key::ChooseHighlighted), "up" if plain && !s.picker_open && (s.draft_empty || s.in_history) => Some(Key::Older), "down" if plain && !s.picker_open && s.in_history => Some(Key::Newer), "o" if m.control && !m.platform && !m.alt && !m.shift => Some(Key::ToggleDetail), @@ -125,6 +133,18 @@ mod tests { assert_eq!(press("2", idle()), None, "no question: a digit is typed"); } + #[test] + fn a_question_takes_the_arrows_and_enter_until_something_is_typed() { + let asking = State { question: 3, ..idle() }; + assert_eq!(press("down", asking), Some(Key::OptionDown)); + assert_eq!(press("up", asking), Some(Key::OptionUp), "not the history"); + assert_eq!(press("enter", asking), Some(Key::ChooseHighlighted)); + let typing = State { draft_empty: false, ..asking }; + assert_eq!(press("enter", typing), None, "the message box sends the typed answer"); + assert_eq!(press("up", typing), None); + assert_eq!(press("shift-enter", asking), None, "a new line"); + } + #[test] fn ctrl_c_interrupts_or_clears() { assert_eq!(press("ctrl-c", State { working: true, ..idle() }), Some(Key::Interrupt)); diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 6491f46..f743e3b 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -150,11 +150,17 @@ struct Question { reply: QuestionReply, title: String, options: Vec, + /// The option Enter picks; the arrows and the mouse move it. + highlight: usize, + /// What is typed in the message box can be sent as the answer instead of an option (`acp::takes_own_answer`). + 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, /// Already appended to `thread.entries` so a new session shows the user's message while the agent starts. shown: bool, } @@ -270,7 +276,7 @@ impl ThreadView { let this = cx.entity().downgrade(); let mut subscriptions = vec![ cx.subscribe_in(&composer, window, |v: &mut Self, _, ev: &InputEvent, window, cx| match ev { - InputEvent::PressEnter { .. } => v.submit(window, cx), + ev if crate::panels::composer::sends(ev) => v.submit(window, cx), InputEvent::Change => { v.command_highlight = 0; cx.notify(); @@ -300,7 +306,7 @@ impl ThreadView { if shown { thread.sent(prompt.clone()); } - queue.push_back(Queued { text: prompt, shown, compact: false }); + queue.push_back(Queued { text: prompt, shown, compact: false, by_user: false }); } let rows = thread.entries.len(); let list = ListState::new(rows, ListAlignment::Top, px(600.0)); @@ -537,7 +543,8 @@ impl ThreadView { }) .collect(); let title = params.pointer("/toolCall/title").and_then(Value::as_str).unwrap_or("The agent asks for permission").to_string(); - self.question = Some(Question { reply: QuestionReply::Acp(id), title, options }); + let takes_own_answer = acp::takes_own_answer(¶ms); + self.question = Some(Question { reply: QuestionReply::Acp(id), title, options, highlight: 0, takes_own_answer }); } Event::Elicitation { id, params } => { let mut fields: VecDeque = acp::parse_elicitation(¶ms).into(); @@ -562,6 +569,9 @@ impl ThreadView { }, title: first.title, options, + highlight: 0, + // A field's answer must be one of its schema's values. + takes_own_answer: false, }); } else if let Some(connection) = &self.connection { connection.respond(id, acp::elicitation_decline()); @@ -622,6 +632,10 @@ impl ThreadView { 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) { + self.answer_in_own_words(&text, cx); + return; + } self.history_at = None; self.picker = None; self.send(text, window, cx); @@ -630,7 +644,7 @@ impl ThreadView { /// 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 }); + self.queue.push_back(Queued { text, shown: false, compact: false, by_user: false }); self.send_next(cx); cx.notify(); } @@ -664,7 +678,7 @@ impl ThreadView { if shown && let Some(at) = self.thread.sent(text.clone()) { self.remeasure(at); } - self.queue.push_back(Queued { text, shown, compact: false }); + self.queue.push_back(Queued { text, shown, compact: false, by_user: true }); self.send_next(cx); cx.notify(); } @@ -678,7 +692,7 @@ impl ThreadView { let next = if 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 } + Queued { text: format!("/{}", command.unwrap()), shown: true, compact: true, by_user: false } } else { let Some(next) = self.queue.pop_front() else { return }; next @@ -830,7 +844,8 @@ impl ThreadView { if let Some(Question { reply: QuestionReply::Bridge(prev), .. }) = self.question.take() { crate::claude::bridge::respond(&prev, false, "Replaced by a newer question."); } - self.question = Some(Question { reply: QuestionReply::Bridge(req_id), title, options }); + // `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 }); cx.notify(); } @@ -858,6 +873,8 @@ impl ThreadView { reply: QuestionReply::Elicitation { id, field: next.field, kind: next.kind, answers, remaining }, title: next.title, options, + highlight: 0, + takes_own_answer: false, }); } else if let Some(c) = &self.connection { c.respond(id, acp::elicitation_accept(answers)); @@ -874,6 +891,32 @@ impl ThreadView { 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 }; + match q.reply { + QuestionReply::Acp(id) => { + if let Some(c) = &self.connection { + c.respond(id, acp::own_answer(text)); + } + } + QuestionReply::Bridge(req_id) => crate::claude::bridge::respond(&req_id, true, text), + // Never marked as taking the user's own words (`takes_own_answer`). + QuestionReply::Elicitation { .. } => {} + } + 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() + && q.highlight != index + { + q.highlight = index; + cx.notify(); + } + } + /// 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")); @@ -1040,6 +1083,21 @@ impl ThreadView { keys::Key::Interrupt => self.interrupt(cx), 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); + self.answer(at, cx); + } + keys::Key::OptionUp | keys::Key::OptionDown => { + if let Some(q) = self.question.as_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, + (true, at) => at + 1, + (false, 0) => last, + (false, at) => at - 1, + }; + } + } keys::Key::EditLast => { if let Some(last) = self.thread.sent_texts().pop() { self.set_draft(&last, window, cx); @@ -1229,6 +1287,28 @@ impl ThreadView { } /// Replace what the composer holds, with the cursor after it so typing carries on from the end. + /// 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); + 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(); @@ -1487,6 +1567,42 @@ mod tests { }); } + #[gpui::test] + fn a_waiting_message_can_be_taken_back_but_m4codes_own_cannot(cx: &mut gpui::TestAppContext) { + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let start = super::Start { + record_id: String::new(), + harness: Harness::Claude, + all_models: vec![], + picked: vec![], + cwd: dir.path().to_path_buf(), + 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![])), + }; + 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 }); + v.queue.push_back(super::Queued { text: "first\nmore".into(), shown: false, compact: false, by_user: true }); + v.queue.push_back(super::Queued { text: "second".into(), shown: false, compact: false, by_user: true }); + 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.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"); + }); + } + #[gpui::test] fn new_session_shows_prompt_immediately_at_top(cx: &mut gpui::TestAppContext) { cx.update(gpui_kit::init); diff --git a/src/thread/render.rs b/src/thread/render.rs index 67d3572..cf1ffd3 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -15,7 +15,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, key_badge, spinner}; +use crate::panels::widgets::{EffortPick, Trigger, 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). @@ -60,6 +60,7 @@ impl Render for ThreadView { .min_h_0() .child(conversation) .child(div().absolute().bottom_0().left_0().right_0().h(px(18.0)).bg(fade)); + let conversation = div().flex_1().min_h_0().flex().flex_col().child(conversation).children(self.render_activity()); let bottom_dock = div() .flex_none() .flex() @@ -73,6 +74,27 @@ impl Render for ThreadView { } } +/// The user's message as markdown that keeps each line they typed. Markdown would join lines with a single break +/// between them into one, so every line before another ends in a hard break (two trailing spaces, which unlike a +/// backslash leave nothing behind when the next line starts a list or a fence), except inside a fenced code block, +/// where lines already stay as they are. +fn keep_line_breaks(text: &str) -> String { + let lines: Vec<&str> = text.lines().collect(); + let mut in_fence = false; + let mut out = String::with_capacity(text.len() + lines.len()); + for (i, line) in lines.iter().enumerate() { + let fence = line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~"); + if fence { + in_fence = !in_fence; + } + out.push_str(line); + let Some(next) = lines.get(i + 1) else { break }; + let breaks = !in_fence && !fence && !line.trim().is_empty() && !next.trim().is_empty(); + out.push_str(if breaks { " \n" } else { "\n" }); + } + out +} + fn waiting(message: &str) -> Div { div() .flex_1() @@ -165,7 +187,7 @@ impl ThreadView { .bg(hsla(theme::ROW_ACTIVE)) .border_1() .border_color(hsla(theme::PANEL_BORDER)) - .child(text.clone()) + .child(crate::github::ui::markdown(format!("thread-user-md-{ix}"), &keep_line_breaks(text))) .into_any_element(), Entry::Agent(text) => div().px(px(2.0)).child(crate::github::ui::markdown(format!("thread-md-{ix}"), text)).into_any_element(), Entry::Thought(text) => { @@ -263,6 +285,27 @@ impl ThreadView { } /// An entry in the conversation's centred column. + /// What the agent is doing, at the foot of the conversation: the chat is where you look to see whether it works, + /// and the message box stays yours. + fn render_activity(&self) -> Option { + let (label, stoppable) = match self.starting_label() { + Some(label) => (label, false), + None if self.is_working() => ((if self.compaction.running { "Compacting…" } else { "Working…" }).to_string(), true), + None => return None, + }; + let row = div() + .w_full() + .max_w(px(COLUMN_MAX_W)) + .px(px(2.0)) + .flex() + .items_center() + .gap(px(8.0)) + .child(spinner("thread-activity", 12.0)) + .child(div().text_size(scale::px(12.5)).text_color(hsla(theme::TEXT_DIM)).child(label)) + .when(stoppable, |d| d.child(div().flex().gap(px(4.0)).items_center().child(key_badge("Esc")).child(div().text_size(scale::px(11.5)).text_color(hsla(theme::TEXT_FAINT)).child("to stop")))); + Some(div().flex_none().w_full().px(px(22.0)).pb(px(10.0)).flex().justify_center().child(row).into_any_element()) + } + fn wrap_entry(&self, ix: usize, body: AnyElement) -> AnyElement { let is_last = ix + 1 == self.thread.entries.len(); div() @@ -618,18 +661,22 @@ impl ThreadView { let q = self.question.as_ref()?; let mut options = div().flex().flex_col().gap(px(6.0)).w_full(); for (i, opt) in q.options.iter().enumerate() { - let primary = opt.kind == "allow_once" && i == 0; + let lit = i == q.highlight; let row = div() .id(SharedString::from(format!("thread-perm-{i}"))) .w_full() .px(px(10.0)) .py(px(8.0)) .rounded(px(7.0)) - .bg(hsla(if primary { theme::ROW_ACTIVE } else { theme::PANEL_BG })) + .bg(hsla(if lit { theme::ROW_ACTIVE } else { theme::PANEL_BG })) .border_1() - .border_color(hsla(if primary { theme::FOCUS_BORDER } else { theme::PANEL_BORDER })) - .hover(|s| s.bg(hsla(theme::SURFACE_HOVER))) + .border_color(hsla(if lit { theme::FOCUS_BORDER } else { theme::PANEL_BORDER })) .cursor_pointer() + .on_hover(cx.listener(move |v, hovered: &bool, _, cx| { + if *hovered { + v.highlight_option(i, cx); + } + })) .flex() .items_start() .gap(px(10.0)) @@ -672,7 +719,23 @@ impl ThreadView { .gap(px(8.0)) .child(div().font_weight(FontWeight::SEMIBOLD).child(q.title.clone())) .child(div().id("thread-question-options").max_h(px(240.0)).overflow_y_scroll().child(options)) - .child(div().flex().gap(px(6.0)).items_center().text_color(hsla(theme::TEXT_FAINT)).text_size(scale::px(11.5)).child(key_badge("1-9")).child("to choose").child(key_badge("Esc")).child("to decline")), + .child( + div() + .flex() + .flex_wrap() + .gap(px(6.0)) + .items_center() + .text_color(hsla(theme::TEXT_FAINT)) + .text_size(scale::px(11.5)) + .child(key_badge("↑↓")) + .child(key_badge("Enter")) + .child("or") + .child(key_badge("1-9")) + .child("to choose") + .child(key_badge("Esc")) + .child("to decline") + .when(q.takes_own_answer, |d| d.child("· or type your own answer below")), + ), ) } @@ -895,12 +958,54 @@ impl ThreadView { .pt(px(4.0)) .flex() .justify_center() - .child(inner.child(dock)) + .child(inner.children(self.render_waiting(cx)).child(dock)) } - /// Assemble the shared message box parts: model, permission mode, branch, status, review, queue and send. + /// 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(); + if waiting.is_empty() { + return None; + } + let rows = waiting.into_iter().map(|(at, text)| { + let first_line = text.lines().find(|l| !l.trim().is_empty()).unwrap_or_default().trim().to_string(); + div() + .w_full() + .flex() + .items_center() + .gap(px(8.0)) + .px(px(10.0)) + .py(px(4.0)) + .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-{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-{at}")), IconName::X) + .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| drop(v.unqueue(at, cx)))), + ) + }); + Some( + div() + .w_full() + .py(px(4.0)) + .rounded(px(10.0)) + .bg(hsla(theme::SURFACE_ELEVATED)) + .border_1() + .border_color(hsla(theme::PANEL_BORDER)) + .flex() + .flex_col() + .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), + ) + } + + /// 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 { - let faint = |text: String| div().text_size(scale::px(11.5)).text_color(hsla(theme::TEXT_FAINT)).child(text); 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(); @@ -936,20 +1041,8 @@ impl ThreadView { .into_any_element() }); - let mut extra_chips: Vec = vec![]; - if let Some(label) = self.starting_label() { - extra_chips.push(div().ml(px(4.0)).flex().items_center().gap(px(5.0)).child(spinner("thread-starting", 11.0)).child(faint(label)).into_any_element()); - } - if self.is_working() { - extra_chips.push(div().ml(px(4.0)).flex().items_center().gap(px(5.0)).child(spinner("thread-working", 11.0)).child(faint(if self.compaction.running { "Compacting".into() } else { "Working".into() })).into_any_element()); - extra_chips.push(div().flex().gap(px(4.0)).items_center().child(key_badge("Esc")).child(faint("stop".into())).into_any_element()); - } - + let extra_chips: Vec = vec![]; let mut extra_actions: Vec = vec![]; - let queued = self.queue.iter().filter(|q| !q.shown).count(); - if queued > 0 { - extra_actions.push(faint(format!("{queued} queued")).into_any_element()); - } // Outside a git repository there are no snapshots, and so no review at all. if !self.snapshots.is_empty() { let chip = if self.can_review() { @@ -1076,7 +1169,15 @@ fn tool_run(groupable: &[bool], ix: usize) -> Option> { #[cfg(test)] mod tests { - use super::{report_line, run_label, tool_run}; + use super::{keep_line_breaks, report_line, run_label, tool_run}; + + #[test] + fn a_users_lines_stay_lines_but_code_and_paragraphs_do_not_change() { + assert_eq!(keep_line_breaks("one\ntwo\nthree"), "one \ntwo \nthree"); + assert_eq!(keep_line_breaks("para\n\nnext"), "para\n\nnext", "a blank line already splits them"); + assert_eq!(keep_line_breaks("look:\n```\na\nb\n```\nafter"), "look: \n```\na\nb\n```\nafter"); + assert_eq!(keep_line_breaks("single"), "single"); + } #[test] fn a_runs_line_says_what_it_holds() { From 3f1bc68e7a4ed81293eb54b7612a31365a33cfa5 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 21:07:51 +0200 Subject: [PATCH 2/8] Steer or queue a message sent while the agent works MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → General picks Steer (the default, as in t3code) or Queue, and Cmd/Ctrl+Enter does the other for one message. Slash commands and messages during compaction always queue. - Claude Code takes a steer in its running turn through the bridge's `_m4code/steer`. The bridge stamps every message with a uuid and keeps the ACP turn open until Claude's results have answered each one. A steer Claude drops by itself comes back in `_meta.m4code.resend` and goes as the next message. One the user stopped before Claude read it comes back in `_meta.m4code.unread`, shows as a notice, and its own turn is stopped too. - Codex, OpenCode and Antigravity stop their turn and start again with the message. --- README.md | 2 +- bridge/claude.mjs | 96 +++++++++++++++++++++++++--- src/app/act.rs | 3 +- src/app/keymap.rs | 3 + src/app/mod.rs | 1 + src/app/modal.rs | 3 + src/app/sessions.rs | 2 + src/harness/antigravity.rs | 1 + src/harness/claude.rs | 1 + src/harness/codex.rs | 1 + src/harness/mod.rs | 2 + src/harness/opencode.rs | 1 + src/panels/settings_view.rs | 28 ++++++++- src/store.rs | 2 +- src/store/settings.rs | 39 ++++++++++++ src/thread/mod.rs | 121 +++++++++++++++++++++++++++++++++++- 16 files changed, 292 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 7bc8876..ec1bdf7 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. Messages you send meanwhile wait in a list above the message box, where you can edit or remove them before m4code sends them. 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. 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 it to the agent in the turn it is working on. Claude Code reads it between tool calls, and 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. 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/claude.mjs b/bridge/claude.mjs index 9ea6b89..fb3a352 100644 --- a/bridge/claude.mjs +++ b/bridge/claude.mjs @@ -4,6 +4,7 @@ // // Only the part of ACP m4code uses is here: initialize, session/new, session/load, session/list, session/prompt, // session/cancel, session/set_mode and session/set_config_option, and session/request_permission back to m4code. +// `_m4code/steer` is m4code's own: a message for the turn that is running, which ACP has no request for. // stdout carries the protocol only, so anything logged goes to stderr. import { randomUUID } from "node:crypto"; @@ -247,13 +248,36 @@ function stopReason(session, result) { return "end_turn"; } -function finishTurn(session, result) { +/** The uuids of the messages a result answered: every one Claude took into that turn. */ +function answeredBy(result) { + if (Array.isArray(result.user_message_uuids)) return result.user_message_uuids; + return result.user_message_uuid ? [result.user_message_uuid] : null; +} + +/** + * A result ends the turn m4code sees once it has answered every message sent in it. A steer Claude takes between tool + * calls is answered by the same result; one it takes after the turn gets a result of its own, so the turn stays open + * for it. A Claude Code too old to say which messages a result answered ends the turn at its first result, as before. + */ +async function finishTurn(session, result) { const turn = session.turn; + if (turn && !session.cancelled && !result.is_error) { + const answered = answeredBy(result); + if (answered) for (const uuid of answered) turn.waiting.delete(uuid); + else turn.waiting.clear(); + if (turn.waiting.size) { + turn.held = result; + return; + } + } session.turn = null; + // The receipt lists the messages Claude Code still means to run, which is how `unreadSteers` tells a steer it + // dropped from one it already answered. An older Claude Code sends none, and its steers are left to run. + const receipt = session.cancelled ? await session.interrupted : undefined; 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) }); + else turn.resolve({ stopReason: stopReason(session, result), ...steersBack(session, turn, receipt) }); } // The context size is only shown, so the turn ends without waiting for it. session.query @@ -262,10 +286,50 @@ 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) && 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)); + if (turn.waiting.size === 0 && turn.held) return finishTurn(session, turn.held); +} + /** The session's messages from the SDK, as updates to m4code, until the session ends. */ async function pump(session) { try { for await (const m of session.query) { + if (session.dropping.size && !session.turn) { + if (m.type === "result") { + for (const uuid of answeredBy(m) ?? [...session.dropping]) session.dropping.delete(uuid); + session.dropInterrupted = false; + } else if (!session.dropInterrupted) { + session.dropInterrupted = true; + session.query.interrupt().catch(() => {}); + } + continue; + } + // Not in the SDK's types yet; t3code reads it the same way. + if (m.type === "command_lifecycle") { + await steerDropped(session, m); + continue; + } // A subagent's own steps stay inside its tool call. if (m.parent_tool_use_id) continue; if (m.type === "stream_event") { @@ -287,7 +351,7 @@ async function pump(session) { update(session.id, { sessionUpdate: "current_mode_update", currentModeId: session.mode }); } } else if (m.type === "result") { - finishTurn(session, m); + await finishTurn(session, m); } } } catch (error) { @@ -300,7 +364,7 @@ async function pump(session) { 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, mode: "default", model: "", effort: "medium", models: [] }; + 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, mode: "default", model: "", effort: "medium", models: [] }; session.query = query({ prompt: session.inbox, options: { @@ -376,11 +440,25 @@ const handlers = { if (!s) throw new Error("That session has ended."); if (s.turn) throw new Error("A turn is already running."); s.cancelled = false; + // A new message is the user's own again: stopping the steers they took back must not stop this one. + s.dropping.clear(); + s.dropInterrupted = false; const text = (p.prompt ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n"); - const done = new Promise((resolve, reject) => (s.turn = { resolve, reject })); - s.inbox.push({ type: "user", message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, session_id: s.id, origin: { kind: "human" } }); + const uuid = randomUUID(); + const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), dropped: [], held: null })); + s.inbox.push(userMessage(s, text, uuid)); return done; }, + "_m4code/steer": async (p) => { + 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(); + s.turn.waiting.add(uuid); + s.turn.steers.set(uuid, p.text); + s.inbox.push(userMessage(s, p.text, uuid)); + return {}; + }, "session/set_mode": async (p) => { const s = sessions.get(p.sessionId); await s.query.setPermissionMode(p.modeId); @@ -403,11 +481,15 @@ const handlers = { }, }; +function userMessage(session, text, uuid) { + return { type: "user", uuid, message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, session_id: session.id, origin: { kind: "human" } }; +} + function cancel(p) { const s = sessions.get(p.sessionId); if (!s?.turn) return; s.cancelled = true; - s.query.interrupt().catch(() => {}); + s.interrupted = s.query.interrupt().catch(() => undefined); } async function handle(m) { diff --git a/src/app/act.rs b/src/app/act.rs index 72fb0c6..f82c42b 100644 --- a/src/app/act.rs +++ b/src/app/act.rs @@ -330,6 +330,7 @@ impl Workspace { ); let updates = s.update_url.as_deref() != Some(""); let chrome = s.chrome_default; + let s_follow_up = s.follow_up; let default_model = s.default_model(); let claude_hint = self.claude_exe.as_ref().map_or("not found".to_string(), |p| p.to_string_lossy().into_owned()); let defaults = s.new_session.clone(); @@ -356,7 +357,7 @@ impl Workspace { .filter(|id| modes.iter().any(|(mid, _)| mid == id)) .or_else(|| modes.first().map(|(id, _)| id.clone())) .unwrap_or_else(|| "default".into()); - self.modal = Some(Modal::Settings { shell, claude, default_model, effort: defaults.effort.unwrap_or_default(), permission: initial_perm, updates, chrome, scale: crate::panels::scale::percent(), m4code_off: self.store.data.settings.m4code_tools_off.clone(), skills_field, skill_search, costly: claude::costly::scan(), list_focus, renaming: None, subagents }); + self.modal = Some(Modal::Settings { shell, claude, default_model, effort: defaults.effort.unwrap_or_default(), permission: initial_perm, updates, chrome, scale: crate::panels::scale::percent(), follow_up: s_follow_up, m4code_off: self.store.data.settings.m4code_tools_off.clone(), skills_field, skill_search, costly: claude::costly::scan(), list_focus, renaming: None, subagents }); // After the modal exists: a page that loads something reads the dialog's fields. self.set_settings_page(self.settings_page, cx); } diff --git a/src/app/keymap.rs b/src/app/keymap.rs index 00e8afb..26747f0 100644 --- a/src/app/keymap.rs +++ b/src/app/keymap.rs @@ -84,6 +84,9 @@ pub fn shortcuts() -> Vec { row("Sessions", &["secondary-shift-w"], "Close the session"), row("Sessions", &["secondary-z"], "Reopen the last closed session"), row("Chat", &["enter"], "Send the message"), + row("Chat", &["shift-enter"], "Start a new line"), + row("Chat", &["secondary-enter"], "While the agent works, queue instead of steering, or steer instead of queueing"), + row("Chat", &["up", "down", "enter"], "Pick an answer to the agent's question"), row("Chat", &["escape", "ctrl-c"], "Stop the agent's turn"), row("Chat", &["escape escape"], "Edit your last message, or clear the one you're typing"), row("Chat", &["shift-tab"], "Next permission mode"), diff --git a/src/app/mod.rs b/src/app/mod.rs index c8b275c..6bcaa2f 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -191,6 +191,7 @@ pub enum Modal { updates: bool, chrome: bool, scale: u32, + follow_up: crate::store::FollowUp, /// m4code tools turned off (m4code tools page). m4code_off: Vec, /// Skills to turn off, separated by commas (Claude Code tools page). diff --git a/src/app/modal.rs b/src/app/modal.rs index 8256c28..117b9c7 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -112,6 +112,7 @@ impl Workspace { updates, chrome, scale, + follow_up, m4code_off, skills_field, renaming, @@ -150,6 +151,7 @@ impl Workspace { let scale_changed = s.scale != (scale != 100).then_some(scale); s.scale = (scale != 100).then_some(scale); s.chrome_default = chrome; + s.follow_up = follow_up; let enabled = if subagents.enabled.is_empty() { vec![default_model.harness] } else { subagents.enabled.clone() }; let chosen = if enabled.contains(&default_model.harness) { @@ -222,6 +224,7 @@ impl Workspace { for live in &self.live { if let Some(thread) = live.view.thread() { thread.update(cx, |t, cx| { + t.follow_up = follow_up; if default_model_changed && t.harness == chosen.harness && !chosen.id.is_empty() { t.pick_model(chosen.clone(), cx); } diff --git a/src/app/sessions.rs b/src/app/sessions.rs index e92614f..bb0bd26 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -386,7 +386,9 @@ impl Workspace { if subagent_edits.is_some() { view.update(cx, |v, cx| v.composer.update(cx, |c, cx| c.set_placeholder("Message this subagent…", window, cx))); } + let follow_up = self.store.data.settings.follow_up; view.update(cx, |v, _| { + v.follow_up = follow_up; v.subagent_edits = subagent_edits; v.canonical_history = canonical_history; v.compaction.enabled = auto_compact; diff --git a/src/harness/antigravity.rs b/src/harness/antigravity.rs index a474a03..f374033 100644 --- a/src/harness/antigravity.rs +++ b/src/harness/antigravity.rs @@ -14,5 +14,6 @@ pub const ADAPTER: Adapter = Adapter { compact_command: None, default_modes: super::standard_default_modes, default_models: || super::default_model_entry(super::Harness::Antigravity), + steers: false, // agy has no documented way to resume a session by id from its command line. }; diff --git a/src/harness/claude.rs b/src/harness/claude.rs index e572763..37deaf2 100644 --- a/src/harness/claude.rs +++ b/src/harness/claude.rs @@ -38,6 +38,7 @@ pub const ADAPTER: Adapter = Adapter { .collect() }, default_models: super::CatalogModel::default_claude_models, + steers: true, }; /// Sessions starting together must not install the SDK into the same folder at once. diff --git a/src/harness/codex.rs b/src/harness/codex.rs index 8c3bf82..577bf17 100644 --- a/src/harness/codex.rs +++ b/src/harness/codex.rs @@ -14,4 +14,5 @@ pub const ADAPTER: Adapter = Adapter { compact_command: Some("compact"), default_modes: super::standard_default_modes, default_models: || super::default_model_entry(super::Harness::Codex), + steers: false, }; diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 0581fc0..b2dcc7d 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -75,6 +75,8 @@ pub struct Adapter { /// Whether the empty session opened only to read `configOptions[category == "model"]` should be deleted again. pub delete_model_session: bool, pub compact_command: Option<&'static str>, + /// Whether the agent takes a message in the turn it is working on (`_m4code/steer`, the Claude Code bridge's own). + pub steers: bool, /// Fallback permission modes shown before the adapter's ACP server reports its live list. pub default_modes: fn() -> Vec<(String, String)>, /// Fallback model entries shown before the adapter's ACP server reports its live catalog. diff --git a/src/harness/opencode.rs b/src/harness/opencode.rs index 1e7c653..dde6989 100644 --- a/src/harness/opencode.rs +++ b/src/harness/opencode.rs @@ -32,6 +32,7 @@ pub const ADAPTER: Adapter = Adapter { compact_command: Some("compact"), default_modes: super::standard_default_modes, default_models: || super::default_model_entry(super::Harness::OpenCode), + steers: false, }; #[cfg(test)] diff --git a/src/panels/settings_view.rs b/src/panels/settings_view.rs index 4b17d7a..ad5567a 100644 --- a/src/panels/settings_view.rs +++ b/src/panels/settings_view.rs @@ -31,10 +31,10 @@ pub(super) fn render_settings_card( cx: &mut Context, ) -> gpui::Stateful { let (page, worktrees, scroll) = (ws.settings_page, &ws.worktrees_page, &ws.settings_scroll); - let Some(Modal::Settings { shell, default_model, effort, permission, updates, scale, m4code_off, skill_search, list_focus, renaming, .. }) = &ws.modal else { + let Some(Modal::Settings { shell, default_model, effort, permission, updates, scale, follow_up, m4code_off, skill_search, list_focus, renaming, .. }) = &ws.modal else { return div().id("modal-card"); }; - let (updates, scale) = (*updates, *scale); + let (updates, scale, follow_up) = (*updates, *scale, *follow_up); let scaled = crate::panels::scale::px; let faint = |text: String| div().text_size(scaled(11.5)).text_color(hsla(theme::TEXT_FAINT)).child(text); @@ -51,6 +51,20 @@ pub(super) fn render_settings_card( settings_picker_row("settings-effort", ("Effort", "Reasoning depth for new sessions"), effort.label().to_string(), effort_open, |ws, at, _, cx| ws.open_settings_effort_picker(at, cx), cx).into_any_element(), settings_picker_row("settings-permission", ("Permission mode", "Approval policy for tool calls and edits"), perm_display, perm_open, |ws, at, _, cx| ws.open_settings_permission_picker(at, cx), cx).into_any_element(), ]; + session_rows.push( + row_shell( + "Messages sent while the agent works", + Some("Steer reaches the agent in its turn; Queue waits for it to end. Cmd/Ctrl+Enter does the other."), + div() + .flex_none() + .flex() + .gap(px(4.0)) + .child(follow_up_button(crate::store::FollowUp::Queue, "Queue", follow_up, cx)) + .child(follow_up_button(crate::store::FollowUp::Steer, "Steer", follow_up, cx)) + .into_any_element(), + ) + .into_any_element(), + ); if matches!(permission.as_str(), "bypassPermissions" | "fullAccess" | "full_access" | "yolo") { session_rows.push( div() @@ -337,6 +351,16 @@ fn row_labels(title: &str, subtitle: Option<&str>) -> gpui::Div { .children(subtitle.map(|s| div().text_size(scaled(11.5)).text_color(hsla(theme::TEXT_FAINT)).child(s.to_string()))) } +/// One side of the Queue / Steer switch; the chosen one is drawn as the primary button. +fn follow_up_button(choice: crate::store::FollowUp, label: &'static str, current: crate::store::FollowUp, cx: &mut Context) -> impl IntoElement { + button(format!("settings-follow-up-{label}"), label, choice == current).on_click(cx.listener(move |ws, _: &ClickEvent, _, cx| { + if let Some(Modal::Settings { follow_up, .. }) = ws.modal.as_mut() { + *follow_up = choice; + } + cx.notify(); + })) +} + fn row_shell(title: &str, subtitle: Option<&str>, trailing: AnyElement) -> gpui::Div { div() .px(px(14.0)) diff --git a/src/store.rs b/src/store.rs index 8c20129..0d4b621 100644 --- a/src/store.rs +++ b/src/store.rs @@ -28,7 +28,7 @@ pub use sessions::{SessionKind, ExternalState, Attached, ClaudeMeta, ProviderSes mod accounts; pub use accounts::{RateLimit, AccountUsage, Account, MAIN_ACCOUNT}; mod settings; -pub use settings::{WindowGeom, Layout, Settings}; +pub use settings::{FollowUp, WindowGeom, Layout, Settings}; mod data; pub use data::{Data}; diff --git a/src/store/settings.rs b/src/store/settings.rs index 882222f..eadc7fb 100644 --- a/src/store/settings.rs +++ b/src/store/settings.rs @@ -107,6 +107,30 @@ pub struct Settings { /// Installed `SKILL.md` packages and their global / per-project toggles (Settings → Skills). #[serde(default)] pub skills: crate::skills::SkillsConfig, + /// What a message sent while the agent works does (Settings → General). + #[serde(default)] + pub follow_up: FollowUp, +} + +/// What a message sent while the agent works does. Cmd/Ctrl+Enter does the other one for a single message. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FollowUp { + /// Wait for the turn to end. + Queue, + /// Reach 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 starts again with the message. + #[default] + Steer, +} + +impl FollowUp { + pub fn other(self) -> Self { + match self { + Self::Queue => Self::Steer, + Self::Steer => Self::Queue, + } + } } impl Settings { @@ -247,3 +271,18 @@ impl Settings { } } + +#[cfg(test)] +mod tests { + use super::FollowUp; + + #[test] + fn messages_mid_turn_steer_unless_the_user_chose_to_queue() { + let older: super::Settings = serde_json::from_str("{}").unwrap(); + assert_eq!(older.follow_up, FollowUp::Steer, "a state file from before the setting steers, as t3code does"); + let queue: super::Settings = serde_json::from_str(r#"{"follow_up":"queue"}"#).unwrap(); + assert_eq!(queue.follow_up, FollowUp::Queue); + assert_eq!(FollowUp::Queue.other(), FollowUp::Steer); + assert_eq!(FollowUp::Steer.other(), FollowUp::Queue); + } +} diff --git a/src/thread/mod.rs b/src/thread/mod.rs index f743e3b..258d9a0 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -217,6 +217,8 @@ pub struct ThreadView { /// Ctrl+O: every tool's output in full. pub detail: bool, pub(crate) subagent_edits: Option, + /// What a message sent while the agent works does (Settings → General). + pub(crate) follow_up: crate::store::FollowUp, pub compaction: crate::harness::compaction::Policy, pub(crate) canonical_history: bool, persist_on_drop: bool, @@ -276,7 +278,7 @@ impl ThreadView { let this = cx.entity().downgrade(); let mut subscriptions = vec![ cx.subscribe_in(&composer, window, |v: &mut Self, _, ev: &InputEvent, window, cx| match ev { - ev if crate::panels::composer::sends(ev) => v.submit(window, cx), + InputEvent::PressEnter { secondary, .. } if crate::panels::composer::sends(ev) => v.submit_with(*secondary, window, cx), InputEvent::Change => { v.command_highlight = 0; cx.notify(); @@ -344,6 +346,7 @@ impl ThreadView { rows, detail: false, subagent_edits: None, + follow_up: crate::store::FollowUp::default(), compaction: Default::default(), canonical_history: false, persist_on_drop: true, @@ -627,6 +630,12 @@ impl ThreadView { /// Enter in the composer. fn submit(&mut self, window: &mut Window, cx: &mut Context) { + self.submit_with(false, window, cx); + } + + /// 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) { let text = self.composer.read(cx).value().trim().to_string(); if !crate::panels::composer::can_send(&text) { return; @@ -638,7 +647,55 @@ impl ThreadView { } self.history_at = None; self.picker = None; - self.send(text, window, cx); + let follow_up = if the_other_way { self.follow_up.other() } else { self.follow_up }; + self.send_as(text, follow_up, cx); + } + + /// Whether `text` goes to the turn that is running. A slash command waits, as t3code's do, because a command + /// steered into a turn would replace the agent's task; so does a message while the context is compacted. + fn can_steer(&self, text: &str, follow_up: crate::store::FollowUp) -> bool { + follow_up == crate::store::FollowUp::Steer + && self.working + && self.phase == Phase::Ready + && !self.compaction.running + && !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) { + 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 }); + cx.notify(); + return; + }; + if !self.harness.adapter().steers { + self.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); + connection.notify("session/cancel", json!({"sessionId": session})); + // ACP says a client that cancels answers every open permission question as cancelled. + self.answer(None, cx); + cx.notify(); + return; + } + if let Some(at) = self.thread.sent(text.clone()) { + self.remeasure(at); + } + self.persist_entries(); + self.list.scroll_to_end(); + let reply = connection.request("_m4code/steer", json!({"sessionId": session, "text": text})); + 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; the chat already + // shows it. + let _ = this.update(cx, |v, cx| { + v.queue.push_front(Queued { text, shown: true, compact: false, by_user: true }); + v.send_next(cx); + cx.notify(); + }); + } + }) + .detach(); + cx.notify(); } /// A message m4code sends on the session's behalf, such as a subagent's report. It waits for the current turn @@ -651,6 +708,10 @@ impl ThreadView { /// Send `text` as the user's next message, now or after the turn that is running. pub fn send(&mut self, text: String, _window: &mut Window, cx: &mut Context) { + self.send_as(text, self.follow_up, cx); + } + + fn send_as(&mut self, text: String, follow_up: crate::store::FollowUp, cx: &mut Context) { if let Some(target) = self.pending_model.take().filter(|m| m.harness != self.harness) { let effort = self.pending_effort.take(); if self.working { @@ -674,6 +735,10 @@ impl ThreadView { cx.notify(); return; } + if self.can_steer(&text, follow_up) { + self.steer(text, 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); @@ -764,6 +829,19 @@ 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. + for text in steers_back("resend").into_iter().rev() { + self.queue.push_front(Queued { text, shown: true, compact: false, by_user: true }); + } + for text in steers_back("unread") { + let at = self.thread.notice(format!("The agent stopped before reading your message, so it was not sent: {text}"), false); + self.remeasure(at); + } 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"); @@ -1603,6 +1681,45 @@ mod tests { }); } + #[gpui::test] + fn only_a_plain_message_mid_turn_steers(cx: &mut gpui::TestAppContext) { + use crate::store::FollowUp; + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let start = super::Start { + record_id: String::new(), + harness: Harness::Codex, + all_models: vec![], + picked: vec![], + cwd: dir.path().to_path_buf(), + 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![])), + }; + let (view, cx) = cx.add_window_view(|window, cx| super::ThreadView::new(start, window, cx)); + view.update(cx, |v, cx| { + v.phase = super::Phase::Ready; + assert!(!v.can_steer("hi", FollowUp::Steer), "nothing to steer while idle"); + v.working = true; + assert!(v.can_steer("hi", FollowUp::Steer)); + assert!(!v.can_steer("hi", FollowUp::Queue)); + assert!(!v.can_steer("/compact", FollowUp::Steer), "a command waits for the turn"); + v.compaction.running = true; + assert!(!v.can_steer("hi", FollowUp::Steer), "compaction takes no steers"); + v.compaction.running = false; + // 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")]); + }); + } + #[gpui::test] fn new_session_shows_prompt_immediately_at_top(cx: &mut gpui::TestAppContext) { cx.update(gpui_kit::init); From 772eed6c9689bd6149c4631edaa782f8175c1885 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 21:12:50 +0200 Subject: [PATCH 3/8] Show the right sidebar as cards you can drag into any order The menu drops its outer panel and sits on the window's background, and each section is a card drawn like the chat's panel, so cards no longer sit inside a card. Dragging a card over another moves it there, the way session rows reorder. The order is saved in `layout.right_cards`. A blank card holds a place for later. --- README.md | 2 +- src/app/mod.rs | 3 + src/panels/inspector.rs | 118 +++++++++++++++++++++++++++++----------- src/panels/sidebar.rs | 8 +-- src/panels/theme.rs | 2 - src/store.rs | 2 +- src/store/settings.rs | 51 ++++++++++++++++- 7 files changed, 144 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index ec1bdf7..81a4afa 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 between tool calls, and 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. 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 it to the agent in the turn it is working on. Claude Code reads it between tool calls, and 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. 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/src/app/mod.rs b/src/app/mod.rs index 6bcaa2f..3e02c26 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -593,6 +593,8 @@ pub struct Workspace { pub window_title: String, /// The session being dragged in the sidebar (lifted in place while its ghost follows the cursor). pub dragging: Option, + /// The right sidebar card being dragged, lifted in place like a session row. + pub dragging_card: Option, /// Pointer position at the last drag-over check, see `pointer_moved`. /// Sidebar reorder animation: last drawn order of the running rows, and the slides in flight. pub prev_current: Vec, @@ -744,6 +746,7 @@ impl Workspace { .collect(), window_title: String::new(), dragging: None, + dragging_card: None, drag_pos: None, prev_current: Vec::new(), slides: HashMap::new(), diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs index da159f2..69fc8ee 100644 --- a/src/panels/inspector.rs +++ b/src/panels/inspector.rs @@ -13,7 +13,10 @@ use std::time::Duration; use gpui::{Animation, AnimationExt}; use crate::app::{Act, GitOp, MenuItem, SideDrag, Workspace}; +use crate::panels::sidebar::{DragGhost, lifted, move_to}; use crate::panels::widgets::{Trigger, button}; +use crate::store::SideCard; +use gpui::{AppContext, DragMoveEvent, prelude::FluentBuilder}; use crate::platform::Editor; use crate::github::model::State; use crate::store::{Attached, Id, Project, SessionKind, SessionRecord}; @@ -162,16 +165,10 @@ impl Workspace { .flex_none() .w(px(width)) .h_full() - .child( - div() - .size_full() - .rounded(px(theme::PANEL_RADIUS)) - .overflow_hidden() - .border_1() - .border_color(hsla(theme::PANEL_BORDER)) - .bg(hsla(theme::SIDEBAR_BG)) - .child(body), - ) + // The menu's cards sit on the window's background; GitHub is one view, so it keeps the panel around it. + .child(div().size_full().when(shown_view != "menu", |d| { + d.rounded(px(theme::PANEL_RADIUS)).overflow_hidden().border_1().border_color(hsla(theme::PANEL_BORDER)).bg(hsla(theme::SIDEBAR_BG)) + }).child(body)) .children(handle), ) .into_any_element(), @@ -191,13 +188,10 @@ impl Workspace { let subagents = id.as_ref().filter(|_| !children.is_empty()).map(|parent| (children.len(), self.subagent_rows(parent, children, cx))); let away = id.as_deref().and_then(|i| self.session_away(i, cx)); let status = self.status_rows(&shown, id.as_ref(), running, cx); - self.menu_scroll - .wire(div().id("right-menu").size_full(), window) - .flex() - .flex_col() - .gap(px(theme::PANEL_GAP)) - .p(px(6.0)) - .children(away.map(|(from, to_name)| { + if self.dragging_card.is_some() && !cx.has_active_drag() { + self.dragging_card = None; + } + let account = away.map(|(from, to_name)| { // Fades in when the session turns out to be on another account. let body = div() .flex() @@ -210,12 +204,64 @@ impl Workspace { }))) .with_animation("handoff-fade", Animation::new(Duration::from_millis(220)).with_easing(gpui::ease_out_quint()), |d, t| d.opacity(t)); group("ACCOUNT", None, body) + }); + let mut cards: Vec<(SideCard, Div)> = [ + (SideCard::Account, account), + (SideCard::Actions, Some(group("ACTIONS", None, actions))), + (SideCard::Github, github.map(|(n, g)| group("GITHUB", Some(n), g))), + (SideCard::Subagents, subagents.map(|(n, s)| group("SUBAGENTS", Some(n), s))), + (SideCard::Linked, linked.map(|(n, l)| group("LINKED", Some(n), l))), + (SideCard::Status, Some(group("STATUS", None, status))), + (SideCard::Empty, Some(card().h(px(72.0)))), + ] + .into_iter() + .filter_map(|(kind, card)| Some((kind, card?))) + .collect(); + let order = self.store.data.layout.right_card_order(); + cards.sort_by_key(|(kind, _)| order.iter().position(|k| k == kind)); + let cards: Vec> = cards.into_iter().map(|(kind, card)| self.draggable_card(kind, card, cx)).collect(); + self.menu_scroll + .wire(div().id("right-menu").size_full(), window) + .flex() + .flex_col() + .gap(px(theme::PANEL_GAP)) + .children(cards) + } + + /// A card you can drag over the others to move it; the order is saved as it changes. + fn draggable_card(&self, kind: SideCard, card: Div, cx: &mut Context) -> Stateful
{ + let ws = cx.entity().downgrade(); + card.id(SharedString::from(format!("right-card-{kind:?}"))) + .on_drag(DragCard(kind), move |_, _, _, cx| { + ws.update(cx, |ws, cx| { + ws.dragging_card = Some(kind); + ws.drag_pos = None; + cx.notify(); + }) + .ok(); + cx.new(|_| DragGhost) + }) + .on_drag_move(cx.listener(move |ws, ev: &DragMoveEvent, _w, cx| { + let from = ev.drag(cx).0; + if from == kind || !ev.bounds.contains(&ev.event.position) || !ws.pointer_moved(ev.event.position) { + return; + } + ws.move_right_card(from, kind); + ws.last_swap = std::time::Instant::now(); + cx.notify(); })) - .child(group("ACTIONS", None, actions)) - .children(github.map(|(n, g)| group("GITHUB", Some(n), g))) - .children(subagents.map(|(n, s)| group("SUBAGENTS", Some(n), s))) - .children(linked.map(|(n, l)| group("LINKED", Some(n), l))) - .child(group("STATUS", None, status)) + .when(self.dragging_card == Some(kind), lifted) + } + + /// Put card `from` where card `to` is, and save the order. + fn move_right_card(&mut self, from: SideCard, to: SideCard) { + let mut order = self.store.data.layout.right_card_order(); + let at = |card: SideCard| order.iter().position(|k| *k == card); + if let (Some(from), Some(to)) = (at(from), at(to)) { + move_to(&mut order, from, to); + self.store.data.layout.right_cards = order; + self.store.mark_dirty(); + } } /// Open in the editor, the folder, git, the shell and the GitHub view. @@ -497,6 +543,22 @@ fn subagent_row(parent: &Id, child: SubagentRow, cx: &mut Context) -> })) } +/// Drag payload: a right sidebar card, dragged over another to move it there. +struct DragCard(SideCard); + +/// A card of the right sidebar, which sits on the window's background: drawn like the chat's panel. +fn card() -> Div { + div() + .flex() + .flex_col() + .gap(px(4.0)) + .p(px(4.0)) + .rounded(px(theme::PANEL_RADIUS)) + .border_1() + .border_color(hsla(theme::PANEL_BORDER)) + .bg(hsla(theme::PANEL_BG)) +} + /// One section of the sidebar, as a card: its label, the number of entries for a list, then its rows. fn group(label: &str, count: Option, body: impl IntoElement) -> Div { let header = div() @@ -507,17 +569,7 @@ fn group(label: &str, count: Option, body: impl IntoElement) -> Div { .pt(px(4.0)) .child(section_label(label.to_string())) .children(count.map(|n| section_label(n.to_string()))); - div() - .flex() - .flex_col() - .gap(px(4.0)) - .p(px(4.0)) - .rounded(px(theme::PANEL_RADIUS)) - .border_1() - .border_color(hsla(theme::BORDER)) - .bg(hsla(theme::CARD_BG)) - .child(header) - .child(body) + card().child(header).child(body) } /// How long the grey bar of an item still waiting for its title pulses. Then it rests, because an item GitHub never diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index 53a06c1..526239f 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -51,7 +51,7 @@ struct DragSession(Id); /// The drag view GPUI requires. It draws nothing: the dragged row itself stays in the list (lifted, see /// `lifted`) and slides to wherever the cursor is, so it can never leave its list. -struct DragGhost; +pub(super) struct DragGhost; impl Render for DragGhost { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { @@ -71,7 +71,7 @@ fn begin_drag(ws: &WeakEntity, id: &Id, cx: &mut gpui::App) -> gpui:: } /// Style of the row or header being dragged. -fn lifted(el: T) -> T { +pub(super) fn lifted(el: T) -> T { el.bg(hsla(theme::ROW_ACTIVE)).border_1().border_color(hsla(theme::TEXT_FAINT)) } @@ -122,7 +122,7 @@ fn slid(el: impl IntoElement + gpui::Styled + 'static, id: &Id, slide: Option(v: &mut [T], from: usize, to: usize) { +pub(super) fn move_to(v: &mut [T], from: usize, to: usize) { if from < to { v[from..=to].rotate_left(1); } else { @@ -224,7 +224,7 @@ impl Workspace { /// /// Also false while the previous swap is still sliding: rows are hit-tested where they are painted, so a row /// mid-slide sits under the pointer and would be swapped straight back (flicker). - fn pointer_moved(&mut self, pos: gpui::Point) -> bool { + pub(super) fn pointer_moved(&mut self, pos: gpui::Point) -> bool { if self.last_swap.elapsed() < Duration::from_millis(SLIDE_MS + 40) { return false; } diff --git a/src/panels/theme.rs b/src/panels/theme.rs index 90c04dc..d4cd14b 100644 --- a/src/panels/theme.rs +++ b/src/panels/theme.rs @@ -12,8 +12,6 @@ pub const TERMINAL_BG: u32 = PANEL_BG; pub const SIDEBAR_BG: u32 = PANEL_BG; /// Elevated dark surfaces (composer box, cards, popovers). pub const SURFACE_ELEVATED: u32 = 0x1a1a1a; -/// A group of rows set apart on a panel, such as the right sidebar's sections. Dark enough that `ROW_HOVER` still shows. -pub const CARD_BG: u32 = 0x161616; pub const SURFACE_HOVER: u32 = 0x222222; pub const BORDER: u32 = 0x242424; /// The faint outline that separates a panel from the window background. diff --git a/src/store.rs b/src/store.rs index 0d4b621..1feebbe 100644 --- a/src/store.rs +++ b/src/store.rs @@ -28,7 +28,7 @@ pub use sessions::{SessionKind, ExternalState, Attached, ClaudeMeta, ProviderSes mod accounts; pub use accounts::{RateLimit, AccountUsage, Account, MAIN_ACCOUNT}; mod settings; -pub use settings::{FollowUp, WindowGeom, Layout, Settings}; +pub use settings::{FollowUp, SideCard, WindowGeom, Layout, Settings}; mod data; pub use data::{Data}; diff --git a/src/store/settings.rs b/src/store/settings.rs index eadc7fb..f2232b0 100644 --- a/src/store/settings.rs +++ b/src/store/settings.rs @@ -46,6 +46,45 @@ pub struct Layout { /// Width of the right sidebar's menu when the user has dragged it; the default otherwise. #[serde(default)] pub right_menu_w: Option, + /// The right sidebar's cards top to bottom, as the user dragged them; `right_card_order` fills in the rest. + #[serde(default)] + pub right_cards: Vec, +} + +/// One card of the right sidebar. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SideCard { + Account, + Actions, + Github, + Subagents, + Linked, + Status, + /// A blank card, kept in the layout for something later. + Empty, + /// A card this version doesn't know, from a newer state file; it keeps the rest of the file loading. + #[serde(other)] + Unknown, +} + +impl SideCard { + /// Every card in its default place. + pub const ALL: [SideCard; 7] = [Self::Account, Self::Actions, Self::Github, Self::Subagents, Self::Linked, Self::Status, Self::Empty]; +} + +impl Layout { + /// The cards in the order the user left them, then any the saved order doesn't name (every card, in a state file + /// from before they could move) in their default order. + pub fn right_card_order(&self) -> Vec { + let mut order: Vec = vec![]; + for card in self.right_cards.iter().chain(SideCard::ALL.iter()) { + if *card != SideCard::Unknown && !order.contains(card) { + order.push(*card); + } + } + order + } } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -274,7 +313,17 @@ impl Settings { #[cfg(test)] mod tests { - use super::FollowUp; + use super::{FollowUp, Layout, SideCard}; + + #[test] + fn the_cards_keep_the_users_order_and_gain_the_ones_it_misses() { + assert_eq!(Layout::default().right_card_order(), SideCard::ALL, "an older state file"); + let moved: Layout = serde_json::from_str(r#"{"selected_session":null,"sidebar_visible":true,"other_collapsed":false,"right_cards":["status","from_the_future","actions","status"]}"#).unwrap(); + assert_eq!( + moved.right_card_order(), + [SideCard::Status, SideCard::Actions, SideCard::Account, SideCard::Github, SideCard::Subagents, SideCard::Linked, SideCard::Empty] + ); + } #[test] fn messages_mid_turn_steer_unless_the_user_chose_to_queue() { From 49bb2bdc8855b86606692fce6abf8dff23ab2c56 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 21:18:14 +0200 Subject: [PATCH 4/8] Keep each chat message's parsed markdown so scrolling doesn't jump `TextView::markdown` kept its parse in frame state, which GPUI drops when a row scrolls out of the list. A message that came back into view parsed again, and one over 4 KB parses in the background, so it drew empty for a frame and then grew, moving everything around it. The chat now holds each entry's `TextViewState` and draws it with `TextView::new`; `github::ui::styled_markdown` gives both kinds of view the same look. --- src/github/ui/mod.rs | 8 ++++++-- src/thread/mod.rs | 37 +++++++++++++++++++++++++++++++++++++ src/thread/render.rs | 16 ++++++++++++++-- 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/github/ui/mod.rs b/src/github/ui/mod.rs index 5a992ca..b8379dc 100644 --- a/src/github/ui/mod.rs +++ b/src/github/ui/mod.rs @@ -117,14 +117,18 @@ fn check_color(state: &str) -> u32 { } pub(crate) fn markdown(id: String, text: &str) -> TextView { + styled_markdown(TextView::markdown(SharedString::from(id), SharedString::from(text.to_string()))) +} + +/// m4code's look and link handling for a markdown view, whoever holds its parsed text. +pub(crate) fn styled_markdown(view: TextView) -> TextView { // The stock style highlights code with the light theme (dark text), which vanishes on m4code's dark panels. let style = gpui_kit::component::text::TextViewStyle { highlight_theme: gpui_kit::component::highlighter::HighlightTheme::default_dark(), is_dark: true, ..Default::default() }; - TextView::markdown(SharedString::from(id), SharedString::from(text.to_string())) - .style(style) + view.style(style) .selectable(true) .on_link_click(|url, _, _, cx: &mut App| { if url.starts_with("https://") || url.starts_with("http://") { diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 258d9a0..33f6d57 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -217,6 +217,10 @@ pub struct ThreadView { /// Ctrl+O: every tool's output in full. pub detail: bool, pub(crate) subagent_edits: Option, + /// Each message's parsed markdown, by entry. The chat keeps it rather than the frame: a row that scrolls out of + /// the list would otherwise drop it and parse again when it comes back, and a long message (over 4 KB) parses + /// in the background, so it would draw empty for a frame and then grow, moving everything around it. + markdown: HashMap>, /// What a message sent while the agent works does (Settings → General). pub(crate) follow_up: crate::store::FollowUp, pub compaction: crate::harness::compaction::Policy, @@ -346,6 +350,7 @@ impl ThreadView { rows, detail: false, subagent_edits: None, + markdown: HashMap::new(), follow_up: crate::store::FollowUp::default(), compaction: Default::default(), canonical_history: false, @@ -1720,6 +1725,38 @@ mod tests { }); } + #[gpui::test] + fn a_reply_keeps_its_parsed_markdown_between_frames(cx: &mut gpui::TestAppContext) { + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let start = super::Start { + record_id: String::new(), + harness: Harness::Claude, + all_models: vec![], + picked: vec![], + cwd: dir.path().to_path_buf(), + 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![])), + }; + let (view, cx) = cx.add_window_view(|window, cx| super::ThreadView::new(start, window, cx)); + view.update(cx, |v, cx| { + let mut cache = std::mem::take(&mut v.markdown); + super::render::markdown_of(&mut cache, 3, "**first**", cx); + let first = cache[&3].entity_id(); + super::render::markdown_of(&mut cache, 3, "**first** and more", cx); + assert_eq!(cache[&3].entity_id(), first, "a redraw or a streamed reply keeps the parse, so the row keeps its height"); + super::render::markdown_of(&mut cache, 4, "other", cx); + assert_ne!(cache[&4].entity_id(), first, "each entry has its own"); + }); + } + #[gpui::test] fn new_session_shows_prompt_immediately_at_top(cx: &mut gpui::TestAppContext) { cx.update(gpui_kit::init); diff --git a/src/thread/render.rs b/src/thread/render.rs index cf1ffd3..eaa29ef 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -9,6 +9,9 @@ use gpui::{ }; use gpui_kit::assets::IconName; use gpui_kit::component::input::Textarea; +use gpui_kit::component::text::{TextView, TextViewState}; +use std::collections::HashMap; +use gpui::{AppContext, Entity}; use super::{ThreadEvent, ThreadPicker, ThreadView}; use crate::harness::CatalogModel; @@ -95,6 +98,15 @@ fn keep_line_breaks(text: &str) -> String { out } +/// Entry `ix`'s text as markdown, parsed once and kept in `cache` (`ThreadView::markdown`) so it keeps its height +/// as it scrolls. +pub(super) fn markdown_of(cache: &mut HashMap>, ix: usize, text: &str, cx: &mut Context) -> TextView { + let state = cache.entry(ix).or_insert_with(|| cx.new(|cx| TextViewState::markdown(text, cx))).clone(); + // Unchanged text costs a comparison; a reply still streaming in is appended to what is parsed. + state.update(cx, |s, cx| s.set_text(text, cx)); + crate::github::ui::styled_markdown(TextView::new(&state)) +} + fn waiting(message: &str) -> Div { div() .flex_1() @@ -187,9 +199,9 @@ impl ThreadView { .bg(hsla(theme::ROW_ACTIVE)) .border_1() .border_color(hsla(theme::PANEL_BORDER)) - .child(crate::github::ui::markdown(format!("thread-user-md-{ix}"), &keep_line_breaks(text))) + .child(markdown_of(&mut self.markdown, ix, &keep_line_breaks(text), cx)) .into_any_element(), - Entry::Agent(text) => div().px(px(2.0)).child(crate::github::ui::markdown(format!("thread-md-{ix}"), text)).into_any_element(), + Entry::Agent(text) => div().px(px(2.0)).child(markdown_of(&mut self.markdown, ix, text, cx)).into_any_element(), Entry::Thought(text) => { let run = tool_run(&self.groupable(), ix); match &run { From 0a4a5a22de4705524600ec6942c696c68071e035 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 21:30:54 +0200 Subject: [PATCH 5/8] Make inline code's background cover its whole glyph box Upstream gpui-base fits the box behind inline code to the capital height plus some padding, so in fonts with deep descenders g, p and y reach past it. The patched `code_background` uses the code's ascent and descent instead. The Cargo.toml patch notes say so. --- Cargo.toml | 3 +- vendor/gpui-base/src/text/inline_flow.rs | 78 ++++++++++++++++-------- 2 files changed, 53 insertions(+), 28 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0e8ae9e..75cc195 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,7 +90,8 @@ opt-level = 2 # (`handle_completion_trigger` in src/input/editor/lsp/completions.rs). It also makes `has_multiple_cursors`, `select_range` # and `replace_range` public, which the line actions (src/app/line_actions.rs) edit through, and makes a drag that began # with a double click select whole words (`snap_to_word_edge` in src/input/base/selection.rs). `SelectableText::runs` lets -# a card's text keep its styling while selectable. +# a card's text keep its styling while selectable. `code_background` (src/text/inline_flow.rs) covers inline code's +# whole glyph box rather than its capital height, so descenders stay inside it. [patch.crates-io] gpui-base = { path = "vendor/gpui-base" } diff --git a/vendor/gpui-base/src/text/inline_flow.rs b/vendor/gpui-base/src/text/inline_flow.rs index 8db982b..f8e106a 100644 --- a/vendor/gpui-base/src/text/inline_flow.rs +++ b/vendor/gpui-base/src/text/inline_flow.rs @@ -963,15 +963,7 @@ fn layout_measured_flow( let baseline = shaped_line.ascent; let code_background = is_code .then(|| { - code_background( - &shaped_line, - &runs, - segment_font_size, - &mut highlights, - glyph_size, - baseline, - window, - ) + code_background(&shaped_line, &mut highlights, glyph_size, baseline) }) .flatten(); line_ascent = line_ascent.max(baseline - body_overflow_above); @@ -1105,28 +1097,18 @@ fn layout_measured_flow( } } -/// The rounded box behind a code span, relative to the fragment: centered on -/// the capital-height body of the text, with the descender room shared -/// between both sides instead of added only below. Takes the background -/// color out of `highlights`, so the text does not paint it a second time -/// at the full line height. +/// The rounded box behind a code span, relative to the fragment: the code's +/// whole glyph box, from the top of its tallest letters to the bottom of its +/// descenders, so no letter sticks out of it. (m4code's patch: upstream fits +/// it to the capital height, which leaves g, p and y hanging below.) Takes the +/// background color out of `highlights`, so the text does not paint it a +/// second time at the full line height. fn code_background( shaped_line: &ShapedLine, - runs: &[TextRun], - font_size: Pixels, highlights: &mut [(Range, InlineHighlight)], fragment_size: Size, baseline: Pixels, - window: &Window, ) -> Option<(Bounds, Hsla)> { - let cap_height = runs - .iter() - .map(|run| { - let font = window.text_system().resolve_font(&run.font); - window.text_system().cap_height(font, font_size) - }) - .fold(Pixels::ZERO, Pixels::max); - let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.; let color = highlights .iter() .find_map(|(_, h)| h.style.background_color); @@ -1136,8 +1118,8 @@ fn code_background( color.map(|color| { ( Bounds::new( - point(Pixels::ZERO, baseline - cap_height - vertical_padding), - size(fragment_size.width, cap_height + vertical_padding * 2.), + point(Pixels::ZERO, baseline - shaped_line.ascent), + size(fragment_size.width, shaped_line.ascent + shaped_line.descent), ), color, ) @@ -2017,6 +1999,48 @@ mod tests { }); } + #[test] + fn inline_code_background_covers_the_codes_whole_glyph_box() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, HighlightStyle, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(16.)), + ..Default::default() + }; + let items = vec![MeasureItem::Text { + text: "a code z".into(), + links: vec![], + highlights: vec![( + 2..6, + InlineHighlight { + style: HighlightStyle { background_color: Some(gpui::red()), ..Default::default() }, + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + }, + )], + }]; + window.update(|_, window, cx| { + let layout = layout_flow(&items, &[None], &style, None, window, cx); + let background = layout + .fragments + .iter() + .find_map(|fragment| match fragment { + PositionedFragment::Text { code_background: Some((bounds, _)), .. } => Some(*bounds), + _ => None, + }) + .expect("the code span has a background"); + // The test font rises 0.8 em and descends 0.2 em, so the 14px code's glyph box is 14px tall. Fitted to + // the capital height, as upstream does, it would be 16.1px and sit off center. + assert_eq!(background.size.height, px(14.)); + assert!(background.origin.y >= Pixels::ZERO); + assert!(background.origin.y + background.size.height <= layout.size.height, "it stays inside its line"); + }); + } + #[test] fn inline_code_size_is_relative_and_uses_the_native_body_baseline() { use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; From 620414b1e8615beaa981801e80534c2306d88483 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 21:55:53 +0200 Subject: [PATCH 6/8] Show a steer where Claude reads it, and send it at "next" priority A steer went into the chat the moment it was sent, while Claude was still writing. The rest of that reply then landed after the user's message, so the reply looked cut off and its end looked like the answer to the steer. The bridge now sends a steer at "next" priority, as t3code does, so Claude finishes its current step first. Once Claude reads the steer, the bridge emits it as a `user_message_chunk` marked `_meta.m4code.steer`. Until then the chat holds it above the message box. A steer still unread when the agent exits becomes a notice. --- README.md | 2 +- bridge/claude.mjs | 37 ++++++++++++++++--- src/thread/mod.rs | 88 +++++++++++++++++++++++++++++++++++++++----- src/thread/render.rs | 26 +++++++++++-- 4 files changed, 134 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 81a4afa..42428ea 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 between tool calls, and 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 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. 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/claude.mjs b/bridge/claude.mjs index fb3a352..a1306d0 100644 --- a/bridge/claude.mjs +++ b/bridge/claude.mjs @@ -263,6 +263,8 @@ async function finishTurn(session, result) { const turn = session.turn; if (turn && !session.cancelled && !result.is_error) { const answered = answeredBy(result); + // A Claude Code that never said it started a steer has answered it by now, so it shows before the turn ends. + showWaitingSteers(session, answered); if (answered) for (const uuid of answered) turn.waiting.delete(uuid); else turn.waiting.clear(); if (turn.waiting.size) { @@ -294,7 +296,7 @@ async function finishTurn(session, result) { */ function steersBack(session, turn, receipt) { const stillQueued = new Set(receipt?.still_queued ?? []); - const unread = [...turn.waiting].filter((uuid) => turn.steers.has(uuid) && stillQueued.has(uuid)); + 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)); @@ -327,6 +329,7 @@ async function pump(session) { } // Not in the SDK's types yet; t3code reads it the same way. if (m.type === "command_lifecycle") { + if (m.state === "started") showSteer(session, m.command_uuid); await steerDropped(session, m); continue; } @@ -334,7 +337,11 @@ async function pump(session) { if (m.parent_tool_use_id) continue; if (m.type === "stream_event") { const ev = m.event; - if (ev.type === "message_start") session.streamed.add(ev.message.id); + if (ev.type === "message_start") { + session.streamed.add(ev.message.id); + // After a result the turn stayed open for, what Claude writes next answers the steers it still owed. + if (session.turn?.held) showWaitingSteers(session, [...session.turn.waiting]); + } if (ev.type === "content_block_delta" && ev.delta.type === "text_delta") update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: ev.delta.text } }); if (ev.type === "content_block_delta" && ev.delta.type === "thinking_delta") update(session.id, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: ev.delta.thinking } }); } else if (m.type === "assistant") { @@ -445,7 +452,7 @@ const handlers = { s.dropInterrupted = false; 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(), dropped: [], held: null })); + const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), shown: new Set(), dropped: [], held: null })); s.inbox.push(userMessage(s, text, uuid)); return done; }, @@ -456,7 +463,8 @@ const handlers = { const uuid = randomUUID(); s.turn.waiting.add(uuid); s.turn.steers.set(uuid, p.text); - s.inbox.push(userMessage(s, p.text, uuid)); + // "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 {}; }, "session/set_mode": async (p) => { @@ -481,8 +489,25 @@ const handlers = { }, }; -function userMessage(session, text, uuid) { - return { type: "user", uuid, message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, session_id: session.id, origin: { kind: "human" } }; +function userMessage(session, text, uuid, priority) { + return { type: "user", uuid, ...(priority ? { priority } : {}), message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, session_id: session.id, origin: { kind: "human" } }; +} + +/** + * Show a steer in the conversation once Claude reads it, not when it was sent: what Claude was still writing then + * comes first. m4code knows it by `_meta.m4code.steer` and takes it off the list of steers waiting to be read. + */ +function showSteer(session, uuid) { + const turn = session.turn; + 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 } } }); +} + +/** Every steer not shown yet, oldest first: Claude is about to answer them, or just did. */ +function showWaitingSteers(session, only) { + for (const uuid of session.turn?.steers.keys() ?? []) if (!only || only.includes(uuid)) showSteer(session, uuid); } function cancel(p) { diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 33f6d57..6d1d528 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -221,6 +221,10 @@ pub struct ThreadView { /// the list would otherwise drop it and parse again when it comes back, and a long message (over 4 KB) parses /// in the background, so it would draw empty for a frame and then grow, moving everything around it. markdown: HashMap>, + /// 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, /// What a message sent while the agent works does (Settings → General). pub(crate) follow_up: crate::store::FollowUp, pub compaction: crate::harness::compaction::Policy, @@ -351,6 +355,7 @@ impl ThreadView { detail: false, subagent_edits: None, markdown: HashMap::new(), + steering: VecDeque::new(), follow_up: crate::store::FollowUp::default(), compaction: Default::default(), canonical_history: false, @@ -506,6 +511,9 @@ impl ThreadView { if let Some(at) = self.thread.apply(&update) { self.remeasure(at); } + if update.pointer("/_meta/m4code/steer").and_then(Value::as_bool) == Some(true) { + self.steering.pop_front(); + } if self.thread.title != title && let Some(t) = self.thread.title.clone() { @@ -610,6 +618,10 @@ impl ThreadView { crate::claude::bridge::respond(&req_id, false, "The session ended before the user answered."); } 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); + } self.connection = None; cx.emit(ThreadEvent::Exited(if self.error.is_some() { Some(1) } else { Some(0) })); cx.notify(); @@ -682,18 +694,16 @@ impl ThreadView { cx.notify(); return; } - if let Some(at) = self.thread.sent(text.clone()) { - self.remeasure(at); - } - self.persist_entries(); - self.list.scroll_to_end(); + self.steering.push_back(text.clone()); let reply = connection.request("_m4code/steer", json!({"sessionId": session, "text": text})); 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; the chat already - // shows it. + // The turn ended before the message reached it, so it is the next message instead. let _ = this.update(cx, |v, cx| { - v.queue.push_front(Queued { text, shown: true, compact: false, by_user: true }); + if let Some(at) = v.steering.iter().position(|t| *t == text) { + v.steering.remove(at); + } + v.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); v.send_next(cx); cx.notify(); }); @@ -841,12 +851,14 @@ impl ThreadView { // 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. for text in steers_back("resend").into_iter().rev() { - self.queue.push_front(Queued { text, shown: true, compact: false, by_user: true }); + self.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); } for text in steers_back("unread") { let at = self.thread.notice(format!("The agent stopped before reading your message, so it was not sent: {text}"), false); self.remeasure(at); } + // Every steer was read, given back above, or lost with the agent; none waits past its turn. + self.steering.clear(); 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"); @@ -1370,6 +1382,11 @@ impl ThreadView { } /// 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() @@ -1757,6 +1774,59 @@ mod tests { }); } + #[gpui::test] + fn a_steer_joins_the_chat_where_the_agent_reads_it_not_where_it_was_sent(cx: &mut gpui::TestAppContext) { + use crate::harness::acp::Event; + use crate::store::FollowUp; + use serde_json::json; + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let start = super::Start { + record_id: String::new(), + harness: Harness::Claude, + all_models: vec![], + picked: vec![], + cwd: dir.path().to_path_buf(), + 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![])), + }; + let (view, cx) = cx.add_window_view(|window, cx| super::ThreadView::new(start, window, cx)); + // An agent that never answers: the steer request goes out and waits. Its ends stay open for the rest of the + // run, because closing them fails the request from the connection's reader thread, which GPUI's test + // executor rejects as activity from outside it. + let (from_agent, to_client) = std::io::pipe().unwrap(); + let (from_client, to_agent) = std::io::pipe().unwrap(); + std::mem::forget((to_client, from_client)); + let (tx, _events) = futures::channel::mpsc::unbounded(); + let connection = crate::harness::acp::Connection::connect(from_agent, to_agent, None::, tx); + let chunk = |kind: &str, text: &str| json!({"sessionUpdate": kind, "content": {"type": "text", "text": text}}); + view.update(cx, |v, cx| { + v.connection = Some(std::rc::Rc::new(connection)); + v.session_id = Some("s1".into()); + v.phase = super::Phase::Ready; + v.working = true; + v.thread.entries.clear(); + v.on_event(Event::Update(chunk("agent_message_chunk", "Hello wor")), cx); + v.send_as("stop".into(), FollowUp::Steer, cx); + assert_eq!(v.unread_steers().collect::>(), ["stop"], "waits above the message box"); + // 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}}); + 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())]); + assert_eq!(v.unread_steers().count(), 0); + }); + } + #[gpui::test] fn new_session_shows_prompt_immediately_at_top(cx: &mut gpui::TestAppContext) { cx.update(gpui_kit::init); diff --git a/src/thread/render.rs b/src/thread/render.rs index eaa29ef..d91e266 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -107,6 +107,11 @@ pub(super) fn markdown_of(cache: &mut HashMap>, ix: crate::github::ui::styled_markdown(TextView::new(&state)) } +/// A message's first line with text, for a one-line row. +fn first_line(text: &str) -> String { + text.lines().find(|l| !l.trim().is_empty()).unwrap_or_default().trim().to_string() +} + fn waiting(message: &str) -> Div { div() .flex_1() @@ -977,11 +982,25 @@ impl ThreadView { /// before it is sent. fn render_waiting(&self, cx: &mut Context) -> Option
{ let waiting = self.waiting_messages(); - if waiting.is_empty() { + let steering: Vec = self.unread_steers().map(first_line).collect(); + if waiting.is_empty() && steering.is_empty() { return None; } + let steering_rows = steering.into_iter().enumerate().map(|(i, line)| { + div() + .w_full() + .flex() + .items_center() + .gap(px(8.0)) + .px(px(10.0)) + .py(px(4.0)) + .child(spinner(SharedString::from(format!("steering-{i}")), 12.0)) + .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(line)) + .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 rows = waiting.into_iter().map(|(at, text)| { - let first_line = text.lines().find(|l| !l.trim().is_empty()).unwrap_or_default().trim().to_string(); + let first_line = first_line(text); div() .w_full() .flex() @@ -1010,7 +1029,8 @@ impl ThreadView { .border_color(hsla(theme::PANEL_BORDER)) .flex() .flex_col() - .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(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), ) } From 03ca4d4b663373eae5e91afe4e775f359d89acc4 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 22:21:04 +0200 Subject: [PATCH 7/8] Fix what review found in steering, the queue, questions and card drag - Bridge: - A new message waits, up to 10 s, until the steers the user stopped have run and been stopped. Clearing them let one run in the new turn and fail it. - A turn still open when Claude Code's stream ends is rejected rather than left working. - After a held result, only the oldest waiting steer shows as read. - Chat: - A steer the turn ends without reading, as when it fails, becomes a notice instead of disappearing. - Each steer is its own message, even right after another one. - Steers for an agent that restarts keep their order, ahead of the queue. - A running slash command such as a manual /compact can't be steered into. - The slash menu stays closed while a question takes the typed answer. - Replay drops the parsed markdown along with the entries. - Queue buttons get new ids when messages move. - Fences close only on a marker as long as the one that opened them. - Sidebar: a card moves only once the pointer passes the middle of the card it goes over, so cards of different heights no longer swap back and forth. --- bridge/claude.mjs | 40 ++++++++++-- src/panels/inspector.rs | 10 +++ src/thread/mod.rs | 136 ++++++++++++++++++++++++++++++++++------ src/thread/render.rs | 38 ++++++++--- 4 files changed, 192 insertions(+), 32 deletions(-) diff --git a/bridge/claude.mjs b/bridge/claude.mjs index a1306d0..9811fbe 100644 --- a/bridge/claude.mjs +++ b/bridge/claude.mjs @@ -321,10 +321,13 @@ async function pump(session) { if (m.type === "result") { for (const uuid of answeredBy(m) ?? [...session.dropping]) session.dropping.delete(uuid); session.dropInterrupted = false; + } else if (m.type === "command_lifecycle" && ["cancelled", "discarded", "refused"].includes(m.state)) { + session.dropping.delete(m.command_uuid); } else if (!session.dropInterrupted) { session.dropInterrupted = true; session.query.interrupt().catch(() => {}); } + if (!session.dropping.size) session.dropsDone?.(); continue; } // Not in the SDK's types yet; t3code reads it the same way. @@ -339,8 +342,14 @@ async function pump(session) { const ev = m.event; if (ev.type === "message_start") { session.streamed.add(ev.message.id); - // After a result the turn stayed open for, what Claude writes next answers the steers it still owed. - if (session.turn?.held) showWaitingSteers(session, [...session.turn.waiting]); + // After a result the turn stayed open for, what Claude writes next answers the oldest steer it still + // owed; a later one may still be waiting, so it shows when Claude starts or answers it. + const turn = session.turn; + if (turn?.held) { + turn.held = null; + const oldest = [...turn.waiting].find((uuid) => turn.steers.has(uuid) && !turn.shown.has(uuid)); + if (oldest) showSteer(session, oldest); + } } if (ev.type === "content_block_delta" && ev.delta.type === "text_delta") update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: ev.delta.text } }); if (ev.type === "content_block_delta" && ev.delta.type === "thinking_delta") update(session.id, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: ev.delta.thinking } }); @@ -365,13 +374,16 @@ async function pump(session) { session.turn?.reject(error); session.turn = null; } + // Claude Code ended with a turn still open, such as one held for a steer it never answered. + session.turn?.reject(new Error("Claude Code stopped before it finished the turn.")); + session.turn = null; sessions.delete(session.id); } 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, mode: "default", model: "", effort: "medium", models: [] }; + 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: [] }; session.query = query({ prompt: session.inbox, options: { @@ -447,9 +459,9 @@ const handlers = { if (!s) throw new Error("That session has ended."); if (s.turn) throw new Error("A turn is already running."); s.cancelled = false; - // A new message is the user's own again: stopping the steers they took back must not stop this one. - s.dropping.clear(); - s.dropInterrupted = false; + // 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); 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 })); @@ -489,6 +501,22 @@ const handlers = { }, }; +/** + * Resolves once the stopped steers (`dropping`) have run and been stopped, or after 10 s: Claude Code's receipt said + * it would run them, and one that hasn't started by then is taken as gone, so a new message never waits forever. + */ +async function afterDropped(session) { + if (session.dropping.size) { + await new Promise((resolve) => { + session.dropsDone = resolve; + setTimeout(resolve, 10_000); + }); + } + session.dropsDone = null; + session.dropping.clear(); + session.dropInterrupted = false; +} + function userMessage(session, text, uuid, priority) { return { type: "user", uuid, ...(priority ? { priority } : {}), message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, session_id: session.id, origin: { kind: "human" } }; } diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs index 69fc8ee..3d860f3 100644 --- a/src/panels/inspector.rs +++ b/src/panels/inspector.rs @@ -246,6 +246,16 @@ impl Workspace { if from == kind || !ev.bounds.contains(&ev.event.position) || !ws.pointer_moved(ev.event.position) { return; } + // Cards differ in height, so a short card dragged onto a tall one could still be over it after they + // swap, and swap back. It moves only once the pointer is past the middle of the card it goes over, in + // the direction it travels, which the card that moved out of the way never is. + let order = ws.store.data.layout.right_card_order(); + let at = |card: SideCard| order.iter().position(|k| *k == card); + let down = at(from) < at(kind); + let middle = ev.bounds.center().y; + if (down && ev.event.position.y < middle) || (!down && ev.event.position.y > middle) { + return; + } ws.move_right_card(from, kind); ws.last_swap = std::time::Instant::now(); cx.notify(); diff --git a/src/thread/mod.rs b/src/thread/mod.rs index 6d1d528..ea072c8 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -161,6 +161,8 @@ struct Queued { 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, } @@ -225,6 +227,11 @@ pub struct ThreadView { /// 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, + /// 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). pub(crate) follow_up: crate::store::FollowUp, pub compaction: crate::harness::compaction::Policy, @@ -316,7 +323,7 @@ impl ThreadView { if shown { thread.sent(prompt.clone()); } - queue.push_back(Queued { text: prompt, shown, compact: false, by_user: false }); + queue.push_back(Queued { text: prompt, shown, compact: false, by_user: false, ahead: false }); } let rows = thread.entries.len(); let list = ListState::new(rows, ListAlignment::Top, px(600.0)); @@ -356,6 +363,8 @@ 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, @@ -501,6 +510,7 @@ impl ThreadView { if self.canonical_history { return; } self.cached_replay = false; self.thread.entries.clear(); + self.markdown.clear(); self.remeasure(0); } if self.phase == Phase::Ready && !self.cached_replay && is_conversation_update(&update) { @@ -508,11 +518,16 @@ impl ThreadView { } let title = self.thread.title.clone(); let prev_ctx = self.thread.context; - if let Some(at) = self.thread.apply(&update) { - self.remeasure(at); - } - if update.pointer("/_meta/m4code/steer").and_then(Value::as_bool) == Some(true) { + // 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()) + } else { + self.thread.apply(&update) + }; + if let Some(at) = at { + self.remeasure(at); } if self.thread.title != title && let Some(t) = self.thread.title.clone() @@ -675,6 +690,7 @@ impl ThreadView { && self.working && self.phase == Phase::Ready && !self.compaction.running + && !self.running_command && !text.starts_with('/') } @@ -682,12 +698,15 @@ impl ThreadView { /// can't stops its turn, and the message goes first once it has stopped. fn steer(&mut self, text: String, 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 }); + self.queue.push_back(Queued { text, shown: false, compact: false, by_user: true, ahead: false }); cx.notify(); return; }; if !self.harness.adapter().steers { - self.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); + // After any message steered in before it, so they go in the order they were sent. + 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); @@ -703,7 +722,7 @@ impl ThreadView { if let Some(at) = v.steering.iter().position(|t| *t == text) { v.steering.remove(at); } - v.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); + v.queue.push_front(Queued { text, shown: false, compact: false, by_user: true, ahead: false }); v.send_next(cx); cx.notify(); }); @@ -716,7 +735,7 @@ impl ThreadView { /// 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 }); + self.queue.push_back(Queued { text, shown: false, compact: false, by_user: false, ahead: false }); self.send_next(cx); cx.notify(); } @@ -758,7 +777,7 @@ impl ThreadView { if shown && let Some(at) = self.thread.sent(text.clone()) { self.remeasure(at); } - self.queue.push_back(Queued { text, shown, compact: false, by_user: true }); + self.queue.push_back(Queued { text, shown, compact: false, by_user: true, ahead: false }); self.send_next(cx); cx.notify(); } @@ -772,7 +791,7 @@ impl ThreadView { let next = if 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 } + Queued { text: format!("/{}", command.unwrap()), shown: true, compact: true, by_user: false, ahead: false } } else { let Some(next) = self.queue.pop_front() else { return }; next @@ -783,6 +802,8 @@ impl ThreadView { self.remeasure(at); } self.cached_replay = false; + self.queue_changes += 1; + self.running_command = next.text.starts_with('/'); let text = next.text; let compact = next.compact; self.persist_entries(); @@ -850,15 +871,24 @@ impl ThreadView { }; // 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. - for text in steers_back("resend").into_iter().rev() { - self.queue.push_front(Queued { text, shown: false, compact: false, by_user: true }); + 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 steers_back("unread") { + 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); + } + // 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); } - // Every steer was read, given back above, or lost with the agent; none waits past its turn. - self.steering.clear(); 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"); @@ -1347,6 +1377,10 @@ impl ThreadView { /// The commands a typed `/` prefix matches, for the menu over the composer: all of them, which it scrolls. 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) { + return vec![]; + } let Some(typed) = draft.strip_prefix('/').filter(|t| !t.contains(char::is_whitespace)) else { return vec![] }; self.shown_commands().filter(|c| c.name.starts_with(typed)).collect() } @@ -1396,6 +1430,7 @@ impl ThreadView { 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 } @@ -1690,9 +1725,9 @@ 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 }); - v.queue.push_back(super::Queued { text: "first\nmore".into(), shown: false, compact: false, by_user: true }); - v.queue.push_back(super::Queued { text: "second".into(), shown: false, compact: false, by_user: true }); + 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.set_draft("typed", window, cx); @@ -1735,6 +1770,9 @@ mod tests { v.compaction.running = true; assert!(!v.can_steer("hi", FollowUp::Steer), "compaction takes no steers"); v.compaction.running = false; + v.running_command = true; + assert!(!v.can_steer("hi", FollowUp::Steer), "nor does a /compact the user ran"); + v.running_command = false; // With no agent to reach, the message waits rather than being lost. v.queue.clear(); v.send_as("hi".into(), FollowUp::Steer, cx); @@ -1824,6 +1862,66 @@ mod tests { 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())]); assert_eq!(v.unread_steers().count(), 0); + // Two steers read one after the other stay two messages. + v.send_as("do X".into(), FollowUp::Steer, cx); + 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}}); + 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("unread".into(), FollowUp::Steer, 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 + ); + }); + } + + #[gpui::test] + fn steers_an_agent_restarts_for_go_in_the_order_sent_before_the_queue(cx: &mut gpui::TestAppContext) { + use crate::store::FollowUp; + cx.update(gpui_kit::init); + let dir = tempfile::tempdir().unwrap(); + let start = super::Start { + record_id: String::new(), + harness: Harness::Codex, + all_models: vec![], + picked: vec![], + cwd: dir.path().to_path_buf(), + 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![])), + }; + let (view, cx) = cx.add_window_view(|window, cx| super::ThreadView::new(start, window, cx)); + // Kept open for the rest of the run, as in `a_steer_joins_the_chat_where_the_agent_reads_it_not_where_it_was_sent`. + let (from_agent, to_client) = std::io::pipe().unwrap(); + let (from_client, to_agent) = std::io::pipe().unwrap(); + std::mem::forget((to_client, from_client)); + let (tx, _events) = futures::channel::mpsc::unbounded(); + let connection = crate::harness::acp::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("s1".into()); + v.phase = super::Phase::Ready; + v.working = true; + v.queue.clear(); + v.send_as("queued".into(), FollowUp::Queue, cx); + v.send_as("first".into(), FollowUp::Steer, cx); + v.send_as("second".into(), FollowUp::Steer, cx); + let order: Vec<&str> = v.queue.iter().map(|q| q.text.as_str()).collect(); + assert_eq!(order, ["first", "second", "queued"]); }); } diff --git a/src/thread/render.rs b/src/thread/render.rs index d91e266..c8edd29 100644 --- a/src/thread/render.rs +++ b/src/thread/render.rs @@ -83,13 +83,23 @@ impl Render for ThreadView { /// where lines already stay as they are. fn keep_line_breaks(text: &str) -> String { let lines: Vec<&str> = text.lines().collect(); - let mut in_fence = false; + // The open fence's marker character and length: only a run of that character at least as long closes it. + let mut open: Option<(char, usize)> = None; let mut out = String::with_capacity(text.len() + lines.len()); for (i, line) in lines.iter().enumerate() { - let fence = line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~"); - if fence { - in_fence = !in_fence; - } + let marker = fence_marker(line); + let fence = match (open, marker) { + (None, Some(m)) => { + open = Some(m); + true + } + (Some((c, n)), Some((mc, mn))) if mc == c && mn >= n => { + open = None; + true + } + _ => false, + }; + let in_fence = open.is_some(); out.push_str(line); let Some(next) = lines.get(i + 1) else { break }; let breaks = !in_fence && !fence && !line.trim().is_empty() && !next.trim().is_empty(); @@ -107,6 +117,14 @@ pub(super) fn markdown_of(cache: &mut HashMap>, ix: crate::github::ui::styled_markdown(TextView::new(&state)) } +/// A line that opens or closes a fenced code block: its marker character and how many of it there are. +fn fence_marker(line: &str) -> Option<(char, usize)> { + let trimmed = line.trim_start(); + let c = trimmed.chars().next().filter(|c| *c == '`' || *c == '~')?; + let n = trimmed.chars().take_while(|x| *x == c).count(); + (n >= 3).then_some((c, n)) +} + /// A message's first line with text, for a one-line row. fn first_line(text: &str) -> String { text.lines().find(|l| !l.trim().is_empty()).unwrap_or_default().trim().to_string() @@ -999,6 +1017,7 @@ 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); div() @@ -1011,11 +1030,11 @@ impl ThreadView { .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-{at}")), IconName::Pencil) + 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-{at}")), IconName::X) + icon_button(SharedString::from(format!("queued-remove-{changes}-{at}")), IconName::X) .on_click(cx.listener(move |v, _: &ClickEvent, _, cx| drop(v.unqueue(at, cx)))), ) }); @@ -1209,6 +1228,11 @@ mod tests { assert_eq!(keep_line_breaks("para\n\nnext"), "para\n\nnext", "a blank line already splits them"); assert_eq!(keep_line_breaks("look:\n```\na\nb\n```\nafter"), "look: \n```\na\nb\n```\nafter"); assert_eq!(keep_line_breaks("single"), "single"); + assert_eq!( + keep_line_breaks("````\n```\nliteral\nlines\n````\nafter\nmore"), + "````\n```\nliteral\nlines\n````\nafter \nmore", + "a shorter marker inside a longer fence is code, not its end" + ); } #[test] From 10f49d0a61bd70c2d6e4eb877d82a112b0882b26 Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Sun, 22 Nov 2026 22:40:01 +0200 Subject: [PATCH 8/8] Stop the one headless test that runs with the unit tests from moving their data folder `a_process_that_ends_closes_the_session_and_leaves_its_worktree` isn't ignored, so it ran beside the unit tests and set `M4CODE_DATA_DIR` to its own folder while the worktree tests read theirs. It failed CI on Linux, including on main. The test now uses the run's one throwaway folder (`datadir::use_throwaway_folders`) and finds its project by path. Part of #149: the ignored headless tests still set the variable, though they run on their own. --- src/app/headless/agents.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/headless/agents.rs b/src/app/headless/agents.rs index 60e3488..de16493 100644 --- a/src/app/headless/agents.rs +++ b/src/app/headless/agents.rs @@ -339,8 +339,10 @@ fn a_missing_claude_offers_the_setup_window() { /// exit is a toast, and the worktree stays: Claude Code already asked on `/exit`, and the X is the path that offers. #[test] fn a_process_that_ends_closes_the_session_and_leaves_its_worktree() { - let data = tempfile::tempdir().unwrap(); - unsafe { std::env::set_var("M4CODE_DATA_DIR", data.path()) }; + // Not `#[ignore]`d, so it runs beside the unit tests: it takes the run's one data folder rather than setting + // `M4CODE_DATA_DIR` to its own, which would move theirs while they read it (#149). Its repository is new, so + // its worktree folder and project are its own there. + crate::datadir::use_throwaway_folders(); let work = tempfile::tempdir().unwrap(); let repo_dir = dunce::canonicalize(work.path()).unwrap().join("proj"); let git = |args: &[&str]| std::process::Command::new("git").args(args).current_dir(&repo_dir).output().unwrap(); @@ -360,7 +362,7 @@ fn a_process_that_ends_closes_the_session_and_leaves_its_worktree() { let (window, ws) = cx .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![repo_dir.clone()], cx)))) .unwrap(); - let project = ws.read_with(&cx, |ws, _| ws.store.data.projects[0].id.clone()); + let project = ws.read_with(&cx, |ws, _| ws.store.data.projects.iter().find(|p| p.path == repo_dir).expect("the project opened").id.clone()); let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap();