From 201f61d873c9962b6fb6d65d381ed6a40936cbdd Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:22:44 -0800 Subject: [PATCH 01/35] Docs: compare conch with herdr, T3 Code and Orca A Compared page in the docs: one table across the four tools (shape, platforms, persistence, agents, state, sessions, git and PRs, the autopilot, MCP and scoping, remote machines, sandboxes, phone), then when another tool is the better choice and when conch is. Dated, from each project's own docs, since the others ship weekly. Linked from the introduction's "Is conch for you?". Tests: every sidebar entry has a page.mdx, and the compare page lists all four tools, says when it was written, and has no row whose cells would shift under the wrong column. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/docs_test.go | 69 +++++++++++++++++++++++++++++++ web/src/app/docs/compare/page.mdx | 57 +++++++++++++++++++++++++ web/src/app/docs/page.mdx | 2 +- web/src/lib/docs.ts | 1 + 4 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 cmd/conch/docs_test.go create mode 100644 web/src/app/docs/compare/page.mdx diff --git a/cmd/conch/docs_test.go b/cmd/conch/docs_test.go new file mode 100644 index 00000000..0183c353 --- /dev/null +++ b/cmd/conch/docs_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// TestDocsSidebarPages: every page the docs sidebar lists has a page.mdx, +// so a link added to the sidebar cannot lead to a 404 on the website. +func TestDocsSidebarPages(t *testing.T) { + nav, err := os.ReadFile("../../web/src/lib/docs.ts") + if err != nil { + t.Fatal(err) + } + hrefs := regexp.MustCompile(`href: "(/docs[^"]*)"`).FindAllStringSubmatch(string(nav), -1) + if len(hrefs) == 0 { + t.Fatal("no pages found in docs.ts") + } + for _, m := range hrefs { + dir := filepath.Join("../../web/src/app", strings.TrimPrefix(m[1], "/")) + if _, err := os.Stat(filepath.Join(dir, "page.mdx")); err != nil { + t.Errorf("sidebar lists %s, which has no page: %v", m[1], err) + } + } +} + +// TestDocsComparePage: the comparison with other agent orchestrators is in +// the sidebar, has its table with a column for each tool, and says when it +// was written — what the others do changes weekly, so an undated table +// would read as current long after it is not. +func TestDocsComparePage(t *testing.T) { + nav, err := os.ReadFile("../../web/src/lib/docs.ts") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(nav), `href: "/docs/compare"`) { + t.Fatal("the docs sidebar does not list /docs/compare") + } + page, err := os.ReadFile("../../web/src/app/docs/compare/page.mdx") + if err != nil { + t.Fatal(err) + } + header := regexp.MustCompile(`(?m)^\|[^\n]*conch[^\n]*\|\n\| ?---`).Find(page) + if header == nil { + t.Fatal("no comparison table with a conch column") + } + for _, tool := range []string{"herdr", "T3 Code", "Orca"} { + if !strings.Contains(string(header), tool) { + t.Errorf("comparison table has no %s column: %s", tool, header) + } + } + if !regexp.MustCompile(`As of \w+ \d{4}`).Match(page) { + t.Error("comparison page does not say when it was written") + } + // Every row has as many cells as the header, or a cell renders under + // the wrong tool. + start := strings.Index(string(page), string(header)) + table, _, _ := strings.Cut(string(page)[start:], "\n\n") + cells := func(l string) int { return strings.Count(strings.ReplaceAll(l, `\|`, ""), "|") } + lines := strings.Split(strings.TrimSpace(table), "\n") + for _, l := range lines[1:] { + if cells(l) != cells(lines[0]) { + t.Errorf("row has %d cells, header %d: %s", cells(l)-1, cells(lines[0])-1, l) + } + } +} diff --git a/web/src/app/docs/compare/page.mdx b/web/src/app/docs/compare/page.mdx new file mode 100644 index 00000000..0142f520 --- /dev/null +++ b/web/src/app/docs/compare/page.mdx @@ -0,0 +1,57 @@ +export const metadata = { title: "Compared", description: "conch beside herdr, T3 Code and Orca: what each does, and where each is the better choice." } + +# Compared + +conch is one of several tools for running coding agents side by side. The three it is most often weighed against are [herdr](https://herdr.dev), [T3 Code](https://github.com/pingdotgg/t3code) and [Orca](https://orca.dev). Each takes a different shape: + +- **herdr** is closest to conch: a server that owns the terminals, a tmux-style TUI, and ssh machines that install it themselves. It is written in Rust. +- **T3 Code** drives agents through their SDKs (Claude's Agent SDK, the Codex app server, ACP) and shows them as chat threads, on the desktop, the web and phones. +- **Orca** is a desktop IDE built on Electron around worktrees: agents in terminals or a chat view, an editor, diffs, pull request review and a browser. + +As of November 2026, from each project's own documentation. All three ship often, so check their docs for anything that matters to you, and [open an issue](https://github.com/Amitgb14/conch/issues) if something here has gone out of date. + +## At a glance + +| | conch | herdr | T3 Code | Orca | +| --- | --- | --- | --- | --- | +| Shape | TUI, plus a [Mac app](/docs/mac-app) and a [phone](/docs/phone) page | TUI, plus a desktop app | Chat app: desktop, web, iOS, Android | Desktop IDE, plus iOS and Android | +| Language, license | Go, Apache-2.0 | Rust, Apache-2.0 | TypeScript, MIT | TypeScript (Electron), MIT | +| Platforms | macOS, Linux (WSL on Windows) | macOS, Linux, Windows | macOS, Linux, Windows, web | macOS, Linux, Windows | +| Where the agent shows | its own interface, in a terminal | its own interface, in a terminal | a chat thread; terminals beside it | a terminal, or a chat view | +| Agents keep running with the UI closed | yes | yes | yes | yes | +| Updating keeps agents running | yes, by default | opt-in, experimental | no: running turns are interrupted | yes, for app updates | +| Usable over plain ssh | yes | yes | no | no | +| Agents | 5 [supported](/docs/agents), 6 more run from manifests, and your own | about 18 integrated, more by screen | about 10, plus any ACP agent | about 34, plus any CLI agent | +| How state is known | the agent's own reports (OSC 7501), hooks, then the screen | the screen, by rules updated without a release, and agents' own reports | the SDK's events | window titles and hooks | +| Conversations after a restart | listed in [Sessions](/docs/sessions), resumed with a key | resumed automatically | threads carry on | layout and scrollback restored | +| Saved conversations across agents | search, resume, delete, hand to another agent | — | threads, forks, delegation | full-text search | +| Worktree per task | yes | yes | yes | yes | +| Diff, hunk staging | yes | — | yes, per turn | yes, with notes for the agent | +| Pull request review | basic, GitHub only | — | full, 7 forges, stacks | full, stacks, Linear and Jira | +| Failed CI sent back to the agent | yes, by the server, with no UI open ([autopilot](/docs/interface#sending-a-failure-back)) | — | — | with a button | +| Merge when green | yes, by the server | — | auto-merge | auto-merge | +| Scheduled work | yes: at a time, repeating, queued, after other work | — | yes | yes, with prechecks | +| MCP | conch is a server (`conch mcp`) | — | injected into its agents | servers you add, for its agents | +| An agent limited to its own work | yes, by [scope](/docs/agents-together#what-an-agent-may-do) | — | yes, by token | — | +| Remote machines | ssh, installed for you, one tree | ssh, installed for you, one window | ssh, Tailscale, its relay | ssh, or a server of its own | +| Cloud sandboxes | [Daytona, boat.dev, Tensorlake, Devin Cloud](/docs/sandboxes), and your own | — | — | cloud VMs, experimental | +| Phone | a web app, through Tailscale or a relay you run | ssh from a phone | native apps, through its hosted relay | native apps, through its relay | +| Plain-language requests | the [brain](/docs/brain), confirmed before it runs | — | — | — | + +A dash means the project's documentation says nothing of it, not that a plugin or a later release cannot do it. + +## When to choose another + +- **You want a graphical review.** T3 Code and Orca review pull requests in full — threads, reactions, stacks, more forges than GitHub. conch's review is the diff and the hunk, and leaves the conversation with other people to your forge. +- **You want a chat, not a terminal.** T3 Code shows each agent as a conversation with structured approvals; conch shows the agent's own interface, as you would see it without conch. +- **You are on Windows.** herdr, T3 Code and Orca build for it; conch is macOS and Linux, and WSL. +- **Your agent is not one of conch's five.** herdr and Orca know many more agents. conch [runs others](/docs/agents#supported-agents) from a manifest, without reading their saved conversations. +- **You want native phone apps.** T3 Code and Orca have them, with their own hosted relay. conch's phone page is reached through a network you already have. + +## When to choose conch + +- **You want the loop closed without you.** conch's server sends a failed check or CI run back to the branch's agent and merges once it is green, with no window open — the step the others leave to a button or to you. +- **You want agents to drive agents, and stay in their lane.** `conch mcp` and the CLI let one agent start, prompt and read another, and an agent calling from its pane reaches only what it started and its own project. +- **You want agents in the cloud.** A sandbox is a machine like any other: conch makes it, installs itself there, and stops it when you say. +- **You live in a terminal, often over ssh.** The TUI is conch, not a fallback, and a reload onto a new build keeps every agent running. +- **You want nobody else's server between you and your phone.** The phone reaches conch through Tailscale or a relay you run, encrypted end to end. diff --git a/web/src/app/docs/page.mdx b/web/src/app/docs/page.mdx index 2d761101..6b4ec1a2 100644 --- a/web/src/app/docs/page.mdx +++ b/web/src/app/docs/page.mdx @@ -18,7 +18,7 @@ conch is a terminal orchestrator for AI coding agents. A background server owns - **An agent conch does not support in full.** Five are [supported](/docs/agents#supported-agents) — adapter, detection, sessions that list and resume. Others **run here** from a manifest: conch starts and watches them and does not read their saved conversations. If what you need is deep support for a sixth agent, say so rather than assuming the manifest covers it. - **Unattended swarms.** conch waits for Enter on purpose: the [brain](/docs/brain) proposes actions and nothing runs until you confirm, and an agent's question stops the work until somebody answers it. If you want dozens of agents running without a person in the loop, conch is deliberately not that, and will not become it. -The shortest version: **conch is a terminal multiplexer that understands agents and git branches.** Where it is the wrong tool, it is usually because you want fewer agents, a graphical diff, or no human in the loop. +The shortest version: **conch is a terminal multiplexer that understands agents and git branches.** Where it is the wrong tool, it is usually because you want fewer agents, a graphical diff, or no human in the loop. How it stands beside herdr, T3 Code and Orca is on [Compared](/docs/compare). ## How it fits together diff --git a/web/src/lib/docs.ts b/web/src/lib/docs.ts index dcdd8176..ddbc7485 100644 --- a/web/src/lib/docs.ts +++ b/web/src/lib/docs.ts @@ -10,6 +10,7 @@ export const docs: DocSection[] = [ { title: "Introduction", href: "/docs", description: "What conch is and how it is put together." }, { title: "Installation", href: "/docs/installation", description: "Install, update and reload conch." }, { title: "Quick start", href: "/docs/quick-start", description: "From an empty terminal to agents working in parallel." }, + { title: "Compared", href: "/docs/compare", description: "conch beside herdr, T3 Code and Orca." }, ], }, { From 6f55e2e9e7bd08918a6ac550041e1b84eacacbc4 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:29:29 -0800 Subject: [PATCH 02/35] Docs: replace the comparison table with a Why conch page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The comparison page named herdr, T3 Code and Orca row by row, which dates quickly and reads as a claim about other projects. In its place, Why conch: what conch does that other agent orchestrators leave to you — the server-side autopilot, reloads that keep agents running, OSC 7501, scoped agent-to-agent work, sandboxes as machines, cross-agent sessions, a phone without a third party's server, the terminal first, and the brain — each linking to the page that explains it. Test: the sidebar and introduction point at /docs/why and not at the removed /docs/compare, and every point on the page links to its docs. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/docs_test.go | 50 +++++++++++++-------------- web/src/app/docs/compare/page.mdx | 57 ------------------------------- web/src/app/docs/page.mdx | 2 +- web/src/app/docs/why/page.mdx | 41 ++++++++++++++++++++++ web/src/lib/docs.ts | 2 +- 5 files changed, 67 insertions(+), 85 deletions(-) delete mode 100644 web/src/app/docs/compare/page.mdx create mode 100644 web/src/app/docs/why/page.mdx diff --git a/cmd/conch/docs_test.go b/cmd/conch/docs_test.go index 0183c353..4a212c74 100644 --- a/cmd/conch/docs_test.go +++ b/cmd/conch/docs_test.go @@ -27,43 +27,41 @@ func TestDocsSidebarPages(t *testing.T) { } } -// TestDocsComparePage: the comparison with other agent orchestrators is in -// the sidebar, has its table with a column for each tool, and says when it -// was written — what the others do changes weekly, so an undated table -// would read as current long after it is not. -func TestDocsComparePage(t *testing.T) { +// TestDocsWhyPage: the page on what conch does that other agent +// orchestrators do not is in the sidebar, in place of the comparison table +// it replaced, and every point on it links to the page that explains it. +func TestDocsWhyPage(t *testing.T) { nav, err := os.ReadFile("../../web/src/lib/docs.ts") if err != nil { t.Fatal(err) } - if !strings.Contains(string(nav), `href: "/docs/compare"`) { - t.Fatal("the docs sidebar does not list /docs/compare") + if !strings.Contains(string(nav), `href: "/docs/why"`) { + t.Fatal("the docs sidebar does not list /docs/why") } - page, err := os.ReadFile("../../web/src/app/docs/compare/page.mdx") + if strings.Contains(string(nav), "/docs/compare") { + t.Error("the docs sidebar still lists /docs/compare") + } + if _, err := os.Stat("../../web/src/app/docs/compare"); err == nil { + t.Error("the compare page is still there") + } + page, err := os.ReadFile("../../web/src/app/docs/why/page.mdx") if err != nil { t.Fatal(err) } - header := regexp.MustCompile(`(?m)^\|[^\n]*conch[^\n]*\|\n\| ?---`).Find(page) - if header == nil { - t.Fatal("no comparison table with a conch column") + points := regexp.MustCompile(`(?m)^## (.+)\n\n((?:.+\n?)+)`).FindAllStringSubmatch(string(page), -1) + if len(points) < 5 { + t.Fatalf("expected at least 5 points, found %d", len(points)) } - for _, tool := range []string{"herdr", "T3 Code", "Orca"} { - if !strings.Contains(string(header), tool) { - t.Errorf("comparison table has no %s column: %s", tool, header) + for _, p := range points { + if !strings.Contains(p[2], "](/docs/") { + t.Errorf("point %q links to no page explaining it", p[1]) } } - if !regexp.MustCompile(`As of \w+ \d{4}`).Match(page) { - t.Error("comparison page does not say when it was written") + intro, err := os.ReadFile("../../web/src/app/docs/page.mdx") + if err != nil { + t.Fatal(err) } - // Every row has as many cells as the header, or a cell renders under - // the wrong tool. - start := strings.Index(string(page), string(header)) - table, _, _ := strings.Cut(string(page)[start:], "\n\n") - cells := func(l string) int { return strings.Count(strings.ReplaceAll(l, `\|`, ""), "|") } - lines := strings.Split(strings.TrimSpace(table), "\n") - for _, l := range lines[1:] { - if cells(l) != cells(lines[0]) { - t.Errorf("row has %d cells, header %d: %s", cells(l)-1, cells(lines[0])-1, l) - } + if strings.Contains(string(intro), "/docs/compare") || !strings.Contains(string(intro), "](/docs/why)") { + t.Error("the introduction should link to /docs/why, not /docs/compare") } } diff --git a/web/src/app/docs/compare/page.mdx b/web/src/app/docs/compare/page.mdx deleted file mode 100644 index 0142f520..00000000 --- a/web/src/app/docs/compare/page.mdx +++ /dev/null @@ -1,57 +0,0 @@ -export const metadata = { title: "Compared", description: "conch beside herdr, T3 Code and Orca: what each does, and where each is the better choice." } - -# Compared - -conch is one of several tools for running coding agents side by side. The three it is most often weighed against are [herdr](https://herdr.dev), [T3 Code](https://github.com/pingdotgg/t3code) and [Orca](https://orca.dev). Each takes a different shape: - -- **herdr** is closest to conch: a server that owns the terminals, a tmux-style TUI, and ssh machines that install it themselves. It is written in Rust. -- **T3 Code** drives agents through their SDKs (Claude's Agent SDK, the Codex app server, ACP) and shows them as chat threads, on the desktop, the web and phones. -- **Orca** is a desktop IDE built on Electron around worktrees: agents in terminals or a chat view, an editor, diffs, pull request review and a browser. - -As of November 2026, from each project's own documentation. All three ship often, so check their docs for anything that matters to you, and [open an issue](https://github.com/Amitgb14/conch/issues) if something here has gone out of date. - -## At a glance - -| | conch | herdr | T3 Code | Orca | -| --- | --- | --- | --- | --- | -| Shape | TUI, plus a [Mac app](/docs/mac-app) and a [phone](/docs/phone) page | TUI, plus a desktop app | Chat app: desktop, web, iOS, Android | Desktop IDE, plus iOS and Android | -| Language, license | Go, Apache-2.0 | Rust, Apache-2.0 | TypeScript, MIT | TypeScript (Electron), MIT | -| Platforms | macOS, Linux (WSL on Windows) | macOS, Linux, Windows | macOS, Linux, Windows, web | macOS, Linux, Windows | -| Where the agent shows | its own interface, in a terminal | its own interface, in a terminal | a chat thread; terminals beside it | a terminal, or a chat view | -| Agents keep running with the UI closed | yes | yes | yes | yes | -| Updating keeps agents running | yes, by default | opt-in, experimental | no: running turns are interrupted | yes, for app updates | -| Usable over plain ssh | yes | yes | no | no | -| Agents | 5 [supported](/docs/agents), 6 more run from manifests, and your own | about 18 integrated, more by screen | about 10, plus any ACP agent | about 34, plus any CLI agent | -| How state is known | the agent's own reports (OSC 7501), hooks, then the screen | the screen, by rules updated without a release, and agents' own reports | the SDK's events | window titles and hooks | -| Conversations after a restart | listed in [Sessions](/docs/sessions), resumed with a key | resumed automatically | threads carry on | layout and scrollback restored | -| Saved conversations across agents | search, resume, delete, hand to another agent | — | threads, forks, delegation | full-text search | -| Worktree per task | yes | yes | yes | yes | -| Diff, hunk staging | yes | — | yes, per turn | yes, with notes for the agent | -| Pull request review | basic, GitHub only | — | full, 7 forges, stacks | full, stacks, Linear and Jira | -| Failed CI sent back to the agent | yes, by the server, with no UI open ([autopilot](/docs/interface#sending-a-failure-back)) | — | — | with a button | -| Merge when green | yes, by the server | — | auto-merge | auto-merge | -| Scheduled work | yes: at a time, repeating, queued, after other work | — | yes | yes, with prechecks | -| MCP | conch is a server (`conch mcp`) | — | injected into its agents | servers you add, for its agents | -| An agent limited to its own work | yes, by [scope](/docs/agents-together#what-an-agent-may-do) | — | yes, by token | — | -| Remote machines | ssh, installed for you, one tree | ssh, installed for you, one window | ssh, Tailscale, its relay | ssh, or a server of its own | -| Cloud sandboxes | [Daytona, boat.dev, Tensorlake, Devin Cloud](/docs/sandboxes), and your own | — | — | cloud VMs, experimental | -| Phone | a web app, through Tailscale or a relay you run | ssh from a phone | native apps, through its hosted relay | native apps, through its relay | -| Plain-language requests | the [brain](/docs/brain), confirmed before it runs | — | — | — | - -A dash means the project's documentation says nothing of it, not that a plugin or a later release cannot do it. - -## When to choose another - -- **You want a graphical review.** T3 Code and Orca review pull requests in full — threads, reactions, stacks, more forges than GitHub. conch's review is the diff and the hunk, and leaves the conversation with other people to your forge. -- **You want a chat, not a terminal.** T3 Code shows each agent as a conversation with structured approvals; conch shows the agent's own interface, as you would see it without conch. -- **You are on Windows.** herdr, T3 Code and Orca build for it; conch is macOS and Linux, and WSL. -- **Your agent is not one of conch's five.** herdr and Orca know many more agents. conch [runs others](/docs/agents#supported-agents) from a manifest, without reading their saved conversations. -- **You want native phone apps.** T3 Code and Orca have them, with their own hosted relay. conch's phone page is reached through a network you already have. - -## When to choose conch - -- **You want the loop closed without you.** conch's server sends a failed check or CI run back to the branch's agent and merges once it is green, with no window open — the step the others leave to a button or to you. -- **You want agents to drive agents, and stay in their lane.** `conch mcp` and the CLI let one agent start, prompt and read another, and an agent calling from its pane reaches only what it started and its own project. -- **You want agents in the cloud.** A sandbox is a machine like any other: conch makes it, installs itself there, and stops it when you say. -- **You live in a terminal, often over ssh.** The TUI is conch, not a fallback, and a reload onto a new build keeps every agent running. -- **You want nobody else's server between you and your phone.** The phone reaches conch through Tailscale or a relay you run, encrypted end to end. diff --git a/web/src/app/docs/page.mdx b/web/src/app/docs/page.mdx index 6b4ec1a2..f9e18fe3 100644 --- a/web/src/app/docs/page.mdx +++ b/web/src/app/docs/page.mdx @@ -18,7 +18,7 @@ conch is a terminal orchestrator for AI coding agents. A background server owns - **An agent conch does not support in full.** Five are [supported](/docs/agents#supported-agents) — adapter, detection, sessions that list and resume. Others **run here** from a manifest: conch starts and watches them and does not read their saved conversations. If what you need is deep support for a sixth agent, say so rather than assuming the manifest covers it. - **Unattended swarms.** conch waits for Enter on purpose: the [brain](/docs/brain) proposes actions and nothing runs until you confirm, and an agent's question stops the work until somebody answers it. If you want dozens of agents running without a person in the loop, conch is deliberately not that, and will not become it. -The shortest version: **conch is a terminal multiplexer that understands agents and git branches.** Where it is the wrong tool, it is usually because you want fewer agents, a graphical diff, or no human in the loop. How it stands beside herdr, T3 Code and Orca is on [Compared](/docs/compare). +The shortest version: **conch is a terminal multiplexer that understands agents and git branches.** Where it is the wrong tool, it is usually because you want fewer agents, a graphical diff, or no human in the loop. What it does that other tools leave to you is on [Why conch](/docs/why). ## How it fits together diff --git a/web/src/app/docs/why/page.mdx b/web/src/app/docs/why/page.mdx new file mode 100644 index 00000000..983d90b4 --- /dev/null +++ b/web/src/app/docs/why/page.mdx @@ -0,0 +1,41 @@ +export const metadata = { title: "Why conch", description: "What conch does that other agent orchestrators leave to you." } + +# Why conch + +Plenty of tools run coding agents side by side. conch goes further in the places where the work actually stalls: waiting on CI, losing agents to an update, guessing what an agent is doing, and being away from the laptop. + +## It finishes the job without you + +Most tools stop when the agent stops. In conch, a failed check or a failed CI run goes back to the branch's agent with the log, the agent fixes it, and the pull request merges once it is green. The machine's conch server does this, not a window you have to keep open, so it carries on with your laptop shut. Drafts, requested changes, conflicts and open review threads hold a merge back, and nothing is merged unless you turned it on. See [Sending a failure back](/docs/interface#sending-a-failure-back). + +## Updating never stops your agents + +conch reloads its server onto a new build and keeps every terminal open, so an agent halfway through a task does not notice. That is the default, not an experiment, and the TUI picks up the new build by itself. See [Updating without stopping agents](/docs/installation#updating-without-stopping-agents). + +## It hears from the agent, not just its screen + +conch is the terminal, so an agent can tell it what it is doing — working, waiting for permission, done — through the Program Status Protocol (OSC 7501), and conch answers when the agent asks whether anyone is listening. Hooks and the screen come after that, not instead of it. conch then passes one overall state up to the terminal you run it in, so a Ghostty or kitty tab says when an agent waits. See [Agent states](/docs/agents#agent-states). + +## Agents can run agents, and stay in their lane + +An agent can start a reviewer, prompt it, wait for it and read what it said, through the CLI or `conch mcp`, and six bundled skills turn that into a review loop, a team or a factory. An agent calling from its own pane reaches only the panes it started and its own project, so a helper cannot wander into the rest of your work. See [What an agent may do](/docs/agents-together#what-an-agent-may-do). + +## A cloud sandbox is just another machine + +conch creates a sandbox at Daytona, boat.dev, Tensorlake or Devin Cloud, installs itself there, and puts it in the tree beside your own machines — start a task on it, move a worktree to it, stop it when you are done. A provider conch has no code for can be described in a file. See [Sandboxes](/docs/sandboxes). + +## Every conversation, from every agent, in one place + +The Sessions view lists what Claude Code, Codex, Gemini CLI, OpenCode and Devin saved for a project: search them, resume one, delete one, or hand it to a different agent, even on another machine. Runs a crash or a reboot interrupted are remembered and come back with one key. See [Sessions](/docs/sessions). + +## Your phone, without anyone else's server + +Answer a waiting agent from your phone over Tailscale, or through a relay you run yourself. The connection is encrypted end to end, so the relay cannot read it, and there is no account to make. See [Phone](/docs/phone). + +## Built for the terminal, and for ssh + +The TUI is conch, not a fallback for a desktop app, so it works the same from a laptop or over ssh from anywhere. conch installs itself on every machine you add and shows them all in one tree, and the [Mac app](/docs/mac-app) is a window on the same servers rather than a second product. See [Remote machines](/docs/remote-machines). + +## Ask in plain words, approve before anything runs + +Tell the [brain](/docs/brain) what you want — "start Claude on a fix for the login bug" — and it proposes the actions. Nothing runs until you press Enter, with whichever model you choose. See [Brain](/docs/brain). diff --git a/web/src/lib/docs.ts b/web/src/lib/docs.ts index ddbc7485..a188f084 100644 --- a/web/src/lib/docs.ts +++ b/web/src/lib/docs.ts @@ -10,7 +10,7 @@ export const docs: DocSection[] = [ { title: "Introduction", href: "/docs", description: "What conch is and how it is put together." }, { title: "Installation", href: "/docs/installation", description: "Install, update and reload conch." }, { title: "Quick start", href: "/docs/quick-start", description: "From an empty terminal to agents working in parallel." }, - { title: "Compared", href: "/docs/compare", description: "conch beside herdr, T3 Code and Orca." }, + { title: "Why conch", href: "/docs/why", description: "What conch does that other agent orchestrators leave to you." }, ], }, { From 24ccc5986256f3223e6e73906f88e4bf012c262a Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:39:21 -0800 Subject: [PATCH 03/35] =?UTF-8?q?Docs:=20diagrams=20a=20page=20can=20draw?= =?UTF-8?q?=20=E2=80=94=20feature=20cards,=20the=20autopilot=20loop,=20a?= =?UTF-8?q?=20task's=20flow,=20agent=20states?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Built from the site's own type and colours rather than pictures, so they stay sharp, follow the light and dark themes, and need no retaking when the TUI changes. TuiShot puts a captured TUI screen in a docs page, and the landing page's architecture drawing is now available to pages too. Co-Authored-By: Claude Opus 5.5 --- web/src/components/docs-visuals.tsx | 238 ++++++++++++++++++++++++++++ web/src/mdx-components.tsx | 9 ++ 2 files changed, 247 insertions(+) create mode 100644 web/src/components/docs-visuals.tsx diff --git a/web/src/components/docs-visuals.tsx b/web/src/components/docs-visuals.tsx new file mode 100644 index 00000000..3934a8cc --- /dev/null +++ b/web/src/components/docs-visuals.tsx @@ -0,0 +1,238 @@ +import { + BotIcon, + CloudIcon, + CornerDownLeftIcon, + FileDiffIcon, + FolderTreeIcon, + GitBranchIcon, + GlobeIcon, + HistoryIcon, + MessageSquareIcon, + MonitorIcon, + PanelsTopLeftIcon, + RadioIcon, + RefreshCwIcon, + RotateCwIcon, + ShieldCheckIcon, + SmartphoneIcon, + SparklesIcon, + SquareTerminalIcon, + type LucideIcon, +} from "lucide-react" +import Link from "next/link" + +import { TuiScreen, TuiWindow } from "@/components/landing/tui-screen" +import { cn } from "@/lib/utils" + +// The pictures a docs page draws rather than shows: diagrams built from the +// page's own type and colours, so they stay sharp, follow the light and dark +// themes, and say nothing a screenshot would have to be retaken for. + +// Icons by name, since an MDX page cannot import them. +const icons: Record = { + agents: BotIcon, + browser: GlobeIcon, + chat: MessageSquareIcon, + cloud: CloudIcon, + desktop: MonitorIcon, + diff: FileDiffIcon, + files: FolderTreeIcon, + git: GitBranchIcon, + loop: RefreshCwIcon, + phone: SmartphoneIcon, + reload: RotateCwIcon, + scope: ShieldCheckIcon, + sessions: HistoryIcon, + signal: RadioIcon, + sparkles: SparklesIcon, + terminal: SquareTerminalIcon, + workbench: PanelsTopLeftIcon, +} + +function Icon({ name, className }: { name: string; className?: string }) { + const I = icons[name] + if (!I) throw new Error(`no such icon: ${name} (add it to docs-visuals.tsx)`) + return +} + +/** Cards in two columns: `…` */ +export function FeatureGrid({ children }: { children: React.ReactNode }) { + return
{children}
+} + +export function Feature({ + icon, + title, + href, + badge, + children, +}: { + icon: string + title: string + href?: string + badge?: string + children: React.ReactNode +}) { + const body = ( + <> +
+ + + +

{title}

+ {badge && ( + + {badge} + + )} +
+
{children}
+ + ) + const cls = "flex flex-col gap-2.5 rounded-xl border bg-card p-4" + return href ? ( + + {body} + + ) : ( +
{body}
+ ) +} + +type Node = { icon: string; title: string; sub: string; tone?: "brand" | "done" | "waiting" } + +const toneRing = { + brand: "border-brand/30 bg-brand-soft/50 text-brand", + done: "border-done/30 bg-done/10 text-done", + waiting: "border-waiting/30 bg-waiting/10 text-waiting", +} + +function Flow({ nodes, back, label }: { nodes: Node[]; back?: React.ReactNode; label: string }) { + return ( +
+
    + {nodes.map((n, i) => ( +
  1. + + + + {i < nodes.length - 1 && ( + + )} + + {n.title} + {n.sub} + +
  2. + ))} +
+ {back && ( +
+ + {back} +
+ )} +
{label}
+
+ ) +} + +/** The autopilot's loop: an agent's work checked, sent back while red, merged once green. */ +export function AutopilotLoop() { + return ( + + Red? The failed check or the tail of the CI log goes back to the + branch’s agent, which fixes it and finishes again — up to the limit you set, then it is yours. All of it runs + in the machine’s server, so it carries on with every window closed. + + } + /> + ) +} + +/** A task's way from a prompt to a merge. */ +export function TaskFlow() { + return ( + + ) +} + +const states = [ + { glyph: "⠋", name: "working", sub: "busy", cls: "text-working border-working/30 bg-working/10" }, + { glyph: "!", name: "waiting", sub: "needs you", cls: "text-waiting border-waiting/30 bg-waiting/10" }, + { glyph: "✓", name: "done", sub: "finished, unseen", cls: "text-done border-done/30 bg-done/10" }, + { glyph: "○", name: "idle", sub: "wants a prompt", cls: "text-muted-foreground border-border bg-muted/50" }, + { glyph: "✗", name: "failed", sub: "ended in an error", cls: "text-destructive border-destructive/30 bg-destructive/10" }, +] + +const sources = [ + { name: "The agent's own report", sub: "OSC 7501", width: "w-full" }, + { name: "Hooks", sub: "Claude Code and others", width: "w-[82%]" }, + { name: "Screen rules", sub: "the bottom of its screen", width: "w-[64%]" }, + { name: "Foreground process", sub: "is the agent running at all", width: "w-[46%]" }, +] + +/** The five states an agent is shown in, and where conch learns them, most reliable first. */ +export function AgentStates() { + return ( +
+
+ {states.map((s) => ( +
+ + {s.glyph} + + {s.name} + {s.sub} +
+ ))} +
+
+

How conch knows, most reliable first

+ {sources.map((s, i) => ( +
+ {i + 1} + {s.name} + {s.sub} +
+ ))} +
+
+ ) +} + +/** A captured TUI screen in a docs page: `` */ +export function TuiShot({ id, title, caption }: { id: string; title?: string; caption?: string }) { + return ( +
+ {title}}> + + + {caption &&
{caption}
} +
+ ) +} diff --git a/web/src/mdx-components.tsx b/web/src/mdx-components.tsx index 5488f7ad..ad9b9488 100644 --- a/web/src/mdx-components.tsx +++ b/web/src/mdx-components.tsx @@ -4,6 +4,8 @@ import Link from "next/link" import { Callout } from "@/components/callout" import { CodeBlock } from "@/components/code-block" import { Shot } from "@/components/doc-shot" +import { AgentStates, AutopilotLoop, Feature, FeatureGrid, TaskFlow, TuiShot } from "@/components/docs-visuals" +import { Architecture } from "@/components/landing/architecture" import { Step, Steps } from "@/components/steps" import { cn } from "@/lib/utils" @@ -58,6 +60,13 @@ const components: MDXComponents = { Steps, Step, Shot, + Architecture, + FeatureGrid, + Feature, + AutopilotLoop, + TaskFlow, + AgentStates, + TuiShot, } export function useMDXComponents(): MDXComponents { From 1820b3080e2e3033845dd77861ffffcd31504d74 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:39:21 -0800 Subject: [PATCH 04/35] Docs: refresh the introduction and Why conch with the desktop and pictures The introduction opens with the TUI on a project and a What's new grid (Conch.app's workbench, a branch's changes, browser tabs, files and Edit with Agent, the server's autopilot, phones per device), draws how conch fits together and the agent states, lists Devin with the other supported agents, and ends on cards rather than a list. Why conch gets a summary grid, the autopilot's loop, a section on the desktop app with its screenshots, the phone, and the architecture; Tensorlake is left out of it, since making a Tensorlake sandbox is hidden. Tasks draws a task's way from prompt to merge, and Agents the states and how they are known. Tests: every component a docs page uses is registered for MDX, every screenshot and TUI screen it names exists, and these pages carry their pictures. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/docs_test.go | 84 ++++++++++++++++++++++++++++++++ web/src/app/docs/agents/page.mdx | 2 + web/src/app/docs/page.mdx | 57 +++++++++++++++++----- web/src/app/docs/tasks/page.mdx | 2 + web/src/app/docs/why/page.mdx | 46 +++++++++++++++-- 5 files changed, 175 insertions(+), 16 deletions(-) diff --git a/cmd/conch/docs_test.go b/cmd/conch/docs_test.go index 4a212c74..9da192a8 100644 --- a/cmd/conch/docs_test.go +++ b/cmd/conch/docs_test.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "os" "path/filepath" "regexp" @@ -65,3 +66,86 @@ func TestDocsWhyPage(t *testing.T) { t.Error("the introduction should link to /docs/why, not /docs/compare") } } + +// TestDocsComponents: every component a docs page uses is one the MDX map +// gives it, every screenshot it names exists, and every TUI screen it draws +// was captured — otherwise the page fails the website's build, which no Go +// test or CI job here runs. +func TestDocsComponents(t *testing.T) { + mdx, err := os.ReadFile("../../web/src/mdx-components.tsx") + if err != nil { + t.Fatal(err) + } + shots, err := os.ReadFile("../../web/src/components/doc-shot.tsx") + if err != nil { + t.Fatal(err) + } + frames, err := os.ReadFile("../../web/src/components/landing/tui-frames.json") + if err != nil { + t.Fatal(err) + } + var tui struct { + Frames map[string]json.RawMessage `json:"frames"` + } + if err := json.Unmarshal(frames, &tui); err != nil { + t.Fatal(err) + } + registered := map[string]bool{} + body := string(mdx)[strings.Index(string(mdx), "const components"):] + for _, m := range regexp.MustCompile(`(?m)^ ([A-Z]\w*),$`).FindAllStringSubmatch(body, -1) { + registered[m[1]] = true + } + pages, err := filepath.Glob("../../web/src/app/docs/*/page.mdx") + if err != nil { + t.Fatal(err) + } + pages = append(pages, "../../web/src/app/docs/page.mdx") + tag := regexp.MustCompile(`<([A-Z]\w*)[\s/>]`) + shot := regexp.MustCompile(`]*?name="([^"]+)"`) + screen := regexp.MustCompile(`]*?id="([^"]+)"`) + for _, p := range pages { + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + // Code, fenced or inline, may show a that is no component. + src := regexp.MustCompile("(?s)```.*?```|`[^`\n]*`").ReplaceAllString(string(b), "") + for _, m := range tag.FindAllStringSubmatch(src, -1) { + if !registered[m[1]] { + t.Errorf("%s uses <%s>, which mdx-components.tsx does not give it", p, m[1]) + } + } + for _, m := range shot.FindAllStringSubmatch(src, -1) { + if !strings.Contains(string(shots), `"`+m[1]+`":`) { + t.Errorf("%s shows screenshot %q, which doc-shot.tsx does not have", p, m[1]) + } + } + for _, m := range screen.FindAllStringSubmatch(src, -1) { + if _, ok := tui.Frames[m[1]]; !ok { + t.Errorf("%s draws TUI screen %q, which tui-frames.json does not have", p, m[1]) + } + } + } +} + +// TestDocsPictures: the pages people read first carry pictures, not only +// prose — the introduction shows how conch fits together and what is new, +// and Why conch draws the autopilot's loop and shows the desktop app. +func TestDocsPictures(t *testing.T) { + for page, want := range map[string][]string{ + "../../web/src/app/docs/page.mdx": {"", page, w) + } + } + } +} diff --git a/web/src/app/docs/agents/page.mdx b/web/src/app/docs/agents/page.mdx index 6beb198e..faaf9ff3 100644 --- a/web/src/app/docs/agents/page.mdx +++ b/web/src/app/docs/agents/page.mdx @@ -67,6 +67,8 @@ conch never edits an agent's own configuration or answers its trust prompts for ## Agent states + + | State | Meaning | | --- | --- | | `⠋` working | the agent is busy | diff --git a/web/src/app/docs/page.mdx b/web/src/app/docs/page.mdx index d4bfedfd..171fbfbe 100644 --- a/web/src/app/docs/page.mdx +++ b/web/src/app/docs/page.mdx @@ -4,6 +4,35 @@ export const metadata = { title: "Introduction", description: "What conch is and conch is a terminal orchestrator for AI coding agents. A background server owns the terminals your agents run in, so they keep working when you close the UI. + + +## What's new + + + +An agent's whole branch in one tab: its files, a terminal in its checkout, the agent as a chat, and its own terminal, in four layouts. + + +Overview, changes and graph for a branch: commit single hunks, leave the agent a note on a line it answers in a thread, and see the pull request's checks. + + +Your dev server's page in a tab beside the agents, split and moved like any other. + + +A project's files in a tab, each marked by its language, and any of them handed to the agent you pick. + + +Failed CI goes back to the agent, and green pull requests merge, with every window closed. + + +Answer a waiting agent from your phone. Each phone sees only the machines you gave it. + + + ## Is conch for you? **conch is for running several coding agents at once and keeping track of them.** If you have three or four going — on different branches, worktrees or machines — and the hard part is knowing which one is waiting on you, what each has changed, and getting back to it after your laptop slept, that is what this is. It assumes you live in a terminal, that you want work to survive the UI closing, and that you want to answer an agent's question from wherever you are, including [a phone](/docs/phone). @@ -27,6 +56,8 @@ conch has two parts: - **The server.** Each machine runs one conch server. It owns every pane — the pseudo-terminals your agents and shells run in — along with their screens, scrollback and agent states. It starts on its own the first time you run `conch`. - **The TUI.** Running `conch` opens a client that connects to the server. Press `q` to detach: the TUI exits, and the server and everything in it keep running. Run `conch` again to pick up where you left off. + + Because the server owns the panes, you can close your terminal, lose your ssh session or update conch without stopping an agent. The server on a [remote machine](/docs/remote-machines) keeps working when your laptop sleeps, and the TUI connects to every machine at once. The TUI is not the only client. [Conch.app](/docs/mac-app) is one, in a native macOS window; `conch web` is another, serving the same agents to [a phone](/docs/phone), so you can see what each one is doing and answer the question it is waiting on from somewhere else. The phone reaches your laptop directly over your own tailnet, or from any network through a [relay](/docs/phone#through-a-relay) you run yourself, which carries the traffic without being able to read it. Either way nothing goes through a service of conch's: there is no account, and no server of ours between you and your agents. @@ -65,12 +96,7 @@ See [The interface](/docs/interface) for every detail of the tree. ## Agent states at a glance -| State | Meaning | -| --- | --- | -| `⠋` working | the agent is busy | -| `!` waiting | blocked on you: a permission, trust or other question | -| `✓` done | finished while you were looking elsewhere | -| `○` idle | waiting for a prompt | + `!` jumps to the next agent waiting for you, and a desktop notification fires when one you aren't viewing needs you. [Agents](/docs/agents#agent-states) explains how conch decides a state. @@ -80,14 +106,21 @@ See [The interface](/docs/interface) for every detail of the tree. - **Codex** - **Gemini CLI** - **OpenCode** +- **Devin** (preview) + +Others — Aider, Amp, Cursor CLI and more — run from a manifest: conch starts and watches them without reading their saved conversations. conch can install any of them for your user, on any machine, without root. See [Agents](/docs/agents). ## Where to go next -- [Installation](/docs/installation) — install conch and keep it up to date. -- [Quick start](/docs/quick-start) — from an empty terminal to agents working in parallel. -- [Tasks and worktrees](/docs/tasks) — one branch and worktree per task. -- [Remote machines](/docs/remote-machines) — run agents on other machines over ssh. -- [Brain](/docs/brain) — ask for work in plain words and approve the plan. -- [Keys and mouse](/docs/keys) and [Command line](/docs/cli) — the reference. + +Install conch and keep it up to date. +From an empty terminal to agents working in parallel. +One branch and worktree per task. +conch in a native window, with panes drawn by Ghostty. +Run agents on other machines over ssh. +Ask for work in plain words and approve the plan. + + +[Keys and mouse](/docs/keys) and [Command line](/docs/cli) are the reference. diff --git a/web/src/app/docs/tasks/page.mdx b/web/src/app/docs/tasks/page.mdx index 8c370c5f..b4902656 100644 --- a/web/src/app/docs/tasks/page.mdx +++ b/web/src/app/docs/tasks/page.mdx @@ -8,6 +8,8 @@ A task is an agent on its own branch, in its own git worktree, so agents working `t` on a project (or `conch task "PROMPT"`) creates a branch named from the prompt, checks it out into `.worktrees/`, and starts the agent with the prompt — every task isolated from the others. + + The branch goes under the project's own name — a task in **OneNutri** becomes `onenutri/fix-flaky-login-test` — so the branches conch makes are grouped and obvious in a repository other people push to as well. `-branch B`, or the task dialog's Branch field, names it yourself. Tasks use the default agent (Settings → Agents; until you choose one, Claude Code, or an agent the machine has when it has no Claude Code) unless the task dialog's Agent field, or `conch task -agent NAME`, names another. diff --git a/web/src/app/docs/why/page.mdx b/web/src/app/docs/why/page.mdx index 983d90b4..7bc0fdc3 100644 --- a/web/src/app/docs/why/page.mdx +++ b/web/src/app/docs/why/page.mdx @@ -2,12 +2,23 @@ export const metadata = { title: "Why conch", description: "What conch does that # Why conch -Plenty of tools run coding agents side by side. conch goes further in the places where the work actually stalls: waiting on CI, losing agents to an update, guessing what an agent is doing, and being away from the laptop. +Plenty of tools run coding agents side by side. conch goes further where the work actually stalls: waiting on CI, losing agents to an update, guessing what an agent is doing, and being away from the laptop. + + +Failed CI goes back to the agent; green merges. No window open. +A new build, and every terminal still open. +The agent says what it is doing, not a guess from its spinner. +A reviewer, a tester, a team, each kept to its own work. +Conch.app: Ghostty panes, a workbench, a branch's changes. +Answer an agent from anywhere, with no account. + ## It finishes the job without you Most tools stop when the agent stops. In conch, a failed check or a failed CI run goes back to the branch's agent with the log, the agent fixes it, and the pull request merges once it is green. The machine's conch server does this, not a window you have to keep open, so it carries on with your laptop shut. Drafts, requested changes, conflicts and open review threads hold a merge back, and nothing is merged unless you turned it on. See [Sending a failure back](/docs/interface#sending-a-failure-back). + + ## Updating never stops your agents conch reloads its server onto a new build and keeps every terminal open, so an agent halfway through a task does not notice. That is the default, not an experiment, and the TUI picks up the new build by itself. See [Updating without stopping agents](/docs/installation#updating-without-stopping-agents). @@ -16,13 +27,31 @@ conch reloads its server onto a new build and keeps every terminal open, so an a conch is the terminal, so an agent can tell it what it is doing — working, waiting for permission, done — through the Program Status Protocol (OSC 7501), and conch answers when the agent asks whether anyone is listening. Hooks and the screen come after that, not instead of it. conch then passes one overall state up to the terminal you run it in, so a Ghostty or kitty tab says when an agent waits. See [Agent states](/docs/agents#agent-states). + + ## Agents can run agents, and stay in their lane An agent can start a reviewer, prompt it, wait for it and read what it said, through the CLI or `conch mcp`, and six bundled skills turn that into a review loop, a team or a factory. An agent calling from its own pane reaches only the panes it started and its own project, so a helper cannot wander into the rest of your work. See [What an agent may do](/docs/agents-together#what-an-agent-may-do). +## A native desktop on the same servers + +[Conch.app](/docs/mac-app) is a window on the very servers the TUI talks to, not a separate product with its own idea of your agents: close it and nothing stops. Its panes are drawn by Ghostty. Every waiting agent is a card under **Needs you**, answered with a click. A branch opens with its changes, review notes and checks; the **workbench** puts an agent's files, terminal, chat and own terminal in one tab; and your dev server's page sits in a browser tab beside them. + + + + + ## A cloud sandbox is just another machine -conch creates a sandbox at Daytona, boat.dev, Tensorlake or Devin Cloud, installs itself there, and puts it in the tree beside your own machines — start a task on it, move a worktree to it, stop it when you are done. A provider conch has no code for can be described in a file. See [Sandboxes](/docs/sandboxes). +conch creates a sandbox at Daytona, boat.dev or Devin Cloud, installs itself there, and puts it in the tree beside your own machines — start a task on it, move a worktree to it, stop it when you are done. A provider conch has no code for can be described in a file. See [Sandboxes](/docs/sandboxes). ## Every conversation, from every agent, in one place @@ -30,11 +59,20 @@ The Sessions view lists what Claude Code, Codex, Gemini CLI, OpenCode and Devin ## Your phone, without anyone else's server -Answer a waiting agent from your phone over Tailscale, or through a relay you run yourself. The connection is encrypted end to end, so the relay cannot read it, and there is no account to make. See [Phone](/docs/phone). +Answer a waiting agent from your phone over Tailscale, or through a relay you run yourself. The connection is encrypted end to end, so the relay cannot read it, there is no account to make, and each phone sees only the machines you gave it. See [Phone](/docs/phone). + + ## Built for the terminal, and for ssh -The TUI is conch, not a fallback for a desktop app, so it works the same from a laptop or over ssh from anywhere. conch installs itself on every machine you add and shows them all in one tree, and the [Mac app](/docs/mac-app) is a window on the same servers rather than a second product. See [Remote machines](/docs/remote-machines). +The TUI is conch, not a fallback for a desktop app, so it works the same from a laptop or over ssh from anywhere. conch installs itself on every machine you add and shows them all in one tree. See [Remote machines](/docs/remote-machines). + + ## Ask in plain words, approve before anything runs From 7fdcb03659cfaeda60c175d9387e5557fb19e8e3 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:51:38 -0800 Subject: [PATCH 05/35] =?UTF-8?q?Docs:=20keep=20the=20guide=20pages=20shor?= =?UTF-8?q?t=20=E2=80=94=20a=20feature,=20how=20to=20use=20it,=20a=20pictu?= =?UTF-8?q?re?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guides had grown to 88k words (the interface page alone 16k, the Mac app 14k) and went unread; people look at the pictures and a line. Each guide page is now a picture, one heading per feature, a sentence or two on what it does and how to use it — key, command or menu — and a link to the reference for the rest. The reference pages (keys, command line, configuration, protocol) stay whole, since they are looked things up in. Headings other pages link to were kept; three links that pointed at headings no longer there (interface#workspaces, sessions#sharing-with- another-agent, agents#two-tiers) now land. Tensorlake is one line, as making one is hidden; Conch Cloud is not promoted. Tests: each guide stays under 700 words of prose with no paragraph over 60, and every link to a docs page — from a page, the sidebar or the site's components — reaches a page and heading that are there. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/docs_test.go | 124 +++++ web/src/app/docs/agents-together/page.mdx | 292 ++---------- web/src/app/docs/agents/page.mdx | 158 ++----- web/src/app/docs/brain/page.mdx | 145 ++---- web/src/app/docs/installation/page.mdx | 121 +---- web/src/app/docs/interface/page.mdx | 547 +++------------------- web/src/app/docs/mac-app/page.mdx | 254 ++++------ web/src/app/docs/page.mdx | 62 +-- web/src/app/docs/phone/page.mdx | 196 ++------ web/src/app/docs/quick-start/page.mdx | 60 +-- web/src/app/docs/remote-machines/page.mdx | 150 ++---- web/src/app/docs/sandboxes/page.mdx | 220 +++------ web/src/app/docs/sessions/page.mdx | 57 ++- web/src/app/docs/tasks/page.mdx | 312 +++--------- web/src/app/docs/why/page.mdx | 27 +- 15 files changed, 674 insertions(+), 2051 deletions(-) diff --git a/cmd/conch/docs_test.go b/cmd/conch/docs_test.go index 9da192a8..7b49364e 100644 --- a/cmd/conch/docs_test.go +++ b/cmd/conch/docs_test.go @@ -2,11 +2,13 @@ package main import ( "encoding/json" + "io/fs" "os" "path/filepath" "regexp" "strings" "testing" + "unicode" ) // TestDocsSidebarPages: every page the docs sidebar lists has a page.mdx, @@ -149,3 +151,125 @@ func TestDocsPictures(t *testing.T) { } } } + +// guides are the docs pages people read through rather than look things +// up in. They are kept short — what a feature is and how to use it, in a +// few lines beside a picture — because the long versions went unread. The +// reference pages (keys, command line, configuration, protocol) are tables +// to look things up in and are left out. +var guides = []string{ + "page.mdx", "installation/page.mdx", "quick-start/page.mdx", "why/page.mdx", + "interface/page.mdx", "tasks/page.mdx", "agents/page.mdx", "agents-together/page.mdx", + "sessions/page.mdx", "remote-machines/page.mdx", "sandboxes/page.mdx", + "mac-app/page.mdx", "phone/page.mdx", "brain/page.mdx", +} + +const ( + guideMaxWords = 700 // a page's prose, outside code and components + guideMaxParagraph = 60 // one paragraph, or one list item +) + +// prose is what a reader reads on a page: no code blocks, no components, +// no metadata, no link targets. +func prose(page string) string { + page = regexp.MustCompile("(?s)```.*?```").ReplaceAllString(page, "") + page = regexp.MustCompile(`(?s)]*>`).ReplaceAllString(page, "") + page = regexp.MustCompile(`(?m)^export const metadata.*$`).ReplaceAllString(page, "") + page = regexp.MustCompile(`\]\([^)]*\)`).ReplaceAllString(page, "]") + return page +} + +// TestDocsGuidesAreShort: every guide page stays within its budget, so a +// page is a feature, a line on how to use it, and a picture. +func TestDocsGuidesAreShort(t *testing.T) { + for _, g := range guides { + b, err := os.ReadFile("../../web/src/app/docs/" + g) + if err != nil { + t.Fatal(err) + } + p := prose(string(b)) + if n := len(strings.Fields(p)); n > guideMaxWords { + t.Errorf("%s: %d words of prose, keep it under %d", g, n, guideMaxWords) + } + for _, para := range regexp.MustCompile(`\n\s*\n|\n- |\n\d+\. `).Split(p, -1) { + if strings.HasPrefix(strings.TrimSpace(para), "|") { + continue // a table's rows are counted in the page's total + } + if n := len(strings.Fields(para)); n > guideMaxParagraph { + t.Errorf("%s: a paragraph of %d words, keep each under %d: %.80s…", g, n, guideMaxParagraph, strings.TrimSpace(para)) + } + } + } +} + +// slug is the id rehype-slug gives a heading: lower case, punctuation +// dropped, spaces as hyphens. +func slug(h string) string { + h = strings.ToLower(strings.NewReplacer("`", "", "*", "").Replace(h)) + var b strings.Builder + for _, r := range h { + switch { + case r == ' ': + b.WriteRune('-') + case r == '-' || r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r): + b.WriteRune(r) + } + } + return b.String() +} + +// TestDocsLinksResolve: every link to a docs page, from a page or from the +// website's components, reaches a page that is there and, with #, a +// heading on it — shortening a page must not leave links into what it cut. +func TestDocsLinksResolve(t *testing.T) { + anchors := map[string]map[string]bool{} + pages, _ := filepath.Glob("../../web/src/app/docs/*/page.mdx") + pages = append(pages, "../../web/src/app/docs/page.mdx") + heading := regexp.MustCompile(`(?m)^#{1,4} (.+)$`) + for _, p := range pages { + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + route := "/docs/" + strings.TrimSuffix(strings.TrimPrefix(filepath.ToSlash(p), "../../web/src/app/docs/"), "page.mdx") + route = strings.TrimSuffix(route, "/") + set := map[string]bool{} + src := regexp.MustCompile("(?s)```.*?```").ReplaceAllString(string(b), "") + for _, m := range heading.FindAllStringSubmatch(src, -1) { + set[slug(strings.TrimSpace(m[1]))] = true + } + anchors[route] = set + } + link := regexp.MustCompile(`(?:\]\(|href[=:] ?")(/docs[^)"#\s]*)(?:#([^)"\s]+))?`) + var sources []string + sources = append(sources, pages...) + _ = filepath.WalkDir("../../web/src/components", func(path string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(path, ".tsx") { + sources = append(sources, path) + } + return nil + }) + sources = append(sources, "../../web/src/lib/docs.ts") + checked := 0 + for _, s := range sources { + b, err := os.ReadFile(s) + if err != nil { + t.Fatal(err) + } + for _, m := range link.FindAllStringSubmatch(string(b), -1) { + checked++ + route := strings.TrimSuffix(m[1], "/") + set, ok := anchors[route] + if !ok { + t.Errorf("%s links to %s, which is no docs page", s, m[1]) + continue + } + if m[2] != "" && !set[m[2]] { + t.Errorf("%s links to %s#%s, which has no such heading", s, route, m[2]) + } + } + } + if checked == 0 { + t.Fatal("no docs links found — the regexp or the pages moved") + } +} diff --git a/web/src/app/docs/agents-together/page.mdx b/web/src/app/docs/agents-together/page.mdx index fa7fbd82..2a226766 100644 --- a/web/src/app/docs/agents-together/page.mdx +++ b/web/src/app/docs/agents-together/page.mdx @@ -2,330 +2,120 @@ export const metadata = { title: "Agents working together", description: "Let on # Agents working together -An agent in a conch pane can start another agent, prompt it, wait for it and read its answer — a reviewer for its change, a tester, a second opinion — without you passing messages between them. Each helper runs in a pane of its own, on its own branch, and shows in the tree like any other agent, so you can watch it, answer it or close it at any time. +How an agent in conch starts other agents — a reviewer, a tester, a second opinion — prompts them, waits and reads their answers, each helper in its own pane and branch. + + + Start a helper on its own branch, prompt it, wait, read its answer. + One task tried by several agents, or split into parts. + Review, fix, review again until clean. + Tests, push, pull request, CI, merge when asked. + Set up a project's automated workflow. + A ticket all the way to a merged pull request. + ## Setting it up -The agents learn how from skills conch carries. Install them once on each machine: +The agents learn how from six skills conch carries. Install them once per machine. ```sh -conch agent skill # says where it would write, and writes nothing +conch agent skill # shows where it would write conch agent skill -apply # writes them ``` -There are six, installed together: - -| Skill | What it teaches the agent | -| --- | --- | -| `conch` | start a helper agent on a branch of its own, prompt it, wait for it and read its answer — the rest build on this | -| `conch-team` | several agents at once: one task tried by two or three to keep the best, a task split into parts that run side by side, or a chain where each starts from the last one's branch | -| `conch-review` | another agent reviews a branch and comments on its lines, the author fixes or answers each comment, and the reviewer looks again — until it is clean, or three rounds and it asks you | -| `conch-ship` | the project's tests, a commit, a push, the pull request, CI watched and a failure sent back to the branch's agent, and a merge once it is green — only when you asked for one | -| `conch-autopilot` | set up the automated workflow for a project: it finds the project's check and runs it once, proposes the `[verify]` policy (the check, a reviewer, failures sent back, pull requests opened, merging left off until you trust it), guardrails and a worktree's setup, applies only what you agree to, and shows the ways to feed it work | -| `conch-factory` | a ticket all the way: read it (a GitHub issue, or your tracker through the agent's own tools), one agent builds it test-first, another reviews, the builder fixes, review again, a tester tries it, then the pull request, CI and the merge | - -Or without leaving the TUI. `i` on a project, branch or pane says under **conch** whether the agent whose tab is open has the skill on that machine, and `S` installs it or takes it away. For every agent at once: `,` → **Agents** → **conch's skills…** lists every machine and how it stands there — *every agent has it*, *1 have it · 1 not* (an agent counts once it has all five), or the reason it could not be asked — and opening a machine names each skill for each agent and what would happen to it. **Install it for every agent…** and **Take conch's copy away…** name every path in a question before anything is written, the way the command plans before `-apply`. A machine at a time, through that machine's own server. - -In Claude Code they are also a plugin, from the conch repository itself: +Or `i` on a pane then `S`, or `,` → **Agents** → **conch's skills…**. In the Mac app: **Settings → Skills & MCP servers**. In Claude Code they are also a plugin (pick one way, not both): ``` /plugin marketplace add Amitgb14/conch /plugin install conch@conch ``` -Its skills are named `conch:conch-factory` and so on. Pick one way for Claude Code — the plugin, or `conch agent skill` — or it reads each skill twice. The plugin installs the same files conch does, and they act only inside a conch pane. - -In the Mac app it is **Settings → Skills & MCP servers**, or **Skills & MCP servers…** on a machine's right-click menu. - -They go where each agent reads your skills — `~/.claude/skills/conch`, `~/.claude/skills/conch-factory` and so on for Claude Code, `~/.agents/skills/…` for Codex, Gemini CLI and OpenCode, and `~/.config/devin/skills/…` for Devin — beside your own skills, replacing none of them: a skill of yours under one of those names is left alone, and the others still install. `conch skill NAME` prints one (`conch skill -list` names them), for an agent conch can't install it for. `-skill conch,conch-review` installs only those skills, `-agent claude,codex` installs them for some agents only, `-remove -apply` takes it away again, and `conch -m MACHINE agent skill -apply` installs it on another machine. Claude Code picks it up at once, even mid-session; restart the others if they don't list it. - ## Asking an agent for a second opinion -In a project, start an agent (`c`) and ask in plain words: - -> Get a second opinion on the change on this branch from another agent, and tell me what it found. - -What happens, as it did in a real run with Claude Code: +Start an agent (`c`) and ask in plain words. It starts a helper as a task on its own branch, waits, reads what it wrote and tells you. If the helper asks a question, the agent tells you which pane is waiting. -1. The agent sees it is in conch and loads the skill. -2. It starts a helper as a task — `conch task -name login-reviewer "…"` — which appears under the project in the tree, on a branch and worktree of its own. -3. Its change wasn't committed, so rather than commit your work to hand it over, it put the diff in the helper's prompt. -4. It waits for the helper, then reads the `REVIEW.md` the helper wrote in its worktree. -5. It tells you what the reviewer found, and closes the reviewer's pane. The reviewer's branch and worktree stay for you to keep or [clean up](/docs/tasks#cleaning-up-worktrees). - -If the helper stops to ask something — a permission, a question — the agent doesn't answer for it: it tells you which pane is waiting. Open that pane and answer it yourself. - -Other things to ask for the same way: *"have Codex write tests for this and run them"*, *"ask another agent to try the migration on a copy of the branch"*, *"get Claude and Gemini to each review it and compare"*. +**How:** _"Get a second opinion on the change on this branch from another agent, and tell me what it found."_ ## A team, a review loop, a factory -The other skills are asked for the same way, in plain words, or in Claude Code by name as a command: - -> Have Claude and Codex each try the parser fix, and tell me which one to keep. *(conch-team)* - -> Get this branch reviewed by Codex and have the fixes made until the review is clean. *(conch-review)* - -> Open the pull request for this branch and merge it once CI is green. *(conch-ship)* +Ask for the other skills the same way, or by name as a command in Claude Code. -> Take issue 123 from build to a merged pull request. *(conch-factory, or `/conch-factory 123` in Claude Code)* - -> Set up an automated workflow for this project. *(conch-autopilot)* - -The factory runs the whole line with the agent you asked as its foreman, each stage an agent in a pane of its own: - -``` -ticket → spec → build → review → fix → review → test → pull request → CI → merge → retro -``` +| Ask | Skill | +| --- | --- | +| _"Have Claude and Codex each try the parser fix, and tell me which one to keep."_ | conch-team | +| _"Get this branch reviewed by Codex and have the fixes made until the review is clean."_ | conch-review | +| _"Open the pull request for this branch and merge it once CI is green."_ | conch-ship | +| _"Take issue 123 from build to a merged pull request."_ | conch-factory (`/conch-factory 123`) | +| _"Set up an automated workflow for this project."_ | conch-autopilot | -It first writes the ticket down as a short spec — the goal, acceptance criteria a test or a reviewer can check, and what is out of scope — and agrees it with you; a vague ticket gets questions, one at a time, until it is whole. Builders work test-first against the spec, a slice at a time, and the reviewer checks fidelity to it before anything else. At the end a short retro says what slowed the line — review rounds, CI failures, questions a permission rule would have answered — and proposes changes for you to make. It tells you the plan first — which ticket, which agent builds, which reviews, and whether it will merge — and stops the line rather than guessing: a ticket too vague to build comes back with questions, a review still open after three rounds or CI still red after three fixes comes back to you, and an agent waiting on a question is yours to answer. It merges only when you asked it to. With conch's autopilot on (`auto_pr`, `auto_merge` under `[verify]` in [config.toml](/docs/configuration)), the pull request and the merge are conch's, and the factory waits for them rather than racing it. For a backlog it queues the tickets, at most two builders at a time (`conch task -queue -wip 2 -issue N`). + -Every stage is an agent spending your usage, so ask for the size of team you want. +Every stage is an agent spending your usage, so ask for the team size you want. ## Who started what -A pane an agent started carries the pane it came from, so the tree reads as a chain of work rather than a list of strangers. It is **listed under** the agent that started it: +A pane an agent started is listed under it, and the agent shows **⑂2** (amber **⑂2!** when one waits). ``` Agents ▾ claude ⑂2 ↳ reviewer ↳ tester - codex ``` -Fold the agent and its helpers go with it. The agent that started them carries **⑂2**, which turns amber as **⑂2!** when one of them is waiting on a question. A helper that cannot sit under its agent — it is in another section, on another machine, or a search has narrowed the agent away — says **↳ for claude** on its own row instead. The review queue (`Q`), the jump to whoever needs you (`!`) and desktop notifications all name the same thing — *waiting for an answer for claude* — so the three read as one. - -A pane nobody started says nothing either way, and a creator that has gone leaves its helpers unclaimed rather than naming a pane that is not there. - ### Claude's own subagents -Claude Code can also hand work to **subagents** of its own — its Agent tool, background tasks — which run inside the same `claude` process and have no terminal. conch lists them under the agent too, from the hooks Claude reports when one starts and stops, each with the task it was given and its kind: - -``` -Agents - ▾ claude - ⠋ Writing gateway e2e tests general-purpose - ⠋ Running race tests Explore -``` - -A subagent is listed only while it runs, and goes when it finishes or the session ends. It has no screen of its own, so selecting it shows the agent running it, and `enter` opens that agent — where Claude itself shows what its subagents are doing. There is nothing to type into, close or rename. Agents other than Claude Code report no subagents, and a remote machine lists them once its conch is updated. +Claude Code's own subagents are listed under it too, with their task and kind, while they run. `enter` opens the agent running them. ## From the tree -`m` on an agent's pane — or a right-click — has **Prompt…**: type the message, and it goes in as that agent's next one. conch then watches the work it started and says when it ends: *finished what you asked*, *is waiting for you*, or *ended before it answered*, in the status bar, or as a desktop notification when that pane is not the one you are looking at. You are told once. - -An agent that is already waiting on a question of its own is not sent anything — the menu says so before you open it, and the server refuses it in its own words if it starts waiting in between. A machine whose server predates `agent.prompt.v1` says that instead of offering it. - -## A long-running job - -A build that takes most of an hour needs a little more care than a review, because an agent's shell tool isn't made for it: Claude Code's stops a command after 2 minutes by default, and an agent that moves a long command into the background ends its turn early — so "done" would come long before the build is. The way round it is to run the build in a **terminal pane** of its own, which has no time limit and outlives the agent's turns, and to have it leave a file saying it finished. - -Start an agent in the project and ask: - -> Hand the full build of this project to a helper agent and tell me how it went. -> -> Start the helper with `conch task -name builder`. Tell it to: -> - build the entire package with `make all`, in its own worktree; -> - the build takes about 40 minutes — too long for its shell tool — so run it in a conch terminal pane: -> `conch new -name build-run -cwd -- sh -c 'make all > build.log 2>&1; echo $? > build.exit'` -> - then check every couple of minutes whether `build.exit` exists, running each check in the foreground, never in the background; -> - if the build fails, fix the cause, run it again the same way, and repeat — at most 3 attempts; -> - at the end write `BUILD.md`: pass or fail, the exit code, how long it took, the first error if any, and what it changed; -> - close `build-run` when done. Don't commit, push or merge anything. -> -> Then wait for the helper with `conch agent prompt -wait -timeout 2h` or `conch wait`, and when it stops, read `BUILD.md` from its worktree. If `BUILD.md` isn't there yet, it's still going — wait again rather than report. -> -> If the helper, or anything it runs, asks for a permission or a decision, stop and tell me which pane is waiting — don't answer for it. - -Put your own build command and time in place of `make all` and 40 minutes. Three panes appear under the project — the agent you asked, `builder` on a branch of its own, and `build-run`, the terminal the build scrolls in — and you can open any of them while it runs: - -```text -you ──▶ your agent (p1) - │ conch task -name builder "…" - ▼ - builder (p2, its own branch and worktree) - │ conch new -name build-run -- sh -c 'make all > build.log …' - ▼ - build-run (p3, a terminal) ── writes build.log and build.exit - ▲ - └─ builder checks build.exit, fixes, runs again, writes BUILD.md -your agent ◀── reads BUILD.md and tells you -``` - -Why each instruction is there: - -| Instruction | Why | -| --- | --- | -| the build in a terminal pane | no time limit, and it outlives the helper's turns | -| `echo $? > build.exit` | a file that says it finished, and how — surer than reading a scrolling screen | -| checks in the foreground | keeps the helper's turn open while it waits, so its end means the job's end | -| `BUILD.md` | the result is read from a file, not guessed from a screen | -| at most 3 attempts | a build it can't fix doesn't spend your usage for ever | -| no commit, push or merge | that is yours to decide; the branch stays for you | -| stop when it asks | a question is yours to answer; `conch agent prompt` won't type onto it anyway | - -Without an agent in between, start the builder from a terminal pane and wait for it yourself: - -```sh -conch task -name builder "Build the entire package with make all … (the instructions above)" -conch wait -state done,waiting -timeout 2h builder -cat "$(conch status | awk '$2 == "builder" { print $7 }')/BUILD.md" -``` +`m` on an agent's pane → **Prompt…** sends it a message, and conch tells you once when that work ends. ## Giving helpers files that aren't committed -A helper works in a fresh worktree, which holds what is committed on its branch — so a design plan you keep out of git, a spec you haven't committed, or notes in `.gitignore` aren't there. Two ways to hand them over: - -- **Let conch copy them in.** When it makes a worktree, conch copies files from the project's main checkout that git ignores and that match the project's [local files](/docs/tasks#local-files-in-worktrees) — `.env` and a few others by default. Add a pattern for yours, keeping the defaults, since the list replaces them: - - ```sh - conch project ls # the project's ID - conch project files ID .env '.env.*' .envrc .claude/settings.local.json CLAUDE.local.md \ - .mcp.json AGENTS.override.md .gemini/.env 'docs/plans/*.md' - ``` - - Every task from then on starts with those files in its worktree — copied, never committed, so never pushed. The files must be in the **main checkout**, and git must ignore them there (`.gitignore`, or `.git/info/exclude` to keep even the names private). -- **Or give the path.** Name the file's absolute path in the helper's prompt — *"build against `~/src/app/docs/plans/api.md`"* — and it reads it from there. Every worktree is on the same disk. - -Don't commit a private file, or force-add an ignored one, just to hand it over: it would then be in the branch's history for anyone who fetches it. The skill tells agents the same, and to ask you to add a pattern rather than change the project's local files themselves. +A helper's worktree holds only committed files. Add a [local files](/docs/tasks#local-files-in-worktrees) pattern so conch copies yours in, or name the file's absolute path in the prompt. ## Doing it yourself -The commands the agents use are plain `conch` commands, so a script — or you, in a terminal pane — can drive agents the same way: +The agents use plain `conch` commands, so a script can too: ```sh -# A reviewer on its own branch, starting from yours (commit first: it sees only commits). conch task -name reviewer -agent codex -base "$(git branch --show-current)" \ - "Review this branch against main. Run commands in the foreground. Write findings to REVIEW.md." - -# Wait for its first answer. + "Review this branch against main. Write findings to REVIEW.md." conch wait -state done,waiting -timeout 30m reviewer - -# A follow-up: typed in, submitted, and waited for in one step. -conch agent prompt -wait -timeout 30m reviewer "Now check the error handling in login.py too." -case $? in - 0) echo "finished" ;; - 3) echo "it is asking something:"; conch read reviewer ;; - 124) echo "still working after 30 minutes" ;; -esac - -conch read reviewer # its screen -conch close reviewer # its branch and worktree stay +conch agent prompt -wait -timeout 30m reviewer "Now check the error handling too." +conch read reviewer +conch close reviewer ``` -`conch agent prompt` is the safe way to message an agent. It types only into an agent, never into one waiting for an answer — a permission prompt, a trust question or a menu, where its Enter would answer something nobody read — and with `-wait` it waits for the work that message starts, not for the state the agent was in before it. It exits: - -| Exit | Meaning | -| --- | --- | -| `0` | the agent's turn ended | -| `3` | the agent is waiting for an answer; nothing was typed | -| `124` | `-timeout` ran out; it may still be working | -| `1` | anything else: the pane ended, another program took it over, a name two panes share | - -`conch send` still types anything anywhere — for your terminals, not for agents. - -`conch wait` sees an agent `done` only while nobody is looking at it: finished in front of you, it goes straight to `idle`. Wait for `-state done,waiting` in scripts that run unwatched. - -### Names - -`-name reviewer` on `conch task`, or `conch rename ID NAME` on any pane, lets every pane command address it by name: `send`, `read`, `close`, `redraw`, `wait`, `agent prompt`, `agent explain`. An ID (`p` and a number) always means the ID, so names of that shape are refused, and a name two running panes share is refused rather than guessed. See [pane names](/docs/cli#pane-names). +`conch agent prompt` exits `0` when the turn ended, `3` when the agent waits for an answer (nothing typed), `124` on timeout. See [pane names](/docs/cli#pane-names). ## Through MCP instead of the command line -An agent that would rather call a tool than run a command can reach the same work through `conch mcp`, an MCP server over stdin and stdout: +`conch mcp` offers the same work as MCP tools: `list`, `read`, `start`, `prompt`, `wait`, `task`, `rename`. -```sh -conch agent library mcp # conch's own tools, as a server in the library -conch agent library apply # write it into each agent's configuration -``` - -Or in the TUI: `,` → **Agents** → **Shared MCP servers & skills…** → **Add conch's own tools…**, then **Apply…**. Restart an agent afterwards for its client to list the tools. - -The [library](/docs/tasks#shared-mcp-servers-and-skills) writes it into each agent's own configuration, so this is one action rather than five formats. Its tools are `list`, `read`, `start`, `prompt`, `wait`, `task` and `rename` — the same server calls the commands above make, so neither door tells the agent something the other wouldn't. A tool call comes back as a typed result and a refusal written for the agent to act on: a prompt onto an open question says to read the screen and answer it, and a wait that runs out says it timed out rather than failing. - -`list` says which subagents are running inside each agent too (the ones above), so an agent waiting on a helper can see it is busy without reading its screen. - -The skill above teaches the commands. An agent that has both should use whichever its client makes easier; nothing goes wrong if it mixes them, since both reach one server. +**How:** `conch agent library mcp`, then `conch agent library apply`, and restart the agent. ### Three reviewers at once -Where the tools earn their keep is a job with several helpers in it. One agent reviewing `auth.py`, another `billing.py`, a third the tests — three agents, three branches, three worktrees — driven by a lead agent that never runs a shell command: +A lead agent can run several reviewers through the tools without a shell command: ```jsonc task {"prompt":"review auth.py", "branch":"review-auth", "agent":"claude", "name":"auth"} -→ p2: claude started on branch review-auth in /src/api.worktrees/review-auth. - Wait for it (the wait tool) before prompting it: conch has to see the agent start - task {"prompt":"review billing.py", "branch":"review-billing", "agent":"codex", "name":"billing"} -task {"prompt":"review the tests", "branch":"review-tests", "agent":"gemini", "name":"tests"} - wait {"pane":"auth", "state":["idle","waiting"], "timeout_seconds":1800} -→ p2: claude is idle - prompt {"pane":"auth", "text":"Write what you found to FINDINGS.md, worst first."} read {"pane":"auth", "tail":20} -→ …what it said ``` -Four things that are harder from a shell, and why each matters: - -- **Nothing is parsed.** `list` answers with data — `{"pane":"p3","name":"billing","agent":"codex","agent_state":"idle","branch":"review-billing"}` — where `conch status` answers with a table whose columns move when a name gets longer. With three helpers to keep track of, a mis-split prompts the wrong agent. -- **Three kinds of agent, one interface.** `agent` is just a name; how each is launched, resumed and detected is conch's business. Reviewers that disagree usefully are the point of fanning out. -- **The order comes from the tool.** Each `task` says to wait before prompting, because conch has to *see* an agent start before it can be messaged. Without that, a prompt sent in the same breath is refused — and an agent that then reaches for `conch send` types into whatever is on screen, which may be a trust question nobody read. -- **It stops at the boundary.** Every pane above is the lead's own. Reach outside and the answer is `out_of_scope: … it did not start it, and it is in another project`, which an agent can repeat to you instead of working around. - -For one helper and one question, `conch task` and `conch wait` in a terminal are two lines and need none of this. The tools pay off when there are several helpers, several kinds of agent, or a client where every shell command needs your approval and a tool can be allowed once. - ## What an agent may do -An agent calling conch from inside its pane may start panes and tasks and read anything. What it may **change** is kept to its own work: - -| It may change | It may not | -| --- | --- | -| panes it started, and the panes those started | other panes in other projects: typing, keys, closing, renaming, marking as seen | -| any pane in its own project | another project's branches and worktrees | -| its own project's branches and worktrees: commit, push, discard | `conch server stop` or `reload` | -| | your own setup: the skill, the [library](/docs/tasks#shared-mcp-servers-and-skills), syncing one agent's setup to the others, and which [local files](/docs/tasks#local-files-in-worktrees) a project copies into its worktrees — even in its own project | - -The rest is refused, and the agent is told why: +An agent may start panes and tasks and read anything, but change only its own work: panes it started, panes in its project, and that project's branches. Anything else is refused with `out_of_scope` and a reason. The TUI and your own terminals are never limited. -```text -conch: out_of_scope: the claude agent in p1 may not close p4: it did not start it, and it is in another project; do it from the TUI or a terminal pane -``` - -You are never held to this: the TUI, your terminal panes and scripts run outside conch act as you. conch tells who is asking from the operating system — the process at the other end of its socket and that process's parents, up to a pane — so an agent can't get round it by changing its environment. It is a guard against an agent closing the wrong session, not a sandbox: a program set on escaping can leave its pane's process tree. - -### What an agent may start - -An agent may start other agents, and choose which one and its model — `conch new -agent codex -- --model gpt-5`, or the MCP `start` tool's `--model NAME`. It may not choose anything else about what runs: no command of its own (a plain terminal is fine), no environment, and no other flags. Otherwise an agent that asks you before each command could start a helper told to ask nobody — `--dangerously-skip-permissions`, `--yolo` — or a pane running whatever it liked, and one tool call would step around every prompt you rely on. That is what an injected instruction in a README or an issue would try first. - -```text -conch: out_of_scope: the claude agent in p1 may not start an agent with "--dangerously-skip-permissions": an agent may choose which agent to start and its --model, nothing else ([agents] unrestricted_launch in config.toml allows more); do it from the TUI or a terminal pane -``` - -If you want agents to start agents however they like — workers in bypass mode, a launcher of your own — set it in `config.toml` (or Settings → Agents): +Agents may pick which agent to start and its `--model`, nothing more. To allow more: ```toml [agents] unrestricted_launch = true ``` -An agent can't set this through conch: changing your setup is out of its scope. Like the rest, it holds for agents going through conch; one that runs `claude` in its own shell isn't held by it, and is held by whatever that shell asks you instead. - -### On another machine - -`conch -m MACHINE` from an agent's pane carries the agent's scope along: on the other machine it reaches only the panes it started there, and the projects it started them in. - -```text -conch: out_of_scope: the claude agent in p1 on laptop.local may not close p1: it did not start it; do it from the TUI or a terminal pane -``` - -A machine whose conch predates this isn't driven from an agent's pane at all — `conch machine upgrade` it. Like the rest, this holds for agents going through conch: one that runs `ssh` itself isn't held by it. - -## Good to know - -- **A helper sees only committed work.** It starts on a branch of its own. With your work committed, pass your branch as `-base`; if it isn't, the skill has the agent put the diff in the helper's prompt instead of committing for you. -- **Files a helper needs that aren't committed** — a spec, a plan, notes kept out of git — don't reach its worktree on their own. See [giving helpers files that aren't committed](#giving-helpers-files-that-arent-committed). -- **Exit 0 is the end of a turn, not always of the work.** A helper that puts a long command in the background ends its turn and takes the work up again later; a request that failed (an expired API key, say) ends a turn too. Ask helpers to run commands in the foreground, and check the result — the file you asked for — before relying on it. -- **Codex and Devin are read from their screen.** conch can't see a failed request there: it ends like a finished one. Claude Code, Gemini CLI and OpenCode report it through their hooks. -- **Every helper spends usage.** The skill tells agents to start only as many as the job needs. +`conch -m MACHINE` from an agent's pane keeps the same limits on the other machine. diff --git a/web/src/app/docs/agents/page.mdx b/web/src/app/docs/agents/page.mdx index faaf9ff3..02ab9402 100644 --- a/web/src/app/docs/agents/page.mdx +++ b/web/src/app/docs/agents/page.mdx @@ -1,63 +1,48 @@ -export const metadata = { title: "Agents", description: "Supported agents, their states, usage and plan limits." } +export const metadata = { title: "Agents", description: "Supported agents, their states, broadcast, usage and plan limits." } # Agents -conch runs Claude Code, Codex, Gemini CLI, OpenCode and Devin in panes it owns, tracks what each is doing, and shows their token usage and plan limits. It wires in its state tracking without touching the agents' own configuration. +conch runs Claude Code, Codex, Gemini CLI, OpenCode and Devin in panes it owns, tracks what each is doing, and shows their usage and plan limits. -## Two tiers, said plainly + -conch supports five agents and **runs** more. The difference is a promise, not a ranking: +## Supported agents + +| Agent | Install (no root) | +| --- | --- | +| **Claude Code** | `curl -fsSL https://claude.ai/install.sh \| bash` | +| **Codex** | `curl -fsSL https://chatgpt.com/codex/install.sh \| sh` | +| **Gemini CLI** | `npm install -g --prefix ~/.local @google/gemini-cli` (Node 20+) | +| **OpenCode** | `curl -fsSL https://opencode.ai/install \| bash` | +| **Devin** (preview) | `curl -fsSL https://cli.devin.ai/install.sh \| bash`, then `devin auth login` | + +Devin is Cognition's `devin` CLI. A Devin pane that needs an answer looks idle. -- **Supported** — an adapter written for it, detection rules taken from the real agent, and its saved conversations listed, resumed and deleted in the Sessions view. Claude Code, Codex, Gemini CLI, OpenCode and Devin. -- **Runs here** — described by a manifest: conch starts it, recognises it in a pane, and gives it a first message or resumes it **only where that agent documents how**. Its saved conversations are *not* read, and conch says so — in the agent menu ("runs here · no sessions") and in the Sessions view — rather than showing an empty list that reads as "you have not used it". +## Two tiers -**Pi is the one that needs no rules at all**: it reports its own state through [OSC 7501](#how-the-state-is-decided), so its row in the tree says what pi says — working, waiting, done — where another second-tier agent can only be shown as idle until conch is taught its screen. Any agent that adopts the protocol gets the same, including one you add yourself. +- **Supported** — the five above, with their saved conversations in the [Sessions](/docs/sessions) view. +- **Runs here** — described by a manifest: conch starts and recognises it, but does not read its sessions. -The second tier exists because the wider catalogs *detect* twenty agents while conch *supports* five, and writing fifteen more to the supported bar stalls on session formats nobody has written down. Running an agent is easy; pretending to read its sessions is a lie. +conch ships manifests for **Aider**, **Amp**, **Cursor CLI**, **Grok**, **Kilo Code** and **Pi**, marked with a square rather than a circle. -conch ships manifests for **Aider**, **Amp**, **Cursor CLI**, **Grok**, **Kilo Code** and **Pi**, each saying in its own file what was verified from that agent's documentation and what was not — these are other people's flags, and they change. Add your own with: +**How:** add your own, then reload the server. ```sh conch agent add robo -command robo -label "Robo Coder" \ -prompt '--message {prompt}' -resume '--resume {id}' -resume-last --continue ``` -That writes `~/.config/conch/agents/robo.toml`, which you can then edit by hand; reload the server to pick it up. Leave `-prompt` out and conch will not try to give it a first message; leave `-resume` out and it will not offer to resume one. Add an `install` line to its `[run]` table for an installer conch can offer; without one the agent menu says conch has none rather than running nothing and calling it installed. A manifest cannot take a supported agent's name — that would replace a tested adapter with a guess. - -An agent conch runs from a manifest is marked in the tree like any other — a square rather than a circle (see [the sidebar](/docs/interface#the-sidebar)), and 🤖 for one conch has no mark of its own for. - -| Agent | Tier | First message | Resume | -| --- | --- | --- | --- | -| **Aider** | runs here | no — `--message` answers and exits | the folder's own history (`--restore-chat-history`) | -| **Amp** | runs here | no — only piped stdin | by thread (`amp threads continue T-…`) | -| **Cursor CLI** | runs here | yes, as an argument | `--resume ID`, `--continue` | -| **Grok** | runs here | not verified for its TUI | `--resume ID`, `--continue` | -| **Kilo Code** | runs here | no — `kilo run` answers and exits | the most recent here (`--continue`) | -| **Pi** | runs here | yes, as an argument (`--print` is the one that answers and exits) | `--session ID`, `--continue` | - -## Supported agents - -| Agent | Launch | How conch knows its state | Install (no root) | -| --- | --- | --- | --- | -| **Claude Code** | `claude --settings ` | hooks, screen, token usage from the transcript | `curl -fsSL https://claude.ai/install.sh \| bash` | -| **Codex** | `codex` | terminal title (`[ ! ] Action Required`, spinner) and screen ("Would you like to run the following command?") | `curl -fsSL https://chatgpt.com/codex/install.sh \| sh` | -| **Gemini CLI** | `gemini` with conch's hooks in a system-defaults settings file (merged with yours; Gemini runs hooks only in trusted folders) | hooks when trusted, title (`✋ Action Required`, `✦ Working…`, `◇ Ready`) and screen | `npm install -g --prefix ~/.local @google/gemini-cli` (Node 20+) | -| **OpenCode** | `opencode` with conch's plugin via `OPENCODE_CONFIG_CONTENT` (merged with your config) | plugin events (busy, idle, permission, question) and screen | `curl -fsSL https://opencode.ai/install \| bash` | -| **Devin** (preview) | `devin`; a task's first message after `--`, resume with `-r ID` or `-c` | screen (`esc twice to interrupt`, the placeholder "Guide Devin while it works", and the trust prompt); a question it asks mid-task is not separable from idle | `curl -fsSL https://cli.devin.ai/install.sh \| bash`, then `devin auth login` | - -Devin for Terminal is Cognition's `devin` CLI, not the Devin desktop app. conch starts, resumes and installs it like the other agents, and lists it in `c`. Its instructions, skills and MCP servers show in the setup view (`i`) and take part in [sync and the library](/docs/tasks#one-setup-every-agent); since it reads Claude Code's files by itself, it is only given what it would not otherwise see. - -conch reads **working** from its screen, so the tree shows the spinner while it thinks or edits, and it catches the trust prompt Devin shows on its first run in a directory. It cannot show **waiting** the rest of the time: Devin asks for permission in prose in the conversation — "This will permanently delete the file. Should I proceed?" — leaving the input placeholder and status bar exactly as they are when it is idle, and its terminal title is only the session's first prompt. So a Devin pane that needs an answer looks idle, and `!` will not jump to it. Hooks would fix that; conch only adds them once it's confirmed that passing `--config` leaves your own Devin settings intact. +That writes `~/.config/conch/agents/robo.toml`. ## Starting agents -`c` (or clicking **c agent** in the status bar, or **Start an agent…** in the right-click menu) asks which agent to start at the selected place — a machine, project, branch or pane. Every agent installed there is listed first, in the machine's own order, with what would have to be installed after it; the default (Settings → Agents) is pre-selected, so `c` `enter` starts it. The first ten rows that do something take a digit — `1`–`9` and then `0`, as the tab keys do — so the agents you are choosing between keep the numbers even when a dozen are listed. Missing agents can be installed from the same list; `A` starts or installs any agent. - -Opening the menu asks the machine again which agents are there, so one you installed since conch started — by hand, or with `brew`, `npm` or its own installer — is offered as a **start** rather than an install; if the answer arrives while the menu is open, the menu redraws. An agent whose manifest named no installer is listed as "not installed · conch has no installer for it" and cannot be chosen: install it yourself and conch will find it on your PATH. - -In the [Mac app](/docs/mac-app), starting an agent — a new agent, or a task — on a machine that does not have it installs it first: a new Conch Cloud machine has none. The status bar says *Installing Claude Code on bot…* while the installer runs in a terminal of its own (in the sidebar, to watch), and the agent starts once the machine finds it. When the installer fails its terminal opens with what it said; a server too old to install agents is said rather than tried. +`c` asks which agent to start at the selected row; `c` `enter` starts the default (Settings → Agents). Missing agents can be installed from the same list; `A` starts or installs any agent. -`t` [tasks](/docs/tasks) use the default agent unless the task dialog's Agent field (or `conch task -agent NAME`) names another. From a shell, `conch new -agent claude -cwd DIR` starts Claude Code with state tracking, and `conch agent status` / `conch agent install NAME` check or install agents (add `-m MACHINE` for a remote machine). +**From a shell:** `conch new -agent claude -cwd DIR`, `conch agent status`, `conch agent install NAME` (add `-m MACHINE` for a remote machine). @@ -75,100 +60,47 @@ conch never edits an agent's own configuration or answers its trust prompts for | `!` waiting | blocked on you: a permission, trust or other question | | `✓` done | finished while you were looking elsewhere | | `○` idle | waiting for a prompt | -| `✗` failed | its last request ended with an error instead of an answer (Claude Code and OpenCode report this), e.g. an expired provider login; cleared by the next prompt | +| `✗` failed | its last request ended with an error; cleared by the next prompt | -A desktop notification fires when an agent you aren't viewing needs you (see [notification settings](/docs/interface#notifications)). `!` in the tree, or `ctrl+b !` in a pane, jumps to the next agent waiting for you. +**How:** `!` in the tree, or `ctrl+b !` in a pane, jumps to the next agent waiting for you. ### How the state is decided Most reliable first: -1. **The program's own report ([OSC 7501](https://mitchellh.com/writing/program-status-osc7501)).** An agent that speaks the Program Status Protocol says what it is doing on the terminal it already has — `idle`, `working`, `done`, `blocked` (with `permission`, `question` or `auth`), `error` — and conch takes that over its own screen rules, because the program is not guessing. A program asks first whether the terminal speaks it, and conch answers; one that gets no answer stays quiet, so this works in conch and not in a terminal that has not implemented it. It travels down the pty, so it works over ssh and inside a container, where a hook or a socket would not. **Claude Code 2.1.295 and later emit it**, and so do a growing number of others. A blocked report outranks everything; otherwise hooks still come first for the agents that have them, since a hook also carries the message, whether the work failed and which session it belongs to. -2. **Hooks.** Claude panes started by conch get `--settings ~/.config/conch/claude-settings.json`, adding hooks that call `conch report claude-hook`. Your own settings files are untouched and their hooks still run. conch writes that file — and Gemini's defaults and OpenCode's plugin beside it — when its server starts *and* before every launch, so clearing `~/.config` does not leave an agent failing with *Settings file not found*; the folder is made again if it has gone. -3. **Screen rules.** Regexes over the bottom of the screen (tolerant of line wrapping), e.g. "Do you want to proceed?" with its numbered choices under it → waiting; the question alone (typed, logged or quoted) is not. Also covers `claude` started by hand. Override `internal/detect/manifests/claude.toml` by copying it to `~/.config/conch/agents/claude.toml`. -4. **Foreground process.** A pane is only an agent while the agent is the terminal's foreground process. +1. **The program's own report** ([OSC 7501](https://mitchellh.com/writing/program-status-osc7501)), from Claude Code 2.1.295 and later. +2. **Hooks**, added with `--settings`; yours still run. +3. **Screen rules** over the bottom of the screen. +4. **Foreground process**: a pane is an agent only while the agent is in front. -A report decides a pane's *state*, never whether it holds an agent: that still comes from the manifest and the foreground process, so a build tool reporting `working` in a terminal stays a terminal. - -`conch agent explain p1` shows the evidence behind a state. +**How:** `conch agent explain p1` shows the evidence behind a state. ### conch reports its own state too -conch reads OSC 7501 because it is the terminal its agents run in. It is -also a program on *your* terminal, with the same thing to say, so it emits -one report of its own: `blocked` while any agent is waiting on you, -`error` when one has failed, otherwise `working`, `done` or `idle`, with a -line naming the agent when there is one of it (`claude on feat waiting`) -and counting them when there are more. A terminal that understands the -protocol can then put that on the tab or the window — **which is the one -state you cannot see for yourself, because seeing it means looking at -conch.** It counts every agent conch knows of, not only the -[workspace](/docs/interface#workspaces) on screen, since the terminal's tab -is outside workspaces and an agent waiting in one you switched away from is -exactly the one that is out of sight. conch takes the report away when it -quits, so no tab is left saying an agent waits after the conch that said so -has gone. - -Unlike an agent, conch does not ask the terminal whether it speaks the -protocol first. The answer would arrive on conch's own stdin, where the TUI -reads keys and would take `ESC ] 7 5 0 1 ;` for an escape followed by the -digits `7`, `5`, `0`, `1` — digits that switch tabs. Writing without -listening is the safe half: never asking means nothing ever arrives to be -misread. A terminal without support throws an unknown `OSC` away, and these -are written only when something changes, so the cost of telling one that is -not listening is a few bytes a minute. It is off inside tmux and screen, -which own the window the report would reach, and `CONCH_STATUS=0` turns it -off anywhere (`1` turns it on, tmux included). +conch sends one OSC 7501 report to your terminal — `blocked` while any agent waits on you — for the terminal's tab to show. + +**How:** it is off inside tmux and screen; `CONCH_STATUS=0` turns it off anywhere, `1` turns it on. ## Agents working together -An agent can start another — a reviewer for its change, a tester — prompt it and read its answer, kept to its own work while it does. See [Agents working together](/docs/agents-together). +An agent can start and prompt another. See [Agents working together](/docs/agents-together). ## Broadcast -`B` types one message into several panes at once and submits it. The [brain](/docs/brain#one-message-to-several-agents) can propose the same thing from a plain request, such as _"tell every agent in api to run the tests"_. An agent gets it as its next message — "run the tests and fix anything you broke" to every agent in a project — and a terminal runs it as a command — `git pull` in every checkout. - -What is listed follows the selection in the tree, grouped the same way (project or CLI, then Agents and Terminals): - -| Selected | Listed | -| --- | --- | -| a machine | its agents and terminals, by project and CLI | -| `Workspace` | the agents and terminals of every project on the machine | -| a project (or its Branches, Sessions) | the project's agents and terminals, in all its worktrees | -| a branch | the agents and terminals on that branch | -| `CLI` | the machine's agents and terminals outside projects | -| an `Agents` section, or an agent | that group's agents | -| a `Terminals` section, or a terminal | that group's terminals | - -What starts ticked: +`B` types one message into several panes and submits it: a prompt to every agent in a project, or `git pull` in every terminal. The list follows the tree's selection; agents waiting for an answer, and terminals in a mixed list, start unticked. -- **Agents** — all of them, except agents **waiting for an answer**: the message would answer their question. You can tick them; the confirmation says so. -- **Terminals** — ticked when you selected a Terminals section or a terminal. In a mixed list they start unticked, since a prompt meant for agents would run as a command; `t` ticks them all. - -In the dialog, type the message, then `tab` to the list: `space` ticks or unticks, `a` ticks all, `t` all terminals, `e` widens to every machine. `enter` shows the recipients and how many terminals will run it as a command, and asks to confirm; `n` goes back with the message kept. - -Panes on other machines receive it through their own servers. A server from an older build is skipped and named (older servers can broadcast to agents but not terminals). +**How:** type the message, `tab` to the list, then `space` ticks, `a` ticks all, `t` all terminals, `e` every machine. `enter` asks to confirm; `n` goes back. ## Token usage -Agent panes show token usage in their title — `ctx 45k/200k · out 12k · $0.42`: - -- **ctx** — how much of the model's context window the conversation fills right now (the input of the latest request), out of the window's size when the agent reports it. When it nears the size, the agent compacts or forgets. -- **out** — output tokens the agent has generated in this session so far. -- **$** — the session's cost, only when the agent reports one. +Agent panes show usage in their title: `ctx 45k/200k · out 12k · $0.42`. -conch reads these from each agent's own session data and never estimates prices: - -| Agent | Usage from | Cost | -| --- | --- | --- | -| Claude Code | the transcript the hooks point at | when the transcript records it | -| Codex | the session's rollout file (found by folder and start time) | — | -| OpenCode | its session database (via `sqlite3`) | yes | - -A machine's page totals the usage of its running agents. +**ctx** is the context window used now, **out** the output tokens this session, **$** the cost when the agent reports one. ## Plan limits -For Claude subscriptions the status bar shows the current windows, e.g. `Claude 5h 42% · 7d 18%` (amber from 70%, red from 90%); click it for reset times. The machine page draws them as bars with when each window resets. When a window passes 80% and again at 95%, conch alerts once (see [notification settings](/docs/configuration#notify)). + + +For Claude subscriptions the status bar shows the current windows, e.g. `Claude 5h 42% · 7d 18%`, amber from 70% and red from 90%. Codex's windows come from its session files; API-key logins have none. -Claude shares these only with its status line, so conch adds a status line command to its `--settings` that records them and then runs your own status line unchanged. Codex's windows are read from its session files when its login has them. API-key logins have no plan windows. +**How:** click it for reset times. conch alerts once at 80% and again at 95% (see [notify](/docs/configuration#notify)). diff --git a/web/src/app/docs/brain/page.mdx b/web/src/app/docs/brain/page.mdx index fcc5320f..aed44511 100644 --- a/web/src/app/docs/brain/page.mdx +++ b/web/src/app/docs/brain/page.mdx @@ -2,78 +2,37 @@ export const metadata = { title: "Brain", description: "Ask for work in plain wo # Brain -The brain turns a request in plain words into a plan of conch actions — start tasks, message agents, answer questions — and summarises what agents are doing. It uses your own agent login or API key. +How to ask conch for work in plain words, approve the plan it proposes, and get summaries of what agents are doing. ## Asking -Press `:` (or click **✦ Ask**) and say what you want: +Say what you want; the brain turns it into a plan of conch actions — start tasks, message agents, hand work over — using your own agent login or API key. -- _"start 3 agents on api: fix the flaky login test, add rate limiting, update the README"_ — split into tasks, each on its own branch and worktree with a self-contained prompt -- _"tell the agent on fix-login to also cover the logout path"_ — a message typed into that agent -- _"hand the auth thread to Codex"_ — the Claude conversation in that pane is written to a handoff file and Codex is started on it, [as `s` does in Sessions](/docs/sessions#sharing-with-another-agent) -- _"tell every agent in api to run the tests"_ — one message to several agents at once, [as `B` does in the tree](/docs/agents#broadcast) -- _"what is waiting for me?"_ — an answer, no actions +**How:** press `:` (or click **✦ Ask**), or `conch ask [-y | -n] [-model] "…"` from a shell. -Under the request the window says what it applies to (the row selected in the tree), how many agents are waiting, working or done, and which model would plan it. Below that are things worth asking now — _"what is waiting for me?"_ while an agent waits, _"show claude"_ for each one waiting, _"tell claude to …"_ for the agent selected, _"tell everyone to …"_, _"start an agent here to …"_ — and the last few requests you made. Each says whether conch answers it at once or the model plans it, and typing narrows the list. +- _"start 3 agents on api: fix the flaky login test, add rate limiting, update the README"_ +- _"tell the agent on fix-login to also cover the logout path"_ +- _"what is waiting for me?"_ -| Key | | -| --- | --- | -| `↑` `↓` | choose an option | -| `enter`, a click | ask it; one ending in _…_ is put in the box for you to finish | -| `tab` | fill the box from the option chosen, or the first | -| `ctrl+p` `ctrl+n` | earlier and later requests, as in a shell | -| `esc` | close | - -Once something is typed, the line above the keys says what `enter` will cost: _conch answers it at once, no model_, or which model plans it. - -From a shell, `conch ask [-y | -n] [-model] "…"` does the same: `-y` runs the plan without asking, `-n` only shows it, `-model` always asks the model. In [Conch.app](/docs/mac-app), **✦ Ask** in the status bar offers the same list, for the pane in front. +`↑` `↓` choose a suggestion, `enter` asks, `tab` fills the box, `ctrl+p` `ctrl+n` recall earlier requests, `esc` closes. ## Without the model -Some requests mean only one thing, and conch plans them at once, without a model call. That works even when no provider is set up: +Requests that mean only one thing are planned at once, with no model call — even with no provider set up. | Request | Plan | | --- | --- | -| _"show codex"_, _"go to fix-login"_ | Show that pane | +| _"show codex"_ | Show that pane | | _"close the zsh terminal"_ | Close it | -| _"tell codex to run the tests"_ | Send _Run the tests_ to that agent | -| _"tell everyone to commit"_ | Broadcast to every agent, one action per machine | -| _"what is waiting?"_, _"what's working?"_ | An answer listing those agents, no actions | - -A pane is named by its name, its branch, its agent or its id. The plan says _answered without the model_; press `m` to send the same request to the model instead. - -conch does this only when exactly one reading is possible. Anything else goes to the model: +| _"tell codex to run the tests"_ | Send _Run the tests_ | +| _"tell everyone to commit"_ | Broadcast to every agent | +| _"what is waiting?"_ | List those agents | -- a name that matches two panes, or matches a project or a machine -- a shell named as the one to tell -- a message about the agent rather than to it, such as _"tell codex to check its tests"_, since the model can rewrite that - -`no_fast_path = true` under `[brain]` sends every request to the model. +**How:** press `m` on the plan to send it to the model instead. ## Approving the plan -The brain sees every connected machine, its projects, branches and agents (with their states and summaries) and proposes a plan. Each action is listed with a checkbox; invalid ones (an unknown project, an agent that isn't installed, an offline machine) are marked and skipped. - -It can propose these actions: - -| Action | What it does | -| --- | --- | -| Start a task | a new branch and worktree with an agent working on a prompt | -| Start an agent | an agent in a project or branch you already have | -| Send | a message typed into one running agent and submitted | -| Share | hand one agent's conversation to another, new or already running | -| Broadcast | one message to several agents on a machine at once | -| Show, Close | focus a pane, or close it (only when you ask) | - -A broadcast and a share only ever reach agents: a terminal would run the text as a shell command, so conch skips it and says so. Sharing needs the agent to have saved a conversation; until it has, the action is refused rather than starting an agent with nothing to read. - -## Handing work to another agent - -Say who should take over, and from where: - -- _"hand the auth thread to Codex"_ -- _"let Gemini continue what Claude is doing on fix-login"_ -- _"give the drag-and-drop thread to the Codex that is already running"_ +Each proposed action has a checkbox; invalid ones are marked and skipped. ```text ✦ Plan @@ -81,82 +40,48 @@ Say who should take over, and from where: enter run · space tick · esc cancel ``` -On enter, conch writes that agent's conversation to a handoff file in the checkout and starts the other agent on it with a prompt to read it and continue — the same handoff as `s` in [Sessions](/docs/sessions#sharing-with-another-agent). Name an agent that is already running and the conversation goes to it instead of starting a pane. +**Nothing runs until you press enter.** -## One message to several agents - -- _"tell every agent in api to run the tests before committing"_ -- _"ask both agents on conch to stop and summarise what they changed"_ - -```text -✦ Plan - 1. Send to 2 agents on this computer (fix login, codex): run the tests before committing -``` +## Handing work to another agent -Each agent receives it once, submitted as its next message, like [`B` in the tree](/docs/agents#broadcast). Agents on several machines take one action per machine, each confirmed on its own. +Say who should take over. conch writes the conversation to a handoff file and starts the other agent on it, or gives it to one already running — the same as `s` in [Sessions](/docs/sessions). -## Finding what needs you +**How:** _"hand the auth thread to Codex"_, _"let Gemini continue what Claude is doing on fix-login"_. -`/` then `!` keeps only the agents waiting for an answer, on every machine, without asking the model anything: +## One message to several agents -```text -/ ! agents waiting for you -▾ ● local ⠋1 ⚑3 - ▾ ◆ api ⠋1 ⚑2 - ▾ Agents 3 - ! claude feat - ✓ gemini done -``` +Each agent gets the message once, as its next one — like `B` in the tree ([Agents](/docs/agents)). -`esc` clears it; `!` on its own jumps to the next waiting agent instead of filtering. +**How:** _"tell every agent in api to run the tests before committing"_. - +## Finding what needs you -**Nothing runs until you press enter.** +`/` then `!` keeps only the agents waiting for an answer, on every machine. `!` alone jumps to the next one; `esc` clears. - + ## Summaries -`S` on an agent asks for a one-line summary — what it is doing and what it needs from you — shown in its title bar and on the project page, and given to the planner. - -Settings → Brain → _Summarise agents_ does this on its own whenever an agent finishes or starts waiting. - - +`S` on an agent asks for a one-line summary of what it is doing and what it needs from you, shown in its title bar. -Each automatic summary is a small model request, and the agent's visible screen is sent to the provider. +**How:** `S`, or Settings → Brain → _Summarise agents_ to do it whenever an agent finishes or starts waiting. Each summary is a small model request that sends the agent's screen to the provider. - - -## Providers - -Choose a provider in Settings → Brain, or with `[brain]` in config.toml: +## Configuration -| Provider | Uses | Default models | -| --- | --- | --- | -| `claude` _(default)_ | the Claude Code CLI headless (`claude -p`, no tools, MCP servers, settings or session history) with your existing Claude login | sonnet · haiku for summaries | -| `anthropic` | the API with `$ANTHROPIC_API_KEY` | claude-sonnet-5 · claude-haiku-4-5 | -| `openai` | any OpenAI-compatible endpoint: `base_url = "http://localhost:11434/v1"` for Ollama | set `model` | +Choose a provider in Settings → Brain, or in `config.toml`: -## Configuration +| Provider | Uses | +| --- | --- | +| `claude` _(default)_ | the Claude Code CLI with your Claude login | +| `anthropic` | the API with `$ANTHROPIC_API_KEY` | +| `openai` | any OpenAI-compatible endpoint, such as Ollama | ```toml [brain] provider = "claude" model = "" # provider default -summary_model = "" # a small, fast model by default +summary_model = "" summaries = false # automatic summaries ``` -Four more keys are optional: - -| Key | Effect | -| --- | --- | -| `base_url` | overrides the API endpoint (`anthropic`, `openai`) | -| `api_key_env` | names the environment variable holding the API key (default `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`) | -| `command` | the `claude` binary for the `claude` provider; empty finds it on `PATH` | -| `no_fast_path` | `true` sends every request to the model, even those [conch plans alone](#without-the-model) | - -## New providers - -New providers implement `brain.Provider` (`Complete` with an optional JSON schema for structured output). +Other keys (`base_url`, `api_key_env`, `command`, `no_fast_path`) are on [Configuration](/docs/configuration). diff --git a/web/src/app/docs/installation/page.mdx b/web/src/app/docs/installation/page.mdx index 7d2cb742..46450bf2 100644 --- a/web/src/app/docs/installation/page.mdx +++ b/web/src/app/docs/installation/page.mdx @@ -2,26 +2,23 @@ export const metadata = { title: "Installation", description: "Install, update a # Installation -conch is a single binary for macOS and Linux. Install it with a script, with Homebrew, with Go, or from source, and update it later without stopping your agents. +conch is a single binary for macOS and Linux; install it one of four ways and update it without stopping your agents. -This page is the binary — the TUI, the server and every `conch` command, which is what a remote machine runs too. **[Conch.app](/docs/mac-app)**, conch in a native macOS window, is a separate download with the server inside it: see [installing the beta](/docs/mac-app#installing-the-beta). +[Conch.app](/docs/mac-app), conch in a native macOS window, is a separate download: see [Mac app](/docs/mac-app). ## Install script -macOS and Linux (amd64 and arm64): +Installs `~/.local/bin/conch` and adds conch to your desktop's applications (`CONCH_APP=no` skips that). ```sh curl -fsSL https://raw.githubusercontent.com/Amitgb14/conch/master/install.sh | sh ``` -This downloads the latest release, checks it against the release checksums and installs `~/.local/bin/conch`. It then puts conch in your desktop's applications with its own icon, so it can be clicked as well as typed — a `conch.desktop` entry on Linux, a `conch.app` in `~/Applications` on macOS — and says which files it wrote. That step is [`conch app install`](/docs/cli#app), run with the binary it has just installed, so it is also the first time that binary runs; `CONCH_APP=no` skips it. A machine with none of the terminals conch can open — every server you only ssh into — says so and is installed just the same. - -A version as an argument installs that release instead — including an older -one, to go back to it: +Add a version to install that release, including an older one: ```sh curl -fsSL https://raw.githubusercontent.com/Amitgb14/conch/master/install.sh | sh -s -- 0.2.0 @@ -29,46 +26,24 @@ curl -fsSL https://raw.githubusercontent.com/Amitgb14/conch/master/install.sh | | Variable | Effect | | --- | --- | -| `CONCH_VERSION=0.2.0` | install that release instead of the latest (the argument wins) | +| `CONCH_VERSION=0.2.0` | install that release | | `CONCH_INSTALL_DIR` | install into another directory | -| `CONCH_RELEASE_URL` | download releases from a mirror instead of GitHub | -| `CONCH_APP=no` | don't add conch to the desktop's applications | - -Later, `conch update` replaces the binary with the newest release — the same -download, without the script. +| `CONCH_RELEASE_URL` | download from a mirror | +| `CONCH_APP=no` | don't add conch to the applications | -If the folder isn't on your `PATH` yet, the script prints the line that puts -it there for your shell — `~/.zshrc` for zsh, the default on macOS — and the -first command to run. - -Then `conch doctor` checks everything conch leans on — git, gh, an agent to -run, the terminal — and says how to fix whatever is missing. See -[doctor](/docs/cli#doctor). +Then run `conch doctor` to check what conch needs. See [doctor](/docs/cli#doctor). ## With Homebrew -macOS and Linux: +Includes tab completion. Update with `brew upgrade conch`, then press **u** in the version box to reload. ```sh brew install Amitgb14/conch/conch ``` -This installs the same release archives from the `Amitgb14/conch` tap, with -tab completion for bash, zsh and fish. Homebrew then owns the binary, so update it with Homebrew rather than `conch update`: - -```sh -brew upgrade conch -``` - -conch notices the new build, as it does a rebuild: press **u** in the version -box, or run `conch server reload`, and the server moves onto it with your -agents still running. `conch update` and its `rollback` refuse a Homebrew -install and say so, since replacing the file under Homebrew would leave it -believing in a version that is no longer there. - ## With Go -With Go 1.25 or newer: +Needs Go 1.25 or newer. ```sh go install github.com/Amitgb14/conch/cmd/conch@latest @@ -77,95 +52,35 @@ go install github.com/Amitgb14/conch/cmd/conch@latest ## From source ```sh -make build # bin/conch -make test # go test -race ./... -make release VERSION=0.2.0 # dist/: archives for every platform + checksums.txt +make build ``` -Pushing a `v*` tag runs the release workflow, which builds the same archives and publishes them as a GitHub release. - ## Shell completion -Installed any way but Homebrew, turn on tab completion for your shell: +For any install but Homebrew. See [completion](/docs/cli#completion). ```sh -echo 'eval "$(conch completion zsh)"' >> ~/.zshrc # zsh, after compinit -echo 'eval "$(conch completion bash)"' >> ~/.bashrc # bash -conch completion fish > ~/.config/fish/completions/conch.fish +echo 'eval "$(conch completion zsh)"' >> ~/.zshrc ``` -In a new terminal, `conch ` lists the commands with what each does, and -`conch read ` the panes running now. See [completion](/docs/cli#completion). - ## Updating without stopping agents -The server owns every pane, so a new build takes effect in the server only once it restarts — and a restart would stop the agents. Instead, **reload**: +Reload the server onto the new build; every pane keeps running. ```sh conch server reload # or click the version in the status bar, then r ``` -The server execs the new binary in place. It keeps its process ID, so the programs in its panes stay its children; their terminals and the listening socket stay open across the exec; screens, scrollback, terminal modes and agent states are handed over in a state file. Agents never notice — output they write meanwhile waits in the kernel — and the TUI reconnects on its own. Whatever you type into a pane in that moment is held and sent once the pane is back; keys held for more than 15 seconds, or for a pane that didn't survive, are dropped, and the status bar says so. - -When the server is older than the TUI, its version shows amber in the status bar. The machine menu has **Reload server** too; a remote machine reloads onto the build `machine upgrade` installed. - - - -They need one last `conch server stop`, which stops the server and every pane it owns. - - - ## Auto-update -conch notices newer builds on its own: - -- its executable rebuilt or replaced (`make build`, `conch update`); -- a newer GitHub release (checked once a day for release builds; `[update] check_releases = false` turns it off); -- machines running an older build. - -The version in the status bar then shows `⬆`; click it for the list and press **u** to update everything: - -1. download the release, if there is one, over the conch executable; -2. reload the local server onto it (panes keep running); -3. restart the TUI in place onto the new build; -4. install the build on each ticked remote machine and reload its server. +When a newer build or release is out, the version in the status bar shows `⬆`. Click it and press **u** to update conch, its server, the TUI and your remote machines. -Remote machines behind your build are listed with checkboxes, all ticked. To update only some, move with `↑` `↓` and press `space` (or click a row) to untick the ones to leave alone; `a` ticks or unticks them all. The box then reads **u update 1 of 2 machines**. Unticked machines stay on their build, also after the TUI restarts; a machine that was offline when you pressed `u` is updated when it connects. - -Step 3 is why the screen redraws: a running program cannot replace its own code, so the TUI execs the new binary in its place — same terminal, same process. Nothing you are running stops: the server keeps every pane, agent and terminal, the new TUI reattaches to them, and your tabs and folds come back. It stays on the alternate screen across the swap, so your shell never shows through. - -`conch update` does steps 1–2 from a shell, and `conch machine upgrade ID` installs and reloads one machine. - -With `[update] auto = true` in [config.toml](/docs/configuration#update), that -daily check installs the release it finds on its own — steps 1–4, without -pressing **u** — and the status bar says so while it runs. It needs -`check_releases`; it is off by default, so the default stays: conch tells you, -you decide. - -On a Homebrew install the version box lists the release with -`brew upgrade conch` beside it, and neither **u** nor `auto` downloads it: -after `brew upgrade`, **u** reloads onto the new build. +`[update] auto = true` in [config.toml](/docs/configuration#update) installs releases on its own. ## Going back to an older version -Every update keeps the binary it replaces (the newest three) in -`$CONCH_HOME/versions` and notes the version it left, so going back is a file -copy, not a download: - ```sh -conch update list # every release published upstream, newest first +conch update list # every release, newest first conch update rollback # back to the version before the last update -conch update 0.2.0 # or straight to a version you name +conch update 0.2.0 # or a version you name ``` - -`conch update list` marks the running version with `*`, the one -`conch update` would install, and the versions kept locally. Going back notes -the version it leaves in turn, so a second `conch update rollback` comes -forward again. - -A version conch never had a copy of is downloaded from its release, exactly -as an update is — so a version that was only ever a local build (`make -build`) can be gone back to only while its kept copy is there. The local -server is reloaded onto the older binary too, so panes keep running; remote -machines follow when you press **u** in the version box or run -`conch machine upgrade ID`. diff --git a/web/src/app/docs/interface/page.mdx b/web/src/app/docs/interface/page.mdx index 1aacae4a..fa0d57a5 100644 --- a/web/src/app/docs/interface/page.mdx +++ b/web/src/app/docs/interface/page.mdx @@ -1,572 +1,151 @@ -export const metadata = { title: "The interface", description: "The tree, splits and tabs, scrollback and settings." } +export const metadata = { title: "The interface", description: "The tree, splits and tabs, the review queue, files and settings." } # The interface -The TUI shows a tree of machines, projects, branches, agents and terminals beside a main area with tabs and splits. This page covers each part and the settings that shape it. +The TUI shows a tree of machines, projects, branches, agents and terminals beside tabs and splits; this page covers each part. -## The sidebar - -```text -MACHINES -▾ ● local ⠋1 ⚑1 - ▾ ▤ Workspace 2 - ▾ ◆ api ⠋1 ⚑1 - ▾ Branches 7 - ● main +1 checked out in the repo, uncommitted lines - ◇ conch/add-health-check ⠋ ↑3 own worktree, agent working, 3 ahead of main - · feat/login #12✓ ↑2 not checked out, pull request with passing checks - … 18 more - ▾ Agents 2 - ⠋ Add health check conch/add-health-check - ! Fix flaky tests fix/flaky - ▾ Terminals 1 - › dev-server main - ▸ ◆ web - ▾ ❯ CLI 2 - ▾ Terminals 1 - › zsh - ▾ SSH 3 - ▾ prod 2 - › ssh dev@build-box - ○ prod db saved - ○ ssh staging-1 saved -``` - -The badges on a machine or project count its agents: `⠋1` working, `⚑1` waiting for an answer from you, `✓1` done — finished while nobody was looking; it turns idle once you open or type into it. The status bar adds them up across every machine (`⚑ 1 waiting · 1 done`), and clicking that, like `!`, goes to the next one. Beside it is the ID of the pane you are in or on — `p12`, or `busybox:p12` on another machine — which is what `conch read`, `send` and `wait` take; a click copies it, and so does **Copy pane ID** in a pane's menu, whose title says it too. It is the first thing the bar lets go of when it is short of room. Each split's border ends with its pane's ID too — `╭─ claude · working ──── p12 ─╮` — and a click on it copies it; on a narrow split the ID gives way to the title. - -Each machine has two groups. `Workspace` holds its projects (folders you added with `a`); selecting it shows every project with what runs in it, and the tab bar lists the tabs of all of them. `CLI` holds a machine's agents and terminals that belong to no project. `n` or `c` on the machine (or on `CLI`) starts one there, in your home folder. - -Where you start conch counts. Run it in a project's folder (or anywhere in it, or in one of its worktrees) and the tree opens on that project, so `c` starts an agent there. Run it in a git repository that isn't a project yet and conch asks whether to add it: **Yes** adds it and selects it, **No** stops conch asking about that repository (kept in `ui.json`), and `esc` leaves the question for next time. A home folder kept in git is never offered, and a TUI restarting onto a new build keeps your place. - -### SSH sessions - -`H` (or **SSH to a host…** in the tab bar's `+` menu, or in the menu of `local` and its `CLI`) opens a terminal on this computer logged in to another host. Pick a host from your `~/.ssh/config` or one of your machines, or type `user@host`, an alias or `ssh://user@host:port`. It runs your own `ssh` with your config and keys, so password and host-key prompts appear in the terminal. Each session makes its own connection, as a plain `ssh` does — through a jump host too (`-J`, or `ProxyJump` in your config) — so a host that stopped answering never holds up the next login. Connection sharing you set up yourself in `~/.ssh/config` still applies. Nothing is installed on the host — unlike [adding a machine](/docs/remote-machines), which installs conch there to run agents. Sessions are listed under `CLI` → `SSH`, which has its own page and tabs like `Terminals`; closing the session (`exit`) closes its tab. - -Before connecting, conch asks whether to save the host. The default is not to: `enter` (or `n`) just connects, `y` saves it too. A saved host stays listed under `CLI` → `SSH` every time conch opens, even with no session to it (the `○ … saved` row above); `enter` or a click on it connects again without asking, and `x` forgets it. While a session to it is running, the session's own row stands in for it; a login that failed stays on screen, exited, to show why, with the saved host beside it to try again. Saved hosts come first in the `H` menu, and are kept in `ui.json` in the conch config folder. - -**SSH options.** Some hosts need more than a name: an old switch that only speaks an old key exchange, a port, a jump host. The **SSH options** field (when you type a host after `H`, and in the host editor) takes them as you would type them after `ssh`: `-o KexAlgorithms=+diffie-hellman-group14-sha1 -p 2222 -J bastion`. A word like `HostKeyAlgorithms=+ssh-rsa` on its own is taken as `-o HostKeyAlgorithms=+ssh-rsa`, as it is written in `ssh_config`. Only options are accepted — a stray word would be read by `ssh` as the host — and not those that would stop it logging in (`-F`, `-G`, `-V`, `-Q`, `-O`, `-W`). A saved host keeps its options and uses them on every connect; a session already open keeps the ones it started with. - -**Editing a host.** `e` on a saved host (or **Edit host…** in its menu) changes the host itself, a name to show in its place (`prod db` rather than `ssh admin@10.0.4.12`), its folder and its options. `e` on an open ssh session does the same for its host, saving it if it wasn't. - -**Duplicating a host.** `d` on a saved host (or **Duplicate…** in its menu) offers its name, folder and ssh options again under a host of its own — the same machine reached as another user, on another port, or in through a jump host. The copy cannot keep the host it came from: conch tells saved hosts apart by the host, so `admin@10.0.4.12` saved twice is one row, and saving without changing it says *10.0.4.12 is already saved* rather than quietly replacing what is there. What it saves you is the options, which are the part worth not typing twice. - -**A second session to the same host.** `d` on an open ssh session (or **Another session to…** in its menu) opens one more terminal logged in to the same host, with the options that session was started with — one to tail a log while you work in the other, without going back through `H` and picking the host again. It asks nothing: whether to save the host was settled when the first session was made. Two sessions to one host are two terminals, not one row, so `r` gives either its own name. A session is duplicated by making another login, where a saved host is duplicated by copying its entry — which is why the same key does a different thing on each. - -**Conch Cloud machines.** Once this conch is [signed in to Conch Cloud](/docs/cloud) (`conch login`), the account's machines are in the tree like any other, with ☁ beside them and, when one is not connected, the control plane's word on it: `☁ asleep`, `☁ waking`, `☁ creating`, `☁ error`. A machine asleep is not woken by conch on its own — waking it counts toward the plan's hours — so its row waits for you: `m` → **Wake** wakes it and connects once it is up, and **Sleep** on a running one puts it to sleep (asking first while agents work). A machine woken elsewhere — by `conch cloud exec`, Conch.app or the web — connects by itself within a quarter of a minute. Without a sign-in none of this is there, and conch asks Conch Cloud nothing. - -**A host as a machine.** An ssh session is a terminal on *this* computer, so what you start in it ends when the link does — a dropped network, a sleeping laptop, a closed session. `M` on a saved host or on a session logged in to one (or **Add as a machine…** in its menu, or **A host you already ssh to…** in the `M` menu anywhere) offers that same host as a [machine](/docs/remote-machines) instead: conch installs itself there, and that conch owns the terminals, so its agents keep running whether or not you are connected, and its projects, branches, sessions and token usage are read on the host. The **Add machine** dialog opens with the host and the ssh options it is saved with already filled in, so nothing is retyped; a machine keeps the options that say how to log in (a jump host, a port, a key, an old key exchange) and drops the ones that belong to a terminal's own session (a forward, a tty, agent forwarding). Nothing is taken away by it: the host stays saved under `SSH`, any session open to it keeps running, and the host's page then names the machine it also is — neither the page nor the status bar offers `M` there any more, and pressing it says which machine it already is and goes to it. A host that needs a password should get `K` first — a machine reconnects by itself. A sandbox is reached through its provider rather than a host of yours, so there is nothing there to promote. - -### SSH folders - -`SSH` takes [folders](#folders-of-your-own) like `Agents` and `Terminals` — `eng`, `staging`, `prod`, one per cluster — and a folder there holds **saved hosts** as well as sessions. A saved host in a folder is listed in it while nothing is open to it, and every session to it is listed there instead, so a host and its sessions stay together and connecting again moves nothing. A session to a host you haven't saved goes in by itself, as any pane does. - -- **Make one**: `N` on `SSH`, on a saved host or on a session (or **New folder…** in their menus) — or type a new folder's name in a host's editor. -- **Drag a host in**: press on a saved host or a session to one, carry it onto a folder (the row under the pointer is marked), and let go; drop it on `SSH` itself to take it out. With a folder to drag to, a press and release on a saved host is still a click and connects; with none, the press connects as it always did. -- **From the keyboard**: **Move to folder…** in the host's menu (`m`), or the **Folder** field of its editor (`e`). `a` on an SSH folder adds a saved host to it without connecting. - -`x` on a folder removes it; the hosts and sessions in it go back to `SSH`, and nothing closes. Forgetting a host takes it out of its folder. - -### Login without a password - -`K` on a saved host or an ssh session (**Set up login without a password** in its menu) opens a terminal that copies your public key to the host's `~/.ssh/authorized_keys` — what `ssh-copy-id` does, but through conch's ssh with the host's own options. It uses the first of `~/.ssh/id_ed25519.pub`, `id_ecdsa.pub` and `id_rsa.pub`; with none, it runs `ssh-keygen` to make `~/.ssh/id_ed25519` first, asking for a passphrase you may leave empty. The host asks for its password one last time; a key already there is not added twice. The terminal stays open to say whether it worked, until you press `enter`. - -### Projects - -Projects appear when you open a pane inside a git repository, or add them with `a`, which opens a folder browser on the selected machine (local or remote): - -| Key | In the folder browser | -| --- | --- | -| `enter` | open a folder | -| `←` | go up | -| `a` | add the selected folder | -| `.` | add the folder you're in | -| `/` | filter | -| `g` | jump to a typed path | -| `n` | create a folder | -| `p` | create a new project (a folder with a git repository and an initial commit) | - -Git repositories show `◆ git`, existing projects `◆ project`. From the CLI: `conch project add PATH`, `conch project clone URL [DIR]` or `conch project create [-no-git] PATH`. Linked worktrees belong to their main repository. The list is kept in `~/.config/conch/projects.json`. - -### Branches - -An agent started by another agent is **listed under it**, indented, and folds away with it; the agent that started them shows **⑂N** for the helpers it has out — amber with `!` when one of them is waiting. Where a helper cannot be listed under its agent — another section, another machine, or narrowed away by a search — it says **↳ for** the pane that started it instead, as it always did. The subagents Claude Code runs inside its own process — its Agent tool, background tasks — are listed under it as well, with the task each was given, for as long as they run; selecting one shows its agent. See [Agents working together](/docs/agents-together). - -Each agent row shows what it has spent (Settings → Theme → Tree turns this off) — `$1.40` when the agent reports a cost (Claude Code and OpenCode do), otherwise what it has used, like `3.0k out` or `120k in` (Codex and Gemini CLI report no cost). The `Agents` section, the project and the machine show the total of the agents under them. This is only the usage conch has seen: plan windows are per account, so an agent you started outside conch spends the same window without appearing here. The project and machine pages spell that out in full. - -Branches list checked-out branches, the base branch, branches with panes and recent ones; the rest fold into `… N more`. Each shows uncommitted changes (`+42 −7`, `⚠` conflicts), commits ahead/behind the base (`↑2 ↓1`), and the state of agents working on it. Branch rows leave the cost out: they are busy enough, and the agents beneath them name their branch. Git state refreshes when git metadata changes, after an agent uses a tool, and every few seconds. - -### Pull requests - -Pull requests come from the `gh` CLI (your existing GitHub login): `#12✓` checks passing, `#13✗` failing, `#14●` running, purple when merged. `o` opens the branch's PR. They refresh every minute while agents work in the project, every five minutes otherwise, and on `R`. When one conch saw open is merged, conch fetches the branch it merged into from that branch's own remote, so `origin/main` and the merge commit GitHub made are in your checkout without a `git fetch` of your own; a fetch that fails (offline, a lock) is tried again at the next look, and nothing else is fetched for you. - -### Agents - -A click shows a pane and leaves the keyboard in the tree, where the row keys are; double-click (or `enter`) hands it to the pane. Agents are named after their task (Claude's title) until you rename them with `r`. A mark in front of the name says **which agent** it is, while the glyph before that says what it is **doing** — the thing worth seeing first. With `[ui] icons = "nerd"` the marks are Nerd Font glyphs, each the shape of that agent's own mark wherever a character comes close: Google's own logo for Gemini, a starburst for Claude Code (Anthropic's is one), a six-fold rosette for Codex (OpenAI's Blossom is three triangles woven into six), a cube for Cursor CLI, an ✕ for Grok (xAI's letter, and the slash through its mark), pixels for Kilo Code (its wordmark is built from them), a π for Pi, and a terminal for OpenCode, whose whole identity is the terminal. Only Aider, Amp and Devin have no shape to copy, and get a plain thing that suits them. A real logo would need a terminal's image protocol, which not every terminal has and ssh and tmux lose. Otherwise the marks are coloured dots — 🟠 Claude Code, 🟢 Codex, 🔵 Gemini CLI, 🟣 OpenCode, 🟡 Devin — which are emoji and so two cells wide; every line of the tree is measured and cut to fit, so a narrow sidebar shortens the name rather than spilling. The agents conch only [runs from a manifest](/docs/agents#two-tiers) get squares rather than circles, so the shape says which tier it is: 🟩 Aider, 🟧 Amp, 🧊 Cursor CLI (a cube, as its own mark is), 🟦 Grok (xAI's accent blue, since its own black and white would vanish on one background or the other), 🟨 Kilo Code (its own yellow) and 🟥 Pi (the salmon of its three-block mark, the blue of it being Grok's square already) — and 🤖 for an agent you described yourself, since a blank where every other agent has a mark would read as "conch does not think this is an agent". The colours are the agents' own where a brand publishes one; four of them are black and white, and four marks all in white would be one mark, so there the shape carries the agent and the colour is only chosen to be legible on a dark terminal and a light one. An agent that puts its own mark at the start of its window title — Pi titles its window `π - conch` — has that copy dropped from the name, since conch has just drawn one in front of it; only the very same character goes, never anything that merely looks like a symbol. `icons = "off"` leaves them out altogether. Their states are described in [Agents](/docs/agents#agent-states); every project also has a [Sessions](/docs/sessions) section. - -### conch inside conch - -`conch` refuses to open a TUI inside one of its own panes, and tells you how to do it anyway (`CONCH_PANE_ID= conch`) — useful when you want a second view without leaving the pane you are in. The one thing that view will not do is show **its own pane**: conch asks the server which pane it is running in and refuses, saying so, because a TUI resizes every pane it draws to the space it has for it — showing itself would shrink its own terminal, and then the space, and then the pane, down to nothing. - -### Checking conch - -A moment after conch starts it runs the same checks as [`conch doctor`](/docs/cli#doctor) in the background — config, socket, agents, git, gh, the terminal and the ssh your machines need. Anything they find is listed on **this computer's** page with its fix, and anything conch cannot work without (no agent installed, no git, a `config.toml` that does not parse) also puts **✗ N things to fix** on the status bar, which opens the list in a click. A warning alone stays off the bar: `gh` not installed can be a settled choice, and a bar that nags for ever is one nobody reads. - -`,` → **Check conch…** — or `!` on any Settings tab, since the item sits at the foot of the first — opens the list at any time and checks again, so it says how things stand after you have fixed one. A fix that is a command can be copied from there, ready to paste into a terminal (`n` opens one) — without the note beside it, which a shell would reject. Checking again also asks this computer's agent list again, so an agent you have just installed in a shell shows on the page and in the guide at once. - -### Reporting a problem + -**⊙** (GitHub's issue sign) on the status bar opens it in one click, when the window is wide enough to show it without pushing a key hint off; `,` → **Report a problem…** is the same thing from Settings. It shows what conch knows about itself — its build, the build of the server it is talking to (not always the same one), what is missing between them, how many panes and agents are running, how big the terminal is, and the last error it showed you — and offers to open a GitHub issue with it, copy it, or copy the path of the server's log. `conch bug` is the same thing from a terminal. - -The report carries **facts, not contents**. No path, no project, no branch, no pane title, nothing off a screen: that is what makes it safe behind one key, since nothing has to be read through before it is handed over. The log is the exception and is never included — it holds paths and branch names — so conch gives you its path and leaves it to you. - -Nothing is sent by conch. `-open` ends in a browser with every word visible, and you press submit. - -### Folders of your own - -conch groups panes by what they are and, with the setting below, by the tab they are open in. Neither says what *you* think belongs together, and names repeat across environments. **`N`** on Agents, Terminals or SSH — or on a pane in one — makes a folder; drag rows into it, and back onto the section to take them out. `x` on a folder removes it and its panes go back to the list; nothing closes. A folder of `SSH` holds saved hosts too, with their sessions: see [SSH folders](#ssh-folders). - -``` -Terminals - ▾ eng 2 - › vm1 - › vm2 - ▸ prod 1 - › vm3 -``` - -Folders come first, and a folder **starts folded**. Both follow from the same thing: a row one step out from an open folder's contents is not in that folder, but at a glance it can read as though it were. Folded, nothing is under a folder but its own; opened, you are the one who opened it. The panes in no folder are listed after the folders, as `vm3` is. - -A folder holds each pane **by name and by id**. The id says which pane, always — two terminals may share a name, and the id is the only thing that tells `vm1` in `eng` from `vm1` in `prod`. The name is for one moment: when conch connects to a machine and finds the ids it wrote down belong to a server that has since restarted, each folder looks for its panes by name **once** (`r` in the tree, or `conch rename`, gives a pane its name). What it finds then it keeps by id; what it cannot find it lets go. Two consequences worth knowing: a pane you never named is held by id alone and leaves its folder when the server goes, and if **two** panes answer to one name at that moment the folder keeps neither, there being nothing to choose by — and it does not come back for them later, so a terminal that merely outlives its namesake stays where you left it. Renaming a pane while it runs keeps it in its folder: the id still says which pane, and the folder takes the new name with it. A pane is in one folder at a time, and folders live in `ui.json` per machine, project and section, so they cost nothing to anyone who never makes one. - -### Grouped by tab - -A project lists its panes under **Agents** and **Terminals** — what each one is — with its **Branches** between them, then **Files** and **Sessions**: agents first, in the order Conch.app shows them. **Settings → Tree grouping → By tab** lists them under the tab each is open in instead, so the tree says what the tab bar says: - -``` -▾ ◆ conch - ▾ Tab 1 claude ⊞ - › claude - › zsh - ▾ Tab 2 codex - › codex - Branches 13 -``` - -Drag an agent or terminal row onto a tab's section to put it in that tab: it leaves whatever tab it was in — which closes if that was its last split — or, if it was open in none, it is opened there. The section under the pointer is marked while you hold. +## The sidebar -A tab's row is named as the bar names it, a renamed tab (`ctrl+b ,`) and the `⊞` for a tab of more than one split included, and it is numbered among that project's tabs. Panes open in **no** tab keep their Agents and Terminals sections below, so closing a tab never hides a pane. A tab holding panes from two projects, or from none, belongs under neither and is left out; its panes keep their sections. It is `[ui] tree_groups = "tabs"` in [config.toml](/docs/configuration). +Each machine holds `Workspace` (its projects) and `CLI` (agents and terminals of no project). Badges: `⠋1` working, `⚑1` waiting, `✓1` done. -### Fold state +**How:** `a` adds a project, `c` starts an agent, `n` a terminal. `!` goes to the next waiting agent. -Fold state and sidebar width are remembered in `~/.config/conch/ui.json`. With two conch windows open at once, each keeps its own tabs, workspaces and folds, while folders, saved ssh hosts and the repositories you said No to are shared: a change made in one shows in the other within a second, and neither writes over the other's. If both change the folders of one section in the same moment, the later change wins. A conch from before this was added still writes over the file, so restart an old window after upgrading. + -### Commit graph +## Workspaces -**Commit graph** on a project's menu (`m`, then `G`) opens its history in a window over the screen: every branch and tag of the repository, newest first, as `git log --graph` draws it — each commit a dot on its branch's lane (`◉` where HEAD is), lanes in the theme's colours joining where branches merge — with its short hash, its refs as git names them (`(HEAD → main, origin/main, tag: v1)`), subject, author and age. On a branch's menu it opens at that branch's newest commit. `↑↓` move, `enter` shows the changes of the branch a commit is the tip of, `y` copies its hash, `r` reads it again and `esc` closes; the wheel scrolls and a click picks a row. The newest 300 are read first and older ones as you scroll to the end, up to 2000. It needs a server with `project.log.v1`; an older one says to reload it. Conch.app draws the same graph in a tab of its own. +Each workspace shows only its own projects, agents, terminals, hosts and tabs. -### Git panel +**How:** `+` atop the sidebar or `ctrl+b N`; `ctrl+b (` and `)` switch. -Press `b` or `$` on a branch — `$` in its changes, or **Git panel** from its menu — and a command window opens in the middle of the right-hand panel, while the branch's changes load behind it. A *click* on a branch shows its changes and leaves the window closed: opening a window over the right-hand side is more than one click on a row should do. The tree stays in view, and `b` on another branch moves the window to that one. On a screen too narrow for that, it takes the whole width. It opens empty and holds only what your commands print, and the prompt — the files and where the branch stands (upstream, base, its pull request) are on the branch's changes behind it. +## SSH sessions -Type any git command — `log -5 --stat`, `switch -c spike`, `commit -m 'fix: the "quoted" bit'` — and it runs in that branch's worktree; a leading `git` is optional. Quotes group words as in a shell, but nothing is expanded, so `*.go` reaches git as it is. The command starts with git's subcommand: options before it, like `-C` or `-c`, are refused, so it can't reach another repository. Nothing waits for an editor or a password: a merge or `rebase --continue` takes git's own message, `commit` with no `-m` stops, and a fetch that needs credentials fails rather than hangs. +A terminal logged in to another host with your own `ssh`. Nothing is installed there. -A session in it reads as a transcript — what you typed, and what git printed: +**How:** `H`, then pick a host or type `user@host`; `y` saves it. On a saved host `K` sets up login without a password and `M` makes it a [machine](/docs/remote-machines). -``` -status -sb -## fix-login...origin/fix-login [ahead 1] - M internal/tui/keys.go -?? notes.md +## SSH folders -add -A +Group saved hosts with their sessions — `eng`, `staging`, `prod`. -commit -m 'fix: the "quoted" bit' -[fix-login 9f3c1a2] fix: the "quoted" bit - 2 files changed, 18 insertions(+), 3 deletions(-) +**How:** `N` on `SSH`, `Agents` or `Terminals` makes a folder; drag hosts or panes into it. -push -``` +## Grouped by tab -`tab` shows the everyday ones in place of the output, each with a key: **Status**, **Log**, **Diff stat**, **Fetch**, **Pull** (rebasing, with your changes stashed around it), **Push**, **Commit…**, **Amend**, **Stash**, **Pop stash**, **Stashes**, **Branches**, **Rebase on** and **Merge in** the base, **Undo last commit** (the changes stay, staged), and **Discard changes…**. Amend, undo and discard ask first, and discard only takes `y`. Push and commit are the same as `P` and `c` in the changes view, so a push the remote is ahead of still offers to rebase. `tab` or `esc` goes back to the prompt. +The tree lists a project's panes under the tab each is open in, as the tab bar does. -When a rebase, merge, cherry-pick or revert stops on conflicts, a line above the output says so, and the actions start with **Continue**, **Abort** and — with an agent on the branch — **Ask it to resolve**. +**How:** Settings → Tree grouping → By tab lists panes under their tab. -With an agent working on the branch, `ctrl+t` (or a click on the prompt's label) sends what you type to it as its next message instead, and the actions become instructions for it: review the changes, commit its work, write tests, rebase on the base, resolve a conflict, or open its pane. An agent waiting on a question isn't sent anything, and the window says so. +## Git panel -Servers older than the window still open it, with push, commit and messages for the agent; typed git commands need the server reloaded. +Type git commands that run in a branch's worktree. -### Changes view +**How:** `b` or `$` on a branch; `tab` lists everyday actions. With an agent on the branch, `ctrl+t` sends what you type to it instead. -Selecting a branch shows its **changes**: its pull request (checks, review), uncommitted files (or files changed since the base when it isn't checked out), commits ahead, and diffs. +## Changes view -**On a wide terminal the diff is side by side** — the old on the left, the new on the right — and unified below about 100 columns, where two columns would be two columns of wrapped code. **Settings → Diffs** makes that your choice rather than conch's: *side by side where there is room* (the default), *always side by side*, or *always one column*. `s` says otherwise for the file you are looking at, without writing anything down. A line too long for its column **wraps inside it** rather than being cut — the end of a line is often exactly where the change is. Within a run of removals and the additions after it, the first pairs with the first and so on; whatever is left over stands alone, which is the only pairing that can be made without guessing which line became which. +Selecting a branch shows its pull request, files and diffs, following the agent's edits live. -**Inside a changed line, what changed is picked out.** Where one line replaces another, conch compares the two and marks only the part that differs — a renamed variable in a long line is two characters, and finding them by eye is the slow part. A block of removals followed by a block of additions is left plain: there is no "this became that" to show, and marking it would invent a pairing. So are two lines with nothing in common, where the `+` and `−` have said it already. + -| Key | In the changes view | +| Key | | | --- | --- | -| `↑↓` | select a file | -| `enter` | show its diff | -| `space` | mark a file for the next commit (`✓` beside the cursor; clicking that column marks it too); inside a diff, the hunk the `▸` cursor is on | -| `n` `N` | move to the next or previous hunk of an open diff (`[` and `]` too) | -| `s` | side by side or unified, for this file (wide terminals start side by side) | -| `a` | inside a diff, comment on the hunk the `▸` cursor is on (`✎` marks it; `a` again edits it, and an empty comment removes it). Only on a checked-out branch, since the comments are for the agent working in it | -| `S` | send every comment on the branch to its agent as one message: each numbered, with the file, the hunk header and the hunk itself quoted (the first 40 lines), so a comment still makes sense after the agent rewrites the lines. With no agent on the branch, your default agent starts in its worktree with them. Refused while the agent waits on a question of its own, and the comments stay. They are cleared once sent | -| `e` | open the file in the machine's own `$EDITOR`, at the hunk the `▸` cursor is on — in a pane of its own, so conch keeps running. From the file list it opens at the top. The editor runs on the machine the worktree is on, which is the machine whose `$EDITOR` and whose file they are. conch knows the line flag for vim, nano, emacs, VS Code, Cursor, Zed, Sublime, Helix and the JetBrains editors; anything else opens the file without a line rather than being handed a flag it would read as a file name | -| `F` | inside a diff, follow what just changed (on until you scroll away) | -| `R` | re-read the branch, or the open diff, now | -| `c` | commit the marked files, or every change when none are marked | -| `P` | push, setting the upstream the first time; when the remote has commits this checkout lacks, conch says so and offers to rebase onto them and push. A rebase that conflicts is undone — the branch and the remote stay as they were — and the notice says where to sort it out and what to run | -| `p` | push and open a pull request into the base | -| `M` | merge into the base | -| `D` | discard the branch and its worktree (`x` in the tree does the same once a branch has no worktree left) | -| `A` | compare the attempts at this task, when a prompt was tried several times | -| `o` | open the PR | -| `$` | the branch's [git window](#git-panel) | -| `y` | copy the file path or the whole diff | -| `esc` | back | - -These also sit in a branch's menu (`m`). See [Finishing a task](/docs/tasks#finishing-a-task) for what each one checks first. - -**Review comments are the server's, not this window's.** The machine's conch keeps them, so they are still there after you leave the changes view, quit conch or reload the server, and everything else that talks to that server sees the same ones: another conch window, [`conch review`](/docs/cli#review) in a shell — which is also how a reviewing agent leaves comments for you to read and send — and the [phone](/docs/phone#review-comments), which shows them on the agent's card and sends them with a tap. A branch that is merged or discarded takes its comments with it. A server from before this says so when you press `a`; `conch server reload` brings it up to date. +| `a` / `S` | comment / send comments to the agent | +| `c` / `p` | commit / push and open a PR | -**What reviewers said on the pull request is here too.** For a branch with an open pull request, conch reads its unresolved comments through `gh`, with your own login, about a minute after the pull request changes: each comment thread is marked `✎` on the hunk its line is in. A review's own summary is listed too, when it asked for changes or left a comment. The title counts them (`✎ 5 comments (3 from GitHub)`), and the lines under it say who wrote each one, where, and how many replies it has: `✎ alice on GitHub · line 42 · 1 reply: this swallows the timeout`. A comment whose lines have changed since it was written is marked *outdated* and listed under the hunk's comments, as are comments about the whole pull request. `S` sends them with conch's own, each with its replies and who wrote it. They are GitHub's: `a` doesn't edit them, and sending one doesn't resolve it on GitHub. A sent comment isn't sent again, and comes back only when somebody replies to its thread. A thread resolved on GitHub disappears here, and so does every GitHub comment once the pull request is merged or closed. - -#### Diffs as the agent writes them - -The server watches the worktrees of every project it knows, and says so the moment their files are written — a diff you have open re-reads itself about a tenth of a second later. It cannot wait for the file list to change: an agent rewriting a line leaves the file's `+`/`−` counts exactly as they were, so the diff on screen would quietly go stale. - -Only the branch you are looking at is re-read, and the open diff only when its own file was one of the ones that changed. Directories git ignores cost nothing — `node_modules` and `target` are never watched — and git's own metadata is left to the project's ordinary refresh. A machine that can give no file watches (an old kernel, or its watch budget already spent) says so in its capabilities, and conch falls back to re-reading the branch every two seconds instead; a remote on a build older than this feature does the same. - -Splits work the way you would want: put an agent's pane beside its branch's changes, or two branches side by side, and each half follows its own worktree — an event about one moves only the half showing it. Tabs are different, because only the tab on screen is read: one you come back to is re-read then, rather than left showing what it had when you switched away. - -The file list says where the work is happening: a file written in the last few seconds has its whole row washed in a faint tint of the theme's warn colour and is marked `▌` right beside its name — where your eye already is, rather than out by the `+`/`−` numbers, which on a wide split are most of a screen away — and the heading counts them (`· 2 changing`), so you can see which file an agent is in without opening each one. Lines the last re-read brought are marked `▌` in the gutter for a few seconds, and the header counts them — enough to see at a glance what the agent just wrote. The view follows them, scrolling to the first one when it is off screen; scrolling yourself stops it following, `g` or `F` starts again, and `F` turns it off while you read. Hunks you marked for a commit lose their mark when the agent rewrites them, rather than committing something you didn't read. When the file goes back to matching the branch — committed underneath, or the edit undone — the diff says so instead of going blank. +All keys: [Keys and mouse](/docs/keys). ## Review queue -`Q` opens the **review queue** in the focused split: one list of what needs a decision, across every machine, instead of walking the tree to find it. +What needs a decision, across machines: waiting agents, failed checks, finished work. -| Order | Row | Why | -| --- | --- | --- | -| `!` | an agent is waiting | it is blocked on an answer and nothing proceeds until you give one | -| `✗` | its check failed | the project's command came back non-zero on that branch, or its pull request's CI failed | -| `✓` | an agent finished | it is done and nobody has looked at what it did | -| `↑` | commits not pushed or merged | work that is finished but hasn't shipped | -| `·` | uncommitted changes | a worktree left dirty, with no agent running in it | -| `⏲` | scheduled | a message or task the server will send or start later ([Later, and on a schedule](/docs/tasks#later-and-on-a-schedule)); `x` takes it off the schedule | +**How:** `Q`; `enter` opens a row, `v` runs the check. -Within each group the thing that has been waiting longest comes first, so nothing quietly rots at the bottom. Rows are gathered under the project they belong to — a repository is named once, however many of its branches need you — and the projects themselves are ordered by their most urgent row. Each row names the branch, what it is waiting on, what the agent has spent, and how long it has been there. It also says what you would open it to find out: a waiting agent's question in its own words (`waiting for an answer: Claude needs your permission to use Bash`), and how much is uncommitted on the branch (`3 files +42 −7`) — so coming back to a handful of agents is reading a list, not opening each one. `/` filters by any of it, the question included. - -**Merge trouble, before the merge.** Agents in parallel branches collide when their work is merged, and finding out then means untangling a conflict after the work is done. So a branch's row — and the top of its changes — says when another branch's checkout has touched the same files (`⚠ also changed on api/fix-login: auth.go`), and when merging it into the base would conflict, tried without merging anything (`⚠ conflicts with main in auth.go`, with git 2.38 or later). The row has one line for it; the changes page lists the files themselves, one to a line under the branch each collides with, and counts anything it has no room for. That is the moment to decide which agent goes first, or to have one rebase onto the other — `b` opens the git panel, which can hand the rebase to the branch's agent. - -`enter` goes where the answer is: a waiting agent opens its pane so you can reply, and anything else opens the branch's [changes](#changes-view), where committing, pushing and opening a PR already live. ### Checks - -A project can have a **check** — its own command, `go test ./...`, `npm test`, `make check` — which conch runs in a branch's worktree when the agent working there finishes. The queue then says what happened (`check passed`, `check failed (exit 1)`, `checking…`) instead of only that an agent stopped, and a branch whose check failed sorts to the top: that is the clearest call for your attention there is. A verdict is about the branch as it stood when the check ran, so a commit or an edit afterwards makes it read **check out of date** — it stops counting as a failure, and conch runs the check again once the branch has been quiet for half a minute and no agent is still writing in it. `v` runs one whenever you like. - -`v` on a row runs the check, or asks for the command when the project has none; `o` opens that check's terminal, which is where a failure's output is, and `ctrl+b b` comes back to the queue (pressing it again returns to the terminal). There is no default and nothing runs until you name one, since a project's own command can take minutes, touch a database or cost money. A project without a check is not scolded — its rows simply say nothing about checks. Each run happens in its own terminal. A run that **fails** keeps it — unlike a shell that exits — so the output is there to read; close it with `x` when you are done, or leave it: the next check on that branch takes its place. A run that **passes** closes its terminal as it ends, since the verdict is on the row and in the flash and nobody opens a passing run's output — otherwise every branch you ever checked would leave a dead terminal in the tree. conch also says what happened as it finishes, and a failure says where to look. + ### Sending a failure back -`f` on a row that failed hands the failure to the agent on that branch, as its next message: which command, how it ended, the end of its output (the last 80 lines, at most 6 KB, colours stripped) and a request to fix the cause and run it again to show it passes. When nobody is working on the branch any more, `f` starts your default agent in its worktree with the same message. An agent waiting on a question of its own is left alone — answer that first. - -The same goes for **CI**. A branch whose open pull request failed its checks is in the queue as `CI failed on #12`, even when everything is pushed, since fixing it is your move again; `f` on it reads the failed steps of the newest failed GitHub Actions run at the pull request's head commit, through `gh` on the machine the branch is on, and sends that. A check run by another service has no log conch can read, and conch says so. - -To have conch do this without asking, set how many times in a row it may in `config.toml`: - -```toml -[verify] -auto_fix = 2 # send a failed check back to the branch's agent up to twice -``` - -It only sends to an agent that has finished — never one still working or waiting on you, and never by starting an agent nobody asked for — and a check that passes resets the count. When the count runs out, conch says the failure is yours. The default, `0`, never sends on its own: a cap is the difference between an agent fixing a test and an agent spending a night of your plan on one it cannot fix. - -**This covers CI as well as the project's own check.** conch reads a pull request's checks every minute while you are working, and when a branch's checks turn red it hands the end of the failed run's log to that branch's agent, exactly as `f` would — same cap, same count, same guards. Both kinds share one count, since "a check failed, give it to the agent" is one idea, and green clears it, so a branch that goes red again gets the whole allowance rather than none. Only a change conch *watched* counts: reaching a machine that already has four red pull requests on it prompts nobody, because conch did not see those turn red and the work may be days old. They wait in the review queue, where `f` sends them when you say so. - -**And it can merge when they pass.** The other half of the same loop: - -```toml -[verify] -auto_merge = true # a green pull request merges itself -``` - -On the turn to green — once, not on every poll — conch merges the pull request **on GitHub**, through `gh`, the way the repository allows: a merge commit, else a squash, else a rebase. It merges the commit whose checks passed, so a push in the meantime is not merged unchecked, and it leaves the branch in place, since a worktree may still be on it. Pull your base afterwards to have the merge locally. - -What holds it back, said once on the status bar rather than quietly: a **draft** is not finished whatever CI says; **changes requested** is a person asking for something, and green checks are not an answer to it; a pull request that **conflicts with its base** cannot be merged as it stands, so rebase it; an **unresolved thread** on the pull request is somebody still waiting, which catches the commoner case of a reviewer who left notes and no verdict (conch's own comments on the diff are not counted — those are your working notes, and a stale one would hold a branch for ever); this **project's own check failing** on the commit being merged while CI passes is a disagreement rather than a go-ahead — and with a check command, the pull request waits until that check has passed on the very commit being merged: while it is running; while it has not run on a commit that is checked out here, which conch runs it on; and while the commit is not checked out here at all — pushed by hand, say, or the branch has moved on since — which it says, since the check can only run where the commit is; a branch whose **agent is still working or waiting** may be mid-push; and a pull request whose **commit is not on the branch here** — pushed from somewhere else, or one GitHub would not name — is not what an agent here made, so it is held until the branch has it (a head the branch has moved past is still its own). A pull request from a **fork** is never taken for a branch here, whatever its branch is called: anyone can name a branch after one of yours. Held back is not given up: the pull request waits, and merges as soon as the hold is gone — the agent finishing, the thread resolved, the conflict rebased away and CI green again. If GitHub itself refuses (a branch protection rule, say), conch says why and tries again only when the pull request next turns green. A pull request that was already green when conch first read it is not merged — conch did not see it turn — and neither is one that arrives green, opened while the server was stopped or between two reads. The machine's conch has to be new enough to merge on GitHub; an older one is asked for nothing, and the status bar says to update it. It is off by default, because it writes to your base branch. - -**And it can open the pull request in the first place.** The start of the same loop: - -```toml -[verify] -auto_pr = true # a finished branch is pushed and given a pull request -``` - -When a branch's agent finishes, the server runs the project's check there — in a terminal named `check · BRANCH`, as `v` does, which the review queue shows as its own, with git's pager off since nobody may be there to page it — and once it passes for the commit the branch is at, conch pushes the branch and opens a pull request titled from its commits (`gh pr create --fill`). A branch whose pull request is already open has its new commits pushed to it instead, which is how an agent's fix for red CI gets back to CI. Without a check command for the project it goes out as soon as the agent finishes. What it will not do, said once: push work that is **uncommitted** — the agent is asked, once for each commit it is at, to commit what belongs to the work, since which files belong is its call and not conch's; open a second pull request for a branch whose last one somebody **closed**; or push a branch whose agent is still working. The base branch is never pushed, and a branch with no commits of its own has nothing to send. Off by default: it publishes the agent's work. +`f` on a failed row sends the failure to the branch's agent. `[verify]` automates it: -**What it asks of the work first.** Two gates decide whether a pull request conch opens may merge itself: + ```toml [verify] -require_tests = true # code with no test opens as a draft, and the agent is asked for one -max_diff = 800 # so does a pull request bigger than this many changed lines +auto_fix = 2 # send a failed check back up to twice +auto_pr = true # push a finished branch and open its pull request +auto_merge = true # merge a pull request when it turns green +auto_resolve = 2 # bring a conflicting branch up to date ``` -A pull request conch opens that fails one is opened **as a draft**, with the reason on the status bar; and any green pull request that fails one — whoever opened it, or one that has grown since — is held back from merging itself, saying which. With `require_tests` a branch that changes code — not documentation, configuration or data — and touches no test is one; its agent is asked once for the branch to add a test (or to say why it cannot be tested, which leaves the draft for you) that fails without the change, and the push that brings one marks the pull request ready. Tests are recognised by the usual conventions: a `test`, `tests`, `__tests__` or `spec` directory, or a name like `x_test.go`, `test_x.py`, `x.test.ts` or `FooTest.java`. With `max_diff` the line count is what is added and removed together, and the advice is to split it. A draft you made yourself is yours; conch marks ready only the ones it held. - -While `auto_pr` is on, a task's first message also ends with how its branch is shipped — the check that runs, and that the agent should write the failing test first, commit in small commits whose messages say why, leave nothing uncommitted, and never push, force-push, rebase onto the base or merge, since conch does those after checking. It is the same practice the messages conch sends later ask for, said at the start rather than learnt from a refusal. - -**And a conflict with the base need not stop it.** A pull request that conflicts cannot merge, whatever CI says: - -```toml -[verify] -auto_resolve = 2 # bring a conflicting branch up to date, asking its agent up to twice -``` - -When a pull request turns conflicting, the server rebases the branch onto the base as the remote has it, which is all most conflicts need — the base moved, and the branch did not touch the same lines. When the rebase stops on a real conflict it is undone, and the branch's agent is asked to do it: told which files, what the base did to them since the branch left it, and to keep both sides — every change the base made and every change the branch made, stopping to say so where they truly contradict rather than picking one, and never deleting a file or a test to get past a conflict. The rewritten branch then has to replace the pushed one, which is the step that could lose work, so it is checked first: the project's check must pass for the new commit; the base must be all there; nothing may be deleted that the branch did not delete before; and it is pushed with a lease, only while the remote still has what was there when the rebase began, so anybody else's push meanwhile is kept and the rewrite refused. Each refusal says why. A pull request already conflicting when conch first saw it is left to you, and so is one past the allowance. - -**It runs on the machine, not in your terminal.** Each machine's conch server does the sending back and the merging, so both carry on with the TUI closed, through a server reload, and with two TUIs open without either acting twice. The TUI hands each server your `auto_fix`, `auto_merge`, `auto_pr`, `auto_resolve`, `require_tests`, `max_diff` and check commands when it connects and whenever you change them in **Settings** (`,` → **Git** for merging, **Agents** for sending a failure back), and the server keeps them — with the CI each pull request last had, the count, and what waits to merge — in `autopilot.json` beside its other state. A machine whose server predates this is named on the Git tab: there the TUI still does both itself, and only while it is open. The project's check runs on the server too when an agent finishes; one you start yourself with `v` is reported to it, since a failed check is what holds a merge back. - -Together with `auto_fix`, `auto_pr` and `auto_resolve` that is the whole loop people write skills for — the agent finishes, its check passes, the branch is pushed and a pull request opened, CI goes red and the agent gets the log and fixes it, the base moves and the branch is brought up to date, CI goes green, it merges — except that nothing sits in a polling loop: conch reads pull requests every minute anyway, so no agent is kept awake and no tokens are spent waiting. - ### A second opinion -Name an agent to review finished work and conch asks it, on every branch whose agent finishes — once the check passes, where the project has one: +A reviewer reads each finished branch; `R` hands its report to the writer. ```toml [verify] -reviewer = "codex" # Codex reads what Claude wrote; any agent conch runs will do +reviewer = "codex" ``` -The reviewer starts in the branch's worktree, in a pane named `review · `, told to read the diff against the base, report what is wrong with a file and line for each finding, and not to edit anything. When it finishes, its row in the queue says `review ready`, and `R` there hands its report — its whole last message, read from its saved conversation rather than off its screen — to the agent that wrote the code, asking it to address each finding that holds up and say why where it disagrees. A branch is reviewed once per state: the reviewer finishing, or the writer finishing again with nothing changed, starts nothing; a branch already being reviewed is left to that reviewer. **A reviewer closes once its report is used**: after `R` hands it over (a send that fails keeps it), when the branch has changed and the next review starts (the last one goes as the new one begins), and when the branch is merged — by conch, `gh` or GitHub's page, seen the next time conch reads the pull requests — discarded, or its worktree removed. A finished reviewer no longer stops a worktree being removed or cleaned up; one still reading, asking you something or stopped by an error is left open for you to look at. Another vendor's model, with a fresh context, is the point — it catches what the writer's own context hides from it — but nothing stops you naming the same agent. Every review spends plan usage, so nothing is reviewed until you name a reviewer. - -A passing check means the tests passed. It does not mean the change is right, so it sorts the obvious failures out of your way rather than deciding anything for you. - -`/` filters the queue as you type — over the project, branch, agent, machine and the reason a row is there, so "onenutri failed" or "codex waiting" both work — and the count says how many rows it hides; `esc` clears the filter before it leaves the queue. `x` dismisses a row you have decided to leave alone; it comes back when what it says changes — another file edited, the agent finishing again — and dismissals are kept in `ui.json`, so they outlive the TUI; one is forgotten once the row it was about is gone. `esc` returns to the tree. - -The status bar counts what the queue holds (`3 to review`, beside `⚑ 1 waiting · 1 done`), so it is worth opening; clicking the count opens it, and `Q` works from a view as well as from the tree (inside a pane it is typed, like any other key). The queue keeps a tab of its own, so opening a row from it leaves the queue where it was to come back to. - -A branch with an open pull request and nothing unpushed is not in the queue — it is waiting on a reviewer, not on you. Nor is a machine that is offline, whose panes conch only holds a stale cache of. Branches the tree has stopped listing — nothing committed for a fortnight and not checked out — drop out too, so the queue stays a list of what to do now rather than a history of the repository. An agent waiting or finished is always listed, however old its branch. - ## Files -Every project has a **Files** row, and `f` opens it from anywhere in the tree: on a branch — or an agent or terminal working on one — it browses that branch's worktree, so "what did the agent on `fix-flaky` actually write?" is one key; anywhere else in a project it browses the main checkout. A branch with no worktree falls back to the main checkout and says so, and `w` moves through the project's checkouts. `w` says which checkout it landed on, since a project with four worktrees otherwise leaves you counting. - -``` - Files conch · fix-flaky-tests enter open · a → agent · y path · d diff · w checkout · / find - ~/.conch/wt/conch-fix-flaky-tests › internal › tui · 3 changed - ──────────────────────────────────────────┬───────────────────────────────────── - ▾ internal/ M │ queue.go · 472 lines · modified - ▾ tui/ M │ 1 package tui - go model.go M │ 2 - go queue.go M │ 3 import ( - tx app.tsx ? │ 4 "fmt" - ▸ web/ │ 5 "sort" - rd README.md │ -``` - -The tree opens a folder at a time, as you expand it, and the selected file shows beside it once the split is 100 columns wide; narrower, `enter` swaps the preview in and `esc` swaps it back. The letter on the right is the file's git status in the same letters as the [changes view](#changes-view) — `M` modified, `A` added, `?` untracked, `U` conflicted — and a folder carries the most telling one of what is in it. **Dotfiles are shown** — in a checkout `.github`, `.claude`, `.gitignore` and `.env` are the work, not clutter — and `.` hides them. What git ignores (`node_modules`, build output) is left out until `i` asks for it. Both choices are remembered, here and after a restart. `.git` is never listed: it is git's own, and a thousand objects nobody browses. - -**The explorer keeps itself current, three ways.** Edits in a watched worktree reach it on their own, about a tenth of a second after the file is written; a commit — which changes every status without writing a file — re-reads it too; and **coming back to it reads its folders again**, because the first two depend on conch watching that checkout, and a machine that gives conch no watches polls instead, an unwatched worktree waits for the slow poll, and a checkout changed by something outside conch is not announced at all. `r` reads it again whenever you want. +Every project has a **Files** row: a checkout with each file's git status and a preview. -`a` is the one to remember: it types the selected file's path into the prompt of the agent working in that checkout — the one beside the explorer if there is one, else the one busy most recently — on whichever machine the checkout is on, relative to where the agent runs. `d` opens the file's diff in its branch's changes, `e` opens it in that machine's own `$EDITOR` in a new terminal, and `y` copies its path. - -The preview is plain text with line numbers, the first 256 KB of a file; a binary file is described (`binary · image/png · 1.2 MB`) rather than shown. Where the server watches worktrees, what an agent writes appears on its own — the open folders are listed again and the file in the preview read again — and `r` reads the checkout again anywhere. The explorer only reads files, and only inside the project's checkouts: a path, or a symlink, that leads out of one is refused by the server. A machine on a conch from before the explorer says it needs updating rather than showing an empty repository. - -Each kind of file gets an icon, by its whole name first (`Dockerfile`, `go.mod`, `pom.xml`, `Jenkinsfile`, `.prettierrc`, `CHANGELOG.md`) and then its extension, coloured from the theme. The table covers about 220 extensions and 95 names — the languages, templates, manifests, lock files, tables, documents, media, bundles, keys and certificates a repository actually holds — with the glyphs taken from the Nerd Fonts glyph list and nvim-web-devicons, so a file looks here the way it looks in the editors you also have open. Anything unknown keeps the plain file icon. Settings → Theme chooses letters (`go`, `ts`, `tx` for `.tsx`, the default, since they read in any font), [Nerd Font](https://www.nerdfonts.com) glyphs — which need a Nerd Font in your terminal, and show as boxes without one — or none. +**How:** `f` browses a branch's worktree; `a` types a file's path into the agent's prompt, `d` shows its diff, `e` opens it in `$EDITOR`. ### A machine's own files -A machine elsewhere — an ssh host, a sandbox — has a **Files** row of its own, under its Workspace and CLI. It is the same explorer on the machine as a whole rather than a checkout: it starts in the home folder there, `-` (or `backspace`) goes up a folder and `~` comes back home, and there is no git to show. This computer has no such row: its files are a Finder away. - -A terminal where you typed `ssh host` — on this computer or any other — gets a **Files** row under it, naming the host, for as long as ssh is what is running in it; `f` on the terminal opens it. It is the same explorer on that host, with nothing of conch's needed there: conch makes a session of its own with what you typed (the host, user, port, key, jump host and `-F` config, leaving out forwards), and reaches the files through the host's sftp server, which OpenSSH has by default. That session never asks for anything, so it needs a key or an ssh agent; a host that only takes a password says so instead. With `ControlMaster` in your `~/.ssh/config` it shares the terminal's own connection and does not log in again at all. It is closed after five minutes unused, and when the terminal leaves the host. `e` on a file there opens the host's own `$EDITOR` in a new terminal beside it, which runs `ssh -t` to the host with the same options — so this one may ask for a password — and closes when you quit the editor; an `$EDITOR` set in the host's `.zshrc` or `.bashrc` is the one used. - -On any machine elsewhere, or a terminal's ssh host, this view and a project's alike, the explorer is also how files cross between it and this computer: - -- `U` asks for a file or folder here and copies it into the selected folder there — or the folder the selected file is in. Dragging files or folders from Finder onto the view does the same without asking. -- `D` copies the selected file or folder to `~/Downloads` here (your home folder, on a computer without one). -- A folder is copied whole, symlinks as links. A name already taken is never written over: the copy is numbered — `ca 2.pem`, `site 2` — and the status bar says where it landed. `U`'s dialog has a **Replace** box for writing over instead; for a folder that merges, keeping files only the other side has. A copy is written under a hidden `.name.part-…` and renamed when it is whole, so nothing half-copied ever has the real name; the view leaves those out while they last. +A remote machine, and a terminal running `ssh host`, get a **Files** row of their own, which also copies files between there and here. -Copies go over the machine's own conch connection — the one its panes use — so an ssh host and a sandbox are the same: no address to look up, no key or password to give, nothing to install. [`conch upload -to` and `conch download`](/docs/cli) do the same from a shell, and with `-ssh PANE` for a terminal's ssh host. A machine running a conch from before this says it needs updating (`conch machine upgrade`). - -The explorer browses; it does not manage. There is no creating or deleting here: `n` opens a terminal in the folder you are looking at, which does the whole job rather than the two verbs a file manager would reimplement. `y` copies a file's path, `e` opens it in `$EDITOR`, `a` hands it to the agent working in that checkout, `d` shows its diff. - -Dragging to select keeps to the column it started in — the list or the preview — so copying a file's text does not bring the file names sitting on the same rows with it. +**How:** `f` on a remote machine or ssh terminal; `U` uploads, `D` downloads. ## Splits and tabs -The main area has tabs (click them, `+` adds one, `×` closes), and each tab can be split into several views: panes, branch changes, projects or machines side by side. The tab on screen is underlined in the accent, and the bar's far end names whose tabs it lists (`api`, `CLI`, `busybox › api`). The focused split has the highlighted border. - -Tabs work like tmux windows. Every agent and terminal you open from the tree gets its own tab, and opening it again jumps to that tab; a pane is never shown in two places. Projects, branches and sessions share a browsing tab that follows the tree as you move. - -**The palette.** `ctrl+b /` (`⌘K` in [conch's own window](/docs/cli#app)) lists every agent and terminal in the workspace — the ones waiting for you first — its projects and task branches, and the commands you would otherwise need a key for, each with its key beside it. Type to narrow it (words match in any order, `ctrl+u` clears), then `enter` or a click: a place opens as `enter` on its row in the tree does, and a command is its key sent as if typed, so it does exactly what the key does. - -**Workspaces.** The top of the sidebar reads `◆ conch` followed by a `+` — in [conch's own window](/docs/cli#app), the left of the strip along the top does instead. Clicking the `+` (or `ctrl+b N`) opens another workspace, and each one — the first included — is isolated: it shows only its own projects, agents and terminals, sessions, machines, saved SSH hosts, folders and tabs. A new workspace starts empty. A project belongs to the workspaces you add it to with `a` (adding one conch already has, by its path, shares it: its agents and sessions then show in each); an agent or terminal belongs to the workspace it was started in, or to its project's, and what an agent starts follows it; a saved SSH host belongs to the workspace it was saved in; a machine is listed where it was added — over ssh, as a sandbox, or with `M` → **Machine already in conch…** — or where something of the workspace runs on it, and this computer is listed everywhere. Folders show where they were made, or where they hold something shown. What belongs to no workspace — everything from before workspaces, and what the `conch` command makes outside the TUI — is workspace 1's, so nothing is out of reach, and bringing something workspace 1 has into another keeps it in workspace 1 too. The machine row, machine page, Workspace page, the status bar's `⚑ waiting` counter and `!` count only what the workspace shows; the plan limits view still counts the whole machine, since limits are the account's. With more than one workspace, they are numbered beside conch; click one to switch, or use `ctrl+b (` and `)`. `ctrl+b $` names the workspace on screen, and `×` beside it (or `ctrl+b X`) closes it. Its projects, machines, hosts, folders and tabs move to workspace 1 — what no workspace claims is workspace 1's, so they land there whatever you answer — and anything running in it is the one thing you decide: closing a workspace with agents or terminals of its own asks whether to **move** them to workspace 1, still running, or **end** them along with it, naming how many of each. A pane another workspace also shows — one in a shared project, or started by an agent in one — is never ended: it keeps running there. With nothing running, closing just asks to confirm. `x` on a project, machine or saved host takes it out of this workspace while another workspace has it, and otherwise removes it from the sidebar, removes the machine or forgets the host, as it always has. Workspaces are remembered in `ui.json` and shared: two conch windows open at once, and [Conch.app](/docs/mac-app), see the same workspaces — one made, renamed, given a project or closed in one shows in the others within a second — while each keeps its own tabs and the workspace it has on screen. - -The tab bar lists the tabs of what you select in the tree: a project shows its tabs, `Workspace` those of all the machine's projects, `CLI` the machine's own, and `Agents`, `Terminals` or `SSH` (or an agent or terminal in them) narrows to those. A tab with an agent waiting for your answer shows `!` before its name, in amber, as the tree does. A branch — or `Branches` — lists the tabs showing changes, not the project's agents and terminals. Each branch opens in its own tab and keeps it, so looking at another branch, or at the project's page, leaves it alone. `Branches` itself shows a page of every branch — including the ones the tree hides behind "… more" — with its worktree, uncommitted lines, pull request, how far it is from the base, and when it last changed. Clicking one opens its changes, listing it in the tree first when it was hidden behind "… more". `Agents`, `Terminals` and `SSH` show their own pages the same way — what runs in them, with state, branch and usage — and a click opens that pane. `Sessions` keeps its own view. A tab belongs to the group of its first split. Moving onto a project, its branches or Sessions shows that page — in the group's browsing tab if there is one, otherwise as a preview — while the bar keeps listing the group's tabs. The machine row has no tabs and shows its page as a preview too. On `local`, until you have tried them, that page also lists four steps under **Getting started** (add a project, give an agent a task, open the review queue, detach), each ticked off once done; the list goes away once all four are, and `x` on `local` hides it sooner. Which steps are done is kept in `ui.json`. A preview becomes a tab once you open, split or type into it. `ctrl+b C` opens the changes of the branch the focused split is on in a tab of their own, without walking the tree for it: from an agent's pane it is one key to the diff it is writing, and pressing it again goes back to that tab rather than opening a second. Splitting from a preview divides the tab you were on rather than the preview, so pointing at a branch and pressing `v` puts its changes in the new half **beside** what the tab already showed — an agent's pane on one side, the diff it is writing on the other. Splitting onto what the focused half already shows still gives an empty half to pick for, since one branch twice, or a pane typed into in two places, helps nobody. `ctrl+b c` opens a new tab with a terminal in it, in the folder the tree is pointing at (the `+` menu's **Empty tab** is there when you want one to fill yourself). `ctrl+b n`, `p` and the numbers move through the tabs listed; `ctrl+b w` lists every tab, grouped. Closing a split or a tab ends the agents and terminals in it, after you confirm, and a pane that exits (a shell's `exit`, an agent's `/exit`) closes along with its split or tab. Only a pane that fails within its first 10 seconds (a missing command, a bad flag) stays, marked exited, so you can read the error; `x` removes it. +Tabs work like tmux windows: every agent and terminal gets its own tab, and each tab can be split. | Keys | | | --- | --- | -| `ctrl+b %` or `v` / `ctrl+b "` or `-` | split right / down (beside a terminal or agent, the new split starts a shell in its folder; otherwise it waits for you to open something) | -| `ctrl+b ←→↑↓`, `o`, `;` | move focus between splits: by direction, to the next, to the last one focused | -| `ctrl+b {` / `}` | swap the split with the previous / next | -| `ctrl+b q` | show split numbers; press a number while they show to focus that split | -| `ctrl+b space` | next layout: even-horizontal, even-vertical, main-horizontal, main-vertical, tiled (`ctrl+b alt+1`–`alt+5` pick one) | -| `ctrl+b ctrl+arrow` / `alt+arrow` | resize by 1 / 5 cells; press the arrow again within half a second to keep resizing | -| `ctrl+b x` | close the split; an agent or terminal in it ends, after you confirm | -| drag a split's title | onto another split swaps the two; onto a tab in the bar moves it into that tab, and the tab it leaves closes if that was its last split; onto the `+` gives it a tab of its own | -| `ctrl+b c`, `n`, `p`, `0-9`, `l` | new, next, previous, go to, last tab (among the tabs listed for the tree selection) | -| `ctrl+b <` / `>`, `.` | move the tab left / right, or to a position you type (among the tabs listed); dragging a tab along the bar with the mouse does the same | -| `ctrl+b w` | pick any tab or split, grouped by project and CLI, with each split's branch or folder and agent state | -| `ctrl+b &`, `,` | close, rename tab | -| `ctrl+b N`, `(` / `)`, `$`, `X` | new workspace, previous / next workspace, rename it, close it (asks whether its agents and terminals move to workspace 1 or end) — also the `+`, numbers and `×` beside conch at the top of the sidebar (in [conch's own window](/docs/cli#app), at the left of the strip along the top) | -| `ctrl+b =`, `z` | equalize splits, zoom | -| `ctrl+b S` | type into every agent and terminal in the tab at once, like tmux's `synchronize-panes`; their borders turn amber and the status bar shows `SYNC`. Press it again to stop. | +| `ctrl+b %` / `ctrl+b "` | split right / down | +| `ctrl+b c`, `n`, `p` | new, next, previous tab | +| `ctrl+b z` | zoom | +| `ctrl+b /` | palette | | `ctrl+b d` | detach (agents keep running) | -| `ctrl+b !`, `:` | jump to the next agent waiting for you, ask the brain | -| `v` / `s` / `O` in the tree | open the selected item in a split right / below / a new tab | - -These follow tmux's default bindings; `ctrl+b 1` is the first tab and `0` the tenth. `ctrl+b !` jumps to the next agent waiting for you instead of breaking a pane out. -Drag a border between splits to resize. Tabs and splits are remembered in `ui.json`. +All keys: [Keys and mouse](/docs/keys). ## Scrollback and copying -The wheel over a pane scrolls back through its history (10,000 lines); the view stays on the same text while output continues, and typing returns to the live screen. - -`ctrl+b [` (or `ctrl+b pgup`) enters scroll mode with a cursor. It works in an agent's pane too: an agent draws on the alternate screen, which keeps no scrollback of its own, so conch watches that screen and keeps the lines that scroll off it — what it said a page ago is there to read and select. A program that repaints its whole screen instead of scrolling (an editor) leaves nothing behind, because nothing scrolled away, and the kept lines are plain text without their colours. - -| Key | In scroll mode | -| --- | --- | -| `↑↓←→` / `hjkl` | move the cursor (scrolling at the edges) | -| `0` / `$` | line start / end | -| `pgup` / `pgdn` | page | -| `g` | oldest line | -| `/` / `?` | search up / down | -| `n` / `N` | next match, the same way / the other way | -| `v` or `space` | start a selection | -| `y` or `enter` | copy the selection | -| any other key | return to live | - -`/` searches back through the whole history, `?` towards the live screen; the query is typed on the pane's bottom line. The view scrolls to the match and puts the cursor on it, so `v` and `y` select and copy from there, and every match on screen is highlighted. A query in lower case matches either case; one with a capital matches exactly. A search that reaches the oldest line (or the bottom) goes on from the other end and says so. Searching needs the pane's machine to run this build or newer. - -A pane that has history shows a thumb on its right border — where the screen is in that history, and how much of it there is — and dragging the thumb goes straight there. A border shared with another split resizes as before; the outer edge scrolls. - -Drag across a pane to select and copy; double-click copies a word, triple-click the line it is on — the text, not the padding, and the whole line even when it wrapped over several rows. What is copied joins the rows a long line wrapped over, so a command that reached the edge of the pane pastes into a shell as one command rather than two halves. A row that stops short of the edge ended there and keeps its newline; conch judges this by the row being full, since the terminal emulator does not record which rows were continuations. Hold the drag past the pane's top or bottom edge — over the tab bar or the status bar — and the history scrolls to take in more, or turn the wheel while the button is down; the copy has every line passed over, not just what is left on screen. The same works in an agent's pane, over the history conch keeps for it. Pages in a tab or split — a diff, a file, the sessions or branches list — select and copy the same way; a click that doesn't drag still clicks, and lands on release. Copies use OSC 52 (works over SSH) plus `pbcopy`/`wl-copy`/`xclip` locally. `y` copies a branch name or directory in the tree, a file path or the whole diff in the changes view. +Every pane keeps 10,000 lines of history, an agent's pane included. -Programs that use the mouse themselves (vim, htop) still get the mouse. **The wheel is conch's while a program is on the main screen** — an agent asks for the mouse to take clicks and does nothing with the wheel, so conch scrolls its own history rather than sending reports the agent would print into its prompt. On the alternate screen the wheel goes to the program, which keeps its own scrollback; full-screen programs that don't take the mouse get arrow keys from it. Hold **alt** or **ctrl** to send the wheel to the program wherever it is. - -Dropping files on a pane pastes their paths. On a remote machine's pane conch uploads the files there first and pastes their paths there — see [Dropping files on a remote pane](/docs/remote-machines#dropping-files-on-a-remote-pane). +**How:** the wheel scrolls; drag copies. `ctrl+b [` enters scroll mode: `/` searches, `v` selects, `y` copies. ## Watching a pane -Agents say for themselves when they need you. For anything else — a build, a test run, a server's log — watch the pane, as tmux's `monitor-silence` and `monitor-activity` do: - -- `ctrl+b M` alerts when the pane **goes quiet** after printing: a build or test run has finished. How long counts as quiet is 30 seconds, set under Settings → Notifications (10 s to 5 min) or `[notify] silence` in config.toml; it applies to panes watched from then on. -- `ctrl+b A` alerts when the pane **prints** while you are looking at something else. +Alerts for a pane that is not an agent — a build, a test run, a log. -Press the same keys again to stop, or use the pane's menu (`m` or right-click in the tree), where a tick shows what is on. A pane that has something to tell shows `~` (quiet) or `#` (output) in the tree and tab bar, and a desktop notification goes out as for agents (quiet hours and snooze apply). Looking at the pane clears it. Only a pane nobody has on screen raises an alert, a pane already quiet when you start watching it waits for its next output, and the watching survives a server reload. The server does the watching, so alerts are waiting in the tree after you detach and come back. - -## Resource monitor - -Click `▁▃▆` in the bottom-right corner of the status bar to see how much memory and CPU conch uses on this computer: - -``` -╭─ monitor ──────────────────────────────────────────────╮ -│ memory cpu │ -│ This window (TUI) 30 MB 50.0% █████░░░░░ │ -│ Server · pid 100 20 MB 50.0% █████░░░░░ │ -│ Panes (2) 319 MB 150.0% ██████████ │ -│ claude 315 MB 150.0% ██████████ │ -│ zsh 4 MB 0.0% ░░░░░░░░░░ │ -│ Total 369 MB 250.0% ██████████ │ -╰────────────────────────────────────────────────────────╯ -``` - -- A pane's row counts everything running inside it — the agent and the tools it starts. Panes are listed largest first; after 8 the rest share one "N more" row. -- The total counts each process once, even when this TUI runs inside a conch pane. -- CPU is worked out between two readings, so it shows `…` for the first 2 seconds. 100% is one full core, so a busy agent can go past it. The number and its bar are green, amber from 80% and red from 200%; the colours follow the theme. -- It refreshes every 2 seconds while open, reading `ps`, and stops when closed. Any key, a click outside, or clicking the icon again closes it. The icon stays dim until the box is open. -- It covers this computer only, not remote machines. - -### A job that takes minutes - -Making a [sandbox](/docs/sandboxes) or adding a [machine](/docs/remote-machines) means installing conch at the other end: a minute or two of copying and connecting. The status bar shows what it is doing, with a spinner — *copying conch to hull (16 MB)…* — and keeps showing it until the job ends, rather than flashing once and leaving you to wonder. Whatever ends it, a machine in the tree or a reason it failed, takes the line away. +**How:** `ctrl+b M` alerts when a pane goes quiet, `ctrl+b A` when it prints. ## Links an agent printed -An agent that wants you to log in prints a URL and asks you to open it — and inside a sandbox or a remote machine, it has to be opened *here*, not there. Selecting it with the mouse rarely works: the URL is longer than the pane, so the agent wraps it inside its own box, and the selection comes back with the border and the line break in the middle of it: - -``` -│ …&scope=user%3Asessio │ -│ ns%3Aclaude_code&code… │ - -Invalid OAuth Request · Unknown scope: user:sessio│ns:claude_code -``` - -`ctrl+b u`, or `m` on the pane → **Open a link it printed**, lists the links on the pane's screen with each one put back together: the box's borders and padding taken off, and the rows the link ran across joined. Choosing one opens it in this computer's browser *and* puts it on the clipboard, since a login URL often has to go somewhere else — a phone, another browser, someone else's machine. - -Clicking one opens it too: hold **alt** (option on a Mac) or **ctrl** and click a link, and conch opens it and copies it. It opens when you let go where you pressed, a moment after (the time a double click takes): alt or ctrl with a **drag** is also how text is selected over an agent that took the mouse, so dragging across a link — or double-clicking it — selects and copies it and opens nothing. A plain click never opens one, in any pane: it starts a selection, or goes to the program when that program asked for the mouse — an agent's own interface, vim. With **[ui] hover** on, a link under the pointer is underlined while alt or ctrl is held, which is when a click would open it; the terminal reports the key only as the pointer moves, so hold it and move onto the link. **In Ghostty and kitty the pointer itself becomes a hand**, as it would in a browser: conch asks for it with `OSC 22`, the one escape for this that terminals have. iTerm2 and Terminal.app have no such escape — iTerm2 shows a hand for a link of its own finding, with cmd held — and tmux does not pass it on, so there the underline is all of it. `CONCH_POINTER=1` asks anyway, in a terminal that supports it and is not named here; `CONCH_POINTER=0` stops conch asking at all. - -**Not cmd+click**, which is what a Mac asks for first. The mouse protocols a terminal speaks carry three modifier bits — shift, alt and ctrl — and cmd has nowhere to go in them, so no terminal can report it to conch whatever it wanted to. iTerm2 and Terminal.app keep cmd+click for their own URL opening, which works on conch's screens as it does anywhere else; alt or ctrl is what reaches conch. A link that wrapped over several rows opens whole either way, the same reading that `ctrl+b u` does. +A login URL an agent wrapped inside its box, put back together and opened in this computer's browser. -It goes by shape, since the agent did the wrapping and left no mark to read: a row that fills the screen may have run on, and the next row is the rest of it when it keeps the same left edge. That can be wrong — prose directly under a full-width link would lend it a word — so the whole link is shown before anything is opened, and at most nine are offered. A 400-character OAuth URL in a narrow pane is followed over as many rows as it takes. A link that has scrolled away comes back with `ctrl+b [` first. +**How:** `ctrl+b u` opens and copies a link, rewrapped whole; or alt-click it. ## Settings -Press `,` or click `⚙` at the right end of the status bar. Changes are saved to `~/.config/conch/config.toml` (see [Configuration](/docs/configuration)). - -### Edit in browser - -`e` on any tab of Settings, or a click on **↗ Edit in browser** under the list, opens every setting in `config.toml` as a form in your browser — including the ones the screen only names: [custom actions](/docs/configuration#actions), [permission rules](/docs/configuration#permissions), each project's check command and every sandbox provider's table. Each section has its switches, menus and fields with what they do beside them; a search box narrows them; a dot marks what you have changed; and **Save** (or `⌘S`) writes the file. The **config.toml** tab is the file itself, saved as you type it, comments and all, once conch can read it. - -The page is served by the TUI on `127.0.0.1` for as long as it runs, behind a key made fresh for each TUI and carried in the address, so nothing else on the network reaches it. A save is handed straight to the TUI, which applies it — the theme at once — as a change on the Settings screen would. If something else wrote `config.toml` after the page read it, the save is refused and the page offers the newer version, so neither overwrites the other. `conch config web` serves the same page without a TUI. - -### Theme +Theme, notifications, agents, sandboxes and the rest. -Colour schemes: Conch, Dracula, Catppuccin Mocha, Nord, Gruvbox Dark, Tokyo Night, One Dark, Solarized Dark, Rosé Pine, Kanagawa, Everforest Dark, Monokai, GitHub Dark, Ayu Dark, Night Owl, VS Code's Dark Modern and Dark+, and conch's own Firefly (a meadow at night), Cel (flat cel-shaded colour) and Terminal (conch's teal on a terminal's ink black, after herdr), JetBrains Dark (IntelliJ's New UI), and nine light ones for a light terminal: GitHub Light, Solarized Light, Catppuccin Latte, and conch's own Ink (black ink on paper, one spot red), Meadow (sky, grass and sun on warm paper, Firefly's daytime) and Terminal Light (Terminal on paper), JetBrains Light, and VS Code's Light Modern and Light+ (applied instantly). +**How:** `,` or `⚙`. Saved to `config.toml`: [Configuration](/docs/configuration). -Under **Tree**, _What agents spend_ shows or hides the cost (and the token counts that stand in for it) on tree rows, in Sessions and on the project and machine pages — everything [the sidebar](#the-sidebar) shows. - -**Light what the pointer is on** tints the tree row or tab under the pointer. It needs the terminal to report every pointer move rather than only drags, which is a message per cell crossed — nothing on this computer, more over a slow ssh link — so it is off by default and applies to conch windows started afterwards. Nothing a program in a pane receives changes: a move with no button held is conch's own. +### Edit in browser -Under **File icons**, how [the file explorer](#files) marks each kind of file: _Letters, in any font_ (the default), _Nerd Font glyphs_ for a terminal with a Nerd Font, or _None_ (`[ui] icons` = `text`, `nerd` or `off`). +Every setting in `config.toml` as a form in your browser. -Below that, an **Oh My Zsh prompt theme** for zsh terminals, picked from the themes installed on this computer. Each theme shows **the prompt it draws** beside its name, in its own colours: conch asks zsh to expand it, in an empty folder that is no repository, so a git-aware theme shows its plain form. A prompt of two lines is shown on one, a long one is cut to fit, and a theme zsh could not expand simply shows nothing. conch starts zsh with a wrapper that loads your own `.zshenv`/`.zprofile`/`.zshrc`/`.zlogin` first and then switches the theme for that terminal only (`omz theme use`), so your dotfiles are never edited; "Keep my .zshrc theme" turns it off. Terminals already open follow a theme saved later — from here, the settings page, Conch.app or an editor: the server notices `config.toml` change and nudges each zsh it started with `SIGURG`, which the wrapper answers by taking the theme and redrawing the prompt where it is, nothing typed. A zsh conch did not start (one run inside a terminal, or a terminal opened before this version) ignores the signal and keeps its prompt; a terminal on another machine follows that machine's settings. +**How:** `e` in Settings, or `conch config web`. ### Notifications -- A master switch. -- How: desktop notification, system sound, terminal beep. -- When: an agent is waiting, one finishes, and/or a plan limit is nearly used (Claude's or Codex's 5-hour or weekly window passing 80% and 95%, once per window); and how long a [watched pane](#watching-a-pane) must be quiet. -- **Quiet hours** (22:00–08:00 and other presets, or any `quiet_start` / `quiet_end` in config.toml) and **snooze for an hour**. While silenced the status bar shows `🔕` (click it to resume); waiting agents still show in the sidebar. -- Send a test. - -### Agents - -The default agent chosen here is what `c` pre-selects and what tasks use. Until you choose one it is Claude Code — or, on a machine without Claude Code, an agent that machine does have (one conch supports before one of your own), so `c` starts Codex for somebody who installed only Codex rather than offering to install Claude Code. Under **Agents on each machine**, one row per machine saying how it stands — *all 4 installed*, *1 installed · 1 not*, *offline* — which opens a page of its own with each supported agent and its version, or *not installed · enter installs*; `esc` or the `‹ Agents` row goes back. A machine is a row rather than a section so the tab still fits a small window. - -Under **What each agent loads**: a line saying that a *checkout's* setup lives on its own rows (`i` on a project, branch or pane, and `s` there), and **Your own setup…**, which opens a page of its own — one row per agent to take the setup from, and **Put the last one back…** — rather than putting an action per agent on a tab that is long enough already. Both say what they would write before writing it. See [One setup, every agent](/docs/tasks#one-setup-every-agent). **conch's own skill…** is the third row: whether each machine's agents carry the skill that teaches them conch's commands, and installing or removing it there — planned first, with every path named in the question. See [Agents working together](/docs/agents-together). +A notification, sound or beep when an agent waits or finishes, or a plan limit is nearly used. -**Shared MCP servers & skills…** opens the library: a row per server and skill, with a column per agent (`Cl` Claude Code, `Cx` Codex, `Gm` Gemini, `Oc` OpenCode, `Dv` Devin) marked `✓` has it, `+` Apply writes it, `−` Apply takes it out, `·` off, `○` set by hand, `!` declared differently by hand and left alone, `✗` cannot. What an agent cannot be given is said on a line under the row. `enter` on a row edits it — its command or URL, its variables, a box per agent, and Remove; **Add a server…**, **Add a skill…** and **Take an agent's into the library…** add to it; **Apply…** shows every write before making it, and **Put the last one back…** undoes the last apply. See [Shared MCP servers and skills](/docs/tasks#shared-mcp-servers-and-skills). - -Under **Remote machines**: whether files dropped on a remote pane are uploaded there, and the largest file to upload (10, 25, 50, 100 or 250 MB). See [Dropping files on a remote pane](/docs/remote-machines#dropping-files-on-a-remote-pane). - -### Sandboxes - -The providers conch knows, each saying whether its key is there to be found (`✓ $DAYTONA_API_KEY is set`, or `no key · $BOAT_API_KEY is not set`). Enter, or a click, opens one; `esc` (or the `‹ Sandboxes` row) goes back to the list. Every provider takes the same settings, saved under its own name in `[sandbox.]`, so the tab lists them rather than growing a section with each one conch learns. - -| Setting | What it does | -| --- | --- | -| **API key** | the key itself, if you would rather keep it here than in your environment. It is written to `config.toml` (0600) as it is, so anything running as you can read it and it travels with a backup or a synced dotfile; the row shows only its last few characters. Empty leaves it to the variable below | -| **API key variable** | which variable of your environment the key is read from when none is kept above; empty means the provider's own, `DAYTONA_API_KEY`, `BOAT_API_KEY` or `DEVIN_API_KEY` | -| **Snapshot** | what new sandboxes start from; empty means the provider's default. For boat.dev this is also where a machine size goes — `small`, `default` or `large` — since its machines are sized by name | -| **Region** | where they are made, e.g. `us` or `eu`. boat.dev has no regions and ignores it | -| **Platform** | Devin Cloud's in place of Snapshot and Region: where new sessions run — an OS your organization offers, such as `windows`, or an outpost pool. Empty means the organization's default | -| **Bring back what was running** | on by default: when a sandbox stops, conch writes down its agents (with the conversation each was on) and its terminals, and offers them back when it starts again. Off keeps no note at all | -| **Stop when idle** | 30 minutes by default, or 15, 60, 120, or never. conch watches for an agent working and for panes printing, and pauses the sandbox when neither has happened for that long — its files, and where the provider can its memory, are kept. A provider's own timer sees only what reaches it from outside, so it would stop an agent working quietly; this doesn't | -| **Life** | only for a provider that gives a sandbox a fixed life rather than stopping an idle one (boat.dev): how long a new one is given, in minutes, counted from when it was made. Empty means the provider's own — two hours for boat.dev, which is what its free trial allows. A plan that allows less says so, and conch asks again for the longest it named | -| **Price an hour** | what an hour of a sandbox costs — per vCPU, per GiB of memory, per GiB of disk — so the tree can say what one has run up, and what a stopped one still costs for the disk it keeps. Empty shows running time alone; conch ships no price list | -| **Pass in** | names of your environment variables to put into every new sandbox — an agent's token, say — separated by spaces or commas. Names only: a `NAME=value` is refused. The dialog that makes a sandbox can add more, for that one only | - -### Actions - -What `[[actions]]` in `config.toml` puts on the row menus, read only: each one's name, command, the rows it is offered on, and whether its terminal closes when the command is done. Below them, under **Not offered**, anything conch is leaving out and why — an action with no name or no command, two with the same name, an `on` that is not one of `pane`, `branch`, `project`, `machine`. Nothing here is conch's to edit: an action is your own command. See [`[[actions]]`](/docs/configuration#actions). +**How:** `,` → Notifications: when, how, quiet hours. diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 0f76af1f..bc1fd0dc 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -1,254 +1,158 @@ -export const metadata = { title: "Mac app", description: "conch in a native macOS window: the tree, tabs and splits, panes drawn by Ghostty where it is built in, a branch's changes, sessions, commits, and answers on a waiting agent." } +export const metadata = { title: "Mac app", description: "conch in a native macOS window: the tree, tabs and splits, a branch's changes, files, sessions, the workbench and answers on a waiting agent." } # Mac app -Conch.app is conch in a native macOS window. It is another client of the same servers the TUI talks to — this computer's and every machine you added — so it shows the same agents and terminals, and closing it stops nothing: the agents keep running, as they do when you close the TUI. - - - -The Mac app is in **beta**, and says so: it is **Conch (Beta)** in the menu bar, the Dock and Finder. Download it from the release (below), or build it from source. A few things are still the TUI's alone: syncing one agent's setup to another, your own folders inside a project, and a project's check and the server's scheduled tasks in the review queue. **conch → Run in Terminal** opens the TUI beside the window, in a terminal of its own. The first time it opens, a short **welcome** walks through the sidebar, starting work, answering agents, search and other machines, with the keys for each; **Help → Welcome to Conch** shows it again. - - +Conch.app shows the same agents and terminals as the TUI in a native macOS window; closing it stops nothing. +The Mac app is in **beta**; a few things are still the TUI's alone. + + + Answer a waiting agent from the sidebar. + Diff, commit hunks and leave the agent notes. + Edit a checkout and resume saved conversations. + An agent's files, terminal and chat in one tab. + A dev server's page beside the agents. + The project's commit graph. + + ## The window -- **The toolbar** holds conch's workspaces (click one to switch — on the press itself; the one under the pointer lights up, its tooltip says what runs in it, and an amber dot marks one whose agent is waiting for you; `+` makes one, as in the TUI, which shows it too; double-click or right-click one to name it — `1 main 2 review` — which the TUI shows as well; right-click → **Close Workspace…** or **File → Close Workspace…** for the one on screen, on any but the first, closes it as the TUI's `ctrl+b X` does, its projects, machines, hosts and tabs going to workspace 1 and what runs only in it moved there or ended, as you choose) — each isolated as in the TUI, with tabs of its own and only what is in it: its projects, the panes started in it and what those started, the ssh hosts saved in it (and the SSH folders holding them), the machines added in it or holding any of that, and in the first whatever no other workspace has; an agent or terminal started from the app, a host saved or a machine added goes into the workspace on screen, and a machine's right-click → **Machine Already in conch** brings one another workspace has into this one, a search field in the middle (⌘K), and how many agents in that workspace are waiting for you or finished, dimmed at none rather than gone — a click on the waiting count goes to the next one (⌘.), and on the done count to the next agent that finished — the machine of what is selected — the sidebar's row, else the tab in front: *This Mac*, *busybox · remote*, *bot · Conch Cloud* — since a folder, a file, a branch or an agent looks the same on every machine, then **N to review**, the TUI's review queue counted on every machine: agents waiting or finished, branches whose pull request's CI failed, with commits not pushed or merged, or with uncommitted work and no agent on it, leaving out rows dismissed in the TUI. A click lists them, the most urgent first; a row opens its agent or the branch's changes. **Fix**, on a row whose pull request's CI failed, sends the failure to the branch's agent (or starts one in its worktree with it), as `f` does in the TUI's queue (`conch branch fix-ci`); **✕** dismisses a row until it changes, as `x` does — kept in `ui.json`, so the TUI leaves it out too. A row's right-click menu has the same. A project's own check and the server's scheduled tasks are in the TUI's queue only. -- **The sidebar** is conch's tree: this computer, then each machine you added (`conch machine add`), each with its projects under **Workspace**, as in the TUI — agents, branches, terminals and how many saved sessions — and **CLI** for what belongs to no project. The Workspace row folds as the TUI's does, and its menu starts a task in any of its projects. Each agent is marked as the TUI marks it, following the same `[ui] icons`: with `icons = "nerd"` the TUI's glyph in the agent's own colour (Claude's asterisk, Codex's six-fold mark…) from a Nerd Font on the Mac, or an SF Symbol of the same shape without one; otherwise a dot in the agent's colour, the mock's, or nothing for `off` and, at the right, its branch (muted, as the TUI's row has it, cut in the middle when it is long) and a pill while it is **working** (with the TUI's spinner turning in it), **waiting** for you or **done**; a tab with an agent at work shows the spinner beside its name; a pane that ended says **exited**. A machine or project row counts what is working (blue), waiting (amber) and done (green) in pills; the tree's icons are Lucide's, the outlines shadcn/ui draws: this computer a laptop, another machine a server and a sandbox a cloud, each with its state as a dot on the corner (green online, amber connecting, grey not there); a project a folder, open while it is; a branch git's branch, in the accent when it is checked out in a worktree of its own, muted when not, with its pull request and how far ahead it is; a terminal `>_`, an ssh session a globe; CLI a terminal in a box; Workspace layers; Sessions a history clock. The pane you are in is the row with the accent behind it, and the row under the pointer is tinted. Another machine is reached as the TUI reaches it, through [`conch machine bridge`](/docs/cli#machine); one that cannot be reached says **offline**, with why on hovering, and is tried again every half minute. A sandbox is listed with its provider (`sandbox · daytona`) and says **stopped** while it is; the app never starts one by itself and looks again every five minutes. **New Sandbox…** (**File** menu, ⌘K, or a machine's right-click menu) makes one, as the TUI's `M` → **New Sandbox…** does: pick a provider — one without its API key is shown greyed with what to set, and **Sandbox settings…** is where it goes; **Add a provider…** [adapts one conch doesn't know](/docs/sandboxes#a-provider-conch-doesnt-know) from its API docs, showing the agent writing the file, then what conch will call for what and the file itself, and saving it only when you say — give it a name and a snapshot and size (or the size or place the provider takes instead), and `conch sandbox -provider P create` runs in a tab of its own, so the install can be watched; the sandbox joins the sidebar when it is ready. Its row's menu starts it (**Start Sandbox**), stops it (**Stop Sandbox…**, after asking: its agents and terminals stop with it), says **What It Has Cost** period by period, and deletes it for good (**Delete Sandbox…**, after asking) — each `conch sandbox` with its provider. Rows fold as they do in the TUI — the same rows open, read from its `ui.json` — and what you fold or open here is remembered by the app without changing the TUI's. A folded machine shows the dots of the agents on it. A project lists the branches the TUI lists: the main checkout's first, those checked out in a worktree, the base and those a pane works on, then up to twelve committed to in the last two weeks; the rest are counted in a **… N more** row, which lists them all when clicked, and **Show fewer** puts them away again. A click opens a pane; a click on a branch opens its changes (below). Drag the sidebar's edge to make it wider or narrower; the width is remembered. With the pointer on a project or a machine, or the keyboard on it, three buttons take the place of its counts: **+** (a **New Task…** in a project, **Add Project…** on a machine), the robot — **Start an Agent**, a menu of the agents installed there with **Terminal** at its foot, started in the project or, on a machine, in its home — and **⋯**, the row's whole menu, the one a right-click opens; a machine that is offline keeps only **⋯**. **Workspace** has them too — **+** Add Project…, the robot a **New Task** in one of its projects, ⋯ with **Collapse All Projects** — and so does **CLI**: a folder button (a **New Folder** in Agents, Terminals or SSH), the robot with **SSH to a Host…** under **Terminal**, and ⋯. A project on this Mac's menu also has **Reveal in Finder**. Right-click a project → **Remove Project…** takes it off the sidebar, as the TUI's `x` does: out of this workspace alone when another workspace has it too, else out of conch altogether — its folder, branches and worktrees are never touched, its running agents and terminals move to **CLI**, and `conch project add` brings it back. -- **Skills & MCP Servers** — a section of **Settings** of its own (or **Skills & MCP Servers…** on a machine's right-click menu, which opens it on that machine), with a picker for the machine when there is more than one, since both halves are written to the agents' folders there through that machine's server: - - **conch's skills** — `conch` (start another agent, prompt it, read its answer), `conch-team`, `conch-review`, `conch-ship`, `conch-factory` and `conch-autopilot` ([agents working together](/docs/agents-together)). Where the machine stands (*✓ every agent has them*, *1 have them · 1 not*, *missing some · an older install*, *not installed*, or why it can't be asked), then each agents' folder with each skill in it. **Install for every agent…** and **Take conch's copies away…** name every path in a question before anything is written, as `conch agent skill` plans before `-apply`; a skill of yours of one of those names is left alone. Each skill's row has its own **Install** or **Remove**, for that one skill alone, where the machine's server can pick (`agent.skill.pick.v1`). - - **Your MCP servers & skills** — the [library](/docs/tasks#shared-mcp-servers-and-skills): servers and skills of your own kept in conch and given to the agents you tick. A row per server and skill with a column per agent (✓ has it, + Apply writes it, − Apply takes it out, ○ set by hand, ! differs, ✗ cannot — hover a mark for why); a click on a mark ticks or unticks that agent. **Add a skill…** takes a folder holding a `SKILL.md` (**Choose…** on this computer) or, under **From GitHub**, a skill shared there (`owner/repo/path/to/skill`), which that machine's server downloads into its library — **Fetch again** brings it up to date, **Add a server…** a command or URL with its environment and headers as `NAME=${VAR}`, **Take an agent's in** starts from what one agent has, and **Add conch's own tools** is `conch mcp` for every agent. Nothing is written to an agent until **Apply…**, which names every write first; **Put the last one back…** undoes it. -- **Conch Cloud** — **Settings → Conch Cloud**: the server to sign in to (`[cloud] api`, empty for Conch Cloud itself), then **Sign in…**, which runs `conch login` and shows the code while your browser opens the page to approve it; once signed in, who you are, the plan, this month's running hours and storage, this device, and **Sign out**. Below, the account's machines with their size, provider and state — running, asleep, waking, creating, or error with why — **Wake** or **Sleep** each, and a link to manage it in the browser, read again every few seconds while the section is open. Before anyone signs in nothing is asked of Conch Cloud at all. The account's machines are in the sidebar too, named `box · cloud`, reached like every machine through `conch machine bridge`; one asleep says so on its row rather than offline, and its right-click menu has **Wake** (or **Sleep** while it runs) and **Delete Machine…**, which asks first and then destroys the machine and its disk (`conch cloud machine rm`): work there that is not pushed goes with it. See [Conch Cloud](/docs/cloud). -- **Notifications.** When an agent comes to wait for an answer or finishes and you are not looking at it, Conch.app posts a notification — a click on it opens the agent — and the Dock icon carries how many agents are waiting, on every machine, bouncing once when one starts waiting while the app is in the background. It follows `[notify]` in config.toml as the TUI does: `enabled`, `desktop`, `sound`, `waiting`, `done` and the `quiet_start`/`quiet_end` hours. A plan nearly used up is said the same way: when an agent's 5-hour, weekly or spend window passes a percentage in `limit_at` (80 and 95 unless you set others; `limits = false` turns it off), a **conch · plan limit** notification says which agent, how much is used and when it resets — once per percentage per window, again after the window resets — and the status bar says it too, red from 90%. With a TUI open on that machine the notification is left to the TUI, so it is not said twice. macOS asks once whether conch may post them (System Settings → Notifications); where it may not, the system's own notification is shown instead. -- **Marks and icons.** Agents are marked by their own logos — Claude, Codex and Gemini from Simple Icons; Grok, Devin, Amp, Kilo Code, OpenCode and Cursor from LobeHub's icons — filled in each agent's colour, or in the theme's text colour where that would vanish into the background (Grok's white on a light theme), in the tree, the tabs and the pane headers. An agent with no logo there (Aider, Pi, your own) keeps the mark `[ui] icons` gives it, and `icons = "off"` shows none. Agents, Branches and Terminals each have an icon, as Files and Sessions do. -- **What a row says.** A branch says what the TUI's does, part by part: its agents' state (`!` waiting first), conflicts (`⚠2`) or its uncommitted changes (`+3 −1`, or `~4` files), its pull request (`#7✓` passing, `#7✗` failing, `#7●` pending, merged in purple, `×` closed, a draft muted), and `gone`, or how far it is ahead of and behind the base (`↑2↓1`; the base itself against its upstream, `⇡1⇣2`). A pane that ended says how — `exited`, or `exit N` and `failed` in red — and a terminal watched for it carries `# output` or `~ quiet`. Watch one from its menu — **Alert When It Goes Quiet** (for `[notify] silence` seconds after printing, 30 by default: a build or a test run ending) or **Alert on Output** — as the TUI's `ctrl+b M` and `A`; an alert raised while you are looking elsewhere is also a notification, and looking at the pane clears it. -- **What agents spend.** Each agent's row, and the machine, project and Agents rows for what they hold, carry what the agents have spent as the TUI's do — a cost where the agent reports one (Claude Code and OpenCode), else the tokens written (`42k out`), else read — and an agent's pane header says its context against the model's window, its output and cost (`ctx 45k/200k · out 1.2k · $0.42`). Only what conch has seen is counted. `[ui] cost = false` turns it off here and in the TUI. -- **Helpers and subagents.** A pane an agent started — a helper it handed work to — is listed under that agent, and so is each subagent it runs in its own process (Claude Code's Agent tool, a spinner and the task it was given), as in the TUI. The arrow folds them; a click on a subagent shows its agent, since it has no screen of its own. A section's count is every pane in it, the nested ones included. -- **Find in a pane.** ⌘F opens a find bar over the focused pane. Return looks back through its whole history for the text and brings the match into view with every match on screen marked, as `/` does in the TUI's scroll mode; ⌘G looks further back and ⇧⌘G forward again. A query in lower case matches either case. Esc closes it and clears the marks. Shift-Page Up and Page Down scroll a pane's history from the keyboard, and shift-Home and End go to the top and back. -- **Links.** ⌘-click a link a pane printed — an agent's login URL, a dev server's address — to open it in your browser; web and mail links only, never `file:` or a custom scheme. A plain click still goes to the program, as before. -- **Dropping files on a pane.** Drag files from the Finder (or an image from a browser or a screenshot's thumbnail, which is saved as a PNG first) onto a pane and their paths are pasted into it, escaped as Terminal escapes them — what an agent needs to read a screenshot. On another machine's pane the files are copied there first (`conch -m MACHINE upload`, into its uploads folder) and the paths they landed at are pasted instead, as the TUI does with a drop. A paste with a line break into a program that does not tell a paste from typing — a plain `bash`, a Python prompt, `cat` — runs each line as soon as it lands, so the app asks first (**Paste 3 lines?**) and shows what it holds; shells such as zsh and the agents take a paste as one and are not asked about. -- **On opening**, the window shows the tabs the TUI is showing (each machine's, as its server keeps them), a tab of three panes as one tall beside two stacked — and gives none of them the keyboard, so no key reaches an agent until you click a pane. -- **Tabs** along the top, the one on screen underlined, each with its number for `⌘1`–`⌘9` and **⊞** when it holds more than one split. Each pane's header ends with its ID in a small outlined chip, before its state — a click copies it. A tab's tooltip names its pane's ID — `p12`, or `busybox:p12` on another machine, what `conch read` takes — and its right-click menu has **Copy Pane ID**, as a pane's row in the sidebar does; ⌘K finds a pane by its ID too. Drag a tab onto another to move it there; double-click one, or right-click → **Rename Tab…**, to name it (an empty name goes back to naming it by its pane) — a tab taken from the TUI keeps the name the TUI gave it. A pane is shown in one place: opening it again goes to where it is. A pane whose program exits on its own — a shell's `exit`, an ssh logout, an agent's `/exit` — closes, and its split or tab with it, as in the TUI; one that fails in its first seconds stays, so its error can be read. **Settings → Mac app → Tabs** (`[app] tabs`) puts them down a side instead: on the **left** they sit at the top of the sidebar, grouped under each machine (*This Mac*, then each machine by name) with the tree below them, so a tab on another machine reads as one before it is opened; on the **right** they are a column of their own. Down a side each row is a tab — its number, its agent or kind, its name, **⊞** and the number of its splits, and what the agents in it are doing: a spinner while one works, an amber dot while one waits for you, ✓ when one has finished — and the line above the splits says which tab is on screen and where. -- **Splits** sit side by side as cards with a gap between them, each with a header saying which agent it is, its branch and its state — with how long it has been working. A terminal in a checkout that has been given ports shows the first, `CONCH_PORT` (`:4317`); on this computer a click opens it in a browser tab, ⌥-click in your own browser. The focused one has the accent border. Drag the gap between two splits to resize them; ⇧⌘↩ zooms the focused split to the whole tab and back, and ⌥⌘ with an arrow moves the focus to the split that way. The tab bar ends with where the tab on screen is (`api · local`). A pane whose programs listen on a TCP port — a dev server started there, however deep under the shell — shows it in its header (`:4317 ↗`, found every few seconds by the server, `pane.listening.v1`), taking the place of `CONCH_PORT`; a click opens it in a browser tab beside the agents (⌥-click: in the browser you use), and on another machine copies the ssh tunnel that brings it here (`ssh -N -L 4317:localhost:4317 host`). **Settings → Mac app → Ports in pane headers** turns them off. With **Density** compact the header is shorter and the splits sit closer. -- **The status bar** says where the keyboard is (**PANE**, or **TREE** when no terminal has it) and the keys for there, each as a keycap — or, for a few seconds, what was just done or why it could not be (a failure in red; a click puts the keys back), and while a long job runs (a reload, an upgrade, a push) what it is doing beside a spinner. Closing a split that holds a working agent says the agent goes on running and where to find it: a split or tab closed in the app only hides its panes; each agent plan's use, as a chip with the agent's mark and each window's bar and share (`✱ 5h ▰▱ 36% │ 7d ▰▱ 19%`, amber from 80%, red at the limit; when each resets is in its tooltip) — a click lists every window the agent reported, the 5 hours, the week and any per-model one, with when each resets; **✦ Ask**, conch's brain bar — a request in plain words, its plan shown, and nothing run until **Run** (it is `conch ask`, answered through its own confirmation, so what runs is the plan shown). Under the request it says what it applies to and how many agents are waiting or working, and lists what is worth asking now — what is waiting, each waiting agent, the agent in front, everyone, a project — and your recent requests, each saying whether conch answers it at once or the model plans it, as the [TUI's](/docs/brain#asking) does (`conch ask -suggest`). ↑↓ choose one, ↩ or a click asks it, ⇥ puts it in the box to finish; *this* and *here* mean the pane in front; **⊙**, report a problem — the facts `conch bug` gathers, never a path or a screen, and **Open a GitHub issue** with them for you to read before submitting; the phone, pair a phone — a one-time code with its QR code (`conch web pair`), **Full**, **Reply** or **View** for what it may do, and **Start it** when the gateway is not running (`conch web start`); conch's version, with which terminal draws the panes in its tooltip; **⚙ Settings** (or **conch → Settings…**, `⌘,`), which opens conch's settings in a panel of the app's own — the [settings page](/docs/interface#edit-in-browser)'s sections down the left in groups — **General** (Appearance, Mac app, Keys, Notifications, Updates), **Agents** (Agents, Skills & MCP servers, Permission rules, Brain), **Workspace** (Git, Terminals, Actions) and **Machines** (Remote machines, Sandboxes, Phone) — with a search (`⌘F`) that finds a section by any of its settings, and the chosen one's settings on the right in cards, drawn from the same schema and saved through the same page. Each setting gets the control that suits it: a switch; a few choices side by side; a menu with each agent's mark and a search; − and + for a number; a slider for the window's text size; a dot per accent colour; pictures of where the tabs go; **Record** for the prefix key, which you then press; fields that say what is wrong as you type (an address, a time, a variable's name); chips for the plan-limit percentages; the quiet hours drawn across the day; and **Git**, which holds everything git: how conch merges, then **Checks & autopilot** — the line a finished branch takes (check, review, pull request, fix CI, merge, each step clicked on or off), the check command each project runs (picked from your projects), then the checks and the autopilot's own settings. **Remote machines** lists the machines conch reaches, as **Phone** lists the phones paired: this Mac first, then each machine — turned-off ones too — with its ssh target or sandbox provider, its conch version and whether it is online, connecting, offline, stopped or on an older build (with **Reload** or **Upgrade** beside it), and a menu to **Reconnect**, **Reload Server**, **Upgrade conch There**, **Rename…** or **Remove…** it; **Add a Machine…** is at the top of the list. A changed setting is marked *edited*, its section shows how many, and a bar rises with **Revert** and **Save** (`⌘S`; a file changed meanwhile is read again rather than written over; an open TUI takes in what you save, and the app's theme follows it unless you picked one). **Brain**'s **Model** and **Summary model** are menus of what the provider offers — the Claude Code CLI's aliases (opus, sonnet, haiku) and models by name, the Anthropic API's own list when its key is set, an OpenAI-compatible endpoint's (Ollama, LM Studio) as it answers — the small ones first for summaries, and any other name can still be typed; when the list is only the known names, it says why (a key not set, an endpoint not answering). **Appearance → Icons** draws the sections' icons in Lucide's outlines or the Mac's SF Symbols, line or filled — a card each, the pointer on one trying it in the sidebar — and **Plain**, **Tinted** (each section a colour of its own) or as **Tiles**, white on a square of that colour, as System Settings does; they are `[app]` settings, kept with the app's, and the window's sidebar follows them once saved — its machines, workspace, projects, branches, terminals, Sessions and Files (agents keep their own marks). **Terminals → Oh My Zsh theme** is a menu of the themes installed on this Mac, yours in `custom/` too, or a name typed, each with its prompt under its name, and the chosen one's (or the one `.zshrc` chooses) under the field: conch draws each with zsh in a home of its own, in a checkout `~/my-project` on `main` with a change, so what a theme says about git shows — your `.zshrc` and git config are not read, a theme that takes over three seconds says so, and powerline's arrows are drawn in a Nerd Font or Powerline font when one is installed, else as plain arrows. Saving it changes the zsh terminals already open as well as new ones, each redrawing its prompt in place. **Actions**, **Permission rules** and **Sandboxes** are lists: each action or rule is a card headed by what it does (*deny* `Bash git push --force*`, a rule's agent and project under it), opened with a click to its fields, removed with its bin, and **Add** starts a new one open; rules are numbered and move up or down with the arrows, since the first that matches answers; a sandbox provider is added from the ones conch knows or by name. A map is a list of pairs — a project's check command, a key rebound under **Keys** (its action picked from those conch has) — each changed in place or removed, and added from the row at its foot. All of it saves with the rest, and **Edit config.toml** at the foot of the sections opens the file in your text editor (the app never sends you to a browser for settings); and `▁▃▆` in the corner, the memory and CPU conch uses on this computer — the app, the server and each pane with everything running in it — sampled every two seconds while it is open, as the TUI's is. A pane repainted from conch's screen rather than drawn by Ghostty (an older server, or a build without Ghostty) says **repainted** there when it is in front; a pane Ghostty draws says nothing. The usage chip — or **Usage**, before any agent has reported its plan — opens the plan windows and below them **Tokens used**: for the last 24 hours, 7 days or 30 days, each agent's input, output and cache reads and writes, how many responses, and each model's share, read by each machine's conch from the conversations the agents saved, so sessions outside conch count too (`usage.history.v1`). When a machine's conch is older than the app's — it lacks something this build has — the version at the end of the bar turns warn-coloured and says how many are behind (**↑ v0.1.9 · 2**); a click lists each one (this Mac first) with what it lacks, ticked, and **Upgrade** reloads this Mac's server and installs this build on the others — built from conch's source on this Mac when the app was built here (it is told where `macos/bundle.sh` built it from), else the released binaries of its version. conch's version is at the very end, after **Settings**. The **conch** menu says under **Quit** how many panes keep running when the app quits. -- **Styles.** **View → Style** decides how the window is drawn, apart from its colours. **Standard** is the window described here. **Ink** draws it as a manga page: ink borders and square panels with white gutters, the focused one lifted off the page by a shadow in the theme's accent, screentone behind the sidebar and the status bar, the tab on screen and the focused pane's row in solid ink, waiting and done counts as lettering bursts, each agent's state lettered in its pane's header (a working one with its *tap tap*), and a waiting agent's question in a speech bubble, in its pane and in the sidebar's Needs you. Choosing Ink also chooses the Ink theme, black on paper, which it was drawn for, as **View → Theme** would; any theme can be picked after, since the ink is the theme's text colour, and a theme chosen in the Settings panel takes over from it (the window goes back to **Same as conch**). **Meadow** is hand-painted, after the anime films: a sky behind the toolbar (clouds and a sun by day; under a dark theme a night sky with a moon, stars and fireflies), warm paper in the sidebar, the rounded system face for the window's own text, rounder cards with a soft shadow and the focused one ringed in the accent, a leaf on the tab on screen, a waiting agent's question as a note with a dashed amber edge, in its pane and in Needs you, and a strip of grass along the status bar. Choosing it chooses the Meadow theme; its dark pair is Firefly, so `theme = "firefly"` with `light_theme = "meadow"` follows macOS between night and day. **Cel** is cel-shaded — flat fills, thick dark outlines and one hard shadow on every card — and lays the window out around the agents: every agent and terminal the workspace shows is a card in a roster across the top (its mark as a face, its project and branch, a bar and a word for its state, since when), what needs you first, then what is working, done, at rest, terminals and what has exited; a click opens it. A column of projects stands in for the tree — ☰ brings the tree back (⌃⌘S hides it again), **all** or a project's two letters narrows the roster — and on the right the longest-waiting agent's question is a dialogue box with its name tag and its answers, above a log of what the agents last did. Choosing it chooses the Cel theme. **Terminal** is the Standard window on a terminal's ground, after herdr: the same layout, tree, pills and teal accent, on ink black with dark hairline borders, every word of the window in the monospace face (SF Mono, a size smaller, so a label takes the room it did — except the tree's names and labels, which stay full size) and the sidebar 70 points wider for it, the title bar the window's own colour; choosing it chooses the Terminal theme, which the TUI has too, and while it is the theme a light Mac shows its pair, **Terminal Light** — off-white, grey hairlines, the teal deepened, a selected row solid teal with white words — and back to Terminal when macOS goes dark (Terminal Light picked by name stays light). Terminals keep their own font in every style. **Sizes.** **Settings → Mac app** has **Window text size**, in percent, for the window's own text (`[app] text_size`), and **Terminal font size**, in points, for every pane (`font_size`, 14 by default); **View** steps each with the keys in the table below, saving to `config.toml` as the settings page does, and every pane and label takes the new size at once. **JetBrains** is IntelliJ's New UI: flat panels meeting at hairlines, square corners, IntelliJ's greys and blue, the title bar in the panels' colour, and chat bubbles and buttons squared to match; choosing it chooses the **JetBrains Dark** theme, which follows macOS to **JetBrains Light** as Terminal does, and the TUI has both. The style is the app's own, kept in its preferences; the TUI has no borders to draw this way. -- **Themes.** **View → Theme** has conch's thirty themes, nine of them light (GitHub Light, Solarized Light, Catppuccin Latte, VS Code's Light Modern and Light+, JetBrains Light, and conch's own Ink, Meadow and Terminal Light; Meadow's night is the dark Firefly, a pair for `theme` and `light_theme`, Cel and Terminal are conch's own too; VS Code's Dark Modern and Dark+, with their light pairs, are taken from VS Code's own theme files, and like Terminal each follows macOS to its light one while it is the theme); themes of your own, files in `~/.config/conch/themes/`, follow under **Your Themes**, with any file that did not read said there and **Open Themes Folder** at the end ([Configuration](/docs/configuration#themes-of-your-own)), and `[ui] accent` goes over the theme in use, in the app as in the TUI; the Settings panel's **Theme** is a grid of them, each a small picture of the window in it; with the pointer on a card the app shows that theme — the main window and Settings itself — and moving off the cards puts it back, so you see one before choosing it. The first item, **Same as conch**, follows `[ui] theme` in conch's settings, so the window matches the TUI until you pick another; your choice is remembered. A theme colours everything, the terminals in the panes included. Agents draw for a dark terminal — Claude Code's own theme writes white text — so in a light theme each pane keeps a contrast floor: text too close to the colour behind it is darkened until it reads (Ghostty's `minimum-contrast`, 3 on a light theme). The SwiftTerm panes, used when Ghostty isn't built in, have no such setting. -- **Light and dark.** Settings' **Light theme**, below **Theme**, offers only the light themes and makes the app follow macOS: that theme while the system is light, the one above while it is dark, switching as macOS does, by hand or by the time of day. **Off**, the default, keeps the app on the one theme. It is `[ui] light_theme` in `config.toml`, and only the app reads it: the TUI keeps to `theme`. A theme picked under **View → Theme** stays put in either appearance. - -Each pane is a real terminal running [`conch attach`](/docs/cli#attach), so an agent looks exactly as it does in the TUI or any terminal. +The sidebar is conch's tree: each machine, its projects, agents, branches and terminals. Tabs and splits are as in the TUI. -## Panes drawn by Ghostty +**How:** click a row to open it, right-click for its menu. ⌘K searches, ⌘. goes to the next waiting agent, ⌃⌘S hides the sidebar. -Where the pane's server can give it (`pane.raw.v1`), a pane's Ghostty is given the program's own output (`conch attach -raw`) rather than conch's screen repainted into it — as Rex does with the same library. Ghostty then is the pane's terminal for everything it draws: its scrollback, which the trackpad scrolls with momentum and a pill at the bottom says how far (**↓ 214 lines below · End**, a click back down); selection the way Ghostty selects (a word, a line, a block with option); images a program prints with the kitty graphics protocol; ⌘F, which is Ghostty's own search over its history, saying which match of how many. A pane opened after it started has its history replayed into Ghostty first, so the search and the scrollback reach what it printed before. +## Settings -conch's server still keeps every pane's screen, since the TUI, the phone and an agent's state are read from it, and it still answers the program's questions, which are taken out of what Ghostty is given so the program is not answered twice. The clipboard escape (OSC 52) is taken out too, both ways: a program in a pane — on another machine, or a file it printed — cannot write your Mac's clipboard, nor ask Ghostty for it and have the answer typed into the pane. conch's own screen never acted on it either, nor does tmux by default. Copy from a pane by selecting in it. +conch's settings, including **Skills & MCP Servers**. -A pane has one size, and the server settles it between everyone showing it: whoever typed into it last. While that is another window — the TUI, the phone, another Conch — the pane is drawn **letterboxed**: at its own size, from the top left, the rest dotted with a dashed edge where it ends, and *Sized 160×38 for another window · Take it* at the corner. A click on the dots or **Take it**, or typing in the pane, makes it this window's, at the size the window has room for. The terminal's own answers and the pointer just moving over it take nothing. +**How:** ⚙ in the status bar, or **conch → Settings…** (⌘,). **View → Theme** and **View → Style** change the look. -A machine whose server is older, and an app built without Ghostty's library, keep the repainted panes: the status bar says **repainted**, and history and search are conch's, as before. + -## The scratch layer + -**⌥Space** shows a shell floating over the splits, in the project on screen — in the branch's worktree when a branch's pane is in front, else the project's checkout, or the machine's home outside any project — and hides it again. It is an ordinary pane named **Scratch**: the tree lists it under the project's terminals (the TUI's too), it keeps running while hidden, through a reload and with the app quit, and **⌥Space** brings the same one back. **⌥⌘↩** docks it as a split beside the focused pane, **⌥⌘T** makes it a tab; a scratch pane already in a split or a tab is gone to rather than floated as well. **Settings → Mac app → Option-space anywhere** (`[app] scratch_key`) makes ⌥Space work with Conch in the background too, as Ghostty's quick terminal does — a system hot key, which needs no Accessibility permission. +## Plan limits -**Help → Check conch…** runs [`conch doctor`](/docs/cli#doctor) on this computer and lists its checks — the server, the agents, git, gh, the terminal, the machines — each with how to fix it; **Check again** runs them again after you have. +The status bar shows each agent's plan use; a click lists every window and when it resets. -## A branch's changes + + +## Panes drawn by Ghostty -A click on a branch opens it in a tab of its own, as `enter` on a branch does in the TUI. The header says the branch, the base it goes into and how far ahead of it, its pull request with its checks, what is uncommitted and what its agent is doing; **Overview · Changes · Graph** switches between three views of it, and ⋯ holds **Agent or Terminal** (the branch's agent, or the terminal already in its worktree), **Push**, **Merge into main…** (the base: squashed or as a merge commit, where the base is checked out; a merge that conflicts is undone and nothing changes), **Open Pull Request** (or update it) and **Delete Branch…**, after saying what that would lose. A branch with changes — uncommitted, or committed and not yet in the base — opens on Changes; one with none on Overview. +Each pane runs [`conch attach`](/docs/cli#attach), drawn by Ghostty. A pane sized by another window is letterboxed. -**Overview** says whether the branch is clean and how it stands against its upstream (`master is up to date with origin/master`), with its last commit. A branch with a pull request has a card for it: whether it merges — **Conflicts with main in …**, naming the files from the server's own trial merge where GitHub only says it conflicts; that trial merges with the base as it is on your computer, so when your base has commits not pushed and GitHub finds the pull request clean, a collision with those alone is an amber note instead — **your local master (4 commits not pushed) would conflict in …** — with nothing to resolve until the base is pushed — its checks as they run (**3 of 5 done**, with a bar) and each one by name — failing first, then running, then passed, each linking to its run on GitHub — and the review's decision, with **Open on GitHub**. **Ask *agent* to resolve** hands a conflict to the branch's agent — merge the base in (not rebase: the branch is pushed), resolve keeping both sides, test, commit and push, and ask rather than guess — starting one in the branch's worktree when no agent is running there, and when the branch is checked out nowhere — a pull request's branch made on another computer — checking it out in a worktree of its own first (GitHub's copy, if it is not here at all); **Send the failure to *agent*** sends failed checks, as the review queue's **Fix** does. The header's pull request chip says **conflicts** in red, and beside it the checks in a few words — **CI running 1/3** with the spinner, **CI failing · 1 failed**, **CI passed 3/3** — in every view; in the graph the same chip marks the commit the checks run on, and the Changes view's **Checks** card, above the review, lists them too. A server before this build sends the counts without the names. Work handed over this way is followed in a strip under the header, in every view: **claude is resolving the conflict with main**, with the spinner, while it works; **waiting for you** with **Answer claude** when it asks something; **finished — check the result** once it is done, or gone if its pane closed; **Open claude** goes to it and **Dismiss** clears the strip. The header's agent is then the one the work went to, else one at work on the branch. Then the branch's recent commits (a click opens one in the graph); who changed it in the last week and how much of it; how far it is behind and ahead of its upstream and its base; its commits a day over the last fourteen (click a day for its count); and the project's other branches against the base, each with its pull request — a click opens that branch. +**How:** click **Take it**, or type in the pane, to size it to this window. -**Changes** has three columns. On the left: +## The scratch layer -- **Uncommitted** — what is changed in the branch's worktree and not yet committed (`M` changed, `A` added, `D` deleted, `?` new and untracked, `U` a conflict), each with its `+`/`−`, how many comments are on it, and a dot while the agent is writing it. -- **Committed on the branch** — what its commits change against the base, for a branch with a worktree. -- **Commits** — the branch's commits. +A shell floating over the splits, in the project on screen. -In the middle, the file's diff hunk by hunk, unified or split side by side, with line numbers; while an agent works in the worktree the open diff reads again. Each uncommitted file and each hunk has a box: tick a file for all of it, or hunks for part of it (the file's box then shows a dash). The box in the **Uncommitted** heading ticks every file, or none, and shift-click on a file's box ticks the run from the box you clicked last, as in Finder; and **Commit** commits only what is ticked. **Stage** is `git add`: it puts what is ticked in the index without committing it, and the file is marked staged — a green check, or a half circle when only part of it is; right-click a file to stage or unstage it whole. With nothing ticked, **Commit** commits what is staged, as git does, and when nothing is staged either, every change. Staging needs `branch.stage.v1` on that machine's server, and committing part of a file `branch.hunks.v1`. +**How:** ⌥Space shows or hides it, ⌥⌘↩ docks it as a split, ⌥⌘T makes it a tab. -Hover a line and press **+** to comment on it — a line of the new file, so a removed line takes none — then **Add note for the agent** (or ↩; ⇧↩ is a new line) or **Add to PR review**, which is there while the branch has an open pull request. A comment is either +## A branch's changes -- **a note for the agent** — kept by conch on that line (the TUI's review, `review.comments.v1`), so every client sees it; **Send** hands every open note to the agent you pick from the branch's agents, or to a new one started with them (`review.send.to.v1`; an older server picks the oldest agent not waiting on you), and each stays on its line as **sent to** that agent. The agent is asked to answer each in a sentence — what it changed, or why it left it — with [`conch review reply`](/docs/cli#review), and the answer appears under the note as it comes, marked **answered by** the agent; one that finishes without answering says so, and **Open *agent*** goes to its session either way. **Reply** answers back: the note waits to be sent again with its thread. Sent notes are kept by the server (`review.thread.v1`) for 30 days, or until resolved; against an older server they are the app's and last while the tab is open. **Resolve** drops one; or -- **a comment on the pull request** — it waits in your review until you submit it. GitHub's own comments on the pull request show on their lines too, with a link to reply there. +A click on a branch opens it in a tab: **Overview · Changes · Graph**. Tick files or hunks and **Commit**; **✦ Write** drafts the message. Hover a line and press **+** to leave a note for the agent or a pull request comment. -On the right, the commit: the message (**✦ Write** drafts it from what is ticked, or from everything, with the brain set in Settings, by [`conch commit-message`](/docs/cli#commit-message)), and a box to credit the branch's agent with a `Co-Authored-By` line. Below it the review: the notes for the agent, and for a branch with an open pull request **Approve**, **Request changes** or **Comment**, a summary, and **Submit review**, which sends it with its waiting comments through `gh` (requesting changes also sends the notes to the agent). Approving needs nothing else; requesting changes or commenting needs a summary or a comment. Then the pull request's checks. Submitting needs `pr.review.v1` on the machine's server. +**How:** ⋯ holds **Push**, **Merge into main…**, **Open Pull Request** and **Delete Branch…**. -**Graph** is the project's [commit graph](#commits), in the tab. - ## Agent setup -**Agent setup** on a project's menu (or **Agent setup here** on a checked-out branch's) opens what each agent loads in that checkout, as the TUI's `i` view: its instructions, skills, MCP servers and the rest, each with where it comes from (`user`, `project`, `local`, `plugin`…), anything named but missing in red, and what conch noticed about how they fit together. A worktree also lists the main checkout's local files it should have and whether it does. A file's path opens it in that machine's editor. It reads only: syncing one agent's setup to another is the TUI's. +What each agent loads in a checkout: instructions, skills and MCP servers. -## Answering an agent without opening it - -Every agent waiting for you is a card under **Needs you**, at the top of the sidebar — across every machine the workspace shows, the longest waiting first, as direction C of the design has it. A card says which agent it is, what it wants as a pill (**permission**, **question**), the question itself, where the agent is (its project and branch, and the machine when it is not this one), and its choices as buttons — *Allow*, *Always*, *Deny…*, or the options of a question, the one the agent's own cursor is on in amber. A click on a button answers: conch moves the agent's cursor there and presses Enter, exactly as the [phone](/docs/phone) does, and refuses an answer to a question that has changed since it was shown. A click anywhere else on the card opens the agent. The same buttons are along the top of the agent's pane. An agent whose choices conch cannot read off its screen offers **Open to answer** instead. conch reads numbered menus, numbered menus with a description under each choice (Claude Code's question tool), and menus without numbers (Claude Code's folder-trust question). The card is read again every couple of seconds while the agent waits, so it follows the agent: a menu drawn a moment after the agent started waiting shows its buttons once it is there, and Claude Code asking several questions at once — a tab each — shows each question in turn as the one before is answered, here or in the agent. +**How:** **Agent setup** on a project's menu. -## Files and sessions +## Answering an agent without opening it -The **Files** row of a project, under its terminals as in the TUI, opens its main checkout in a tab of its own: folders opening as you click them, each file marked by what it is, as an editor's file tree does — its language's or tool's own logo in its brand colour (Python's for `.py`, Docker's whale for a `Dockerfile` or compose file, Go's for `.go` and `go.mod`, npm's for `package.json`, React's for `.tsx`, and some sixty more, from Simple Icons), else an outline for its kind (a picture, an archive, a secret, a spreadsheet, a README) — and each file and folder with its git status letter, beside the file picked in an editor — line numbers, the caret's line lit, the theme's colours for comments, strings, numbers and keywords (Go, Swift, TypeScript and JavaScript, Python, Rust, shell, C-like languages, JSON, YAML, TOML, Markdown), undo and the find bar (⌘F). A binary file is named rather than shown. Edit it and **Save** (⌘S) writes it (`fs.write.v1`); the file's row shows a dot and its bar says **edited** until then. Agents write in the same files, so a save is checked against the file as it was opened: if something wrote it meanwhile the save is refused and you choose — **Reload Theirs** (your edits go) or **Overwrite with Mine** (theirs go); with edits open, a change on disk is said in a banner instead of replacing them. Leaving a file or a branch with edits asks whether to save them. The branch beside the project's name switches the tab to any branch checked out in a worktree — an agent's, say — and editing then writes there; a branch with no worktree is listed but can't be picked, and the tab never checks a branch out in your main checkout. **Hidden files** lists dotfiles too, ↻ reads it again and turns while it does, and it reads again by itself when an agent writes in that checkout. Everything on a machine whose conch predates `fs.write.v1` is shown read only, and says to reload its server; one that predates `fs.files.v1` can't list the files at all. +Every waiting agent is a card under **Needs you**, with its question and its choices as buttons. -Files open in **tabs** across the top of the editor, each keeping its edits while another is shown — a dot marks one not saved, and closing it asks first. **Go to File** (`⌘P`) opens one by a few letters of its name. The editor's find bar (`⌘F`) also replaces (`⌥⌘F`, or the magnifier in the file's bar). Right-click a file or folder for **New File Here…** and **New Folder Here…** (a `/` in the name makes the folders on the way), **Rename…** (a path from the top moves it), **Duplicate**, **Delete…** (gone from that machine at once, not to the Trash), **Find in This Folder…**, **Copy Path** and **Copy Relative Path**, **Open Terminal Here** and, on this Mac, **Reveal in Finder**; the tree's own bar has new file, new folder and collapse all. Nothing is ever written over, nothing leaves the checkout, and `.git` is left to git. These need `fs.ops.v1`. +**How:** click a button to answer, or the card to open the agent. -**Search** (`⇧⌘F`, or the header's button) turns the side into a search of the whole project: one box finds **file names** and **text** in files alike — **Everything**, **File names** or **Text** — with **Aa** (match case), **ab** (whole word) and **.\*** (a regular expression, Go's syntax), **files to include** and **files to exclude** as globs (`internal/, cmd/`, `*_test.go`, `cmd/**/main.go`), and what git ignores left out unless asked. Text results are grouped by file with their line numbers; a click opens the file at that line. The arrow beside the box shows **Replace**: each match is drawn struck through with its replacement after it, a line or a whole file can be left out with its ✕, and **Replace All** (or a file's own replace button) writes them — each file only if it is still what was searched, so a file an agent wrote meanwhile is skipped and named rather than written over. A file with edits not saved has to be saved first. Search needs `fs.search.v1`, replace `fs.replace.v1`. +## Files and sessions -**Big files.** A file up to 4 MB is read whole and edits as any other. A bigger one — a log of a few gigabytes — is read a window of lines at a time (`fs.lines.v1`): the app holds only what is on screen and a little around it, the scrollbar beside the lines stands for the whole file, **Go to line** jumps anywhere, and **Follow end** keeps the last lines in view as they are written. Its find runs on the server a piece at a time, with how much it has searched, and marks every match down the scrollbar; the arrows go from one to the next. Click a line's number to pick it (shift-click to pick up to another), then **Edit Lines…**: the lines open in an editor and **Save Lines** writes just those, checked against what was read. Past 2 GB a save would mean copying too much, so a file that size is read and searched only; lines that are not UTF-8 are shown with replacement characters and can't be saved back. +The **Files** row opens the checkout in an editor; the **Sessions** row lists saved conversations to search and resume. -**Edit with Agent** (`⌘I`, or the button in the file's bar) hands the file — or the lines selected in it — to an agent: pick one of the agents installed there from the menu at the top, each with its own logo, say what to do or press **Explain**, **Fix the bug**, **Add tests**, **Add comments** or **Simplify**, and name other files it may need. The agent runs in a pane of its own in that checkout, as one started from the sidebar would — it shows there, and **Open its pane** goes to it — while a banner over the file says it is working. When it writes the file, its change is shown as a diff against the file as it was handed over: **Keep** it, or **Undo It**, which writes the old text back if the agent's version is still what is on disk. An ask that changes nothing, an explanation, is read in the agent's pane; **Stop Waiting** puts the banner away. The panel lists what agents were asked in this checkout. The file has to be saved before it is handed over, since the agent edits it on disk. +| Keys | | +| --- | --- | +| `⌘S` | save | +| `⌘P` | go to a file | +| `⇧⌘F` | search the project | +| `⌥⌘F` | find and replace | +| `⌘I` | edit with an agent | -Not every file is text. A picture (PNG, JPEG, GIF, WebP, HEIC, TIFF, ICO, SVG) is shown fitted to the pane — pinch or ⌘-scroll to zoom, double-click to fit again; a video (MP4, MOV, M4V) or a sound (MP3, M4A, WAV, AIFF, FLAC) plays with the system's controls, full screen and Picture in Picture; a PDF pages through; and an HTML page is rendered, reading its stylesheets and pictures from the checkout around it. A page or an SVG has **Page** / **Source** (**Picture** / **Source**) to switch to its text and edit it; saving a page shows it again as saved. The bar's ↗ opens the file in its own app (Preview, QuickTime, your browser), and a page's 🌐 opens it in a browser tab. On another machine the file is fetched into the app's cache first, with its progress shown (`fs.transfer.v1`, up to 512 MB; a page there gets its own file only, not the files beside it). - -The **Sessions** row of a project opens its saved conversations in a tab of their own: every agent's, the newest first, any interrupted by a restart above them and starred ones next, each with its agent, title, branch and how long ago. Search narrows them by title, branch or agent, and from three letters looks inside the conversations too (`session.search`), each match with the words around it. **Resume** (or a double-click) starts the agent on that conversation again in a pane; one already running says **open**, and **Open** goes to its pane; **Resume N interrupted** brings back every conversation a restart cut off. The star on a row keeps it to find again — conch's mark, not the agent's. A row's right-click menu also has **Hand Off To ▸**, which writes the conversation out where it was and starts another agent there to read it and carry on. The bin on a row deletes the conversation where its agent keeps it, after asking. - ## Workbench -An agent's whole branch in one tab: its files, a terminal in its checkout, the agent as a chat, and the agent's own terminal. Open it from an agent's row (right-click → **Open Workbench**) or with **View → Workbench → Open Workbench** (⌥⌘B) for the agent in focus; one already open is brought to the front. Its terminal is a shell started in the agent's folder, or an idle one already there that nothing shows. +An agent's files, a terminal and its chat in one tab. -**The chat** is the agent's conversation read from what it saves, kept up to date while it is on screen — asked for every second while the agent works, and sent only what changed, so a long session costs no more than a short one. Answers are laid out as they were written: headings, lists, tables, quotes and code blocks with a copy button. The tools it used between two answers fold into one line — *Read 2 files, ran 1 command*, with a red mark if one failed — that opens to a card per tool: what it was used on, whether it worked (a spinner while the newest is still running), and opened, what it was given (an edit as the lines it took out and put in, a command, a file written) and what came back. Claude Code's transcripts say which tools were used; for Codex, Gemini and OpenCode the chat is their conversation without them, and an agent conch cannot read sessions of has no chat. While it works, the line under the conversation says for how long and what it is doing, and the send button in the box becomes **Stop**, its escape key (as does pressing Escape in the box) — shown from the moment a message is sent until the agent has answered or been stopped, since conch's own state can take a moment to catch up. A question it is waiting on is a card with its answers, sent as keys exactly as the pane's own buttons are. What you write in the box below goes into the agent as if typed at its prompt (⏎ sends, ⇧⏎ a new line) and shows at once, marked *Sent* until the agent's transcript has it — or *Not sent*, with **Retry**. The chat follows the conversation while you are at its end and stays where you are while you read back, with **↓ Latest** to return. The chat and the terminal are the same agent: where only one has room, **Chat | Terminal** in its header swaps them. A server from before chats says so and asks to be reloaded. - -**Layouts**, from the bar above the workbench or **View → Workbench** (⌥⌘1–⌥⌘4), remembered for the next one: - -| Layout | | -| --- | --- | -| **IDE** | files and the editor on the left, the terminal below them, the chat on the right | -| **Chat First** | the chat in the middle of the window, files and a terminal in a column beside it | -| **Agent** | the chat and the agent's own terminal side by side, files and a terminal in a row below | -| **JetBrains** | IntelliJ's arrangement: tool windows round the editor, opened and closed from a strip of icons down each edge — Project and Terminal on the left, Agent Chat and the agent's terminal on the right, the layout menu at the bottom right; a waiting agent marks its icon | - -Each part is an ordinary split: drag between them to resize, ⌘W closes one. The buttons in the bar (or the strips) hide a part and give its room to the rest, and show it again. The **JetBrains** style (**View → Style**) suits the JetBrains layout, but any style and any layout go together. +**How:** ⌥⌘B, or right-click an agent → **Open Workbench**. ⌥⌘1–⌥⌘4 pick the IDE, Chat First, Agent or JetBrains layout. ## Browser tabs -**File → New Browser Tab** (⇧⌘B) opens a web page in a tab beside the agents, as a terminal or a branch's changes are — split it, move it, close it with ⌘W. Type in the address bar: a port on this computer (`localhost:3000`, `127.0.0.1:8080`) or an address on your network goes over http, since that is what a dev server speaks; anything else with a dot over https; a full address as it is. Back, forward and reload are beside it (or swipe), a page that fails to load says why with **Try Again**, links that would open a window open in the same tab, and the tab is named by the page's title. The compass opens the page in your own browser, for the extensions, sign-ins and devtools that live there — though **Develop → Inspect** works here too, as in Safari. A port in a pane's header opens here. +A web page in a tab beside the agents. + +**How:** **File → New Browser Tab** (⇧⌘B). ## Commits -**Commit Graph** on a project's menu opens its history in a tab of its own: every branch and tag of the repository, newest first, as `git log --graph` draws it — each commit a dot on its branch's lane, a lane coloured for its branch from the theme, merges where lanes join — with its short hash, its branches, remote branches and tags as chips (the checked-out one as **HEAD → name**), its subject, author and how long ago. **Show in Commit Graph** on a branch's menu opens it at that branch's newest commit. The newest 300 are read first; **Show older commits** reads 300 more, up to 2000. It reads again when git moves (a commit, a push, a pull request merged on GitHub, whose base conch then fetches), and ↻ reads it again at any time, asking GitHub about the pull requests then too rather than at the next minute; opening the graph or a branch's git tab asks as well. Right-click a commit to copy its hash or subject, or to view the changes on a branch that points at it. The field at the top finds commits by hash, subject or author, dimming the rest. A click on a commit shows it on the right — its author, its whole message, its parents and the files it changed, each opening its diff there; shift-click another to compare the two, every commit between them and what they change together (**Done** goes back to one). Showing a commit needs `project.commit.v1`. A machine's server needs `project.log.v1` for it: an older one says so, and reloading that server brings it. - -## Starting agents and tasks - -**File → New Task…** (`⌘N`), or **New task…** on a project's or branch's menu, opens a sheet for a prompt, the agent to give it to and, if you like, the branch's name — [`conch task`](/docs/cli#task) from a window: the server makes a branch and a worktree of its own and starts the agent there with your prompt, in a tab of its own. In a folder that isn't a git repository the agent works in the folder itself. **Issue** picks one of the project's open GitHub issues to work on — its title and body are the prompt, and anything typed is added to it — and **When** starts it later rather than now: a time (`14:05`, `+30m`, `tomorrow 9:00`), `every 1d` for a task that comes back on a branch of its own each time, `queue` to wait until fewer agents are running in the project, or `after BRANCH` to start once that work has finished, on top of it. Later is kept by the server and starts with conch closed too; it is `conch task -at`/`-every`/`-queue`/`-after`/`-issue`. **File → Start Agent** (`⇧⌘N`) starts an agent where the focused pane is. - -Right-clicking a row in the sidebar gives its menu, as `m` does in the TUI: - -| Row | Menu | -| --- | --- | -| Agent, terminal | Open · Rename… · Prompt… (an agent: a message typed in and submitted for you) · Start an agent here ▸ · New terminal here · View changes on its branch · Alert when it goes quiet and Alert on output (a running terminal; ✓ when on) · Close (an agent asks first; its conversation stays in Sessions) | -| Branch | View changes · Start an agent on this branch ▸ and Open terminal on this branch (when it is checked out) · New task in project… · Show in commit graph · Open pull request (when it has one) · Copy branch name · Remove worktree… (keeps the branch; a worktree with uncommitted work is not removed) · Delete branch… (with its worktree, after saying what that loses — uncommitted files, commits in neither the base nor its upstream — as the server's own dry run counts it; never the base or the main checkout's) | -| Project | New task… · Start an agent in project ▸ · Open terminal in project · Commit graph (a git repository) · Copy path · Move to another machine… (a git repository: the whole project, its branches, worktrees and agents — [how](/docs/remote-machines#moving-a-whole-project)) · Remove Project… | -| Machine | Start an agent ▸ (in the home directory, in no project) · New terminal · SSH to a host… (this computer) · Add project… · Add machine… · Reconnect · Reload server (its panes keep running) · Upgrade conch there and Remove machine… (another machine; removing asks first, and leaves its agents running there) | -| CLI | Start an agent ▸ · New terminal · SSH to a host… (this computer's) | -| Workspace | Add project… · New task in each project… | - -**Add Project…** (⌘O, a machine's menu or a workspace's) offers three ways in: **Open a folder** that is already there; **Clone a repository** — paste its URL (`https://…`, `ssh://…`, `git@github.com:owner/repo.git`), the folder's name fills in from it as `git clone` would name it, and **In** says where (`~/workspace` when you have one); or **New repository**, an empty folder with `git init` run in it. A path under the fields says where the project will be. On another machine the paths are typed, since the panel only sees this Mac; a private repository is cloned with that machine's git credentials (gh, an ssh key, a credential helper), and git never stops to ask for a password — it fails with git's own message instead. - -**Project groups** keep projects together that change together — an API, its web app, their specs — each still a project of its own, with its own git, branches and pull requests. Drag one project onto another and the app asks *Group angular-clinic with spring?*, naming the group after the one you dropped it on; drag a project onto a group to add it. Or use **New Project Group…** on Workspace's menu (a name, the projects ticked off a list, notes for the agents), or **Group With ▸** on a project's. A group is a row under Workspace with its projects under it, in its order, how many repos it holds and what their agents are doing; its menu renames it, edits its notes, adds or takes out a project, and removes it — its projects stay. Groups are the server's (`groups.json`), so `conch group` shows the same ones. - -**A task across a group's repos** — the group's **+**, or **New Task Across Repos…** on its menu — asks what to do, the branch (the same in each repo; named from what to do when left empty), which repos, and one agent for the whole task or one per repo. It makes the branch in a worktree of each repo, as any task's worktree, and a task folder (`$CONCH_HOME/tasks/GROUP/BRANCH`) with a link to each worktree under the repo's name and `CONCH-TASK.md` — the prompt, the repos and their bases, the group's notes. One agent starts in that folder with every worktree in reach (Claude Code's and Codex's `--add-dir`, Gemini CLI's `--include-directories`; any other works from the folder), so there is no adding folders by hand; or each repo gets an agent in its own worktree, told what the others are doing. Nothing is made if a repo is not a git repository or already has the branch checked out, and if one repo's worktree fails the others are undone. The task is listed first under its group: its agent, then its branch in each repo — the project's own branch, so a click opens that repo's changes and its badge says its pull request. Its menu pushes the branch in every repo, opens a pull request in each (naming the others), copies or reveals the folder, and removes the task — its folder only; each repo keeps its worktree and branch. `conch group task` does the same from a terminal. - -**The task page** — a click on the task's row, or **Open Task Page** on its menu — has every repo on one page. **Overview** is a card for each: its base and how far ahead, what is uncommitted, lines added and removed, its pull request with its checks and review, the files the branch changed, and buttons for that repo alone (Open Changes, its pull request on GitHub or Open Pull Request, Terminal Here, and Send to the Agent when a check failed, with the failing checks listed). Above them are the task's agents, each a click away, and **Push All**, **Open Pull Requests…** and **Merge All When Green…**. **Changes** lists every repo's files together, grouped by repo, each repo with its own message box and Commit (a commit belongs to one repo) and **Commit Each…** for all of them at once; the diff on the right is the git tab's, and **Open in Its Git Tab** goes there for hunks, lines and comments. **Brief** is the task's `CONCH-TASK.md`, saved with ⌘S, and **Tell the Agents** asks every agent of the task to read it again. +The project's history as a graph. -**Merge All When Green…** asks for the order the repos merge in — drag them, the contract before the code that serves it — and whether to remove the task once all are merged (its folder, and each repo's worktree and branch). Then the server waits: nothing merges until every pull request is open, green and held back by nothing the autopilot would hold one for (a draft, changes asked for, a conflict, an agent still at it), and then they merge one by one in that order, each after the one before has landed, each repo in its own way as GitHub has it set. A repo merged by hand meanwhile counts as merged. If GitHub refuses one, it stops there and nothing after it merges; **Arm Again…** carries on from where it stopped. The page's banner says what it is waiting for, and it carries on with the app closed. `conch group merge` does the same from a terminal. +**How:** **Commit Graph** on a project's menu, or **Show in Commit Graph** on a branch's. -**CLI** is split as the TUI splits it: **Agents**, **Terminals** and **SSH**, each holding **folders of your own** — *eng*, *staging*, *prod* — and then whatever is in none. They are the TUI's folders (`ui.json`), so one made in either shows in both, and a TUI running at the same time picks up a change made here at once. Make one from a section's or a folder's menu, or CLI's folder button; drag an agent, a terminal, an ssh session or a saved host onto a folder to put it in, or onto its section to take it out again; or use **Move to Folder ▸** on its menu, which ticks where it is now and can make a folder on the way. A folder is folded until opened, as in the TUI; **Rename Folder…** keeps what is in it, and **Remove Folder** closes nothing — what was in it goes back to the section. A saved host goes in a folder as itself, so every session to it follows it there. - -**Saved ssh hosts** — the ones the TUI keeps (`ui.json`) — are listed under **CLI → SSH**, marked *saved*, while no session to one is open; a click logs in to it again with the ssh options it was saved with. **SSH to a Host…** asks for the host, a name for the sidebar, its ssh options and a folder, saves it unless you untick that, and can set up a login without a password first. An ssh session's menu has **Another Session** to the same host with the same options, **Copy ssh Command**, **Save This Host…** or **Edit Host (Name, Folder, Options)…**, **Set Up Login Without a Password…**, **Add as a Machine…** (conch installed there, the host filled in) and **Move to Folder ▸**; a saved host's has the same, with **Connect** and **Forget This Host**. Each change is the TUI's too. - -**Login without a password.** **Set Up Login Without a Password…** opens a terminal that puts this Mac's public key on the host — making one first (`~/.ssh/id_ed25519`) if you have none — and **ssh asks for the host's password there, the once**; the app never sees it (`conch ssh -copy-key`). When that terminal is closed the app logs in again in batch mode, which never asks (`conch ssh -check-key`), and says whether the key was taken. Every ssh row says the same thing at a glance: a green **key** when the host takes your key, an amber **lock** when it asks for a password each time — learnt by one such batch-mode login a host, once while the app runs, and nothing at all for a host that could not be reached. - -An agent's or terminal's menu also has **Redraw**, which asks its program to draw its screen again (the TUI's ctrl+b r), and an agent waiting for an answer says so beside **Prompt…**. - -**Your own actions** — the `[[actions]]` in `config.toml`, which the TUI puts on its menus — are at the end of the menus of the rows they are for (`on = ["pane", "branch", "project", "machine"]`, all four when unset). Each runs `sh -lc` with its command in a terminal of its own where the row is — a pane's folder, a branch's worktree, a project's checkout, a machine's home — with `CONCH_MACHINE`, `CONCH_PROJECT`, `CONCH_BRANCH`, `CONCH_WORKTREE` and `CONCH_PANE` set, and its terminal stays when the command ends so you can read it (`keep = false` closes it). A branch that is not checked out has nowhere to run one, and says so. +## Starting agents and tasks -**Broadcast…** — on a machine, CLI, Workspace or project row (**Broadcast to Its Agents…**), or a project's Agents or Terminals section — sends one message to its running panes, as the TUI's broadcast: a sheet lists them with a tick each, agents first. An agent takes the message as its next prompt and starts ticked, unless it is waiting on an answer (the message would answer it); a terminal runs it as a command, so terminals start ticked only from a Terminals section. ⌘↩ sends, and the status bar says how many took it and why any did not. +A task gives an agent a prompt on a branch of its own. -**Start an Agent ▸** lists the agents installed on that machine. A machine that is offline offers nothing that would start something there; it can still be reconnected, upgraded or removed. A machine whose conch is from an older build than the app's own says **behind** on its row — what it lacks is in the tooltip — and **Reload Server** (this computer) or **Upgrade conch There** (another machine) brings it up to date. +**How:** **File → New Task…** (⌘N); **File → Start Agent** (⇧⌘N) starts one where the focused pane is; **Add Project…** (⌘O). ## Keys | Keys | | | --- | --- | -| `⌘K` | search: agents, terminals, projects, task branches, files and commands, waiting agents first; a file opens in that machine's `$EDITOR`, in a terminal tab in its checkout. With the selection on a pane, the pane itself is beside the list, live — drawn whole at a font small enough to fit, without resizing it for anybody (`conch attach -raw -view`); an agent waiting is answered from the buttons under it, and `⇥` hands the preview the keyboard to type into the pane | -| `⌥Space` / `⌥⌘↩` / `⌥⌘T` | show or hide the scratch layer / dock it as a split / make it a tab | -| `⌘N` | a new task: a prompt, an agent, a branch and worktree of its own | -| `⇧⌘N` | start an agent where the focused pane is | -| `⌘T` | a new terminal tab, in the focused pane's folder | -| `⇧⌘B` | a new browser tab | -| `⌥⌘B` | the workbench of the agent in focus: its files, a terminal, its chat and its own terminal | -| `⌥⌘1`–`⌥⌘4` | the workbench in the IDE, Chat First, Agent or JetBrains layout | -| `⌘O` | add a project: a folder picked in the Finder's panel (on another machine, from its row, a path typed in); added from a workspace after the first, it is put in that workspace | -| `⇧⌘H` | a terminal here logged in to a host with ssh, as the TUI's `H` — the session [`conch ssh`](/docs/cli#panes) starts | -| `⇧⌘M` | add a machine: `conch machine add` in a terminal tab, so the install is watched; the machine is in the sidebar as soon as it is added | -| `⌘D` / `⇧⌘D` | a new terminal split right / down | -| `⇧⌘↩` | zoom the focused split, or show every split again | -| `⌥⌘←` `⌥⌘→` `⌥⌘↑` `⌥⌘↓` | focus the split to the left, right, above or below | -| `⌘F` / `⌘G` / `⇧⌘G` | find in the focused pane / the next older match / the next newer one | -| `⌘P` / `⇧⌘F` / `⌥⌘F` / `⌘I` | in a Files tab: go to a file by name / search the project for file names and text / find and replace in the file / edit the file with an agent | -| `⇧PgUp` `⇧PgDn` `⇧Home` `⇧End` | scroll the pane's history a page, or to the top and back — conch's history in a repainted pane, Ghostty's own in one it draws directly | -| `⌘/` | Help → Keyboard Shortcuts: every key the menus answer to, read off the menus themselves, and the ones for panes and the mouse | -| `⌘W` | close the split — the pane keeps running, and is in the sidebar to open again | -| `⌘1`–`⌘9`, `⇧⌘]` / `⇧⌘[` | go to a tab, next / previous tab | -| `⌘.` | the next agent waiting for you, then the ones that finished | -| `⌃⌘S` | show or hide the sidebar | -| `⌘+` / `⌘−` / `⌃⌘0` | the terminal's text a point bigger / smaller / back to 14 (`[app] font_size`) | -| `⇧⌘+` / `⇧⌘−` / `⌃⇧⌘0` | the window's own text a step bigger / smaller / back to 100% (`[app] text_size`) | -| `⌘0` | the sidebar takes the keyboard (so does a click on a row that is not a pane): `↑` `↓` (or `k` `j`) move, `←` folds or goes to the row above it, `→` unfolds or goes in, space folds, `⏎` opens — going into a pane, a branch's changes — and `t` a task, `c` an agent, `n` a terminal, each where the row is, `x` closes a pane | - -Everything else you type goes to the focused pane — except **the TUI's prefix keys**, which work here as there: `ctrl+b` (or whatever `[keys] prefix` is), then a key from the [prefix table](/docs/configuration#rebinding-the-keys). `ctrl+b %` splits right, `ctrl+b z` zooms, `ctrl+b c` a new tab, `ctrl+b n` / `p` the next and previous tab, `ctrl+b 1`–`0` a tab by its place, `ctrl+b o` the next split, `ctrl+b &` closes the tab, `ctrl+b /` the palette, `ctrl+b :` ✦ Ask, `ctrl+b ?` the keys — and `ctrl+b ctrl+b` gives the program its own `ctrl+b`. A key bound to nothing hands the keyboard to the sidebar, as the TUI's prefix does. The table is the TUI's own (`conch keys -json`), so a key you moved in `[keys.bind]` moves in both; while the prefix is down the status bar says **PREFIX** and shows the keys that follow, and Help → Keyboard Shortcuts lists the whole table. The few that are the TUI's alone — scroll mode, layouts, links, typing into every split, detach — say so rather than doing nothing. **Settings → Mac app → Prefix keys in panes** (`[app] prefix_keys = false`) turns them off, and the prefix goes to the program like any other key. +| `⌘K` | search | +| `⌘T` / `⌘D` | new terminal tab / split | +| `⇧⌘↩` | zoom the focused split | +| `⌘F` | find in the pane | +| `⌘W` | close the split; the pane keeps running | +| `⌘1`–`⌘9` | go to a tab | +| `⌘0` | the sidebar takes the keyboard | +| `⌘/` | every keyboard shortcut | -## Installing the beta +The TUI's prefix keys work too: `ctrl+b`, then a key from the [prefix table](/docs/configuration#rebinding-the-keys). -Each release from v0.1.9 carries `Conch__macos_arm64.zip` on its [GitHub release page](https://github.com/Amitgb14/conch/releases), with its SHA-256 beside it. It needs a Mac with Apple Silicon and macOS 14 or later, and conch's server comes inside it, so nothing else has to be installed first. +## Installing the beta -1. Download the zip and open it: it unpacks **Conch.app**. -2. Drag Conch.app into **Applications** — the system's `/Applications`. In `~/Applications` it has the same name, to a Mac, as the launcher [`conch app install`](/docs/cli#app) writes there, so that launcher is not added; install and remove never touch Conch.app. -3. Open it. The app is signed with a Developer ID and notarized by Apple, so macOS only asks the usual *downloaded from the internet* question the first time — no "could not verify" warning, and nothing to allow in System Settings. +Download `Conch__macos_arm64.zip` from the [GitHub release page](https://github.com/Amitgb14/conch/releases). It needs Apple Silicon and macOS 14 or later. -To update, download the next release's zip and replace the app; your agents keep running through it, since the server holds them, not the window. A machine you reach over ssh gets the released conch of the same version when the app upgrades it. Report what breaks with **⊙** in the status bar. +**How:** unzip it, drag **Conch.app** into **Applications** and open it. To update, replace the app. ## Building it -It needs the Xcode Command Line Tools (Swift 6) and Go. For Ghostty's terminal in the panes it also needs Xcode 26 with its Metal toolchain, and Zig: +Needs the Xcode Command Line Tools and Go; Ghostty needs Xcode 26 and Zig. ```sh -xcodebuild -downloadComponent MetalToolchain # once, after installing Xcode -brew install zig -macos/ghostty.sh # Ghostty's library, from a pinned release → macos/vendor +macos/ghostty.sh # Ghostty's library → macos/vendor macos/bundle.sh # → macos/build/Conch.app -macos/bundle.sh /Applications # or straight into Applications -make app-release VERSION=0.1.9 # the beta's zip, for a release: dist/Conch_0.1.9_macos_arm64.zip -make app-release VERSION=0.1.9 NOTARY=conch-notary # signed with a Developer ID and notarized ``` - -A release build signs the app with the first **Developer ID Application** certificate in the keychain (`CONCH_SIGN_IDENTITY` names another) and the hardened runtime; without one it is signed ad hoc and macOS warns whoever downloads it. `NOTARY` names a profile saved by `xcrun notarytool store-credentials`: the app is then sent to Apple, the ticket stapled to it, and the build fails unless Gatekeeper accepts it as notarized. - -Without `macos/ghostty.sh` the app builds just the same, with SwiftTerm drawing the panes; the status bar says which. - -The app carries its own `conch` inside it, so each pane's `conch attach` is the same build as the window. It looks for conch's server where `conch` does (`$CONCH_SOCKET`, else `conch.sock` in `$CONCH_HOME` or `~/.config/conch`), and when none is running it offers to start one. `CONCH_BIN` points it at another `conch`. Launched with `-background YES` it opens behind whatever is in front and does not make itself active — for a scripted run beside somebody at work. Every sidebar row and tab is a button to accessibility, so VoiceOver (and a script) can open one as a click does. - -## What it is built on - -The window is AppKit and SwiftUI; the terminal in each pane is [Ghostty](https://ghostty.org)'s — its library (libghostty) from an upstream release, unmodified, with conch's own settings rather than your Ghostty configuration, given the program's own output where the server can (`conch attach -raw`, above) — or [SwiftTerm](https://github.com/migueldeicaza/SwiftTerm) where Ghostty's library has not been built, behind a single seam. Typing goes through macOS's input methods, so Japanese, Chinese and Korean input, dead keys (option-e then e for é), dictation and the character viewer all work; what is being composed is shown at the cursor until it is committed. The left option key is alt; the right one types the characters your keyboard puts there. The code is in `macos/` in the repository: `ConchKit` (the protocol client, the tree, search and layout, with tests run by `swift test`) and `ConchApp` (the window). diff --git a/web/src/app/docs/page.mdx b/web/src/app/docs/page.mdx index 171fbfbe..cf82b831 100644 --- a/web/src/app/docs/page.mdx +++ b/web/src/app/docs/page.mdx @@ -2,28 +2,28 @@ export const metadata = { title: "Introduction", description: "What conch is and # Introduction -conch is a terminal orchestrator for AI coding agents. A background server owns the terminals your agents run in, so they keep working when you close the UI. +conch is a terminal orchestrator for AI coding agents: a background server owns their terminals, so they keep working when you close the UI. ## What's new -An agent's whole branch in one tab: its files, a terminal in its checkout, the agent as a chat, and its own terminal, in four layouts. +An agent's whole branch in one tab: its files, a terminal, the agent as a chat. -Overview, changes and graph for a branch: commit single hunks, leave the agent a note on a line it answers in a thread, and see the pull request's checks. +Commit single hunks, leave the agent a note on a line, see the pull request's checks. -Your dev server's page in a tab beside the agents, split and moved like any other. +Your dev server's page in a tab beside the agents. -A project's files in a tab, each marked by its language, and any of them handed to the agent you pick. +A project's files in a tab, any of them handed to the agent you pick. Failed CI goes back to the agent, and green pull requests merge, with every window closed. @@ -35,36 +35,24 @@ Answer a waiting agent from your phone. Each phone sees only the machines you ga ## Is conch for you? -**conch is for running several coding agents at once and keeping track of them.** If you have three or four going — on different branches, worktrees or machines — and the hard part is knowing which one is waiting on you, what each has changed, and getting back to it after your laptop slept, that is what this is. It assumes you live in a terminal, that you want work to survive the UI closing, and that you want to answer an agent's question from wherever you are, including [a phone](/docs/phone). +- **Yes**, if you run several agents at once — on different branches, worktrees or machines — and need to know which one is waiting on you. +- **No**, for one agent in one repo: run the agent's own CLI. +- **No**, for unattended swarms: nothing runs until you confirm. +- macOS and Linux only; on Windows, use WSL. -**It is the wrong shape for several things, and here is what to use instead.** - -- **One agent, one repo, no branches.** conch adds a server, a tree and a key map you do not need. Run the agent's own CLI; add tmux if you want it to survive a dropped ssh session. conch earns its keep from the third agent, not the first. -- **You handle git by hand.** Tasks, worktrees per branch and the harvest flow are most of conch. If you would rather branch and commit yourself, a plain multiplexer — tmux, zellij, Zellij's floating panes — gives you the panes without the opinions. -- **Review is your bottleneck.** conch reads diffs properly now — [side by side](/docs/interface#changes-view) on a wide terminal, with what changed inside a line picked out, single hunks staged for a commit, and `e` to open the file at the hunk in your editor. What it still has none of: a review thread with another person (comments in conch are for the agent — written on a hunk or a line, kept by the server, sent to it as one message, and answered in the thread), a three-way editor for a merge conflict (conch merges and, when that conflicts, hands it to an agent or to the git window), or a diff between two arbitrary commits. **Reviewing the pull request itself is [Conch.app](/docs/mac-app#a-branchs-changes)'s**: its git tab submits approve, request changes or comment through `gh`, and shows GitHub's own comments on their lines with **Reply on GitHub**; from the TUI that is still `gh` or your forge. If the rest of those are your day, that is `gh`, your forge's web UI, or a graphical tool, and conch is the thing beside it rather than the thing it replaces. -- **You want a desktop app, and you are not on a Mac.** [Conch.app](/docs/mac-app) is a native macOS window on the same servers — the tree, tabs and splits, panes drawn by Ghostty, a branch's changes and files in tabs — and it is in beta. There is no Windows or Linux window, and the [phone app](/docs/phone) is a companion for answering agents away from the laptop rather than a second home. Everywhere else, the TUI is conch. -- **Windows.** conch does not build for Windows — it is macOS and Linux, and it uses unix sockets and pty internals that have no Windows equivalent here. WSL works, and is the supported answer. -- **An agent conch does not support in full.** Five are [supported](/docs/agents#supported-agents) — adapter, detection, sessions that list and resume. Others **run here** from a manifest: conch starts and watches them and does not read their saved conversations. If what you need is deep support for a sixth agent, say so rather than assuming the manifest covers it. -- **Unattended swarms.** conch waits for Enter on purpose: the [brain](/docs/brain) proposes actions and nothing runs until you confirm, and an agent's question stops the work until somebody answers it. If you want dozens of agents running without a person in the loop, conch is deliberately not that, and will not become it. - -The shortest version: **conch is a terminal multiplexer that understands agents and git branches.** Where it is the wrong tool, it is usually because you want fewer agents, a graphical diff, or no human in the loop. What it does that other tools leave to you is on [Why conch](/docs/why). +What it does that other tools leave to you is on [Why conch](/docs/why). ## How it fits together -conch has two parts: - -- **The server.** Each machine runs one conch server. It owns every pane — the pseudo-terminals your agents and shells run in — along with their screens, scrollback and agent states. It starts on its own the first time you run `conch`. -- **The TUI.** Running `conch` opens a client that connects to the server. Press `q` to detach: the TUI exits, and the server and everything in it keep running. Run `conch` again to pick up where you left off. +Each machine runs one conch **server** that owns every pane. Running `conch` opens the **TUI**, a client of that server; press `q` to detach, and run `conch` again to pick up where you left off. -Because the server owns the panes, you can close your terminal, lose your ssh session or update conch without stopping an agent. The server on a [remote machine](/docs/remote-machines) keeps working when your laptop sleeps, and the TUI connects to every machine at once. - -The TUI is not the only client. [Conch.app](/docs/mac-app) is one, in a native macOS window; `conch web` is another, serving the same agents to [a phone](/docs/phone), so you can see what each one is doing and answer the question it is waiting on from somewhere else. The phone reaches your laptop directly over your own tailnet, or from any network through a [relay](/docs/phone#through-a-relay) you run yourself, which carries the traffic without being able to read it. Either way nothing goes through a service of conch's: there is no account, and no server of ours between you and your agents. +[Conch.app](/docs/mac-app) and [your phone](/docs/phone) are clients of the same server. ## The tree -The TUI organises everything as a tree beside a live view of whatever you select: +Machines, then their projects, then each project's branches, agents and terminals. See [The interface](/docs/interface). ```text MACHINES @@ -84,33 +72,15 @@ MACHINES › zsh ``` -- **Machines** — your own computer (`local`) and any machines you add over ssh. -- **Workspace** — a machine's projects, grouped together. -- **Projects** — git repositories (or plain folders) on a machine. -- **Branches** — with uncommitted changes, commits ahead and behind, pull requests, and the agents working on them. -- **Agents** and **Terminals** — the panes running in the project. -- **CLI** — a machine's own agents and terminals, started outside any project. -- **Sessions** — conversations agents saved, ready to resume. - -See [The interface](/docs/interface) for every detail of the tree. - ## Agent states at a glance -`!` jumps to the next agent waiting for you, and a desktop notification fires when one you aren't viewing needs you. [Agents](/docs/agents#agent-states) explains how conch decides a state. +`!` jumps to the next agent waiting for you. See [Agents](/docs/agents). ## Supported agents -- **Claude Code** -- **Codex** -- **Gemini CLI** -- **OpenCode** -- **Devin** (preview) - -Others — Aider, Amp, Cursor CLI and more — run from a manifest: conch starts and watches them without reading their saved conversations. - -conch can install any of them for your user, on any machine, without root. See [Agents](/docs/agents). +Claude Code, Codex, Gemini CLI, OpenCode and Devin (preview). Others — Aider, Amp, Cursor CLI and more — run from a manifest. See [Agents](/docs/agents). ## Where to go next diff --git a/web/src/app/docs/phone/page.mdx b/web/src/app/docs/phone/page.mdx index aff1dcbc..46eb9129 100644 --- a/web/src/app/docs/phone/page.mdx +++ b/web/src/app/docs/phone/page.mdx @@ -2,80 +2,36 @@ export const metadata = { title: "Phone", description: "See your agents from you # Phone -`conch web` lets a phone reach the agents on this machine: see what each is doing, reply to one, and answer the question it is waiting on. It is a small web server that conch runs on your laptop, in front of the same server the TUI talks to. The phone reaches the laptop over [Tailscale](https://tailscale.com), or from any network through a [relay](#through-a-relay) of your own, which carries the traffic without being able to read it. +`conch web` lets a phone see your agents, reply to one, and answer the question it is waiting on. - - -Notifications are built but haven't been seen on a real phone yet. On an iPhone they need iOS 16.4 or later and conch added to the Home Screen. - - + ## What you need -- **Tailscale on both.** The phone reaches the laptop over your tailnet, so install Tailscale on the phone as well and sign in to the same account. There is no relay and no service of conch's in between: the two talk directly, and a phone that is not on the tailnet cannot reach the gateway at all. -- **`tailscale serve`**, once, to put HTTPS in front — phones need it, and the next section says why. -- **conch running on the laptop.** `conch web` starts the server itself if it is not up. - -Without a tailnet, the simplest way is a [relay](#through-a-relay): a server of yours that the phone and the laptop both connect out to. The other ways — a certificate of your own (`-cert`/`-key`) or a tunnel that terminates HTTPS in front of a loopback gateway (`-url`) — are under [Without Tailscale](#without-tailscale). +- **Tailscale** on the laptop and the phone, signed in to the same account — or a [relay](#through-a-relay) of your own. +- **HTTPS** in front, which `tailscale serve` gives you. +- **conch** on the laptop. ## Start it -The simplest way is from the TUI: **⚙ Settings → Web**. Set the address phones open — the `https://…ts.net` name `tailscale serve` gives this computer — and, if you like, the port; then **Start conch web**. It runs in the background, with no window of its own, and keeps running when the TUI closes; **Stop conch web** there, or `conch web stop`, ends it. Put Tailscale's HTTPS in front of it once: `tailscale serve --bg http://127.0.0.1:8722`. The settings are saved in `config.toml`: - -```toml -[web] -url = "https://laptop.tail1234.ts.net" -port = 8722 -``` - -From a terminal it is the same: +In the TUI, **⚙ Settings → Web**: set the address phones open, then **Start conch web**. Or from a terminal: ```sh -tailscale serve --bg http://127.0.0.1:8722 # Tailscale's HTTPS in front of the gateway -conch web -url https://laptop.tail1234.ts.net # listens on 127.0.0.1:8722, for tailscale serve -conch web pair # a QR code and a one-time code for the phone — or P in the TUI +tailscale serve --bg http://127.0.0.1:8722 +conch web -url https://laptop.tail1234.ts.net ``` -`conch web` starts conch's server if it isn't running, and keeps running in the foreground; stop it with `ctrl+c`. It is a client of that server like the TUI is, so agents keep running whether or not the gateway does. - -**It is reachable only over your tailnet.** A paired phone can type into your agents, so this is remote access to your machine. With `-url`, `tailscale serve` is in front and `conch web` listens on `127.0.0.1` only: the Tailscale app can't proxy back to the machine's own tailnet address (on macOS it gets "connection refused"), and nothing on the tailnet should reach the plain-http port directly. Without `-url` it listens on the Tailscale address, and with no Tailscale address it refuses to start. `-listen ADDR` names another address (with a warning unless it is loopback or Tailscale's); `-port N` changes the port. - -**Phones need HTTPS.** The device's token travels in a cookie marked `Secure`, which a browser only sends over HTTPS. `tailscale serve` puts HTTPS in front with a certificate for your machine's tailnet name; tell conch that address with `-url`, so the QR code points phones there rather than at the plain address it listens on, and so pages from it count as the gateway's own. Without either, `conch web` prints the two commands to run, with your machine's tailnet name filled in, and `conch web pair` says the same rather than pointing a phone at the plain address — and draws no QR code for it. Pairing from a plain `http://` page is refused with that reason — the browser would pair and then drop the key — except on the laptop itself (`localhost`), which browsers treat as secure. Or give conch a certificate yourself with `-cert FILE -key FILE` (`tailscale cert` makes one). - -## The app - -The gateway serves the app itself, so it always matches your conch build; there is nothing to install from a store. It is plain HTML, CSS and ES modules with no framework and no build step, deflated as it is served — about 34 KB for a cold start, which matters on a phone that is on mobile data rather than at home. **The live connection is deflated too**, with the window kept between messages: a pane's frame is the whole screen as styled text and the next one is that screen with a few rows changed, so a burst of them crossed the wire about fifteen times smaller when measured end to end, and cost less processor time a frame than compressing each on its own. Open the gateway's address in the phone's browser. **Add it to the Home Screen** (Safari: Share → Add to Home Screen; Chrome: Install app) and it opens like an app, without the browser's bars. It is laid out like the Claude app: warm colours, one conversation at a time, everything else a tap away. - - - -Four tabs run along the bottom — **Agents**, **Watch**, **Machines** and **Settings** — and **+** floats above them (devices with `full`). - -- **Agents** — what needs you, first. Chips along the top narrow it: **All**, **Waiting**, **Working**, **Done**, **Terminals**, each with how many. An agent waiting on a question shows the question and its choices right there: tap one to answer without opening anything. Each **working** agent shows the last line it printed under its name, live, so you can tell what it is doing without opening it; then what is done or idle, and your terminals. Each agent has its mark in a circle of its colour, ringed by its state — coral while it waits, a turning blue while it works, green when it is done. The tab's badge says how many wait for you. -- **One message to many** — **long-press** an agent's card to start choosing, tap others to add them, then **Message N**: the same message goes to each, as its own reply, with a row of the usual ones to tap (*commit and push*, *stop and summarise*, *run the tests*). An agent waiting on a question is left out, and the sheet says so — a reply would be typed onto its question. -- **Watch** — every agent's and terminal's screen at once, small and live, two to a row: a wall of monitors. A tile turns coral when its agent waits; tap one to open it. Only the tiles on screen stream (up to eight), and a project menu narrows it. -- **Machines** — each machine and how the phone reaches it (*relay*, *direct*, or *offline*), and each project on it with its branches, agents and terminals, and a dot count by state. Tap a project and **Agents** and **Watch** narrow to it; the ✕ on its chip widens them again. When the device reaches more than one [machine](#and-where-a-phone-reaches-this-computer-only), every one is listed — **a machine with nothing running on it is listed all the same**, since leaving it out reads as the phone having lost it. A machine whose own conch is older than this one says what that costs (“replies need a newer conch there”), since each machine is reached with the conch installed on it. Trying it anyway is refused with the machine named and `conch machine upgrade NAME` to mend it. -- **An agent** — a conversation: every agent along the top, ringed by its state, to move to another with a tap — or **swipe sideways** for the next one, or the one before — then its state, the question it asks with its choices as buttons, its output, and a composer pinned to the bottom, with the usual replies over it to tap (*continue*, *run the tests*, *commit it*, *open a pull request*). **Scroll the output up** to read back. An agent with a full-screen view — Claude Code, Codex — keeps its own history, as at the laptop: scroll to the top of the box and keep pulling down (or turn the mouse wheel, or tap the line at the top) and the agent scrolls back through its conversation; at the bottom, pushing up brings it forward. Because it is the agent's own view, the laptop sees it scrolled too. For anything else — a shell — earlier output loads above, as far back as the pane keeps. Back at the bottom it follows along again. While it works and the box is empty, the send button becomes **■ stop** (Esc, as at the laptop; needs `full`). A reply is held back while it waits on a question, and it says why. -- **Its terminal** — the whole screen, live, fitted to what the keyboard leaves visible so the prompt and the key row stay in view. In a window with room to spare — a browser on a laptop, rather than a phone — conch asks for the **pane itself** to be made wider, since the page can otherwise only grow its type and the columns are the laptop's. It only ever asks to **grow**: a phone never shrinks the pane your laptop is working in, and a pane already as wide as the window is left alone. A terminal has one size, so the laptop sees the change too, and if its TUI is also showing that pane it will set the size back to its own — the last one to look wins, which is the rule the TUI has always had. Devices with `view` cannot resize, because it changes what everybody sees. **Tap it and type**: the phone's keyboard goes straight to the pane, accents, paste and all. A row of keys rides on top of the keyboard — esc, tab, **ctrl** and **alt** (tap once for the next key, twice to lock), the arrows, shift+tab, `| ~ / -`, and ^C (two taps). **Aa** changes the text size; a wide terminal scrolls sideways, and scrolling up loads its history. A plain terminal opens straight on its screen. -- **Your other machines** — the gateway reaches every machine in your catalog, not only the one it runs on, keeping a client per machine as the TUI does. A row on another machine carries its name beside the agent's, and nothing is drawn for the laptop itself or when there is only one machine: the machine is only ever news when there is more than one. A machine still being reached, or one that would not answer, shows above the lists with what is wrong (`ssh: connect to host vm1 port 22: Host is unreachable`), so an empty list is an empty list rather than a phone quietly missing half of them. Notifications come from every machine, and **+ New** asks which machine to start on. -- **⋯** on an agent or terminal — switch between conversation and terminal, rename it, or close it (two taps). -- **+** (devices with `full`) — a new **task** (branch, worktree and agent), a new **agent** in a project or your home folder, with an optional first message, or a new **terminal**. The agent is a tile to tap, each with its own logo. A task can be started as **2 or 3 tries** at once, each on a branch of its own named as `conch task -n` names them, to keep the best; they open in **Watch**. - -**When the laptop can't be reached** — asleep, or off the tailnet — the app still opens, says so, and shows the agents and terminals as they were when it last heard from the laptop, with the time. It keeps trying and catches up by itself. Questions are not kept on the phone between visits: they can quote a command. - - +`conch web stop` ends it. Every flag is on [Command line](/docs/cli#web). ## Pair a phone +Run `conch web pair`, or click 🌐 in the status bar (`P` in the tree). Point the phone's camera at the QR code, or type the six-digit code. + ```sh conch web pair # full: everything, typing into terminals included conch web pair -permission reply # see agents, reply, answer questions — no typing @@ -83,128 +39,54 @@ conch web pair -permission view # look only conch web pair -machine busybox # and let it reach that machine, not only this computer ``` -Pairing says where the device will reach as well as what it may do, because a phone that reaches this computer alone is the thing people are surprised by: a machine it was not given is not shown to it at all. `-machine` pairs it for one in the same breath; without it, `conch web permission ID PERM -machine NAME` adds one afterwards. - -This prints a QR code and a six-digit code. Point the phone's camera at the QR code: it opens conch with the code filled in, and one tap pairs it. Or open the gateway's address on the phone and type the code. Either way the phone gets a token of its own, kept in a cookie the page's scripts can't read. - -**In the TUI, click 🌐 in the status bar** (beside ⚙ Settings), or press `P` in the tree, for the same: a QR code and a code, for a phone with `full`. `v`, `r` and `f` give a new code for `view`, `reply` or `full`. The dialog draws over the screen, so its text can't be selected: **click the code** to copy it, or anywhere else in the dialog to copy the pairing link (`c` and `y` do the same). The QR code needs about 37 columns by 17 rows, so it shows in an 80×24 terminal; a smaller one shows the code and the address alone. It pairs with this computer's `conch web`, whichever machine is selected in the tree. The dialog also says whether `conch web` is running; if it has run before and isn't now, **`s`** starts it again in the background, with the same flags as last time — no terminal to keep open — logging to `web.log` in conch's directory. `conch web stop` ends it. - -The code travels in the link's fragment (`#code=…`), which a browser never sends to a server, so it is in no log. - -- A code works **once**, for **5 minutes**. Asking for a new one cancels the old. -- Guesses are limited: a few attempts a minute, and five wrong codes cancel the one outstanding. -- conch keeps only a hash of each token, in `phone.json` in its [directory](/docs/configuration). The file alone doesn't let anyone in. +A phone reaches this computer only until you name a machine for it. **Add it to the Home Screen** to open it like an app. -| Permission | The device can | -| --- | --- | -| `view` | see the agents, their state and their screens | -| `reply` | also send an agent its next message, pick an answer to the question it asks, and resize a pane it has open | -| `full` (default) | also type into terminals, stop an agent, start tasks, agents and terminals, rename and close them | - -The permission is checked on every request and on every message over the live connection, not only when the phone connects. - -### And where: a phone reaches this computer only - -A permission says what a device may do. It does not say **where**, and the gateway can reach every [machine](/docs/remote-machines) in your catalog — over ssh, with your own credentials. So a device reaches **this computer and nothing else** until you name a machine for it: - -```sh -conch web permission d_7h2k full -machine busybox # and this computer, always -conch web permission d_7h2k full -machine busybox -machine gpu-1 -conch web permission d_7h2k full -machine local # take them away again -``` - -A phone without a machine is not merely unable to act on it: it is never told the machine exists. It is left out of the machine list, out of the agent and pane lists, out of `hello`, and out of notifications — a push names a pane and taps through to it, so one about a machine the device may not see is not sent. A request naming it is refused before conch says whether there is such a machine, so asking is not a way to learn what is in your catalog. +## The app -The reason is that conch cannot tell a test box from a production one, and a machine is reached as you. Pairing a phone is one decision; letting it into a machine is another, taken on purpose, one machine at a time. **Devices paired before conch could reach machines keep this computer alone** — nobody's phone gained reach because conch was updated. +- **Agents** — what needs you first; tap an answer to a waiting agent's question. +- **Watch** — every screen at once, small and live. +- **Machines** — each machine and its projects. +- **An agent** — its output and a composer; swipe sideways for the next one. +- **+** — a new task, agent or terminal. -Giving or taking away a machine applies at once, on connections already open: a phone loses a machine mid-session without being paired again, and gains one without reconnecting. + ## Devices -In the TUI, **⚙ Settings → Web → Devices…** opens a panel of every paired phone and browser: its name, ID, what it may do, the machines it reaches, when it was paired and when it was last seen — `on · relay` or `on · direct` while it has the app open — and the settings row counts the phones on now. `v`, `r` and `f` set what the selected one may do, `n` renames it, `x` twice revokes it, esc goes back. Every phone pairs as what its browser calls itself — iPhone, Browser — so naming them is how two iPhones are told apart. A change applies to the device's next request at once. - -From a terminal: +**⚙ Settings → Web → Devices…** lists paired phones, or from a terminal: ```sh -conch web devices # ID, name, permission, the machines it reaches, when it was paired, when last seen -conch web devices -json # the same, with whether conch web is on its relay, for a program to show -conch web revoke d_7h2k # cut one off -conch web rename d_7h2k Amit's iPhone # name it; no quotes needed -conch web permission d_7h2k full # let it type into terminals, without pairing again -conch web permission d_7h2k full -machine busybox # and let it reach a machine +conch web devices +conch web revoke d_7h2k +conch web permission d_7h2k full -machine busybox ``` -In Conch.app, the phone icon in the status bar shows how many phones are on now, by its colour and a count, and turns amber while `conch web` is running but not on its relay; its tooltip names each phone and its route. Its popover pairs a phone — the QR code, the code to type, what it may do, the routes it can come by with whether each is up now, and the relay's **safety code** — and **Paired phones…** lists them, each with its route or when it was last seen, what it may do (changed there), renaming it (the pencil, or double-click its name) and revoking it. **Settings → Phone** shows the same list under the relay's state, and whether `conch web` is running. **Restart** there, or **Restart conch web** in the popover, stops it and starts it again on the app's own conch — what to do after an update, since the gateway keeps running the build it started with. Phones reconnect by themselves. - -`permission` without `-machine` leaves the machines as they were: what a device may do and where it may do it are two decisions, and changing one does not quietly change the other. - -Revoking takes effect at once: the token stops working, and a running gateway closes the connections that device has open — within a quarter of a second — telling the phone why. - -An agent that conch [keeps to its own work](/docs/cli#when-an-agent-runs-these-commands) may not run `conch web pair` or `revoke`: a paired phone acts as you, not as the agent. - ## Replying and answering -These are two different things, on purpose. - -**A reply** is the agent's next message, as [`conch agent prompt`](/docs/cli#agent) sends it. It is refused while the agent waits on a question — typed in, its Enter would answer the question — and the phone is told the agent is waiting. - -An agent's or terminal's screen ends its subtitle with the pane's ID — `p12`, or `busybox:p12` on another machine — what `conch read` and `conch send` take on the computer; a tap on it copies it, as **Copy pane ID** in the **⋯** menu does. - -**An answer** picks one of the choices of the question an agent is asking. conch reads the choices off the agent's screen — a numbered menu with a cursor on one row — and the phone shows them as buttons. Tapping one moves the cursor to that row and presses Enter; nothing else is sent. The answer carries the ID of the question it was shown for, and is refused if the agent is no longer asking that question, so a tap that arrives late can't answer the next one. - -When conch can't read choices — no menu, or no cursor to steer by — the question comes without any. A device with `full` answers it in the terminal, with the key bar; the others at the laptop. +**A reply** is the agent's next message. **An answer** picks one of the choices of the question it is asking, shown as buttons. ## Review comments -Comments written on a branch's diff — in the [changes view](/docs/interface#changes-view) at the laptop, with [`conch review add`](/docs/cli#review), or by a reviewing agent — show on the card of the agent working on that branch, with `✎ 2` on its row in the list. **Send to the agent** hands them all over as one message, as `S` does at the laptop, and needs what a reply needs: `reply` or `full`. Like a reply, it is refused while the agent is waiting on a question, and the comments stay until it can take them. The phone shows and sends comments; writing them needs the diff, which is at the laptop. The unresolved comments on the branch's pull request are on the card too, with the reviewer's name, the thread's replies and **Open on GitHub** to answer them there. +Comments on a branch's diff show on its agent's card. **Send to the agent** hands them over as one message. ## Through a relay -A relay is how a phone reaches the laptop from any network with nothing to install on the phone and no port opened at home. `conch web` connects *out* to the relay and keeps the connection open; the phone opens the relay's address and connects there too; the relay pairs the two and copies what passes between them. - -What it copies, it cannot read. The pairing QR code carries the laptop's key as well as the code — in the part of the link after `#`, which a browser never sends anywhere — so the phone knows the key before it talks to anything, through the camera rather than the network. The phone and `conch web` then make a [Noise](https://noiseprotocol.org) session with it (`Noise_NK_25519_AESGCM_SHA256`, all of it in the browser's own WebCrypto), and every call, every screen and every keystroke travels inside. A relay that tried to answer in the laptop's place could not finish the handshake, and the device token that says who the phone is goes inside the session too. The relay sees that a room exists, when it is used and how many bytes pass — never what they are. - - - -**Run the relay yourself, or use one run by somebody you trust as you trust the laptop.** The encryption keeps the relay out of what it *carries*, but the relay also *serves the app* the phone opens — the code that makes the session and keeps the phone's token. A relay that served a changed app could read every screen and type into every terminal the phone may. No encryption between the two ends can rule that out; only running the relay on a server of your own does. - - - -Run one on any server that has a name and a certificate: +Reach the laptop from any network through a relay you run; it carries the traffic without being able to read it. Run the relay yourself. ```sh -conch relay -listen :8443 # behind a proxy that does HTTPS (Caddy: reverse_proxy :8443) -conch relay -listen :443 -cert FILE -key FILE # or with a certificate of its own +conch relay -listen :8443 ``` -Then, on the laptop, point `conch web` at it — in **Settings → Phone (conch web) → Relay**, or in `config.toml`: +Then point `conch web` at it in **Settings → Phone (conch web) → Relay**, or in `config.toml`: ```toml [web] relay = "wss://relay.example.com" ``` -and start `conch web` as usual. Without Tailscale it listens on loopback only and takes phones through the relay. `conch web pair` puts the relay's address in the QR code, and says the laptop's key as four words — `brook dove camel thistle` — which the phone shows too when it pairs: the same words, the same laptop. The phone asks before pairing — **They match — continue**, or **They don't match**, which forgets the link and sends nothing. The words come from the key in the QR code, so a code that did not come from your laptop shows different ones. `conch web relay` says whether `conch web` is connected to the relay now; `conch web relay reset` makes a new key and revokes every phone that paired through the relay; restart `conch web` to use it. A phone it revoked can't be told so — the laptop is no longer where the phone's link points — so the phone says the laptop isn't connected to the relay, and that a reset key is one reason why; pair it again with a new code. - -On the phone, open the link once from the QR code and add it to the Home Screen; from then on it reaches the laptop through the relay wherever the phone is. When it can't, it says which part is missing: the relay answered, but the laptop isn't connected to it — asleep, or `conch web` isn't running. - -The relay keeps nothing — no accounts, no list of laptops, no messages — and one relay serves any number of laptops, each in a room only its own `conch web` can open: the room's id is a hash of a secret the laptop keeps, so a phone that knows the id can ask for the laptop but cannot stand in for it. - -## Without Tailscale - -Phones need HTTPS, so something has to provide it. Besides a [relay](#through-a-relay), three ways, in the order they are worth trying: - -1. **Any tunnel in front of a loopback gateway** — Cloudflare Tunnel, ngrok, a VPS with Caddy. conch does not care which: `conch web -listen 127.0.0.1 -port 8722 -url https://conch.example.com`, with the tunnel forwarding to that port. `-url` is the same seam `tailscale serve` uses: it tells conch what phones will open, so the QR code and the cookie's origin agree. This is the one that works away from your network. -2. **A certificate of your own** — `conch web -listen 0.0.0.0 -port 8443 -cert FILE -key FILE -url https://192.168.1.23:8443`. The work is on the phone, not in conch: it has to trust the certificate, which for a local CA (`mkcert`) means installing the root on the phone and turning full trust on. Your LAN only. -3. **An SSH port forward from the phone**, if its SSH app can hold one: `conch web -listen 127.0.0.1`, forward the port, and open `http://localhost:8722` on the phone. Browsers treat `localhost` as a secure context, so the cookie and the service worker work with no certificate anywhere. It lasts as long as the forward does. - -`-listen` on anything but loopback or a Tailscale address warns, deliberately: a paired phone can type into your agents, so you are publishing control of this machine and the pairing code is what stands in the way. - -## What it doesn't do yet - -- Showing the question in a notification: there is no setting for it, so it is never shown. -- A list of the agents installed on the laptop: the new-task form offers every agent conch knows, installed or not. - -## What is logged - -One line per request and per message: its kind, its status and its size. Never a screen, a reply, a question or a token. +When you pair, check that the four words the phone shows match the ones `conch web pair` printed. diff --git a/web/src/app/docs/quick-start/page.mdx b/web/src/app/docs/quick-start/page.mdx index 4d572369..84623b05 100644 --- a/web/src/app/docs/quick-start/page.mdx +++ b/web/src/app/docs/quick-start/page.mdx @@ -2,7 +2,13 @@ export const metadata = { title: "Quick start", description: "From an empty term # Quick start -This guide takes you from installing conch to several agents working in parallel, each on its own branch. It takes a few minutes and assumes you have at least one agent, such as Claude Code, or are happy to let conch install one. +From installing conch to several agents working in parallel, each on its own branch. + + ## Your first session @@ -14,9 +20,7 @@ This guide takes you from installing conch to several agents working in parallel curl -fsSL https://raw.githubusercontent.com/Amitgb14/conch/master/install.sh | sh ``` -This installs `~/.local/bin/conch`, and says what to add to your shell if that folder isn't on your `PATH`. With Homebrew, `brew install Amitgb14/conch/conch` instead. See [Installation](/docs/installation) for other ways. - -`conch completion zsh` (or `bash`, `fish`) says how to get tab completion, which also lists what each command does. If anything below does not work, `conch doctor` checks git, gh, your agents and your terminal, and says how to fix what it finds. +Other ways are on [Installation](/docs/installation). `conch doctor` checks what conch needs. @@ -26,65 +30,51 @@ This installs `~/.local/bin/conch`, and says what to add to your shell if that f conch ``` -The first run starts the conch server in the background. You see the tree on the left, with your computer as `local`, and a live view of the selection on the right. `?` lists every key. - -Until you have tried them, the page on the right also lists five steps under **Getting started**: install an agent (`c`; already ticked if you have one), add a project, give an agent a task, open the review queue, and detach. Each ticks itself off once you have done it, the list goes away once all five are, and `x` on `local` hides it sooner. The steps below go through them. +The first run starts the server. `?` lists every key. -Select `local` and press `a`. A folder browser opens: `enter` opens a folder, `←` goes up, `/` filters and `g` jumps to a typed path. Press `a` to add the selected folder, or `.` to add the folder you're in. `p` creates a new project instead — a folder with a git repository and an initial commit. - -Projects also appear on their own when you open a pane inside a git repository. From a shell, `conch project add PATH` does the same, and `conch project clone https://github.com/owner/repo.git` clones a repository and adds it. In Conch.app, **File → Add Project…** (⌘O) opens a folder, clones a repository from its URL, or makes a new git repository. +Select `local` and press `a`, pick a folder and press `a` again. Or `conch project add PATH`. -With the project selected, press `c`. conch lists every agent installed on the machine with your default pre-selected, so `c` `enter` starts it in the project's folder. A missing agent can be installed from the same list. - -The agent's pane opens on the right. Type into it as you would in any terminal; `ctrl+b` then any key returns to the tree. +Press `c` then `enter` to start your default agent in the project. `ctrl+b` then any key returns to the tree. -Press `t` on the project and describe the work, for example "Add a health check endpoint". conch creates a branch named from the prompt, checks it out into `.worktrees/`, copies your local files such as `.env` into it, and starts the agent with the prompt. Start a few tasks: each is isolated from the others. - -The same from a shell: +Press `t` on the project and describe the work. conch makes a branch and worktree and starts the agent there. See [Tasks and worktrees](/docs/tasks). ```sh conch task -cwd ~/src/api "Add a health check endpoint" ``` -See [Tasks and worktrees](/docs/tasks). - -Each agent shows its state in the tree: `⠋` working, `!` waiting for you, `✓` done, `○` idle. Press `!` (or `ctrl+b !` from inside a pane) to jump to the next agent waiting for you, or click the count in the status bar. It keeps the two apart — `⚑ 1 waiting · 1 done` — as the tree's badges do (`⚑1 ✓1`): **waiting** means the agent stopped to ask you something (a permission, a question) and does nothing until you answer; **done** means it finished while you weren't watching, and turns idle once you look at it or type into it. - -To tell several agents the same thing — "run the tests and fix what you broke" — select the project and press `B`: pick who receives it and confirm. - -A desktop notification fires when an agent you aren't viewing needs you. Press `,` to open Settings, where Notifications sets how you are told — desktop, sound, terminal beep — and quiet hours. +`⠋` working, `!` waiting for you, `✓` done, `○` idle. Press `!` to jump to the next waiting agent, and `B` to tell several agents the same thing. -Select a task's branch to see its changes: its pull request (checks, review), uncommitted files, commits ahead and diffs. `enter` on a file shows its diff, `o` opens the branch's pull request and `esc` goes back. `x` on the branch removes its worktree once you're done (never with uncommitted changes). +Select a branch to see its changes. `enter` on a file shows its diff, `o` opens the pull request, `x` removes the worktree. -Press `q`. The TUI exits, but the server keeps every agent running. Close the terminal, go for lunch, then run `conch` again: everything is where you left it, including agents that finished or started waiting meanwhile. +Press `q` to detach; agents keep running. Run `conch` again to come back. -`q` only detaches. `conch server stop` stops the server **and every pane it owns**. +`conch server stop` stops the server **and every pane it owns**. @@ -98,27 +88,13 @@ Press `q`. The TUI exits, but the server keeps every agent running. Close the te -Press `M`, or from a shell: - -```sh -conch machine add gpu-box # an alias from ~/.ssh/config, user@host or ssh://user@host:port -``` - -conch probes the machine over ssh, installs itself there if needed and connects. The machine appears in the tree, and you add projects and start agents on it exactly as on `local`. See [Remote machines](/docs/remote-machines). +Press `M`, or run `conch machine add gpu-box`. See [Remote machines](/docs/remote-machines). -Press `:` (or click **✦ Ask**) and say what you want, for example "start 3 agents on api: fix the flaky login test, add rate limiting, update the README". conch proposes a plan with a checkbox for each action. - - - -Nothing runs until you press enter. - - - -See [Brain](/docs/brain). +Press `:` and say what you want. Nothing runs until you press enter. See [Brain](/docs/brain). diff --git a/web/src/app/docs/remote-machines/page.mdx b/web/src/app/docs/remote-machines/page.mdx index 761ce34c..51408bda 100644 --- a/web/src/app/docs/remote-machines/page.mdx +++ b/web/src/app/docs/remote-machines/page.mdx @@ -2,165 +2,95 @@ export const metadata = { title: "Remote machines", description: "Run agents on # Remote machines -Each machine runs its own conch server, which owns that machine's panes and agents, so work continues there when your laptop sleeps or the network drops. The TUI connects to all of them at once over your normal `ssh`. +Each machine runs its own conch server, so its agents keep working when your laptop sleeps; the TUI reaches all of them over your normal `ssh`. -## Commands - -```sh -conch machine add gpu-box # an alias from ~/.ssh/config, user@host or ssh://user@host:port -conch machine ls -conch -m gpu-box status # any command against a machine -conch -m gpu-box new -- make test # a pane in the machine's home -conch -m gpu-box task -cwd /home/dev/src/api "Fix the flaky tests" -``` - -With `-m`, `-cwd` is a directory on that machine and must be an absolute path: your shell expands `~` to your own home before conch sees it. Without `-cwd`, `new` and `task` start in the machine's home, outside every project: the task's agent gets the prompt there, with no repository needed. A `-cwd` that isn't a git repository works the same way, in that folder. - -No machine of your own? `conch sandbox -provider daytona create` (or `-provider boat`, or `-provider devin` for a Devin Cloud session's VM) makes one in the cloud and adds it here, and `conch sandbox -provider P add ID` adds one `ls` shows with no machine; see [Sandboxes](/docs/sandboxes). - -Or press `M` in the TUI — and on a [saved ssh host or an ssh session](/docs/interface#ssh-sessions), `M` offers that host as a machine with its ssh options already filled in. `conch machine rm ID` removes a machine, `conch machine rename ID LABEL` renames it, `conch machine upgrade ID` installs your build there and reloads its server, and `conch machine hosts` lists the hosts in your ssh config. See [Command line](/docs/cli#machine) for flags. + ## Adding a machine - - - - -conch probes the machine over ssh (OS, CPU, an installed conch). - -A host that needs more than a name — a jump host, a port, an old key exchange — takes **SSH options** in the `M` dialog, or `-o Setting=value` (repeatable) on `conch machine add`; they are kept with the machine and used for every connection it makes, including the bridge that carries the protocol. conch's own settings are given to `ssh` first, so a machine cannot turn off the batch mode that keeps an unwatched connection from waiting on a prompt. Options that belong to one terminal's session — a forward, a tty, agent forwarding — are dropped, since a machine's connections are not that. A changed set reconnects the machine rather than keeping a connection made the old way. - - +conch probes the machine over ssh, installs itself to `~/.local/bin/conch` there if it is missing or older, and connects. - +**How:** press `M` in the TUI, or: -conch installs itself to `~/.local/bin/conch` there if it is missing or older than your client — `machine add` asks first. - -For another platform (say a Linux server from a Mac) conch cross-compiles itself from its source tree (found next to the binary, or `CONCH_SOURCE`) with your Go toolchain, and caches the result in `~/.config/conch/binaries/-/`. The cache is keyed on your conch build *and* on that source tree, so rebuilding conch or moving the checkout on makes the next install build again. A released conch without source or Go downloads the matching release binary instead (checksum-verified). Otherwise put a binary there or point `CONCH_REMOTE_BINARY` at one. - -conch checks what the machine has after installing. If the binary it had to install is itself from an older build — a checkout older than your conch, or a `CONCH_REMOTE_BINARY` left behind — it says so and names where that binary came from, rather than starting a server from it and reporting the machine as merely needing a reload. - - - - - -conch connects through `conch bridge`, which starts the server there if needed. - - - - - -## How conch uses ssh - -conch runs the system `ssh` with a generated config that includes yours first (so your settings win) and adds keepalives and connection sharing. It stores no secrets; `machines.json` holds only an ID, label and ssh target. +```sh +conch machine add gpu-box # an alias from ~/.ssh/config, user@host or ssh://user@host:port +conch machine ls +``` -**Connections to other machines are compressed** (`Compression yes` in that generated config). What they mostly carry is panes, and a pane's frame is the whole screen as styled text: one measures 12 KB and deflates to under a kilobyte — ten to sixty times, depending on what is on screen — and 4.3 MB of real frame traffic crossed a LAN here as 54 KB, arriving sooner than it did uncompressed. It is asked for in the config rather than on each command because ssh settles compression when it opens a connection and conch shares connections: a bridge started with `ssh -C` onto a connection some earlier probe had opened gets nothing, and says nothing about it. The same sharing means installs ride along compressed too, which costs little and does a Go binary no harm. +A host that needs a jump host, a port or other ssh options takes them in the `M` dialog's **SSH options**, or `-o Setting=value` on `conch machine add`. On a [saved ssh host](/docs/interface), `M` offers it as a machine with its options filled in. -Nothing on this computer is compressed — there is no connection to settle it on, only a unix socket, which moves a frame in about 12 µs where compressing it would take 26 µs. If your machine is as fast as its link (a VM on this host, say), **Settings → Agents → Compress what a machine's panes send** turns it off. It applies to the next conch you start, since the config is written as conch comes up — and then only to connections made after that. ssh settles compression when it opens a connection, and conch keeps one per machine alive for as long as that machine is up, so a connection already open keeps what it was born with: after changing the setting, close it with `ssh -O exit -F ~/.config/conch/ssh/config user@host` and conch redials within a minute. **R** (Reconnect) on its own usually rejoins the same connection, which lingers a minute after its last session. +If ssh needs a password, type it in the **Password** field; it is never saved. With **Key login** ticked (the default), conch uses it once to add your public key to the machine. - +`conch machine rm ID`, `conch machine rename ID LABEL` (or `r` in the tree) and `conch machine upgrade ID` manage machines; see [Command line](/docs/cli#machine) for flags. -If ssh needs a password, type it in the **Password** field of the `M` dialog. It is handed to ssh only for that add (through a short-lived `SSH_ASKPASS` helper), never saved, and a new host's key is accepted the first time. With **Key login** ticked (the default), conch uses the password once to add your ssh public key to the machine's `~/.ssh/authorized_keys` — your `~/.ssh/id_ed25519`, `id_ecdsa` or `id_rsa`, or a key it creates in `~/.config/conch/ssh` when you have none — and checks that logging in with the key works, so reconnects never need the password. A copy that is dropped part-way is tried again — three attempts, a couple of seconds apart — and a connection that fails with nothing said reads as *the ssh connection failed (255)* rather than a bare exit code. conch's ssh names every key it might use — its own and your defaults — so a machine authorized with one of yours is still let in once conch has made a key of its own, whether or not `ssh-agent` holds anything. If the machine refuses keys, the status bar says so. From a shell, `conch machine add` lets ssh ask for the password on the terminal instead. +## Running commands on a machine -To rename a machine, press `r` on it in the tree (or use its menu), or run `conch machine rename ID LABEL`. The ssh target and the machine's ID stay the same. A label is a name you type (`-m busybox`, `busybox:p3`), so no two machines share one, and none is `local` or another machine's ID: a rename to one is refused, and a machine added with one — `alice@devbox` and then `bob@devbox` both default to `devbox` — is labelled with its own ID instead (`devbox-2`). +`-m` sends any command to a machine. `-cwd` is a path there and must be absolute; without it, work starts in the machine's home. -Machines added or removed with `conch machine add` and `conch machine rm` appear in (or leave) a TUI that is already open within a few seconds; conch watches `machines.json`. +```sh +conch -m gpu-box status +conch -m gpu-box new -- make test +conch -m gpu-box task -cwd /home/dev/src/api "Fix the flaky tests" +``` - +No machine of your own? A [sandbox](/docs/sandboxes) is one made in the cloud. ## Machine states -In the sidebar each machine shows its state: - | State | Meaning | | --- | --- | | `●` online | connected | | `⠋` connecting | connecting | -| `○ offline` | unreachable; its last-seen panes stay visible, dimmed, while conch retries with backoff | +| `○ offline` | unreachable; its panes stay visible, dimmed, while conch retries | | `! setup` | conch needs installing or upgrading — `m` → Install | -| `outdated` | the server there predates your client — `m` → Restart server, which stops its panes | +| `outdated` | the server there predates your client — `m` → Restart server | -`R` on a machine reconnects now; `x` removes it. To move a machine onto a new build without stopping its panes, see [Updating without stopping agents](/docs/installation#updating-without-stopping-agents). +**How:** `R` on a machine reconnects now; `x` removes it. -**Adding a machine installs conch on it, and that is not optional.** The server there is what owns the ptys: it is why an agent keeps working when you close conch, when the ssh connection drops and when the laptop sleeps, and it is what sessions, git, worktrees, the file explorer and usage are all asking. A machine without it holds no panes at all, so adding one and installing conch are the same act. What it writes is one static binary at `~/.local/bin/conch` (no root, no package manager, `.new` then an atomic rename so a half-copy is never run) and a `~/.config/conch` of its own for the socket, the log and the agent glue — your `~/.claude` and the rest are not touched, since conch launches Claude with `--settings` pointing at its own file. Nothing starts at boot. If what you want is a shell on a machine with nothing installed on it, a [saved SSH host](/docs/interface#ssh-sessions) is the right tool instead: that runs `ssh` in a pane on *this* computer and touches the far side not at all. +## Compression -**Which build a machine runs.** A machine's page says `conch build …` and then **up to date** or **older build**. The build it names is not the hash of the binary running over there: conch cross-builds that binary from this computer's source, so it is a different file for a different platform and its own hash could never match yours. What the two share is the *source* build stamped into it, which is what the page shows and what conch compares — a machine on exactly your build says so, whatever its own file hash is. Nothing is said about a server too old to report a build, rather than a guess either way. A machine's uptime is not the clue it looks like either: it counts from the *first* server of a chain of reloads, so one upgraded a minute ago still reads as days old, by design — the panes have been alive that whole time. `conch status -m ID` says `(reloaded N ago)` beside it for when the running binary was actually loaded. +Connections to other machines are compressed, since they mostly carry pane frames. -## Dropping files on a remote pane +**How:** turn it off with **Settings → Agents → Compress what a machine's panes send**. It applies to connections the next conch you start opens. -Drag a screenshot or any file from Finder, the desktop or the floating screenshot thumbnail onto conch while a pane on a remote machine has focus. Terminals paste a dropped file's path, which means nothing on the other machine, so conch uploads the file there first and pastes its path there instead. Claude Code attaches a pasted image path as `[Image #1]`; Codex, Gemini CLI and OpenCode take file paths in the prompt. +## Dropping files on a remote pane -- The status bar shows `uploading to gpu-box 40% · Shot.png`, then `uploaded to gpu-box · Shot.png`. The path goes to the pane the files were dropped on, even if you moved on meanwhile. -- A paste counts as a drop only when every word in it is the path of a file on this computer, under your home folder, a temporary folder or `/Volumes`. Anything else, and anything pasted into a local pane, is pasted unchanged. -- Files are stored in `~/.config/conch/uploads///` on that machine, readable only by you, and deleted after 7 days. -- Files over 25 MB are refused; change the limit, or turn uploads off, in Settings → Agents → Remote machines, or with `[remote]` in [config.toml](/docs/configuration#remote). The server there takes at most 256 MB. -- If one file fails, nothing is pasted and the status bar says why. A machine running an older conch gets the paste unchanged, with a warning to update it. -- SSH sessions under `CLI → SSH` have no conch server on the other side, so drops there paste the local path. +Drag a screenshot or any file onto conch while a remote pane has focus: conch uploads it there and pastes the path on that machine. Claude Code attaches a pasted image as `[Image #1]`. -`conch -m gpu-box upload FILE...` does the same from a shell and prints each file's path there. +**How:** files over 25 MB are refused; change the limit or turn uploads off in Settings → Agents → Remote machines, or `[remote]` in [config.toml](/docs/configuration#remote). From a shell: `conch -m gpu-box upload FILE...`. ## Copying files to and from a machine -To put a file somewhere of your choosing, or to bring one back, use the machine's **Files** row (`U` uploads, `D` downloads; see [A machine's own files](/docs/interface#a-machines-own-files)) or the commands: +Use the machine's **Files** row (`U` uploads, `D` downloads) or: ```sh -conch -m gpu-box upload -to ~/certs ~/doc/ca.pem # prints /home/you/certs/ca.pem -conch -m gpu-box upload -to ~ ./site # a folder, copied whole +conch -m gpu-box upload -to ~/certs ~/doc/ca.pem conch -m gpu-box download -to ~/Downloads ~/logs/run.log ~/results +conch upload -ssh bb ./site # a terminal where you typed ssh host ``` -They travel over the connection conch already has to the machine, so they work the same for an ssh host and a sandbox — whose address can change at every start, and which you may hold no key for. Paths there may start with `~`, and `upload -p` makes a `-to` folder that is missing. A name already taken on the receiving side is numbered (`ca 2.pem`) unless `-f` is given, and each path is printed as it lands. Up to 4 GB a file or packed folder; a file dropped on a pane stays limited as above. - -### A host you reached with plain ssh - -A terminal where you typed `ssh host` needs no conch on that host: `-ssh` names the terminal — its ID or name, as `conch status` shows it, beside the host it is on — and the copy goes to or from the host it is logged in to, through the host's own sftp server, with the options you typed. - -```sh -conch upload -ssh bb ./site ~/doc/ca.pem # into that host's home -conch upload -ssh p4 -p -to ~/certs ~/doc/ca.pem # into a folder there, made if missing -conch download -ssh bb -to ~/Downloads ~/logs/app.log -``` - -That needs a key or an ssh agent for the host, since nobody is there to type a password; with `-m`, it is a terminal on that machine. The same host's files are in the terminal's [Files row](/docs/interface#a-machines-own-files). - ## Moving a worktree to another machine -When this computer is slow, or you're about to close the lid, move a task to a machine that stays up: `T` on a branch in the tree, or on an agent working in it (or in the branch's changes view, or `m` → **Move to another machine or a sandbox…**), pick the machine, and confirm. That is all: conch settles the rest. +Move a task to a machine that stays up. conch finds or clones the project there, sends the branch's commits, staged, unstaged and untracked files, and hands each agent's conversation to the same agent there. The worktree here is kept until you remove it. -- **Which project:** the one there cloned from the same origin, however the URL is written (`git@github.com:acme/api.git` and `https://github.com/acme/api` match) — the one in the same place under the home folder, if there are several. If the machine doesn't have it, conch clones the origin there first, into the same place under the home folder as here; the confirmation says so. Only when that folder already holds another project, or the project here has no origin to match, does conch ask which project gets it (or where to clone). The machine needs access to the repository itself; conch never copies keys or credentials. -- **A new sandbox:** each [sandbox provider](/docs/sandboxes) with a key is listed too, as **New Daytona sandbox** and so on. Picked, conch creates one with that provider's settings in `config.toml` (`snapshot`, `auto_stop`, and `env` — the names of the variables passed in, such as `CLAUDE_CODE_OAUTH_TOKEN`; the confirmation says when none are, since an agent there then logs in afresh), installs itself there, adds it as a machine, clones the origin and moves the worktree, saying each step in the status bar. A project with no origin can't go to one: there is nothing to clone. If the sandbox can't be made or set up it is deleted; if the clone in it fails, conch says the sandbox is still running, and costing, until you stop or delete it. -- **What moves:** the branch's commits, and only those the machine lacks (it compares the branch's history first, so a pushed branch sends none); staged changes arrive staged and unstaged ones unstaged; untracked files, and the project's [local files](/docs/tasks#local-files-in-worktrees) such as `.env`, go along. Files git ignores otherwise — `node_modules`, build output — stay behind. The worktree is recreated there like any conch worktree, under `.worktrees/`. -- **Agents:** each agent working in the worktree continues there. Its conversation is [handed over](/docs/sessions#on-another-machine) to the same agent in the new worktree (an agent that saved none starts afresh), then its pane here is closed. Terminals stay. An agent in the middle of a task is stopped; changes it makes during the move stay here. -- **This computer:** the worktree and branch are kept, so nothing is lost if something goes wrong; remove them with `x` when you're done. - -The status bar follows it: `moving feat to gpu-box · sending 40%`, then `moved feat to gpu-box · 2 agents continue there`. If a step fails, conch shows why in full, nothing changes on this computer, and the other machine undoes what it started. conch refuses when the branch is already checked out there, or has commits there that the moved one doesn't. A worktree with unresolved conflicts, and one whose pack is over 256 MB (large untracked files), can't be moved. Both machines need a conch with this; an older one says to reload it. +**How:** `T` on a branch or an agent in it (or `m` → **Move to another machine or a sandbox…**), pick the machine or a **New Daytona sandbox**, and confirm. ### Moving a whole project -`T` on a project's row (or `m` → **Move the whole project to another machine or a sandbox…**) moves all of it at once: pick the machine or a new sandbox, confirm, and conch does the rest — the project there is settled as above, then every task worktree moves into it one after another, each with its agents and their conversations, and the agents in the main checkout continue in the project's own checkout there. - -- **What the confirmation lists:** the worktrees that move, every agent that continues there, and any worktree that can't move (unresolved conflicts, say), which stays here with its agents. -- **What stays:** uncommitted changes in the main checkout (commit or stash them, or start a task for them, first), terminals, and saved conversations no agent has open — share one later from **Sessions** → `s` → **On another machine**. Detached checkouts aren't moved. -- **When one worktree fails:** the others still go. The status bar says `moved api to gpu-box · 2 worktrees · 3 agents continue there`, and anything that stayed here is listed with why. - -In Conch.app, right-click the project → **Move to another machine…**. The sheet goes in three steps: **Where** (every other machine, and whether it already has a clone of the same origin, which the move joins rather than cloning again), **What moves** (read from both machines, nothing changed yet: the repository, each worktree and what it takes — commits, staged, unstaged and untracked files — the branches, the agents, and what stays here), then **Moving**, a line a step as it happens. Hide it and the move goes on; the status bar says when it's done, and **Show on …** selects the project there. +Moves every task worktree, its agents and their conversations at once; a project with no origin is copied whole. Uncommitted changes in the main checkout and terminals stay here. -From a shell, the same move is `conch project move daos -to busybox` (`-plan` to only see what would move, `-into ~/src/daos` to clone it somewhere else there, `-y` not to be asked, `-json` a line of JSON a step). Both also take **branches with no worktree** that hold commits the origin hasn't — only here, ahead of their upstream, or with their upstream gone: each is given a worktree here, then moves like the others. +**How:** `T` on a project's row, right-click → **Move to another machine…** in Conch.app, or: -A project with **no origin** moves too: there is nothing for the other machine to clone, so conch copies the repository itself — every branch and tag, bundled here and made a new repository there with the main checkout's branch checked out and no remote — and the worktrees and agents follow as above. Both servers need a conch that can (`project.bundle.v1`), and the history has to fit in 256 MB; past that, push it somewhere and move it from there. The main checkout's uncommitted files stay here, as they do for a clone. - -Moving the same project again is safe: a branch the project there already has checked out isn't copied over (whatever happened to it there is kept), its agents continue in it, and a branch with nothing left to follow it is listed as **on busybox already**. That is how an agent that stayed behind — its agent wasn't installed there yet, say — follows once it is. +```sh +conch project move daos -to busybox # -plan to see what would move, -y not to be asked +``` ## Claude Code on a machine -conch checks whether `claude` is installed on each machine (the machine view shows its version). If it isn't, `c` offers to install it, or press `C` (also in the machine menu, or `conch -m NAME agent install claude`). conch runs Anthropic's official installer (`curl -fsSL https://claude.ai/install.sh | bash`) in a pane you can watch; it installs `~/.local/bin/claude` for your user, no root. - -Then `c` starts Claude there: on first run it asks you to log in — open the link it shows on any computer and paste the code back. +**How:** `c` offers to install `claude` where it is missing, or press `C` (or `conch -m NAME agent install claude`). It runs Anthropic's installer in a pane; then `c` starts Claude, which asks you to log in on first run. -conch never copies credentials between machines. For unattended machines Claude also accepts `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from `claude setup-token`. +conch never copies credentials between machines. Unattended machines can use `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from `claude setup-token`. - -Alpine needs `apk add bash curl libgcc libstdc++ ripgrep` (as root) first. diff --git a/web/src/app/docs/sandboxes/page.mdx b/web/src/app/docs/sandboxes/page.mdx index 0de1e3f0..84b6bf58 100644 --- a/web/src/app/docs/sandboxes/page.mdx +++ b/web/src/app/docs/sandboxes/page.mdx @@ -2,13 +2,19 @@ export const metadata = { title: "Sandboxes", description: "Run agents in a clou # Sandboxes -A sandbox is a machine in the cloud that conch creates for you, so a long agent task runs away from your laptop and keeps running when you close it. conch makes the sandbox, installs itself there and adds it as a [remote machine](/docs/remote-machines): `-m` and every other machine feature work with it. +A sandbox is a cloud machine conch makes and adds as a [remote machine](/docs/remote-machines), so a task keeps running with your laptop closed. -In the tree they sit together under **Sandboxes**, one group per provider, so a fleet of them doesn't fill the top: + +M → New sandbox…, and conch sets it up as a machine. +A link to a dev server running inside. +Time up and what the provider billed, beside each row. +Idle ones stop; what was running comes back. + + +In the tree they sit under **Sandboxes**, one group per provider: ``` ▾ ● local -▾ ● busybox ▾ ▤ Sandboxes 3 ▾ Daytona 2 ▸ ● sdx01 @@ -17,22 +23,19 @@ In the tree they sit together under **Sandboxes**, one group per provider, so a ▸ ● sdx01 ``` -Each one opens like any machine — its projects, agents and terminals underneath — and `m` on its row starts, stops or deletes it. Selecting **Sandboxes**, or one provider, shows what is in it with each sandbox's state. The group appears once there is a sandbox; the same label under two providers is two different sandboxes, and each keeps its own row. - -Four providers are supported: +## Providers | Provider | What it is | How conch gets in | | --- | --- | --- | -| [Daytona](https://www.daytona.io) | sandboxes with an ssh gateway, sized in vCPUs, memory and disk | a fresh ssh token per connection, through Daytona's gateway | -| [boat.dev](https://boat.dev) | whole Ubuntu machines in named sizes, with an sshd of their own | your own public key, authorized in the sandbox | -| [Tensorlake](https://docs.tensorlake.ai/sandboxes/quickstart) | microVMs sized in vCPUs, memory and disk (10–100 GiB), suspended and resumed with their memory | your own public key, registered once with your Tensorlake account, through its ssh gateway `sandbox.tensorlake.ai`. Not offered in **New sandbox…** in the TUI or Conch.app; made only with `conch sandbox -provider tensorlake create` | -| [Devin Cloud](https://docs.devin.ai/cli/cloud) | the VM of a Devin Cloud session, with Devin in it; sized by Devin, placed on a platform or an outpost pool | `devin ssh`, the devin CLI's own approved connection | +| [Daytona](https://www.daytona.io) | sandboxes sized in vCPUs, memory and disk | a fresh ssh token per connection | +| [boat.dev](https://boat.dev) | whole Ubuntu machines in named sizes | your public key, authorized in the sandbox | +| [Devin Cloud](https://docs.devin.ai/cli/cloud) | the VM of a Devin Cloud session | `devin ssh` | -Everything on this page works with all of them unless it says otherwise. Where they differ — sizes, prices, snapshots, what stopping keeps — it says so. Devin Cloud does least of it: no preview links, snapshots or billed cost, since its API has none to give. +Tensorlake sandboxes are made from the command line only (`conch sandbox -provider tensorlake create`). ## Setting up -Create an API key in the provider's dashboard and put it in your environment: +Create an API key in the provider's dashboard and put it in your environment, then restart conch: ```sh export DAYTONA_API_KEY=dtn_… # Daytona @@ -41,206 +44,91 @@ export DEVIN_API_KEY=cog_… # Devin Cloud: a service user's key export TENSORLAKE_API_KEY=tl_… # Tensorlake ``` -Tensorlake's gateway lets in the ssh keys registered with your account, and registering one takes your own login rather than an API key, so conch cannot do it for you. A sandbox made before that is paid for and then cannot be set up, which is why Tensorlake is left out of **New sandbox…** and is made from the command line only. Its sandboxes are still listed, added and deleted like any other. Register your key once, with [Tensorlake's CLI](https://docs.tensorlake.ai/sandboxes/remote-dev): - -```sh -pip install tensorlake -tl login -env -u TENSORLAKE_API_KEY tl sbx ssh keys add --name laptop ~/.ssh/id_ed25519.pub -``` - -(`env -u` because the key in `TENSORLAKE_API_KEY` would be used instead of your login, and registering a key is refused to an API key.) Until it is registered, a sandbox is made but conch cannot log in to it: it says Tensorlake refused your ssh key, with these steps, and asks whether to delete the sandbox — your project may allow only one running at a time. **API endpoint** in its settings is the API's base, `https://api.tensorlake.ai`; one given with `/sandboxes` on the end is taken as its base. - -conch offers the first of `~/.ssh/id_ed25519`, `id_ecdsa` and `id_rsa` it finds (else a key of its own, in conch's directory: register that one). Every sandbox conch makes there is named `conch-…`, since only a named sandbox can be suspended and resumed, and that is how `conch sandbox -provider tensorlake ls` tells conch's apart from yours. Stop suspends it, keeping its disk and memory; start resumes it. Tensorlake takes no variables when a sandbox is made — only secrets it already holds — so a sandbox with `env` set is refused, with that reason; and the snapshot setting is the image a sandbox starts from. - -Devin Cloud also needs the [devin CLI](https://docs.devin.ai/cli/cloud), installed (`conch agent install devin`) and signed in (`devin auth login`): its API makes the session, but only the CLI's login can open the way into its VM. conch makes the session in the organization `$DEVIN_ORG_ID` names, or else the one Devin says the key's sessions run in. - -Only the provider you use needs a key. A provider with no key is still listed, and says what is missing rather than failing when you try. - -By default conch reads the key from the environment every time and never writes it down — set it where your shell will have it (`~/.zshrc`), and restart conch, since a running process keeps the environment it started with. The key is read by whatever connects: the TUI and the `conch sandbox` commands, never the server, and it never goes over the protocol. A different variable can be named in Settings (`,` → **Sandboxes** → the provider) or as `api_key_env` in [`[sandbox.]`](/docs/configuration#sandbox), along with the snapshot, region, auto-stop and what of your environment every new sandbox gets. Each provider has its own section, and its own key. - -If you would rather not keep it in your shell at all, Settings → **Sandboxes** → the provider → **API key** takes the key itself. It is then written to `config.toml` (0600) as it is: anything running as you can read it, and it travels with a backup or a synced dotfile, so it is the convenient choice rather than the careful one. A key kept there wins over the variable, the settings show only its last few characters, and emptying the field gives the variable back. - -## The provider registry - -Providers that others have adapted (see below), checked with their own key and published are in the **provider registry**, [github.com/Amitgb14/conch-sandbox-providers](https://github.com/Amitgb14/conch-sandbox-providers): Hetzner Cloud and DigitalOcean to start with. Installing one costs no agent's time. **Settings → Sandboxes → Add provider…** opens on it in Conch.app; `M` → **New sandbox…** → **\* Install a provider from the registry…** in the TUI; or: - -```sh -conch sandbox provider search # what there is, and what you have of it -conch sandbox provider install hetzner -conch sandbox provider update # newer versions of what you installed -``` - -Before saving anything, install says where the file sends your API key and where ssh goes, and asks. It checks that the file it downloaded is the one the registry's index lists, by its hash, and checks the file as it checks one you adapted. With the key set, it lists your sandboxes too, which makes nothing. An installed provider is a provider like any other, marked **adapted**. - -`update` takes the registry's newer version of each one you installed, but never: - -- **a file you have edited** since you installed it: that one is left alone, and saying `rm` then `install` takes theirs. -- **new hosts**, unless you say yes: a file that would send your key somewhere new is shown, and with `-y` it is left as it is. - -A provider that has left the registry is kept. - -**Publishing one of yours.** `conch sandbox provider publish NAME`, or **Publish…** beside it in Settings, first lists sandboxes with your key, so only a file that has worked is proposed. It then opens a pull request to the registry through `gh`, as you: through your fork, or straight to the repository if you can push to it. The pull request holds the file and a `meta.json` saying who adapted it, from which docs, and when your key last listed sandboxes with it. Your key is not in it. `-dry-run` shows both files and opens nothing. The registry's checks run on it: conch's own check, no secrets, and a provider's hosts kept unless a maintainer allows a change. A maintainer reviews it before it is listed, since the file is what everybody's key will be sent with. - -The registry is read from `https://amitgb14.github.io/conch-sandbox-providers`; `CONCH_PROVIDERS_URL` points conch at another, such as one of your own. - -## A provider conch doesn't know - -conch can be taught a provider it has no code for, from that provider's API docs. **Settings → Sandboxes → Add provider…** in Conch.app, `M` → **New sandbox…** → **+ Add a provider conch doesn't know…** in the TUI, or: - -```sh -conch sandbox adapt https://api.example.dev/sandboxes # Claude writes it -conch sandbox adapt -agent codex -name acme https://docs.acme.dev/openapi.json -``` - -If the registry has that provider already (by its name, or the host of the address you give), conch says so and offers to install it instead; `-new` adapts it all the same. - -conch downloads the docs — the address you give, or, when that is the API itself answering *401*, the usual places beside it (`llms.txt`, `openapi.json`/`.yaml` on the docs host) — and starts the agent in a pane of its own, in a folder holding those docs and the format of a **provider file**. The agent writes the file: which call makes a sandbox, looks at one, lists them, starts, stops and deletes one; which of the provider's states mean started, stopped and the rest; and how ssh gets in — a gateway with a key registered with your account, an sshd conch hands its key to through the API, or a credential handed out per connection. It checks its own work with `conch sandbox provider check -offline`. You can watch it, and answer it if it asks. - -conch then shows what it will do with the file, a line per call, and checks it — every call there, every state mapped, the ssh way in. Asking the provider for its list with your key, which makes nothing, waits for you: the agent wrote both the variable the key is read from and the host it is sent to, so on a terminal conch names the two (`$ACME_API_KEY to https://api.acme.dev`) and asks first, and Conch.app leaves it to `conch sandbox provider check NAME`, once you have read the file. Nothing is a provider until you save it (**Save provider**, or `conch sandbox provider save NAME`); until then it is a draft in `~/.config/conch/providers/drafts/`. Something wrong with it can be sent back to the same agent (**Ask Claude to change…**, or `conch sandbox adapt -revise "…" NAME`). - -Saved, it is `~/.config/conch/providers/NAME.toml`, and it is a provider like the others: in **New sandbox…**, `conch sandbox -provider NAME …`, Stop, Start, Delete and the idle stop, marked **adapted** wherever providers are listed. It is a description, not code: conch reads it with one provider of its own, so a wrong file fails a check or a call — and says which call — rather than doing something else. Edit it by hand if you like; `conch sandbox provider check NAME` says whether it still holds. `conch sandbox provider rm NAME` forgets it, and refuses while a machine here is one of its sandboxes. - -Some things it cannot do: - -- **A provider with no ssh** cannot be adapted. conch runs everything in a sandbox over ssh; one that offers only its own way to run commands (E2B's, for one) is refused with that reason, and nothing is saved. -- **The key is yours and conch's.** It is never put in the agent's prompt or folder, and the variables API keys are usually kept in are emptied in the agent's pane — but the agent runs as you, so do not adapt a provider with an agent you would not trust in your shell. -- **The agent reads what the docs say**, and a docs page can say anything. Read the lines conch shows before saving: they are every request it will make, with your key, to that address. -- **Format 2.** A file says `format = 2` when it needs what the first format lacked: - - **A wrapped reply:** `[get] item`, when one sandbox comes back as `{"server": {...}}`. - - **Your public key at creation:** `{public_key}` in the create body, put in through cloud-init where a provider has no key registry. - - **A selector:** `networks.v4[type=public].ip_address`, for an address kept in a list. +Devin Cloud also needs the devin CLI installed (`conch agent install devin`) and signed in (`devin auth login`). - A conch older than 0.1.10 refuses such a file rather than misreading it. -- Snapshots, preview links and what a sandbox has cost are left out: an adapted provider makes, starts, stops, deletes and reaches sandboxes, and the built-in ones do the rest. +**How:** a different variable, or the key itself, goes in Settings (`,` → **Sandboxes** → the provider) or [`[sandbox.]`](/docs/configuration#sandbox), with the snapshot, region and auto-stop. ## In the TUI -Press `M`, choose **New sandbox…** and then the provider — Daytona (`d`), boat.dev (`b`) or Devin Cloud (`e`) (Tensorlake is [command line only](#setting-up)), or one you [adapted](#a-provider-conch-doesnt-know), and whatever conch grows later sits beside it under the first letter of its name nobody else has; `esc` goes back to the machine menu. The dialog takes a label, a snapshot, a size and the names of environment variables to pass in; leave any of them empty for the defaults. boat.dev's machines come in named sizes rather than numbers: put `small`, `default` or `large` where the snapshot goes and leave vCPUs, memory and disk empty — a number there is refused, with that sentence, rather than quietly ignored. Devin Cloud's dialog asks for a **Platform** where the snapshot goes and no size at all, and says before anything is made that Devin works, and bills, in the session. conch creates the sandbox, sets itself up there and adds the machine to the tree, which takes a minute or two — and says what it is doing while it does it, in the status bar with a spinner: *asking boat.dev for a sandbox…*, *waiting for hull to answer…*, *copying conch to hull (16 MB)…*. A provider says a sandbox is started before its sshd is (Daytona says so within a second), so conch waits for it to answer, and tries again when a connection drops — copying 16 MB is the longest thing it asks of one — rather than throwing the sandbox away at the first refusal. That line stays until the job is done, unlike a message that fades. If setting up fails, the sandbox is deleted rather than left to cost — it says that too — and the reason is shown. +**How:** press `M`, choose **New sandbox…**, then Daytona (`d`), boat.dev (`b`) or Devin Cloud (`e`). Leave label, snapshot and size empty for the defaults. If setup fails, the sandbox is deleted. `m` on a sandbox's row adds: | Item | What it does | | --- | --- | -| **Start sandbox** | on a stopped sandbox: starts it and connects | -| **Stop sandbox…** | ends its agents and terminals; its files stay. Asks first, saying how many agents are still working | -| **Delete sandbox…** | deletes it and everything in it, and removes the machine. Asks first, listing the branches conch last saw there with commits no remote has, and uncommitted changes | - -A stopped sandbox shows `stopped` in the tree, and a spinner while it is starting, stopping or being deleted. **Remove machine** only takes it out of the tree; the sandbox keeps running, and costing, until `conch sandbox -provider P rm`. +| **Start sandbox** | starts a stopped sandbox and connects | +| **Stop sandbox…** | ends its agents and terminals; its files stay | +| **Delete sandbox…** | deletes it and everything in it, after listing unpushed work | ## Looking at what runs inside -An agent that starts a dev server in a sandbox has nothing to show for it — the port is inside somebody else's machine. `m` → **Open a port in the browser…** asks which port (3000 to begin with, then whatever you used last) and opens a link to it. From a shell: `conch sandbox -provider P url ID PORT`, with `-open` to open it and `-expires` to change how long it lasts (an hour by default, a day at most). - -The link carries its own credential, so it works in any browser — and so anyone with the link can reach that port until it expires. Daytona keeps 22222, 2280 and 33333 for itself; conch refuses those rather than letting you wonder why the page is wrong. boat.dev's links are the other kind: one per port, at the sandbox's own address, which stays the same the next time you ask and lasts as long as the sandbox — `-expires` means nothing to it. - -conch tries the link before opening it. When the proxy reaches the sandbox and finds nothing there — a `502 proxy upstream error` — it says so instead of opening that page, and says what usually mends it: **the server has to listen on `0.0.0.0`, not `127.0.0.1`**. The proxy arrives on the sandbox's own network interface, where a loopback-only server cannot be seen; `next dev --hostname 0.0.0.0`, `vite --host`, `rails s -b 0.0.0.0`. The link is put on your clipboard either way, so you can try it again once the server is up. +**How:** `m` → **Open a port in the browser…**, or `conch sandbox -provider P url ID PORT -open`. Anyone with the link reaches that port until it expires. The server must listen on `0.0.0.0`, not `127.0.0.1`. ## Keeping one to make others from -A sandbox that is set up — the repository cloned, dependencies installed, an agent logged in — can be kept and used as the starting point for the next one. `m` → **Keep a snapshot…**, or `conch sandbox -provider P snapshot ID`, names it; `conch sandbox -provider P snapshots` lists what is kept and `-rm NAME` forgets one. Then **New sandbox…**, or `conch sandbox -provider P create -snapshot NAME`, starts from it. - -Daytona takes a cold snapshot, which wants the sandbox stopped first, and says so if it isn't — nothing is changed when it refuses. boat.dev takes it from a running sandbox instead, and keeps ten named ones, so forgetting one is how you make room. Either way a snapshot takes a few minutes to become usable, is kept until you forget it, and is charged for storage meanwhile. +**How:** `m` → **Keep a snapshot…** or `conch sandbox -provider P snapshot ID`; start from it with **New sandbox…** or `create -snapshot NAME`. Snapshots are charged for storage. ## What one has cost -A sandbox costs while it runs, so the tree shows how long each has been up — `4h 12m` beside its row, and the total on the Sandboxes page. conch asks the provider what it has billed, every quarter of an hour, and shows that. Daytona reports per sandbox on its own analytics host; conch learns which organization to ask from the sandbox itself, so there is nothing to configure. boat.dev answers with one number for the whole sandbox — the seconds it has run and what they cost — so its detail page shows that single stretch rather than a period each. Those figures settle hours behind what is running, so until they arrive conch falls back to an estimate, marked with a `~`: `4h 12m · ~$0.59` is conch's arithmetic, `4h 12m · $0.03` is the provider's own number. - -Set what an hour costs in Settings → **Sandboxes** → the provider → **Price an hour** (per vCPU, per GiB of memory, per GiB of disk, from the provider's own pricing page) and the money appears beside the time: `4h 12m · $0.59`. conch ships no price list, because providers change theirs and a stale one misleads. - -`m` → **What it has cost…** asks the provider afresh and shows where the money went, newest first — each stretch the sandbox was billed for, what it was doing then, and what that cost: - -``` -Daytona f4c07743-2955-4c24-9977-9db242af22af - -$0.009 since 26 Sep 09:00 +The tree shows how long each sandbox has been up and what the provider billed: `4h 12m · $0.03` (`~` marks conch's estimate). -26 Sep 17:32 5m 48s $0.006 running · 1 vCPU, 1 GiB, 3 GiB disk -26 Sep 16:45 47m 02s $0.000 stopped · 3 GiB disk -26 Sep 16:43 1m 35s $0.002 running · 1 vCPU, 1 GiB, 3 GiB disk -``` - -`conch sandbox -provider P usage [-since 720h] ID` prints the same as a table. A provider with nothing to report yet says so rather than showing an empty page. - -**Stopped is not always free.** The disk a stopped sandbox keeps is charged until the sandbox is deleted — on a small Daytona sandbox that is most of what it costs over a week. boat.dev is the exception: it charges for machine time only, so a stopped sandbox there costs nothing and shows nothing. A stopped sandbox's row shows what it has cost all told, and — while the provider has yet to report anything — the rate its disk keeps costing: `disk $0.23/month` rather than nothing, and the Sandboxes page totals it: *stopped ones keep $0.47/month of disk*. Rates are shown in whatever unit says something — an hour, a day or a month — because a few GiB of disk rounds to `$0.000/h` and tells nobody anything. It is a rate rather than a total because a provider doesn't say when a sandbox stopped, and a total conch cannot know would be worse than the rate it can. +**How:** set **Price an hour** in Settings → **Sandboxes** → the provider. `m` → **What it has cost…** or `conch sandbox -provider P usage ID` shows each billed stretch. ## Stopping one nobody is using -A sandbox costs while it runs, and it is easy to leave one running. conch pauses a sandbox when no agent there is working, none is waiting for an answer, and no pane has printed for **30 minutes** — Settings → **Sandboxes** → the provider → **Stop when idle** changes it (15, 30, 60, 120 or never), per provider, as `idle_stop` in [`[sandbox.]`](/docs/configuration#sandbox). The status bar says which sandbox went and why, its files are kept, and `m` → **Start sandbox** brings it back where it was. +conch stops a sandbox when no agent is working or waiting and no pane has printed for **30 minutes**. Its files are kept. -This is conch's own watching, not the provider's. Daytona's `auto_stop` counts only what reaches it from outside — an ssh connection, a preview request, an API call — so an agent working quietly inside looks idle to it and would be stopped mid-task. conch leaves that timer off and watches the agents and panes it can actually see. boat.dev has no idle timer at all, only a lifetime from when the sandbox was made: conch gives a new one a day, which `auto_stop` changes, and its own watch is what stops one nobody is using before then. +**How:** Settings → **Sandboxes** → the provider → **Stop when idle** (15, 30, 60, 120 or never), or `idle_stop`. conch never starts a stopped sandbox by itself. ## Starting one again -Stopping a sandbox ends every process in it — that is what stopping means, and the provider keeps the filesystem rather than the memory. The work itself stays: the checkout is as it was, and an agent's conversation is saved in the sandbox's own home. - -So conch writes down what was running — each agent, its conversation and its folder, and each terminal — and offers it back when the sandbox starts again: - -> sdx1 was running 2 Claude Code agents and a terminal when it stopped. Start them again? 2 agents carry on where they left off. +When a stopped sandbox starts, conch offers to start again the agents and terminals that were running. -Each is started in turn, and conch says what came of it: *started 3 of them again in sdx1*, or the reason each one didn't — a sandbox that comes back with nothing showing and nothing said is the thing to avoid. The first pane to start is opened, so it is plain that something is running. An agent whose conversation has gone is started afresh in the same folder rather than skipped; any other refusal is reported instead, so a busy or broken server doesn't quietly get a second agent. - -Nothing is started until you say yes: an agent picking up where it left off is not always what you want to happen twice. Settings → **Sandboxes** → the provider → **Bring back what was running** turns the whole thing off, per provider (`restore_running`), and then conch keeps no note of what ran — the conversations are still on the sandbox's disk, and the Sessions view still finds them. Agents with a saved conversation are resumed on it; one that saved none starts afresh, and the question says which is which. The note survives conch restarting, and is forgotten when the sandbox is deleted or when something is already running there. - -## Deleted somewhere else - -A sandbox deleted in the provider's own interface is gone as far as conch is concerned, however long Daytona takes to finish: `conch sandbox -provider P ls` shows it as `gone` rather than sitting at `destroying`, starting or stopping it says so straight away instead of waiting, and the machine it left behind is cleared with `conch sandbox -provider P rm ID` (or **Delete sandbox…** in the tree, which then only tidies up). The listing says as much when anything is in that state. +**How:** say yes when asked. **Bring back what was running** (`restore_running`) turns it off per provider. ## Commands ```sh conch sandbox -provider daytona create -label fix-login # make one, install conch, add it as a machine -conch sandbox -provider boat create -label hull # the same with boat.dev -conch -m fix-login task -cwd /home/daytona/api "Fix the flaky tests" # a branch in a checkout there -conch -m fix-login task "Plan a CLI for tracking expenses" # an agent in its home, no repository (t on its row) -conch sandbox -provider daytona ls # conch's Daytona sandboxes and their state -conch sandbox stats # every provider's sandboxes at once +conch -m fix-login task -cwd /home/daytona/api "Fix the flaky tests" +conch sandbox -provider daytona ls # conch's sandboxes and their state +conch sandbox stats # every provider at once conch sandbox -provider daytona ssh fix-login # a shell in it -conch sandbox -provider daytona ssh fix-login git -C api status # or one command, exiting with its status -conch sandbox -provider daytona stop fix-login # ends its agents and terminals; files stay +conch sandbox -provider daytona stop fix-login conch sandbox -provider daytona start fix-login -conch sandbox -provider daytona rm fix-login # deletes it and everything in it +conch sandbox -provider daytona rm fix-login +conch sandbox -provider P add ID # make one ls lists a machine ``` -`create` takes `-snapshot`, `-cpu`, `-memory` and `-disk` (GiB), and `-env NAME` to pass one of your environment variables in, say `CLAUDE_CODE_OAUTH_TOKEN`. A named variable that isn't set is refused before anything is created. If setting conch up fails after the sandbox was made, `create` offers to delete it so it doesn't keep costing; `-yes` deletes it without asking. - -`-provider daytona` or `-provider boat`, in front of any subcommand, says whose sandboxes you mean. Every subcommand but `stats` needs it, and there is no default: a command without it is refused rather than guessing at an account you didn't pick, and a sandbox named under a provider that isn't its own — `-provider boat stop fix-login` for a Daytona sandbox — is refused with the provider it does belong to. +Flags are on [Command line](/docs/cli#sandbox). -`conch sandbox stats` needs no provider: it asks every provider at once and lists all their sandboxes in one table, with the provider in the first column, then a line for each provider — how many sandboxes it has, how many are in each state, the vCPUs and memory of the running ones, and how many have no machine here. A provider with no key says it is not set up; one that can't be asked (a bad key, the service down) says why, shows its machines' state as `?`, and makes the command fail, so a script can tell. `-provider P` narrows it to one. - -`conch sandbox -provider P ssh ID` opens a shell in a running sandbox, through the same fresh access conch connects with, so there is no token to copy. Anything after the ID is run there instead, and it exits with its status, so it works in scripts; `-t` gives such a command a terminal, for one that draws a screen (`conch sandbox -provider daytona ssh -t fix-login htop`). A stopped sandbox is refused with the command that starts it. - -`start`, `stop` and `rm` take the machine's ID or label, or the provider's own sandbox ID. `stop` and `rm` ask first; `-y` doesn't. Before deleting a running sandbox, `rm` lists branches there with commits no remote has and uncommitted changes. - -`conch sandbox -provider P ls` also lists sandboxes with no machine here — one whose setting up failed, one removed with `conch machine rm`, or, with a provider that lists the whole account rather than only conch's own (boat.dev has no labels to tell them apart), one you made yourself. They show with `-` for the ID and label, and a line underneath says so: they cost until `conch sandbox -provider P rm ID` deletes them. The size column names only what the provider reports, so a boat.dev sandbox shows `4 vCPU, 8 GiB` rather than inventing a disk it said nothing about. - -`conch sandbox -provider P add [-label L] ID` makes one of them a machine: it starts the sandbox if it is stopped, installs conch there and adds it to the sidebar, as `create` would have. It takes only what `ls` lists — with Daytona and Devin Cloud that is what conch made, since they list sandboxes by conch's label; a sandbox or session you made in their own interface is refused, as conch would lose sight of it (and a Devin session made by hand is somebody's work, which conch's wake-up message would interrupt). A sandbox conch already has a machine for is refused with that machine's name. If setting it up fails, the sandbox is left as it was — it is yours, so nothing offers to delete it. `[sandbox.P] env` and `auto_stop` are given to a sandbox when it is made, so one conch did not make — on boat.dev, which lists the whole account — has neither; `add` says so when they are set, and an agent there may start logged out until you sign it in. - -## Running until you stop it - -A Devin Cloud session is never just a machine: Devin has to be given a task, and works on it. conch gives it one asking it to change nothing and wait, so it does as little as it can — but it is billed in ACUs while the session runs, like any session. Devin also puts a session to sleep when nothing has happened in it for a while, and a sleeping session's VM is not running: conch shows it **stopped**, and **Start sandbox** wakes it (with a message, which is the only way Devin's API has). Stopping one archives it, which is how the API puts a session to sleep; starting it unarchives it again. Deleting one ends the session for good. A session asleep for a reason waiting won't mend — out of credits, a usage limit — says so instead of starting. - -Daytona stops an idle sandbox after 15 minutes by default, and an agent working inside doesn't count as activity — only an ssh connection or an API call does. So a sandbox conch creates never stops on its own: close the TUI and its agents carry on. It costs for as long as it runs, so stop or delete it when you're done. `auto_stop` in [`[sandbox.]`](/docs/configuration#sandbox) sets a timeout instead. - -boat.dev is the other way about: a sandbox is given a length of life when it is made, counted from then and not from the last thing that happened in it. conch asks for two hours, which is what the free trial allows, and Settings → **Sandboxes** → **boat.dev** → **Life** (`auto_stop`, in minutes) raises it on a paid plan; a plan that allows less says so, and conch asks again for the longest it named instead of failing. conch's own idle watch stops a sandbox nobody is using long before that clock runs out, and **Start sandbox** gives it a fresh two hours. +## Getting the work out -conch never starts a stopped sandbox by itself: use **Start sandbox** in its menu, or `conch sandbox -provider P start ID`. +**How:** `T` on a branch or agent, then **New Daytona sandbox**, moves the worktree there ([Moving a worktree](/docs/remote-machines#moving-a-worktree-to-another-machine)). Bring code back by pushing the branch, or with `T` again. -## Getting the work out +## The provider registry -Work goes *in* the same way: `T` on a branch or an agent, then **New Daytona sandbox** (or another provider's), makes a sandbox for it and moves the worktree and its agents there in one go (see [Moving a worktree to another machine](/docs/remote-machines#moving-a-worktree-to-another-machine)). +Providers others have adapted, such as Hetzner Cloud and DigitalOcean, from [the registry](https://github.com/Amitgb14/conch-sandbox-providers). Install says where your key is sent and asks first. -The code comes back the way it would from any machine: push the branch from the sandbox, or move the worktree back with **T** (see [Remote machines](/docs/remote-machines)). The sandbox needs its own access to a private repository — a token scoped to that repository, passed with `-env`. +**How:** `M` → **New sandbox…** → **\* Install a provider from the registry…**, Settings → Sandboxes → **Add provider…** in Conch.app, or: -## How conch reaches it +```sh +conch sandbox provider search +conch sandbox provider install hetzner +conch sandbox provider update +conch sandbox provider publish NAME # a pull request through gh +``` -All are reached over ssh, by different means. +## A provider conch doesn't know -With Daytona, each connection asks for a fresh ssh token and goes through Daytona's ssh gateway, so nothing that lets you in is saved. The token is kept out of conch's messages, but ssh has it on its command line while connected, where other users of your computer could see it in the process list. Daytona's gateway key is accepted the first time it is seen. +An agent reads the provider's API docs and writes a provider file; conch shows each call it will make and checks it before you save. The provider needs ssh. -With boat.dev, the sandbox is a machine with an sshd of its own. A new one is ready a moment before it has an address, so conch waits for one rather than failing a create that was going to work. conch authorizes your public key in it — your default `~/.ssh/id_*.pub`, or one conch makes for itself — and connects to the machine directly as `user`, offering that same key (`-i`, and nothing else), so the half that opens it never leaves your computer and there is no token to hide. Your key does not need to be in `ssh-agent`. A sandbox that comes back from being stopped lands on another machine, so where to connect is read afresh each time, and the new host key is accepted as the gateway's is. +**How:** `M` → **New sandbox…** → **+ Add a provider conch doesn't know…**, or: -With Devin Cloud, conch runs `devin ssh SESSION`, which wraps ssh to Devin's gateway (`ssh.devin.ai`) and approves the connection with the CLI's own login — plain ssh there would ask for approval in a browser, and the API hands out no credential for it. What conch runs there goes as an ssh `RemoteCommand`, encoded, so it arrives whole whatever the CLI does with the options it is given. `conch sandbox -provider devin ssh` opens a shell the same way. A session whose CLI isn't signed in says so (`not logged in — run devin auth login first`) rather than hanging. +```sh +conch sandbox adapt https://api.example.dev/sandboxes +conch sandbox provider save NAME +``` diff --git a/web/src/app/docs/sessions/page.mdx b/web/src/app/docs/sessions/page.mdx index 09384ebe..d4dd644f 100644 --- a/web/src/app/docs/sessions/page.mdx +++ b/web/src/app/docs/sessions/page.mdx @@ -1,12 +1,19 @@ -export const metadata = { title: "Sessions", description: "Resume saved conversations and interrupted runs." } +export const metadata = { title: "Sessions", description: "Resume, search and share saved conversations, and interrupted runs." } # Sessions -Agents save their conversations; conch lists them per project so you can resume any of them in the right folder. It also remembers agents that were running when the server stopped. +conch lists the conversations your agents saved, per project, so you can resume, search or hand on any of them. + + +Every agent's conversations for a project, newest first. +Pick one up in its folder with the agent's own resume option. +Hand a conversation to another agent, here or on another machine. +Agents that were running when the server stopped, back in one key. + ## Saved conversations -Every project has a **Sessions** section in the tree. Select it to list, on the right, the conversations agents saved for the project and its worktrees — Claude Code, Codex, Gemini CLI, OpenCode and Devin — newest first, with the agent, title, branch, what it used and its age: +Select a project's **Sessions** section in the tree to list what Claude Code, Codex, Gemini CLI, OpenCode and Devin saved for it and its worktrees, with the agent, title, branch, what it used and its age. ```text Sessions · api enter resume · * star · / search · s share · d delete · a agent @@ -18,17 +25,11 @@ Sessions · api enter resume · * star · / search · s share · d delete · a · Gemini CLI Explain the auth flow main · 3d ``` -What a session used comes from the agent's own store, so it differs by agent: Claude Code and OpenCode record a cost, Codex the tokens it generated, and Gemini CLI neither — that row simply says nothing rather than showing `$0.00`. Costs are read from the end of the store, so listing stays fast on long conversations. - -**`*` stars a session**, and starred ones are listed first — after anything interrupted, which is work waiting rather than a bookmark. A project collects hundreds of conversations and the useful one is remembered by its first line, which is no way to find it next week; the star is how you say "this one". It has a column of its own, so the mark beside it still says what the session is doing: `★·` is a starred conversation sitting there, `★●` one that is open in a pane. - -The star is **conch's**, not the agent's. It is kept by the server that owns those sessions (`stars.json`), so a second terminal, the phone and the command line see the same ones and it survives a restart — and the agents' own files are left exactly as they are. `*` again takes it off; a run that saved no conversation has nothing to star and says so. - -conch reads the agents' own session stores and never changes them (except `d`, which deletes one after asking); on remote machines the server there lists its sessions. +**How:** `*` stars a session so it is listed first, `a` filters by agent, `d` deletes one after asking, `R` reloads. `●` sessions are already open; `enter` shows their pane. ## Resuming a session -`enter` (or a click on the selected row) resumes a session in its folder with the agent's own resume option: +`enter` (or a click on the selected row) resumes a session in its folder: | Agent | Resume option | | --- | --- | @@ -38,17 +39,15 @@ conch reads the agents' own session stores and never changes them (except `d`, w | OpenCode | `opencode --session` | | Devin | `devin -r` | -Devin keeps its sessions in a database of its own, so conch lists them by asking its CLI (`devin list`) in each folder, and `d` deletes one with `devin rm`. Devin conversations can't be searched inside or shared with another agent yet; their titles and IDs still match `/`. +## Reading a conversation -Asking another program takes a moment, and a slow or signed-out one used to hold up the whole list. It no longer does: the list waits about a second and a half for it, then shows the agents whose sessions are files on disk and fills the rest in a moment later. +`Y` opens a conversation to read and copy from; on an agent in the tree it opens the one it is writing now. -`Y` opens a conversation to read and copy from — and `Y` on an agent in the tree opens the one it is writing now. It opens on the newest part. Scroll with the wheel or `↑` `↓`, a page at a time with `pgup` `pgdn`, and jump with `g` (top) and `G` (bottom, also `home` and `end`). Drag over the part you want — dragging past the top or bottom keeps scrolling — and releasing copies just that; `a` copies all of it, `esc` closes. What is shown is the conversation as text: escape sequences in it (people paste terminal output into agents) are taken out, so nothing the transcript holds can move your cursor or reach your clipboard as an escape. This is how a long answer is taken out of an agent: an agent draws on the alternate screen, which keeps no scrollback, so dragging over its pane can only ever reach what is on screen. - -`●` sessions are already open and `enter` shows their pane. `a` filters by agent, and `R` reloads the list. +**How:** scroll with the wheel, `↑` `↓`, `pgup` `pgdn`, `g` and `G`. Drag over a part to copy it, `a` copies all, `esc` closes. ## Searching -`/` searches the list as you type: titles, agents, branches and session IDs match at once, and a moment after you stop typing the server searches inside the conversations too — what you asked and what the agents answered, not tool output. A conversation match shows the text around it: +`/` matches titles, agents, branches and session IDs as you type, then searches inside the conversations too. Every word must appear. ```text / cross compiler 2 found @@ -57,26 +56,24 @@ Asking another program takes a moment, and a slow or signed-out one used to hold · Codex Release script “…needs a cross compiler for linux/arm64…” main · 5d ``` -Every word must appear. `enter` keeps the results and returns to the list keys, `esc` clears the search, `ctrl+u` empties it. - -## Sharing a session with another agent +**How:** `enter` keeps the results, `esc` clears the search, `ctrl+u` empties it. Devin conversations match by title and ID only. -`s` hands a conversation to a different agent, so it can pick up where the other left off: +## Sharing with another agent -- **Start an agent with it** — Claude Code, Codex, Gemini CLI or OpenCode starts in the session's folder. -- **Send to a running agent** — any agent already running in the project gets it as its next message. -- **On another machine** (`o`) — pick a project on another online machine, then an agent to start there or one already running in that project. A machine with no project yet — a sandbox conch has just made, before anything is cloned — is offered as **home folder** instead, so a conversation can go to it too. +`s` hands a conversation to a different agent so it picks up where the other left off: -The [brain](/docs/brain#handing-work-to-another-agent) does the same from a plain request, such as _"hand the auth thread to Codex"_, for the conversation of an agent that is running. +- **Start an agent with it** in the session's folder. +- **Send to a running agent** in the project, as its next message. +- **On another machine** (`o`) — see below. -conch writes the conversation — the messages, without tool calls or their output — to `.conch/handoff/-.md` in the session's folder and asks the agent to read it, summarise what was done and what remains, and continue. The new pane takes the **same name** as the work it continues — the name of the pane the session is running in, or the session's title — so the tree shows two rows of the same piece of work rather than one called "fix the flaky login test" and one called "codex"; the agent replaces it with its own title once it has one. `.conch/` is added to the repository's local `.git/info/exclude`, so it never shows up as a change. Very long conversations keep the first request and the latest messages. +conch writes the conversation to `.conch/handoff/-.md` and asks the agent to read it and continue. The [brain](/docs/brain) does the same from a plain request. ### On another machine -The other machine can't read this one's session files, so conch asks this machine's server for the conversation and sends the document to the other one, which writes it to `.conch/handoff/` in that project and tells the agent which machine it came from. It goes into the checkout of the session's branch when the project there has one, otherwise into the project's folder — or into the home folder, for a machine with no project, where the agent starts and reads it. - -Only the conversation moves, not the code: push the branch and check it out on the other machine first if the agent needs the changes. The agent's own session isn't copied either, so it can't be resumed there with the agent's resume option. Both servers need a build that has this; an older one says to reload it. +Pick a project on another online machine — or its **home folder**, for one with no project yet — then an agent to start or one already running there. Only the conversation moves, not the code: push the branch first if the agent needs the changes. ## Interrupted runs -conch remembers which agents are running. When its server stops — `conch server stop`, a crash, a reboot — those agents are marked `⚠ interrupted` in Sessions (and counted in the tree) for a week. `I` resumes all of them, `x` dismisses one. +When the server stops — `conch server stop`, a crash, a reboot — running agents are marked `⚠ interrupted` in Sessions for a week. + +**How:** `I` resumes all of them, `x` dismisses one. diff --git a/web/src/app/docs/tasks/page.mdx b/web/src/app/docs/tasks/page.mdx index b4902656..309005b3 100644 --- a/web/src/app/docs/tasks/page.mdx +++ b/web/src/app/docs/tasks/page.mdx @@ -2,343 +2,149 @@ export const metadata = { title: "Tasks and worktrees", description: "One branch # Tasks and worktrees -A task is an agent on its own branch, in its own git worktree, so agents working in parallel never step on each other. conch also brings along the local files a fresh worktree would miss. - -## Tasks - -`t` on a project (or `conch task "PROMPT"`) creates a branch named from the prompt, checks it out into `.worktrees/`, and starts the agent with the prompt — every task isolated from the others. +How to give each agent its own branch and worktree, finish its work, and set those worktrees up. -The branch goes under the project's own name — a task in **OneNutri** becomes `onenutri/fix-flaky-login-test` — so the branches conch makes are grouped and obvious in a repository other people push to as well. `-branch B`, or the task dialog's Branch field, names it yourself. - -Tasks use the default agent (Settings → Agents; until you choose one, Claude Code, or an agent the machine has when it has no Claude Code) unless the task dialog's Agent field, or `conch task -agent NAME`, names another. - -When that agent's plan window is already past an alert threshold (80% and 95% by default — see [notifications](/docs/configuration)), the task dialog says so before you start another one, and follows the Agent field as you change it. It is a warning, never a refusal: limits can be missing, stale, or unreported by an older server, and conch would rather let you work than block on a number it isn't sure of. - -```sh -conch task -cwd ~/src/api "Add a health check endpoint" # pane, worktree, branch -``` - -`conch task` also takes `-branch B` to name the branch and `-base B` to start from another branch than the project's base. - -**In a sandbox of its own.** `conch task -sandbox daytona "…"` (or `boat`, or any provider you have [set up](/docs/sandboxes)) makes a sandbox for the task, clones the project there from its origin remote, and starts the agent on its own branch inside it — so nothing the agent runs touches your computer. It works from what origin has: push what it needs first. The sandbox then sits in the sidebar like any other machine, with its usual idle stop, until you stop or remove it. +## Tasks -**From a GitHub issue.** **New task from a GitHub issue…** in a project's menu (`m`) lists its open issues, read through `gh` on the machine the project is on, and choosing one starts the default agent on a branch named after it — `api/issue-12-login-fails-safari` — with the issue's title and body as the prompt and a reminder that its pull request should say `Fixes #12`. From a shell, `conch task -issue 12`; words after it are added to the issue as further instructions, and `-n`, `-agent`, `-queue` and `-at` work as for any task. Only GitHub, through your own `gh` login: conch holds no token of its own. +A task is an agent on its own branch and git worktree (`.worktrees/`), so parallel agents never step on each other. -No git repository is needed. `t` on a machine row — a sandbox's included — asks for a prompt, an agent and a number of attempts, and starts the agent in that machine's home directory, outside every project; `t` on a project that isn't a repository does the same in its folder. From a shell, in a folder that isn't one, `conch task` starts the agent there with the prompt — no branch, no worktree — which is what you want for a planning agent or a scratch folder. `-branch` and `-base` are refused there, and several attempts (`-n`, or several agents) share the folder, which conch says as it starts them. With `-m MACHINE` and no `-cwd`, the agent starts in that machine's home directory, outside every project: +**How:** `t` on a project, or: ```sh -conch -m fix-login task -agent claude "Plan a CLI for tracking expenses" # in the sandbox's home +conch task -cwd ~/src/api "Add a health check endpoint" +conch task -issue 12 # from a GitHub issue, via gh +conch task -sandbox daytona "…" # in a sandbox of its own ``` -A folder you `git init` after adding it becomes a git project within a second, with no restart. If the repository has no commits yet, the first task gives its base branch an empty first commit to branch from. Anything you staged stays staged and out of that commit. This needs git to have an author (`user.name` and `user.email`), and the task says so when it doesn't. - -- `c`/`n` on a branch that isn't checked out creates its worktree first. -- `x` on a branch removes its worktree (never with uncommitted changes, never the main one). +`-agent`, `-branch` and `-base` choose the agent and branches; see the [CLI](/docs/cli#task). Outside a git repository the agent starts in the folder, with no branch. ## Finishing a task -When an agent is done, finish its branch from the changes view (select the branch, `tab` into it) or the branch's menu (`m`). Every step runs on the machine the project is on, so it works the same for remote machines. +Finish a branch from its changes view (select it, `tab`) or its menu (`m`). The header always names the next key. -You don't need to remember the keys. The changes view's header says the next one for where the branch stands: `c commit` while there is uncommitted work; once it is committed (agents often commit their own), `P push · p pull request · M merge`; once pushed, `p pull request · M merge`; with a pull request open, `o its pull request · M merge`; and once the base has every commit — or once you have merged it from here, since a squash merge leaves git counting the branch's own commits as ahead — `D removes the branch and worktree`. The status bar follows suit: with nothing uncommitted it leaves out marking and committing. Each step's message says the next one too — *committed 0123456 on feat · P pushes it, p opens a pull request*, *pushed feat · p opens a pull request*, *merged feat into main · D removes the branch and its worktree*. + | Key | What it does | | --- | --- | -| `space`, `c` | Commit. `space` marks files; `c` commits the marked ones, or every change (untracked files included) when none are marked. Other changes stay as they were. | -| `space` in a diff | Mark single hunks. `n` and `N` move between hunks, `space` marks the one under `▸`, and `c` commits just those. A file is committed either whole or by hunks, so marking a hunk drops its whole-file mark. | -| `P` | Push the branch, setting its upstream on `origin` (or the only remote) the first time. | -| `p` | Push, then open a pull request into the base with `gh`. Leave the title empty to take the title and description from the commits; tick Draft for a draft. | -| `M` | Merge the branch's commits into the base where the base is checked out, as one squashed commit (the default) or a merge commit. The base checkout must have no uncommitted changes, and the branch must have its changes committed. A merge that conflicts is undone: nothing changes, and conch names the conflicting files. | -| `D` | Discard: remove the worktree and delete the branch. conch first shows what that loses — uncommitted files, and commits that are in neither the base, the base's upstream, nor the branch's upstream (a branch squash-merged, or merged through its pull request, loses nothing). Only `y` confirms. | - -Committing hunks stages them and commits what is staged, as `git add -p` then `git commit` does, so anything you had staged already goes in too; the dialog says so. conch commits exactly the hunks it showed you: if the file changed in between, the commit is refused (`R` reloads the diff) rather than committing something else. Binary files and branches that aren't checked out have no hunks to mark. +| `space`, `c` | Mark files (or hunks in a diff), then commit them — or everything when none are marked | +| `P` | Push | +| `p` | Push and open a pull request with `gh` | +| `M` | Merge into the base, squashed by default | +| `D` | Remove the worktree and branch, after showing what is lost | -The same steps are `conch branch commit | push | pr | merge | discard` and `conch worktree ls | clean` from a shell, so a script or an agent can finish its own task; see the [CLI](/docs/cli#branch). - -None of these touch the base branch itself except a merge into it. Discarding refuses while panes are still running in the worktree, and never removes the main checkout. +From a shell: `conch branch commit | push | pr | merge | discard` ([CLI](/docs/cli#branch)). ## Cleaning up worktrees -Worktrees outlive their tasks. `W` on a project (also in its menu) lists every worktree besides the main checkout, with what removing it would lose and why it looks finished: - -- **merged into main**, or **no commits of its own** — the base already has everything on the branch (a squash merge counts) -- **pull request merged** or **closed**, **upstream deleted** -- **folder gone** — deleted by hand; git still lists it until it is pruned -- **detached** — a checkout with no branch +`W` on a project lists every worktree besides the main checkout, with what removing it would lose and why it looks finished (merged, pull request closed, folder gone). -The finished ones that lose nothing come ticked. `space` ticks others, `a` toggles the finished ones, `enter` reviews. Removing a worktree deletes its branch too, except the base branch; a folder that is already gone is pruned. Worktrees with panes running, or locked with `git worktree lock`, can't be ticked. - -Ticking one with uncommitted files, or commits that are in neither the base nor an upstream, is allowed, but the confirmation names what is lost and only `y` accepts it. Each worktree is checked again when it is removed: work added after the list was read makes conch keep it and say why. +**How:** finished ones come ticked; `space` ticks others, `a` toggles the finished ones, `enter` reviews, `y` confirms. From a shell: `conch worktree ls | clean`. ## Several attempts at one task -The same prompt can be tried more than once, each attempt on its own branch and worktree, so you can compare the results and keep one. Name several agents, ask for a number of attempts, or both: +Try one prompt several times, each attempt on its own branch, and keep the best. ```sh -conch task -agent claude,codex "Add a health check endpoint" # one attempt each +conch task -agent claude,codex "Add a health check endpoint" # one each conch task -n 3 "Fix the flaky login test" # three, same agent -conch task -agent claude,codex -n 3 "Fix the flaky login test" # three, agents cycling -``` - -In the TUI, the task dialog's **Agent** field takes a list (`claude,codex`) and **Attempts** a number; it shows the branches it will create before anything starts. - -Attempts are branches under the task's own name, so they sort together in the tree: - -```text -conch/fix-flaky-login-test/claude -conch/fix-flaky-login-test/codex -conch/fix-flaky-login-test/claude-2 ``` -A single attempt keeps the plain branch name, exactly as before. Branch names already in the project are never reused, and at most 10 attempts start at once. An attempt that can't start — a branch taken, an agent missing — leaves the others running and is reported on its own. - - - -Attempts multiply what you spend: three Claude attempts use three times the plan window. The task dialog warns when an agent's window is already nearly used. +In the task dialog, fill **Agent** with a list and **Attempts** with a number. - +Three attempts use three times the plan window. ### Comparing them -`A` on an attempt's changes, or **Compare the N attempts…** in its branch menu, puts them side by side: - -```text -╭─ Compare attempts ────────────────────────────────────────────────────╮ -│ Attempts at conch/fix-flaky-test │ -│ ▸ claude 2 files · +16 −3 · 1 commit · passed $0.90 working │ -│ claude-2 nothing yet │ -│ codex 1 file · +4 · 1 commit · failed (exit 2) done │ -│ │ -│ enter its changes · t rerun go test ./... · o its terminal · │ -│ M merge · D discard · x keep it, discard the rest · R reload · esc │ -╰───────────────────────────────────────────────────────────────────────╯ -``` - -Each row is what that attempt changed, what its agent is doing and what it has spent. `enter` opens its diff, and the rest are the ordinary [harvest](#finishing-a-task) steps: `M` merges it into the base, `D` throws it away, `x` keeps the selected one and discards the others — each still naming what it would lose and asking first. An attempt whose agent is still running is never discarded by `x`; close it or let it finish. +`A` on an attempt's changes shows the attempts side by side. -### Running a command in each - -`t` asks for a command — `go test ./...`, `npm test`, `make check` — and runs it in every attempt's worktree, each in its own terminal named `test · claude`. The row then shows `running…`, `passed` or `failed (exit 2)`, straight from that terminal's exit code, so a comparison rests on what the tests say rather than on the size of the diff. - -The terminals stay open: `o` shows the selected attempt's one so you can read the output, and they close like any other terminal (`x` in the tree). `t` again reruns the same command, in fresh terminals. +**How:** `enter` opens a diff, `M` merges, `D` discards, `x` keeps the selected one and discards the rest, `t` runs a command such as `go test ./...` in every attempt and shows `passed` or `failed`. ## Later, and on a schedule -The server keeps a list of things to do later, so they happen with conch closed — which is usually the point: +The server runs scheduled tasks with conch closed. ```sh -conch task -at 02:00 "Upgrade the test framework and fix what breaks" # tonight +conch task -at 02:00 "Upgrade the test framework and fix what breaks" conch task -every daily -at 07:00 "Bump the dependencies and run the tests" -conch agent prompt -at +30m reviewer "Check the CI result and report" -conch schedule # what is scheduled, when, and how its last run went -conch schedule rm s1a2b3 # take one away +conch task -queue "Add rate limiting to the login endpoint" # starts when fewer than 3 agents run +conch task -after api/model "Add a REST endpoint for invoices" # starts from that branch once it is done +conch schedule # list; conch schedule rm ID removes one ``` -`-at` takes `14:05` (today, or tomorrow once it has passed), `+30m` / `+2h` / `+1d`, or `2026-10-15 09:00`. `-every` takes `hourly`, `daily`, `weekly` or a span such as `6h` or `2d`, five minutes at the least; with no `-at`, the first run is now. A span of whole days (`daily`, `weekly`, `2d`) keeps its time on the clock — a task set for 21:24 runs at 21:24 on the night the clocks change, too — while shorter ones (`hourly`, `6h`) count hours as they pass. A repeating task starts on a branch of its own each time — the prompt's branch name with the date and time after it — so one morning's work never lands on the last's. Missed runs, a laptop asleep overnight, are skipped rather than run in a burst. - -**A queue.** Starting ten agents at once makes ten diffs to read at once, and reading is the slow part. `-queue` adds a task to the project's queue instead: it starts as soon as fewer than three agents are running in the project (`-wip N` for another number), in the order queued. Closing an agent you have finished with is what makes room. Reviewers are not counted — they read work rather than make more of it. - -```sh -conch task -queue "Add rate limiting to the login endpoint" -conch task -queue -wip 2 "Move the settings page to the new form library" -``` - -**After other work.** Some changes need another first: the endpoint needs the model it serves. `-after` holds a task until that work has finished, then starts it from that work's branch, so the second agent builds on what the first committed: - -```sh -conch task -branch api/model "Add the Invoice model and its migration" -conch task -after api/model "Add a REST endpoint for invoices" -conch task -after p4 "Write the client for the new endpoint" # the branch the agent in pane p4 is on -``` - -`-after` takes a branch of the project, a pane working on one, or a task still on the schedule — by the ID `conch task -queue` printed, or the `-branch` it was given — so a whole stack can be queued at once, each waiting for the one before. "Finished" is the agent on that branch having worked and stopped: not still at work, not waiting on a question. With `-queue` too it also waits for room; with `-base` it waits but starts from that base instead. - -When it can't be sure, it waits and says why in `conch schedule` and the queue, rather than starting on the wrong code: - -- the branch has **uncommitted changes**, which a branch made from it would not have — commit them and it starts; -- the branch is **gone without being merged** — discarded, so there is nothing to build on. A branch that was merged into the base and then deleted is fine: the task starts from the base, which now has that work; -- the task it waits for was **taken off the schedule or failed to start**. - -In the TUI, the task dialog's **When** field does the same: leave it empty to start now, type `queue` to queue it, `after api/model` to wait for other work, or a time — `02:00`, `+2h` — to schedule it. +In the task dialog, the **When** field takes `queue`, `after api/model` or a time. For an agent stopped at its plan limit, `C` in the [review queue](/docs/interface) resumes it after the reset. -A scheduled message waits for its agent: it is never typed into one that is working, or waiting on a question of its own — the schedule says so beside it — and is sent once the agent is free. A message for a pane that has since closed, or now runs another agent, is dropped rather than typed into something that never asked for it. - -**After a plan limit.** An agent that stopped because its plan ran out is in the [review queue](/docs/interface#review-queue) as `stopped at its plan limit, which resets at 14:00`. `C` there has the server tell it to carry on a minute after the limit resets — whether or not conch is open then. Everything scheduled shows at the bottom of the queue too (`⏲`), and `x` on one takes it off the schedule. + ## Local files in worktrees -A fresh worktree has only what git tracks, so an agent there would miss your `.env` or personal agent settings. When conch creates a worktree it copies the main checkout's **gitignored** files that match the project's patterns — by default: - -- `.env`, `.env.*`, `.envrc` -- `.claude/settings.local.json`, `CLAUDE.local.md` -- `.mcp.json` -- `AGENTS.override.md` -- `.gemini/.env` - -Untracked files git doesn't ignore are never copied, so an agent can't commit them on the task's branch by accident; the setup view lists them instead. +A new worktree gets copies of the main checkout's gitignored local files — `.env`, `.env.*`, `.envrc`, `.claude/settings.local.json`, `CLAUDE.local.md`, `.mcp.json`, `AGENTS.override.md`, `.gemini/.env` — so the agent has your settings. -`F` on a project changes the patterns, which are git globs. Existing files in a worktree are never overwritten. +**How:** `F` on a project changes the patterns, or: ```sh -conch project files ID PATTERN... # set the patterns -conch project files ID -reset # restore the defaults -conch project files ID -none # copy no local files +conch project files ID PATTERN... # set +conch project files ID -reset # defaults +conch project files ID -none # none ``` ## Setup and ports in worktrees -Copied files make a worktree *configured*; they don't make it *run*. It still has no `node_modules`, no virtualenv, no database. Give the project a **setup command** and conch runs it in every new worktree — tasks, attempts, `c` on a branch, a worktree moved from another machine — in a terminal of its own named `setup`, beside the agent rather than before it: +A **setup command** runs in every new worktree, in a terminal named `setup` beside the agent. + +**How:** `F` on a project, or: ```sh -conch project setup ID 'npm ci && cp .env.example .env' # set it -conch project setup ID # show it -conch project setup -none ID # run nothing +conch project setup ID 'npm ci && cp .env.example .env' +conch project setup -none ID ``` -`F` on a project sets it too. The command runs in your login shell, so the `PATH` your version managers set up (nvm, pyenv, asdf) is the one it sees. A setup that works closes its terminal by itself; one that fails stays open at a shell in the worktree, with `setup failed (exit N)` under its output, which is where you fix it from. The command is kept with the project on that machine, never read from the repository: a branch somebody else pushed can't bring a command that runs on checkout. - -The command can read where it is: `CONCH_WORKTREE`, `CONCH_BRANCH`, `CONCH_ROOT` (the main checkout, to copy a database from) and `CONCH_PROJECT`. +It can read `CONCH_WORKTREE`, `CONCH_BRANCH`, `CONCH_ROOT` and `CONCH_PROJECT`. ### Ports -Every checkout is given **ten ports of its own**, from `$CONCH_PORT` (and `$CONCH_PORT_COUNT`, which is 10), set in every terminal and agent started there and in its setup. Two agents each running `npm run dev` in their own worktree then don't fight over port 3000 — start servers on the port conch gave: +Each checkout gets ten ports of its own, starting at `$CONCH_PORT`, so two dev servers don't fight over one port. `L` on a branch opens `http://localhost:$CONCH_PORT`. ```sh npm run dev -- --port $CONCH_PORT -PORT=$CONCH_PORT rails s -uvicorn app:app --port $CONCH_PORT ``` -A checkout keeps its ports for as long as it is on disk, through restarts and reloads, so a link to it still works tomorrow; ports already in use on the machine are skipped. `L` on a branch, or on a pane in a checkout, opens `http://localhost:$CONCH_PORT` in your browser — on another machine through a port forward on conch's own ssh connection, in a sandbox through the provider's link. When nothing answers there yet, conch says how to start a server on it and keeps the link on your clipboard. - ## Agent setup -`i` on a project, branch or pane shows what each agent loads there, read from the agents' own configuration (conch only reads it), a tab per agent — `tab` moves between them. In a narrow window the tab strip moves along to keep the open tab in view, with `‹` where it has left tabs off: - -- **Instructions** — `CLAUDE.md`, `AGENTS.md`, `GEMINI.md` and friends, from your home and every folder the agent reads them from, plus the files `CLAUDE.md` and `GEMINI.md` pull in with `@path` imports (marked *imported by*) -- **Skills** — `~/.claude/skills`, `.agents/skills` (Codex, Gemini, OpenCode, Devin), `.gemini/skills`, `.opencode/skills`, `.devin/skills`, plugin skills. Devin's tab also lists what it reads of Claude Code's — `CLAUDE.md`, `.claude/skills`, `.mcp.json` — marked *Claude Code compatibility* -- **Commands and subagents**, **MCP servers** (names and transport only — never commands, URLs or secrets), **plugins and extensions** -- **Added by conch** — the hooks or plugin conch injects for state tracking -- Warnings, e.g. a folder Claude or Codex hasn't trusted yet -- **conch** — whether conch's own skill, the one that teaches an agent to start, prompt and read other agents, is installed for this agent **on this machine**: `S` installs it or takes it away, after a question naming the file. A skill of that name conch didn't write is yours and is left alone. Settings → Agents → **conch's own skill…** does the same for every agent at once; see [Agents working together](/docs/agents-together) - -In a worktree it also compares with the main checkout: local files that are missing (`c` copies them) and setup that only the main checkout has, such as Claude MCP servers registered for that folder or an uncommitted `.mcp.json`. +`i` on a project, branch or pane shows what each agent loads there, a tab per agent: instructions, skills, commands, MCP servers, plugins, hooks conch added, and warnings. In a worktree it lists local files that are missing; `c` copies them. `S` installs conch's own skill. -```sh -conch agent setup [-agent NAME] [-copy] [-json] [DIR] -``` - -prints the same. +**How:** `i`, or `conch agent setup [-agent NAME] [-copy] [-json] [DIR]`. ## One setup, every agent -Running several agents should not mean setting each one up three times. In the setup view, `s` takes the setup of the agent whose tab is open and gives it to the others, in this checkout: its instructions, its skills and the MCP servers it declares, each written where that agent looks for it. - -It says what it would write before it writes anything: - -``` - Sync agent setup - - Give Codex, Gemini CLI and OpenCode Claude Code's setup in this checkout? - - create AGENTS.md (a copy of CLAUDE.md) - create GEMINI.md (pointing at CLAUDE.md) - link review → .agents/skills/review (pointing at ../../.claude/skills/review) - create gh → .codex/config.toml (stdio · npx · 1 variable) - - Left out — 1 item: its environment holds a value, not a ${VAR} reference: - conch does not copy secrets -``` - -What it does, and what it refuses to do: - -| | | -| --- | --- | -| **Instructions** | an agent that expands `@path` (Claude Code, Gemini CLI) is pointed at the other file, so the two never drift; one that doesn't (Codex, OpenCode read `AGENTS.md`) gets the text in a block conch can find again, between `` and `` | -| **Skills** | linked, not copied: one folder holds the skill and `.agents/skills` is read by Codex, Gemini and OpenCode alike, so one link serves three | -| **MCP servers** | written in each agent's own format — `.mcp.json`, `.codex/config.toml`, `.gemini/settings.json`, `opencode.json`, `.devin/mcp_config.json` — keeping everything else in those files. A server already declared there is left as it is | -| **Variables** | each agent names one its own way, and conch writes that way: `${TOKEN}` for Claude Code and Gemini, `{env:TOKEN}` for OpenCode, `${env:TOKEN}` for Devin. Codex expands nothing in its config, so it is told the names to pass on — `env_vars = ["TOKEN"]`, `bearer_token_env_var` for an `Authorization: Bearer ${TOKEN}` header, `env_http_headers` for the rest. A server Codex cannot express — a variable passed under another name, a reference in its arguments, an SSE server — is left out for Codex with the reason | -| **Devin** | reads Claude Code's `CLAUDE.md`, `.claude/skills` and `.mcp.json`, and OpenCode's servers, by itself, so it is given only what it would not otherwise see — a second copy would be read twice. Turn that off with `read_config_from` in Devin's `config.json` and it gets its own `AGENTS.md`, skills link and `.devin/mcp_config.json` | -| **Nothing else** | logins are each agent's own and are never touched. A server whose environment or headers hold a value rather than a `${VAR}` reference is not copied: conch does not carry secrets between files | -| **Hand-written files** | left alone. conch writes its own block, or a file that wasn't there; a file somebody wrote is reported as skipped, and a second sync updates the block rather than the rest | -| **Undo** | `u` puts the last sync back, file by file, from a record conch keeps in its own folder (`~/.config/conch/agent-sync/checkouts/`), never in the checkout — a record in a checkout could have come with a clone. A file conch created is removed; one it changed goes back to what it held. Undoing touches only the files a sync writes, and only inside the checkout. A record an older conch left in `.conch/agent-sync/` is listed but not acted on: undoing it names the files, for `git` to put back | - -A file conch cannot rewrite without losing something is left alone and says so — a `.json` with comments in it, for instance, since rewriting it would drop them. - -The plan also says where the instructions came from, and which agents want the folder trusted before they will read what was written: **Codex** reads a project's `config.toml` only once you have trusted it, and **Gemini** leaves a project's MCP servers *and* skills out until then — the servers with a warning, the skills silently, which is how an afternoon goes missing. Trust the folder in the agent itself (conch never answers that prompt for you) and both appear. - -Undoing names each thing it puts back, and takes away the folders the sync made — `.codex`, `.agents/skills` — so the checkout looks as it did. A folder with anything else in it stays. +`s` in the setup view gives the open agent's instructions, skills and MCP servers to the other agents in this checkout, each where that agent looks. It shows the plan first, never copies secrets, and leaves hand-written files alone. `u` undoes it. ```sh -conch agent sync # what it would do, from Claude Code -conch agent sync -from codex -to claude,gemini # from another agent, to some of them -conch agent sync -apply # write it -conch agent sync -undo # put the last one back -conch agent sync -undo -stamp 20260926-101500 # or a particular one +conch agent sync # show the plan +conch agent sync -from codex -to claude,gemini +conch agent sync -apply +conch agent sync -undo +conch agent sync -user -apply # your home, not a checkout ``` -`-from` is `claude` unless you say otherwise, `-to` is every other agent, and without `-apply` nothing is written. It works on a remote machine's checkout with `-m` as well, since the server does the writing; a server too old to know how says so. - -### Your own setup, not just a checkout's - -The half that follows you from project to project — `~/.claude/CLAUDE.md` and `~/.claude/skills`, `~/.codex/config.toml`, `~/.gemini/settings.json`, `~/.config/opencode` — is machine-wide, so it lives in Settings → **Agents** → **Your own setup…** rather than on a row that names a folder: a page with one row per agent to take the setup from, and **Put the last one back…**. From a shell it is `-user`: - -```sh -conch agent sync -user # what it would write in your home -conch agent sync -user -apply -conch agent sync -user -undo -``` - -The rules are the checkout's, with two differences that matter: - -- **There is no `git status` here.** Nothing shows what changed in your home afterwards, so the plan carries every path in full (`~/.codex/AGENTS.md`, `~/.agents/skills/tide-check`) and the record — under `~/.config/conch/agent-sync/`, not a `.conch` in your home — is what puts it back. -- **A file that is a link is left alone.** These files are often symlinks into a dotfiles repository, and writing through the link would edit that repository. conch skips one and says so rather than touching it. - -Claude is never *given* MCP servers here: its own live in `~/.claude.json`, the file it keeps its state and every project's history in, and conch does not rewrite that for a setting — it reads from it happily enough, so Claude's servers still reach the other agents. (The library below gives Claude servers through its own `claude mcp add-json` instead.) Devin's go in `~/.config/devin/mcp_config.json` and its skills in `~/.config/devin/skills`, since it does not read `~/.agents/skills`. +The home version is also in Settings → **Agents** → **Your own setup…**. ## Shared MCP servers and skills -A sync copies one agent's setup to the others, once. The library is what they *follow*: MCP servers and skills kept in conch, each ticked for the agents that should have it. Untick an agent and applying takes the server back out of it; change a server and every agent that has it is told. It lives in Settings → **Agents** → **Shared MCP servers & skills…** (in the [Mac app](/docs/mac-app), **Settings → Skills & MCP servers**), is kept per machine in `~/.config/conch/library/`, and covers your home — the setup that follows you from project to project. - -``` - Shared MCP servers & skills given to the agents you choose - ‹ Agents esc - - MCP servers Cl Cx Gm Oc Dv - ○ docs http ✓ + · · ✓ - ○ github stdio · npx ✓ ✓ ! · ✓ - Gm declared there by hand, differently: conch leaves it alone - ○ Add a server… - - Skills Cl Cx Gm Oc Dv - ○ review ~/skills/review ✓ ✓ ✓ ✓ · -``` - -- **Take an agent's into the library…** starts it from what you have: an agent's servers and skills in your home go in, ticked for it and for any agent that already has the same. Nothing is written to any agent. -- **Add a server…** takes a command (`npx -y @modelcontextprotocol/server-github`) or a URL, its environment and headers as `NAME=value; …`, and a box per agent. A value must refer to a variable — `GITHUB_TOKEN=${GITHUB_TOKEN}`, `Authorization=Bearer ${TOKEN}` — and a literal token is never written into an agent's file: the secret stays out of them, and each agent is given its own way of naming it. -- **A token** for a server: paste it in the form's **Token** field (or into its `Authorization` header, from where it is moved). On **Save** Conch.app asks whether to keep it securely. **Yes** keeps it in the macOS Keychain as `CONCH_MCP__TOKEN` (service `conch-mcp`), a URL's header becomes `Authorization=Bearer ${CONCH_MCP__TOKEN}`, and the conch server gives that variable to every agent it starts from then on — read from the Keychain, never written to disk. A variable you export yourself wins over it. A command's server says where it reads the token, e.g. `API_KEY=${CONCH_MCP_JIRA_TOKEN}`. Taking the server out of the library takes its token out of the Keychain. After a Keychain save it says where to find the token in Keychain Access (login → search “conch”). **No** writes the token in plain text into each agent's config file, where anything that can read those files can read it; the server is marked `plain`, and editing it shows the token in the Token field rather than in the header. On another machine the Keychain is out of reach, so a token is written in plain text there, or you set the variable in the environment its conch server starts with — a variable exported in your shell's rc file does not reach a server started by the app. -- **Add a skill…** takes a folder holding a `SKILL.md`, wherever you keep it — or, under **From GitHub**, a skill shared there: `owner/repo`, `owner/repo/path/to/skill`, `@ref` at the end, or the link to its folder. The machine's own server downloads it (a shallow `git clone`; nothing in it is run) into conch's library there, `~/.config/conch/library/skills/NAME`, and keeps where it came from so **Fetch again** brings it up to date. A repository holding several skills, none named, lists them for you to pick one. Each agent gets a link to it: one in `~/.claude/skills`, one in `~/.agents/skills` for Codex, Gemini and OpenCode together, one in `~/.config/devin/skills`. Since that middle link is shared, it stays while any of the three still wants it, and the row says so. -- **Apply…** shows every write first, then makes it. **Put the last one back…** undoes the last apply, file by file. +The library keeps MCP servers and skills in conch, each ticked for the agents that should have them. Applying writes them into each agent's own configuration; unticking takes them out. -What keeps it safe is the sync's, plus one thing of its own: conch remembers what it wrote (`library/written.json`), and only that is ever changed or taken out. A server somebody declared by hand under the same name is marked `!` or `○` and left alone; a config that is a link into a dotfiles repository is skipped. Claude's servers are added with `claude mcp add-json --scope user` and taken out with `claude mcp remove`, since conch does not write `~/.claude.json`. Devin is not given a server Claude Code or OpenCode already has, because it reads theirs. + -From a shell: +**How:** Settings → **Agents** → **Shared MCP servers & skills…** (in the [Mac app](/docs/mac-app), **Settings → Skills & MCP servers**), or: ```sh -conch agent library # the library, a column per agent -conch agent library import claude # take Claude Code's in +conch agent library # a column per agent +conch agent library import claude conch agent library add -to codex,devin -env GITHUB_TOKEN='${GITHUB_TOKEN}' github -- npx -y @modelcontextprotocol/server-github -conch agent library add -header 'Authorization=Bearer ${DOCS_TOKEN}' docs https://docs.example/mcp -conch agent library add -plain -header 'Authorization=Bearer tok-123' docs https://docs.example/mcp # the token as it is, in plain text -conch agent library mcp # conch's own tools (conch mcp), one action -conch agent library skill review ~/skills/review -conch agent library skill anthropics/skills/skills/pdf # from GitHub, named by its folder -conch agent library skill -to claude docs owner/repo@v2 # named, at a tag -conch agent library off github codex # untick one -conch agent library plan # what apply would write +conch agent library skill anthropics/skills/skills/pdf # from GitHub conch agent library apply conch agent library undo ``` -Quote the `${…}` in a shell, or the shell expands it before conch sees it. +Values must refer to variables (`${TOKEN}`); in Conch.app a token can be kept in the macOS Keychain. diff --git a/web/src/app/docs/why/page.mdx b/web/src/app/docs/why/page.mdx index 7bc0fdc3..8dd958c7 100644 --- a/web/src/app/docs/why/page.mdx +++ b/web/src/app/docs/why/page.mdx @@ -2,40 +2,45 @@ export const metadata = { title: "Why conch", description: "What conch does that # Why conch -Plenty of tools run coding agents side by side. conch goes further where the work actually stalls: waiting on CI, losing agents to an update, guessing what an agent is doing, and being away from the laptop. +conch goes further where agent work stalls: waiting on CI, losing agents to an update, guessing what an agent is doing, and being away from the laptop. Failed CI goes back to the agent; green merges. No window open. + A new build, and every terminal still open. + The agent says what it is doing, not a guess from its spinner. + A reviewer, a tester, a team, each kept to its own work. + Conch.app: Ghostty panes, a workbench, a branch's changes. + Answer an agent from anywhere, with no account. ## It finishes the job without you -Most tools stop when the agent stops. In conch, a failed check or a failed CI run goes back to the branch's agent with the log, the agent fixes it, and the pull request merges once it is green. The machine's conch server does this, not a window you have to keep open, so it carries on with your laptop shut. Drafts, requested changes, conflicts and open review threads hold a merge back, and nothing is merged unless you turned it on. See [Sending a failure back](/docs/interface#sending-a-failure-back). +A failed check or CI run goes back to the branch's agent with the log, and the pull request merges once it is green — run by the server, with your laptop shut. See [Sending a failure back](/docs/interface). ## Updating never stops your agents -conch reloads its server onto a new build and keeps every terminal open, so an agent halfway through a task does not notice. That is the default, not an experiment, and the TUI picks up the new build by itself. See [Updating without stopping agents](/docs/installation#updating-without-stopping-agents). +conch reloads its server onto a new build and keeps every terminal open. See [Updating without stopping agents](/docs/installation#updating-without-stopping-agents). ## It hears from the agent, not just its screen -conch is the terminal, so an agent can tell it what it is doing — working, waiting for permission, done — through the Program Status Protocol (OSC 7501), and conch answers when the agent asks whether anyone is listening. Hooks and the screen come after that, not instead of it. conch then passes one overall state up to the terminal you run it in, so a Ghostty or kitty tab says when an agent waits. See [Agent states](/docs/agents#agent-states). +An agent tells conch what it is doing — working, waiting for permission, done — through OSC 7501, and conch passes that up to your terminal's tab. See [Agent states](/docs/agents). ## Agents can run agents, and stay in their lane -An agent can start a reviewer, prompt it, wait for it and read what it said, through the CLI or `conch mcp`, and six bundled skills turn that into a review loop, a team or a factory. An agent calling from its own pane reaches only the panes it started and its own project, so a helper cannot wander into the rest of your work. See [What an agent may do](/docs/agents-together#what-an-agent-may-do). +An agent can start a reviewer, prompt it and read its answer, but reaches only the panes it started and its own project. See [Agents together](/docs/agents-together). ## A native desktop on the same servers -[Conch.app](/docs/mac-app) is a window on the very servers the TUI talks to, not a separate product with its own idea of your agents: close it and nothing stops. Its panes are drawn by Ghostty. Every waiting agent is a card under **Needs you**, answered with a click. A branch opens with its changes, review notes and checks; the **workbench** puts an agent's files, terminal, chat and own terminal in one tab; and your dev server's page sits in a browser tab beside them. +[Conch.app](/docs/mac-app) is a window on the same servers the TUI talks to, with panes drawn by Ghostty; close it and nothing stops. ## Ask in plain words, approve before anything runs -Tell the [brain](/docs/brain) what you want — "start Claude on a fix for the login bug" — and it proposes the actions. Nothing runs until you press Enter, with whichever model you choose. See [Brain](/docs/brain). +Tell the [brain](/docs/brain) what you want; nothing runs until you press Enter. From f477f6141ae63ba6dae45882ce21e3fb15c4886c Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:11:11 -0800 Subject: [PATCH 06/35] Docs: take Conch Cloud out of the navigation and say it is not enabled The Conch Cloud and Cloud machine image pages stay but are no longer linked from the sidebar, and open with how to turn Cloud on. The CLI page's login, logout, account and cloud sections move to a Conch Cloud section at its end under the same note; the interface and Mac app pages say it is off and what a cloud machine somebody has keeps. Co-Authored-By: Claude Opus 5.5 --- web/src/app/docs/cli/page.mdx | 82 +++++++++++++------------ web/src/app/docs/cloud-machine/page.mdx | 2 + web/src/app/docs/cloud/page.mdx | 2 + web/src/lib/docs.ts | 2 - 4 files changed, 47 insertions(+), 41 deletions(-) diff --git a/web/src/app/docs/cli/page.mdx b/web/src/app/docs/cli/page.mdx index 3b8be465..b0d605f1 100644 --- a/web/src/app/docs/cli/page.mdx +++ b/web/src/app/docs/cli/page.mdx @@ -318,45 +318,6 @@ conch relay [-listen ADDR] [-cert FILE -key FILE] # a relay phones and `conch relay` runs a [relay](/docs/phone#through-a-relay) on a server of your own (`:8443` by default): `conch web` connects out to it, a phone opens its address, and it copies the encrypted session between them without being able to read it. It stores nothing and serves the phone's app — which is why it should be a server of your own: a relay that served a changed app could read what the phone sees. Without `-cert`, put a proxy that does HTTPS in front of it — a phone's browser encrypts only on an https page. -### login - -```sh -conch login [-no-browser] [-json] [-api URL] # sign this device in to Conch Cloud -``` - -`conch login` signs this device in to [Conch Cloud](/docs/cloud): it prints a code, opens the page where you approve it (signed in there in your browser), and waits until you do. The server is `CONCH_CLOUD_URL`, else `[cloud] api` in `config.toml`, else Conch Cloud itself; `-api` names one for this sign-in. The device's tokens go in the macOS Keychain, or elsewhere in `cloud.json` in conch's folder, readable by you alone — conch refuses that file if anyone else can read it. `-json` says each step as a line of JSON (the code, then `signed_in` or `error`), which is how Conch.app's Settings signs in. A conch that has never signed in asks nothing of Conch Cloud, ever. - -### logout - -```sh -conch logout # revoke this device's sign-in and forget it -``` - -### account - -```sh -conch account [-json] # who, the plan, this month's hours and storage, the devices -``` - -### cloud - -```sh -conch cloud machine ls [-json] # the account's cloud machines and their state -conch cloud machine new NAME [-size S] [-region R] [-provider ID] [-wait] -conch cloud machine wake|sleep NAME [-force] # sleep refuses while agents work, unless -force -conch cloud machine rm NAME [-y] # destroy it and its disk -conch cloud machine forget-key NAME # the next connection pins whatever key it is given -conch cloud exec [-t] NAME [-- SCRIPT…] # run a script there (a shell with none), waking it -conch cloud bridge NAME # conch's protocol on stdin/stdout, for conch machine bridge -conch cloud agent [-boot FILE] [-state DIR] [-user NAME] # inside a Conch Cloud machine only -conch cloud install [-user NAME] # ready a machine image (as root) -conch cloud git-credential [-socket PATH] get # git's credential helper there -``` - -Once signed in, the account's machines are in conch's machines (`conch machine ls`, the TUI's tree, Conch.app's sidebar) as `conch:`, named as on the account, and `-m NAME` reaches one. They are reached through Conch Cloud's relay rather than ssh: `exec` and `bridge` ask the control plane for a ticket and the machine's key, check the key against the one kept from the first connection (`cloud-keys.json`; a different key on a machine that was not recreated is refused), and open an end-to-end encrypted tunnel to the machine's conch. A background connection never wakes a machine that sleeps — it is shown asleep — but `exec` and `bridge`, asked for by you, wake it and wait. - -`conch cloud agent` is the machine's side of Conch Cloud, and runs **inside** a cloud machine: its host starts it (the `conch-cloud-agent` systemd unit — see [Cloud machine image](/docs/cloud-machine)) after writing `/run/conch-cloud/boot.json`. It refuses a `boot.json` anyone but its owner can read, keeps the machine's Noise key in `/var/lib/conch/cloud/noise.key` (0600, made once), starts the machine's conch server as `-user` (`conch` when it runs as root), says hello to the control plane, reports what the agents are doing so an idle machine sleeps, and joins the relay as the room's gateway so clients reach the server through an end-to-end encrypted tunnel. Agents it starts are given the account's env secrets (a shell is not, and only the server it registered with may ask for them); the machine token and those secrets are never written to disk, though a running agent's environment, and the token git is handed, are readable by processes of the same user — see [Cloud machine image](/docs/cloud-machine). It exits 3 when the control plane refuses its token — each inject gives the machine a new one and restarts the agent — and 4 when the control plane refuses the machine itself. `install` readies a machine image: it writes the `conch-cloud-agent` unit (running this conch), enables it and makes `/var/lib/conch/cloud`; the user (`conch` by default) must exist. `git-credential` is what git asks for the git proxy's password: the machine token, from the agent's memory. - ### config ```sh @@ -587,3 +548,46 @@ These are run by conch itself, not by you: | --- | --- | | `conch bridge` | a remote client over ssh: connects stdio to this machine's server, starting it if needed | | `conch report` | agent hooks and plugins, to report state to the server | + +## Conch Cloud commands + +Conch Cloud is not enabled in this release: these commands are left out of `conch help all` and completion, and run they say so. To try it, set `CONCH_CLOUD=1` in the environment or put `enabled = true` under `[cloud]` in `config.toml` (the variable, when set, wins: `CONCH_CLOUD=0` turns it off again). A cloud machine already among your machines keeps working either way — it is reached, woken and put to sleep (`conch cloud machine wake|sleep|rm`) as before. + +### login + +```sh +conch login [-no-browser] [-json] [-api URL] # sign this device in to Conch Cloud +``` + +`conch login` signs this device in to [Conch Cloud](/docs/cloud): it prints a code, opens the page where you approve it (signed in there in your browser), and waits until you do. The server is `CONCH_CLOUD_URL`, else `[cloud] api` in `config.toml`, else Conch Cloud itself; `-api` names one for this sign-in. The device's tokens go in the macOS Keychain, or elsewhere in `cloud.json` in conch's folder, readable by you alone — conch refuses that file if anyone else can read it. `-json` says each step as a line of JSON (the code, then `signed_in` or `error`), which is how Conch.app's Settings signs in. A conch that has never signed in asks nothing of Conch Cloud, ever. + +### logout + +```sh +conch logout # revoke this device's sign-in and forget it +``` + +### account + +```sh +conch account [-json] # who, the plan, this month's hours and storage, the devices +``` + +### cloud + +```sh +conch cloud machine ls [-json] # the account's cloud machines and their state +conch cloud machine new NAME [-size S] [-region R] [-provider ID] [-wait] +conch cloud machine wake|sleep NAME [-force] # sleep refuses while agents work, unless -force +conch cloud machine rm NAME [-y] # destroy it and its disk +conch cloud machine forget-key NAME # the next connection pins whatever key it is given +conch cloud exec [-t] NAME [-- SCRIPT…] # run a script there (a shell with none), waking it +conch cloud bridge NAME # conch's protocol on stdin/stdout, for conch machine bridge +conch cloud agent [-boot FILE] [-state DIR] [-user NAME] # inside a Conch Cloud machine only +conch cloud install [-user NAME] # ready a machine image (as root) +conch cloud git-credential [-socket PATH] get # git's credential helper there +``` + +Once signed in, the account's machines are in conch's machines (`conch machine ls`, the TUI's tree, Conch.app's sidebar) as `conch:`, named as on the account, and `-m NAME` reaches one. They are reached through Conch Cloud's relay rather than ssh: `exec` and `bridge` ask the control plane for a ticket and the machine's key, check the key against the one kept from the first connection (`cloud-keys.json`; a different key on a machine that was not recreated is refused), and open an end-to-end encrypted tunnel to the machine's conch. A background connection never wakes a machine that sleeps — it is shown asleep — but `exec` and `bridge`, asked for by you, wake it and wait. + +`conch cloud agent` is the machine's side of Conch Cloud, and runs **inside** a cloud machine: its host starts it (the `conch-cloud-agent` systemd unit — see [Cloud machine image](/docs/cloud-machine)) after writing `/run/conch-cloud/boot.json`. It refuses a `boot.json` anyone but its owner can read, keeps the machine's Noise key in `/var/lib/conch/cloud/noise.key` (0600, made once), starts the machine's conch server as `-user` (`conch` when it runs as root), says hello to the control plane, reports what the agents are doing so an idle machine sleeps, and joins the relay as the room's gateway so clients reach the server through an end-to-end encrypted tunnel. Agents it starts are given the account's env secrets (a shell is not, and only the server it registered with may ask for them); the machine token and those secrets are never written to disk, though a running agent's environment, and the token git is handed, are readable by processes of the same user — see [Cloud machine image](/docs/cloud-machine). It exits 3 when the control plane refuses its token — each inject gives the machine a new one and restarts the agent — and 4 when the control plane refuses the machine itself. `install` readies a machine image: it writes the `conch-cloud-agent` unit (running this conch), enables it and makes `/var/lib/conch/cloud`; the user (`conch` by default) must exist. `git-credential` is what git asks for the git proxy's password: the machine token, from the agent's memory. diff --git a/web/src/app/docs/cloud-machine/page.mdx b/web/src/app/docs/cloud-machine/page.mdx index d21ca954..c1f2031d 100644 --- a/web/src/app/docs/cloud-machine/page.mdx +++ b/web/src/app/docs/cloud-machine/page.mdx @@ -2,6 +2,8 @@ export const metadata = { title: "Cloud machine image", description: "Build a ma # Cloud machine image +> Conch Cloud is not enabled in this release: set `CONCH_CLOUD=1`, or `enabled = true` under `[cloud]` in `config.toml`, to try it ([more](/docs/cli#conch-cloud-commands)). + A Conch Cloud machine is a VM with conch in it. Its host — Tensorlake, Hetzner or any provider the control plane drives — boots it from an image, writes a small file into it, and from then on the machine looks after itself: **`conch cloud agent`** starts the machine's conch server, tells the control plane it is up, reports what its agents are doing so an idle machine can sleep, and joins the relay so your laptop and phone reach the server through an end-to-end encrypted tunnel. This page is for whoever builds that image. diff --git a/web/src/app/docs/cloud/page.mdx b/web/src/app/docs/cloud/page.mdx index b174e888..193fcee4 100644 --- a/web/src/app/docs/cloud/page.mdx +++ b/web/src/app/docs/cloud/page.mdx @@ -2,6 +2,8 @@ export const metadata = { title: "Conch Cloud", description: "Cloud machines tha # Conch Cloud +> Conch Cloud is not enabled in this release: set `CONCH_CLOUD=1`, or `enabled = true` under `[cloud]` in `config.toml`, to try it ([more](/docs/cli#conch-cloud-commands)). + Conch Cloud runs machines with conch in them for you. Your agents keep working on one with the laptop closed; it sleeps when nothing is happening and wakes when you come back. To conch — the TUI, Conch.app, the commands — a cloud machine is one more machine. Nothing of it is there until you sign in. A conch that has never signed in asks nothing of Conch Cloud, shows no new rows, and behaves exactly as it did. diff --git a/web/src/lib/docs.ts b/web/src/lib/docs.ts index b0098294..a188f084 100644 --- a/web/src/lib/docs.ts +++ b/web/src/lib/docs.ts @@ -23,7 +23,6 @@ export const docs: DocSection[] = [ { title: "Sessions", href: "/docs/sessions", description: "Resume saved conversations and interrupted runs." }, { title: "Remote machines", href: "/docs/remote-machines", description: "Run agents on other machines over ssh." }, { title: "Sandboxes", href: "/docs/sandboxes", description: "Run agents in a Daytona sandbox that keeps going with your laptop closed." }, - { title: "Conch Cloud", href: "/docs/cloud", description: "Cloud machines that keep your agents working with the laptop closed: sign in, and they are machines like any other." }, { title: "Mac app", href: "/docs/mac-app", description: "conch in a native macOS window: the tree, tabs and splits, panes drawn by Ghostty where it is built in, a branch's changes, sessions, commits, and answers on a waiting agent." }, { title: "Phone", href: "/docs/phone", description: "See your agents from your phone, reply to one and answer what it asks." }, { title: "Brain", href: "/docs/brain", description: "Ask for work in plain words and approve the plan." }, @@ -36,7 +35,6 @@ export const docs: DocSection[] = [ { title: "Command line", href: "/docs/cli", description: "Scripting conch from a shell." }, { title: "Configuration", href: "/docs/configuration", description: "Files conch keeps and config.toml." }, { title: "Protocol", href: "/docs/protocol", description: "The NDJSON protocol and the source layout." }, - { title: "Cloud machine image", href: "/docs/cloud-machine", description: "Build a machine image with conch in it for Conch Cloud." }, ], }, ] From b528a1e45931b03ec1dd440d9d0166e91dfde2cd Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Thu, 12 Nov 2026 23:57:13 -0800 Subject: [PATCH 07/35] Test that the website hides Conch Cloud MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Conch Cloud is not enabled in 0.2.0. The test says the sidebar leaves its two pages out, both pages say it is not enabled, and nothing else on the site names it but the Command line page's own section about its commands — so a guide page rewritten later cannot bring it back. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/docs_test.go | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/cmd/conch/docs_test.go b/cmd/conch/docs_test.go index 7b49364e..bacf162f 100644 --- a/cmd/conch/docs_test.go +++ b/cmd/conch/docs_test.go @@ -273,3 +273,54 @@ func TestDocsLinksResolve(t *testing.T) { t.Fatal("no docs links found — the regexp or the pages moved") } } + +// TestDocsHideCloud: Conch Cloud is not enabled in this release, so the +// website does not offer it. Its pages stay, for whoever turns it on, but +// the sidebar leaves them out, each says it is not enabled, and no other +// page — nor the site's components — names it, except the Command line +// page's own section about its commands. +func TestDocsHideCloud(t *testing.T) { + nav, err := os.ReadFile("../../web/src/lib/docs.ts") + if err != nil { + t.Fatal(err) + } + for _, p := range []string{"/docs/cloud", "/docs/cloud-machine"} { + if strings.Contains(string(nav), `href: "`+p+`"`) { + t.Errorf("the docs sidebar lists %s", p) + } + b, err := os.ReadFile("../../web/src/app" + p + "/page.mdx") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), "Conch Cloud is not enabled in this release") { + t.Errorf("%s does not say Conch Cloud is not enabled", p) + } + } + cloud := regexp.MustCompile(`(?i)conch cloud|/docs/cloud\b`) + var files []string + _ = filepath.WalkDir("../../web/src", func(path string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && (strings.HasSuffix(path, ".mdx") || strings.HasSuffix(path, ".tsx") || strings.HasSuffix(path, ".ts")) { + files = append(files, path) + } + return nil + }) + for _, f := range files { + if strings.Contains(f, "/docs/cloud/") || strings.Contains(f, "/docs/cloud-machine/") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + src := string(b) + if strings.HasSuffix(f, "/docs/cli/page.mdx") { + if i := strings.Index(src, "## Conch Cloud commands"); i >= 0 { + src = src[:i] // the one place the commands are described + } + } + for _, m := range cloud.FindAllStringIndex(src, -1) { + line := strings.Count(src[:m[0]], "\n") + 1 + t.Errorf("%s:%d names Conch Cloud", f, line) + } + } +} From 418bfb752a17ebe6b9be3faf731147ebaa190953 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 15:55:14 -0800 Subject: [PATCH 08/35] Notice ref changes in reftable repositories Git 3 makes new repositories with reftable refs, where branches and HEAD live in reftable/ and refs/heads never moves. MetaStamp read only the files backend, so the project ticker skipped every refresh there and the branch list went stale. It now hashes reftable/tables.list for the repository and each linked worktree. The new git3_test.go runs conch's reading of history, branches, worktrees and changes against a SHA-256 reftable repository. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/git3_test.go | 157 +++++++++++++++++++++++++++++++++++++ internal/gitx/stamp.go | 12 +++ 2 files changed, 169 insertions(+) create mode 100644 internal/gitx/git3_test.go diff --git a/internal/gitx/git3_test.go b/internal/gitx/git3_test.go new file mode 100644 index 00000000..85e5f73c --- /dev/null +++ b/internal/gitx/git3_test.go @@ -0,0 +1,157 @@ +package gitx + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +// Git 3.0 makes a new repository SHA-256 with reftable refs on a branch +// called main (Documentation/BreakingChanges). Existing repositories keep +// what they have, so conch meets both kinds for years, side by side. +// These tests make the new kind with today's git and run conch against it. + +// git3 says whether this git can make a Git 3 repository: reftable came +// in 2.45. +func git3(t *testing.T) { + t.Helper() + dir := t.TempDir() + out, err := exec.Command("git", "init", "-q", "--object-format=sha256", "--ref-format=reftable", dir).CombinedOutput() + if err != nil { + t.Skipf("this git cannot make a SHA-256 reftable repository: %v\n%s", err, out) + } +} + +// newGit3Repo is newRepo the way git 3 makes one. +func newGit3Repo(t *testing.T) string { + t.Helper() + git3(t) + dir := filepath.Join(t.TempDir(), "repo") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + dir = resolve(dir) + git(t, dir, "init", "-q", "--object-format=sha256", "--ref-format=reftable", "-b", "main") + configure(t, dir) + commit(t, dir, "README.md", "hello\n", "initial") + return dir +} + +// A reftable repository keeps no refs/heads files: every ref lives in +// reftable/, HEAD included, so a stamp that read only the files backend +// never moved there and a branch on screen went stale. +func TestMetaStampReftable(t *testing.T) { + root := newGit3Repo(t) + common := filepath.Join(root, ".git") + s1 := MetaStamp(common) + if s := MetaStamp(common); s != s1 { + t.Fatal("unstable stamp") + } + git(t, root, "branch", "other") + s2 := MetaStamp(common) + if s2 == s1 { + t.Error("stamp unchanged after a branch was made") + } + git(t, root, "update-ref", "refs/heads/other", "HEAD") // same value: still a write + git(t, root, "branch", "-D", "other") + s3 := MetaStamp(common) + if s3 == s2 { + t.Error("stamp unchanged after a branch was deleted") + } + git(t, root, "checkout", "-q", "-b", "side") + if s := MetaStamp(common); s == s3 { + t.Error("stamp unchanged after checkout") + } + + // A linked worktree keeps its own HEAD in its own reftable. + wt := filepath.Join(filepath.Dir(root), "linked") + git(t, root, "worktree", "add", "-q", "-b", "feat", wt) + s4 := MetaStamp(common) + configure(t, wt) + commit(t, wt, "f.txt", "f\n", "on feat") + git(t, wt, "checkout", "-q", "--detach") + if s := MetaStamp(common); s == s4 { + t.Error("stamp unchanged after a linked worktree moved HEAD") + } +} + +// What the graph, the branch list and the changes view read works the +// same on 64-character hashes and reftable refs. +func TestGit3Repository(t *testing.T) { + root := newGit3Repo(t) + head := git(t, root, "rev-parse", "HEAD") + if len(head) != 64 { + t.Fatalf("not a SHA-256 repository: %q", head) + } + r, err := Discover(ctx, root) + if err != nil || r.Root != root { + t.Fatalf("Discover = %+v, %v", r, err) + } + if b := DefaultBase(ctx, root); b != "main" { + t.Errorf("DefaultBase = %q", b) + } + wt := filepath.Join(filepath.Dir(root), "wt") + if err := AddWorktree(ctx, root, wt, "feat", "main"); err != nil { + t.Fatal(err) + } + configure(t, wt) + commit(t, wt, "a.txt", "a\n", "add a") + write(t, wt, "a.txt", "a\nb\n") + + commits, more, err := Log(ctx, root, 10) + if err != nil || more || len(commits) != 2 { + t.Fatalf("Log = %d commits, more %v, %v", len(commits), more, err) + } + for _, c := range commits { + if len(c.Hash) != 64 { + t.Errorf("hash %q", c.Hash) + } + for _, p := range c.Parents { + if len(p) != 64 { + t.Errorf("parent %q", p) + } + } + } + if commits[0].Parents[0] != head { + t.Errorf("feat's parent %q, want %q", commits[0].Parents[0], head) + } + + bs, err := Branches(ctx, root, "main") + if err != nil { + t.Fatal(err) + } + var feat *Branch + for i := range bs { + if bs[i].Name == "feat" { + feat = &bs[i] + } + } + if feat == nil || feat.BaseAhead != 1 { + t.Errorf("Branches = %+v", bs) + } + wts, err := Worktrees(ctx, root) + if err != nil || len(wts) != 2 { + t.Fatalf("Worktrees = %+v, %v", wts, err) + } + ch, err := WorktreeChanges(ctx, wt, "main") + if err != nil || len(ch.Files) == 0 { + t.Fatalf("WorktreeChanges = %+v, %v", ch, err) + } + d, err := ShowCommit(ctx, root, "feat") + if err != nil || len(d.Hash) != 64 { + t.Fatalf("ShowCommit = %+v, %v", d, err) + } + if Ahead(ctx, root, "feat", "main") != 1 || !Merged(ctx, root, "main", "feat") { + t.Error("ahead/merged wrong on SHA-256") + } + if c := CommitOf(ctx, root, "feat"); len(c) != 64 { + t.Errorf("CommitOf = %q", c) + } + if !isHash(head) { + t.Error("isHash refuses a SHA-256 hash") + } + if got, _ := HaveCommits(ctx, root, []string{head}); len(got) != 1 { + t.Errorf("HaveCommits = %v", got) + } +} diff --git a/internal/gitx/stamp.go b/internal/gitx/stamp.go index 25a2137e..1cc1ba64 100644 --- a/internal/gitx/stamp.go +++ b/internal/gitx/stamp.go @@ -11,6 +11,9 @@ import ( // MetaStamp is a cheap fingerprint of a repository's git metadata, computed // from file mtimes and sizes without running git. It changes when refs, HEAD, // the index or worktrees change, so callers can skip refreshes otherwise. +// It reads both ref backends: the files one (refs/heads, packed-refs) and +// reftable, git 3's default, where every ref — HEAD too — is in +// reftable/ and the files above never move. func MetaStamp(commonDir string) string { h := fnv.New64a() add := func(path string) { @@ -20,9 +23,17 @@ func MetaStamp(commonDir string) string { } fmt.Fprintf(h, "%s\x00%d\x00%d\x00", path, info.Size(), info.ModTime().UnixNano()) } + // Every reftable write adds a table and rewrites tables.list with its + // name, so the list's text moves even when its size and mtime might not. + list := func(dir string) { + if b, err := os.ReadFile(filepath.Join(dir, "reftable", "tables.list")); err == nil { + fmt.Fprintf(h, "%s\x00%s\x00", dir, b) + } + } for _, name := range []string{"HEAD", "index", "packed-refs", "FETCH_HEAD"} { add(filepath.Join(commonDir, name)) } + list(commonDir) // A deleted branch only shows as a missing path, which the hash of // present paths captures. filepath.WalkDir(filepath.Join(commonDir, "refs", "heads"), func(p string, d fs.DirEntry, err error) error { @@ -35,6 +46,7 @@ func MetaStamp(commonDir string) string { for _, wt := range wts { add(filepath.Join(wt, "HEAD")) add(filepath.Join(wt, "index")) + list(wt) } return fmt.Sprintf("%016x", h.Sum64()) } From 01c68c755bf4d2e76730e49d77e4ac4d18a267bd Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 15:55:14 -0800 Subject: [PATCH 09/35] Make a moved repository with its bundle's object format InitFromBundle ran a bare git init, which makes git's default hash: SHA-1 today, SHA-256 under git 3. A bundle from a repository of the other kind was then refused (pack is corrupted / early EOF), so moving a project between machines with different gits failed. It now reads the bundle's @object-format header and inits to match. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/git3_test.go | 55 ++++++++++++++++++++++++++++++++++++++ internal/gitx/move.go | 29 +++++++++++++++++++- 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/internal/gitx/git3_test.go b/internal/gitx/git3_test.go index 85e5f73c..b0abd5c6 100644 --- a/internal/gitx/git3_test.go +++ b/internal/gitx/git3_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" ) @@ -155,3 +156,57 @@ func TestGit3Repository(t *testing.T) { t.Errorf("HaveCommits = %v", got) } } + +// A bundle carries its repository's hash. The repository made to take it +// has to be made with the same one, whatever git would make by default — +// SHA-1 now, SHA-256 under git 3 — or the fetch is refused. +func TestInitFromBundleKeepsObjectFormat(t *testing.T) { + git3(t) + for _, c := range []struct{ src, dflt string }{ + {"sha256", "sha1"}, // a git 3 repository moved to a machine with git 2 + {"sha1", "sha256"}, // an old repository moved to a machine with git 3 + } { + t.Run(c.src+"-into-"+c.dflt, func(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "src") + bundleGit(t, dir, "init", "-q", "--object-format="+c.src, "-b", "main", src) + os.WriteFile(filepath.Join(src, "a.txt"), []byte("a\n"), 0o644) + bundleGit(t, src, "add", "a.txt") + bundleGit(t, src, "commit", "-q", "-m", "one") + file := filepath.Join(dir, "all.bundle") + if err := BundleAll(ctx, src, file); err != nil { + t.Fatal(err) + } + t.Setenv("GIT_DEFAULT_HASH", c.dflt) + dst := filepath.Join(dir, "dst") + if err := InitFromBundle(ctx, file, dst, "main"); err != nil { + t.Fatal(err) + } + if got := bundleGit(t, dst, "rev-parse", "--show-object-format"); got != c.src { + t.Errorf("made a %s repository from a %s bundle", got, c.src) + } + if a, b := bundleGit(t, src, "rev-parse", "HEAD"), bundleGit(t, dst, "rev-parse", "HEAD"); a != b { + t.Errorf("HEAD %s, want %s", b, a) + } + }) + } +} + +func TestBundleObjectFormat(t *testing.T) { + dir := t.TempDir() + for name, c := range map[string]struct{ body, want string }{ + "v2": {"# v2 git bundle\nabc refs/heads/main\n\nPACK", "sha1"}, + "v3 sha256": {"# v3 git bundle\n@object-format=sha256\n@filter=blob:none\nabc refs/heads/main\n\nPACK", "sha256"}, + "v3 no cap": {"# v3 git bundle\nabc refs/heads/main\n\nPACK", "sha1"}, + "empty": {"", "sha1"}, + } { + p := filepath.Join(dir, strings.ReplaceAll(name, " ", "-")) + os.WriteFile(p, []byte(c.body), 0o644) + if got := bundleObjectFormat(p); got != c.want { + t.Errorf("%s: %q, want %q", name, got, c.want) + } + } + if got := bundleObjectFormat(filepath.Join(dir, "missing")); got != "sha1" { + t.Errorf("missing: %q", got) + } +} diff --git a/internal/gitx/move.go b/internal/gitx/move.go index 35c08f15..b17466ae 100644 --- a/internal/gitx/move.go +++ b/internal/gitx/move.go @@ -1,6 +1,7 @@ package gitx import ( + "bufio" "context" "errors" "fmt" @@ -228,6 +229,29 @@ func BundleAll(ctx context.Context, root, file string) error { return err } +// bundleObjectFormat is the hash a bundle's objects are named by. A v3 +// bundle says so in an @object-format line of its header; one that does +// not, and every v2 bundle, is SHA-1. The header ends at its first empty +// line, before the pack. +func bundleObjectFormat(file string) string { + f, err := os.Open(file) + if err != nil { + return "sha1" + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := sc.Text() + if line == "" { + break + } + if v, ok := strings.CutPrefix(line, "@object-format="); ok && v != "" { + return v + } + } + return "sha1" +} + // InitFromBundle makes dir, which must not exist yet or be empty, a new // repository holding every branch and tag of bundle, with branch checked // out — or, when it has no such branch, its first. It has no remote: a @@ -236,7 +260,10 @@ func InitFromBundle(ctx context.Context, bundle, dir, branch string) error { if err := os.MkdirAll(dir, 0o755); err != nil { return err } - if _, err := run(ctx, dir, "init", "-q"); err != nil { + // The new repository takes the bundle's hash, not this git's default: + // SHA-1 objects cannot be fetched into a SHA-256 repository, and git 3 + // makes SHA-256 ones. + if _, err := run(ctx, dir, "init", "-q", "--object-format="+bundleObjectFormat(bundle)); err != nil { return err } if _, err := run(ctx, dir, "bundle", "verify", "-q", bundle); err != nil { From 5574974fc849a0aa887e73fec227ddf33d11690f Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:36:49 -0800 Subject: [PATCH 10/35] Say a repository's object and ref format in project.log The commit graph is to show whether a project is a git 3 repository (SHA-256 objects, reftable refs) or an older one, since conch meets both side by side. gitx.Format reads it with rev-parse; a git older than 2.45 cannot name its ref backend and cannot open reftable, so its refs are files. The field is optional: older servers leave it out. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/git3_test.go | 9 +++++++++ internal/gitx/log.go | 25 +++++++++++++++++++++++++ internal/proto/proto.go | 10 ++++++++++ internal/server/log.go | 3 +++ internal/server/log_test.go | 5 +++++ 5 files changed, 52 insertions(+) diff --git a/internal/gitx/git3_test.go b/internal/gitx/git3_test.go index b0abd5c6..8c4b2ba2 100644 --- a/internal/gitx/git3_test.go +++ b/internal/gitx/git3_test.go @@ -149,6 +149,15 @@ func TestGit3Repository(t *testing.T) { if c := CommitOf(ctx, root, "feat"); len(c) != 64 { t.Errorf("CommitOf = %q", c) } + if f := Format(ctx, root); f.Objects != "sha256" || f.Refs != "reftable" { + t.Errorf("Format = %+v", f) + } + if f := Format(ctx, newRepo(t)); f.Objects != "sha1" || f.Refs != "files" { + t.Errorf("Format of a git 2 repository = %+v", f) + } + if f := Format(ctx, t.TempDir()); f != (RepoFormat{}) { + t.Errorf("Format outside a repository = %+v", f) + } if !isHash(head) { t.Error("isHash refuses a SHA-256 hash") } diff --git a/internal/gitx/log.go b/internal/gitx/log.go index d7f28237..9c2bde98 100644 --- a/internal/gitx/log.go +++ b/internal/gitx/log.go @@ -100,3 +100,28 @@ func Remotes(ctx context.Context, dir string) []string { } return strings.Fields(string(out)) } + +// RepoFormat is how a repository stores itself: its object hash (sha1, or +// sha256 as git 3 makes new repositories) and its refs backend (files, or +// reftable). Both are "" outside a repository. +type RepoFormat struct { + Objects string + Refs string +} + +// Format reads dir's repository format. A git older than 2.45 cannot say +// its refs backend, and cannot open a reftable repository either, so the +// refs of one it can read are files. +func Format(ctx context.Context, dir string) RepoFormat { + out, err := run(ctx, dir, "rev-parse", "--show-object-format") + if err != nil { + return RepoFormat{} + } + f := RepoFormat{Objects: strings.TrimSpace(string(out)), Refs: "files"} + if out, err := run(ctx, dir, "rev-parse", "--show-ref-format"); err == nil { + if r := strings.TrimSpace(string(out)); r != "" { + f.Refs = r + } + } + return f +} diff --git a/internal/proto/proto.go b/internal/proto/proto.go index 5ee68d5d..50164341 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -1631,6 +1631,16 @@ type LogResult struct { // remote's branch (fork/main) from a local one with a slash. Absent // from an older server: clients then take origin and upstream. Remotes []string `json:"remotes,omitempty"` + // Format is how the repository stores itself — sha1 or sha256 + // objects, files or reftable refs — absent from an older server. + Format *RepoFormat `json:"format,omitempty"` +} + +// RepoFormat is a repository's object hash and refs backend: git 3 makes +// new repositories sha256 and reftable, and conch meets both kinds. +type RepoFormat struct { + Objects string `json:"objects,omitempty"` + Refs string `json:"refs,omitempty"` } // CommitParams asks project.commit about Hash: the commit itself; with diff --git a/internal/server/log.go b/internal/server/log.go index e492c146..a5bccf59 100644 --- a/internal/server/log.go +++ b/internal/server/log.go @@ -34,6 +34,9 @@ func (pm *projectManager) log(lp proto.LogParams) (proto.LogResult, *proto.Error return proto.LogResult{}, proto.Errorf(proto.ErrBadRequest, "%v", err) } res := proto.LogResult{Commits: make([]proto.LogCommit, 0, len(commits)), More: more, Remotes: gitx.Remotes(ctx, p.root)} + if f := gitx.Format(ctx, p.root); f.Objects != "" { + res.Format = &proto.RepoFormat{Objects: f.Objects, Refs: f.Refs} + } for _, c := range commits { res.Commits = append(res.Commits, proto.LogCommit{Hash: c.Hash, Parents: c.Parents, Subject: c.Subject, Author: c.Author, Time: c.Time, Refs: c.Refs}) diff --git a/internal/server/log_test.go b/internal/server/log_test.go index 8d0033cb..45256206 100644 --- a/internal/server/log_test.go +++ b/internal/server/log_test.go @@ -41,6 +41,11 @@ func TestProjectLog(t *testing.T) { if len(res.Commits) != 1 || !res.More || res.Commits[0].Subject != "on feat" { t.Errorf("limit 1: %+v", res) } + // The repository's format comes with it: a SHA-1 repository with the + // files backend, as git 2 makes them. + if res.Format == nil || res.Format.Objects != "sha1" || res.Format.Refs != "files" { + t.Errorf("format: %+v", res.Format) + } } // An unknown project is an error, as everywhere else; so is one that is From c8be64a1982d3862b2bc7e9376751899f4f8bc73 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:40:23 -0800 Subject: [PATCH 11/35] ConchKit: whose commit is whose, and what each agent branch needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The commit graph is to show which agent made each commit and what each agent's branch needs from the person (option A of the git view mocks). commitOwners gives a branch the commits its first parents reach before the base, stopping at a branch stacked beneath it; graphBranches lists the worktree branches with their agent and the most urgent state — stopped on a conflict, agent waiting, CI red, a conflict coming (merge- tree), working, done, idle. resolvePrompt is what an agent is asked to fix a conflict; ciMarks are a pull request's checks for its commit; and LogResult reads the repository format the server now sends. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchKit/BranchGraph.swift | 192 ++++++++++++++++++ macos/Sources/ConchKit/CommitGraph.swift | 2 + .../ConchKitTests/BranchGraphTests.swift | 148 ++++++++++++++ 3 files changed, 342 insertions(+) create mode 100644 macos/Sources/ConchKit/BranchGraph.swift create mode 100644 macos/Tests/ConchKitTests/BranchGraphTests.swift diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift new file mode 100644 index 00000000..c76205cb --- /dev/null +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -0,0 +1,192 @@ +import Foundation + +// What the commit graph says about the agents' branches: which commits are +// whose, what each branch needs from the person, and what an agent is +// asked when its branch conflicts with the base. + +/// The local branches pointing at commits of a history, each at its newest: +/// "HEAD -> main" is main; a remote's branch and a tag are not branches. +public func branchTips(_ commits: [LogCommit], remotes: Set = ["origin", "upstream"]) -> [String: String] { + var tips: [String: String] = [:] + for c in commits { + for r in CommitRef.parse(c.refs, remotes: remotes) where (r.kind == .head || r.kind == .branch) && r.name != "HEAD" { + if tips[r.name] == nil { tips[r.name] = c.hash } + } + } + return tips +} + +/// Which branch each commit is on, for the graph's agent column: a +/// branch's commits are those its first parents reach before reaching the +/// base. The base's own history, and what was merged into it, is nobody's +/// branch. A branch stacked on another keeps only its own commits, since +/// the branch nearer the top claims first. +public func commitOwners(_ commits: [LogCommit], base: String, remotes: Set = ["origin", "upstream"]) -> [String: String] { + let byHash = Dictionary(commits.map { ($0.hash, $0) }, uniquingKeysWith: { a, _ in a }) + let tips = branchTips(commits, remotes: remotes) + // Everything the base reaches, by any parent. + var onBase = Set() + if let t = tips[base] { + var stack = [t] + while let h = stack.popLast() { + guard onBase.insert(h).inserted, let c = byHash[h] else { continue } + stack.append(contentsOf: c.parents ?? []) + } + } + // Newest tip first, so a stacked branch claims its commits before the + // one beneath it walks through them. + let order = Dictionary(commits.enumerated().map { ($1.hash, $0) }, uniquingKeysWith: { a, _ in a }) + var owners: [String: String] = [:] + let tipHashes = Set(tips.filter { $0.key != base }.values) + for (name, tip) in tips.sorted(by: { (order[$0.value] ?? 0, $0.key) < (order[$1.value] ?? 0, $1.key) }) where name != base { + var h: String? = tip + // Another branch's tip is where this one was stacked on it. + while let cur = h, !onBase.contains(cur), owners[cur] == nil, cur == tip || !tipHashes.contains(cur), let c = byHash[cur] { + owners[cur] = name + h = c.parents?.first + } + } + return owners +} + +/// What an agent's branch needs, most urgent first. +public enum GraphBranchState: Equatable, Sendable { + /// Its worktree stopped mid-rebase or merge with files to resolve. + case conflicted(Int) + /// Its agent is waiting for the person. + case waiting + /// Its pull request's checks failed. + case ciFailing + /// Merging it into the base would conflict (git merge-tree), though + /// nothing has moved yet. + case willConflict + case working + case done + case idle + + /// Sorts the side's list: lower comes first. + public var urgency: Int { + switch self { + case .conflicted: 0 + case .waiting: 1 + case .ciFailing: 2 + case .willConflict: 3 + case .working: 4 + case .done: 5 + case .idle: 6 + } + } + + /// Whether an agent should be asked to resolve a conflict. + public var conflicts: Bool { + switch self { + case .conflicted, .willConflict: true + default: false + } + } +} + +/// An agent's branch as the graph's side lists it. +public struct GraphBranch: Equatable, Sendable { + public var name: String + /// The agent working on it, if one is running. + public var agent: PaneInfo? + public var state: GraphBranchState + /// Commits ahead of and behind the base. + public var ahead: Int + public var behind: Int + /// The files merging it into the base would conflict in. + public var conflicts: [String] + public var pr: PRInfo? +} + +/// The project's agent branches — every branch checked out in a worktree +/// of its own, never the base or the main checkout — with the state each +/// is in, most urgent first and otherwise as the worktrees are listed. +public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo]) -> [GraphBranch] { + let base = project.base ?? "" + let mainBranches = Set((project.worktrees ?? []).filter { $0.main == true }.compactMap(\.branch)) + let info = Dictionary((project.branches ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) + var out: [GraphBranch] = [] + for w in project.worktrees ?? [] where w.main != true { + guard let name = w.branch, !name.isEmpty, name != base, !mainBranches.contains(name), + !out.contains(where: { $0.name == name }) else { continue } + let b = info[name] + let agent = branchAgent(branchAgents(panes, project: project.id, branch: name), handedTo: nil) + let pr = b?.pr.flatMap { ($0.state ?? "OPEN") == "OPEN" ? $0 : nil } + let state: GraphBranchState + if let n = w.status?.conflicts, n > 0 { + state = .conflicted(n) + } else if agent?.agent?.state == .blocked { + state = .waiting + } else if pr?.checks == "fail" { + state = .ciFailing + } else if !(w.conflicts ?? []).isEmpty { + state = .willConflict + } else if agent?.agent?.state == .working { + state = .working + } else if agent?.agent?.state == .done { + state = .done + } else { + state = .idle + } + out.append(GraphBranch(name: name, agent: agent, state: state, ahead: b?.baseAhead ?? 0, behind: b?.baseBehind ?? 0, + conflicts: w.conflicts ?? [], pr: pr)) + } + return out.enumerated().sorted { ($0.element.state.urgency, $0.offset) < ($1.element.state.urgency, $1.offset) }.map(\.element) +} + +/// What an agent is asked when its branch conflicts with the base: finish +/// the rebase that stopped, or bring the branch up to date before the +/// conflict reaches a pull request. Tests are run; pushing is left to the +/// person or the autopilot. +public func resolvePrompt(branch: String, base: String, files: [String], stopped: Bool) -> String { + let shown = files.prefix(8).joined(separator: ", ") + let rest = files.count > 8 ? " and \(files.count - 8) more" : "" + let which = files.isEmpty ? "the conflicting files (git status lists them)" : shown + rest + if stopped { + return "The rebase of \(branch) onto \(base) stopped on conflicts in \(which). Resolve each one, keeping what both sides meant, " + + "run the tests that cover those files, then git add them and git rebase --continue. Say what you kept from each side." + } + return "Rebase \(branch) onto \(base): it will conflict in \(which). Resolve each conflict, keeping what both sides meant, " + + "run the tests that cover those files, and say what you kept from each side." +} + +/// One of a pull request's checks, as a mark on the commit it ran on. +public struct CIMark: Equatable, Sendable { + public var name: String + /// pass, fail or pending. + public var state: String + public var url: String? +} + +/// A pull request's checks as marks: failures first, then those still +/// running, then passes, a handful at most so a row stays a row. +public func ciMarks(_ pr: PRInfo, limit: Int = 8) -> [CIMark] { + let rank = ["fail": 0, "pending": 1, "pass": 2] + let runs = (pr.runs ?? []).enumerated().sorted { + (rank[$0.element.state] ?? 3, $0.offset) < (rank[$1.element.state] ?? 3, $1.offset) + } + return runs.prefix(limit).map { CIMark(name: $0.element.name, state: $0.element.state, url: $0.element.url) } +} + +/// How a repository stores itself (project.log's format): git 3 makes new +/// ones SHA-256 with reftable refs. +public struct RepoFormat: Decodable, Equatable, Sendable { + public var objects: String? + public var refs: String? + + public init(objects: String?, refs: String?) { + self.objects = objects + self.refs = refs + } + + public var git3: Bool { objects == "sha256" } + + /// "SHA-256 · reftable", or "" when the server did not say. + public var label: String { + guard let o = objects, !o.isEmpty else { return "" } + let hash = o == "sha256" ? "SHA-256" : o == "sha1" ? "SHA-1" : o + return refs.map { "\(hash) · \($0)" } ?? hash + } +} diff --git a/macos/Sources/ConchKit/CommitGraph.swift b/macos/Sources/ConchKit/CommitGraph.swift index 608ccceb..30a04943 100644 --- a/macos/Sources/ConchKit/CommitGraph.swift +++ b/macos/Sources/ConchKit/CommitGraph.swift @@ -27,6 +27,8 @@ public struct LogResult: Decodable, Sendable { public var more: Bool? /// The repository's remotes; nil from an older server. public var remotes: [String]? + /// How the repository stores itself; nil from an older server. + public var format: RepoFormat? } /// A project's commit graph tab's key in the layout: diff --git a/macos/Tests/ConchKitTests/BranchGraphTests.swift b/macos/Tests/ConchKitTests/BranchGraphTests.swift new file mode 100644 index 00000000..6e6fb845 --- /dev/null +++ b/macos/Tests/ConchKitTests/BranchGraphTests.swift @@ -0,0 +1,148 @@ +import Foundation +import Testing +@testable import ConchKit + +// The commit graph's history as conch has it: master with a merged pull +// request, and two agents' branches off it — one two commits long, one +// that started before the merge. +// +// u1 (conch/graph) codex +// r2 (HEAD -> conch/git3) claude +// m5 (master) merge of a2 +// r1 claude +// u0 codex +// a2 (origin/feature) +// m4 +func history() -> [LogCommit] { + [ + LogCommit(hash: "u1", parents: ["u0"], subject: "lanes", refs: ["conch/graph"]), + LogCommit(hash: "r2", parents: ["r1"], subject: "bundle", refs: ["HEAD -> conch/git3"]), + LogCommit(hash: "m5", parents: ["m4", "a2"], subject: "merge", refs: ["master", "origin/master"]), + LogCommit(hash: "r1", parents: ["m4"], subject: "stamp"), + LogCommit(hash: "u0", parents: ["m4"], subject: "model"), + LogCommit(hash: "a2", parents: ["m4"], subject: "feature", refs: ["origin/feature"]), + LogCommit(hash: "m4", parents: [], subject: "root"), + ] +} + +// Each branch's commits are what its first parents reach before the base +// does: the merged feature is master's, and so is everything below. +@Test func ownersFollowFirstParentsToTheBase() { + let owners = commitOwners(history(), base: "master") + #expect(owners["u1"] == "conch/graph") + #expect(owners["u0"] == "conch/graph") + #expect(owners["r2"] == "conch/git3") + #expect(owners["r1"] == "conch/git3") + #expect(owners["m5"] == nil && owners["a2"] == nil && owners["m4"] == nil) + #expect(branchTips(history())["conch/git3"] == "r2") + #expect(branchTips(history())["master"] == "m5") + // A remote's branch is not a tip of a local one. + #expect(branchTips(history())["origin/feature"] == nil) +} + +// A branch stacked on another keeps only its own commits; the one below +// it keeps the rest. A base that is not in the history (a log cut short, +// a base never fetched) leaves each branch everything its first parents +// reach, and an empty history owns nothing. +@Test func ownersOfStackedAndOddHistories() { + let stacked = [ + LogCommit(hash: "c3", parents: ["c2"], subject: "top", refs: ["top"]), + LogCommit(hash: "c2", parents: ["c1"], subject: "mid", refs: ["mid"]), + LogCommit(hash: "c1", parents: ["c0"], subject: "low"), + LogCommit(hash: "c0", parents: [], subject: "base", refs: ["main"]), + ] + let o = commitOwners(stacked, base: "main") + #expect(o["c3"] == "top") + #expect(o["c2"] == "mid" && o["c1"] == "mid") + #expect(o["c0"] == nil) + let noBase = commitOwners(stacked, base: "trunk") + #expect(noBase["c0"] != nil) + #expect(commitOwners([], base: "main").isEmpty) + // A parent outside the history ends the walk without a crash. + #expect(commitOwners([LogCommit(hash: "x", parents: ["gone"], subject: "", refs: ["b"])], base: "main") == ["x": "b"]) +} + +// The side's list: one entry per agent's worktree branch, never the base +// or the main checkout, each in the state that needs the person most. +@Test func graphBranchStates() throws { + let json = #""" + {"id":"r1","name":"conch","path":"/p","base":"master", + "worktrees":[{"path":"/p","branch":"master","main":true}, + {"path":"/w/a","branch":"stopped","status":{"files":2,"conflicts":2}}, + {"path":"/w/b","branch":"red"}, + {"path":"/w/c","branch":"forecast","conflicts":["a.go","b.go"]}, + {"path":"/w/d","branch":"asking"}, + {"path":"/w/e","branch":"busy"}, + {"path":"/w/f","branch":"quiet"}], + "branches":[{"name":"master"}, + {"name":"red","base_ahead":2,"base_behind":1,"pr":{"number":7,"state":"OPEN","checks":"fail"}}, + {"name":"forecast","base_ahead":1}]} + """# + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(json.utf8)) + let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" + [{"id":"p1","name":"a","state":"running","project_id":"r1","branch":"stopped","agent":{"name":"codex","state":"working"}}, + {"id":"p2","name":"d","state":"running","project_id":"r1","branch":"asking","agent":{"name":"claude","state":"blocked"}}, + {"id":"p3","name":"e","state":"running","project_id":"r1","branch":"busy","agent":{"name":"gemini","state":"working"}}, + {"id":"p4","name":"other","state":"running","project_id":"r2","branch":"quiet","agent":{"name":"claude","state":"working"}}] + """#.utf8)) + let bs = graphBranches(project, panes: panes) + #expect(bs.map(\.name) == ["stopped", "asking", "red", "forecast", "busy", "quiet"]) + let by = Dictionary(uniqueKeysWithValues: bs.map { ($0.name, $0) }) + #expect(by["stopped"]?.state == .conflicted(2)) + #expect(by["stopped"]?.agent?.id == "p1") + #expect(by["red"]?.state == .ciFailing && by["red"]?.ahead == 2 && by["red"]?.behind == 1) + #expect(by["forecast"]?.state == .willConflict && by["forecast"]?.conflicts == ["a.go", "b.go"]) + #expect(by["asking"]?.state == .waiting) + #expect(by["busy"]?.state == .working) + // Another project's agent on a branch of the same name is not this one's. + #expect(by["quiet"]?.state == .idle && by["quiet"]?.agent == nil) + #expect(graphBranches(ProjectInfo(id: "x", name: "x", path: "/x"), panes: []).isEmpty) +} + +// A conflict stopped mid-rebase is the most urgent, then an agent asking, +// then red CI, then one coming: the order the side's list sorts by. +@Test func graphBranchStateOrder() { + let order: [GraphBranchState] = [.conflicted(1), .waiting, .ciFailing, .willConflict, .working, .done, .idle] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) + #expect(Set(order.map(\.urgency)).count == order.count) +} + +// What an agent is asked: the branch, the base, the files, and to finish +// what was started — continue a rebase that stopped, or bring the branch +// up to date when nothing has moved yet. It never asks it to push. +@Test func resolvePromptSaysWhatToDo() { + let stopped = resolvePrompt(branch: "conch/graph", base: "master", files: ["a.go", "b.go"], stopped: true) + #expect(stopped.contains("conch/graph") && stopped.contains("master")) + #expect(stopped.contains("a.go") && stopped.contains("b.go")) + #expect(stopped.contains("--continue")) + #expect(!stopped.contains("push")) + let ahead = resolvePrompt(branch: "conch/graph", base: "master", files: ["a.go"], stopped: false) + #expect(ahead.contains("Rebase conch/graph onto master")) + #expect(!ahead.contains("--continue")) + // Many files are named a few at a time, with a count of the rest. + let many = resolvePrompt(branch: "b", base: "main", files: (1...12).map { "f\($0).go" }, stopped: true) + #expect(many.contains("f1.go") && !many.contains("f12.go") && many.contains("and 4 more")) + // No files known (an older server): it still says where to look. + #expect(resolvePrompt(branch: "b", base: "main", files: [], stopped: true).contains("git status")) +} + +// The checks of a pull request as marks on its commit, failures first, a +// few at most; none for a pull request without checks. +@Test func ciMarksFromChecks() { + var pr = PRInfo(number: 1, state: "OPEN", checks: "fail") + pr.runs = [PRCheck(name: "build", state: "pass"), PRCheck(name: "test macos", state: "fail"), + PRCheck(name: "swift", state: "pending")] + #expect(ciMarks(pr).map(\.name) == ["test macos", "swift", "build"]) + pr.runs = (1...20).map { PRCheck(name: "c\($0)", state: "pass") } + #expect(ciMarks(pr).count == 8) + #expect(ciMarks(PRInfo(number: 2)).isEmpty) +} + +// The repository's format in a word or two, git 3's shown as such. +@Test func repoFormatLabel() { + #expect(RepoFormat(objects: "sha256", refs: "reftable").label == "SHA-256 · reftable") + #expect(RepoFormat(objects: "sha256", refs: "reftable").git3) + #expect(!RepoFormat(objects: "sha1", refs: "files").git3) + #expect(RepoFormat(objects: "sha1", refs: "files").label == "SHA-1 · files") + #expect(RepoFormat(objects: nil, refs: nil).label == "") +} From ade024c9064ef08e3e1bdd8343081b3e4bb2bb39 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:43:14 -0800 Subject: [PATCH 12/35] Conch.app's commit graph: agents' branches, conflicts and CI Option A of the git view mocks, built on the graph the app already had. Beside the graph, every agent's branch with its agent, what it needs (stopped on a conflict, waiting, CI red, a conflict coming, working) and how far it is from the base; picking one dims the rest. Each commit says which agent made it, a branch's newest commit carries its state, and a pull request's checks show as marks on the commit they ran on. When a branch stops on a conflict, a banner above the graph asks its agent to resolve it, or starts another agent in its worktree with the same request; the commit panel offers the same for a conflict merge-tree sees coming. A commit can be handed to an agent: the task sheet opens with a new branch starting there (task.create's base). The header says when a repository is stored the git 3 way, SHA-256 with reftable. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchApp/CommitsView.swift | 341 ++++++++++++++++++++++- macos/Sources/ConchApp/Store.swift | 52 +++- macos/Sources/ConchApp/Views.swift | 4 + 3 files changed, 391 insertions(+), 6 deletions(-) diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 1292dd35..7e451d39 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -38,6 +38,12 @@ final class CommitsModel: ObservableObject { /// The repository's remotes, as the server names them (nil: an older /// server, and origin and upstream are taken). @Published var remotes: Set? + /// How the repository stores itself (nil from an older server). + @Published var format: RepoFormat? + /// Which agent branch each commit is on, by hash. + @Published var owners: [String: String] = [:] + /// A branch picked in the side's list: the rest of the graph dims. + @Published var focusOn: String? /// The graph's search: commits that do not match are dimmed, never /// taken out, so the lanes stay whole. @Published var query = "" @@ -72,6 +78,31 @@ final class CommitsModel: ObservableObject { var count: Int { rows.count } + var projectInfo: ProjectInfo? { store.snapshots[machine]?.project(project) } + + /// The agents' branches, most urgent first. + var branches: [GraphBranch] { + guard let p = projectInfo else { return [] } + return graphBranches(p, panes: store.snapshots[machine]?.panes ?? []) + } + + /// The branch a commit is on and its entry in the side's list, if it + /// is one of the agents'. + func branch(of hash: String) -> GraphBranch? { + guard let name = owners[hash] else { return nil } + return branches.first { $0.name == name } + } + + /// Asks an agent to resolve a branch's conflict: its own, or a new one + /// of the agent named. + func askToResolve(_ b: GraphBranch, start: String? = nil) { + store.askToResolve(machine: machine, project: project, branch: b, start: start) + } + + func handToAgent(_ c: LogCommit) { + store.handCommit(machine: machine, project: project, hash: c.hash, subject: c.subject) + } + /// Lanes the graph column is wide, the same for every row so hashes /// and subjects line up; a history wider than 16 lanes is clipped /// rather than pushing the text off the row. @@ -97,6 +128,8 @@ final class CommitsModel: ObservableObject { rows = commitGraph(r.commits ?? []) more = r.more ?? false remotes = r.remotes.map(Set.init) + format = r.format + owners = commitOwners(r.commits ?? [], base: projectInfo?.base ?? "", remotes: remotes ?? ["origin", "upstream"]) error = "" // The branch asked for, picked and brought into view if it is // among those read; either way, asked once. @@ -202,6 +235,8 @@ struct CommitsView: View { var body: some View { HStack(spacing: 0) { + BranchSide(model: model, store: store).frame(width: 232) + Rectangle().fill(Theme.line).frame(width: 1) graph if model.selected != nil { Rectangle().fill(Theme.line).frame(width: 1) @@ -217,6 +252,7 @@ struct CommitsView: View { VStack(spacing: 0) { header Rectangle().fill(Theme.line).frame(height: 1) + ConflictBanner(model: model) if model.range != nil { HStack(spacing: 8) { Circle().fill(Theme.merged).frame(width: 7, height: 7) @@ -235,8 +271,10 @@ struct CommitsView: View { ScrollViewReader { reader in ScrollView { LazyVStack(spacing: 0) { + let byName = Dictionary(model.branches.map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) ForEach(model.rows, id: \.commit.hash) { r in - CommitRow(model: model, store: store, row: r).id(r.commit.hash) + CommitRow(model: model, store: store, row: r, owner: model.owners[r.commit.hash].flatMap { byName[$0] }) + .id(r.commit.hash) } if model.canReadMore { Button("Show older commits") { model.loadMore() } @@ -263,6 +301,13 @@ struct CommitsView: View { Text("Commits").font(.ui(size: 13, weight: .semibold)) Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2) Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted) + if let f = model.format, !f.label.isEmpty { + Text(f.git3 ? "Git 3 · \(f.label)" : f.label) + .font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(f.git3 ? Theme.accent : Theme.muted) + .padding(.horizontal, 7).padding(.vertical, 2) + .background(Capsule().fill((f.git3 ? Theme.accent : Theme.muted).opacity(0.14))) + .help(f.git3 ? "This repository is stored the way git 3 makes new ones: SHA-256 object names and reftable refs" : "Object names and refs storage") + } if model.loading { ProgressView().controlSize(.small) } Spacer() HStack(spacing: 6) { @@ -293,6 +338,8 @@ struct CommitRow: View { @ObservedObject var model: CommitsModel @ObservedObject var store: Store let row: GraphRow + /// The agent branch the commit is on, if any. + let owner: GraphBranch? @State private var hovering = false static let height: CGFloat = 26 @@ -303,17 +350,23 @@ struct CommitRow: View { let refs = CommitRef.parse(c.refs, remotes: model.remotes ?? ["origin", "upstream"]) let on = model.selected == c.hash let cmp = model.compareWith == c.hash + let tip = owner != nil && refs.contains { $0.name == owner?.name } let dim = !commitMatches(c, model.query) || (model.inRange.map { !$0.contains(c.hash) } ?? false) + || (model.focusOn != nil && model.owners[c.hash] != model.focusOn) HStack(spacing: 8) { GraphCell(row: row).frame(width: CGFloat(model.lanes) * Self.laneWidth + 6, height: Self.height).clipped() Text(c.short).font(.ui(size: 11.5, design: .monospaced)).foregroundStyle(Theme.muted) ForEach(Array(refs.enumerated()), id: \.offset) { _, r in RefChip(ref: r) } // The commit a pull request's checks run on: its CI, here too. - if let pr = model.pullRequests[c.hash] { CIChip(pr: pr, number: true) } + if let pr = model.pullRequests[c.hash] { + CIChip(pr: pr, number: true) + CIMarks(marks: ciMarks(pr)) + } + if tip, let o = owner { StateTag(state: o.state) } Text(c.subject).font(.ui(size: 12.5)).foregroundStyle(Theme.text).lineLimit(1).truncationMode(.tail) .layoutPriority(-1) Spacer(minLength: 8) - Text(c.author ?? "").font(.ui(size: 11.5)).foregroundStyle(Theme.muted).lineLimit(1) + AgentCell(agent: owner?.agent, author: c.author ?? "").frame(width: 120, alignment: .leading) Text(agoText(c.time)).font(.ui(size: 11.5)).foregroundStyle(Theme.muted).frame(minWidth: 52, alignment: .trailing) } .padding(.horizontal, 10).frame(height: Self.height) @@ -326,6 +379,10 @@ struct CommitRow: View { .contextMenu { Button("Copy Hash") { copy(c.hash) } Button("Copy Subject") { copy(c.subject) } + Button("Hand to an Agent…") { model.handToAgent(c) } + if let o = owner, o.state.conflicts { + Button("Ask \(o.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(o) } + } let branches = refs.filter { $0.kind == .head || $0.kind == .branch }.map(\.name).filter { $0 != "HEAD" } if !branches.isEmpty { Divider() } ForEach(branches, id: \.self) { b in @@ -473,6 +530,16 @@ struct CommitDetailPanel: View { } } } + if model.range == nil { + if let b = model.branch(of: d.hash), b.state.conflicts { ConflictCard(model: model, branch: b) } + HStack(spacing: 8) { + if let c = model.rows.first(where: { $0.commit.hash == d.hash })?.commit { + Button("Hand to an Agent…") { model.handToAgent(c) } + .controlSize(.small) + .help("A new branch starting at this commit, with an agent of your choice on it") + } + } + } Rectangle().fill(Theme.line).frame(height: 1) Text("FILES · \(d.files?.count ?? 0)").font(.ui(size: 11, weight: .semibold)).foregroundStyle(Theme.muted) ForEach(d.files ?? []) { f in @@ -524,3 +591,271 @@ func fileCodeColor(_ code: String) -> Color { default: return Theme.warn } } + +/// Who made a commit: the agent of the branch it is on, with its mark's +/// colour, or the author git has for it. +struct AgentCell: View { + @Environment(\.conchTheme) private var look + let agent: PaneInfo? + let author: String + + var body: some View { + let _ = look + HStack(spacing: 5) { + if let a = agent { + Circle().fill(agentColor(a.agent?.name).map(Theme.color) ?? Theme.muted).frame(width: 7, height: 7) + Text(a.agent?.name.capitalized ?? a.displayName).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1) + } else { + Text(author).font(.ui(size: 11.5)).foregroundStyle(Theme.muted).lineLimit(1) + } + } + .help(agent.map { "\($0.displayName) — \(author)" } ?? author) + } +} + +/// A pull request's checks as small squares on its commit: green passed, +/// red failed, an outline still running. +struct CIMarks: View { + @Environment(\.conchTheme) private var look + let marks: [CIMark] + + var body: some View { + let _ = look + HStack(spacing: 2) { + ForEach(Array(marks.enumerated()), id: \.offset) { _, m in + let tone = m.state == "pass" ? Theme.ok : m.state == "fail" ? Theme.err : Theme.warn + RoundedRectangle(cornerRadius: 2) + .fill(m.state == "pending" ? .clear : tone) + .overlay(RoundedRectangle(cornerRadius: 2).stroke(tone, lineWidth: 1.2)) + .frame(width: 8, height: 8) + .help("\(m.name): \(m.state == "pass" ? "passed" : m.state == "fail" ? "failed" : "running")") + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(marks.map { "\($0.name) \($0.state)" }.joined(separator: ", ")) + } +} + +/// What an agent branch needs, on its newest commit. +struct StateTag: View { + @Environment(\.conchTheme) private var look + let state: GraphBranchState + + var body: some View { + let _ = look + if let (text, tone) = words { + Text(text).font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(tone).lineLimit(1) + .padding(.horizontal, 6).padding(.vertical, 1.5) + .background(Capsule().fill(tone.opacity(0.16))) + .fixedSize() + } + } + + var words: (String, Color)? { + switch state { + case .conflicted(let n): ("✕ conflict · \(n) file\(n == 1 ? "" : "s")", Theme.err) + case .willConflict: ("⚠ will conflict", Theme.warn) + case .ciFailing: ("✕ CI failed", Theme.err) + case .waiting: ("waiting for you", Theme.warn) + default: nil + } + } +} + +/// The agents' branches beside the graph: each with its agent, what it +/// needs, and how far it is from the base. Picking one dims the rest of +/// the graph; picking it again brings it all back. +struct BranchSide: View { + @ObservedObject var model: CommitsModel + @ObservedObject var store: Store + + var body: some View { + let bs = model.branches + VStack(alignment: .leading, spacing: 2) { + HStack { + Text("AGENTS ON BRANCHES").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + Spacer() + Text("\(bs.count)").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + .padding(.horizontal, 10).padding(.top, 12).padding(.bottom, 6) + if bs.isEmpty { + Text("No agent is working on a branch of this project. Start a task and its branch shows here.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.muted).padding(.horizontal, 10) + .fixedSize(horizontal: false, vertical: true) + } + ScrollView { + VStack(spacing: 2) { + ForEach(bs, id: \.name) { b in BranchSideRow(model: model, branch: b) } + } + .padding(.horizontal, 6) + } + Spacer(minLength: 0) + if let base = model.projectInfo?.base { + HStack(spacing: 6) { + Capsule().fill(laneColor(0)).frame(width: 3, height: 12) + Text(base).font(.ui(size: 12)) + Spacer() + Text("base").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + .padding(.horizontal, 12).padding(.vertical, 10) + } + } + .background(Theme.side) + } +} + +struct BranchSideRow: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + @State private var hovering = false + + var body: some View { + let _ = look + let on = model.focusOn == branch.name + let (state, tone) = describe(branch) + HStack(spacing: 8) { + Circle().fill(agentColor(branch.agent?.agent?.name).map(Theme.color) ?? Theme.muted).frame(width: 8, height: 8) + VStack(alignment: .leading, spacing: 1) { + Text(branch.name).font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + HStack(spacing: 4) { + Text(branch.agent.map { $0.agent?.name.capitalized ?? $0.displayName } ?? "no agent").foregroundStyle(Theme.muted) + Text("·").foregroundStyle(Theme.muted) + Text(state).foregroundStyle(tone) + } + .font(.ui(size: 10.5)).lineLimit(1) + } + Spacer(minLength: 4) + Text("↑\(branch.ahead) ↓\(branch.behind)").font(.ui(size: 10.5, design: .monospaced)) + .foregroundStyle(branch.behind > 0 && branch.state.conflicts ? tone : Theme.muted) + } + .padding(.horizontal, 8).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 6).fill(on ? Theme.accentDeep.opacity(0.3) : hovering ? Theme.raise : .clear)) + .contentShape(Rectangle()) + .onHover { hovering = $0 } + .onTapGesture { + model.focusOn = on ? nil : branch.name + // The branch's newest commit, picked and brought into view. + if !on, let tip = branchTips(model.rows.map(\.commit), remotes: model.remotes ?? ["origin", "upstream"])[branch.name] { + model.pick(tip, shift: false) + model.reveal += 1 + } + } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) + .contextMenu { + if branch.state.conflicts { + Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(branch) } + } + Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: branch.name) } + } + } + + func describe(_ b: GraphBranch) -> (String, Color) { + switch b.state { + case .conflicted(let n): ("conflict · \(n) file\(n == 1 ? "" : "s")", Theme.err) + case .waiting: ("waiting for you", Theme.warn) + case .ciFailing: ("CI failed", Theme.err) + case .willConflict: ("will conflict", Theme.warn) + case .working: ("working", Theme.work) + case .done: ("done", Theme.ok) + case .idle: ("idle", Theme.muted) + } + } +} + +/// Above the graph when a branch's rebase or merge stopped on conflicts: +/// what stopped, and the agent to ask — the branch's own, or another one +/// started in its worktree. +struct ConflictBanner: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + if let b = model.branches.first(where: { if case .conflicted = $0.state { return true } else { return false } }) { + let n: Int = { if case .conflicted(let n) = b.state { return n } else { return 0 } }() + HStack(spacing: 10) { + Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Theme.err) + VStack(alignment: .leading, spacing: 1) { + Text("\(b.name) stopped on a conflict with \(model.projectInfo?.base ?? "the base")").font(.ui(size: 12.5, weight: .semibold)) + Text("\(n) file\(n == 1 ? "" : "s") to resolve in its worktree. Nothing has been pushed.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2) + } + Spacer(minLength: 8) + ResolveButton(model: model, branch: b) + Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: b.name) } + .controlSize(.small) + } + .padding(.horizontal, 12).padding(.vertical, 8) + .background(Theme.err.opacity(0.12)) + .overlay(alignment: .bottom) { Rectangle().fill(Theme.err.opacity(0.35)).frame(height: 1) } + } + } +} + +/// Ask the branch's agent to resolve its conflict, or pick another agent +/// to start in its worktree with the same request. +struct ResolveButton: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let startable = model.store.startable(on: model.machine) + let who = branch.agent?.agent?.name.capitalized ?? branch.agent?.displayName + Menu { + if let who { Button("Ask \(who) (on this branch)") { model.askToResolve(branch) } } + Section("Start a new agent in its worktree") { + ForEach(startable, id: \.name) { a in Button(a.title) { model.askToResolve(branch, start: a.name) } } + } + } label: { + Text(who.map { "Ask \($0) to resolve" } ?? "Ask an agent to resolve") + } primaryAction: { + if branch.agent != nil { + model.askToResolve(branch) + } else if let a = startable.first { + model.askToResolve(branch, start: a.name) + } + } + .menuStyle(.borderedButton).fixedSize().controlSize(.small).tint(Theme.accentDeep) + .help("Sends the agent the conflicting files and asks it to resolve them and run the tests. Nothing is pushed.") + } +} + +/// The side panel's word on a branch that conflicts with the base: the +/// files, and an agent to ask. +struct ConflictCard: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let stopped: Bool = { if case .conflicted = branch.state { return true } else { return false } }() + let tone = stopped ? Theme.err : Theme.warn + let base = model.projectInfo?.base ?? "the base" + VStack(alignment: .leading, spacing: 6) { + Text(stopped ? "Stopped on a conflict with \(base)" : "Will conflict with \(base)") + .font(.ui(size: 12.5, weight: .semibold)).foregroundStyle(tone) + Text(stopped ? "The rebase or merge in \(branch.name)'s worktree is waiting for these files to be resolved." + : "\(base) changed the same lines as \(branch.name). Nothing has moved yet: git merge-tree tried it.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).fixedSize(horizontal: false, vertical: true) + ForEach(branch.conflicts.prefix(6), id: \.self) { f in + Text(f).font(.ui(size: 11.5, design: .monospaced)).lineLimit(1).truncationMode(.head) + } + if branch.conflicts.count > 6 { + Text("and \(branch.conflicts.count - 6) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + ResolveButton(model: model, branch: branch) + } + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(tone.opacity(0.10))) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(tone.opacity(0.35))) + } +} diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index d243765c..95de1f17 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -3081,10 +3081,11 @@ final class Store: ObservableObject { /// Starts an agent (or, without one, a terminal) and shows it in a tab /// of its own, as the TUI's c and n do. - func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?) { + func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?, prompt: String? = nil) { guard let c = conns[machine] else { return } struct Create: Encodable { var agent: String? + var prompt: String? var cwd: String? var no_project: Bool? var cols: Int? @@ -3094,7 +3095,7 @@ final class Store: ObservableObject { Task { if let agent, !(await readyAgent(agent, on: machine)) { return } do { - let p = try await c.call("pane.create", Create(agent: agent, cwd: cwd, no_project: inProject ? nil : true, + let p = try await c.call("pane.create", Create(agent: agent, prompt: prompt, cwd: cwd, no_project: inProject ? nil : true, cols: size?.cols, rows: size?.rows), as: PaneInfo.self) snapshots[machine, default: Snapshot()].upsert(p) joinWorkspace(machine: machine, pane: p) @@ -3253,6 +3254,7 @@ final class Store: ObservableObject { var prompt: String var agent: String? var branch: String? + var base: String? } let branch = d.branch.trimmingCharacters(in: .whitespaces) taskDraft = nil @@ -3260,7 +3262,8 @@ final class Store: ObservableObject { if !d.agent.isEmpty, !(await readyAgent(d.agent, on: m)) { return } do { let p = try await c.call("task.create", Params(project_id: pr, prompt: d.prompt, agent: d.agent, - branch: branch.isEmpty ? nil : branch), as: PaneInfo.self) + branch: branch.isEmpty ? nil : branch, + base: d.base.isEmpty ? nil : d.base), as: PaneInfo.self) snapshots[m, default: Snapshot()].upsert(p) joinWorkspace(machine: m, pane: p) layout.open(key(m, p.id)) @@ -3291,6 +3294,44 @@ final class Store: ObservableObject { } } + /// Asks an agent to resolve a branch's conflict with the base: the + /// branch's own agent when it has one running (prompted as if typed), + /// else a new one of `start` in the branch's worktree, given the same + /// words as its first message. + func askToResolve(machine: String, project: String, branch: GraphBranch, start: String? = nil) { + guard let c = conns[machine], let pr = snapshots[machine]?.project(project) else { return } + let stopped: Bool = { if case .conflicted = branch.state { return true } else { return false } }() + let text = resolvePrompt(branch: branch.name, base: pr.base ?? "the base", files: branch.conflicts, stopped: stopped) + if start == nil, let a = branch.agent { + guard c.hello?.capabilities?.contains("agent.prompt.v1") == true else { + error = "The server on \(label(machine)) predates prompting an agent; reload it" + return + } + struct Params: Encodable { var id: String; var text: String } + Task { + do { + try await c.call("agent.prompt", Params(id: a.id, text: text)) + self.say("Asked \(a.displayName) to resolve \(branch.name)") + } catch { self.error = "\(error)" } + } + return + } + guard let path = pr.worktrees?.first(where: { $0.branch == branch.name })?.path else { + error = "\(branch.name) has no worktree to start an agent in" + return + } + newPane(machine: machine, cwd: path, inProject: true, agent: start ?? startable(on: machine).first?.name, prompt: text) + } + + /// Opens the task sheet to hand a commit to an agent: a new branch + /// starting at that commit. + func handCommit(machine: String, project: String, hash: String, subject: String) { + var d = TaskDraft(project: key(machine, project), agent: startable(on: machine).first?.name ?? "claude") + d.base = hash + d.baseLabel = "\(hash.prefix(8)) · \(subject)" + taskDraft = d + } + /// Sends an agent a message, as the TUI's Prompt… does: the server /// types it in and submits it. func promptAgent(_ k: String) { @@ -3499,6 +3540,11 @@ struct TaskDraft: Identifiable { var ticket = "" /// When it starts: "" now, else as `conch task -at` and the rest take it. var when = "" + /// What its branch starts from: "" for the project's base, else a + /// commit or branch — a commit handed to an agent from the graph — + /// and how to name it in the sheet. + var base = "" + var baseLabel = "" } private struct PaneRefParams: Encodable { var id: String } diff --git a/macos/Sources/ConchApp/Views.swift b/macos/Sources/ConchApp/Views.swift index 36d90ba1..b2e16224 100644 --- a/macos/Sources/ConchApp/Views.swift +++ b/macos/Sources/ConchApp/Views.swift @@ -1502,6 +1502,10 @@ struct TaskSheet: View { Text([project?.name ?? "", m == "local" ? "" : store.label(m)].filter { !$0.isEmpty }.joined(separator: " · ") + (project?.git == false ? " — not a git repository yet: Start asks whether to make it one" : " — on a branch and worktree of its own")) .font(.ui(size: 12)).foregroundStyle(.secondary) + if !draft.base.isEmpty { + Text("Starts from \(draft.baseLabel.isEmpty ? String(draft.base.prefix(8)) : draft.baseLabel)") + .font(.ui(size: 12)).foregroundStyle(.secondary).lineLimit(1) + } TextEditor(text: $draft.prompt) .font(.ui(size: 13)).frame(minHeight: 120) .scrollContentBackground(.hidden).padding(6) From 2ab78a249888c3a2202031e5ec497f3e20e7b43f Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:43:39 -0800 Subject: [PATCH 13/35] Docs: the commit graph's agents, conflicts and CI, and project.log's format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Mac app page says what the graph now shows and does (agents on branches, Ask … to resolve, Hand to an Agent…, the git 3 format), the protocol page names project.log's new format field, and end-to-end row 9.175 covers what fakes cannot: real agents resolving, real CI. Co-Authored-By: Claude Opus 5.5 --- docs/testing/end-to-end.md | 1 + web/src/app/docs/mac-app/page.mdx | 8 +++++++- web/src/app/docs/protocol/page.mdx | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 3ad7053a..7ce95e2d 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -414,6 +414,7 @@ What it carries, and what is left over in each row: | 9.172 🌐 | Trackers connected, with real keys | A real Linear key (in the Keychain as conch-mcp LINEAR_API_KEY), a real Jira site with a wrong token, gh signed in; open Settings → Trackers in Conch.app, then run `conch ticket check` in a project. Change the Linear team to one that does not exist, save. Fix the Jira token, press Test again. `gh auth logout`, Test again. | GitHub, Linear: Connected with your name, workspace and real counts (open, yours, teams); the team field offers the teams the key sees; Jira: Couldn't sign in with Atlassian's 401. The bad team: Linear stays Connected with "no team … in Linear" beneath. Jira fixed: Connected. Logged out: GitHub says to run gh auth login. No key appears anywhere on screen or in `-json`. | ☐ | | 9.174 🖥 | The Tickets window with real trackers | Conch.app with two projects with GitHub remotes, Linear set up for one (`[[trackers.projects]]`), a task queued for one issue, an agent working on another's branch, a third with an open PR. ⇧⌘I; try every view in the side, search, and each row's button. | Each project with its issues and tickets, yours marked; the queued, working and PR rows say so (with CI); Needs info counts needs-info and too-big; Task opens New Task in the main window with that issue or ticket picked; Agent focuses the agent; PR and Open open the browser. A project whose tracker fails says why and still lists its issues. An older server says to reload. | ☐ | +| 9.175 💳🌐 | Conch.app's commit graph with agents | A project with Claude and Codex on task branches, one with an open pull request on a real GitHub repository and red CI, one whose change master then touches on the same lines; open **Commit Graph**. Rebase the second onto master by hand so it stops, then **Ask Codex to resolve**, and its menu's *Start a new agent* on another; **Hand to an Agent…** on an older commit; a SHA-256 reftable repository (`git init --object-format=sha256 --ref-format=reftable`) added as a project | Agents on branches lists both in urgency order with the right agent and ↑/↓; commits show their agent; the CI squares match GitHub; *will conflict* shows before anything moves, the banner when the rebase stops; the agent gets the files and resolves without pushing; the new task's branch starts at the commit; the header says **Git 3 · SHA-256 · reftable** | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 667f4b79..188b226d 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,10 +127,16 @@ A web page in a tab beside the agents. ## Commits -The project's history as a graph. +The project's history as a graph, with the agents' branches beside it. **How:** **Commit Graph** on a project's or branch's menu. +- **Agents on branches** lists every branch an agent works on, the most urgent first: stopped on a conflict, waiting for you, CI failed, a conflict coming (git merge-tree tried merging it into the base), working, done. Click one to dim the rest of the graph. +- Each commit says which agent made it. A branch's newest commit carries its state, and a pull request's checks show as small squares on the commit they ran on. +- **Ask … to resolve** — on the banner when a branch stops on a conflict, and in the commit panel when one is coming — sends the branch's agent the conflicting files and asks it to resolve them and run the tests. Its menu starts another agent in the branch's worktree instead. Nothing is pushed. +- **Hand to an Agent…** on a commit opens the task sheet with a new branch starting at that commit. +- The header says how the repository is stored: **Git 3 · SHA-256 · reftable** for one made the way git 3 makes new repositories. + ## Starting agents and tasks A task gives an agent a prompt on a branch of its own. diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index e456ef12..fa19ef75 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -36,7 +36,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Panes | `pane.list`, `pane.create`, `pane.close`, `pane.resize`, `pane.send_text`, `pane.send_keys`, `pane.send_mouse`, `pane.scroll`, `pane.read`, `pane.rename`, `pane.subscribe`, `pane.unsubscribe`, `pane.mark_seen`; `pane.search` finds text in a pane's history (capability `pane.search.v1`); `pane.monitor` watches a pane for output or silence, reported as `monitor` and `alert` in its info (capability `pane.monitor.v1`) | | Agents | `agent.report`, `agent.explain`, `agent.status`, `agent.install`, `agent.setup`, `agent.setup.sync`, `agent.limits`, `agent.broadcast`; `agent.setup.sync` with `user` gives the other agents the setup in your home rather than a checkout's, and `undo` puts it back (capability `agent.setup.sync.user.v1`); `agent.library` and `agent.library.apply` keep MCP servers and skills in conch and write them where each agent looks for them (capability `agent.library.v1`); `agent.prompt` submits one message to an agent and answers with the `turn` that will reply, refusing an agent waiting for an answer with the code `agent_blocked` — `turn` in an agent's status counts its starts of work (capability `agent.prompt.v1`); `agent.skill` installs or removes conch's skill for the agents (capability `agent.skill.v1`); `account.list`, `account.add`, `account.remove`, `account.pin` and `account.failover` keep an agent's other accounts, and `pane.create`, `task.create`, `group.task` and `session.resume` take `account` while panes, plan limits and sessions say theirs (capability `agent.accounts.v1`) | | Scoping | a pane's `created_by` names the pane it was started from, and a change asked from inside an agent's pane to a pane or project that isn't its own comes back with the code `out_of_scope` (capability `pane.scope.v1`); `pane.caller` says which pane a connection comes from and, for an agent, the name it goes by elsewhere, and `scope.act_for` holds a connection to what that agent started on this machine (capability `scope.remote.v1`) | -| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, and the repository's remotes by which a remote's branch is told from a local one; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`) | +| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, the repository's remotes by which a remote's branch is told from a local one, and its `format` — `objects` sha1 or sha256 and `refs` files or reftable — absent from an older server; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`) | | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | From d8ae4999b47fceb86db6adeaa5d48f8bffaa1201 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:47:03 -0800 Subject: [PATCH 14/35] Say which branch a stopped rebase is rewriting A rebase that stops on a conflict detaches the worktree's HEAD, so the worktree named no branch and the commit graph could not show the case that needs the person most: whose conflict it is. WorktreeInfo now carries Rebasing (gitx.RebasingBranch, read only for a detached checkout); the app takes it for the branch's name and finds that branch's agent by the folder it works in, since its pane's branch is blank too while the rebase is stopped. Co-Authored-By: Claude Opus 5.5 --- internal/proto/proto.go | 4 +++ internal/server/log_test.go | 31 +++++++++++++++++++ internal/server/projects.go | 3 ++ macos/Sources/ConchApp/CommitsView.swift | 4 +-- macos/Sources/ConchApp/Store.swift | 3 +- macos/Sources/ConchKit/BranchGraph.swift | 17 ++++++++-- macos/Sources/ConchKit/Protocol.swift | 3 ++ .../ConchKitTests/BranchGraphTests.swift | 7 +++-- 8 files changed, 64 insertions(+), 8 deletions(-) diff --git a/internal/proto/proto.go b/internal/proto/proto.go index 50164341..a0365ce0 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -965,6 +965,10 @@ type WorktreeInfo struct { // servers, and Conflicts where git is older than 2.38. Overlaps []Overlap `json:"overlaps,omitempty"` Conflicts []string `json:"conflicts,omitempty"` + // Rebasing is the branch a rebase left unfinished in this checkout is + // rewriting: git detaches HEAD while it works, so Branch is empty and + // this says whose conflict it is. Absent from older servers. + Rebasing string `json:"rebasing,omitempty"` } // Overlap is another branch's checkout touching the same files. diff --git a/internal/server/log_test.go b/internal/server/log_test.go index 45256206..67212ac3 100644 --- a/internal/server/log_test.go +++ b/internal/server/log_test.go @@ -2,6 +2,7 @@ package server_test import ( "os" + "os/exec" "path/filepath" "slices" "testing" @@ -66,3 +67,33 @@ func TestProjectLogRefusals(t *testing.T) { t.Error("not a repository: no error") } } + +// A rebase that stops on a conflict detaches the worktree's HEAD, so git +// names no branch there; the worktree says which branch the rebase is +// rewriting, or a client could not tell whose conflict it is. +func TestWorktreeRebasingBranch(t *testing.T) { + c, proj, repo, wt, _ := harvestFixture(t) + git(t, wt, "config", "user.name", "t") + git(t, wt, "config", "user.email", "t@example.com") + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-q", "-am", "on feat") + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-q", "-am", "on main") + if out, err := exec.Command("git", "-C", wt, "rebase", "main").CombinedOutput(); err == nil { + t.Fatalf("rebase did not stop: %s", out) + } + call(t, c, proto.MethodProjectRefresh, proto.ProjectRef{ID: proj.ID}, nil) + p := waitProject(t, c, func(p proto.ProjectInfo) bool { + for _, w := range p.Worktrees { + if w.Path == wt && w.Rebasing == "feat" && w.Status != nil && w.Status.Conflicts > 0 { + return true + } + } + return false + }) + for _, w := range p.Worktrees { + if w.Main && w.Rebasing != "" { + t.Errorf("the main checkout is not rebasing: %+v", w) + } + } +} diff --git a/internal/server/projects.go b/internal/server/projects.go index f171fabd..bfb58350 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -895,6 +895,9 @@ func (p *project) load() proto.ProjectInfo { checkedOut := map[string]string{} for _, wt := range wts { wi := proto.WorktreeInfo{Path: wt.Path, Branch: wt.Branch, Head: wt.Head, Detached: wt.Detached, Main: wt.Main} + if wt.Detached { + wi.Rebasing = gitx.RebasingBranch(ctx, wt.Path) + } if st, err := gitx.WorktreeStatus(ctx, wt.Path); err == nil { wi.Status = &proto.GitStatus{ Staged: st.Staged, Unstaged: st.Unstaged, Untracked: st.Untracked, Conflicts: st.Conflicts, diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 7e451d39..924514e1 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -775,7 +775,7 @@ struct ConflictBanner: View { var body: some View { let _ = look - if let b = model.branches.first(where: { if case .conflicted = $0.state { return true } else { return false } }) { + if let b = model.branches.first(where: \.stopped) { let n: Int = { if case .conflicted(let n) = b.state { return n } else { return 0 } }() HStack(spacing: 10) { Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Theme.err) @@ -837,7 +837,7 @@ struct ConflictCard: View { var body: some View { let _ = look - let stopped: Bool = { if case .conflicted = branch.state { return true } else { return false } }() + let stopped = branch.stopped let tone = stopped ? Theme.err : Theme.warn let base = model.projectInfo?.base ?? "the base" VStack(alignment: .leading, spacing: 6) { diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index 95de1f17..a6aa0501 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -3300,8 +3300,7 @@ final class Store: ObservableObject { /// words as its first message. func askToResolve(machine: String, project: String, branch: GraphBranch, start: String? = nil) { guard let c = conns[machine], let pr = snapshots[machine]?.project(project) else { return } - let stopped: Bool = { if case .conflicted = branch.state { return true } else { return false } }() - let text = resolvePrompt(branch: branch.name, base: pr.base ?? "the base", files: branch.conflicts, stopped: stopped) + let text = resolvePrompt(branch: branch.name, base: pr.base ?? "the base", files: branch.conflicts, stopped: branch.stopped) if start == nil, let a = branch.agent { guard c.hello?.capabilities?.contains("agent.prompt.v1") == true else { error = "The server on \(label(machine)) predates prompting an agent; reload it" diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift index c76205cb..9a594e8e 100644 --- a/macos/Sources/ConchKit/BranchGraph.swift +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -98,6 +98,12 @@ public struct GraphBranch: Equatable, Sendable { /// The files merging it into the base would conflict in. public var conflicts: [String] public var pr: PRInfo? + + /// Whether its worktree stopped mid-rebase or merge on a conflict. + public var stopped: Bool { + if case .conflicted = state { return true } + return false + } } /// The project's agent branches — every branch checked out in a worktree @@ -109,10 +115,17 @@ public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo]) -> [GraphBr let info = Dictionary((project.branches ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) var out: [GraphBranch] = [] for w in project.worktrees ?? [] where w.main != true { - guard let name = w.branch, !name.isEmpty, name != base, !mainBranches.contains(name), + // Mid-rebase git names no branch; the server says which it rewrites. + guard let name = w.branch ?? w.rebasing, !name.isEmpty, name != base, !mainBranches.contains(name), !out.contains(where: { $0.name == name }) else { continue } let b = info[name] - let agent = branchAgent(branchAgents(panes, project: project.id, branch: name), handedTo: nil) + // An agent whose branch is blank (its HEAD detached mid-rebase) is + // found by the folder it works in. + let inFolder = panes.filter { p in + p.agent != nil && p.running && p.projectID == project.id && (p.branch ?? "").isEmpty + && (p.cwd == w.path || (p.cwd ?? "").hasPrefix(w.path + "/")) + } + let agent = branchAgent(branchAgents(panes, project: project.id, branch: name) + inFolder, handedTo: nil) let pr = b?.pr.flatMap { ($0.state ?? "OPEN") == "OPEN" ? $0 : nil } let state: GraphBranchState if let n = w.status?.conflicts, n > 0 { diff --git a/macos/Sources/ConchKit/Protocol.swift b/macos/Sources/ConchKit/Protocol.swift index 11f026b9..1d8bf448 100644 --- a/macos/Sources/ConchKit/Protocol.swift +++ b/macos/Sources/ConchKit/Protocol.swift @@ -197,6 +197,9 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { /// The files merging the branch into the base would conflict in, /// tried without merging (git 2.38 and later). public var conflicts: [String]? + /// The branch a rebase left unfinished here is rewriting: git detaches + /// HEAD meanwhile, so branch is nil. nil from an older server. + public var rebasing: String? public init(path: String, branch: String?, main: Bool? = nil, port: Int? = nil) { self.path = path diff --git a/macos/Tests/ConchKitTests/BranchGraphTests.swift b/macos/Tests/ConchKitTests/BranchGraphTests.swift index 6e6fb845..781f471e 100644 --- a/macos/Tests/ConchKitTests/BranchGraphTests.swift +++ b/macos/Tests/ConchKitTests/BranchGraphTests.swift @@ -68,7 +68,7 @@ func history() -> [LogCommit] { let json = #""" {"id":"r1","name":"conch","path":"/p","base":"master", "worktrees":[{"path":"/p","branch":"master","main":true}, - {"path":"/w/a","branch":"stopped","status":{"files":2,"conflicts":2}}, + {"path":"/w/a","rebasing":"stopped","status":{"files":2,"conflicts":2}}, {"path":"/w/b","branch":"red"}, {"path":"/w/c","branch":"forecast","conflicts":["a.go","b.go"]}, {"path":"/w/d","branch":"asking"}, @@ -80,7 +80,7 @@ func history() -> [LogCommit] { """# let project = try conchDecoder().decode(ProjectInfo.self, from: Data(json.utf8)) let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" - [{"id":"p1","name":"a","state":"running","project_id":"r1","branch":"stopped","agent":{"name":"codex","state":"working"}}, + [{"id":"p1","name":"a","state":"running","project_id":"r1","cwd":"/w/a/sub","agent":{"name":"codex","state":"working"}}, {"id":"p2","name":"d","state":"running","project_id":"r1","branch":"asking","agent":{"name":"claude","state":"blocked"}}, {"id":"p3","name":"e","state":"running","project_id":"r1","branch":"busy","agent":{"name":"gemini","state":"working"}}, {"id":"p4","name":"other","state":"running","project_id":"r2","branch":"quiet","agent":{"name":"claude","state":"working"}}] @@ -88,8 +88,11 @@ func history() -> [LogCommit] { let bs = graphBranches(project, panes: panes) #expect(bs.map(\.name) == ["stopped", "asking", "red", "forecast", "busy", "quiet"]) let by = Dictionary(uniqueKeysWithValues: bs.map { ($0.name, $0) }) + // Mid-rebase git names no branch: the worktree says which it is + // rewriting, and its agent is found by the folder it works in. #expect(by["stopped"]?.state == .conflicted(2)) #expect(by["stopped"]?.agent?.id == "p1") + #expect(by["stopped"]?.stopped == true && by["red"]?.stopped == false) #expect(by["red"]?.state == .ciFailing && by["red"]?.ahead == 2 && by["red"]?.behind == 1) #expect(by["forecast"]?.state == .willConflict && by["forecast"]?.conflicts == ["a.go", "b.go"]) #expect(by["asking"]?.state == .waiting) From 2bc868f9e8ec74e2b3bcf7076d9bc89332f217a3 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:49:59 -0800 Subject: [PATCH 15/35] Name the files a stopped rebase or merge is waiting on A worktree stopped mid-rebase had no Conflicts, since merge-tree is only tried for a branch git names, so asking an agent to resolve it said 'the conflicting files' instead of which. A checkout with unmerged files now lists them as its Conflicts (gitx.ConflictFiles), which is also what the TUI's queue says of it: conflicts with the base in those files. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/harvest.go | 4 ++++ internal/proto/proto.go | 3 ++- internal/server/log_test.go | 3 ++- internal/server/overlap.go | 6 ++++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/internal/gitx/harvest.go b/internal/gitx/harvest.go index adda7fdb..b0d72e77 100644 --- a/internal/gitx/harvest.go +++ b/internal/gitx/harvest.go @@ -430,6 +430,10 @@ func undoMerge(dir string, squash bool) { _, _ = run(ctx, dir, "reset", "--quiet", "--merge") } +// ConflictFiles are the files a merge or rebase stopped on in the +// checkout at dir: those git lists as unmerged. +func ConflictFiles(ctx context.Context, dir string) []string { return conflictFiles(ctx, dir) } + func conflictFiles(ctx context.Context, dir string) []string { out, err := run(ctx, dir, "diff", "--name-only", "--diff-filter=U", "-z") if err != nil { diff --git a/internal/proto/proto.go b/internal/proto/proto.go index a0365ce0..b53e48bb 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -961,7 +961,8 @@ type WorktreeInfo struct { // Overlaps are the other checkouts of the project that have touched // files this one has too: two agents heading for the same merge // conflict. Conflicts are the files merging this branch into the base - // would conflict in, tried without merging. Both are absent from older + // would conflict in, tried without merging — or, in a checkout stopped + // mid-rebase or merge, the files it stopped on. Both are absent from older // servers, and Conflicts where git is older than 2.38. Overlaps []Overlap `json:"overlaps,omitempty"` Conflicts []string `json:"conflicts,omitempty"` diff --git a/internal/server/log_test.go b/internal/server/log_test.go index 67212ac3..5ab3e7b8 100644 --- a/internal/server/log_test.go +++ b/internal/server/log_test.go @@ -85,7 +85,8 @@ func TestWorktreeRebasingBranch(t *testing.T) { call(t, c, proto.MethodProjectRefresh, proto.ProjectRef{ID: proj.ID}, nil) p := waitProject(t, c, func(p proto.ProjectInfo) bool { for _, w := range p.Worktrees { - if w.Path == wt && w.Rebasing == "feat" && w.Status != nil && w.Status.Conflicts > 0 { + // Its conflicts are the files the rebase stopped on. + if w.Path == wt && w.Rebasing == "feat" && w.Status != nil && w.Status.Conflicts > 0 && slices.Equal(w.Conflicts, []string{"a.txt"}) { return true } } diff --git a/internal/server/overlap.go b/internal/server/overlap.go index 4b113f3e..cdcbedda 100644 --- a/internal/server/overlap.go +++ b/internal/server/overlap.go @@ -22,6 +22,12 @@ const maxOverlapFiles = 5 func noteOverlaps(ctx context.Context, root string, info *proto.ProjectInfo) { touched := map[int][]string{} for i, wt := range info.Worktrees { + // A checkout stopped mid-rebase or merge: its conflicts are the + // files it stopped on, not a merge still to be tried. + if wt.Status != nil && wt.Status.Conflicts > 0 { + info.Worktrees[i].Conflicts = gitx.ConflictFiles(ctx, wt.Path) + continue + } if wt.Main || wt.Branch == "" { continue } From 68512068b2351dbca5d538463981a27a69c4bd24 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 16:55:40 -0800 Subject: [PATCH 16/35] Commit graph: fit narrow windows, reachable by accessibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run live against a scratch server, the graph tab with the branch list and a commit's panel open was wider than a 1320-point window: the tree and the panel were cut off, the header's title crushed to 'C…' and a selected row's chips pushed its hash and subject out. The panels now give way (the branch list can be hidden from the header), a row's chips and subject share what is left and are clipped, and the compare hint shows only while no commit is picked. Commit rows and the branch list answered only a mouse tap, so VoiceOver could not select a commit; both now have an accessibility action. A server test pins that a branch can start at a commit, as Hand to an Agent asks. Co-Authored-By: Claude Opus 5.5 --- internal/server/log_test.go | 24 ++++++++ macos/Sources/ConchApp/CommitsView.swift | 70 ++++++++++++++++-------- macos/Sources/ConchKit/LucideIcons.swift | 1 + 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/internal/server/log_test.go b/internal/server/log_test.go index 5ab3e7b8..6e2b3bb0 100644 --- a/internal/server/log_test.go +++ b/internal/server/log_test.go @@ -5,6 +5,7 @@ import ( "os/exec" "path/filepath" "slices" + "strings" "testing" "github.com/Amitgb14/conch/internal/proto" @@ -98,3 +99,26 @@ func TestWorktreeRebasingBranch(t *testing.T) { } } } + +// A commit handed to an agent from the graph: the new branch starts at +// that commit, not at the base's newest. +func TestWorktreeFromCommit(t *testing.T) { + c, proj, repo, _, _ := harvestFixture(t) + head := func(dir string) string { + out, err := exec.Command("git", "-C", dir, "rev-parse", "HEAD").Output() + if err != nil { + t.Fatal(err) + } + return strings.TrimSpace(string(out)) + } + first := head(repo) + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("later\n"), 0o644) + git(t, repo, "commit", "-q", "-am", "later") + var res proto.WorktreeResult + if err := call(t, c, proto.MethodWorktreeAdd, proto.WorktreeAddParams{ProjectID: proj.ID, Branch: "from-old", Base: first}, &res); err != nil { + t.Fatal(err) + } + if got := head(res.Path); got != first { + t.Errorf("the branch starts at %s, want %s", got, first) + } +} diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 924514e1..d63aa05c 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -232,15 +232,19 @@ struct CommitsView: View { @ObservedObject var store: Store /// Inside a branch's git tab: no frame of its own, which the tab has. var embedded = false + /// The agents' branches beside the graph, which a narrow window can do without. + @AppStorage("commits.branches") private var showBranches = true var body: some View { HStack(spacing: 0) { - BranchSide(model: model, store: store).frame(width: 232) - Rectangle().fill(Theme.line).frame(width: 1) - graph + if showBranches { + BranchSide(model: model, store: store).frame(minWidth: 180, idealWidth: 228, maxWidth: 228) + Rectangle().fill(Theme.line).frame(width: 1) + } + graph.frame(minWidth: 320) if model.selected != nil { Rectangle().fill(Theme.line).frame(width: 1) - CommitDetailPanel(model: model, store: store).frame(width: 340) + CommitDetailPanel(model: model, store: store).frame(minWidth: 260, idealWidth: 340, maxWidth: 340) } } .background(Theme.window) @@ -297,28 +301,39 @@ struct CommitsView: View { var header: some View { let name = store.snapshots[model.machine]?.project(model.project)?.name ?? model.project return HStack(spacing: 10) { + Button { showBranches.toggle() } label: { + LucideIcon("panel-left", color: showBranches ? Theme.accent : Theme.muted, size: 13).padding(3).contentShape(Rectangle()) + } + .buttonStyle(.plain).help(showBranches ? "Hide the agents' branches" : "Show the agents' branches") + .accessibilityLabel(showBranches ? "Hide the agents' branches" : "Show the agents' branches") LucideIcon("git-commit-horizontal", color: Theme.accent, size: 14) - Text("Commits").font(.ui(size: 13, weight: .semibold)) - Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2) - Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted) + Text("Commits").font(.ui(size: 13, weight: .semibold)).fixedSize() + Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2).lineLimit(1).layoutPriority(-1) + Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted).fixedSize() if let f = model.format, !f.label.isEmpty { Text(f.git3 ? "Git 3 · \(f.label)" : f.label) .font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(f.git3 ? Theme.accent : Theme.muted) .padding(.horizontal, 7).padding(.vertical, 2) .background(Capsule().fill((f.git3 ? Theme.accent : Theme.muted).opacity(0.14))) + .lineLimit(1) .help(f.git3 ? "This repository is stored the way git 3 makes new ones: SHA-256 object names and reftable refs" : "Object names and refs storage") } if model.loading { ProgressView().controlSize(.small) } - Spacer() + Spacer(minLength: 8) HStack(spacing: 6) { LucideIcon("search", color: Theme.muted, size: 11) - TextField("Search commits, hashes, authors", text: $model.query).textFieldStyle(.plain).font(.ui(size: 12)).frame(width: 220) + TextField("Search commits, hashes, authors", text: $model.query).textFieldStyle(.plain).font(.ui(size: 12)) + .frame(minWidth: 60, maxWidth: 220) } .padding(.horizontal, 8).frame(height: 24) .background(RoundedRectangle(cornerRadius: 6).fill(Theme.window)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(Theme.line)) - Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted) - Button { model.refresh() } label: { LucideIcon("refresh-cw", size: 12).padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).help("Read the history again, and its pull requests from GitHub") + // Said until a commit is picked: with its panel open the graph + // is narrow, and the search and refresh need the room. + if model.selected == nil { + Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1).layoutPriority(-2) + } + Button { model.refresh() } label: { LucideIcon("refresh-cw", size: 12).padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).fixedSize().help("Read the history again, and its pull requests from GitHub") } .padding(.horizontal, 12).frame(height: 40) .background(Theme.paneHeader) @@ -355,7 +370,10 @@ struct CommitRow: View { || (model.focusOn != nil && model.owners[c.hash] != model.focusOn) HStack(spacing: 8) { GraphCell(row: row).frame(width: CGFloat(model.lanes) * Self.laneWidth + 6, height: Self.height).clipped() - Text(c.short).font(.ui(size: 11.5, design: .monospaced)).foregroundStyle(Theme.muted) + Text(c.short).font(.ui(size: 11.5, design: .monospaced)).foregroundStyle(Theme.muted).fixedSize() + // Chips and the subject share what is left, clipped rather than + // pushing the hash and the agent out of the row. + HStack(spacing: 8) { ForEach(Array(refs.enumerated()), id: \.offset) { _, r in RefChip(ref: r) } // The commit a pull request's checks run on: its CI, here too. if let pr = model.pullRequests[c.hash] { @@ -365,8 +383,9 @@ struct CommitRow: View { if tip, let o = owner { StateTag(state: o.state) } Text(c.subject).font(.ui(size: 12.5)).foregroundStyle(Theme.text).lineLimit(1).truncationMode(.tail) .layoutPriority(-1) - Spacer(minLength: 8) - AgentCell(agent: owner?.agent, author: c.author ?? "").frame(width: 120, alignment: .leading) + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading).clipped() + AgentCell(agent: owner?.agent, author: c.author ?? "").frame(width: 96, alignment: .leading) Text(agoText(c.time)).font(.ui(size: 11.5)).foregroundStyle(Theme.muted).frame(minWidth: 52, alignment: .trailing) } .padding(.horizontal, 10).frame(height: Self.height) @@ -375,6 +394,9 @@ struct CommitRow: View { .contentShape(Rectangle()) .onHover { hovering = $0 } .onTapGesture { model.pick(c.hash, shift: NSEvent.modifierFlags.contains(.shift)) } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) + .accessibilityAction { model.pick(c.hash, shift: false) } .help(c.hash) .contextMenu { Button("Copy Hash") { copy(c.hash) } @@ -734,16 +756,10 @@ struct BranchSideRow: View { .background(RoundedRectangle(cornerRadius: 6).fill(on ? Theme.accentDeep.opacity(0.3) : hovering ? Theme.raise : .clear)) .contentShape(Rectangle()) .onHover { hovering = $0 } - .onTapGesture { - model.focusOn = on ? nil : branch.name - // The branch's newest commit, picked and brought into view. - if !on, let tip = branchTips(model.rows.map(\.commit), remotes: model.remotes ?? ["origin", "upstream"])[branch.name] { - model.pick(tip, shift: false) - model.reveal += 1 - } - } + .onTapGesture { toggle(on) } .accessibilityElement(children: .combine) .accessibilityAddTraits(.isButton) + .accessibilityAction { toggle(on) } .contextMenu { if branch.state.conflicts { Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(branch) } @@ -752,6 +768,16 @@ struct BranchSideRow: View { } } + /// Focuses the branch, or lets go of it. + func toggle(_ on: Bool) { + model.focusOn = on ? nil : branch.name + // The branch's newest commit, picked and brought into view. + if !on, let tip = branchTips(model.rows.map(\.commit), remotes: model.remotes ?? ["origin", "upstream"])[branch.name] { + model.pick(tip, shift: false) + model.reveal += 1 + } + } + func describe(_ b: GraphBranch) -> (String, Color) { switch b.state { case .conflicted(let n): ("conflict · \(n) file\(n == 1 ? "" : "s")", Theme.err) diff --git a/macos/Sources/ConchKit/LucideIcons.swift b/macos/Sources/ConchKit/LucideIcons.swift index 2bbc6327..e0df05df 100644 --- a/macos/Sources/ConchKit/LucideIcons.swift +++ b/macos/Sources/ConchKit/LucideIcons.swift @@ -64,6 +64,7 @@ public enum LucideIcons { "pencil": ["M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z", "m15 5 4 4"], "trash-2": ["M3 6h18", "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6", "M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2", "M10 11v6", "M14 11v6"], "git-commit-horizontal": [svgCircle(12, 12, 3), svgLine(3, 12, 9, 12), svgLine(15, 12, 21, 12)], + "panel-left": [svgRect(3, 3, 18, 18, 2), svgLine(9, 3, 9, 21)], "tag": ["M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z", svgCircle(7.5, 7.5, 0.5)], "moon": ["M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"], "sun": [svgCircle(12, 12, 4), "M12 2v2", "M12 20v2", "m4.93 4.93 1.41 1.41", "m17.66 17.66 1.41 1.41", "M2 12h2", "M20 12h2", "m6.34 17.66-1.41 1.41", "m19.07 4.93-1.41 1.41"], From 732ddfd3c989920c5d4ff4a73a96adf271b306ce Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:00:54 -0800 Subject: [PATCH 17/35] Docs: keep the Mac app guide under its 700 words The commit graph's new section took the page to 880 words of prose, past the limit TestDocsGuidesAreShort holds every guide to. It now says what the graph shows in one line; the buttons explain themselves. Co-Authored-By: Claude Opus 5.5 --- web/src/app/docs/mac-app/page.mdx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 188b226d..7c1805c2 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,16 +127,10 @@ A web page in a tab beside the agents. ## Commits -The project's history as a graph, with the agents' branches beside it. +The project's history, its agents' branches and their conflicts. **How:** **Commit Graph** on a project's or branch's menu. -- **Agents on branches** lists every branch an agent works on, the most urgent first: stopped on a conflict, waiting for you, CI failed, a conflict coming (git merge-tree tried merging it into the base), working, done. Click one to dim the rest of the graph. -- Each commit says which agent made it. A branch's newest commit carries its state, and a pull request's checks show as small squares on the commit they ran on. -- **Ask … to resolve** — on the banner when a branch stops on a conflict, and in the commit panel when one is coming — sends the branch's agent the conflicting files and asks it to resolve them and run the tests. Its menu starts another agent in the branch's worktree instead. Nothing is pushed. -- **Hand to an Agent…** on a commit opens the task sheet with a new branch starting at that commit. -- The header says how the repository is stored: **Git 3 · SHA-256 · reftable** for one made the way git 3 makes new repositories. - ## Starting agents and tasks A task gives an agent a prompt on a branch of its own. From 6ad5952208bd704d5c32aa416a95c4460157198b Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:12:05 -0800 Subject: [PATCH 18/35] ghx: GitHub Actions history and CI statistics, re-run failed jobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For the commit graph's CI panel: Runs lists a repository's workflow runs and RunJobs a run's jobs through gh; ComputeStats works out a period of whole days — pass rate and the period before, median run and queue time, how long a branch stayed red, runs per day, each job's median and slowest tenth, flaky jobs (failed and passed on one commit, or a run that passed on a later attempt) and the failures that can be run again. Rerun asks gh to run a run's failed jobs again; FailedRunID finds a branch's newest failed run, which FailedLog now shares. Co-Authored-By: Claude Opus 5.5 --- internal/ghx/actions.go | 382 +++++++++++++++++++++++++++++++++++ internal/ghx/cistats_test.go | 213 +++++++++++++++++++ internal/ghx/runs.go | 32 ++- 3 files changed, 619 insertions(+), 8 deletions(-) create mode 100644 internal/ghx/actions.go create mode 100644 internal/ghx/cistats_test.go diff --git a/internal/ghx/actions.go b/internal/ghx/actions.go new file mode 100644 index 00000000..6e484a1e --- /dev/null +++ b/internal/ghx/actions.go @@ -0,0 +1,382 @@ +package ghx + +import ( + "context" + "encoding/json" + "fmt" + "math" + "sort" + "strconv" + "time" +) + +// A repository's GitHub Actions history, read through gh, and what conch +// says about it: how often it passes, how long it takes, which jobs are +// slow or flaky, and which failures can be run again. + +// Run is one workflow run, at its latest attempt. +type Run struct { + ID int64 + Workflow string + Branch string + Sha string + Event string + Status string // queued, in_progress, completed + Conclusion string // success, failure, cancelled, timed_out, skipped… once completed + Attempt int + URL string + Created time.Time + Started time.Time + Updated time.Time +} + +// Job is one job of a run. +type Job struct { + Name string + Conclusion string + Started time.Time + Completed time.Time +} + +// Runs lists the repository's newest workflow runs, up to limit. +func Runs(ctx context.Context, dir string, limit int) ([]Run, error) { + out, err := run(ctx, dir, "run", "list", "--limit", strconv.Itoa(limit), "--json", + "databaseId,workflowName,headBranch,headSha,event,status,conclusion,attempt,url,createdAt,startedAt,updatedAt") + if err != nil { + return nil, err + } + var raw []struct { + ID int64 `json:"databaseId"` + Workflow string `json:"workflowName"` + Branch string `json:"headBranch"` + Sha string `json:"headSha"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + Attempt int `json:"attempt"` + URL string `json:"url"` + Created time.Time `json:"createdAt"` + Started time.Time `json:"startedAt"` + Updated time.Time `json:"updatedAt"` + } + if err := json.Unmarshal(out, &raw); err != nil { + return nil, fmt.Errorf("gh run list: %w", err) + } + runs := make([]Run, 0, len(raw)) + for _, r := range raw { + runs = append(runs, Run{ID: r.ID, Workflow: r.Workflow, Branch: r.Branch, Sha: r.Sha, Event: r.Event, Status: r.Status, + Conclusion: r.Conclusion, Attempt: r.Attempt, URL: r.URL, Created: r.Created, Started: r.Started, Updated: r.Updated}) + } + return runs, nil +} + +// RunJobs lists a run's jobs. A finished run's jobs never change, so a +// caller may keep them. +func RunJobs(ctx context.Context, dir string, id int64) ([]Job, error) { + out, err := run(ctx, dir, "run", "view", strconv.FormatInt(id, 10), "--json", "jobs") + if err != nil { + return nil, err + } + var raw struct { + Jobs []struct { + Name string `json:"name"` + Conclusion string `json:"conclusion"` + Started time.Time `json:"startedAt"` + Completed time.Time `json:"completedAt"` + } `json:"jobs"` + } + if err := json.Unmarshal(out, &raw); err != nil { + return nil, fmt.Errorf("gh run view: %w", err) + } + jobs := make([]Job, 0, len(raw.Jobs)) + for _, j := range raw.Jobs { + jobs = append(jobs, Job{Name: j.Name, Conclusion: j.Conclusion, Started: j.Started, Completed: j.Completed}) + } + return jobs, nil +} + +// Rerun runs a run's failed jobs again, as a new attempt of the same run. +func Rerun(ctx context.Context, dir string, id int64) error { + _, err := run(ctx, dir, "run", "rerun", strconv.FormatInt(id, 10), "--failed") + return err +} + +// FailedRunID is the newest failed Actions run on branch — at commit head +// when given — for a re-run asked for by branch rather than by run. +func FailedRunID(ctx context.Context, dir, branch, head string) (int64, error) { + runs, err := failedRuns(ctx, dir, branch, head) + if err != nil { + return 0, err + } + return runs[0].ID, nil +} + +// failed says whether a finished run's conclusion is a failure: a timeout +// is one, a cancellation is somebody's choice. +func failed(conclusion string) bool { return conclusion == "failure" || conclusion == "timed_out" } + +// CIStats is what the CI panel shows for a period of whole days. +type CIStats struct { + Days int + // Finished runs that passed or failed in the period (a cancelled or + // skipped run is neither), and the same for the period before it. + Runs, Passed, Failed int + PrevRuns, PrevPassed int + // Medians, in seconds, of a run's time from start to finish and of + // its wait in the queue; the run time also for the period before. + MedianSeconds, PrevMedianSeconds, QueueSeconds int + // How long a branch stayed red: from a failed run to the next passing + // run of the same workflow on the same branch, median, and how many. + RedToGreenSeconds, RedToGreenCount int + // One entry a day, the oldest first and today last. + Daily []CIDay + // Each job, the slowest (by median) first. + Jobs []CIJob + // Jobs and runs that failed and then passed without a change. + Flaky []CIFlaky + // The newest run of each workflow on each branch, where it failed: + // what can be run again. + Failing []Run + // How many of the period's runs had their jobs read. + JobsRead int +} + +// CIDay is one day's finished runs. +type CIDay struct { + Date string // YYYY-MM-DD in the server's time zone + Passed, Failed int +} + +// CIJob is one job's record over the period. +type CIJob struct { + Name string + Runs, Failed int + MedianSeconds, P90Seconds int +} + +// CIFlaky is a job (or a whole run) that failed and passed with nothing +// changed: on the same commit, or on a second attempt of the same run. +type CIFlaky struct { + Name string + Times int + How string + Last time.Time +} + +// ComputeStats works out a period's statistics: the days days up to and +// including now's (in loc), and the same number before them. jobs holds +// the jobs of whichever runs have been read. +func ComputeStats(runs []Run, jobs map[int64][]Job, now time.Time, days int, loc *time.Location) CIStats { + if days < 1 { + days = 1 + } + y, m, d := now.In(loc).Date() + start := time.Date(y, m, d, 0, 0, 0, 0, loc).AddDate(0, 0, -(days - 1)) + prevStart := start.AddDate(0, 0, -days) + s := CIStats{Days: days} + day := map[string]int{} + for i := range days { + date := start.AddDate(0, 0, i).Format("2006-01-02") + day[date] = i + s.Daily = append(s.Daily, CIDay{Date: date}) + } + var durations, prevDurations, queues []int + type jobAcc struct { + runs, failed int + secs []int + } + jobAccs := map[string]*jobAcc{} + var inPeriod []Run + for _, r := range runs { + finished := r.Status == "completed" && (r.Conclusion == "success" || failed(r.Conclusion)) + switch { + case !finished: + continue + case !r.Created.Before(start): + inPeriod = append(inPeriod, r) + s.Runs++ + i := day[r.Created.In(loc).Format("2006-01-02")] + if r.Conclusion == "success" { + s.Passed++ + s.Daily[i].Passed++ + } else { + s.Failed++ + s.Daily[i].Failed++ + } + if !r.Started.IsZero() && r.Updated.After(r.Started) { + durations = append(durations, int(r.Updated.Sub(r.Started).Seconds())) + } + if !r.Started.IsZero() && !r.Started.Before(r.Created) { + queues = append(queues, int(r.Started.Sub(r.Created).Seconds())) + } + if js, ok := jobs[r.ID]; ok { + s.JobsRead++ + for _, j := range js { + a := jobAccs[j.Name] + if a == nil { + a = &jobAcc{} + jobAccs[j.Name] = a + } + a.runs++ + if failed(j.Conclusion) { + a.failed++ + } + if !j.Started.IsZero() && j.Completed.After(j.Started) { + a.secs = append(a.secs, int(j.Completed.Sub(j.Started).Seconds())) + } + } + } + case !r.Created.Before(prevStart): + s.PrevRuns++ + if r.Conclusion == "success" { + s.PrevPassed++ + } + if !r.Started.IsZero() && r.Updated.After(r.Started) { + prevDurations = append(prevDurations, int(r.Updated.Sub(r.Started).Seconds())) + } + } + } + s.MedianSeconds = percentile(durations, 0.5) + s.PrevMedianSeconds = percentile(prevDurations, 0.5) + s.QueueSeconds = percentile(queues, 0.5) + for name, a := range jobAccs { + s.Jobs = append(s.Jobs, CIJob{Name: name, Runs: a.runs, Failed: a.failed, MedianSeconds: percentile(a.secs, 0.5), P90Seconds: percentile(a.secs, 0.9)}) + } + sort.Slice(s.Jobs, func(i, j int) bool { + if s.Jobs[i].MedianSeconds != s.Jobs[j].MedianSeconds { + return s.Jobs[i].MedianSeconds > s.Jobs[j].MedianSeconds + } + return s.Jobs[i].Name < s.Jobs[j].Name + }) + + // Oldest first from here: red to green, and flakiness, follow time. + sort.Slice(inPeriod, func(i, j int) bool { + if !inPeriod[i].Created.Equal(inPeriod[j].Created) { + return inPeriod[i].Created.Before(inPeriod[j].Created) + } + return inPeriod[i].ID < inPeriod[j].ID + }) + redSince := map[string]time.Time{} + var greens []int + for _, r := range inPeriod { + k := r.Workflow + "\x00" + r.Branch + if failed(r.Conclusion) { + if _, ok := redSince[k]; !ok { + redSince[k] = r.Updated + } + } else if t, ok := redSince[k]; ok { + greens = append(greens, int(r.Updated.Sub(t).Seconds())) + delete(redSince, k) + } + } + s.RedToGreenSeconds, s.RedToGreenCount = percentile(greens, 0.5), len(greens) + + // A job that failed and passed on one commit in one workflow. + type seen struct{ failed, passed bool } + bySha := map[string]map[string]*seen{} + last := map[string]time.Time{} + for _, r := range inPeriod { + k := r.Workflow + "\x00" + r.Sha + if bySha[k] == nil { + bySha[k] = map[string]*seen{} + } + for _, j := range jobs[r.ID] { + sn := bySha[k][j.Name] + if sn == nil { + sn = &seen{} + bySha[k][j.Name] = sn + } + if failed(j.Conclusion) { + sn.failed = true + } else if j.Conclusion == "success" { + sn.passed = true + } + if sn.failed && sn.passed && r.Updated.After(last[k+"\x00"+j.Name]) { + last[k+"\x00"+j.Name] = r.Updated + } + } + } + flaky := map[string]*CIFlaky{} + for k, names := range bySha { + for name, sn := range names { + if !sn.failed || !sn.passed { + continue + } + f := flaky[name] + if f == nil { + f = &CIFlaky{Name: name, How: "failed and passed on the same commit"} + flaky[name] = f + } + f.Times++ + if t := last[k+"\x00"+name]; t.After(f.Last) { + f.Last = t + } + } + } + for _, f := range flaky { + s.Flaky = append(s.Flaky, *f) + } + sort.Slice(s.Flaky, func(i, j int) bool { + if s.Flaky[i].Times != s.Flaky[j].Times { + return s.Flaky[i].Times > s.Flaky[j].Times + } + return s.Flaky[i].Name < s.Flaky[j].Name + }) + // A run that passed only on a later attempt: which job failed first is + // not in the run's latest attempt, so the run itself is named. + retried := map[string]*CIFlaky{} + var retriedNames []string + for _, r := range inPeriod { + if r.Attempt > 1 && r.Conclusion == "success" { + f := retried[r.Workflow] + if f == nil { + f = &CIFlaky{Name: r.Workflow} + retried[r.Workflow] = f + retriedNames = append(retriedNames, r.Workflow) + } + f.Times++ + f.How = fmt.Sprintf("passed on attempt %d", r.Attempt) + f.Last = r.Updated + } + } + sort.Strings(retriedNames) + for _, n := range retriedNames { + s.Flaky = append(s.Flaky, *retried[n]) + } + + // What can be run again: each workflow's newest run on each branch, + // where it failed. Newest first. + newest := map[string]Run{} + for _, r := range runs { + if r.Status != "completed" { + continue + } + k := r.Workflow + "\x00" + r.Branch + if o, ok := newest[k]; !ok || r.Created.After(o.Created) || (r.Created.Equal(o.Created) && r.ID > o.ID) { + newest[k] = r + } + } + for _, r := range newest { + if failed(r.Conclusion) { + s.Failing = append(s.Failing, r) + } + } + sort.Slice(s.Failing, func(i, j int) bool { + if !s.Failing[i].Created.Equal(s.Failing[j].Created) { + return s.Failing[i].Created.After(s.Failing[j].Created) + } + return s.Failing[i].ID > s.Failing[j].ID + }) + return s +} + +// percentile is the nearest-rank percentile of xs (p in 0..1), 0 for none. +func percentile(xs []int, p float64) int { + if len(xs) == 0 { + return 0 + } + s := append([]int(nil), xs...) + sort.Ints(s) + i := int(math.Ceil(p*float64(len(s)))) - 1 + return s[max(0, min(i, len(s)-1))] +} diff --git a/internal/ghx/cistats_test.go b/internal/ghx/cistats_test.go new file mode 100644 index 00000000..b0225c4b --- /dev/null +++ b/internal/ghx/cistats_test.go @@ -0,0 +1,213 @@ +package ghx + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +var statsNow = time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + +// run is a finished run that started at the given hours before statsNow, +// queued q seconds and took d seconds. +func ciRun(id int64, wf, branch, sha, conclusion string, hoursAgo float64, q, d int) Run { + created := statsNow.Add(-time.Duration(hoursAgo * float64(time.Hour))) + started := created.Add(time.Duration(q) * time.Second) + return Run{ID: id, Workflow: wf, Branch: branch, Sha: sha, Conclusion: conclusion, Status: "completed", Attempt: 1, + Created: created, Started: started, Updated: started.Add(time.Duration(d) * time.Second)} +} + +func job(name, conclusion string, secs int) Job { + start := statsNow.Add(-48 * time.Hour) + return Job{Name: name, Conclusion: conclusion, Started: start, Completed: start.Add(time.Duration(secs) * time.Second)} +} + +func TestStatsCounts(t *testing.T) { + runs := []Run{ + ciRun(6, "ci", "feat", "s3", "success", 2, 10, 300), + ciRun(5, "ci", "feat", "s2", "failure", 5, 20, 600), + ciRun(4, "ci", "main", "m1", "success", 30, 30, 400), + ciRun(3, "ci", "feat", "s1", "cancelled", 40, 5, 50), + // The prior period: older than the 7 days asked for. + ciRun(2, "ci", "main", "m0", "failure", 24*9, 10, 100), + ciRun(1, "ci", "main", "m0", "success", 24*10, 10, 100), + // Still running: counted nowhere yet. + {ID: 7, Workflow: "ci", Branch: "feat", Status: "in_progress", Created: statsNow.Add(-time.Hour)}, + } + jobs := map[int64][]Job{ + 6: {job("build", "success", 60), job("test", "success", 240)}, + 5: {job("build", "success", 80), job("test", "failure", 500)}, + 4: {job("build", "success", 70), job("test", "success", 300)}, + } + s := ComputeStats(runs, jobs, statsNow, 7, time.UTC) + // A cancelled run is neither a pass nor a failure. + if s.Runs != 3 || s.Passed != 2 || s.Failed != 1 { + t.Fatalf("counts: %+v", s) + } + if s.PrevRuns != 2 || s.PrevPassed != 1 { + t.Errorf("prior period: %d runs, %d passed", s.PrevRuns, s.PrevPassed) + } + if s.MedianSeconds != 400 || s.QueueSeconds != 20 { + t.Errorf("median %d, queue %d", s.MedianSeconds, s.QueueSeconds) + } + if s.JobsRead != 3 { + t.Errorf("jobs read for %d runs", s.JobsRead) + } + // One entry a day, oldest first, today last. + if len(s.Daily) != 7 || s.Daily[6].Date != "2026-11-14" || s.Daily[6].Passed != 1 || s.Daily[6].Failed != 1 { + t.Errorf("daily: %+v", s.Daily) + } + if s.Daily[5].Date != "2026-11-13" || s.Daily[5].Passed != 1 { + t.Errorf("yesterday: %+v", s.Daily[5]) + } + // Jobs, slowest first, with their median and slowest tenth. + if len(s.Jobs) != 2 || s.Jobs[0].Name != "test" || s.Jobs[0].Runs != 3 || s.Jobs[0].Failed != 1 || + s.Jobs[0].MedianSeconds != 300 || s.Jobs[0].P90Seconds != 500 { + t.Errorf("jobs: %+v", s.Jobs) + } + // The failure on feat went green when the next run on it finished. + if s.RedToGreenSeconds != 3*3600+310-620 || s.RedToGreenCount != 1 { + t.Errorf("red to green %d over %d", s.RedToGreenSeconds, s.RedToGreenCount) + } +} + +// A job that failed and passed on the same commit is flaky; so is a run +// that passed only on its second attempt. A failure fixed by a new commit +// is not. +func TestStatsFlaky(t *testing.T) { + runs := []Run{ + ciRun(4, "ci", "feat", "same", "success", 1, 1, 10), + ciRun(3, "ci", "feat", "same", "failure", 2, 1, 10), + ciRun(2, "ci", "feat", "fixed", "failure", 3, 1, 10), + ciRun(1, "ci", "feat", "fixed2", "success", 4, 1, 10), + } + retried := ciRun(5, "lint", "main", "x", "success", 1, 1, 10) + retried.Attempt = 2 + runs = append(runs, retried) + jobs := map[int64][]Job{ + 4: {job("test macos", "success", 9), job("build", "success", 1)}, + 3: {job("test macos", "failure", 9), job("build", "success", 1)}, + 2: {job("build", "failure", 1)}, + 1: {job("build", "success", 1)}, + } + s := ComputeStats(runs, jobs, statsNow, 7, time.UTC) + if len(s.Flaky) != 2 || s.Flaky[0].Name != "test macos" || s.Flaky[0].Times != 1 { + t.Fatalf("flaky: %+v", s.Flaky) + } + if s.Flaky[1].Name != "lint" || !strings.Contains(s.Flaky[1].How, "attempt") { + t.Errorf("a run that passed on a retry: %+v", s.Flaky[1]) + } +} + +// Failures that can still be re-run: the newest run of each workflow on a +// branch, when it failed — not one a later run already replaced. +func TestStatsFailing(t *testing.T) { + runs := []Run{ + ciRun(5, "ci", "feat", "b", "failure", 1, 1, 10), + ciRun(4, "ci", "feat", "a", "failure", 2, 1, 10), + ciRun(3, "ci", "main", "m", "success", 1, 1, 10), + ciRun(2, "ci", "main", "l", "failure", 2, 1, 10), + ciRun(1, "lint", "feat", "b", "timed_out", 1, 1, 10), + } + s := ComputeStats(runs, nil, statsNow, 7, time.UTC) + var ids []int64 + for _, f := range s.Failing { + ids = append(ids, f.ID) + } + if len(ids) != 2 || ids[0] != 5 || ids[1] != 1 { + t.Fatalf("failing: %+v", s.Failing) + } +} + +// Nothing ran: every number is zero and every day is there, empty. +func TestStatsEmpty(t *testing.T) { + s := ComputeStats(nil, nil, statsNow, 30, time.UTC) + if s.Runs != 0 || s.MedianSeconds != 0 || len(s.Daily) != 30 || len(s.Jobs) != 0 || s.Days != 30 { + t.Fatalf("%+v", s) + } + if s := ComputeStats(nil, nil, statsNow, 0, time.UTC); s.Days != 1 || len(s.Daily) != 1 { + t.Errorf("no days asked is one: %+v", s) + } +} + +func TestPercentile(t *testing.T) { + for _, c := range []struct { + xs []int + p float64 + want int + }{ + {nil, 0.5, 0}, + {[]int{7}, 0.9, 7}, + {[]int{3, 1, 2}, 0.5, 2}, + {[]int{1, 2, 3, 4}, 0.5, 2}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 0.9, 9}, + } { + if got := percentile(c.xs, c.p); got != c.want { + t.Errorf("percentile(%v, %v) = %d, want %d", c.xs, c.p, got, c.want) + } + } +} + +// gh's own JSON, as gh run list and gh run view print it. +func TestRunsAndJobsThroughGH(t *testing.T) { + fakeGH(t, `case "$1 $2" in +"run list") cat <<'EOF' +[{"attempt":2,"conclusion":"success","createdAt":"2026-11-15T00:40:36Z","databaseId":43,"event":"pull_request","headBranch":"feat","headSha":"abc","startedAt":"2026-11-15T00:40:40Z","status":"completed","updatedAt":"2026-11-15T00:59:44Z","url":"https://x/runs/43","workflowName":"ci"}] +EOF +;; +"run view") [ "$3" = 43 ] && [ "$4" = --json ] || exit 9; cat <<'EOF' +{"jobs":[{"completedAt":"2026-11-15T00:41:14Z","conclusion":"success","databaseId":1,"name":"build","startedAt":"2026-11-15T00:40:38Z","status":"completed","url":"u"}]} +EOF +;; +"run rerun") [ "$3" = 43 ] && [ "$4" = --failed ] || exit 9 ;; +*) exit 7 ;; +esac +`) + ctx := context.Background() + runs, err := Runs(ctx, t.TempDir(), 50) + if err != nil || len(runs) != 1 { + t.Fatalf("runs %+v %v", runs, err) + } + r := runs[0] + if r.ID != 43 || r.Workflow != "ci" || r.Branch != "feat" || r.Sha != "abc" || r.Attempt != 2 || r.Updated.Sub(r.Started) != 19*time.Minute+4*time.Second { + t.Errorf("run %+v", r) + } + jobs, err := RunJobs(ctx, t.TempDir(), 43) + if err != nil || len(jobs) != 1 || jobs[0].Name != "build" || jobs[0].Completed.Sub(jobs[0].Started) != 36*time.Second { + t.Errorf("jobs %+v %v", jobs, err) + } + if err := Rerun(ctx, t.TempDir(), 43); err != nil { + t.Errorf("rerun: %v", err) + } + if err := Rerun(ctx, t.TempDir(), 44); err == nil { + t.Error("a rerun gh refused said nothing") + } +} + +func TestRunsFailures(t *testing.T) { + fakeGH(t, `printf 'oops'`) + if _, err := Runs(context.Background(), t.TempDir(), 10); err == nil || !strings.Contains(err.Error(), "gh run list") { + t.Errorf("bad JSON: %v", err) + } + if _, err := RunJobs(context.Background(), t.TempDir(), 1); err == nil { + t.Error("bad jobs JSON said nothing") + } + t.Setenv("CONCH_GH", "/nonexistent/gh") + if _, err := Runs(context.Background(), t.TempDir(), 10); !errors.Is(err, ErrNoGH) { + t.Errorf("no gh: %v", err) + } +} + +// The newest failed run on a branch, for a re-run asked by branch. +func TestFailedRunOnBranch(t *testing.T) { + runsGH(t, runsJSON) + id, err := FailedRunID(context.Background(), t.TempDir(), "feat", "new") + if err != nil || id != 20 { + t.Fatalf("got %d %v", id, err) + } + if _, err := FailedRunID(context.Background(), t.TempDir(), "feat", "newer"); !errors.Is(err, ErrNoFailedRun) { + t.Errorf("nothing failed there: %v", err) + } +} diff --git a/internal/ghx/runs.go b/internal/ghx/runs.go index 46424ab8..f0bf56ef 100644 --- a/internal/ghx/runs.go +++ b/internal/ghx/runs.go @@ -27,10 +27,26 @@ var ErrNoFailedRun = errors.New("no failed GitHub Actions run on this branch") // repository at dir — at commit head when given, so a run about older work // is not mistaken for this one — and fetches its failed steps' log. func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) { + runs, err := failedRuns(ctx, dir, branch, head) + if err != nil { + return FailedRun{}, err + } + r := runs[0] + log, err := run(ctx, dir, "run", "view", strconv.FormatInt(r.ID, 10), "--log-failed") + if err != nil { + return FailedRun{}, err + } + return FailedRun{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Log: string(log)}, nil +} + +// failedRuns are the failed Actions runs on branch, newest first — at +// commit head when given, so a run about older work is not taken for this +// one — or ErrNoFailedRun. +func failedRuns(ctx context.Context, dir, branch, head string) ([]Run, error) { out, err := run(ctx, dir, "run", "list", "--branch", branch, "--limit", "20", "--json", "databaseId,workflowName,url,headSha,conclusion") if err != nil { - return FailedRun{}, err + return nil, err } var runs []struct { ID int64 `json:"databaseId"` @@ -40,8 +56,9 @@ func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) Conclusion string `json:"conclusion"` } if err := json.Unmarshal(out, &runs); err != nil { - return FailedRun{}, fmt.Errorf("gh run list: %w", err) + return nil, fmt.Errorf("gh run list: %w", err) } + var found []Run for _, r := range runs { if !strings.EqualFold(r.Conclusion, "failure") && !strings.EqualFold(r.Conclusion, "timed_out") { continue @@ -49,11 +66,10 @@ func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) if head != "" && r.HeadSha != "" && r.HeadSha != head { continue } - log, err := run(ctx, dir, "run", "view", strconv.FormatInt(r.ID, 10), "--log-failed") - if err != nil { - return FailedRun{}, err - } - return FailedRun{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Log: string(log)}, nil + found = append(found, Run{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Sha: r.HeadSha, Conclusion: r.Conclusion, Branch: branch}) + } + if len(found) == 0 { + return nil, ErrNoFailedRun } - return FailedRun{}, ErrNoFailedRun + return found, nil } From 00f1a5fd856458f1f0c706c123959e3ed1d36426 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:14:35 -0800 Subject: [PATCH 19/35] Server: ci.stats and ci.rerun for the CI panel ci.stats reads a project's GitHub Actions runs through gh and adds them up with ghx.ComputeStats over the days asked (14 by default, 90 at most) and as many before. Each finished run's jobs are read once and kept on the project, a few dozen per call, four at a time; jobs_pending tells the client to ask again. ci.rerun runs a run's failed jobs again, by run or by a branch's newest failed run, then asks for the pull request's checks sooner. Re-running spends the project's Actions minutes, so an agent may only do it in its own project (scope). Each has a capability. Co-Authored-By: Claude Opus 5.5 --- internal/proto/proto.go | 104 +++++++++++++++++- internal/server/ci.go | 168 +++++++++++++++++++++++++++++ internal/server/ci_test.go | 128 ++++++++++++++++++++++ internal/server/projects.go | 5 +- internal/server/scope.go | 3 + internal/server/server.go | 16 ++- web/src/app/docs/protocol/page.mdx | 1 + 7 files changed, 422 insertions(+), 3 deletions(-) create mode 100644 internal/server/ci.go create mode 100644 internal/server/ci_test.go diff --git a/internal/proto/proto.go b/internal/proto/proto.go index b53e48bb..97e38dcc 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -225,6 +225,15 @@ const CapWorktreeSetup = "worktree.setup.v1" // read through gh on the machine the branch is on, for handing to its agent. const CapBranchCILog = "branch.ci_log.v1" +// CapCIStats is ci.stats: a project's GitHub Actions history over a +// period of days, added up for the CI panel — pass rate, run and queue +// times, runs per day, each job's time, flaky jobs, failures to re-run. +const CapCIStats = "ci.stats.v1" + +// CapCIRerun is ci.rerun: a failed run's failed jobs run again, through +// gh on the machine the project is on. +const CapCIRerun = "ci.rerun.v1" + // CapAgentReply is agent.reply: an agent's last answer, whole, from its // saved conversation rather than off its screen. const CapAgentReply = "agent.reply.v1" @@ -624,6 +633,10 @@ const ( // MethodBranchCILog is the log of the failed steps of a branch's // newest failed GitHub Actions run (CapBranchCILog). MethodBranchCILog = "branch.ci_log" + // MethodCIStats adds up a project's GitHub Actions runs (CapCIStats). + MethodCIStats = "ci.stats" + // MethodCIRerun runs a failed run's failed jobs again (CapCIRerun). + MethodCIRerun = "ci.rerun" // Leftover worktrees: list what each would lose, and remove them. MethodWorktreeStale = "worktree.stale" MethodWorktreeCleanup = "worktree.cleanup" @@ -1837,6 +1850,95 @@ type BranchDiscardParams struct { Force bool `json:"force,omitempty"` } +// CIStatsParams asks for a project's CI over the last Days days, today +// included (14 when 0, 90 at most). +type CIStatsParams struct { + ProjectID string `json:"project_id"` + Days int `json:"days,omitempty"` +} + +// CIStats is a project's GitHub Actions over a period of whole days, and +// the same number of days before it for comparison. Seconds are medians. +type CIStats struct { + Days int `json:"days"` + // Finished runs that passed or failed (a cancelled one is neither). + Runs int `json:"runs"` + Passed int `json:"passed"` + Failed int `json:"failed"` + PrevRuns int `json:"prev_runs"` + PrevPassed int `json:"prev_passed"` + // A run's time from start to finish, and its wait in the queue. + MedianSeconds int `json:"median_seconds"` + PrevMedianSeconds int `json:"prev_median_seconds"` + QueueSeconds int `json:"queue_seconds"` + // From a failed run to the next passing run of the same workflow on + // the same branch, and how many times a branch went from red to green. + RedToGreenSeconds int `json:"red_to_green_seconds"` + RedToGreenCount int `json:"red_to_green_count"` + // One a day, oldest first, today last. + Daily []CIDay `json:"daily"` + // Each job, the slowest first. + Jobs []CIJob `json:"jobs,omitempty"` + // Jobs that failed and passed with nothing changed, and runs that + // passed only on a later attempt. + Flaky []CIFlaky `json:"flaky,omitempty"` + // Each workflow's newest run on each branch, where it failed. + Failing []CIRun `json:"failing,omitempty"` + // JobsPending is how many of the period's runs have not had their jobs + // read yet: a few dozen are read per call, so asking again fills in + // the job times. + JobsPending int `json:"jobs_pending,omitempty"` +} + +// CIDay is a day's finished runs; Date is YYYY-MM-DD where the server is. +type CIDay struct { + Date string `json:"date"` + Passed int `json:"passed"` + Failed int `json:"failed"` +} + +// CIJob is one job over the period. +type CIJob struct { + Name string `json:"name"` + Runs int `json:"runs"` + Failed int `json:"failed"` + MedianSeconds int `json:"median_seconds"` + P90Seconds int `json:"p90_seconds"` +} + +// CIFlaky is a job, or a whole run, that failed and passed without a change. +type CIFlaky struct { + Name string `json:"name"` + Times int `json:"times"` + How string `json:"how"` + Last time.Time `json:"last"` +} + +// CIRun is one workflow run. +type CIRun struct { + ID int64 `json:"id"` + Workflow string `json:"workflow"` + Branch string `json:"branch,omitempty"` + Sha string `json:"sha,omitempty"` + Conclusion string `json:"conclusion,omitempty"` + Attempt int `json:"attempt,omitempty"` + URL string `json:"url,omitempty"` + At time.Time `json:"at"` +} + +// CIRerunParams names the run whose failed jobs to run again, or a branch +// whose newest failed run (at its pull request's head) it is. +type CIRerunParams struct { + ProjectID string `json:"project_id"` + RunID int64 `json:"run_id,omitempty"` + Branch string `json:"branch,omitempty"` +} + +// CIRerunResult is the run started again. +type CIRerunResult struct { + RunID int64 `json:"run_id"` +} + // BranchCILogParams names the branch whose failed CI run to read. type BranchCILogParams struct { ProjectID string `json:"project_id"` diff --git a/internal/server/ci.go b/internal/server/ci.go new file mode 100644 index 00000000..a3709575 --- /dev/null +++ b/internal/server/ci.go @@ -0,0 +1,168 @@ +package server + +import ( + "context" + "errors" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/ghx" + "github.com/Amitgb14/conch/internal/proto" +) + +// The CI panel's numbers: a project's GitHub Actions history read through +// gh and added up (ghx.ComputeStats), and a failed run's jobs run again. + +const ( + ciDaysDefault = 14 + ciDaysMax = 90 + // ciJobsPerCall bounds how many runs' jobs one ci.stats reads: each is + // a gh call, and a first look at a busy repository could need hundreds. + // The rest are said to be pending, and the next call reads more. + ciJobsPerCall = 40 + ciJobsWorkers = 4 + // ciJobsKept bounds the jobs kept per project. + ciJobsKept = 3000 +) + +type ciRunKey struct { + id int64 + attempt int +} + +func ciNoGH(err error) *proto.Error { + if errors.Is(err, ghx.ErrNoGH) { + return proto.Errorf(proto.ErrBadRequest, "gh is not installed on this machine: install the GitHub CLI and run gh auth login to see CI") + } + return proto.Errorf(proto.ErrBadRequest, "%v", err) +} + +func (pm *projectManager) ciStats(sp proto.CIStatsParams) (proto.CIStats, *proto.Error) { + p, perr := pm.gitProject(sp.ProjectID) + if perr != nil { + return proto.CIStats{}, perr + } + days := sp.Days + switch { + case days <= 0: + days = ciDaysDefault + case days > ciDaysMax: + days = ciDaysMax + } + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + // Two periods' worth: this one and the one it is compared with. + runs, err := ghx.Runs(ctx, p.root, min(200+days*2*20, 1000)) + if err != nil { + return proto.CIStats{}, ciNoGH(err) + } + now := time.Now() + start := now.AddDate(0, 0, -days) + + p.mu.Lock() + if p.ciJobs == nil { + p.ciJobs = map[ciRunKey][]ghx.Job{} + } + jobs := map[int64][]ghx.Job{} + var want []ghx.Run + for _, r := range runs { + if r.Status != "completed" || r.Created.Before(start) { + continue + } + if js, ok := p.ciJobs[ciRunKey{r.ID, r.Attempt}]; ok { + jobs[r.ID] = js + } else { + want = append(want, r) + } + } + p.mu.Unlock() + + pending := max(len(want)-ciJobsPerCall, 0) + want = want[:min(len(want), ciJobsPerCall)] + var mu sync.Mutex + var wg sync.WaitGroup + next := make(chan ghx.Run) + for range min(ciJobsWorkers, len(want)) { + wg.Add(1) + go func() { + defer wg.Done() + for r := range next { + js, err := ghx.RunJobs(ctx, p.root, r.ID) + mu.Lock() + if err != nil { + pending++ + } else { + jobs[r.ID] = js + } + mu.Unlock() + if err == nil { + p.mu.Lock() + if len(p.ciJobs) >= ciJobsKept { + clear(p.ciJobs) + } + p.ciJobs[ciRunKey{r.ID, r.Attempt}] = js + p.mu.Unlock() + } + } + }() + } + for _, r := range want { + next <- r + } + close(next) + wg.Wait() + + st := ghx.ComputeStats(runs, jobs, now, days, time.Local) + out := proto.CIStats{ + Days: st.Days, Runs: st.Runs, Passed: st.Passed, Failed: st.Failed, PrevRuns: st.PrevRuns, PrevPassed: st.PrevPassed, + MedianSeconds: st.MedianSeconds, PrevMedianSeconds: st.PrevMedianSeconds, QueueSeconds: st.QueueSeconds, + RedToGreenSeconds: st.RedToGreenSeconds, RedToGreenCount: st.RedToGreenCount, JobsPending: pending, + } + for _, d := range st.Daily { + out.Daily = append(out.Daily, proto.CIDay{Date: d.Date, Passed: d.Passed, Failed: d.Failed}) + } + for _, j := range st.Jobs { + out.Jobs = append(out.Jobs, proto.CIJob{Name: j.Name, Runs: j.Runs, Failed: j.Failed, MedianSeconds: j.MedianSeconds, P90Seconds: j.P90Seconds}) + } + for _, f := range st.Flaky { + out.Flaky = append(out.Flaky, proto.CIFlaky{Name: f.Name, Times: f.Times, How: f.How, Last: f.Last}) + } + for _, r := range st.Failing { + out.Failing = append(out.Failing, proto.CIRun{ID: r.ID, Workflow: r.Workflow, Branch: r.Branch, Sha: r.Sha, + Conclusion: r.Conclusion, Attempt: r.Attempt, URL: r.URL, At: r.Updated}) + } + return out, nil +} + +func (pm *projectManager) ciRerun(rp proto.CIRerunParams) (proto.CIRerunResult, *proto.Error) { + p, perr := pm.gitProject(rp.ProjectID) + if perr != nil { + return proto.CIRerunResult{}, perr + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + id := rp.RunID + if id == 0 { + if rp.Branch == "" { + return proto.CIRerunResult{}, proto.Errorf(proto.ErrBadRequest, "no run or branch given") + } + p.mu.Lock() + head := p.prs[rp.Branch].Head + p.mu.Unlock() + found, err := ghx.FailedRunID(ctx, p.root, rp.Branch, head) + switch { + case errors.Is(err, ghx.ErrNoFailedRun): + return proto.CIRerunResult{}, proto.Errorf(proto.ErrNotFound, + "no failed GitHub Actions run on %s to run again: the failing check is another service's, or it was already re-run", rp.Branch) + case err != nil: + return proto.CIRerunResult{}, ciNoGH(err) + } + id = found + } + if err := ghx.Rerun(ctx, p.root, id); err != nil { + return proto.CIRerunResult{}, ciNoGH(err) + } + // Its checks are pending again: the pull request says so sooner. + pm.requestPRs(p) + return proto.CIRerunResult{RunID: id}, nil +} diff --git a/internal/server/ci_test.go b/internal/server/ci_test.go new file mode 100644 index 00000000..01be3349 --- /dev/null +++ b/internal/server/ci_test.go @@ -0,0 +1,128 @@ +package server_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// fakeCIGH puts a gh on CONCH_GH that lists runs, answers each run's jobs +// (writing down which it was asked for) and records re-runs, so a test can +// see what the server asked GitHub for. +func fakeCIGH(t *testing.T, runs string) (dir string) { + t.Helper() + dir = t.TempDir() + os.WriteFile(filepath.Join(dir, "runs"), []byte(runs), 0o600) + script := `#!/bin/sh +d="` + dir + `" +case "$1 $2" in +"pr list") echo '[]' ;; +"run list") + if [ "$3" = --branch ]; then echo '[{"databaseId": 8, "workflowName": "ci", "url": "u8", "headSha": "h", "conclusion": "failure"}]'; else cat "$d/runs"; fi ;; +"run view") echo "$3" >> "$d/viewed" + echo '{"jobs":[{"name":"test","conclusion":"success","startedAt":"2026-11-01T00:00:00Z","completedAt":"2026-11-01T00:05:00Z"}]}' ;; +"run rerun") echo "$3 $4" >> "$d/reruns"; [ "$3" = 404 ] && { echo "run 404 not found" >&2; exit 1; } ; true ;; +*) exit 7 ;; +esac +` + gh := filepath.Join(dir, "gh") + os.WriteFile(gh, []byte(script), 0o755) + t.Setenv("CONCH_GH", gh) + return dir +} + +func ciRunJSON(id int, conclusion string, ago time.Duration) string { + created := time.Now().Add(-ago).UTC().Format(time.RFC3339) + done := time.Now().Add(-ago + 3*time.Minute).UTC().Format(time.RFC3339) + return fmt.Sprintf(`{"databaseId":%d,"workflowName":"ci","headBranch":"main","headSha":"s%d","event":"push","status":"completed","conclusion":%q,"attempt":1,"url":"u%d","createdAt":%q,"startedAt":%q,"updatedAt":%q}`, + id, id, conclusion, id, created, created, done) +} + +func TestCIStats(t *testing.T) { + runs := "[" + strings.Join([]string{ + ciRunJSON(3, "success", time.Hour), + ciRunJSON(2, "failure", 2*time.Hour), + ciRunJSON(1, "success", 3*time.Hour), + }, ",") + "]" + dir := fakeCIGH(t, runs) + c, _, proj := setupRepo(t) + if miss := c.MissingCapabilities([]string{proto.CapCIStats, proto.CapCIRerun}); len(miss) > 0 { + t.Fatalf("capabilities missing: %v", miss) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var s proto.CIStats + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID, Days: 7}, &s); err != nil { + t.Fatal(err) + } + if s.Days != 7 || s.Runs != 3 || s.Passed != 2 || s.Failed != 1 || len(s.Daily) != 7 || s.MedianSeconds != 180 { + t.Fatalf("stats: %+v", s) + } + if len(s.Jobs) != 1 || s.Jobs[0].Name != "test" || s.Jobs[0].MedianSeconds != 300 || s.JobsPending != 0 { + t.Errorf("jobs: %+v pending %d", s.Jobs, s.JobsPending) + } + // A finished run's jobs never change: asked for once, then kept. + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err != nil { + t.Fatal(err) + } + if s.Days != 14 { + t.Errorf("no days given is 14: %d", s.Days) + } + viewed, _ := os.ReadFile(filepath.Join(dir, "viewed")) + if n := len(strings.Fields(string(viewed))); n != 3 { + t.Errorf("jobs read %d times for 3 runs: %q", n, viewed) + } + // Too many days is held to 90. + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID, Days: 1000}, &s); err != nil || s.Days != 90 { + t.Errorf("1000 days: %d %v", s.Days, err) + } +} + +func TestCIStatsRefusals(t *testing.T) { + fakeCIGH(t, `oops`) + c, _, proj := setupRepo(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var s proto.CIStats + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err == nil || !strings.Contains(err.Error(), "gh run list") { + t.Errorf("gh's bad answer: %v", err) + } + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: "nope"}, &s); err == nil { + t.Error("an unknown project was answered") + } + t.Setenv("CONCH_GH", filepath.Join(t.TempDir(), "no-gh")) + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err == nil || !strings.Contains(err.Error(), "gh") { + t.Errorf("no gh: %v", err) + } +} + +func TestCIRerun(t *testing.T) { + dir := fakeCIGH(t, `[]`) + c, _, proj := setupRepo(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var r proto.CIRerunResult + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, RunID: 42}, &r); err != nil || r.RunID != 42 { + t.Fatalf("by run: %+v %v", r, err) + } + // By branch: its newest failed run. + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, Branch: "main"}, &r); err != nil || r.RunID != 8 { + t.Fatalf("by branch: %+v %v", r, err) + } + reruns, _ := os.ReadFile(filepath.Join(dir, "reruns")) + if string(reruns) != "42 --failed\n8 --failed\n" { + t.Errorf("gh was asked %q", reruns) + } + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID}, &r); err == nil { + t.Error("neither a run nor a branch was taken") + } + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, RunID: 404}, &r); err == nil || !strings.Contains(err.Error(), "not found") { + t.Errorf("gh's refusal: %v", err) + } +} diff --git a/internal/server/projects.go b/internal/server/projects.go index bfb58350..29592b84 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -166,7 +166,10 @@ type project struct { // is older than info and is not applied (refresh). gen uint64 - prs map[string]proto.PRInfo // by head branch + prs map[string]proto.PRInfo // by head branch + // ciJobs are finished Actions runs' jobs, by run and attempt, read + // for the CI panel: they never change, so each is asked for once. + ciJobs map[ciRunKey][]ghx.Job prStatus string prAt time.Time // last fetch prNext time.Time // no fetch before this (after errors) diff --git a/internal/server/scope.go b/internal/server/scope.go index 75c1e73c..493606f7 100644 --- a/internal/server/scope.go +++ b/internal/server/scope.go @@ -123,6 +123,8 @@ var scoped = map[string]scopeKind{ proto.MethodWorktreeRemove: scopeProject, proto.MethodWorktreeCleanup: scopeProject, proto.MethodBranchCommit: scopeProject, proto.MethodBranchStage: scopeProject, proto.MethodBranchReview: scopeProject, proto.MethodBranchPush: scopeProject, proto.MethodBranchPR: scopeProject, proto.MethodBranchMerge: scopeProject, proto.MethodBranchPRMerge: scopeProject, proto.MethodBranchDiscard: scopeProject, proto.MethodBranchGit: scopeProject, + // Running CI again spends the project's Actions minutes. + proto.MethodCIRerun: scopeProject, proto.MethodServerStop: scopeServer, proto.MethodServerReload: scopeServer, // The cloud agent decides what every agent's environment is given. @@ -429,6 +431,7 @@ var verbs = map[string]string{ proto.MethodBranchPush: "push", proto.MethodBranchPR: "open a pull request", proto.MethodBranchMerge: "merge", proto.MethodBranchPRMerge: "merge a pull request", proto.MethodBranchDiscard: "discard a branch", proto.MethodBranchGit: "run git", + proto.MethodCIRerun: "re-run the CI of", proto.MethodTicketUpdate: "change a ticket", proto.MethodAgentSkill: "install or remove the agents' conch skill", proto.MethodProjectFiles: "change which local files a project copies into its worktrees", diff --git a/internal/server/server.go b/internal/server/server.go index d1500715..9784c868 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -454,7 +454,7 @@ var slowMethods = map[string]bool{ proto.MethodProjectFiles: true, proto.MethodProjectSetup: true, proto.MethodSessionList: true, proto.MethodSessionResume: true, proto.MethodSessionDelete: true, proto.MethodSessionSearch: true, proto.MethodSessionShare: true, proto.MethodSessionExport: true, proto.MethodFSUpload: true, proto.MethodBranchCommit: true, proto.MethodBranchStage: true, proto.MethodBranchPush: true, proto.MethodBranchPR: true, - proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, + proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, proto.MethodProjectTickets: true, proto.MethodTicketGet: true, proto.MethodTicketUpdate: true, proto.MethodTicketCheck: true, proto.MethodTicketOverview: true, proto.MethodWorktreeStale: true, proto.MethodWorktreeCleanup: true, proto.MethodProjectResolve: true, proto.MethodProjectGitInit: true, proto.MethodWorktreeDescribe: true, proto.MethodWorktreeHave: true, proto.MethodWorktreePack: true, @@ -1021,6 +1021,20 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { } return s.projects.changes(cp) + case proto.MethodCIStats: + sp, perr := decode[proto.CIStatsParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.ciStats(sp) + + case proto.MethodCIRerun: + rp, perr := decode[proto.CIRerunParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.ciRerun(rp) + case proto.MethodProjectLog: lp, perr := decode[proto.LogParams](msg) if perr != nil { diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index fa19ef75..32d64e22 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -39,6 +39,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, the repository's remotes by which a remote's branch is told from a local one, and its `format` — `objects` sha1 or sha256 and `refs` files or reftable — absent from an older server; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`) | | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | +| CI | `ci.stats` adds up a project's GitHub Actions runs over `days` (14 by default, 90 at most) and the same span before: runs, passes and failures, median run, queue and red-to-green times, runs per day, each job's median and slowest tenth, flaky jobs, and each workflow's newest failed run per branch; a few dozen runs' jobs are read per call and `jobs_pending` says how many are left (capability `ci.stats.v1`). `ci.rerun` runs a run's failed jobs again, by `run_id` or a `branch`'s newest failed run (capability `ci.rerun.v1`). Both go through `gh` on the project's machine | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | | Moving a worktree | `worktree.describe`, `worktree.pack`, `worktree.pack_read` on the machine it leaves; `worktree.have`, `fs.upload`, `worktree.unpack` and `project.clone` on the one it goes to (capability `worktree.move.v1`). The servers never talk to each other: the client carries the pack | | Sessions | `session.list`, `session.search`, `session.resume`, `session.share`, `session.delete`, `session.dismiss`; `session.export` and `session.share` with a `doc` hand a conversation to another machine (capability `session.handoff.v1`) | From cc99f34f12080e02237e56bdd5706869761d31ce Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:26:27 -0800 Subject: [PATCH 20/35] ConchKit: the CI panel's numbers CIStats decodes ci.stats (optional fields, so an answer without the lists still reads); passRate and its change in whole points, the median run's change, durations as the panel says them, and the runs-per-day chart's scale: its top is the busiest day rounded up to a number worth labelling (11 runs to 12, not 20), so the tallest bar fills the chart. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchKit/CIStats.swift | 142 +++++++++++++++++++ macos/Tests/ConchKitTests/CIStatsTests.swift | 71 ++++++++++ 2 files changed, 213 insertions(+) create mode 100644 macos/Sources/ConchKit/CIStats.swift create mode 100644 macos/Tests/ConchKitTests/CIStatsTests.swift diff --git a/macos/Sources/ConchKit/CIStats.swift b/macos/Sources/ConchKit/CIStats.swift new file mode 100644 index 00000000..7c002d3c --- /dev/null +++ b/macos/Sources/ConchKit/CIStats.swift @@ -0,0 +1,142 @@ +import Foundation + +// A project's GitHub Actions over a period of days, as ci.stats gives it, +// and what the CI panel works out from it. + +public struct CIStats: Decodable, Equatable, Sendable { + public var days: Int + public var runs: Int + public var passed: Int + public var failed: Int + public var prevRuns: Int + public var prevPassed: Int + public var medianSeconds: Int + public var prevMedianSeconds: Int + public var queueSeconds: Int + public var redToGreenSeconds: Int + public var redToGreenCount: Int + public var daily: [CIDay] + public var jobs: [CIJob]? + public var flaky: [CIFlaky]? + public var failing: [CIRun]? + public var jobsPending: Int + + enum CodingKeys: String, CodingKey { + case days, runs, passed, failed, daily, jobs, flaky, failing + case prevRuns = "prev_runs", prevPassed = "prev_passed" + case medianSeconds = "median_seconds", prevMedianSeconds = "prev_median_seconds", queueSeconds = "queue_seconds" + case redToGreenSeconds = "red_to_green_seconds", redToGreenCount = "red_to_green_count" + case jobsPending = "jobs_pending" + } + + public init(from d: Decoder) throws { + let c = try d.container(keyedBy: CodingKeys.self) + days = try c.decode(Int.self, forKey: .days) + runs = try c.decodeIfPresent(Int.self, forKey: .runs) ?? 0 + passed = try c.decodeIfPresent(Int.self, forKey: .passed) ?? 0 + failed = try c.decodeIfPresent(Int.self, forKey: .failed) ?? 0 + prevRuns = try c.decodeIfPresent(Int.self, forKey: .prevRuns) ?? 0 + prevPassed = try c.decodeIfPresent(Int.self, forKey: .prevPassed) ?? 0 + medianSeconds = try c.decodeIfPresent(Int.self, forKey: .medianSeconds) ?? 0 + prevMedianSeconds = try c.decodeIfPresent(Int.self, forKey: .prevMedianSeconds) ?? 0 + queueSeconds = try c.decodeIfPresent(Int.self, forKey: .queueSeconds) ?? 0 + redToGreenSeconds = try c.decodeIfPresent(Int.self, forKey: .redToGreenSeconds) ?? 0 + redToGreenCount = try c.decodeIfPresent(Int.self, forKey: .redToGreenCount) ?? 0 + daily = try c.decodeIfPresent([CIDay].self, forKey: .daily) ?? [] + jobs = try c.decodeIfPresent([CIJob].self, forKey: .jobs) + flaky = try c.decodeIfPresent([CIFlaky].self, forKey: .flaky) + failing = try c.decodeIfPresent([CIRun].self, forKey: .failing) + jobsPending = try c.decodeIfPresent(Int.self, forKey: .jobsPending) ?? 0 + } + + /// The share of finished runs that passed, in whole percent; nil + /// without any. + public var passRate: Int? { runs > 0 ? Int((Double(passed) * 100 / Double(runs)).rounded()) : nil } + + /// How many points the pass rate moved from the period before; nil when + /// either has no runs. + public var passRateChange: Int? { + guard let now = passRate, prevRuns > 0 else { return nil } + return now - Int((Double(prevPassed) * 100 / Double(prevRuns)).rounded()) + } + + /// How many seconds the median run moved from the period before. + public var medianChange: Int? { + guard prevRuns > 0, prevMedianSeconds > 0, medianSeconds > 0 else { return nil } + return medianSeconds - prevMedianSeconds + } +} + +public struct CIDay: Decodable, Equatable, Sendable { + public var date: String + public var passed: Int + public var failed: Int + + public init(date: String, passed: Int, failed: Int) { + self.date = date + self.passed = passed + self.failed = failed + } +} + +public struct CIJob: Decodable, Equatable, Sendable { + public var name: String + public var runs: Int + public var failed: Int + public var medianSeconds: Int + public var p90Seconds: Int + + enum CodingKeys: String, CodingKey { + case name, runs, failed + case medianSeconds = "median_seconds", p90Seconds = "p90_seconds" + } +} + +public struct CIFlaky: Decodable, Equatable, Sendable { + public var name: String + public var times: Int + public var how: String? + public var last: Date? +} + +public struct CIRun: Decodable, Equatable, Sendable, Identifiable { + public var id: Int64 + public var workflow: String + public var branch: String? + public var sha: String? + public var conclusion: String? + public var attempt: Int? + public var url: String? + public var at: Date? +} + +/// A duration as the panel says it: "45s", "6m 42s", "1h 02m". +public func ciDuration(_ seconds: Int) -> String { + let s = max(seconds, 0) + if s < 60 { return "\(s)s" } + if s < 3600 { return s % 60 == 0 ? "\(s / 60)m" : "\(s / 60)m \(s % 60)s" } + let m = (s % 3600) / 60 + return m == 0 ? "\(s / 3600)h" : "\(s / 3600)h " + String(format: "%02dm", m) +} + +/// The top of the runs-per-day chart: the busiest day rounded up to the +/// nearest number worth labelling — 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 +/// times a power of ten, whole — at least 1, so the tallest bar fills +/// most of the chart. +public func ciAxisTop(_ busiest: Int) -> Int { + guard busiest > 1 else { return 1 } + var scale = 1 + while busiest > scale * 10 { scale *= 10 } + for step in [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10] { + let v = step * Double(scale) + if v == v.rounded(), Int(v) >= busiest { return Int(v) } + } + return 10 * scale +} + +/// Each day's bar, passed and failed, in points of a chart height high +/// whose top is ciAxisTop of the busiest day. +public func ciBars(_ days: [CIDay], height: Double) -> [(passed: Double, failed: Double)] { + let top = Double(ciAxisTop(days.map { $0.passed + $0.failed }.max() ?? 0)) + return days.map { (Double($0.passed) * height / top, Double($0.failed) * height / top) } +} diff --git a/macos/Tests/ConchKitTests/CIStatsTests.swift b/macos/Tests/ConchKitTests/CIStatsTests.swift new file mode 100644 index 00000000..d8fe4cdf --- /dev/null +++ b/macos/Tests/ConchKitTests/CIStatsTests.swift @@ -0,0 +1,71 @@ +import Foundation +import Testing +@testable import ConchKit + +let ciJSON = #""" +{"days":7,"runs":20,"passed":17,"failed":3,"prev_runs":10,"prev_passed":8, + "median_seconds":402,"prev_median_seconds":440,"queue_seconds":24, + "red_to_green_seconds":660,"red_to_green_count":3, + "daily":[{"date":"2026-11-08","passed":2,"failed":0},{"date":"2026-11-09","passed":5,"failed":1}, + {"date":"2026-11-10","passed":0,"failed":0},{"date":"2026-11-11","passed":3,"failed":2}, + {"date":"2026-11-12","passed":4,"failed":0},{"date":"2026-11-13","passed":1,"failed":0}, + {"date":"2026-11-14","passed":2,"failed":0}], + "jobs":[{"name":"test macos","runs":20,"failed":2,"median_seconds":390,"p90_seconds":610}, + {"name":"lint","runs":20,"failed":0,"median_seconds":48,"p90_seconds":61}], + "flaky":[{"name":"test macos","times":2,"how":"failed and passed on the same commit","last":"2026-11-13T10:00:00Z"}], + "failing":[{"id":42,"workflow":"ci","branch":"conch/git3","sha":"abc","conclusion":"failure","attempt":1,"url":"https://x/42","at":"2026-11-14T11:00:00Z"}], + "jobs_pending":5} +"""# + +// The server's numbers, as the panel reads them; an older server's answer +// without the optional lists still decodes. +@Test func ciStatsDecode() throws { + let s = try conchDecoder().decode(CIStats.self, from: Data(ciJSON.utf8)) + #expect(s.days == 7 && s.runs == 20 && s.passed == 17 && s.medianSeconds == 402) + #expect(s.daily.count == 7 && s.daily[3].failed == 2) + #expect(s.jobs?.first?.p90Seconds == 610) + #expect(s.failing?.first?.id == 42 && s.failing?.first?.branch == "conch/git3") + #expect(s.jobsPending == 5) + let bare = try conchDecoder().decode(CIStats.self, from: Data(#"{"days":14,"runs":0,"passed":0,"failed":0,"daily":[]}"#.utf8)) + #expect(bare.jobs == nil && bare.prevRuns == 0 && bare.jobsPending == 0) +} + +// Pass rate and its change in whole points; none without runs to compare. +@Test func ciRates() throws { + let s = try conchDecoder().decode(CIStats.self, from: Data(ciJSON.utf8)) + #expect(s.passRate == 85) + #expect(s.passRateChange == 5) // 85 now, 80 before + #expect(s.medianChange == -38) + var none = s + none.prevRuns = 0 + #expect(none.passRateChange == nil && none.medianChange == nil) + none.runs = 0 + #expect(none.passRate == nil) +} + +@Test func ciDurations() { + #expect(ciDuration(0) == "0s") + #expect(ciDuration(45) == "45s") + #expect(ciDuration(60) == "1m") + #expect(ciDuration(402) == "6m 42s") + #expect(ciDuration(3600) == "1h") + #expect(ciDuration(3725) == "1h 02m") + #expect(ciDuration(-5) == "0s") +} + +// The chart's top is a round number at or above the busiest day, so its +// gridline label means something; bars are scaled to it. +@Test func ciChartScale() { + #expect(ciAxisTop(0) == 1) + #expect(ciAxisTop(1) == 1) + #expect(ciAxisTop(6) == 6) + #expect(ciAxisTop(7) == 8) + #expect(ciAxisTop(11) == 12) + #expect(ciAxisTop(23) == 25) + #expect(ciAxisTop(130) == 150) + let days = [CIDay(date: "a", passed: 4, failed: 2), CIDay(date: "b", passed: 0, failed: 0)] + let bars = ciBars(days, height: 100) + #expect(bars[0].passed == 400.0 / 6 && bars[0].failed == 200.0 / 6) + #expect(bars[1].passed == 0 && bars[1].failed == 0) + #expect(ciBars([], height: 100).isEmpty) +} From d585271934e9815759b7493ea7b60eea3799628c Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:26:27 -0800 Subject: [PATCH 21/35] Conch.app: a CI panel in the commit graph, and re-run failed jobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI beside the graph's search opens the project's GitHub Actions over 7, 14 or 30 days: pass rate and median run against the period before, how long a branch stays red, the wait in the queue, runs per day, each job's median and slowest tenth, flaky jobs, and the failures that can be run again. While the server is still reading a busy repository's jobs the panel says so and asks again. The branch list steps aside while it is open, since graph, list and panel do not fit together. Re-run failed jobs, in the panel and on a red branch's menus, asks ci.rerun; the button says Re-running… until a later attempt shows up, so a run that fails again can be re-run again. Tried live against a fake gh serving a month of runs, at 14 days: the numbers, the chart and the re-run (gh run rerun ID --failed) as expected. The 30-day chart and the panel with the branch list stepped aside were not seen live. Co-Authored-By: Claude Opus 5.5 --- docs/testing/end-to-end.md | 1 + macos/Sources/ConchApp/CIPanel.swift | 292 +++++++++++++++++++++++ macos/Sources/ConchApp/CommitsView.swift | 113 ++++++++- web/src/app/docs/mac-app/page.mdx | 2 +- 4 files changed, 401 insertions(+), 7 deletions(-) create mode 100644 macos/Sources/ConchApp/CIPanel.swift diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 7ce95e2d..ec70e27b 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -415,6 +415,7 @@ What it carries, and what is left over in each row: | 9.172 🌐 | Trackers connected, with real keys | A real Linear key (in the Keychain as conch-mcp LINEAR_API_KEY), a real Jira site with a wrong token, gh signed in; open Settings → Trackers in Conch.app, then run `conch ticket check` in a project. Change the Linear team to one that does not exist, save. Fix the Jira token, press Test again. `gh auth logout`, Test again. | GitHub, Linear: Connected with your name, workspace and real counts (open, yours, teams); the team field offers the teams the key sees; Jira: Couldn't sign in with Atlassian's 401. The bad team: Linear stays Connected with "no team … in Linear" beneath. Jira fixed: Connected. Logged out: GitHub says to run gh auth login. No key appears anywhere on screen or in `-json`. | ☐ | | 9.174 🖥 | The Tickets window with real trackers | Conch.app with two projects with GitHub remotes, Linear set up for one (`[[trackers.projects]]`), a task queued for one issue, an agent working on another's branch, a third with an open PR. ⇧⌘I; try every view in the side, search, and each row's button. | Each project with its issues and tickets, yours marked; the queued, working and PR rows say so (with CI); Needs info counts needs-info and too-big; Task opens New Task in the main window with that issue or ticket picked; Agent focuses the agent; PR and Open open the browser. A project whose tracker fails says why and still lists its issues. An older server says to reload. | ☐ | | 9.175 💳🌐 | Conch.app's commit graph with agents | A project with Claude and Codex on task branches, one with an open pull request on a real GitHub repository and red CI, one whose change master then touches on the same lines; open **Commit Graph**. Rebase the second onto master by hand so it stops, then **Ask Codex to resolve**, and its menu's *Start a new agent* on another; **Hand to an Agent…** on an older commit; a SHA-256 reftable repository (`git init --object-format=sha256 --ref-format=reftable`) added as a project | Agents on branches lists both in urgency order with the right agent and ↑/↓; commits show their agent; the CI squares match GitHub; *will conflict* shows before anything moves, the banner when the rebase stops; the agent gets the files and resolves without pushing; the new task's branch starts at the commit; the header says **Git 3 · SHA-256 · reftable** | ☐ | +| 9.176 🌐 | The CI panel against real GitHub Actions | On a project with a month of real Actions history and `gh` logged in: **Commit Graph** → **CI**, then 7d, 14d and 30d; on a busy repository watch *Reading the jobs of N more runs…* fill in; break a test on a branch, let its run fail, then **Re-run failed jobs** in the panel and **Re-run Failed Jobs** on the branch's menu | The numbers match GitHub's Actions page for the period (pass rate, the failing runs, a job's time); the re-run starts a new attempt of that run on GitHub, the button says *Re-running…* until the attempt shows, and the pull request's checks turn pending | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/macos/Sources/ConchApp/CIPanel.swift b/macos/Sources/ConchApp/CIPanel.swift new file mode 100644 index 00000000..6f22bd43 --- /dev/null +++ b/macos/Sources/ConchApp/CIPanel.swift @@ -0,0 +1,292 @@ +import AppKit +import ConchKit +import SwiftUI + +// The commit graph's CI panel: the project's GitHub Actions over the last +// week, two or a month — how often it passes, how long it takes and waits, +// how long a branch stays red, runs per day, each job's time, the jobs +// that fail and pass with nothing changed, and the failures that can be +// run again. All of it read through gh on the project's machine (ci.stats). + +struct CIPanel: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + VStack(spacing: 0) { + HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 1) { + Text("CI pipeline").font(.ui(size: 13.5, weight: .semibold)) + Text("GitHub Actions · last \(model.ciDays) days · read with gh") + .font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1) + } + Spacer(minLength: 4) + if model.ciLoading { ProgressView().controlSize(.small) } + Picker("Range", selection: $model.ciDays) { + Text("7d").tag(7) + Text("14d").tag(14) + Text("30d").tag(30) + } + .pickerStyle(.segmented).labelsHidden().fixedSize().controlSize(.small) + .onChange(of: model.ciDays) { _, _ in model.loadCI() } + } + .padding(.horizontal, 14).frame(height: 52) + Rectangle().fill(Theme.line).frame(height: 1) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if !model.ciError.isEmpty { + Text(model.ciError).font(.ui(size: 12)).foregroundStyle(Theme.err) + .fixedSize(horizontal: false, vertical: true) + } + if let s = model.ci { + Tiles(s: s) + if s.runs == 0 { + Text("No finished runs in the last \(s.days) days.").font(.ui(size: 12)).foregroundStyle(Theme.muted) + } else { + RunsPerDay(s: s) + } + if !(s.failing ?? []).isEmpty { Failing(model: model, runs: s.failing ?? []) } + if !(s.jobs ?? []).isEmpty || s.jobsPending > 0 { JobTimes(s: s) } + if !(s.flaky ?? []).isEmpty { Flaky(items: s.flaky ?? []) } + } else if model.ciError.isEmpty { + ProgressView().controlSize(.small).frame(maxWidth: .infinity) + } + } + .padding(14) + } + } + .background(Theme.side) + } +} + +/// A heading and a line saying how to read what follows. +private struct CISection: View { + let title: String + var note = "" + @ViewBuilder let content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline) { + Text(title).font(.ui(size: 12.5, weight: .semibold)) + Spacer(minLength: 6) + if !note.isEmpty { Text(note).font(.ui(size: 10.5)).foregroundStyle(Theme.muted).lineLimit(1) } + } + content + } + } +} + +private struct Tiles: View { + @Environment(\.conchTheme) private var look + let s: CIStats + + var body: some View { + let _ = look + LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) { + tile("PASS RATE", s.passRate.map { "\($0)%" } ?? "—", + s.passRateChange.map { $0 == 0 ? "same as before" : "\($0 > 0 ? "▲" : "▼") \(abs($0)) pts vs before" } ?? "\(s.runs) runs", + (s.passRateChange ?? 0) > 0 ? Theme.ok : (s.passRateChange ?? 0) < 0 ? Theme.err : Theme.muted) + tile("MEDIAN RUN", s.medianSeconds > 0 ? ciDuration(s.medianSeconds) : "—", + s.medianChange.map { $0 == 0 ? "same as before" : "\($0 < 0 ? "▼" : "▲") \(ciDuration(abs($0))) \($0 < 0 ? "faster" : "slower")" } ?? "start to finish", + (s.medianChange ?? 0) < 0 ? Theme.ok : (s.medianChange ?? 0) > 0 ? Theme.warn : Theme.muted) + tile("RED → GREEN", s.redToGreenCount > 0 ? ciDuration(s.redToGreenSeconds) : "—", + s.redToGreenCount > 0 ? "median of \(s.redToGreenCount)" : "nothing went red", Theme.muted) + tile("IN QUEUE", s.runs > 0 ? ciDuration(s.queueSeconds) : "—", "median wait to start", Theme.muted) + } + } + + func tile(_ k: String, _ v: String, _ d: String, _ tone: Color) -> some View { + VStack(alignment: .leading, spacing: 2) { + Text(k).font(.ui(size: 10, weight: .semibold)).foregroundStyle(Theme.muted) + Text(v).font(.ui(size: 19, weight: .semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.7) + Text(d).font(.ui(size: 10.5)).foregroundStyle(tone).lineLimit(1).minimumScaleFactor(0.8) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(Theme.window)) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.line)) + .accessibilityElement(children: .combine) + } +} + +/// Passed runs as green bars with failures stacked on top, one a day; +/// the top gridline is labelled with the count it stands for. +private struct RunsPerDay: View { + @Environment(\.conchTheme) private var look + let s: CIStats + static let height: Double = 96 + + var body: some View { + let _ = look + let bars = ciBars(s.daily, height: Self.height) + let top = ciAxisTop(s.daily.map { $0.passed + $0.failed }.max() ?? 0) + CISection(title: "Runs per day") { + HStack(spacing: 10) { + legend(Theme.ok, "✓ passed") + legend(Theme.err, "✕ failed") + } + HStack(alignment: .bottom, spacing: 6) { + VStack(alignment: .trailing) { + Text("\(top)") + Spacer() + Text("0") + } + .font(.ui(size: 9.5)).foregroundStyle(Theme.muted).frame(height: Self.height) + ZStack(alignment: .bottom) { + VStack { + Rectangle().fill(Theme.line.opacity(0.5)).frame(height: 1) + Spacer() + Rectangle().fill(Theme.line).frame(height: 1) + } + HStack(alignment: .bottom, spacing: s.daily.count > 20 ? 2 : 4) { + ForEach(Array(s.daily.enumerated()), id: \.offset) { i, d in + VStack(spacing: 2) { + if d.failed > 0 { + UnevenRoundedRectangle(topLeadingRadius: 3, topTrailingRadius: 3).fill(Theme.err) + .frame(height: max(bars[i].failed - 1, 1)) + } + if d.passed > 0 { + UnevenRoundedRectangle(topLeadingRadius: d.failed > 0 ? 0 : 3, topTrailingRadius: d.failed > 0 ? 0 : 3) + .fill(Theme.ok).frame(height: max(bars[i].passed - 1, 1)) + } + } + .frame(maxWidth: .infinity, maxHeight: Self.height, alignment: .bottom) + .contentShape(Rectangle()) + .help("\(d.date): \(d.passed) passed, \(d.failed) failed") + } + } + } + .frame(height: Self.height) + } + HStack { + Text(s.daily.first.map { shortDate($0.date) } ?? "") + Spacer() + Text("today") + } + .font(.ui(size: 9.5)).foregroundStyle(Theme.muted).padding(.leading, 18) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("Runs per day: \(s.passed) passed and \(s.failed) failed over \(s.days) days") + } + + func legend(_ c: Color, _ t: String) -> some View { + HStack(spacing: 4) { + RoundedRectangle(cornerRadius: 2).fill(c).frame(width: 9, height: 9) + Text(t).font(.ui(size: 10.5)).foregroundStyle(Theme.text2) + } + } + + func shortDate(_ iso: String) -> String { + let f = DateFormatter() + f.dateFormat = "yyyy-MM-dd" + guard let d = f.date(from: iso) else { return iso } + f.dateFormat = "MMM d" + return f.string(from: d) + } +} + +/// Each job's median time as a bar and its slowest tenth as a tick. +private struct JobTimes: View { + @Environment(\.conchTheme) private var look + let s: CIStats + + var body: some View { + let _ = look + let jobs = s.jobs ?? [] + let longest = Double(max(jobs.map(\.p90Seconds).max() ?? 1, 1)) + CISection(title: "Time per job", note: "bar median · tick slowest 10%") { + ForEach(jobs.prefix(10), id: \.name) { j in + HStack(spacing: 8) { + Text(j.name).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1).truncationMode(.middle) + .frame(width: 92, alignment: .leading) + GeometryReader { g in + ZStack(alignment: .leading) { + UnevenRoundedRectangle(bottomTrailingRadius: 3, topTrailingRadius: 3).fill(Theme.accent) + .frame(width: max(g.size.width * Double(j.medianSeconds) / longest, 2), height: 9) + RoundedRectangle(cornerRadius: 1).fill(Theme.muted) + .frame(width: 2, height: 15) + .offset(x: min(g.size.width * Double(j.p90Seconds) / longest, g.size.width - 2)) + } + .frame(height: g.size.height) + } + .frame(height: 16) + Text(ciDuration(j.medianSeconds)).font(.ui(size: 11)).monospacedDigit().frame(width: 50, alignment: .trailing) + if j.failed > 0 { + Text("✕\(j.failed)").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.err).frame(width: 26, alignment: .trailing) + } else { + Color.clear.frame(width: 26) + } + } + .help("\(j.name): median \(ciDuration(j.medianSeconds)), slowest 10% \(ciDuration(j.p90Seconds)), failed \(j.failed) of \(j.runs)") + .accessibilityElement(children: .ignore) + .accessibilityLabel("\(j.name): median \(ciDuration(j.medianSeconds)), slowest tenth \(ciDuration(j.p90Seconds)), failed \(j.failed) of \(j.runs)") + } + if s.jobsPending > 0 { + Text("Reading the jobs of \(s.jobsPending) more run\(s.jobsPending == 1 ? "" : "s")…") + .font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + } + } +} + +private struct Flaky: View { + @Environment(\.conchTheme) private var look + let items: [CIFlaky] + + var body: some View { + let _ = look + CISection(title: "Flaky", note: "failed, then passed with nothing changed") { + ForEach(items.prefix(6), id: \.name) { f in + VStack(alignment: .leading, spacing: 1) { + HStack { + Text(f.name).font(.ui(size: 11.5, design: .monospaced)).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 6) + Text("\(f.times)×").font(.ui(size: 11, weight: .semibold)).foregroundStyle(Theme.warn) + } + Text([f.how ?? "", f.last.map { agoText($0) } ?? ""].filter { !$0.isEmpty }.joined(separator: " · ")) + .font(.ui(size: 10.5)).foregroundStyle(Theme.muted).lineLimit(1) + } + .accessibilityElement(children: .combine) + } + } + } +} + +/// The failures that can be run again: each workflow's newest run on a +/// branch, where it failed. +private struct Failing: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let runs: [CIRun] + + var body: some View { + let _ = look + CISection(title: "Failing now", note: "the newest run of each workflow, per branch") { + ForEach(runs.prefix(8)) { r in + HStack(spacing: 8) { + Circle().fill(Theme.err).frame(width: 7, height: 7) + VStack(alignment: .leading, spacing: 1) { + Text("\(r.workflow) · \(r.branch ?? "")").font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + Text([r.conclusion == "timed_out" ? "timed out" : "failed", (r.attempt ?? 1) > 1 ? "attempt \(r.attempt ?? 1)" : "", + r.at.map { agoText($0) } ?? ""].filter { !$0.isEmpty }.joined(separator: " · ")) + .font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + Spacer(minLength: 4) + if let u = r.url, let url = URL(string: u) { + Button { NSWorkspace.shared.open(url) } label: { LucideIcon("globe", color: Theme.muted, size: 11).padding(3).contentShape(Rectangle()) } + .buttonStyle(.plain).help("Open the run on GitHub").accessibilityLabel("Open the run on GitHub") + } + if model.canRerun { + let busy = model.rerunning[r.id] == (r.attempt ?? 1) + Button(busy ? "Re-running…" : "Re-run failed jobs") { model.rerun(run: r.id, attempt: r.attempt ?? 1) } + .controlSize(.small).disabled(busy) + .help("Runs this run's failed jobs again on GitHub, as a new attempt") + } + } + } + } + } +} diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index d63aa05c..60093a64 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -44,6 +44,16 @@ final class CommitsModel: ObservableObject { @Published var owners: [String: String] = [:] /// A branch picked in the side's list: the rest of the graph dims. @Published var focusOn: String? + /// The CI panel in place of the commit's, and what it shows. + @Published var showCI = false + @Published var ci: CIStats? + @Published var ciDays = 14 + @Published var ciError = "" + @Published var ciLoading = false + /// Runs asked to start again, by run id, with the attempt that failed: + /// the button says so until a later attempt shows up. + @Published var rerunning: [Int64: Int] = [:] + private var ciReads = Latest() /// The graph's search: commits that do not match are dimmed, never /// taken out, so the lanes stay whole. @Published var query = "" @@ -99,6 +109,67 @@ final class CommitsModel: ObservableObject { store.askToResolve(machine: machine, project: project, branch: b, start: start) } + var canCI: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.stats.v1") == true } + var canRerun: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.rerun.v1") == true } + + /// The project's CI over ciDays. A busy repository's job times arrive + /// a few dozen runs at a time, so while the server says some are still + /// to read it is asked again, a few times. + func loadCI(again: Int = 0) { + guard let c = store.connection(machine) else { return } + guard canCI else { + ciError = "conch on \(store.label(machine)) is older than this app and can't add up CI: reload its server." + return + } + struct P: Encodable { var project_id: String; var days: Int } + ciLoading = true + let n = ciReads.next() + let days = ciDays + Task { + do { + let s = try await c.call("ci.stats", P(project_id: project, days: days), as: CIStats.self) + guard ciReads.isLatest(n) else { return } + ci = s + ciError = "" + ciLoading = false + if s.jobsPending > 0 && again < 4 { + try? await Task.sleep(for: .milliseconds(500)) + if ciReads.isLatest(n) && showCI { loadCI(again: again + 1) } + } + } catch { + guard ciReads.isLatest(n) else { return } + ciLoading = false + ciError = "\(error)" + } + } + } + + /// Runs a failed run's failed jobs again — the run named, or a branch's + /// newest failed one — and reads CI again once GitHub has it. + func rerun(run: Int64? = nil, attempt: Int = 1, branch: String? = nil) { + guard let c = store.connection(machine) else { return } + guard canRerun else { + store.error = "conch on \(store.label(machine)) is too old to re-run CI: reload its server" + return + } + struct P: Encodable { var project_id: String; var run_id: Int64?; var branch: String? } + struct R: Decodable { var run_id: Int64 } + if let run { rerunning[run] = attempt } + Task { + do { + let r = try await c.call("ci.rerun", P(project_id: project, run_id: run, branch: branch), as: R.self) + if run == nil { rerunning[r.run_id] = attempt } + store.say("Running the failed jobs again" + (branch.map { " on \($0)" } ?? "")) + store.refreshProject(machine: machine, project: project) + try? await Task.sleep(for: .seconds(4)) + if showCI { loadCI() } + } catch { + if let run { rerunning[run] = nil } + store.error = "Could not re-run CI: \(error)" + } + } + } + func handToAgent(_ c: LogCommit) { store.handCommit(machine: machine, project: project, hash: c.hash, subject: c.subject) } @@ -237,12 +308,16 @@ struct CommitsView: View { var body: some View { HStack(spacing: 0) { - if showBranches { + // The CI panel takes the room the branch list had. + if showBranches && !model.showCI { BranchSide(model: model, store: store).frame(minWidth: 180, idealWidth: 228, maxWidth: 228) Rectangle().fill(Theme.line).frame(width: 1) } graph.frame(minWidth: 320) - if model.selected != nil { + if model.showCI { + Rectangle().fill(Theme.line).frame(width: 1) + CIPanel(model: model).frame(minWidth: 300, idealWidth: 380, maxWidth: 380) + } else if model.selected != nil { Rectangle().fill(Theme.line).frame(width: 1) CommitDetailPanel(model: model, store: store).frame(minWidth: 260, idealWidth: 340, maxWidth: 340) } @@ -301,11 +376,13 @@ struct CommitsView: View { var header: some View { let name = store.snapshots[model.machine]?.project(model.project)?.name ?? model.project return HStack(spacing: 10) { - Button { showBranches.toggle() } label: { - LucideIcon("panel-left", color: showBranches ? Theme.accent : Theme.muted, size: 13).padding(3).contentShape(Rectangle()) + if !model.showCI { + Button { showBranches.toggle() } label: { + LucideIcon("panel-left", color: showBranches ? Theme.accent : Theme.muted, size: 13).padding(3).contentShape(Rectangle()) + } + .buttonStyle(.plain).help(showBranches ? "Hide the agents' branches" : "Show the agents' branches") + .accessibilityLabel(showBranches ? "Hide the agents' branches" : "Show the agents' branches") } - .buttonStyle(.plain).help(showBranches ? "Hide the agents' branches" : "Show the agents' branches") - .accessibilityLabel(showBranches ? "Hide the agents' branches" : "Show the agents' branches") LucideIcon("git-commit-horizontal", color: Theme.accent, size: 14) Text("Commits").font(.ui(size: 13, weight: .semibold)).fixedSize() Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2).lineLimit(1).layoutPriority(-1) @@ -333,6 +410,24 @@ struct CommitsView: View { if model.selected == nil { Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1).layoutPriority(-2) } + if model.canCI { + Button { + model.showCI.toggle() + if model.showCI { model.loadCI() } + } label: { + HStack(spacing: 4) { + LucideIcon("zap", color: model.showCI ? Theme.accent : Theme.muted, size: 11) + Text("CI").font(.ui(size: 11.5, weight: .semibold)).foregroundStyle(model.showCI ? Theme.accent : Theme.text2) + } + .padding(.horizontal, 7).frame(height: 22) + .background(RoundedRectangle(cornerRadius: 6).fill(model.showCI ? Theme.accent.opacity(0.16) : .clear)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(model.showCI ? Theme.accent.opacity(0.5) : Theme.line)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain).fixedSize() + .help(model.showCI ? "Back to the commit" : "The project's CI: pass rate, run times, slow and flaky jobs, failures to run again") + .accessibilityLabel(model.showCI ? "Hide CI" : "Show CI") + } Button { model.refresh() } label: { LucideIcon("refresh-cw", size: 12).padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).fixedSize().help("Read the history again, and its pull requests from GitHub") } .padding(.horizontal, 12).frame(height: 40) @@ -402,6 +497,9 @@ struct CommitRow: View { Button("Copy Hash") { copy(c.hash) } Button("Copy Subject") { copy(c.subject) } Button("Hand to an Agent…") { model.handToAgent(c) } + if let o = owner, o.state == .ciFailing, tip, model.canRerun { + Button("Re-run Failed Jobs") { model.rerun(branch: o.name) } + } if let o = owner, o.state.conflicts { Button("Ask \(o.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(o) } } @@ -764,6 +862,9 @@ struct BranchSideRow: View { if branch.state.conflicts { Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(branch) } } + if branch.state == .ciFailing, model.canRerun { + Button("Re-run Failed Jobs") { model.rerun(branch: branch.name) } + } Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: branch.name) } } } diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 7c1805c2..2b3b16fe 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,7 +127,7 @@ A web page in a tab beside the agents. ## Commits -The project's history, its agents' branches and their conflicts. +The project's history, its agents' branches, conflicts and **CI**. **How:** **Commit Graph** on a project's or branch's menu. From 56f61c696d5b07cf7d96d7d5c5f955ee3e514b71 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:44:16 -0800 Subject: [PATCH 22/35] Keep what the autopilot did: autopilot.activity The autopilot announced each thing it did (autopilot.note) to whoever was connected and kept nothing, so what it did overnight was in the server's log and nowhere a person looks. Every note now carries its kind (ci, check, ship, merge, resolve, intake, triage) and its time, and is kept: appended a line each to autopilot-activity.jsonl so a restart or a reload keeps them, the newest 500, the file rewritten through a rename once it doubles. A cut-short line loses itself and nothing else. autopilot.activity lists them, newest first, for one project or all (capability autopilot.activity.v1). Intake taking an issue and triage reading one and its verdict only went to the log; they are notes now too. Co-Authored-By: Claude Opus 5.5 --- internal/proto/autopilot.go | 29 ++++++ internal/proto/proto.go | 11 +- internal/server/activity.go | 146 +++++++++++++++++++++++++++ internal/server/activity_test.go | 107 ++++++++++++++++++++ internal/server/autopilot.go | 24 +++-- internal/server/autopilot_resolve.go | 5 +- internal/server/autopilot_ship.go | 14 +-- internal/server/intake.go | 2 + internal/server/server.go | 7 ++ internal/server/triage.go | 6 ++ web/src/app/docs/protocol/page.mdx | 1 + 11 files changed, 332 insertions(+), 20 deletions(-) create mode 100644 internal/server/activity.go create mode 100644 internal/server/activity_test.go diff --git a/internal/proto/autopilot.go b/internal/proto/autopilot.go index 1872575d..5519db44 100644 --- a/internal/proto/autopilot.go +++ b/internal/proto/autopilot.go @@ -3,6 +3,7 @@ package proto import ( "fmt" "strings" + "time" "github.com/charmbracelet/x/ansi" ) @@ -105,6 +106,34 @@ type AutopilotNote struct { Text string `json:"text"` Error bool `json:"error,omitempty"` Merged bool `json:"merged,omitempty"` + // Kind is what the autopilot was doing (an Activity… word) and At + // when; both absent from an older server. + Kind string `json:"kind,omitempty"` + At time.Time `json:"at,omitempty"` +} + +// What a note is about, for the activity feed to group and mark. +const ( + ActivityCI = "ci" // a failed CI run sent to the agent, or not + ActivityCheck = "check" // the project's own check + ActivityShip = "ship" // pushed, a pull request opened or marked ready + ActivityMerge = "merge" // merged, or held back from merging + ActivityResolve = "resolve" // a conflict with the base rebased or sent to the agent + ActivityIntake = "intake" // an issue taken as a task + ActivityTriage = "triage" // an issue read and labelled +) + +// AutopilotActivityParams asks for what the autopilot did, newest first: +// in one project, or everywhere when ProjectID is empty; Limit at most +// (100 when 0). +type AutopilotActivityParams struct { + ProjectID string `json:"project_id,omitempty"` + Limit int `json:"limit,omitempty"` +} + +// AutopilotActivity is the autopilot's notes, newest first. +type AutopilotActivity struct { + Notes []AutopilotNote `json:"notes"` } // A failure sent to an agent is bounded: enough of the end of the output diff --git a/internal/proto/proto.go b/internal/proto/proto.go index 97e38dcc..de15916e 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, CapAutopilotActivity, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -225,6 +225,10 @@ const CapWorktreeSetup = "worktree.setup.v1" // read through gh on the machine the branch is on, for handing to its agent. const CapBranchCILog = "branch.ci_log.v1" +// CapAutopilotActivity is autopilot.activity: what the autopilot did, +// kept by the server across restarts, and each note's kind and time. +const CapAutopilotActivity = "autopilot.activity.v1" + // CapCIStats is ci.stats: a project's GitHub Actions history over a // period of days, added up for the CI panel — pass rate, run and queue // times, runs per day, each job's time, flaky jobs, failures to re-run. @@ -634,7 +638,10 @@ const ( // newest failed GitHub Actions run (CapBranchCILog). MethodBranchCILog = "branch.ci_log" // MethodCIStats adds up a project's GitHub Actions runs (CapCIStats). - MethodCIStats = "ci.stats" + // MethodAutopilotActivity lists what the autopilot did + // (CapAutopilotActivity). + MethodAutopilotActivity = "autopilot.activity" + MethodCIStats = "ci.stats" // MethodCIRerun runs a failed run's failed jobs again (CapCIRerun). MethodCIRerun = "ci.rerun" // Leftover worktrees: list what each would lose, and remove them. diff --git a/internal/server/activity.go b/internal/server/activity.go new file mode 100644 index 00000000..f13fde96 --- /dev/null +++ b/internal/server/activity.go @@ -0,0 +1,146 @@ +package server + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "log" + "os" + "path/filepath" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// The autopilot's activity: every note it makes, kept so the person can +// see later what it did while nobody was looking — which is the point of +// an autopilot. Notes are appended a line each to a file in the config +// directory, so a restart or a reload keeps them, and the file is +// rewritten to the newest activityMax once it is twice that. + +const ( + activityFile = "autopilot-activity.jsonl" + activityMax = 500 + // activityDefault is how many a list gives when not told. + activityDefault = 100 +) + +type activityLog struct { + file string + + mu sync.Mutex + notes []proto.AutopilotNote // oldest first + lines int // lines in the file + // needNL is a file whose last line was cut short: the next line + // written starts a line of its own rather than finishing that one. + needNL bool +} + +func loadActivity(configDir string) *activityLog { + l := &activityLog{file: filepath.Join(configDir, activityFile)} + raw, err := os.ReadFile(l.file) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + log.Printf("autopilot activity: %v", err) + } + return l + } + l.needNL = len(raw) > 0 && raw[len(raw)-1] != '\n' + sc := bufio.NewScanner(bytes.NewReader(raw)) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + l.lines++ + var n proto.AutopilotNote + if json.Unmarshal(sc.Bytes(), &n) == nil { + l.notes = append(l.notes, n) + } + } + if len(l.notes) > activityMax { + l.notes = l.notes[len(l.notes)-activityMax:] + } + return l +} + +// add keeps a note, stamped now unless it has a time, and returns it. +func (l *activityLog) add(n proto.AutopilotNote) proto.AutopilotNote { + if n.At.IsZero() { + n.At = time.Now() + } + l.mu.Lock() + defer l.mu.Unlock() + l.notes = append(l.notes, n) + if len(l.notes) > activityMax { + l.notes = append([]proto.AutopilotNote(nil), l.notes[len(l.notes)-activityMax:]...) + } + line, err := json.Marshal(n) + if err != nil { + return n + } + if l.lines+1 > 2*activityMax { + l.rewriteLocked() + return n + } + f, err := os.OpenFile(l.file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + log.Printf("autopilot activity: %v", err) + return n + } + defer f.Close() + if l.needNL { + line = append([]byte("\n"), line...) + } + if _, err := f.Write(append(line, '\n')); err != nil { + log.Printf("autopilot activity: %v", err) + return n + } + l.needNL = false + l.lines++ + return n +} + +// rewriteLocked writes the notes kept, and only those, through a file +// moved into place, so a crash leaves the old file or the new one. +func (l *activityLog) rewriteLocked() { + var b bytes.Buffer + for _, n := range l.notes { + if line, err := json.Marshal(n); err == nil { + b.Write(line) + b.WriteByte('\n') + } + } + tmp := l.file + ".tmp" + if err := os.WriteFile(tmp, b.Bytes(), 0o600); err != nil { + log.Printf("autopilot activity: %v", err) + return + } + if err := os.Rename(tmp, l.file); err != nil { + log.Printf("autopilot activity: %v", err) + return + } + l.lines, l.needNL = len(l.notes), false +} + +// list is the newest notes first, of one project or of all of them. +func (l *activityLog) list(projectID string, limit int) []proto.AutopilotNote { + switch { + case limit <= 0: + limit = activityDefault + case limit > activityMax: + limit = activityMax + } + l.mu.Lock() + defer l.mu.Unlock() + out := []proto.AutopilotNote{} + for i := len(l.notes) - 1; i >= 0 && len(out) < limit; i-- { + if projectID == "" || l.notes[i].ProjectID == projectID { + out = append(out, l.notes[i]) + } + } + return out +} + +func (s *Server) autopilotActivity(p proto.AutopilotActivityParams) proto.AutopilotActivity { + return proto.AutopilotActivity{Notes: s.autopilot.activity.list(p.ProjectID, p.Limit)} +} diff --git a/internal/server/activity_test.go b/internal/server/activity_test.go new file mode 100644 index 00000000..9d8d0aee --- /dev/null +++ b/internal/server/activity_test.go @@ -0,0 +1,107 @@ +package server + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// What the autopilot did is kept, newest first, each with when it was and +// what kind of thing it was; asked for by project, a project gets its own. +func TestActivityKept(t *testing.T) { + dir := t.TempDir() + l := loadActivity(dir) + before := time.Now() + l.add(proto.AutopilotNote{ProjectID: "a", Branch: "x", Kind: proto.ActivityCI, Text: "one"}) + l.add(proto.AutopilotNote{ProjectID: "b", Branch: "y", Kind: proto.ActivityMerge, Text: "two", Merged: true}) + l.add(proto.AutopilotNote{ProjectID: "a", Branch: "z", Kind: proto.ActivityResolve, Text: "three", Error: true}) + got := l.list("a", 0) + if len(got) != 2 || got[0].Text != "three" || got[1].Text != "one" { + t.Fatalf("project a: %+v", got) + } + if got[0].At.Before(before) || got[0].Kind != proto.ActivityResolve || !got[0].Error { + t.Errorf("stamped: %+v", got[0]) + } + if all := l.list("", 0); len(all) != 3 || all[0].Text != "three" { + t.Errorf("every project: %+v", all) + } + if one := l.list("", 1); len(one) != 1 || one[0].Text != "three" { + t.Errorf("limit 1: %+v", one) + } + // A restart keeps it. + again := loadActivity(dir).list("b", 0) + if len(again) != 1 || !again[0].Merged || again[0].Kind != proto.ActivityMerge { + t.Fatalf("after a restart: %+v", again) + } +} + +// The log is bounded in memory and on disk, and the newest stay. +func TestActivityCapped(t *testing.T) { + dir := t.TempDir() + l := loadActivity(dir) + for i := range activityMax*2 + 10 { + l.add(proto.AutopilotNote{ProjectID: "a", Text: fmt.Sprint(i)}) + } + got := l.list("", activityMax+50) + if len(got) != activityMax || got[0].Text != fmt.Sprint(activityMax*2+9) { + t.Fatalf("kept %d, newest %q", len(got), got[0].Text) + } + raw, _ := os.ReadFile(filepath.Join(dir, activityFile)) + if n := strings.Count(string(raw), "\n"); n > activityMax*2 { + t.Errorf("%d lines on disk", n) + } + if again := loadActivity(dir).list("", activityMax); len(again) != activityMax || again[0].Text != got[0].Text { + t.Errorf("reloaded %d, newest %q", len(again), again[0].Text) + } +} + +// A damaged line — a write cut short, a hand edit — loses that line and +// nothing else; a missing file is an empty log. +func TestActivityDamagedFile(t *testing.T) { + dir := t.TempDir() + if got := loadActivity(dir).list("", 0); len(got) != 0 { + t.Fatalf("no file: %+v", got) + } + good := `{"project_id":"a","branch":"x","text":"kept","at":"2026-11-14T10:00:00Z"}` + os.WriteFile(filepath.Join(dir, activityFile), []byte(good+"\n{\"project_id\":\"a\",\"tex\n"+good+"\n"), 0o600) + l := loadActivity(dir) + if got := l.list("a", 0); len(got) != 2 || got[0].Text != "kept" { + t.Fatalf("damaged: %+v", got) + } + // Writing on after a damaged line starts a line of its own. + l.add(proto.AutopilotNote{ProjectID: "a", Text: "new"}) + if got := loadActivity(dir).list("a", 0); len(got) != 3 || got[0].Text != "new" { + t.Errorf("after writing on: %+v", got) + } +} + +// The autopilot's own notes land in the log with their kind: a pull +// request held, then merged. +func TestActivityFromTheAutopilot(t *testing.T) { + s, p := afterFixture(t) + quietPRs(t, p) + fakeMergeGH(t) + s.autopilot.set(proto.AutopilotPolicy{AutoMerge: true}) + head := apBranch(t, p, "feat") + apPR(s, p, "feat", proto.PRInfo{Number: 5, Checks: "pending", Draft: true, Head: head}) + apPR(s, p, "feat", proto.PRInfo{Number: 5, Checks: "pass", Draft: true, Head: head}) + p.mu.Lock() + pr := p.prs["feat"] + pr.Draft = false + p.prs["feat"] = pr + p.mu.Unlock() + s.autopilotMerges() + a5WaitFor(t, "the merge in the log", func() bool { + got := s.autopilotActivity(proto.AutopilotActivityParams{ProjectID: p.id}).Notes + return len(got) >= 2 && got[0].Merged && got[0].Kind == proto.ActivityMerge && got[0].Branch == "feat" + }) + got := s.autopilotActivity(proto.AutopilotActivityParams{ProjectID: p.id}).Notes + if !strings.Contains(got[1].Text, "draft") || got[1].Kind != proto.ActivityMerge { + t.Errorf("the hold: %+v", got[1]) + } +} diff --git a/internal/server/autopilot.go b/internal/server/autopilot.go index 4660dbd1..00d6e0a8 100644 --- a/internal/server/autopilot.go +++ b/internal/server/autopilot.go @@ -40,6 +40,8 @@ const autopilotTick = 5 * time.Second type autopilot struct { file string + // activity is every note made, kept across restarts. + activity *activityLog mu sync.Mutex saved autopilotFile @@ -158,7 +160,7 @@ func loadAutopilot(configDir string) *autopilot { a := &autopilot{file: filepath.Join(configDir, "autopilot.json"), merging: map[string]bool{}, shipping: map[string]bool{}, unshipped: map[string]string{}, lastCheck: map[string]string{}, resolving: map[string]bool{}, starting: map[string]bool{}, capSaid: map[string]bool{}, recheck: map[string]bool{}, reship: map[string]bool{}, - gateMemo: map[string]gateResult{}, said: map[string]string{}} + gateMemo: map[string]gateResult{}, said: map[string]string{}, activity: loadActivity(configDir)} raw, err := os.ReadFile(a.file) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Printf("autopilot: %v", err) @@ -537,7 +539,7 @@ func (a *autopilot) checked(key, head string, passed bool) { // note tells every client what the autopilot did, and the log. func (s *Server) autopilotNote(n proto.AutopilotNote) { log.Printf("autopilot: %s %s: %s", n.ProjectID, n.Branch, n.Text) - s.broadcast(proto.EventAutopilotNote, n) + s.broadcast(proto.EventAutopilotNote, s.autopilot.activity.add(n)) } // autopilotPrompt is a message from the autopilot to an agent. @@ -656,6 +658,10 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin if s.autopilot.policy().AutoFix <= 0 { return } + kind := proto.ActivityCheck + if what == "CI" { + kind = proto.ActivityCI + } agent := s.freeAgent(projectID, branch) if agent == nil { if waiting := s.busyAgent(projectID, branch); waiting != nil && what == "CI" { @@ -667,7 +673,7 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin s.autopilot.saveLocked() s.autopilot.mu.Unlock() if !already { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: kind, Text: fmt.Sprintf("CI failed on %s; it goes to %s once it is free", branch, waiting.DisplayName())}) } } @@ -676,7 +682,7 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin ci := what == "CI" ok, capped, limit := s.autopilot.takeFix(key, ci) if capped { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: kind, Text: fmt.Sprintf("%s failed on %s again; auto_fix tried %d times, so it's yours now", what, branch, limit)}) } if !ok { @@ -692,11 +698,11 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin } if err != nil { s.autopilot.giveBack(key, ci) - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: kind, Text: fmt.Sprintf("%s failed on %s, and could not go to %s: %v", what, branch, agent.DisplayName(), err)}) return } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: kind, Text: fmt.Sprintf("%s failed on %s: sent it to %s to fix", what, branch, agent.DisplayName())}) }() } @@ -843,7 +849,7 @@ func (s *Server) autopilotMerge(key string) { a.saveLocked() } a.mu.Unlock() - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityMerge, Text: fmt.Sprintf("%s is green but not merged: %s", branch, why)}) } return @@ -866,11 +872,11 @@ func (s *Server) autopilotMerge(key string) { a.saveLocked() a.mu.Unlock() if perr != nil { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityMerge, Text: fmt.Sprintf("#%d is green but GitHub would not merge it: %s", pr.Number, perr.Message)}) return } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Merged: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Merged: true, Kind: proto.ActivityMerge, Text: fmt.Sprintf("merged #%d on GitHub (%s), green", pr.Number, res.Method)}) }() } diff --git a/internal/server/autopilot_resolve.go b/internal/server/autopilot_resolve.go index 35a050a4..6284d1e5 100644 --- a/internal/server/autopilot_resolve.go +++ b/internal/server/autopilot_resolve.go @@ -204,7 +204,8 @@ func (s *Server) noteOnce(key, what, text string, isErr bool) { return } projectID, branch, _ := strings.Cut(key, "\x00") - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text, Error: isErr}) + kind := map[string]string{"check": proto.ActivityCheck, "ready": proto.ActivityShip, "resolve": proto.ActivityResolve}[what] + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text, Error: isErr, Kind: kind}) } // unsay forgets the last thing said about a branch's what, so it is said @@ -338,7 +339,7 @@ func (s *Server) shipRewrite(p *project, branch, dir string, rw rewrite, prNumbe a.mu.Unlock() s.projects.request(p) s.projects.requestPRs(p) - s.autopilotNote(proto.AutopilotNote{ProjectID: p.id, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: p.id, Branch: branch, Kind: proto.ActivityResolve, Text: fmt.Sprintf("pushed %s, rebased onto %s, to #%d", branch, rw.Base, prNumber)}) return "" } diff --git a/internal/server/autopilot_ship.go b/internal/server/autopilot_ship.go index acb8d240..f9bb1c45 100644 --- a/internal/server/autopilot_ship.go +++ b/internal/server/autopilot_ship.go @@ -217,9 +217,9 @@ func (s *Server) autopilotCheckDone(key, head, cmd string, info proto.PaneInfo, return } if info.ExitCode == 0 { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: "check passed on " + branch}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityCheck, Text: "check passed on " + branch}) } else { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityCheck, Text: fmt.Sprintf("check failed on %s (exit %d) — its terminal has the output", branch, info.ExitCode)}) } s.autopilotCheckEnded(p, proto.AutopilotCheck{ProjectID: projectID, Branch: branch, Pane: info.ID, Command: cmd, Exit: info.ExitCode}, output, head) @@ -270,7 +270,7 @@ func (s *Server) autopilotShip(projectID, branch string) { } a.mu.Unlock() if why != "" && why != was { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: branch + " is finished but not pushed: " + why}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: branch + " is finished but not pushed: " + why}) } } @@ -364,7 +364,7 @@ func (s *Server) ship(projectID, branch string) string { if _, perr := s.projects.pushBranch(proto.BranchPushParams{ProjectID: projectID, Branch: branch}); perr != nil { return "pushing it failed: " + perr.Message } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: fmt.Sprintf("pushed %s to #%d", branch, pr.Number)}) } return s.markReady(p, projectID, branch, wt.Path, info.Base, wt.Head, *pr) @@ -389,7 +389,7 @@ func (s *Server) ship(projectID, branch string) string { a.mu.Unlock() text += " as a draft, since " + strings.Join(unmet, " and ") + "; it is marked ready once that changes" } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: text}) } return "" } @@ -432,7 +432,7 @@ func (s *Server) markReady(p *project, projectID, branch, dir, base, head string a.mu.Unlock() s.unsay(key, "ready") s.projects.requestPRs(p) - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: fmt.Sprintf("marked #%d ready: what held it as a draft is met", pr.Number)}) return "" } @@ -533,7 +533,7 @@ func (s *Server) askForTest(projectID, branch string) { delete(a.saved.TestAsked, key) a.saveLocked() a.mu.Unlock() - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityShip, Text: "asking " + agent.DisplayName() + " for a test on " + branch + " failed: " + perr.Message}) } } diff --git a/internal/server/intake.go b/internal/server/intake.go index 7eae0a5d..1ad04fdd 100644 --- a/internal/server/intake.go +++ b/internal/server/intake.go @@ -223,6 +223,8 @@ func (s *Server) intakeProject(id, label string, wip int) { rec.Item = it.ID room-- log.Printf("intake: took #%d %q of %s (label %s)", is.Number, is.Title, info.Name, label) + s.autopilotNote(proto.AutopilotNote{ProjectID: id, Kind: proto.ActivityIntake, + Text: fmt.Sprintf("took #%d %s as a queued task (label %s)", is.Number, is.Title, label)}) msg := fmt.Sprintf("conch took this from the `%s` label: it is queued as a task, and starts once fewer than %d agents are busy in the project. Its pull request will say Fixes #%d.", label, wip, is.Number) if err := ghx.CommentIssue(ctx, p.root, is.Number, msg); err != nil { log.Printf("intake: comment on #%d: %v", is.Number, err) diff --git a/internal/server/server.go b/internal/server/server.go index 9784c868..ccf8e9bb 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1021,6 +1021,13 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { } return s.projects.changes(cp) + case proto.MethodAutopilotActivity: + ap, perr := decode[proto.AutopilotActivityParams](msg) + if perr != nil { + return nil, perr + } + return s.autopilotActivity(ap), nil + case proto.MethodCIStats: sp, perr := decode[proto.CIStatsParams](msg) if perr != nil { diff --git a/internal/server/triage.go b/internal/server/triage.go index 5d9ec3c5..23f93d6b 100644 --- a/internal/server/triage.go +++ b/internal/server/triage.go @@ -274,6 +274,8 @@ func (s *Server) triageStart(ctx context.Context, p *project, rec triageRecord, rec.Pane = pi.ID b.put(rec) log.Printf("triage: %s reads #%d %q of %s", agent, rec.Issue, rec.Title, info.Name) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, + Text: fmt.Sprintf("%s is reading #%d %s for triage", agent, rec.Issue, rec.Title)}) } // triageVerdict is what the agent writes. @@ -324,8 +326,12 @@ func (s *Server) triageFinish(p *project, rec triageRecord, label string, pol pr b.put(rec) if rec.Failed != "" { log.Printf("triage: #%d: %s; the issue is left as it was", rec.Issue, rec.Failed) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, Error: true, + Text: fmt.Sprintf("triage of #%d gave no verdict: %s; the issue is left as it was", rec.Issue, rec.Failed)}) } else { log.Printf("triage: #%d is %s", rec.Issue, rec.Verdict) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, + Text: fmt.Sprintf("triaged #%d %s: %s", rec.Issue, rec.Title, rec.Verdict)}) } } diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index 32d64e22..3da910e0 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -40,6 +40,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | | CI | `ci.stats` adds up a project's GitHub Actions runs over `days` (14 by default, 90 at most) and the same span before: runs, passes and failures, median run, queue and red-to-green times, runs per day, each job's median and slowest tenth, flaky jobs, and each workflow's newest failed run per branch; a few dozen runs' jobs are read per call and `jobs_pending` says how many are left (capability `ci.stats.v1`). `ci.rerun` runs a run's failed jobs again, by `run_id` or a `branch`'s newest failed run (capability `ci.rerun.v1`). Both go through `gh` on the project's machine | +| Autopilot activity | every `autopilot.note` the server sends carries its `kind` (`ci`, `check`, `ship`, `merge`, `resolve`, `intake`, `triage`) and `at`, and is kept — the newest 500, in `autopilot-activity.jsonl` beside the config, so a restart keeps them; `autopilot.activity` lists them newest first, for a `project_id` or every project, `limit` at most (100 by default) (capability `autopilot.activity.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | | Moving a worktree | `worktree.describe`, `worktree.pack`, `worktree.pack_read` on the machine it leaves; `worktree.have`, `fs.upload`, `worktree.unpack` and `project.clone` on the one it goes to (capability `worktree.move.v1`). The servers never talk to each other: the client carries the pack | | Sessions | `session.list`, `session.search`, `session.resume`, `session.share`, `session.delete`, `session.dismiss`; `session.export` and `session.share` with a `doc` hand a conversation to another machine (capability `session.handoff.v1`) | From ae28728ee6d210facad66ac94df1341165b8b4f1 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:48:00 -0800 Subject: [PATCH 23/35] ConchKit: the autopilot's notes, rules and branches for a feed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AutopilotNote decodes autopilot.activity (an older server's note, without kind or time, still reads) and says how the feed marks it: merged, failed, handed to an agent, or said. activityDays groups the notes by the person's day — Today, Yesterday, the date, then those an older server sent without a time under Earlier. AutopilotPolicy and AutopilotState read autopilot.get, and autopilotRules says the policy rule by rule for one project: its own check, intake and triage labels, not another project's. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchKit/AutopilotFeed.swift | 184 ++++++++++++++++++ .../ConchKitTests/AutopilotFeedTests.swift | 73 +++++++ 2 files changed, 257 insertions(+) create mode 100644 macos/Sources/ConchKit/AutopilotFeed.swift create mode 100644 macos/Tests/ConchKitTests/AutopilotFeedTests.swift diff --git a/macos/Sources/ConchKit/AutopilotFeed.swift b/macos/Sources/ConchKit/AutopilotFeed.swift new file mode 100644 index 00000000..43d246b1 --- /dev/null +++ b/macos/Sources/ConchKit/AutopilotFeed.swift @@ -0,0 +1,184 @@ +import Foundation + +// What the server's autopilot did and is set to do, for the commit +// graph's Autopilot panel: its notes (autopilot.activity) and its policy +// (autopilot.get). + +public struct AutopilotNote: Decodable, Equatable, Sendable { + public var projectID: String + public var branch: String? + public var text: String + public var error: Bool? + public var merged: Bool? + /// ci, check, ship, merge, resolve, intake or triage; nil from an + /// older server. + public var kind: String? + public var at: Date? + + enum CodingKeys: String, CodingKey { + case branch, text, error, merged, kind, at + case projectID = "project_id" + } + + public enum Tone: Equatable, Sendable { case done, failed, handed, info } + + /// How the feed marks it: a merge done, something that failed or was + /// refused, a failure handed to an agent to fix, anything else. + public var tone: Tone { + if merged == true { return .done } + if error == true { return .failed } + if (kind == "ci" || kind == "check" || kind == "resolve") && text.contains("sent it to") { return .handed } + if kind == "resolve" && text.contains(" to resolve") { return .handed } + return .info + } + + public var kindLabel: String { + switch kind { + case "ci": "CI" + case "check": "Check" + case "ship": "Push" + case "merge": "Merge" + case "resolve": "Conflict" + case "intake": "Intake" + case "triage": "Triage" + default: "" + } + } +} + +public struct AutopilotActivity: Decodable, Sendable { + public var notes: [AutopilotNote] +} + +/// One day of the feed, newest first. +public struct ActivityDay: Equatable, Sendable { + public var title: String + public var notes: [AutopilotNote] +} + +/// The notes grouped by the day they were made, in the person's calendar: +/// Today, Yesterday, then "Nov 10" — and notes an older server made +/// without a time, last, under Earlier. +public func activityDays(_ notes: [AutopilotNote], now: Date = Date(), calendar: Calendar = .current) -> [ActivityDay] { + var days: [ActivityDay] = [] + var undated: [AutopilotNote] = [] + let f = DateFormatter() + f.calendar = calendar + f.timeZone = calendar.timeZone + f.locale = Locale(identifier: "en_US_POSIX") + f.dateFormat = "MMM d" + for n in notes { + guard let at = n.at else { undated.append(n); continue } + let title: String + if calendar.isDate(at, inSameDayAs: now) { + title = "Today" + } else if let y = calendar.date(byAdding: .day, value: -1, to: now), calendar.isDate(at, inSameDayAs: y) { + title = "Yesterday" + } else { + title = f.string(from: at) + } + if days.last?.title == title { days[days.count - 1].notes.append(n) } else { days.append(ActivityDay(title: title, notes: [n])) } + } + if !undated.isEmpty { days.append(ActivityDay(title: "Earlier", notes: undated)) } + return days +} + +/// The server's autopilot settings (proto.AutopilotPolicy), as much of +/// them as the panel says. +public struct AutopilotPolicy: Decodable, Equatable, Sendable { + public var autoFix: Int? + public var autoMerge: Bool? + public var autoPR: Bool? + public var autoResolve: Int? + public var requireTests: Bool? + public var maxDiff: Int? + public var checks: [String: String]? + public var intake: [String: String]? + public var triage: [String: String]? + + enum CodingKeys: String, CodingKey { + case checks, intake, triage + case autoFix = "auto_fix", autoMerge = "auto_merge", autoPR = "auto_pr", autoResolve = "auto_resolve" + case requireTests = "require_tests", maxDiff = "max_diff" + } + + /// Whether it does anything on its own at all. + public var anyOn: Bool { + (autoFix ?? 0) > 0 || autoMerge == true || autoPR == true || (autoResolve ?? 0) > 0 + || !(checks ?? [:]).isEmpty || !(intake ?? [:]).isEmpty || !(triage ?? [:]).isEmpty + } +} + +/// A branch the autopilot is minding (proto.AutopilotBranch). +public struct AutopilotBranch: Decodable, Equatable, Sendable { + public var projectID: String + public var branch: String + public var fixes: Int? + public var waiting: Bool? + public var held: String? + public var checkFailed: Bool? + public var checking: String? + public var unshipped: String? + public var conflicting: Bool? + public var resolves: Int? + + enum CodingKeys: String, CodingKey { + case branch, fixes, waiting, held, checking, unshipped, conflicting, resolves + case projectID = "project_id", checkFailed = "check_failed" + } + + /// What it is waiting on, in a few words. + public var status: String { + if conflicting == true { return "conflicts with its base" + ((resolves ?? 0) > 0 ? " · asked \(resolves ?? 0)×" : "") } + if checking != nil { return "running the check" } + if checkFailed == true { return "check failed" } + if waiting == true { return held.map { "green, held: \($0)" } ?? "green, merging" } + if let u = unshipped { return "not pushed: \(u)" } + if (fixes ?? 0) > 0 { return "sent \(fixes ?? 0) failure\(fixes == 1 ? "" : "s") to fix" } + return "watching" + } +} + +public struct AutopilotState: Decodable, Sendable { + public var policy: AutopilotPolicy + public var branches: [AutopilotBranch]? +} + +/// One of the autopilot's rules as the panel says it. +public struct AutopilotRule: Equatable, Sendable { + public var on: Bool + public var text: String +} + +/// The policy said rule by rule, for a project: what goes back to the +/// agents, what is pushed and merged, and this project's check, intake +/// label and triage label. +public func autopilotRules(_ p: AutopilotPolicy, project: String) -> [AutopilotRule] { + let fix = p.autoFix ?? 0, resolve = p.autoResolve ?? 0 + var out = [ + AutopilotRule(on: fix > 0, text: fix > 0 ? "Failed CI and checks go back to the agent, \(fix) times at most" : "Failed CI and checks stay with you"), + AutopilotRule(on: resolve > 0, text: resolve > 0 ? "Conflicts with the base go to the agent, \(resolve) times at most" : "Conflicts with the base stay with you"), + AutopilotRule(on: p.autoPR == true, text: "Push finished branches and open their pull requests"), + AutopilotRule(on: p.autoMerge == true, text: "Merge pull requests when green"), + ] + if p.requireTests == true || (p.maxDiff ?? 0) > 0 { + var why: [String] = [] + if p.requireTests == true { why.append("without a test") } + if let m = p.maxDiff, m > 0 { why.append("over \(m) lines") } + out.append(AutopilotRule(on: true, text: "Pull requests " + why.joined(separator: " or ") + " stay drafts")) + } + if let c = p.checks?[project], !c.isEmpty { + out.append(AutopilotRule(on: true, text: "Check: \(c)")) + } else { + out.append(AutopilotRule(on: false, text: "No check for this project")) + } + if let l = p.intake?[project], !l.isEmpty { + out.append(AutopilotRule(on: true, text: "Issues with the label \(l) become queued tasks")) + } + if let l = p.triage?[project], !l.isEmpty { + out.append(AutopilotRule(on: true, text: "Triage issues labelled \(l)")) + } else { + out.append(AutopilotRule(on: false, text: "Triage: off for this project")) + } + return out +} diff --git a/macos/Tests/ConchKitTests/AutopilotFeedTests.swift b/macos/Tests/ConchKitTests/AutopilotFeedTests.swift new file mode 100644 index 00000000..ecabd133 --- /dev/null +++ b/macos/Tests/ConchKitTests/AutopilotFeedTests.swift @@ -0,0 +1,73 @@ +import Foundation +import Testing +@testable import ConchKit + +let activityJSON = #""" +{"notes":[ + {"project_id":"r1","branch":"conch/git3","text":"CI failed on conch/git3: sent it to claude-git3 to fix","kind":"ci","at":"2026-11-14T12:01:00Z"}, + {"project_id":"r1","branch":"conch/phone","text":"merged #234 on GitHub (squash), green","kind":"merge","merged":true,"at":"2026-11-14T11:55:00Z"}, + {"project_id":"r1","branch":"conch/graph","text":"#9 is green but GitHub would not merge it: conflict","kind":"merge","error":true,"at":"2026-11-13T18:00:00Z"}, + {"project_id":"r1","branch":"","text":"took #241 Fix the login as a queued task (label conch)","kind":"intake","at":"2026-11-10T09:12:00Z"}, + {"project_id":"r1","branch":"old","text":"from an older server"} +]} +"""# + +// The server's notes, newest first; one from an older server has no kind +// or time and still reads. +@Test func activityDecodes() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + #expect(a.notes.count == 5) + #expect(a.notes[1].merged == true && a.notes[1].kind == "merge") + #expect(a.notes[2].error == true) + #expect(a.notes[4].kind == nil && a.notes[4].at == nil) +} + +// How each note is marked: a merge done, a failure, something handed to +// an agent, the rest. +@Test func activityTones() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + #expect(a.notes[0].tone == .handed) + #expect(a.notes[1].tone == .done) + #expect(a.notes[2].tone == .failed) + #expect(a.notes[3].tone == .info) + #expect(a.notes[0].kindLabel == "CI") + #expect(a.notes[3].kindLabel == "Intake") + #expect(a.notes[4].kindLabel == "") +} + +// Grouped by day as the person's calendar has it: Today, Yesterday, then +// the date; a note without a time goes last, under Earlier. +@Test func activityByDay() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + var cal = Calendar(identifier: .gregorian) + cal.timeZone = TimeZone(identifier: "UTC")! + let now = ISO8601DateFormatter().date(from: "2026-11-14T15:00:00Z")! + let days = activityDays(a.notes, now: now, calendar: cal) + #expect(days.map(\.title) == ["Today", "Yesterday", "Nov 10", "Earlier"]) + #expect(days[0].notes.count == 2 && days[1].notes.count == 1) + #expect(activityDays([], now: now, calendar: cal).isEmpty) +} + +// The rules said in words, for the panel's top: what is on, and for this +// project its check, intake and triage labels. +@Test func autopilotRules() throws { + let p = try conchDecoder().decode(AutopilotPolicy.self, from: Data(#""" + {"auto_fix":3,"auto_merge":true,"auto_pr":false,"auto_resolve":2,"require_tests":true, + "checks":{"r1":"go test ./..."},"intake":{"r1":"conch"},"triage":{"r2":"triage"}} + """#.utf8)) + let lines = autopilotRules(p, project: "r1") + #expect(lines.first { $0.text.contains("Failed CI") }?.on == true) + #expect(lines.first { $0.text.contains("3 times") } != nil) + #expect(lines.first { $0.text.contains("Merge") }?.on == true) + #expect(lines.first { $0.text.contains("Push finished") }?.on == false) + #expect(lines.first { $0.text.contains("go test ./...") }?.on == true) + #expect(lines.first { $0.text.contains("label conch") }?.on == true) + #expect(lines.first { $0.text.contains("Triage") }?.on == false) + #expect(p.anyOn) + let off = try conchDecoder().decode(AutopilotPolicy.self, from: Data("{}".utf8)) + #expect(!off.anyOn) + #expect(autopilotRules(off, project: "r1").allSatisfy { !$0.on }) + // Another project's check and labels are not this one's. + #expect(autopilotRules(p, project: "r2").first { $0.text.hasPrefix("No check") }?.on == false) + #expect(autopilotRules(p, project: "r2").first { $0.text.contains("Triage") }?.on == true) +} From e7349642bcec8081c7b9cdb3d3103de2785fcb05 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 17:48:00 -0800 Subject: [PATCH 24/35] Conch.app: the autopilot's activity beside the commit graph MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Autopilot in the graph's header, a dot saying whether it is on, opens a panel in the CI panel's place: the rules it follows in this project, the branches it is minding and what each waits on, and what it did, a day at a time — each entry marked by kind and how it ended, its branch a link that brings that branch forward in the graph. It reads the server's kept history (autopilot.activity), so what happened while the app was closed is there, and reads it again whenever the server announces a note. An older server's lack of history is said. Co-Authored-By: Claude Opus 5.5 --- docs/testing/end-to-end.md | 1 + macos/Sources/ConchApp/AutopilotPanel.swift | 142 ++++++++++++++++++++ macos/Sources/ConchApp/CommitsView.swift | 75 ++++++++++- macos/Sources/ConchApp/Store.swift | 5 + web/src/app/docs/mac-app/page.mdx | 2 +- 5 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 macos/Sources/ConchApp/AutopilotPanel.swift diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index ec70e27b..0dfc9a97 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -416,6 +416,7 @@ What it carries, and what is left over in each row: | 9.174 🖥 | The Tickets window with real trackers | Conch.app with two projects with GitHub remotes, Linear set up for one (`[[trackers.projects]]`), a task queued for one issue, an agent working on another's branch, a third with an open PR. ⇧⌘I; try every view in the side, search, and each row's button. | Each project with its issues and tickets, yours marked; the queued, working and PR rows say so (with CI); Needs info counts needs-info and too-big; Task opens New Task in the main window with that issue or ticket picked; Agent focuses the agent; PR and Open open the browser. A project whose tracker fails says why and still lists its issues. An older server says to reload. | ☐ | | 9.175 💳🌐 | Conch.app's commit graph with agents | A project with Claude and Codex on task branches, one with an open pull request on a real GitHub repository and red CI, one whose change master then touches on the same lines; open **Commit Graph**. Rebase the second onto master by hand so it stops, then **Ask Codex to resolve**, and its menu's *Start a new agent* on another; **Hand to an Agent…** on an older commit; a SHA-256 reftable repository (`git init --object-format=sha256 --ref-format=reftable`) added as a project | Agents on branches lists both in urgency order with the right agent and ↑/↓; commits show their agent; the CI squares match GitHub; *will conflict* shows before anything moves, the banner when the rebase stops; the agent gets the files and resolves without pushing; the new task's branch starts at the commit; the header says **Git 3 · SHA-256 · reftable** | ☐ | | 9.176 🌐 | The CI panel against real GitHub Actions | On a project with a month of real Actions history and `gh` logged in: **Commit Graph** → **CI**, then 7d, 14d and 30d; on a busy repository watch *Reading the jobs of N more runs…* fill in; break a test on a branch, let its run fail, then **Re-run failed jobs** in the panel and **Re-run Failed Jobs** on the branch's menu | The numbers match GitHub's Actions page for the period (pass rate, the failing runs, a job's time); the re-run starts a new attempt of that run on GitHub, the button says *Re-running…* until the attempt shows, and the pull request's checks turn pending | ☐ | +| 9.177 💳🌐 | The autopilot's activity in Conch.app | With the autopilot on (auto_fix, auto_merge, auto_resolve, a check) for a real GitHub repository and a real agent on a task branch: open **Commit Graph** → **Autopilot** and leave it open; break a test so CI fails, let the agent fix it, let the pull request merge; then quit everything, reload the server, and open it again | Each step appears in *What it did* as it happens (CI sent to the agent, pushed, merged), marked by kind, under Today, with the branch a link to its commits; *Minding now* follows the branch; the rules match Settings; after the reload the feed is all still there | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/macos/Sources/ConchApp/AutopilotPanel.swift b/macos/Sources/ConchApp/AutopilotPanel.swift new file mode 100644 index 00000000..152f539c --- /dev/null +++ b/macos/Sources/ConchApp/AutopilotPanel.swift @@ -0,0 +1,142 @@ +import ConchKit +import SwiftUI + +// The commit graph's Autopilot panel: what the server's autopilot does on +// its own in this project (its rules), what it is minding now, and what +// it did — kept by the server (autopilot.activity), so it says what +// happened while nobody was looking, and read again as it happens. + +struct AutopilotPanel: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + @ObservedObject var store: Store + + var body: some View { + let _ = look + let on = model.autopilot?.policy.anyOn == true + let minding = (model.autopilot?.branches ?? []).filter { $0.projectID == model.project } + VStack(spacing: 0) { + HStack(spacing: 8) { + Text("Autopilot").font(.ui(size: 13.5, weight: .semibold)) + Text(on ? "On" : "Off").font(.ui(size: 10.5, weight: .semibold)) + .foregroundStyle(on ? Theme.ok : Theme.muted) + .padding(.horizontal, 7).padding(.vertical, 2) + .background(Capsule().fill((on ? Theme.ok : Theme.muted).opacity(0.15))) + Spacer(minLength: 4) + Button("Settings…") { store.openSettings("git") } + .controlSize(.small) + .help("Checks & autopilot: what it does on its own, for every project") + } + .padding(.horizontal, 14).frame(height: 52) + Rectangle().fill(Theme.line).frame(height: 1) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if let p = model.autopilot?.policy { + VStack(alignment: .leading, spacing: 5) { + ForEach(Array(autopilotRules(p, project: model.project).enumerated()), id: \.offset) { _, r in + HStack(alignment: .firstTextBaseline, spacing: 7) { + Text(r.on ? "✓" : "–").font(.ui(size: 11, weight: .bold)) + .foregroundStyle(r.on ? Theme.ok : Theme.muted).frame(width: 10) + Text(r.text).font(.ui(size: 12)).foregroundStyle(r.on ? Theme.text : Theme.muted) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + } + } + } + if !minding.isEmpty { + VStack(alignment: .leading, spacing: 6) { + Text("MINDING NOW").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + ForEach(minding, id: \.branch) { b in + Button { model.focus(branch: b.branch) } label: { + HStack(spacing: 8) { + Text(b.branch).font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 6) + Text(b.status).font(.ui(size: 11)).foregroundStyle(b.conflicting == true || b.checkFailed == true ? Theme.warn : Theme.text2) + .lineLimit(1).truncationMode(.tail) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain).help("Show \(b.branch) in the graph") + } + } + } + Feed(model: model) + } + .padding(14) + } + } + .background(Theme.side) + .onChange(of: store.autopilotTick[model.machine] ?? 0) { _, _ in model.loadAutopilot() } + } +} + +/// What it did, a day at a time, newest first. +private struct Feed: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + VStack(alignment: .leading, spacing: 10) { + Text("WHAT IT DID").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + if !model.activityError.isEmpty { + Text(model.activityError).font(.ui(size: 12)).foregroundStyle(Theme.err) + .fixedSize(horizontal: false, vertical: true) + } else if model.activity.isEmpty { + Text("Nothing yet. What the autopilot does on its own in this project — a failed check sent to an agent, a pull request opened or merged, a conflict handed back — shows here, and stays after a restart.") + .font(.ui(size: 12)).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true) + } + ForEach(activityDays(model.activity), id: \.title) { day in + VStack(alignment: .leading, spacing: 2) { + Text(day.title).font(.ui(size: 11.5, weight: .semibold)).foregroundStyle(Theme.text2).padding(.bottom, 4) + ForEach(Array(day.notes.enumerated()), id: \.offset) { _, n in Entry(model: model, note: n) } + } + } + } + } +} + +private struct Entry: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let note: AutopilotNote + + var body: some View { + let _ = look + let tone: Color = switch note.tone { + case .done: Theme.ok + case .failed: Theme.err + case .handed: Theme.work + case .info: Theme.muted + } + HStack(alignment: .top, spacing: 9) { + Text(note.at.map { Self.time.string(from: $0) } ?? "").font(.ui(size: 10.5)).monospacedDigit() + .foregroundStyle(Theme.muted).frame(width: 36, alignment: .leading).padding(.top, 1) + Circle().fill(tone).frame(width: 7, height: 7).padding(.top, 4) + VStack(alignment: .leading, spacing: 3) { + Text(note.text).font(.ui(size: 12)).foregroundStyle(Theme.text).fixedSize(horizontal: false, vertical: true) + HStack(spacing: 6) { + if !note.kindLabel.isEmpty { + Text(note.kindLabel).font(.ui(size: 10, weight: .semibold)).foregroundStyle(tone) + .padding(.horizontal, 5).padding(.vertical, 1) + .background(RoundedRectangle(cornerRadius: 3).fill(tone.opacity(0.14))) + } + if let b = note.branch, !b.isEmpty { + Button(b) { model.focus(branch: b) } + .buttonStyle(.link).font(.ui(size: 11)).lineLimit(1) + .help("Show \(b) in the graph") + } + } + } + } + .padding(.vertical, 5) + } + + static let time: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm" + return f + }() +} diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 60093a64..fec7dcff 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -44,8 +44,15 @@ final class CommitsModel: ObservableObject { @Published var owners: [String: String] = [:] /// A branch picked in the side's list: the rest of the graph dims. @Published var focusOn: String? - /// The CI panel in place of the commit's, and what it shows. - @Published var showCI = false + /// The CI panel or the autopilot's in place of the commit's — one at a + /// time — and what each shows. + @Published var showCI = false { didSet { if showCI { showAutopilot = false } } } + @Published var showAutopilot = false { didSet { if showAutopilot { showCI = false } } } + var sidePanel: Bool { showCI || showAutopilot } + @Published var activity: [AutopilotNote] = [] + @Published var autopilot: AutopilotState? + @Published var activityError = "" + private var activityReads = Latest() @Published var ci: CIStats? @Published var ciDays = 14 @Published var ciError = "" @@ -78,6 +85,7 @@ final class CommitsModel: ObservableObject { (machine, project) = parseCommitsKey(key) ?? ("local", "") load() store.refreshProject(machine: machine, project: project) + loadAutopilot() } /// ↻: the history again, and the server asked to look at GitHub now. @@ -109,6 +117,45 @@ final class CommitsModel: ObservableObject { store.askToResolve(machine: machine, project: project, branch: b, start: start) } + var canAutopilot: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.v1") == true } + var canActivity: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.activity.v1") == true } + + /// The autopilot's policy and the branches it minds, and what it did + /// in this project, newest first. + func loadAutopilot() { + struct NoParams: Encodable {} + guard let c = store.connection(machine), canAutopilot else { return } + let n = activityReads.next() + Task { + if let st = try? await c.call("autopilot.get", NoParams(), as: AutopilotState.self), activityReads.isLatest(n) { + autopilot = st + } + guard canActivity else { + activityError = "conch on \(store.label(machine)) keeps no record of what the autopilot did: reload its server." + return + } + struct P: Encodable { var project_id: String; var limit: Int } + do { + let a = try await c.call("autopilot.activity", P(project_id: project, limit: 200), as: AutopilotActivity.self) + guard activityReads.isLatest(n) else { return } + activity = a.notes + activityError = "" + } catch { + guard activityReads.isLatest(n) else { return } + activityError = "\(error)" + } + } + } + + /// Brings a branch into view: its commits stand out, its newest picked. + func focus(branch: String) { + focusOn = branch + if let tip = branchTips(rows.map(\.commit), remotes: remotes ?? ["origin", "upstream"])[branch] { + pick(tip, shift: false) + reveal += 1 + } + } + var canCI: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.stats.v1") == true } var canRerun: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.rerun.v1") == true } @@ -309,7 +356,7 @@ struct CommitsView: View { var body: some View { HStack(spacing: 0) { // The CI panel takes the room the branch list had. - if showBranches && !model.showCI { + if showBranches && !model.sidePanel { BranchSide(model: model, store: store).frame(minWidth: 180, idealWidth: 228, maxWidth: 228) Rectangle().fill(Theme.line).frame(width: 1) } @@ -317,6 +364,9 @@ struct CommitsView: View { if model.showCI { Rectangle().fill(Theme.line).frame(width: 1) CIPanel(model: model).frame(minWidth: 300, idealWidth: 380, maxWidth: 380) + } else if model.showAutopilot { + Rectangle().fill(Theme.line).frame(width: 1) + AutopilotPanel(model: model, store: store).frame(minWidth: 300, idealWidth: 380, maxWidth: 380) } else if model.selected != nil { Rectangle().fill(Theme.line).frame(width: 1) CommitDetailPanel(model: model, store: store).frame(minWidth: 260, idealWidth: 340, maxWidth: 340) @@ -376,7 +426,7 @@ struct CommitsView: View { var header: some View { let name = store.snapshots[model.machine]?.project(model.project)?.name ?? model.project return HStack(spacing: 10) { - if !model.showCI { + if !model.sidePanel { Button { showBranches.toggle() } label: { LucideIcon("panel-left", color: showBranches ? Theme.accent : Theme.muted, size: 13).padding(3).contentShape(Rectangle()) } @@ -410,6 +460,23 @@ struct CommitsView: View { if model.selected == nil { Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1).layoutPriority(-2) } + if model.canAutopilot { + let on = model.autopilot?.policy.anyOn == true + Button { model.showAutopilot.toggle(); if model.showAutopilot { model.loadAutopilot() } } label: { + HStack(spacing: 5) { + Circle().fill(on ? Theme.ok : Theme.muted).frame(width: 6, height: 6) + Text("Autopilot").font(.ui(size: 11.5, weight: .semibold)) + .foregroundStyle(model.showAutopilot ? Theme.accent : Theme.text2) + } + .padding(.horizontal, 7).frame(height: 22) + .background(RoundedRectangle(cornerRadius: 6).fill(model.showAutopilot ? Theme.accent.opacity(0.16) : .clear)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(model.showAutopilot ? Theme.accent.opacity(0.5) : Theme.line)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain).fixedSize() + .help(model.showAutopilot ? "Back to the commit" : "What the autopilot does on its own here, and what it did") + .accessibilityLabel(model.showAutopilot ? "Hide the autopilot" : "Show the autopilot, \(on ? "on" : "off")") + } if model.canCI { Button { model.showCI.toggle() diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index a6aa0501..f8121445 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -53,6 +53,9 @@ final class Store: ObservableObject { @Published var agents: [String: [AgentAvailability]] = [:] /// The task being written, while its sheet is up. @Published var taskDraft: TaskDraft? + /// Counts the autopilot's notes from each machine, so a feed showing + /// that machine's reads its list again when one arrives. + @Published var autopilotTick: [String: Int] = [:] /// The machines whose TUI tabs this launch has taken in. private var viewAdopted: Set = [] /// Files the palette's search found, for the query they were found for. @@ -1731,6 +1734,8 @@ final class Store: ObservableObject { terminals.removeValue(forKey: k)?.stop() defer { updateBadge() } questions.removeValue(forKey: k) + case "autopilot.note": + autopilotTick[machine, default: 0] += 1 case "project.updated": if let p = try? dec.decode(ProjectInfo.self, from: data) { // A project added since the connection was counted, or one diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 2b3b16fe..6c0ff62f 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,7 +127,7 @@ A web page in a tab beside the agents. ## Commits -The project's history, its agents' branches, conflicts and **CI**. +The project's history, agents' branches, conflicts, **CI** and **Autopilot**. **How:** **Commit Graph** on a project's or branch's menu. From 6e76d926da04da86df5ccc8926aae139fd4be79d Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 20:44:25 -0800 Subject: [PATCH 25/35] gitx: read a branch's newest rebase back from its reflog LastRebase finds a rebase that is the newest thing done to a branch (its tip before and after, and what it went onto); Rewritten pairs the old commits with the new through git range-diff, so the one whose conflict was resolved shows as changed; RewriteDiff is that diff of diffs; and UndoRebase puts the branch back while it has not moved on. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/rebased.go | 168 ++++++++++++++++++++++++++++++++++ internal/gitx/rebased_test.go | 144 +++++++++++++++++++++++++++++ 2 files changed, 312 insertions(+) create mode 100644 internal/gitx/rebased.go create mode 100644 internal/gitx/rebased_test.go diff --git a/internal/gitx/rebased.go b/internal/gitx/rebased.go new file mode 100644 index 00000000..44ea4589 --- /dev/null +++ b/internal/gitx/rebased.go @@ -0,0 +1,168 @@ +package gitx + +import ( + "context" + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +// A branch just rebased — by an agent asked to resolve a conflict, or by +// anybody — is a rewrite nobody has looked at yet: its commits are new +// ones, and the remote still has the old. What follows reads that rewrite +// back from the branch's reflog, so the person can see what the +// resolution changed, push it over the old one, or put the branch back. + +// Rebase is a branch's newest rebase: its tip before and after, and the +// commit it was put on. +type Rebase struct { + Branch string + Before, After string + Onto string + At time.Time +} + +// finished is the reflog's word for a rebase that ended: "rebase +// (finish): refs/heads/x onto ", "rebase -i (finish): …", and the +// "rebase finished: …" of older gits. +var finished = regexp.MustCompile(`^rebase\b.*\bfinish(?:ed)?\)?: refs/heads/(.+) onto ([0-9a-f]+)$`) + +// LastRebase is branch's rebase when that is the newest thing done to it, +// or nil: a commit, reset or push since and it is no longer news. +func LastRebase(ctx context.Context, dir, branch string) (*Rebase, error) { + ref := "refs/heads/" + branch + if CommitOf(ctx, dir, ref) == "" { + return nil, nil + } + out, err := run(ctx, dir, "reflog", "show", "--date=unix", "--format=%H%x00%gd%x00%gs", "-n", "2", ref, "--") + if err != nil { + return nil, nil // a branch without a reflog has no rebase to show + } + lines := strings.Split(strings.TrimSpace(string(out)), "\n") + if len(lines) < 2 { + return nil, nil + } + newest := strings.SplitN(lines[0], "\x00", 3) + prior := strings.SplitN(lines[1], "\x00", 3) + if len(newest) < 3 || len(prior) < 1 { + return nil, nil + } + m := finished.FindStringSubmatch(newest[2]) + if m == nil || m[1] != branch { + return nil, nil + } + r := &Rebase{Branch: branch, Before: prior[0], After: newest[0], Onto: m[2]} + // refs/heads/x@{1731600000} + if i := strings.LastIndex(newest[1], "@{"); i >= 0 { + if s, err := strconv.ParseInt(strings.TrimSuffix(newest[1][i+2:], "}"), 10, 64); err == nil { + r.At = time.Unix(s, 0) + } + } + if r.Before == r.After { + return nil, nil // already on top: nothing was rewritten + } + return r, nil +} + +// How a commit came through a rebase. +const ( + RewriteSame = "same" // the same change on a new parent + RewriteChanged = "changed" // its change is different: a conflict was resolved in it + RewriteDropped = "dropped" // gone: the base had it already, or it was left out + RewriteAdded = "added" // new in the rewrite +) + +// Rewrite is one commit before and after the rebase, by short hash. +type Rewrite struct { + Old, New string + Subject string + Change string +} + +// rangeLine is a header of git range-diff: "1: abc1234 ! 1: def5678 subject". +var rangeLine = regexp.MustCompile(`^\s*(?:\d+|-):\s+([0-9a-f]+|-+)\s+([<>=!])\s+(?:\d+|-):\s+([0-9a-f]+|-+)\s+(.*)$`) + +// Rewritten pairs the branch's commits before the rebase with those +// after, oldest first, saying of each whether its change is what it was. +// A commit whose conflict was resolved is the one that changed. +func Rewritten(ctx context.Context, dir string, r *Rebase) ([]Rewrite, error) { + // The old commits are those Before has and the base it was put on + // does not (the symmetric range's left side, as range-diff reads it). + mb, err := run(ctx, dir, "merge-base", r.Onto, r.Before) + if err != nil { + return nil, fmt.Errorf("%s and %s share no history", short(r.Onto), short(r.Before)) + } + out, err := run(ctx, dir, "range-diff", "--no-color", "--creation-factor=100", "-s", + strings.TrimSpace(string(mb))+".."+r.Before, r.Onto+".."+r.After) + if err != nil { + return nil, err + } + var cs []Rewrite + for _, l := range strings.Split(string(out), "\n") { + m := rangeLine.FindStringSubmatch(l) + if m == nil { + continue + } + c := Rewrite{Subject: m[4]} + if !strings.HasPrefix(m[1], "-") { + c.Old = m[1] + } + if !strings.HasPrefix(m[3], "-") { + c.New = m[3] + } + c.Change = map[string]string{"=": RewriteSame, "!": RewriteChanged, "<": RewriteDropped, ">": RewriteAdded}[m[2]] + cs = append(cs, c) + } + return cs, nil +} + +// cutNote ends a diff cut short. +const cutNote = "\n… (cut short)\n" + +// RewriteDiff is git range-diff's account of the rebase: for each commit +// that changed, the diff of its diff — what resolving the conflict did. +// Longer than max (when max > 0) and it is cut there. +func RewriteDiff(ctx context.Context, dir string, r *Rebase, max int) (string, error) { + mb, err := run(ctx, dir, "merge-base", r.Onto, r.Before) + if err != nil { + return "", fmt.Errorf("%s and %s share no history", short(r.Onto), short(r.Before)) + } + out, err := run(ctx, dir, "range-diff", "--no-color", "--creation-factor=100", + strings.TrimSpace(string(mb))+".."+r.Before, r.Onto+".."+r.After) + if err != nil { + return "", err + } + s := string(out) + if max > 0 && len(s) > max { + s = s[:max] + cutNote + } + return s, nil +} + +// UndoRebase puts branch back at before, in dir where it is checked out, +// if it is still at after and has nothing uncommitted: the rewrite stays +// in the reflog, so this too can be undone. +func UndoRebase(ctx context.Context, dir, branch, before, after string) error { + if err := readyToRebase(ctx, dir, branch); err != nil { + return err + } + if head, _ := revParse(ctx, dir, "HEAD"); head != after { + return fmt.Errorf("%s has moved on since the rebase (it is at %s now), so it is not undone", branch, short(head)) + } + if CommitOf(ctx, dir, before) == "" { + return fmt.Errorf("%s, where %s was before the rebase, is not in this repository", short(before), branch) + } + if _, err := run(ctx, dir, "reset", "--keep", "--quiet", before); err != nil { + return err + } + return nil +} + +func short(h string) string { + if len(h) > 8 { + return h[:8] + } + return h +} diff --git a/internal/gitx/rebased_test.go b/internal/gitx/rebased_test.go new file mode 100644 index 00000000..31b11ba4 --- /dev/null +++ b/internal/gitx/rebased_test.go @@ -0,0 +1,144 @@ +package gitx + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +// rebasedRepo is a feat branch, pushed, rebased onto a main that changed +// the same line, with the conflict resolved by hand — what an agent asked +// to resolve leaves behind. It returns the tips before and after. +func rebasedRepo(t *testing.T) (root, wt, origin, before, after string) { + t.Helper() + root, wt, origin = ontoRepo(t) + commit(t, wt, "shared.txt", "feat's line\n", "feat edits shared") + commit(t, wt, "own.txt", "own\n", "feat's own file") + if err := Push(ctx, wt, "feat"); err != nil { + t.Fatal(err) + } + pushMain(t, origin, "shared.txt", "main's line\n") + git(t, wt, "fetch", "-q", "origin") + before = git(t, wt, "rev-parse", "HEAD") + cmd := exec.Command("git", "-C", wt, "rebase", "origin/main") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + write(t, wt, "shared.txt", "main's line\nfeat's line\n") + git(t, wt, "add", "shared.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + return root, wt, origin, before, git(t, wt, "rev-parse", "HEAD") +} + +func TestLastRebase(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + r, err := LastRebase(ctx, wt, "feat") + if err != nil || r == nil { + t.Fatalf("%+v %v", r, err) + } + if r.Before != before || r.After != after || r.Onto != git(t, wt, "rev-parse", "origin/main") { + t.Errorf("tips: %+v (before %s after %s)", r, before, after) + } + if r.At.IsZero() { + t.Error("no time") + } + // A commit after the rebase: it is no longer the newest thing done. + commit(t, wt, "later.txt", "later\n", "later") + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("after a commit: %+v %v", r, err) + } +} + +func TestLastRebaseNone(t *testing.T) { + _, wt := taskRepo(t) + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("never rebased: %+v %v", r, err) + } + commit(t, wt, "a.txt", "a\n", "a") + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("committed: %+v %v", r, err) + } + if r, err := LastRebase(ctx, wt, "nope"); err != nil || r != nil { + t.Errorf("no such branch: %+v %v", r, err) + } +} + +// Each commit before against its rewrite: the one whose conflict was +// resolved changed, the other came across as it was. +func TestRewritten(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + r, _ := LastRebase(ctx, wt, "feat") + cs, err := Rewritten(ctx, wt, r) + if err != nil { + t.Fatal(err) + } + if len(cs) != 3 { + t.Fatalf("%+v", cs) + } + byS := map[string]Rewrite{} + for _, c := range cs { + byS[c.Subject] = c + } + if c := byS["feat edits shared"]; c.Change != RewriteChanged || c.Old == "" || c.New == "" || c.Old == c.New { + t.Errorf("resolved: %+v", c) + } + if c := byS["feat's own file"]; c.Change != RewriteSame || !strings.HasPrefix(after, c.New) || !strings.HasPrefix(before, c.Old) { + t.Errorf("unchanged: %+v", c) + } + if c := byS["feat"]; c.Change != RewriteSame { + t.Errorf("first: %+v", c) + } + // Oldest first, as the branch has them. + if cs[2].Subject != "feat's own file" { + t.Errorf("order: %+v", cs) + } + patch, err := RewriteDiff(ctx, wt, r, 0) + if err != nil || !strings.Contains(patch, "feat edits shared") || !strings.Contains(patch, "main's line") { + t.Errorf("diff %v:\n%s", err, patch) + } + if short, _ := RewriteDiff(ctx, wt, r, 40); len(short) > 40+len(cutNote) { + t.Errorf("cut: %d", len(short)) + } +} + +// Undo puts the branch back where it was, keeping the rewrite in the +// reflog; refused once the branch moved on or with changes not committed. +func TestUndoRebase(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + write(t, wt, "own.txt", "edited\n") + if err := UndoRebase(ctx, wt, "feat", before, after); err == nil || !strings.Contains(err.Error(), "uncommitted") { + t.Fatalf("dirty: %v", err) + } + git(t, wt, "checkout", "--", "own.txt") + if err := UndoRebase(ctx, wt, "feat", before, "0123456789012345678901234567890123456789"); err == nil { + t.Fatal("moved on") + } + if err := UndoRebase(ctx, wt, "feat", before, after); err != nil { + t.Fatal(err) + } + if got := git(t, wt, "rev-parse", "HEAD"); got != before { + t.Fatalf("head %s, want %s", got, before) + } + if r, _ := LastRebase(ctx, wt, "feat"); r != nil { + t.Errorf("still says rebased: %+v", r) + } +} + +// The rebased branch replaces the pushed one, which the remote still has. +func TestRebasedPushOver(t *testing.T) { + _, wt, origin, before, after := rebasedRepo(t) + if got := PushedHead(ctx, wt, "feat"); got != before { + t.Fatalf("pushed %s", got) + } + if err := PushOver(ctx, wt, "feat", before); err != nil { + t.Fatal(err) + } + if got := git(t, origin, "rev-parse", "feat"); got != after { + t.Errorf("origin has %s", got) + } +} From ff36187aa5ce36f3817ea32d5247884fe93b8d92 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 20:47:41 -0800 Subject: [PATCH 26/35] branch.rebased: a resolved rebase read back, pushed with a lease, or undone An agent asked to resolve a branch's conflict leaves it rebased and not pushed, and the remote still has the old commits. branch.rebased lists such branches with each commit's fate and, asked for one, git range-diff's account of what the resolution changed; a push with over replaces the remote's branch only while it is still the commit rewritten, and branch.rebase_undo puts the branch back (scoped like a push). Co-Authored-By: Claude Opus 5.5 --- internal/proto/proto.go | 67 +++++++++++++++- internal/server/harvest.go | 8 +- internal/server/rebased.go | 91 +++++++++++++++++++++ internal/server/rebased_test.go | 122 +++++++++++++++++++++++++++++ internal/server/scope.go | 17 ++-- internal/server/server.go | 16 +++- web/src/app/docs/protocol/page.mdx | 1 + 7 files changed, 310 insertions(+), 12 deletions(-) create mode 100644 internal/server/rebased.go create mode 100644 internal/server/rebased_test.go diff --git a/internal/proto/proto.go b/internal/proto/proto.go index de15916e..68745c61 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, CapAutopilotActivity, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, CapAutopilotActivity, CapBranchRebased, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -238,6 +238,12 @@ const CapCIStats = "ci.stats.v1" // gh on the machine the project is on. const CapCIRerun = "ci.rerun.v1" +// CapBranchRebased is branch.rebased and branch.rebase_undo: a branch's +// newest rebase read back — each commit before and after, and what +// resolving its conflicts changed — then pushed over the old branch with +// a lease (BranchPushParams.Over) or undone. +const CapBranchRebased = "branch.rebased.v1" + // CapAgentReply is agent.reply: an agent's last answer, whole, from its // saved conversation rather than off its screen. const CapAgentReply = "agent.reply.v1" @@ -644,6 +650,10 @@ const ( MethodCIStats = "ci.stats" // MethodCIRerun runs a failed run's failed jobs again (CapCIRerun). MethodCIRerun = "ci.rerun" + // MethodBranchRebased reads back the agents' branches' newest + // rebases, and MethodBranchRebaseUndo puts one back (CapBranchRebased). + MethodBranchRebased = "branch.rebased" + MethodBranchRebaseUndo = "branch.rebase_undo" // Leftover worktrees: list what each would lose, and remove them. MethodWorktreeStale = "worktree.stale" MethodWorktreeCleanup = "worktree.cleanup" @@ -1756,10 +1766,65 @@ type BranchRef struct { // of takes the remote's commits first and puts the branch's own on top; // without it such a push comes back as ErrPushRejected. It is a BranchRef // with a field added, so an older server reads it as one. +// +// Over is the commit the remote is expected to have for the branch: the +// push replaces it, and only it (--force-with-lease), which is how a +// rebased branch goes up over the one it rewrote (CapBranchRebased). An +// older server ignores it, and a plain push of a rewrite is rejected. type BranchPushParams struct { ProjectID string `json:"project_id"` Branch string `json:"branch"` Rebase bool `json:"rebase,omitempty"` + Over string `json:"over,omitempty"` +} + +// BranchRebasedParams asks for the newest rebase of each branch checked +// out in the project — or of Branch alone — that has not been pushed +// yet. Diff adds git range-diff's account of what changed. +type BranchRebasedParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch,omitempty"` + Diff bool `json:"diff,omitempty"` +} + +// BranchRebased lists the branches rebased and not pushed since. +type BranchRebased struct { + Rebases []BranchRebase `json:"rebases"` +} + +// BranchRebase is a branch's newest rebase: its tip before and after, +// the commit it went onto, when, and each commit's fate. Remote is the +// commit the remote has for the branch as the checkout last saw it, "" +// when it was never pushed: Before means the push replaces the old +// branch, anything else that somebody pushed since. +type BranchRebase struct { + Branch string `json:"branch"` + Before string `json:"before"` + After string `json:"after"` + Onto string `json:"onto"` + At time.Time `json:"at,omitempty"` + Commits []RebasedCommit `json:"commits,omitempty"` + Remote string `json:"remote,omitempty"` + Diff string `json:"diff,omitempty"` +} + +// RebasedCommit is one commit before (Old) and after (New), short +// hashes; Change is "same", "changed" (a conflict was resolved in it), +// "dropped" or "added". +type RebasedCommit struct { + Old string `json:"old,omitempty"` + New string `json:"new,omitempty"` + Subject string `json:"subject"` + Change string `json:"change"` +} + +// BranchRebaseUndoParams puts Branch back at Before, if it is still at +// After. +type BranchRebaseUndoParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch"` + Before string `json:"before"` + After string `json:"after"` } // BranchPushResult says what a push did: Took counts the commits a rebase diff --git a/internal/server/harvest.go b/internal/server/harvest.go index e67a94b8..11808c50 100644 --- a/internal/server/harvest.go +++ b/internal/server/harvest.go @@ -141,7 +141,11 @@ func (pm *projectManager) pushBranch(pp proto.BranchPushParams) (proto.BranchPus defer cancel() var took int var err error - if pp.Rebase { + switch { + case pp.Over != "": + // A rewrite going up over what the remote has: that, and only that. + err = gitx.PushOver(ctx, p.root, pp.Branch, pp.Over) + case pp.Rebase: // A rebase needs the branch checked out; pushing alone does not. // Asked of git, not the last snapshot: one taken while a rebase // was under way saw the worktree detached, and refused the next. @@ -155,7 +159,7 @@ func (pm *projectManager) pushBranch(pp proto.BranchPushParams) (proto.BranchPus "%s is not checked out here, so its commits cannot be rebased onto the remote's", pp.Branch) } took, err = gitx.PushRebase(ctx, wt.Path, pp.Branch) - } else { + default: err = gitx.Push(ctx, p.root, pp.Branch) } pm.request(p) diff --git a/internal/server/rebased.go b/internal/server/rebased.go new file mode 100644 index 00000000..26428e6c --- /dev/null +++ b/internal/server/rebased.go @@ -0,0 +1,91 @@ +package server + +import ( + "context" + "log" + "time" + + "github.com/Amitgb14/conch/internal/gitx" + "github.com/Amitgb14/conch/internal/proto" +) + +// A branch rebased — an agent asked to resolve its conflict with the base +// does this — and not yet pushed: read back for the person to review +// before it goes up over the branch it rewrote, or to put back. + +// rebasedDiffMax caps the range-diff handed to a client: a rebase that +// rewrote a great deal is better read in a terminal than in a panel. +const rebasedDiffMax = 256 << 10 + +func (pm *projectManager) branchRebased(rp proto.BranchRebasedParams) (proto.BranchRebased, *proto.Error) { + out := proto.BranchRebased{Rebases: []proto.BranchRebase{}} + p, perr := pm.gitProject(rp.ProjectID) + if perr != nil { + return out, perr + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + wts, err := gitx.Worktrees(ctx, p.root) + if err != nil { + return out, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + base := p.baseBranch(ctx) + seen := map[string]bool{} + for _, wt := range wts { + if wt.Branch == "" || wt.Prunable || wt.Branch == base || seen[wt.Branch] || (rp.Branch != "" && wt.Branch != rp.Branch) { + continue + } + seen[wt.Branch] = true + r, err := gitx.LastRebase(ctx, wt.Path, wt.Branch) + if err != nil || r == nil { + continue + } + remote := gitx.PushedHead(ctx, wt.Path, wt.Branch) + if remote == r.After { + continue // pushed already + } + b := proto.BranchRebase{Branch: r.Branch, Before: r.Before, After: r.After, Onto: r.Onto, At: r.At, Remote: remote} + if cs, err := gitx.Rewritten(ctx, wt.Path, r); err == nil { + for _, c := range cs { + b.Commits = append(b.Commits, proto.RebasedCommit{Old: c.Old, New: c.New, Subject: c.Subject, Change: c.Change}) + } + } else { + log.Printf("project %s: reading the rebase of %s: %v", p.id, r.Branch, err) + } + if rp.Diff && rp.Branch != "" { + if d, err := gitx.RewriteDiff(ctx, wt.Path, r, rebasedDiffMax); err == nil { + b.Diff = d + } else { + return out, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + } + out.Rebases = append(out.Rebases, b) + } + return out, nil +} + +func (pm *projectManager) undoRebase(up proto.BranchRebaseUndoParams) (struct{}, *proto.Error) { + p, perr := pm.gitProject(up.ProjectID) + if perr != nil { + return struct{}{}, perr + } + if up.Before == "" || up.After == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "say where %s was before the rebase and after it", up.Branch) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + wt, ok, perr := checkout(ctx, p, up.Branch) + if perr != nil { + return struct{}{}, perr + } + if !ok { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%s is not checked out here, so its rebase cannot be undone", up.Branch) + } + err := gitx.UndoRebase(ctx, wt.Path, up.Branch, up.Before, up.After) + pm.request(p) + if err != nil { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + log.Printf("project %s: put %s back where it was before its rebase", p.id, up.Branch) + return struct{}{}, nil +} diff --git a/internal/server/rebased_test.go b/internal/server/rebased_test.go new file mode 100644 index 00000000..ef175939 --- /dev/null +++ b/internal/server/rebased_test.go @@ -0,0 +1,122 @@ +package server_test + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/proto" +) + +// rebasedFixture is feat pushed, then rebased onto a main that changed +// the same line, its conflict resolved in feat's worktree — as an agent +// asked to resolve it leaves things. It returns feat's tips before and +// after. +func rebasedFixture(t *testing.T) (c *client.Client, proj proto.ProjectInfo, wt, origin, before, after string) { + t.Helper() + c, proj, repo, wt, origin := harvestFixture(t) + git(t, repo, "push", "-q", "origin", "main") + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-qam", "feat edits a") + os.WriteFile(filepath.Join(wt, "b.txt"), []byte("b\n"), 0o644) + git(t, wt, "add", "b.txt") + git(t, wt, "commit", "-qm", "feat adds b") + if err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat"}, nil); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-qam", "main edits a") + before = gitOut(t, wt, "rev-parse", "HEAD") + cmd := exec.Command("git", "-C", wt, "rebase", "main") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("main\nfeat\n"), 0o644) + git(t, wt, "add", "a.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + return c, proj, wt, origin, before, gitOut(t, wt, "rev-parse", "HEAD") +} + +// A resolved rebase is read back for review, pushed over the old branch +// with a lease, and then no longer listed. +func TestBranchRebasedReviewAndPush(t *testing.T) { + c, proj, wt, origin, before, after := rebasedFixture(t) + if miss := c.MissingCapabilities([]string{proto.CapBranchRebased}); len(miss) > 0 { + t.Fatalf("missing %v", miss) + } + var got proto.BranchRebased + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil { + t.Fatal(err) + } + if len(got.Rebases) != 1 { + t.Fatalf("%+v", got) + } + r := got.Rebases[0] + if r.Branch != "feat" || r.Before != before || r.After != after || r.Remote != before || r.At.IsZero() || r.Diff != "" { + t.Errorf("rebase: %+v", r) + } + if len(r.Commits) != 2 || r.Commits[0].Change != "changed" || r.Commits[0].Subject != "feat edits a" || r.Commits[1].Change != "same" { + t.Errorf("commits: %+v", r.Commits) + } + // The resolution itself, asked of one branch. + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID, Branch: "feat", Diff: true}, &got); err != nil { + t.Fatal(err) + } + if len(got.Rebases) != 1 || !strings.Contains(got.Rebases[0].Diff, "main") { + t.Errorf("diff: %+v", got) + } + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID, Branch: "main"}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("main was not rebased: %+v %v", got, err) + } + + // A plain push of the rewrite is refused, and so is one over a commit + // the remote does not have. + err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat"}, nil) + wantErr(t, err, "") + err = call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat", Over: after}, nil) + wantErr(t, err, "") + if gitOut(t, origin, "rev-parse", "feat") != before { + t.Fatal("the remote's branch was replaced") + } + if err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat", Over: before}, nil); err != nil { + t.Fatal(err) + } + if gitOut(t, origin, "rev-parse", "feat") != after { + t.Fatal("the rebased branch was not pushed") + } + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("pushed, still listed: %+v %v", got, err) + } + _ = wt +} + +// Undoing puts the branch back where it was, once. +func TestBranchRebaseUndo(t *testing.T) { + c, proj, wt, _, before, after := rebasedFixture(t) + undo := proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "feat", Before: before, After: after} + os.WriteFile(filepath.Join(wt, "b.txt"), []byte("dirty\n"), 0o644) + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, undo, nil), "uncommitted") + git(t, wt, "checkout", "--", "b.txt") + if err := call(t, c, proto.MethodBranchRebaseUndo, undo, nil); err != nil { + t.Fatal(err) + } + if gitOut(t, wt, "rev-parse", "HEAD") != before { + t.Fatal("not put back") + } + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, undo, nil), "moved on") + var got proto.BranchRebased + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("undone, still listed: %+v %v", got, err) + } + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "nope", Before: before, After: after}, nil), "not checked out") + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "feat"}, nil), "") + wantErr(t, call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: "nope"}, &got), "") +} diff --git a/internal/server/scope.go b/internal/server/scope.go index 493606f7..4284e490 100644 --- a/internal/server/scope.go +++ b/internal/server/scope.go @@ -124,7 +124,7 @@ var scoped = map[string]scopeKind{ proto.MethodBranchCommit: scopeProject, proto.MethodBranchStage: scopeProject, proto.MethodBranchReview: scopeProject, proto.MethodBranchPush: scopeProject, proto.MethodBranchPR: scopeProject, proto.MethodBranchMerge: scopeProject, proto.MethodBranchPRMerge: scopeProject, proto.MethodBranchDiscard: scopeProject, proto.MethodBranchGit: scopeProject, // Running CI again spends the project's Actions minutes. - proto.MethodCIRerun: scopeProject, + proto.MethodCIRerun: scopeProject, proto.MethodBranchRebaseUndo: scopeProject, proto.MethodServerStop: scopeServer, proto.MethodServerReload: scopeServer, // The cloud agent decides what every agent's environment is given. @@ -430,13 +430,14 @@ var verbs = map[string]string{ proto.MethodWorktreeCleanup: "clean up worktrees", proto.MethodBranchCommit: "commit", proto.MethodBranchStage: "stage changes on", proto.MethodBranchReview: "review the pull request of", proto.MethodBranchPush: "push", proto.MethodBranchPR: "open a pull request", proto.MethodBranchMerge: "merge", proto.MethodBranchPRMerge: "merge a pull request", proto.MethodBranchDiscard: "discard a branch", - proto.MethodBranchGit: "run git", - proto.MethodCIRerun: "re-run the CI of", - proto.MethodTicketUpdate: "change a ticket", - proto.MethodAgentSkill: "install or remove the agents' conch skill", - proto.MethodProjectFiles: "change which local files a project copies into its worktrees", - proto.MethodProjectSetup: "change the command a project runs in its new worktrees", - proto.MethodScheduleAdd: "schedule a message or a task", proto.MethodScheduleRemove: "remove something scheduled", + proto.MethodBranchGit: "run git", + proto.MethodCIRerun: "re-run the CI of", + proto.MethodBranchRebaseUndo: "undo the rebase of", + proto.MethodTicketUpdate: "change a ticket", + proto.MethodAgentSkill: "install or remove the agents' conch skill", + proto.MethodProjectFiles: "change which local files a project copies into its worktrees", + proto.MethodProjectSetup: "change the command a project runs in its new worktrees", + proto.MethodScheduleAdd: "schedule a message or a task", proto.MethodScheduleRemove: "remove something scheduled", proto.MethodGroupSave: "change a project group", proto.MethodGroupRemove: "remove a project group", proto.MethodGroupTaskRemove: "remove a task across a group", proto.MethodGroupTaskMerge: "merge a task's pull requests", proto.MethodAgentLibrary: "change the library of MCP servers and skills", proto.MethodLibraryApply: "apply the library to the agents", proto.MethodLibraryFetch: "download a skill into the library", diff --git a/internal/server/server.go b/internal/server/server.go index ccf8e9bb..c958d8e1 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -454,7 +454,7 @@ var slowMethods = map[string]bool{ proto.MethodProjectFiles: true, proto.MethodProjectSetup: true, proto.MethodSessionList: true, proto.MethodSessionResume: true, proto.MethodSessionDelete: true, proto.MethodSessionSearch: true, proto.MethodSessionShare: true, proto.MethodSessionExport: true, proto.MethodFSUpload: true, proto.MethodBranchCommit: true, proto.MethodBranchStage: true, proto.MethodBranchPush: true, proto.MethodBranchPR: true, - proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, + proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodBranchRebased: true, proto.MethodBranchRebaseUndo: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, proto.MethodProjectTickets: true, proto.MethodTicketGet: true, proto.MethodTicketUpdate: true, proto.MethodTicketCheck: true, proto.MethodTicketOverview: true, proto.MethodWorktreeStale: true, proto.MethodWorktreeCleanup: true, proto.MethodProjectResolve: true, proto.MethodProjectGitInit: true, proto.MethodWorktreeDescribe: true, proto.MethodWorktreeHave: true, proto.MethodWorktreePack: true, @@ -1042,6 +1042,20 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { } return s.projects.ciRerun(rp) + case proto.MethodBranchRebased: + rp, perr := decode[proto.BranchRebasedParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.branchRebased(rp) + + case proto.MethodBranchRebaseUndo: + up, perr := decode[proto.BranchRebaseUndoParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.undoRebase(up) + case proto.MethodProjectLog: lp, perr := decode[proto.LogParams](msg) if perr != nil { diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index 3da910e0..9570dcb9 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -39,6 +39,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, the repository's remotes by which a remote's branch is told from a local one, and its `format` — `objects` sha1 or sha256 and `refs` files or reftable — absent from an older server; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`) | | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | +| Rebased branches | `branch.rebased` lists each checked-out branch whose newest change is a finished rebase not yet pushed — or one `branch`'s — with its tip `before` and `after`, the commit it went `onto`, what the `remote` has, and each commit's fate (`same`, `changed` where a conflict was resolved, `dropped`, `added`); `diff` adds git range-diff's account. A push with `over` replaces the remote's branch only if it is still that commit, and `branch.rebase_undo` puts a branch back at `before` while it is still at `after` (capability `branch.rebased.v1`) | | CI | `ci.stats` adds up a project's GitHub Actions runs over `days` (14 by default, 90 at most) and the same span before: runs, passes and failures, median run, queue and red-to-green times, runs per day, each job's median and slowest tenth, flaky jobs, and each workflow's newest failed run per branch; a few dozen runs' jobs are read per call and `jobs_pending` says how many are left (capability `ci.stats.v1`). `ci.rerun` runs a run's failed jobs again, by `run_id` or a `branch`'s newest failed run (capability `ci.rerun.v1`). Both go through `gh` on the project's machine | | Autopilot activity | every `autopilot.note` the server sends carries its `kind` (`ci`, `check`, `ship`, `merge`, `resolve`, `intake`, `triage`) and `at`, and is kept — the newest 500, in `autopilot-activity.jsonl` beside the config, so a restart keeps them; `autopilot.activity` lists them newest first, for a `project_id` or every project, `limit` at most (100 by default) (capability `autopilot.activity.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | From 9ddd84855d850a4c27754551592f228dc741a793 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 20:49:35 -0800 Subject: [PATCH 27/35] ConchKit: a rebased branch not pushed, and range-diff read for review branch.rebased's answer, what pushing each rewrite means (over the old branch, a first push, or somebody pushed since), a rebased state in the graph's branch list right after a stopped conflict, and git range-diff's lines sorted into what the resolution added and took away. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchApp/CommitsView.swift | 1 + macos/Sources/ConchKit/BranchGraph.swift | 26 +++-- macos/Sources/ConchKit/Rebased.swift | 108 +++++++++++++++++++ macos/Tests/ConchKitTests/RebasedTests.swift | 83 ++++++++++++++ 4 files changed, 210 insertions(+), 8 deletions(-) create mode 100644 macos/Sources/ConchKit/Rebased.swift create mode 100644 macos/Tests/ConchKitTests/RebasedTests.swift diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index fec7dcff..6ed7b09d 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -949,6 +949,7 @@ struct BranchSideRow: View { func describe(_ b: GraphBranch) -> (String, Color) { switch b.state { case .conflicted(let n): ("conflict · \(n) file\(n == 1 ? "" : "s")", Theme.err) + case .rebased: ("rebased · not pushed", Theme.ok) case .waiting: ("waiting for you", Theme.warn) case .ciFailing: ("CI failed", Theme.err) case .willConflict: ("will conflict", Theme.warn) diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift index 9a594e8e..24f7bade 100644 --- a/macos/Sources/ConchKit/BranchGraph.swift +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -53,6 +53,9 @@ public func commitOwners(_ commits: [LogCommit], base: String, remotes: Set [GraphBranch] { +/// Rebased is the server's list of branches rebased and not pushed, by +/// name. +public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [String: BranchRebase] = [:]) -> [GraphBranch] { let base = project.base ?? "" let mainBranches = Set((project.worktrees ?? []).filter { $0.main == true }.compactMap(\.branch)) let info = Dictionary((project.branches ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) @@ -130,6 +138,8 @@ public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo]) -> [GraphBr let state: GraphBranchState if let n = w.status?.conflicts, n > 0 { state = .conflicted(n) + } else if rebased[name] != nil { + state = .rebased } else if agent?.agent?.state == .blocked { state = .waiting } else if pr?.checks == "fail" { @@ -144,7 +154,7 @@ public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo]) -> [GraphBr state = .idle } out.append(GraphBranch(name: name, agent: agent, state: state, ahead: b?.baseAhead ?? 0, behind: b?.baseBehind ?? 0, - conflicts: w.conflicts ?? [], pr: pr)) + conflicts: w.conflicts ?? [], pr: pr, rebase: rebased[name])) } return out.enumerated().sorted { ($0.element.state.urgency, $0.offset) < ($1.element.state.urgency, $1.offset) }.map(\.element) } diff --git a/macos/Sources/ConchKit/Rebased.swift b/macos/Sources/ConchKit/Rebased.swift new file mode 100644 index 00000000..7d42b2d0 --- /dev/null +++ b/macos/Sources/ConchKit/Rebased.swift @@ -0,0 +1,108 @@ +import Foundation + +// A branch rebased and not pushed yet (branch.rebased): an agent asked to +// resolve a conflict with the base leaves one. The remote still has the +// old commits, so before it goes up the person can see what resolving +// the conflict changed, push it over the old with a lease, or undo it. + +public struct BranchRebased: Decodable, Sendable { + public var rebases: [BranchRebase]? +} + +public struct BranchRebase: Decodable, Equatable, Sendable { + public var branch: String + public var before: String + public var after: String + public var onto: String + public var at: Date? + public var commits: [RebasedCommit]? + /// What the remote has for the branch, as the checkout last saw it. + public var remote: String? + /// git range-diff's account, when asked for. + public var diff: String? + + /// How a push of the rewrite would go. + public enum Push: Equatable, Sendable { + /// Never pushed: a plain push. + case fresh + /// Over the old branch the remote still has, and only that. + case over(String) + /// The remote has something else: somebody pushed since. + case moved(String) + } + + public var push: Push { + guard let r = remote, !r.isEmpty else { return .fresh } + return r == before ? .over(r) : .moved(r) + } + + public var changed: Int { (commits ?? []).filter { $0.change == "changed" }.count } + public var dropped: Int { (commits ?? []).filter { $0.change == "dropped" }.count } + + /// "3 commits rewritten · 1 changed resolving the conflict · 1 dropped". + public var summary: String { + let cs = commits ?? [] + guard !cs.isEmpty else { return "Nothing to compare" } + let n = cs.filter { $0.change != "added" }.count + var parts = ["\(n) commit\(n == 1 ? "" : "s") rewritten"] + if changed > 0 { parts.append("\(changed) changed resolving the conflict") } + if dropped > 0 { parts.append("\(dropped) dropped") } + let added = cs.count - n + if added > 0 { parts.append("\(added) added") } + return parts.joined(separator: " · ") + } +} + +public struct RebasedCommit: Decodable, Equatable, Sendable { + public var old: String? + public var new: String? + public var subject: String + /// same, changed, dropped or added. + public var change: String +} + +/// A line of git range-diff's account. +public struct RangeDiffLine: Equatable, Sendable, Identifiable { + public enum Kind: Equatable, Sendable { + /// "1: abc ! 1: def subject": a commit before and after. + case commit + /// A section of the diff of diffs. + case hunk + /// What the rewrite added to the commit's change, or took from it. + case added, removed + case context + } + + public var id: Int + public var kind: Kind + public var text: String +} + +/// Reads git range-diff: a commit pair's line stands alone; beneath a +/// changed one, each line is indented four, its first character saying +/// whether the rewrite added it to the commit's diff or took it away. +public func rangeDiffLines(_ text: String) -> [RangeDiffLine] { + var out: [RangeDiffLine] = [] + for raw in text.split(separator: "\n", omittingEmptySubsequences: false) { + let line = String(raw) + if line.isEmpty && out.isEmpty { continue } + let kind: RangeDiffLine.Kind + var body = line + if line.hasPrefix(" ") { + body = String(line.dropFirst(4)) + switch body.first { + case "+": kind = .added + case "-": kind = .removed + case "@": kind = .hunk + default: kind = .context + } + } else if line.isEmpty { + kind = .context + } else { + kind = .commit + } + out.append(RangeDiffLine(id: out.count, kind: kind, text: body)) + } + while out.last?.text.isEmpty == true { out.removeLast() } + return out +} diff --git a/macos/Tests/ConchKitTests/RebasedTests.swift b/macos/Tests/ConchKitTests/RebasedTests.swift new file mode 100644 index 00000000..7b166d7c --- /dev/null +++ b/macos/Tests/ConchKitTests/RebasedTests.swift @@ -0,0 +1,83 @@ +import Foundation +import Testing +@testable import ConchKit + +let rebasedJSON = #""" +{"rebases":[ + {"branch":"conch/git-graph","before":"aaaa1111","after":"bbbb2222","onto":"cccc3333","at":"2026-11-14T12:00:00Z", + "remote":"aaaa1111", + "commits":[{"old":"a1","new":"b1","subject":"Draw merge curves","change":"changed"}, + {"old":"a2","new":"b2","subject":"Lane colours","change":"same"}, + {"old":"a3","subject":"Already on master","change":"dropped"}]}, + {"branch":"fresh","before":"d1","after":"d2","onto":"c"}, + {"branch":"raced","before":"e1","after":"e2","onto":"c","remote":"e9"} +]} +"""# + +// The server's rebases, and what pushing each means: over the old branch +// with a lease, a first push, or one somebody else pushed since. +@Test func rebasedDecodesAndPushes() throws { + let r = try conchDecoder().decode(BranchRebased.self, from: Data(rebasedJSON.utf8)) + let rs = r.rebases ?? [] + #expect(rs.count == 3) + #expect(rs[0].changed == 1 && rs[0].dropped == 1 && rs[0].at != nil) + #expect(rs[0].push == .over("aaaa1111")) + #expect(rs[1].push == .fresh && rs[1].commits == nil) + #expect(rs[2].push == .moved("e9")) + #expect(rs[0].summary == "3 commits rewritten · 1 changed resolving the conflict · 1 dropped") + #expect(rs[1].summary == "Nothing to compare") + let empty = try conchDecoder().decode(BranchRebased.self, from: Data("{}".utf8)) + #expect(empty.rebases == nil) +} + +// A rebased branch that has not gone up needs the person: after a +// conflict stopped somewhere, before anything else. +@Test func rebasedBranchState() throws { + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"conch","path":"/p","base":"master", + "worktrees":[{"path":"/p","branch":"master","main":true}, + {"path":"/w/a","branch":"asking"}, + {"path":"/w/b","branch":"conch/git-graph","conflicts":["a.go"]}, + {"path":"/w/c","rebasing":"stopped","status":{"files":1,"conflicts":1}}], + "branches":[{"name":"conch/git-graph","pr":{"number":3,"state":"OPEN","checks":"fail"}}]} + """#.utf8)) + let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" + [{"id":"p2","name":"d","state":"running","project_id":"r1","branch":"asking","agent":{"name":"claude","state":"blocked"}}] + """#.utf8)) + let rs = try conchDecoder().decode(BranchRebased.self, from: Data(rebasedJSON.utf8)).rebases ?? [] + let bs = graphBranches(project, panes: panes, rebased: Dictionary(uniqueKeysWithValues: rs.map { ($0.branch, $0) })) + #expect(bs.map(\.name) == ["stopped", "conch/git-graph", "asking"]) + #expect(bs[1].state == .rebased && bs[1].rebase?.after == "bbbb2222") + #expect(!bs[1].state.conflicts) + // Without the server's word, as before. + #expect(graphBranches(project, panes: panes)[2].state == .ciFailing) + let order: [GraphBranchState] = [.conflicted(1), .rebased, .waiting] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) +} + +// git range-diff's account, line by line: a pair of commits, the +// resolution's own additions and removals, the rest as context. +@Test func rangeDiffReads() { + let text = """ + 1: c92020d ! 1: 6e6da5d feat one + @@ Commit message + + ## f ## + @@ + - a + --b + + A + +-b2 + +B + c + 2: 860eca6 = 2: eadbc9d feat two + """ + let ls = rangeDiffLines(text) + #expect(ls.first?.kind == .commit && ls.first?.text == "1: c92020d ! 1: 6e6da5d feat one") + #expect(ls[1].kind == .hunk && ls[1].text == "@@ Commit message") + #expect(ls.filter { $0.kind == .removed }.map(\.text) == ["- a", "--b"]) + #expect(ls.filter { $0.kind == .added }.map(\.text) == ["+ A", "+-b2"]) + #expect(ls.last?.kind == .commit) + #expect(ls.contains { $0.kind == .context && $0.text == " +B" }) + #expect(rangeDiffLines("").isEmpty) +} From dd8e985cd3a6522e1805fabae8a606ca42486f0f Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 20:52:08 -0800 Subject: [PATCH 28/35] Conch.app: review a resolved rebase, then push it with a lease or undo it Once an agent has resolved a branch's conflict, the commit graph says so in a green banner and on the branch's card: each commit old -> new, the one the conflict was resolved in marked. Review the resolution shows git range-diff's account, the resolution's own lines marked; Push (with lease) replaces only the old branch the remote still has, and is held back when somebody pushed since; Undo the rebase puts it back after asking. End-to-end row 9.178. Co-Authored-By: Claude Opus 5.5 --- docs/testing/end-to-end.md | 1 + macos/Sources/ConchApp/CommitsView.swift | 120 ++++++++++- macos/Sources/ConchApp/RebasedViews.swift | 234 ++++++++++++++++++++++ web/src/app/docs/mac-app/page.mdx | 2 +- 4 files changed, 355 insertions(+), 2 deletions(-) create mode 100644 macos/Sources/ConchApp/RebasedViews.swift diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 0dfc9a97..c8c2c046 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -417,6 +417,7 @@ What it carries, and what is left over in each row: | 9.175 💳🌐 | Conch.app's commit graph with agents | A project with Claude and Codex on task branches, one with an open pull request on a real GitHub repository and red CI, one whose change master then touches on the same lines; open **Commit Graph**. Rebase the second onto master by hand so it stops, then **Ask Codex to resolve**, and its menu's *Start a new agent* on another; **Hand to an Agent…** on an older commit; a SHA-256 reftable repository (`git init --object-format=sha256 --ref-format=reftable`) added as a project | Agents on branches lists both in urgency order with the right agent and ↑/↓; commits show their agent; the CI squares match GitHub; *will conflict* shows before anything moves, the banner when the rebase stops; the agent gets the files and resolves without pushing; the new task's branch starts at the commit; the header says **Git 3 · SHA-256 · reftable** | ☐ | | 9.176 🌐 | The CI panel against real GitHub Actions | On a project with a month of real Actions history and `gh` logged in: **Commit Graph** → **CI**, then 7d, 14d and 30d; on a busy repository watch *Reading the jobs of N more runs…* fill in; break a test on a branch, let its run fail, then **Re-run failed jobs** in the panel and **Re-run Failed Jobs** on the branch's menu | The numbers match GitHub's Actions page for the period (pass rate, the failing runs, a job's time); the re-run starts a new attempt of that run on GitHub, the button says *Re-running…* until the attempt shows, and the pull request's checks turn pending | ☐ | | 9.177 💳🌐 | The autopilot's activity in Conch.app | With the autopilot on (auto_fix, auto_merge, auto_resolve, a check) for a real GitHub repository and a real agent on a task branch: open **Commit Graph** → **Autopilot** and leave it open; break a test so CI fails, let the agent fix it, let the pull request merge; then quit everything, reload the server, and open it again | Each step appears in *What it did* as it happens (CI sent to the agent, pushed, merged), marked by kind, under Today, with the branch a link to its commits; *Minding now* follows the branch; the rules match Settings; after the reload the feed is all still there | ☐ | +| 9.178 💳 | Review and push a resolved rebase in Conch.app | A task branch pushed with a pull request, then the base changed on the same lines: open **Commit Graph**, **Ask an agent to resolve** with a real agent, wait for it to finish the rebase | The banner turns green (*rebased onto master*), the branch's card lists each commit old → new with the conflicted one marked *resolved*; **Review the resolution** shows the agent's own lines as + / −; **Push (with lease)** replaces the old branch on GitHub and the pull request updates; on a second run, **Undo the rebase** puts the branch back and the conflict returns; with a commit pushed from elsewhere in between, the push is refused rather than overwriting it | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 6ed7b09d..a5291586 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -61,6 +61,14 @@ final class CommitsModel: ObservableObject { /// the button says so until a later attempt shows up. @Published var rerunning: [Int64: Int] = [:] private var ciReads = Latest() + /// Branches rebased and not pushed (branch.rebased), by name. + @Published var rebases: [String: BranchRebase] = [:] + /// The rebase being reviewed in a sheet, with git range-diff's account. + @Published var reviewing: BranchRebase? + @Published var reviewError = "" + /// Branches whose rewrite is going up, or being undone. + @Published var pushing: Set = [] + private var rebaseReads = Latest() /// The graph's search: commits that do not match are dimmed, never /// taken out, so the lanes stay whole. @Published var query = "" @@ -101,7 +109,7 @@ final class CommitsModel: ObservableObject { /// The agents' branches, most urgent first. var branches: [GraphBranch] { guard let p = projectInfo else { return [] } - return graphBranches(p, panes: store.snapshots[machine]?.panes ?? []) + return graphBranches(p, panes: store.snapshots[machine]?.panes ?? [], rebased: rebases) } /// The branch a commit is on and its entry in the side's list, if it @@ -217,6 +225,103 @@ final class CommitsModel: ObservableObject { } } + var canRebased: Bool { store.connection(machine)?.hello?.capabilities?.contains("branch.rebased.v1") == true } + + /// The agents' branches rebased and not pushed. An older server has no + /// such list, and the graph goes on without it. + func loadRebases() { + guard let c = store.connection(machine), canRebased else { return } + struct P: Encodable { var project_id: String } + let n = rebaseReads.next() + Task { + guard let r = try? await c.call("branch.rebased", P(project_id: project), as: BranchRebased.self), + rebaseReads.isLatest(n) else { return } + rebases = Dictionary((r.rebases ?? []).map { ($0.branch, $0) }, uniquingKeysWith: { a, _ in a }) + // A sheet open on a rebase that was pushed or undone elsewhere. + if let open = reviewing, rebases[open.branch]?.after != open.after { reviewing = nil } + } + } + + /// Opens the review of a branch's rebase: what resolving changed. + func review(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + struct P: Encodable { var project_id: String; var branch: String; var diff: Bool } + reviewing = r + reviewError = "" + Task { + do { + let got = try await c.call("branch.rebased", P(project_id: project, branch: r.branch, diff: true), as: BranchRebased.self) + guard reviewing?.branch == r.branch else { return } + if let fresh = got.rebases?.first { + reviewing = fresh + } else { + reviewError = "\(r.branch) is no longer a rebase waiting to be pushed: it was pushed, undone or committed to since." + } + } catch { + guard reviewing?.branch == r.branch else { return } + reviewError = "Could not read the rebase: \(error)" + } + } + } + + /// Pushes a rebased branch: over the old one the remote still has, and + /// only that, or a first push. + func pushRebase(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + struct P: Encodable { var project_id: String; var branch: String; var over: String? } + var over: String? + switch r.push { + case .fresh: over = nil + case .over(let h): over = h + case .moved(let h): + store.error = "Somebody pushed \(String(h.prefix(8))) to \(r.branch) since it was rebased; pushing would throw that away. Bring it in first." + return + } + pushing.insert(r.branch) + Task { + defer { pushing.remove(r.branch) } + do { + try await c.call("branch.push", P(project_id: project, branch: r.branch, over: over)) + store.say("Pushed \(r.branch), rebased onto \(projectInfo?.base ?? "the base")") + if reviewing?.branch == r.branch { reviewing = nil } + rebases[r.branch] = nil + store.refreshProject(machine: machine, project: project) + loadRebases() + } catch { + store.error = "Could not push \(r.branch): \(error)" + loadRebases() + } + } + } + + /// Puts a rebased branch back where it was, after asking: the rewrite + /// stays in git's reflog, but the agent's resolution leaves the branch. + func undoRebase(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + let a = NSAlert() + a.messageText = "Undo the rebase of \(r.branch)?" + a.informativeText = "The branch goes back to \(String(r.before.prefix(8))), where it was before, and the conflict with \(projectInfo?.base ?? "the base") is back. " + + "The rebased commits stay in git's reflog (\(String(r.after.prefix(8)))). A worktree with uncommitted changes is not touched." + a.addButton(withTitle: "Undo the Rebase") + a.addButton(withTitle: "Cancel") + guard a.runModal() == .alertFirstButtonReturn else { return } + struct P: Encodable { var project_id: String; var branch: String; var before: String; var after: String } + pushing.insert(r.branch) + Task { + defer { pushing.remove(r.branch) } + do { + try await c.call("branch.rebase_undo", P(project_id: project, branch: r.branch, before: r.before, after: r.after)) + store.say("Put \(r.branch) back where it was before its rebase", .info) + if reviewing?.branch == r.branch { reviewing = nil } + rebases[r.branch] = nil + store.refreshProject(machine: machine, project: project) + load() + } catch { + store.error = "Could not undo the rebase: \(error)" + } + } + } + func handToAgent(_ c: LogCommit) { store.handCommit(machine: machine, project: project, hash: c.hash, subject: c.subject) } @@ -237,6 +342,7 @@ final class CommitsModel: ObservableObject { } struct Params: Encodable { var project_id: String; var limit: Int } loading = true + loadRebases() let n = reads.next() Task { do { @@ -375,6 +481,9 @@ struct CommitsView: View { .background(Theme.window) .clipShape(RoundedRectangle(cornerRadius: embedded ? 0 : 9)) .overlay(RoundedRectangle(cornerRadius: 9).stroke(embedded ? .clear : Theme.line)) + .sheet(isPresented: Binding(get: { model.reviewing != nil }, set: { if !$0 { model.reviewing = nil } })) { + RebaseReviewSheet(model: model) + } } var graph: some View { @@ -382,6 +491,7 @@ struct CommitsView: View { header Rectangle().fill(Theme.line).frame(height: 1) ConflictBanner(model: model) + RebasedBanner(model: model) if model.range != nil { HStack(spacing: 8) { Circle().fill(Theme.merged).frame(width: 7, height: 7) @@ -719,6 +829,7 @@ struct CommitDetailPanel: View { } if model.range == nil { if let b = model.branch(of: d.hash), b.state.conflicts { ConflictCard(model: model, branch: b) } + if let b = model.branch(of: d.hash), let r = b.rebase { RebasedCard(model: model, branch: b, rebase: r) } HStack(spacing: 8) { if let c = model.rows.first(where: { $0.commit.hash == d.hash })?.commit { Button("Hand to an Agent…") { model.handToAgent(c) } @@ -844,6 +955,7 @@ struct StateTag: View { case .willConflict: ("⚠ will conflict", Theme.warn) case .ciFailing: ("✕ CI failed", Theme.err) case .waiting: ("waiting for you", Theme.warn) + case .rebased: ("✓ rebased · not pushed", Theme.ok) default: nil } } @@ -929,6 +1041,12 @@ struct BranchSideRow: View { if branch.state.conflicts { Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(branch) } } + if let r = branch.rebase { + Button("Review the Resolution…") { model.review(r) } + Button(r.push == .fresh ? "Push" : "Push (with Lease)") { model.pushRebase(r) } + .disabled(model.pushing.contains(r.branch) || { if case .moved = r.push { return true } else { return false } }()) + Button("Undo the Rebase…") { model.undoRebase(r) } + } if branch.state == .ciFailing, model.canRerun { Button("Re-run Failed Jobs") { model.rerun(branch: branch.name) } } diff --git a/macos/Sources/ConchApp/RebasedViews.swift b/macos/Sources/ConchApp/RebasedViews.swift new file mode 100644 index 00000000..7ed016f5 --- /dev/null +++ b/macos/Sources/ConchApp/RebasedViews.swift @@ -0,0 +1,234 @@ +import ConchKit +import SwiftUI + +// A branch rebased onto the base — an agent asked to resolve its conflict +// does this — and not pushed yet: said above the graph, shown beside the +// branch's commit with each commit before and after, and reviewed in a +// sheet with git range-diff's account of what resolving changed, before +// it is pushed over the old branch or put back. + +/// Says the push a rebase needs, for its button. +func pushTitle(_ r: BranchRebase) -> String { + switch r.push { + case .fresh: "Push" + case .over: "Push (with lease)" + case .moved: "Push" + } +} + +func pushHelp(_ r: BranchRebase, base: String) -> String { + switch r.push { + case .fresh: "Pushes \(r.branch) for the first time" + case .over(let h): "Replaces \(String(h.prefix(8))) on the remote with the rebased branch, and only that: anything pushed since is kept and the push refused" + case .moved(let h): "Somebody pushed \(String(h.prefix(8))) to \(r.branch) since the rebase; pushing would throw it away. Bring it in first." + } +} + +func pushBlocked(_ r: BranchRebase) -> Bool { + if case .moved = r.push { return true } + return false +} + +/// Above the graph when a branch is rebased and waiting to go up, and no +/// conflict has stopped anything (that banner comes first). +struct RebasedBanner: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + let bs = model.branches + if !bs.contains(where: \.stopped), let b = bs.first(where: { $0.rebase != nil }), let r = b.rebase { + let base = model.projectInfo?.base ?? "the base" + HStack(spacing: 10) { + Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.ok) + VStack(alignment: .leading, spacing: 1) { + Text("\(b.name) is rebased onto \(base)").font(.ui(size: 12.5, weight: .semibold)).lineLimit(1) + Text(r.summary + ". Not pushed yet.").font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1) + } + Spacer(minLength: 8) + Button("Review…") { model.review(r) } + .controlSize(.small).buttonStyle(.borderedProminent).tint(Theme.accentDeep) + Button(pushTitle(r)) { model.pushRebase(r) } + .controlSize(.small) + .disabled(model.pushing.contains(r.branch) || pushBlocked(r)) + .help(pushHelp(r, base: base)) + } + .padding(.horizontal, 12).padding(.vertical, 8) + .background(Theme.ok.opacity(0.10)) + .overlay(alignment: .bottom) { Rectangle().fill(Theme.ok.opacity(0.35)).frame(height: 1) } + } + } +} + +/// Beside a rebased branch's commit: when and onto what, each commit +/// before and after, and what to do with it. +struct RebasedCard: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + let rebase: BranchRebase + + var body: some View { + let _ = look + let base = model.projectInfo?.base ?? "the base" + let busy = model.pushing.contains(rebase.branch) + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Text("REBASED ONTO \(base.uppercased())").font(.ui(size: 10.5, weight: .bold)).foregroundStyle(Theme.ok) + if let at = rebase.at { Text("· \(agoText(at))").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) } + } + Text("\(rebase.branch) is on \(base) again").font(.ui(size: 13.5, weight: .semibold)) + .fixedSize(horizontal: false, vertical: true) + Text(rebase.summary + (branch.agent.map { " · \($0.agent?.name.capitalized ?? $0.displayName) is on this branch" } ?? "")) + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).fixedSize(horizontal: false, vertical: true) + if let cs = rebase.commits, !cs.isEmpty { + VStack(alignment: .leading, spacing: 3) { + Text("REWRITTEN COMMITS").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + ForEach(Array(cs.prefix(12).enumerated()), id: \.offset) { _, c in RewrittenRow(commit: c) } + if cs.count > 12 { + Text("and \(cs.count - 12) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + } + } + if case .moved(let h) = rebase.push { + Text("Somebody pushed \(String(h.prefix(8))) to \(rebase.branch) since: pushing would throw it away. Bring it in first.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true) + } + Button { model.review(rebase) } label: { + Text("Review the resolution").frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent).tint(Theme.accentDeep).controlSize(.regular) + .help("What resolving the conflict changed in each commit (git range-diff)") + HStack(spacing: 6) { + Button { model.pushRebase(rebase) } label: { Text(pushTitle(rebase)).frame(maxWidth: .infinity) } + .disabled(busy || pushBlocked(rebase)) + .help(pushHelp(rebase, base: base)) + Button { model.undoRebase(rebase) } label: { Text("Undo the rebase").frame(maxWidth: .infinity) } + .disabled(busy) + .help("Puts \(rebase.branch) back at \(String(rebase.before.prefix(8))), where it was before") + } + .controlSize(.small) + } + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(Theme.ok.opacity(0.08))) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.ok.opacity(0.30))) + } +} + +/// One commit before → after, and whether its change is what it was. +struct RewrittenRow: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + let commit: RebasedCommit + + var body: some View { + let _ = look + HStack(spacing: 6) { + Text(commit.old.map { String($0.prefix(7)) } ?? "—").strikethrough(commit.old != nil) + .foregroundStyle(Theme.muted) + Text("→").foregroundStyle(Theme.muted) + Text(commit.new.map { String($0.prefix(7)) } ?? "—").foregroundStyle(Theme.work) + Text(commit.subject).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1).truncationMode(.tail) + Spacer(minLength: 2) + if let (word, tone) = mark { + Text(word).font(.ui(size: 9.5, weight: .semibold)).foregroundStyle(tone) + .padding(.horizontal, 4).padding(.vertical, 1) + .background(RoundedRectangle(cornerRadius: 3).fill(tone.opacity(0.14))) + .fixedSize() + } + } + .font(.ui(size: 11, design: .monospaced)) + .accessibilityElement(children: .combine) + } + + var mark: (String, Color)? { + switch commit.change { + case "changed": ("resolved", Theme.warn) + case "dropped": ("dropped", Theme.muted) + case "added": ("new", Theme.work) + default: nil + } + } +} + +/// The review: git range-diff's account of the rebase, the resolution's +/// own lines marked, with the push and the undo at hand. +struct RebaseReviewSheet: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + let base = model.projectInfo?.base ?? "the base" + VStack(alignment: .leading, spacing: 0) { + if let r = model.reviewing { + VStack(alignment: .leading, spacing: 4) { + Text("Review the resolution").font(.ui(size: 15, weight: .semibold)) + Text("\(r.branch) onto \(base) · \(r.summary)").font(.ui(size: 12)).foregroundStyle(Theme.text2) + Text("Lines marked + or − are what the rebase changed in a commit's own diff: resolving the conflict, mostly. A commit that came across as it was shows as one line.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true) + } + .padding(16) + Rectangle().fill(Theme.line).frame(height: 1) + ScrollView([.vertical, .horizontal]) { + LazyVStack(alignment: .leading, spacing: 0) { + if !model.reviewError.isEmpty { + Text(model.reviewError).font(.ui(size: 12)).foregroundStyle(Theme.err).padding(12) + } else if let d = r.diff { + ForEach(rangeDiffLines(d)) { l in DiffOfDiffLine(line: l) } + } else { + ProgressView().controlSize(.small).padding(16) + } + } + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + } + .background(Theme.side) + Rectangle().fill(Theme.line).frame(height: 1) + HStack(spacing: 8) { + Button("Undo the Rebase…") { model.undoRebase(r) } + .disabled(model.pushing.contains(r.branch)) + Spacer() + Button("Close") { model.reviewing = nil }.keyboardShortcut(.cancelAction) + Button(pushTitle(r)) { model.pushRebase(r) } + .keyboardShortcut(.defaultAction) + .disabled(model.pushing.contains(r.branch) || pushBlocked(r) || !model.reviewError.isEmpty) + .help(pushHelp(r, base: base)) + } + .padding(12) + } + } + .frame(minWidth: 640, idealWidth: 760, minHeight: 420, idealHeight: 560) + .background(Theme.window) + } +} + +struct DiffOfDiffLine: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + let line: RangeDiffLine + + var body: some View { + let _ = look + let (fg, bg): (Color, Color) = switch line.kind { + case .commit: (Theme.text, Theme.raise) + case .hunk: (Theme.work, .clear) + case .added: (Theme.ok, Theme.ok.opacity(0.10)) + case .removed: (Theme.err, Theme.err.opacity(0.10)) + case .context: (Theme.text2, .clear) + } + Text(line.text.isEmpty ? " " : line.text) + .font(.ui(size: 11.5, weight: line.kind == .commit ? .semibold : .regular, design: .monospaced)) + .foregroundStyle(fg) + .lineLimit(1).fixedSize(horizontal: true, vertical: false) + .padding(.horizontal, 12).padding(.vertical, line.kind == .commit ? 4 : 0) + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .background(bg) + .padding(.top, line.kind == .commit && line.id > 0 ? 6 : 0) + .textSelection(.enabled) + } +} diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 6c0ff62f..61060628 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,7 +127,7 @@ A web page in a tab beside the agents. ## Commits -The project's history, agents' branches, conflicts, **CI** and **Autopilot**. +History, agents' branches, conflicts (resolved, reviewed, pushed), **CI**, **Autopilot**. **How:** **Commit Graph** on a project's or branch's menu. From b7cafecd6331f869d8dc5ffe5247fb1880aad208 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 22:35:29 -0800 Subject: [PATCH 29/35] Conch.app: fixes from looking at the rebase review live The graph's header ran off its right edge with a commit's panel open, so the repository format pill now waits for the room; the review sheet's diff sat in the middle of the sheet rather than at its top; undo said a conflict was back after a rebase that had none; and a branch brought into view (after an undo, or opening the graph at a branch) was picked without its panel reading it, which kept showing the commit before. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchApp/CommitsView.swift | 18 +++++++++++++----- macos/Sources/ConchApp/RebasedViews.swift | 6 +++++- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index a5291586..bbf433c8 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -300,7 +300,9 @@ final class CommitsModel: ObservableObject { guard let c = store.connection(machine) else { return } let a = NSAlert() a.messageText = "Undo the rebase of \(r.branch)?" - a.informativeText = "The branch goes back to \(String(r.before.prefix(8))), where it was before, and the conflict with \(projectInfo?.base ?? "the base") is back. " + let base = projectInfo?.base ?? "the base" + a.informativeText = "The branch goes back to \(String(r.before.prefix(8))), where it was before" + + (r.changed > 0 ? ", and its conflict with \(base) is back. " : ", behind \(base) again. ") + "The rebased commits stay in git's reflog (\(String(r.after.prefix(8)))). A worktree with uncommitted changes is not touched." a.addButton(withTitle: "Undo the Rebase") a.addButton(withTitle: "Cancel") @@ -315,6 +317,9 @@ final class CommitsModel: ObservableObject { if reviewing?.branch == r.branch { reviewing = nil } rebases[r.branch] = nil store.refreshProject(machine: machine, project: project) + // The commit picked was the rewrite, gone from the graph now: + // the branch's own tip, where it is back to, instead. + focusBranch = r.branch load() } catch { store.error = "Could not undo the rebase: \(error)" @@ -360,7 +365,8 @@ final class CommitsModel: ObservableObject { if let b = focusBranch { focusBranch = nil if let hit = rows.first(where: { CommitRef.parse($0.commit.refs, remotes: remotes ?? ["origin", "upstream"]).contains { $0.name == b } }) { - selected = hit.commit.hash + // Picked as a click would, so its panel reads it too. + pick(hit.commit.hash, shift: false) reveal += 1 } } @@ -547,7 +553,9 @@ struct CommitsView: View { Text("Commits").font(.ui(size: 13, weight: .semibold)).fixedSize() Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2).lineLimit(1).layoutPriority(-1) Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted).fixedSize() - if let f = model.format, !f.label.isEmpty { + // Left out while a panel takes the right side: the graph is + // narrow then, and the search, panels and refresh need the room. + if let f = model.format, !f.label.isEmpty, model.selected == nil, !model.sidePanel { Text(f.git3 ? "Git 3 · \(f.label)" : f.label) .font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(f.git3 ? Theme.accent : Theme.muted) .padding(.horizontal, 7).padding(.vertical, 2) @@ -955,7 +963,7 @@ struct StateTag: View { case .willConflict: ("⚠ will conflict", Theme.warn) case .ciFailing: ("✕ CI failed", Theme.err) case .waiting: ("waiting for you", Theme.warn) - case .rebased: ("✓ rebased · not pushed", Theme.ok) + case .rebased: ("✓ rebased", Theme.ok) default: nil } } @@ -1067,7 +1075,7 @@ struct BranchSideRow: View { func describe(_ b: GraphBranch) -> (String, Color) { switch b.state { case .conflicted(let n): ("conflict · \(n) file\(n == 1 ? "" : "s")", Theme.err) - case .rebased: ("rebased · not pushed", Theme.ok) + case .rebased: ("rebased", Theme.ok) case .waiting: ("waiting for you", Theme.warn) case .ciFailing: ("CI failed", Theme.err) case .willConflict: ("will conflict", Theme.warn) diff --git a/macos/Sources/ConchApp/RebasedViews.swift b/macos/Sources/ConchApp/RebasedViews.swift index 7ed016f5..3a20e9de 100644 --- a/macos/Sources/ConchApp/RebasedViews.swift +++ b/macos/Sources/ConchApp/RebasedViews.swift @@ -174,6 +174,9 @@ struct RebaseReviewSheet: View { } .padding(16) Rectangle().fill(Theme.line).frame(height: 1) + // Scrolling both ways centres what is smaller than the view; + // the diff starts at the top left, as text does. + GeometryReader { geo in ScrollView([.vertical, .horizontal]) { LazyVStack(alignment: .leading, spacing: 0) { if !model.reviewError.isEmpty { @@ -185,7 +188,8 @@ struct RebaseReviewSheet: View { } } .padding(.vertical, 8) - .frame(maxWidth: .infinity, alignment: .leading) + .frame(minWidth: geo.size.width, minHeight: geo.size.height, alignment: .topLeading) + } } .background(Theme.side) Rectangle().fill(Theme.line).frame(height: 1) From 49984cff8649ee9bff9d2e776b870cfd1f4567ec Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sat, 14 Nov 2026 22:37:20 -0800 Subject: [PATCH 30/35] Conch.app: no compare hint while the CI or Autopilot panel is open MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With either panel open the graph is narrow and the hint was cut to "shi…"; it is left out then, as it already was with a commit picked. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchApp/CommitsView.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index bbf433c8..4f2b3e7b 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -575,7 +575,7 @@ struct CommitsView: View { .overlay(RoundedRectangle(cornerRadius: 6).stroke(Theme.line)) // Said until a commit is picked: with its panel open the graph // is narrow, and the search and refresh need the room. - if model.selected == nil { + if model.selected == nil && !model.sidePanel { Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1).layoutPriority(-2) } if model.canAutopilot { From 3643e3ffcfd6dca84698efd37ce9d7adc6256820 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 11:21:37 -0800 Subject: [PATCH 31/35] branch.resolving: who was asked to resolve a branch's conflict, kept while it is there An agent asked to resolve a conflict works for a while, and all git shows meanwhile is a branch stuck mid-rebase, so a client could only say it was stuck. The person's ask (branch.resolving) and the autopilot's are kept on the branch's worktree (WorktreeInfo.Resolve) until a fresh read of git shows the conflict gone, or the branch has not moved for two minutes after it. Kept in memory: a reload forgets it. Co-Authored-By: Claude Opus 5.5 --- internal/proto/proto.go | 32 ++++- internal/server/autopilot_resolve.go | 3 + internal/server/autopilot_test.go | 11 ++ internal/server/projects.go | 4 + internal/server/resolving.go | 140 +++++++++++++++++++++ internal/server/resolving_internal_test.go | 68 ++++++++++ internal/server/resolving_test.go | 87 +++++++++++++ internal/server/scope.go | 3 +- internal/server/server.go | 9 +- web/src/app/docs/protocol/page.mdx | 1 + 10 files changed, 355 insertions(+), 3 deletions(-) create mode 100644 internal/server/resolving.go create mode 100644 internal/server/resolving_internal_test.go create mode 100644 internal/server/resolving_test.go diff --git a/internal/proto/proto.go b/internal/proto/proto.go index 68745c61..8c911d46 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, CapAutopilotActivity, CapBranchRebased, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapCIStats, CapCIRerun, CapAutopilotActivity, CapBranchRebased, CapBranchResolving, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -244,6 +244,12 @@ const CapCIRerun = "ci.rerun.v1" // a lease (BranchPushParams.Over) or undone. const CapBranchRebased = "branch.rebased.v1" +// CapBranchResolving is branch.resolving and WorktreeInfo.Resolve: which +// agent was asked to resolve a branch's conflict with the base — by the +// person or the autopilot — kept while the conflict is there, so a client +// can say the agent is at it rather than that the branch is stuck. +const CapBranchResolving = "branch.resolving.v1" + // CapAgentReply is agent.reply: an agent's last answer, whole, from its // saved conversation rather than off its screen. const CapAgentReply = "agent.reply.v1" @@ -654,6 +660,9 @@ const ( // rebases, and MethodBranchRebaseUndo puts one back (CapBranchRebased). MethodBranchRebased = "branch.rebased" MethodBranchRebaseUndo = "branch.rebase_undo" + // MethodBranchResolving says which agent was asked to resolve a + // branch's conflict, or that nobody is any more (CapBranchResolving). + MethodBranchResolving = "branch.resolving" // Leftover worktrees: list what each would lose, and remove them. MethodWorktreeStale = "worktree.stale" MethodWorktreeCleanup = "worktree.cleanup" @@ -1000,6 +1009,19 @@ type WorktreeInfo struct { // rewriting: git detaches HEAD while it works, so Branch is empty and // this says whose conflict it is. Absent from older servers. Rebasing string `json:"rebasing,omitempty"` + // Resolve is the agent asked to resolve the branch's conflict with + // the base, while that conflict is there (CapBranchResolving). + Resolve *ResolveAsk `json:"resolve,omitempty"` +} + +// ResolveAsk is an agent asked to resolve a branch's conflict: its pane, +// who asked ("autopilot", or empty for the person), when, and the files +// that conflicted then. +type ResolveAsk struct { + Pane string `json:"pane"` + By string `json:"by,omitempty"` + At time.Time `json:"at"` + Files []string `json:"files,omitempty"` } // Overlap is another branch's checkout touching the same files. @@ -1827,6 +1849,14 @@ type BranchRebaseUndoParams struct { After string `json:"after"` } +// BranchResolvingParams names the agent (its pane) asked to resolve +// Branch's conflict; an empty PaneID says nobody is any more. +type BranchResolvingParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch"` + PaneID string `json:"pane_id,omitempty"` +} + // BranchPushResult says what a push did: Took counts the commits a rebase // brought in from the remote, 0 when nothing was taken. type BranchPushResult struct { diff --git a/internal/server/autopilot_resolve.go b/internal/server/autopilot_resolve.go index 6284d1e5..79654ac9 100644 --- a/internal/server/autopilot_resolve.go +++ b/internal/server/autopilot_resolve.go @@ -268,6 +268,9 @@ func (s *Server) askToResolve(p *project, branch string, rw rewrite, files []str note(fmt.Sprintf("%s conflicts with %s, and asking %s to resolve it failed: %s", branch, rw.Base, agent.DisplayName(), perr.Message), true) return } + ask := newAsk(ctx, p, branch, wt.Path, agent.ID, "autopilot") + ask.Files = files // what the rebase onto the remote's base stopped on + s.projects.noteResolveAsk(p, branch, ask) note(fmt.Sprintf("%s conflicts with %s in %s: asked %s to resolve it", branch, rw.Base, strings.Join(files, ", "), agent.DisplayName()), false) } diff --git a/internal/server/autopilot_test.go b/internal/server/autopilot_test.go index e81f8f7c..c1ff5764 100644 --- a/internal/server/autopilot_test.go +++ b/internal/server/autopilot_test.go @@ -6,6 +6,7 @@ import ( "os/exec" "path/filepath" "reflect" + "slices" "strings" "testing" "time" @@ -840,6 +841,16 @@ func TestAutopilotResolveAsksTheAgent(t *testing.T) { if apGit(t, origin, "rev-parse", "api/model") != pushed { t.Fatal("pushed before the agent resolved it") } + // Said on the branch's worktree, so a client shows the agent at it. + var ask *proto.ResolveAsk + for _, w := range p.snapshot().Worktrees { + if w.Path == wt { + ask = w.Resolve + } + } + if ask == nil || ask.Pane != e.p.ID() || ask.By != "autopilot" || !slices.Equal(ask.Files, []string{"model.go"}) { + t.Errorf("ask: %+v", ask) + } a5WaitFor(t, "the request submitted", func() bool { st, _ := agentState(e); return st == proto.AgentIdle }) // The agent resolves it, keeping both sides, and finishes. diff --git a/internal/server/projects.go b/internal/server/projects.go index 29592b84..6f376243 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -182,6 +182,9 @@ type project struct { prOpen map[string]bool baseOwed map[string]bool baseFetching bool + // asks are the agents asked to resolve a branch's conflict, by + // branch (resolving.go). + asks map[string]resolveAsk } type catalog struct { @@ -631,6 +634,7 @@ func (pm *projectManager) apply(p *project, info proto.ProjectInfo, stamp string } p.gen++ p.applyPRs(&info) + p.applyAsks(&info, time.Now(), true) old := p.info info.LocalFiles, info.LocalFilesDefault = old.LocalFiles, old.LocalFilesDefault info.Setup = old.Setup diff --git a/internal/server/resolving.go b/internal/server/resolving.go new file mode 100644 index 00000000..2a99e1ae --- /dev/null +++ b/internal/server/resolving.go @@ -0,0 +1,140 @@ +package server + +import ( + "context" + "log" + "time" + + "github.com/Amitgb14/conch/internal/gitx" + "github.com/Amitgb14/conch/internal/proto" +) + +// An agent asked to resolve a branch's conflict with the base works for a +// while, and all git shows meanwhile is a branch stuck mid-rebase — or, +// before it has started, one that will conflict. So who was asked is +// kept on the branch's worktree (WorktreeInfo.Resolve) for as long as the +// conflict is there, and a client can say the agent is at it. +// +// It is kept in memory: a reload forgets it, and a client then goes by an +// agent working in a worktree stopped mid-rebase, which is nearly always +// the same thing. + +// askGrace is how long an ask outlives a conflict git no longer shows, +// while the branch has not moved: the agent has not started the rebase +// yet (the autopilot undoes its own before asking), or merge-tree could +// not say there was a conflict (git before 2.38). +const askGrace = 2 * time.Minute + +// resolveAsk is an ask and where the branch was when it was made. +type resolveAsk struct { + proto.ResolveAsk + head string +} + +// stillConflicts is whether a worktree shows a conflict with the base: +// stopped mid-rebase or merge, or one merging it would meet. +func stillConflicts(w proto.WorktreeInfo) bool { + return w.Rebasing != "" || (w.Status != nil && w.Status.Conflicts > 0) || len(w.Conflicts) > 0 +} + +// applyAsks puts each ask on its branch's worktree in info and, when info +// is a fresh read of git (fresh), forgets those whose conflict is over: +// an older read can predate the very rebase the agent was asked about. +// The caller holds p.mu, and info's Worktrees are its own to change. +func (p *project) applyAsks(info *proto.ProjectInfo, now time.Time, fresh bool) { + seen := map[string]bool{} + for i, w := range info.Worktrees { + info.Worktrees[i].Resolve = nil + name := w.Branch + if name == "" { + name = w.Rebasing + } + a, ok := p.asks[name] + if !ok || name == "" { + continue + } + seen[name] = true + if fresh && !stillConflicts(w) && (w.Head != a.head || now.Sub(a.At) > askGrace) { + delete(p.asks, name) // resolved, given up on, or never needed + continue + } + r := a.ResolveAsk + info.Worktrees[i].Resolve = &r + } + for name := range p.asks { + if fresh && !seen[name] { + delete(p.asks, name) // its worktree is gone + } + } +} + +// noteResolveAsk records ask (nil: nobody) for branch and says so to the +// clients at once rather than at the next refresh. +func (pm *projectManager) noteResolveAsk(p *project, branch string, ask *resolveAsk) { + p.mu.Lock() + if ask == nil { + delete(p.asks, branch) + } else { + if p.asks == nil { + p.asks = map[string]resolveAsk{} + } + p.asks[branch] = *ask + } + info := p.info + info.Worktrees = append([]proto.WorktreeInfo(nil), info.Worktrees...) + p.applyAsks(&info, time.Now(), false) + p.info = info + p.gen++ // a read of git begun before this is older than it + p.mu.Unlock() + if pm.s.projectRegistered(p) { + pm.s.broadcast(proto.EventProjectUpdated, info) + } +} + +// newAsk is pane asked to resolve branch, checked out at dir, by by. +func newAsk(ctx context.Context, p *project, branch, dir, pane, by string) *resolveAsk { + // The files a stopped rebase is waiting on; else those merging it + // would conflict in, from the last refresh. + files := gitx.ConflictFiles(ctx, dir) + for _, w := range p.snapshot().Worktrees { + if w.Path == dir && len(files) == 0 { + files = w.Conflicts + } + } + return &resolveAsk{ + ResolveAsk: proto.ResolveAsk{Pane: pane, By: by, At: time.Now(), Files: files}, + head: gitx.CommitOf(ctx, dir, "HEAD"), + } +} + +func (s *Server) branchResolving(rp proto.BranchResolvingParams) (struct{}, *proto.Error) { + p, perr := s.projects.gitProject(rp.ProjectID) + if perr != nil { + return struct{}{}, perr + } + if rp.Branch == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "say which branch") + } + if rp.PaneID == "" { + s.projects.noteResolveAsk(p, rp.Branch, nil) + return struct{}{}, nil + } + if _, perr := s.get(rp.PaneID); perr != nil { + return struct{}{}, perr + } + // Mid-rebase git names no branch: the worktree rewriting it is the one. + dir := "" + for _, w := range p.snapshot().Worktrees { + if w.Branch == rp.Branch || (w.Branch == "" && w.Rebasing == rp.Branch) { + dir = w.Path + } + } + if dir == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%s is not checked out here", rp.Branch) + } + ctx, cancel := context.WithTimeout(context.Background(), gitTimeout) + defer cancel() + s.projects.noteResolveAsk(p, rp.Branch, newAsk(ctx, p, rp.Branch, dir, rp.PaneID, "")) + log.Printf("project %s: pane %s is resolving %s's conflict", p.id, rp.PaneID, rp.Branch) + return struct{}{}, nil +} diff --git a/internal/server/resolving_internal_test.go b/internal/server/resolving_internal_test.go new file mode 100644 index 00000000..c5355716 --- /dev/null +++ b/internal/server/resolving_internal_test.go @@ -0,0 +1,68 @@ +package server + +import ( + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// When an ask is forgotten: only on a fresh read of git, once the branch +// shows no conflict and has moved, or has not moved for askGrace; and +// with its worktree. +func TestApplyAsks(t *testing.T) { + now := time.Now() + ask := func(head string, at time.Time) resolveAsk { + return resolveAsk{ResolveAsk: proto.ResolveAsk{Pane: "p1", At: at}, head: head} + } + info := func(ws ...proto.WorktreeInfo) proto.ProjectInfo { return proto.ProjectInfo{Worktrees: ws} } + stopped := proto.WorktreeInfo{Path: "/w/a", Rebasing: "a", Head: "h2", Status: &proto.GitStatus{Conflicts: 1}} + clean := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h1"} + moved := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h3"} + coming := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h3", Conflicts: []string{"x.go"}} + + cases := []struct { + name string + w proto.WorktreeInfo + at time.Time + fresh bool + kept bool + }{ + {"stopped mid-rebase", stopped, now.Add(-time.Hour), true, true}, + {"will conflict", coming, now.Add(-time.Hour), true, true}, + {"not started yet", clean, now, true, true}, + {"never started", clean, now.Add(-askGrace - time.Second), true, false}, + {"rebase finished", moved, now, true, false}, + {"an older read", moved, now, false, true}, + } + for _, c := range cases { + p := &project{asks: map[string]resolveAsk{"a": ask("h1", c.at)}} + in := info(c.w) + p.applyAsks(&in, now, c.fresh) + if got := in.Worktrees[0].Resolve != nil; got != c.kept { + t.Errorf("%s: shown %v, want %v", c.name, got, c.kept) + } + if _, got := p.asks["a"]; got != c.kept { + t.Errorf("%s: kept %v, want %v", c.name, got, c.kept) + } + } + + // Its worktree gone: forgotten, but not on an older read. + p := &project{asks: map[string]resolveAsk{"a": ask("h1", now)}} + in := info(proto.WorktreeInfo{Path: "/w/b", Branch: "b", Resolve: &proto.ResolveAsk{Pane: "stale"}}) + p.applyAsks(&in, now, false) + if len(p.asks) != 1 || in.Worktrees[0].Resolve != nil { + t.Errorf("older read: %v %+v", p.asks, in.Worktrees[0].Resolve) + } + p.applyAsks(&in, now, true) + if len(p.asks) != 0 { + t.Errorf("worktree gone, still asked: %v", p.asks) + } + // Nothing asked: nothing shown, and a nil map is fine. + p = &project{} + in = info(stopped) + p.applyAsks(&in, now, true) + if in.Worktrees[0].Resolve != nil { + t.Error("shown with no ask") + } +} diff --git a/internal/server/resolving_test.go b/internal/server/resolving_test.go new file mode 100644 index 00000000..439ecb8b --- /dev/null +++ b/internal/server/resolving_test.go @@ -0,0 +1,87 @@ +package server_test + +import ( + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + + "github.com/Amitgb14/conch/internal/proto" +) + +// resolveOf is the ask on the worktree at path, as the project says. +func resolveOf(p proto.ProjectInfo, path string) *proto.ResolveAsk { + for _, w := range p.Worktrees { + if w.Path == path { + return w.Resolve + } + } + return nil +} + +// Who was asked to resolve a branch's conflict is on its worktree for as +// long as the conflict is there, so a client can say an agent is at it, +// and gone once the rebase is finished. +func TestBranchResolving(t *testing.T) { + c, proj, repo, wt, _ := harvestFixture(t) + if miss := c.MissingCapabilities([]string{proto.CapBranchResolving}); len(miss) > 0 { + t.Fatalf("missing %v", miss) + } + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-qam", "feat edits a") + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-qam", "main edits a") + cmd := exec.Command("git", "-C", wt, "rebase", "main") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + var pane proto.PaneInfo + if err := call(t, c, proto.MethodPaneCreate, proto.PaneCreateParams{Command: []string{"/bin/sh", "-c", "sleep 30"}, Cwd: wt}, &pane); err != nil { + t.Fatal(err) + } + + // Mid-rebase git names no branch; the ask is by the branch all the same. + ask := proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat", PaneID: pane.ID} + if err := call(t, c, proto.MethodBranchResolving, ask, nil); err != nil { + t.Fatal(err) + } + got := waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) != nil }) + r := resolveOf(got, wt) + if r.Pane != pane.ID || r.By != "" || r.At.IsZero() || !slices.Equal(r.Files, []string{"a.txt"}) { + t.Errorf("ask: %+v", r) + } + + // Taken back by the person: no longer said. + if err := call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat"}, nil); err != nil { + t.Fatal(err) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) == nil }) + + // Asked again, then resolved: gone with the conflict. + if err := call(t, c, proto.MethodBranchResolving, ask, nil); err != nil { + t.Fatal(err) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) != nil }) + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("main\nfeat\n"), 0o644) + git(t, wt, "add", "a.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { + for _, w := range p.Worktrees { + if w.Path == wt { + return w.Branch == "feat" && w.Resolve == nil + } + } + return false + }) + + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat", PaneID: "nope"}, nil), "no pane") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "nope", PaneID: pane.ID}, nil), "not checked out") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, PaneID: pane.ID}, nil), "") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: "nope", Branch: "feat"}, nil), "") +} diff --git a/internal/server/scope.go b/internal/server/scope.go index 4284e490..bff81caf 100644 --- a/internal/server/scope.go +++ b/internal/server/scope.go @@ -124,7 +124,7 @@ var scoped = map[string]scopeKind{ proto.MethodBranchCommit: scopeProject, proto.MethodBranchStage: scopeProject, proto.MethodBranchReview: scopeProject, proto.MethodBranchPush: scopeProject, proto.MethodBranchPR: scopeProject, proto.MethodBranchMerge: scopeProject, proto.MethodBranchPRMerge: scopeProject, proto.MethodBranchDiscard: scopeProject, proto.MethodBranchGit: scopeProject, // Running CI again spends the project's Actions minutes. - proto.MethodCIRerun: scopeProject, proto.MethodBranchRebaseUndo: scopeProject, + proto.MethodCIRerun: scopeProject, proto.MethodBranchRebaseUndo: scopeProject, proto.MethodBranchResolving: scopeProject, proto.MethodServerStop: scopeServer, proto.MethodServerReload: scopeServer, // The cloud agent decides what every agent's environment is given. @@ -433,6 +433,7 @@ var verbs = map[string]string{ proto.MethodBranchGit: "run git", proto.MethodCIRerun: "re-run the CI of", proto.MethodBranchRebaseUndo: "undo the rebase of", + proto.MethodBranchResolving: "say who resolves", proto.MethodTicketUpdate: "change a ticket", proto.MethodAgentSkill: "install or remove the agents' conch skill", proto.MethodProjectFiles: "change which local files a project copies into its worktrees", diff --git a/internal/server/server.go b/internal/server/server.go index c958d8e1..1f4876d6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -454,7 +454,7 @@ var slowMethods = map[string]bool{ proto.MethodProjectFiles: true, proto.MethodProjectSetup: true, proto.MethodSessionList: true, proto.MethodSessionResume: true, proto.MethodSessionDelete: true, proto.MethodSessionSearch: true, proto.MethodSessionShare: true, proto.MethodSessionExport: true, proto.MethodFSUpload: true, proto.MethodBranchCommit: true, proto.MethodBranchStage: true, proto.MethodBranchPush: true, proto.MethodBranchPR: true, - proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodBranchRebased: true, proto.MethodBranchRebaseUndo: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, + proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodBranchRebased: true, proto.MethodBranchRebaseUndo: true, proto.MethodBranchResolving: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, proto.MethodProjectTickets: true, proto.MethodTicketGet: true, proto.MethodTicketUpdate: true, proto.MethodTicketCheck: true, proto.MethodTicketOverview: true, proto.MethodWorktreeStale: true, proto.MethodWorktreeCleanup: true, proto.MethodProjectResolve: true, proto.MethodProjectGitInit: true, proto.MethodWorktreeDescribe: true, proto.MethodWorktreeHave: true, proto.MethodWorktreePack: true, @@ -1056,6 +1056,13 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { } return s.projects.undoRebase(up) + case proto.MethodBranchResolving: + rp, perr := decode[proto.BranchResolvingParams](msg) + if perr != nil { + return nil, perr + } + return s.branchResolving(rp) + case proto.MethodProjectLog: lp, perr := decode[proto.LogParams](msg) if perr != nil { diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index 9570dcb9..32dd4b3e 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -40,6 +40,7 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | | Rebased branches | `branch.rebased` lists each checked-out branch whose newest change is a finished rebase not yet pushed — or one `branch`'s — with its tip `before` and `after`, the commit it went `onto`, what the `remote` has, and each commit's fate (`same`, `changed` where a conflict was resolved, `dropped`, `added`); `diff` adds git range-diff's account. A push with `over` replaces the remote's branch only if it is still that commit, and `branch.rebase_undo` puts a branch back at `before` while it is still at `after` (capability `branch.rebased.v1`) | +| Resolving a conflict | `branch.resolving` names the agent (`pane_id`) asked to resolve a `branch`'s conflict with the base, or with no `pane_id` that nobody is; the project's worktree then carries `resolve` — the `pane`, `by` (`autopilot`, or empty for the person), `at` and the `files` — while the conflict is there. The autopilot sets it when it hands a conflict to an agent. Kept in memory, so a reload forgets it (capability `branch.resolving.v1`) | | CI | `ci.stats` adds up a project's GitHub Actions runs over `days` (14 by default, 90 at most) and the same span before: runs, passes and failures, median run, queue and red-to-green times, runs per day, each job's median and slowest tenth, flaky jobs, and each workflow's newest failed run per branch; a few dozen runs' jobs are read per call and `jobs_pending` says how many are left (capability `ci.stats.v1`). `ci.rerun` runs a run's failed jobs again, by `run_id` or a `branch`'s newest failed run (capability `ci.rerun.v1`). Both go through `gh` on the project's machine | | Autopilot activity | every `autopilot.note` the server sends carries its `kind` (`ci`, `check`, `ship`, `merge`, `resolve`, `intake`, `triage`) and `at`, and is kept — the newest 500, in `autopilot-activity.jsonl` beside the config, so a restart keeps them; `autopilot.activity` lists them newest first, for a `project_id` or every project, `limit` at most (100 by default) (capability `autopilot.activity.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | From f3c9853447ebe41e1165354e6947f331bc1c4059 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 11:23:43 -0800 Subject: [PATCH 32/35] Conch.app: an agent resolving a conflict, shown while it works The conflict banner stayed red and said the branch was stopped for as long as the agent asked to resolve it worked. Now it says the agent is at it (blue, files left, who asked and when, Show), waiting on the person (Answer), or stopped with the conflict still there, or its pane ended (red, Ask again). The branch list, the graph's tag and the commit's card say the same. Asking records it with branch.resolving; from an older server an agent working in a worktree stopped mid-rebase counts as resolving it. Also: starting a new agent for a branch stopped mid-rebase said it had no worktree, since git names no branch there; branchWorktree finds it. Co-Authored-By: Claude Opus 5.5 --- docs/testing/end-to-end.md | 1 + macos/Sources/ConchApp/CommitsView.swift | 92 ++++++++--- macos/Sources/ConchApp/RebasedViews.swift | 2 +- macos/Sources/ConchApp/Store.swift | 25 ++- macos/Sources/ConchKit/BranchGraph.swift | 148 ++++++++++++++++-- macos/Sources/ConchKit/Protocol.swift | 19 +++ .../ConchKitTests/BranchGraphTests.swift | 6 +- .../Tests/ConchKitTests/ResolvingTests.swift | 125 +++++++++++++++ web/src/app/docs/mac-app/page.mdx | 2 +- 9 files changed, 378 insertions(+), 42 deletions(-) create mode 100644 macos/Tests/ConchKitTests/ResolvingTests.swift diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index c8c2c046..e5ef5892 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -418,6 +418,7 @@ What it carries, and what is left over in each row: | 9.176 🌐 | The CI panel against real GitHub Actions | On a project with a month of real Actions history and `gh` logged in: **Commit Graph** → **CI**, then 7d, 14d and 30d; on a busy repository watch *Reading the jobs of N more runs…* fill in; break a test on a branch, let its run fail, then **Re-run failed jobs** in the panel and **Re-run Failed Jobs** on the branch's menu | The numbers match GitHub's Actions page for the period (pass rate, the failing runs, a job's time); the re-run starts a new attempt of that run on GitHub, the button says *Re-running…* until the attempt shows, and the pull request's checks turn pending | ☐ | | 9.177 💳🌐 | The autopilot's activity in Conch.app | With the autopilot on (auto_fix, auto_merge, auto_resolve, a check) for a real GitHub repository and a real agent on a task branch: open **Commit Graph** → **Autopilot** and leave it open; break a test so CI fails, let the agent fix it, let the pull request merge; then quit everything, reload the server, and open it again | Each step appears in *What it did* as it happens (CI sent to the agent, pushed, merged), marked by kind, under Today, with the branch a link to its commits; *Minding now* follows the branch; the rules match Settings; after the reload the feed is all still there | ☐ | | 9.178 💳 | Review and push a resolved rebase in Conch.app | A task branch pushed with a pull request, then the base changed on the same lines: open **Commit Graph**, **Ask an agent to resolve** with a real agent, wait for it to finish the rebase | The banner turns green (*rebased onto master*), the branch's card lists each commit old → new with the conflicted one marked *resolved*; **Review the resolution** shows the agent's own lines as + / −; **Push (with lease)** replaces the old branch on GitHub and the pull request updates; on a second run, **Undo the rebase** puts the branch back and the conflict returns; with a commit pushed from elsewhere in between, the push is refused rather than overwriting it | ☐ | +| 9.179 💳 | Watch an agent resolve a conflict in Conch.app | A task branch whose rebase onto master stopped on a conflict: open **Commit Graph**, **Ask an agent to resolve** with a real agent; then once more with `auto_resolve` on and the autopilot asking | While the agent works the banner turns blue (*Claude is resolving the conflict with master*, *N of M files left · you asked …*, or *the autopilot asked*), the branch reads *resolving*, and **Show Claude** opens its pane; when the agent asks a permission question the banner says it is waiting on you; it turns green once the rebase is finished; closing the agent's pane mid-way turns it red (*has ended*) with **Ask again**; after `conch server reload` an agent still working in the stopped worktree still reads *resolving* | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 4f2b3e7b..1e2761b1 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -125,6 +125,12 @@ final class CommitsModel: ObservableObject { store.askToResolve(machine: machine, project: project, branch: b, start: start) } + /// Brings the agent resolving b's conflict forward. + func showResolver(_ b: GraphBranch) { + guard let p = b.resolver, p.running else { return } + store.open(ConchKit.key(machine, p.id)) + } + var canAutopilot: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.v1") == true } var canActivity: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.activity.v1") == true } @@ -964,6 +970,9 @@ struct StateTag: View { case .ciFailing: ("✕ CI failed", Theme.err) case .waiting: ("waiting for you", Theme.warn) case .rebased: ("✓ rebased", Theme.ok) + case .resolving: ("resolving", Theme.work) + case .resolveWaiting: ("resolving · needs you", Theme.warn) + case .resolveStopped: ("✕ resolve stopped", Theme.err) default: nil } } @@ -1046,8 +1055,11 @@ struct BranchSideRow: View { .accessibilityAddTraits(.isButton) .accessibilityAction { toggle(on) } .contextMenu { - if branch.state.conflicts { - Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(branch) } + if branch.state == .resolving || branch.state == .resolveWaiting, let r = branch.resolver { + Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) } + } else if branch.state.conflicts { + let again = { if case .resolveStopped = branch.state { return " Again" } else { return "" } }() + Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve" + again) { model.askToResolve(branch) } } if let r = branch.rebase { Button("Review the Resolution…") { model.review(r) } @@ -1079,6 +1091,9 @@ struct BranchSideRow: View { case .waiting: ("waiting for you", Theme.warn) case .ciFailing: ("CI failed", Theme.err) case .willConflict: ("will conflict", Theme.warn) + case .resolving: ("resolving", Theme.work) + case .resolveWaiting: ("needs you", Theme.warn) + case .resolveStopped: ("stopped resolving", Theme.err) case .working: ("working", Theme.work) case .done: ("done", Theme.ok) case .idle: ("idle", Theme.muted) @@ -1088,7 +1103,8 @@ struct BranchSideRow: View { /// Above the graph when a branch's rebase or merge stopped on conflicts: /// what stopped, and the agent to ask — the branch's own, or another one -/// started in its worktree. +/// started in its worktree. Once one is asked, how that is going: at it, +/// waiting on the person, or stopped with the conflict still there. struct ConflictBanner: View { /// Read so this is drawn again when the theme changes (ThemeLook). @Environment(\.conchTheme) private var look @@ -1096,25 +1112,58 @@ struct ConflictBanner: View { var body: some View { let _ = look - if let b = model.branches.first(where: \.stopped) { - let n: Int = { if case .conflicted(let n) = b.state { return n } else { return 0 } }() + if let b = conflictBannerBranch(model.branches) { + let base = model.projectInfo?.base ?? "the base" + let tone = resolveTone(b.state) HStack(spacing: 10) { - Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Theme.err) + if b.state == .resolving { + ProgressView().controlSize(.small).frame(width: 16) + } else { + Image(systemName: b.state == .resolveWaiting ? "hand.raised.fill" : "exclamationmark.triangle.fill").foregroundStyle(tone) + } VStack(alignment: .leading, spacing: 1) { - Text("\(b.name) stopped on a conflict with \(model.projectInfo?.base ?? "the base")").font(.ui(size: 12.5, weight: .semibold)) - Text("\(n) file\(n == 1 ? "" : "s") to resolve in its worktree. Nothing has been pushed.") - .font(.ui(size: 11.5)).foregroundStyle(Theme.text2) + Text(b.state.resolution ? resolveHeadline(b, base: base) : "\(b.name) stopped on a conflict with \(base)") + .font(.ui(size: 12.5, weight: .semibold)).lineLimit(2) + Text(b.state.resolution ? resolveDetail(b) + "." : stoppedDetail(b)) + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(2) } Spacer(minLength: 8) - ResolveButton(model: model, branch: b) + switch b.state { + case .resolving, .resolveWaiting: + if let r = b.resolver, r.running { + Button(b.state == .resolveWaiting ? "Answer \(resolverName(b) ?? r.displayName)…" : "Show \(resolverName(b) ?? r.displayName)") { + model.showResolver(b) + } + .controlSize(.small).tint(Theme.accentDeep) + .help("Opens the agent's pane") + } + default: + ResolveButton(model: model, branch: b) + } Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: b.name) } .controlSize(.small) } .padding(.horizontal, 12).padding(.vertical, 8) - .background(Theme.err.opacity(0.12)) - .overlay(alignment: .bottom) { Rectangle().fill(Theme.err.opacity(0.35)).frame(height: 1) } + .background(tone.opacity(0.12)) + .overlay(alignment: .bottom) { Rectangle().fill(tone.opacity(0.35)).frame(height: 1) } + .accessibilityElement(children: .contain) } } + + func stoppedDetail(_ b: GraphBranch) -> String { + let n = b.stoppedFiles + return "\(n) file\(n == 1 ? "" : "s") to resolve in its worktree. Nothing has been pushed." + } +} + +/// The colour of a conflict in each state: an agent at it is work in +/// hand, one asking is the person's, stuck is an error. +@MainActor func resolveTone(_ s: GraphBranchState) -> Color { + switch s { + case .resolving: Theme.work + case .resolveWaiting, .willConflict: Theme.warn + default: Theme.err + } } /// Ask the branch's agent to resolve its conflict, or pick another agent @@ -1135,7 +1184,8 @@ struct ResolveButton: View { ForEach(startable, id: \.name) { a in Button(a.title) { model.askToResolve(branch, start: a.name) } } } } label: { - Text(who.map { "Ask \($0) to resolve" } ?? "Ask an agent to resolve") + let again = { if case .resolveStopped = branch.state { return " again" } else { return "" } }() + Text((who.map { "Ask \($0) to resolve" } ?? "Ask an agent to resolve") + again) } primaryAction: { if branch.agent != nil { model.askToResolve(branch) @@ -1159,12 +1209,14 @@ struct ConflictCard: View { var body: some View { let _ = look let stopped = branch.stopped - let tone = stopped ? Theme.err : Theme.warn + let resolution = branch.state.resolution + let tone = resolution ? resolveTone(branch.state) : stopped ? Theme.err : Theme.warn let base = model.projectInfo?.base ?? "the base" VStack(alignment: .leading, spacing: 6) { - Text(stopped ? "Stopped on a conflict with \(base)" : "Will conflict with \(base)") - .font(.ui(size: 12.5, weight: .semibold)).foregroundStyle(tone) - Text(stopped ? "The rebase or merge in \(branch.name)'s worktree is waiting for these files to be resolved." + Text(resolution ? resolveHeadline(branch, base: base) : stopped ? "Stopped on a conflict with \(base)" : "Will conflict with \(base)") + .font(.ui(size: 12.5, weight: .semibold)).foregroundStyle(tone).fixedSize(horizontal: false, vertical: true) + Text(resolution ? resolveDetail(branch) + "." + : stopped ? "The rebase or merge in \(branch.name)'s worktree is waiting for these files to be resolved." : "\(base) changed the same lines as \(branch.name). Nothing has moved yet: git merge-tree tried it.") .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).fixedSize(horizontal: false, vertical: true) ForEach(branch.conflicts.prefix(6), id: \.self) { f in @@ -1173,7 +1225,11 @@ struct ConflictCard: View { if branch.conflicts.count > 6 { Text("and \(branch.conflicts.count - 6) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) } - ResolveButton(model: model, branch: branch) + if (branch.state == .resolving || branch.state == .resolveWaiting), let r = branch.resolver, r.running { + Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) }.controlSize(.small) + } else { + ResolveButton(model: model, branch: branch) + } } .padding(10) .background(RoundedRectangle(cornerRadius: 8).fill(tone.opacity(0.10))) diff --git a/macos/Sources/ConchApp/RebasedViews.swift b/macos/Sources/ConchApp/RebasedViews.swift index 3a20e9de..cb899365 100644 --- a/macos/Sources/ConchApp/RebasedViews.swift +++ b/macos/Sources/ConchApp/RebasedViews.swift @@ -39,7 +39,7 @@ struct RebasedBanner: View { var body: some View { let _ = look let bs = model.branches - if !bs.contains(where: \.stopped), let b = bs.first(where: { $0.rebase != nil }), let r = b.rebase { + if conflictBannerBranch(bs) == nil, let b = bs.first(where: { $0.rebase != nil }), let r = b.rebase { let base = model.projectInfo?.base ?? "the base" HStack(spacing: 10) { Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.ok) diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index f8121445..339603d4 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -3086,7 +3086,8 @@ final class Store: ObservableObject { /// Starts an agent (or, without one, a terminal) and shows it in a tab /// of its own, as the TUI's c and n do. - func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?, prompt: String? = nil) { + func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?, prompt: String? = nil, + started: ((PaneInfo) -> Void)? = nil) { guard let c = conns[machine] else { return } struct Create: Encodable { var agent: String? @@ -3106,6 +3107,7 @@ final class Store: ObservableObject { joinWorkspace(machine: machine, pane: p) layout.open(key(machine, p.id)) focusTerminal() + started?(p) } catch { self.error = "Could not start \(agent ?? "a terminal"): \(error)" } @@ -3316,15 +3318,32 @@ final class Store: ObservableObject { do { try await c.call("agent.prompt", Params(id: a.id, text: text)) self.say("Asked \(a.displayName) to resolve \(branch.name)") + self.noteResolving(machine: machine, project: project, branch: branch.name, pane: a.id) } catch { self.error = "\(error)" } } return } - guard let path = pr.worktrees?.first(where: { $0.branch == branch.name })?.path else { + guard let path = branchWorktree(pr, branch.name)?.path else { error = "\(branch.name) has no worktree to start an agent in" return } - newPane(machine: machine, cwd: path, inProject: true, agent: start ?? startable(on: machine).first?.name, prompt: text) + newPane(machine: machine, cwd: path, inProject: true, agent: start ?? startable(on: machine).first?.name, prompt: text) { p in + self.noteResolving(machine: machine, project: project, branch: branch.name, pane: p.id) + } + } + + /// Tells the server which agent is resolving branch's conflict, so the + /// graph says it is at it — in every client, and after the autopilot + /// looks. An older server keeps no asks: the graph then goes by an + /// agent working in the stopped worktree. + func noteResolving(machine: String, project: String, branch: String, pane: String) { + guard let c = conns[machine], c.hello?.capabilities?.contains("branch.resolving.v1") == true else { return } + struct P: Encodable { var project_id: String; var branch: String; var pane_id: String } + Task { + do { try await c.call("branch.resolving", P(project_id: project, branch: branch, pane_id: pane)) } catch { + NSLog("conch: saying %@ resolves %@: %@", pane, branch, "\(error)") + } + } } /// Opens the task sheet to hand a commit to an agent: a new branch diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift index 24f7bade..42c5f4ea 100644 --- a/macos/Sources/ConchKit/BranchGraph.swift +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -53,6 +53,11 @@ public func commitOwners(_ commits: [LogCommit], base: String, remotes: Set 0 || midRebase } } +/// How long an agent just asked has to start before not working means it +/// stopped. +public let resolveStartGrace: TimeInterval = 30 + /// The project's agent branches — every branch checked out in a worktree /// of its own, never the base or the main checkout — with the state each /// is in, most urgent first and otherwise as the worktrees are listed. /// Rebased is the server's list of branches rebased and not pushed, by /// name. -public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [String: BranchRebase] = [:]) -> [GraphBranch] { +public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [String: BranchRebase] = [:], now: Date = Date()) -> [GraphBranch] { let base = project.base ?? "" let mainBranches = Set((project.worktrees ?? []).filter { $0.main == true }.compactMap(\.branch)) let info = Dictionary((project.branches ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) @@ -135,9 +166,36 @@ public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [S } let agent = branchAgent(branchAgents(panes, project: project.id, branch: name) + inFolder, handedTo: nil) let pr = b?.pr.flatMap { ($0.state ?? "OPEN") == "OPEN" ? $0 : nil } + let stoppedFiles = max(w.status?.conflicts ?? 0, 0) + let midRebase = w.rebasing != nil && w.branch == nil + let stopped = stoppedFiles > 0 || midRebase + let conflicting = stopped || !(w.conflicts ?? []).isEmpty + // The agent at its conflict: the one asked, while its pane is + // there; else, from a server keeping no asks, one busy in a + // worktree stopped mid-rebase — nothing else is done there. + var resolver: PaneInfo? + var resolve: GraphBranchState? + if let ask = w.resolve, conflicting { + let p = panes.first { $0.id == ask.pane } + resolver = p + if let p, p.running, p.agent?.state == .working { + resolve = .resolving + } else if let p, p.running, p.agent?.state == .blocked { + resolve = .resolveWaiting + } else if let p, p.running, let at = ask.at, now.timeIntervalSince(at) < resolveStartGrace { + resolve = .resolving + } else { + resolve = .resolveStopped(ended: !(p?.running ?? false)) + } + } else if w.resolve == nil, stopped, let a = agent, a.agent?.state == .working || a.agent?.state == .blocked { + resolver = a + resolve = a.agent?.state == .working ? .resolving : .resolveWaiting + } let state: GraphBranchState - if let n = w.status?.conflicts, n > 0 { - state = .conflicted(n) + if let resolve { + state = resolve + } else if stoppedFiles > 0 { + state = .conflicted(stoppedFiles) } else if rebased[name] != nil { state = .rebased } else if agent?.agent?.state == .blocked { @@ -154,7 +212,8 @@ public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [S state = .idle } out.append(GraphBranch(name: name, agent: agent, state: state, ahead: b?.baseAhead ?? 0, behind: b?.baseBehind ?? 0, - conflicts: w.conflicts ?? [], pr: pr, rebase: rebased[name])) + conflicts: w.conflicts ?? [], pr: pr, rebase: rebased[name], stoppedFiles: stoppedFiles, + midRebase: midRebase, ask: conflicting ? w.resolve : nil, resolver: resolver)) } return out.enumerated().sorted { ($0.element.state.urgency, $0.offset) < ($1.element.state.urgency, $1.offset) }.map(\.element) } @@ -213,3 +272,58 @@ public struct RepoFormat: Decodable, Equatable, Sendable { return refs.map { "\(hash) · \($0)" } ?? hash } } + +/// The agent resolving a branch's conflict, by name: "Claude". +public func resolverName(_ b: GraphBranch) -> String? { + guard let p = b.resolver else { return nil } + return p.agent?.name.capitalized ?? p.displayName +} + +/// The banner's line on a branch whose conflict is in an agent's hands. +public func resolveHeadline(_ b: GraphBranch, base: String) -> String { + let who = resolverName(b) ?? "The agent" + switch b.state { + case .resolving: return "\(who) is resolving the conflict with \(base)" + case .resolveWaiting: return "\(who) is waiting on you while resolving \(b.name)" + case .resolveStopped(ended: true): return "The agent asked to resolve \(b.name) has ended; it still conflicts with \(base)" + case .resolveStopped(ended: false): return "\(who) stopped; \(b.name) still conflicts with \(base)" + default: return "\(b.name) conflicts with \(base)" + } +} + +/// How far it is and who asked when: "2 of 3 files left · you asked 4m +/// ago". +public func resolveDetail(_ b: GraphBranch, now: Date = Date()) -> String { + var parts: [String] = [] + let asked = b.ask?.files?.count ?? 0 + if b.stoppedFiles > 0 { + let n = b.stoppedFiles + parts.append(asked >= n ? "\(n) of \(asked) files left" : "\(n) file\(n == 1 ? "" : "s") left") + } else if b.midRebase { + parts.append("files resolved, the rebase not finished") + } else { + parts.append("not rebased yet") + } + if let ask = b.ask, let at = ask.at { + let who = ask.by == "autopilot" ? "the autopilot" : "you" + parts.append("\(who) asked \(agoText(at, now: now))") + } + return parts.joined(separator: " · ") +} + + +/// The branch the conflict banner is about: one stopped on a conflict, or +/// whose conflict is in an agent's hands — the most urgent, as the list is +/// sorted. nil when there is none, and the rebased banner may show. +public func conflictBannerBranch(_ bs: [GraphBranch]) -> GraphBranch? { + bs.first { b in + if case .conflicted = b.state { return true } + return b.state.resolution + } +} + +/// Where branch is checked out — mid-rebase too, when git names no +/// branch and the server says which one the rebase rewrites. +public func branchWorktree(_ project: ProjectInfo, _ branch: String) -> WorktreeInfo? { + (project.worktrees ?? []).first { $0.branch == branch } ?? (project.worktrees ?? []).first { $0.branch == nil && $0.rebasing == branch } +} diff --git a/macos/Sources/ConchKit/Protocol.swift b/macos/Sources/ConchKit/Protocol.swift index 1d8bf448..4b5bcf7f 100644 --- a/macos/Sources/ConchKit/Protocol.swift +++ b/macos/Sources/ConchKit/Protocol.swift @@ -200,6 +200,9 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { /// The branch a rebase left unfinished here is rewriting: git detaches /// HEAD meanwhile, so branch is nil. nil from an older server. public var rebasing: String? + /// The agent asked to resolve the branch's conflict, while it is + /// there (branch.resolving.v1). nil from an older server. + public var resolve: ResolveAsk? public init(path: String, branch: String?, main: Bool? = nil, port: Int? = nil) { self.path = path @@ -209,6 +212,22 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { } } +/// An agent asked to resolve a branch's conflict: its pane, who asked +/// ("autopilot", or nil for the person), when, and the files then. +public struct ResolveAsk: Decodable, Equatable, Sendable { + public var pane: String + public var by: String? + public var at: Date? + public var files: [String]? + + public init(pane: String, by: String? = nil, at: Date? = nil, files: [String]? = nil) { + self.pane = pane + self.by = by + self.at = at + self.files = files + } +} + /// One check of a pull request: state is pass, fail or pending. /// Not Identifiable by name: a name can repeat across workflows. public struct PRCheck: Decodable, Equatable, Sendable { diff --git a/macos/Tests/ConchKitTests/BranchGraphTests.swift b/macos/Tests/ConchKitTests/BranchGraphTests.swift index 781f471e..ac2fd42a 100644 --- a/macos/Tests/ConchKitTests/BranchGraphTests.swift +++ b/macos/Tests/ConchKitTests/BranchGraphTests.swift @@ -86,11 +86,13 @@ func history() -> [LogCommit] { {"id":"p4","name":"other","state":"running","project_id":"r2","branch":"quiet","agent":{"name":"claude","state":"working"}}] """#.utf8)) let bs = graphBranches(project, panes: panes) - #expect(bs.map(\.name) == ["stopped", "asking", "red", "forecast", "busy", "quiet"]) + // stopped's agent is at its conflict, so it waits behind the rest. + #expect(bs.map(\.name) == ["asking", "red", "forecast", "stopped", "busy", "quiet"]) let by = Dictionary(uniqueKeysWithValues: bs.map { ($0.name, $0) }) // Mid-rebase git names no branch: the worktree says which it is // rewriting, and its agent is found by the folder it works in. - #expect(by["stopped"]?.state == .conflicted(2)) + // Its agent working there: resolving it. + #expect(by["stopped"]?.state == .resolving) #expect(by["stopped"]?.agent?.id == "p1") #expect(by["stopped"]?.stopped == true && by["red"]?.stopped == false) #expect(by["red"]?.state == .ciFailing && by["red"]?.ahead == 2 && by["red"]?.behind == 1) diff --git a/macos/Tests/ConchKitTests/ResolvingTests.swift b/macos/Tests/ConchKitTests/ResolvingTests.swift new file mode 100644 index 00000000..64983020 --- /dev/null +++ b/macos/Tests/ConchKitTests/ResolvingTests.swift @@ -0,0 +1,125 @@ +import Foundation +import Testing +@testable import ConchKit + +/// A project whose one agent branch, feat, is in the worktree given, with +/// the panes given (JSON). +private func resolving(_ worktree: String, panes: String, branches: String = #"[{"name":"main"}]"#) throws -> [GraphBranch] { + try resolving(worktree, panes: panes, branches: branches, now: Date(timeIntervalSince1970: 1_800_000_100)) +} + +private func resolving(_ worktree: String, panes: String, branches: String = #"[{"name":"main"}]"#, now: Date, + rebased: [String: BranchRebase] = [:]) throws -> [GraphBranch] { + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"api","path":"/p","base":"main", + "worktrees":[{"path":"/p","branch":"main","main":true},\#(worktree)], + "branches":\#(branches)} + """#.utf8)) + let ps = try conchDecoder().decode([PaneInfo].self, from: Data(panes.utf8)) + return graphBranches(project, panes: ps, rebased: rebased, now: now) +} + +// 2027-01-15T08:00:00Z is 1_800_000_000: asked 100s before now. +private let stopped = #"{"path":"/w/feat","rebasing":"feat","status":{"files":2,"conflicts":2},"conflicts":["a.go","b.go"],"resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z","files":["a.go","b.go","c.go"]}}"# +private func pane(_ id: String, _ state: String, running: Bool = true) -> String { + #"{"id":"\#(id)","name":"x","state":"\#(running ? "running" : "exited")","project_id":"r1","cwd":"/w/feat","agent":{"name":"claude","state":"\#(state)"}}"# +} + +// The agent asked is at it, asks the person something, or stopped with +// the conflict still there — and the branch says which. +@Test func resolvingStates() throws { + let working = try resolving(stopped, panes: "[\(pane("p9", "working"))]")[0] + #expect(working.state == .resolving) + #expect(working.resolver?.id == "p9" && working.ask?.files?.count == 3) + #expect(working.stopped && working.stoppedFiles == 2 && working.state.conflicts) + + #expect(try resolving(stopped, panes: "[\(pane("p9", "blocked"))]")[0].state == .resolveWaiting) + #expect(try resolving(stopped, panes: "[\(pane("p9", "done"))]")[0].state == .resolveStopped(ended: false)) + // Its pane gone, or its program ended. + #expect(try resolving(stopped, panes: "[]")[0].state == .resolveStopped(ended: true)) + #expect(try resolving(stopped, panes: "[\(pane("p9", "idle", running: false))]")[0].state == .resolveStopped(ended: true)) + // Just asked: it has not started working yet, which is not stopping. + let soon = Date(timeIntervalSince1970: 1_800_000_010) + #expect(try resolving(stopped, panes: "[\(pane("p9", "idle"))]", now: soon)[0].state == .resolving) +} + +// Asked before anything moved — the branch will conflict — and working. +@Test func resolvingBeforeTheRebase() throws { + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"],"resolve":{"pane":"p9","by":"autopilot","at":"2027-01-15T08:00:00Z"}}"# + let b = try resolving(coming, panes: "[\(pane("p9", "working"))]")[0] + #expect(b.state == .resolving && !b.stopped && b.ask?.by == "autopilot") + // Idle long after: it stopped, the conflict still coming. + #expect(try resolving(coming, panes: "[\(pane("p9", "idle"))]")[0].state == .resolveStopped(ended: false)) +} + +// An ask whose conflict is gone is no longer news: the branch is rebased, +// or whatever else it is. +@Test func resolvedAskGivesWay() throws { + let done = #"{"path":"/w/feat","branch":"feat","resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z"}}"# + let r = try conchDecoder().decode(BranchRebase.self, from: Data(#"{"branch":"feat","before":"a","after":"b","onto":"c"}"#.utf8)) + #expect(try resolving(done, panes: "[\(pane("p9", "done"))]", now: Date(), rebased: ["feat": r])[0].state == .rebased) + #expect(try resolving(done, panes: "[\(pane("p9", "working"))]")[0].state == .working) +} + +// From a server that keeps no asks: an agent working in a worktree +// stopped mid-rebase is resolving it; one doing nothing leaves it stuck. +@Test func resolvingWithoutAnAsk() throws { + let old = #"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1}}"# + #expect(try resolving(old, panes: "[\(pane("p1", "working"))]")[0].state == .resolving) + #expect(try resolving(old, panes: "[\(pane("p1", "blocked"))]")[0].state == .resolveWaiting) + #expect(try resolving(old, panes: "[\(pane("p1", "idle"))]")[0].state == .conflicted(1)) + #expect(try resolving(old, panes: "[]")[0].state == .conflicted(1)) + // Will conflict, an agent working: it is doing its own work, not resolving. + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"]}"# + #expect(try resolving(coming, panes: "[\(pane("p1", "working"))]")[0].state == .willConflict) +} + +// Stuck needs the person most, then an agent asking, and an agent at it +// needs nobody yet. +@Test func resolvingUrgency() { + let order: [GraphBranchState] = [.conflicted(1), .resolveStopped(ended: false), .resolveWaiting, .rebased, .waiting, + .ciFailing, .willConflict, .resolving, .working, .done, .idle] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) + #expect(Set(order.map(\.urgency)).count == order.count) + #expect(GraphBranchState.resolveStopped(ended: true).urgency == GraphBranchState.resolveStopped(ended: false).urgency) +} + +// What the banner and the card say of it. +@Test func resolvingWords() throws { + let b = try resolving(stopped, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveHeadline(b, base: "main") == "Claude is resolving the conflict with main") + #expect(resolveDetail(b, now: Date(timeIntervalSince1970: 1_800_000_100)) == "2 of 3 files left · you asked 1m ago") + let w = try resolving(stopped, panes: "[\(pane("p9", "blocked"))]")[0] + #expect(resolveHeadline(w, base: "main") == "Claude is waiting on you while resolving feat") + let s = try resolving(stopped, panes: "[\(pane("p9", "done"))]")[0] + #expect(resolveHeadline(s, base: "main") == "Claude stopped; feat still conflicts with main") + let e = try resolving(stopped, panes: "[]")[0] + #expect(resolveHeadline(e, base: "main") == "The agent asked to resolve feat has ended; it still conflicts with main") + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"],"resolve":{"pane":"p9","by":"autopilot","at":"2027-01-15T07:00:00Z"}}"# + let a = try resolving(coming, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveDetail(a, now: Date(timeIntervalSince1970: 1_800_000_100)) == "not rebased yet · the autopilot asked 1h ago") +} + +// The banner is about the branch most in need: stuck before one in hand, +// and none for a conflict merely coming. +@Test func conflictBannerPicks() throws { + let working = try resolving(stopped, panes: "[\(pane("p9", "working"))]") + #expect(conflictBannerBranch(working)?.name == "feat") + let coming = try resolving(#"{"path":"/w/feat","branch":"feat","conflicts":["a.go"]}"#, panes: "[]") + #expect(conflictBannerBranch(coming) == nil) + let stuck = try resolving(#"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1}}"#, panes: "[]") + #expect(conflictBannerBranch(stuck)?.state == .conflicted(1)) + #expect(conflictBannerBranch([]) == nil) +} + +// A new agent is started where the branch is checked out, which is a +// worktree naming no branch while its rebase is stopped. +@Test func branchWorktreeMidRebase() throws { + let p = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"api","path":"/p","base":"main", + "worktrees":[{"path":"/p","branch":"main","main":true},{"path":"/w/feat","rebasing":"feat"},{"path":"/w/b","branch":"b"}]} + """#.utf8)) + #expect(branchWorktree(p, "feat")?.path == "/w/feat") + #expect(branchWorktree(p, "b")?.path == "/w/b") + #expect(branchWorktree(p, "nope") == nil) +} diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 61060628..cb4503e1 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -127,7 +127,7 @@ A web page in a tab beside the agents. ## Commits -History, agents' branches, conflicts (resolved, reviewed, pushed), **CI**, **Autopilot**. +History, agents' branches, conflicts (resolving, review, push), **CI**, **Autopilot**. **How:** **Commit Graph** on a project's or branch's menu. From ba6446ab726da18d14f1c9573ddd4ca00190f68a Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 11:37:07 -0800 Subject: [PATCH 33/35] gitx: a git without --show-ref-format is not a refs backend called that MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rev-parse prints an option it does not know back as an argument and exits 0, so with Apple's git 2.39 the graph's format pill read "SHA-1 · --show-ref-format". An answer starting with - is no answer: the refs are files, as for any git that cannot say. Co-Authored-By: Claude Opus 5.5 --- internal/gitx/git3_test.go | 17 +++++++++++++++++ internal/gitx/log.go | 12 +++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/internal/gitx/git3_test.go b/internal/gitx/git3_test.go index 8c4b2ba2..65d9bbdf 100644 --- a/internal/gitx/git3_test.go +++ b/internal/gitx/git3_test.go @@ -219,3 +219,20 @@ func TestBundleObjectFormat(t *testing.T) { t.Errorf("missing: %q", got) } } + +// A git older than 2.45 does not know --show-ref-format, and rev-parse +// prints an option it does not know back as if it were an argument, +// exiting 0 (Apple's git 2.39 does): that is no refs backend. +func TestRefsAnswer(t *testing.T) { + for in, want := range map[string]string{ + "reftable\n": "reftable", + "files\n": "files", + "--show-ref-format\n": "", + "": "", + " \n": "", + } { + if got := refsAnswer(in); got != want { + t.Errorf("refsAnswer(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/gitx/log.go b/internal/gitx/log.go index 9c2bde98..8968b5b7 100644 --- a/internal/gitx/log.go +++ b/internal/gitx/log.go @@ -119,9 +119,19 @@ func Format(ctx context.Context, dir string) RepoFormat { } f := RepoFormat{Objects: strings.TrimSpace(string(out)), Refs: "files"} if out, err := run(ctx, dir, "rev-parse", "--show-ref-format"); err == nil { - if r := strings.TrimSpace(string(out)); r != "" { + if r := refsAnswer(string(out)); r != "" { f.Refs = r } } return f } + +// refsAnswer is rev-parse --show-ref-format's answer, or "" for none: a +// git that does not know the option prints it back, and exits 0. +func refsAnswer(out string) string { + r := strings.TrimSpace(out) + if strings.HasPrefix(r, "-") { + return "" + } + return r +} From dbab0a699fe65e8fdfdfa1da01edc986fbc56653 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 11:38:15 -0800 Subject: [PATCH 34/35] Conch.app: fixes from watching an agent resolve live, and another agent mid-way MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The banner turned red when an agent just asked had not started in time, but only once something else redrew it: it now looks again every few seconds while an agent has the conflict. - "1 of 1 files left · you asked now" reads "1 file left · you asked just now"; "stopped resolving" was cut off in the branch list. - While one agent is resolving, Another agent starts a different one in the worktree with the same request (the banner and the card). - The ended headline fits on one line. Co-Authored-By: Claude Opus 5.5 --- macos/Sources/ConchApp/CommitsView.swift | 42 ++++++++++++++++++- macos/Sources/ConchKit/BranchGraph.swift | 7 ++-- .../Tests/ConchKitTests/ResolvingTests.swift | 9 +++- 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 1e2761b1..1e67b610 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -1093,7 +1093,7 @@ struct BranchSideRow: View { case .willConflict: ("will conflict", Theme.warn) case .resolving: ("resolving", Theme.work) case .resolveWaiting: ("needs you", Theme.warn) - case .resolveStopped: ("stopped resolving", Theme.err) + case .resolveStopped: ("stopped", Theme.err) case .working: ("working", Theme.work) case .done: ("done", Theme.ok) case .idle: ("idle", Theme.muted) @@ -1137,6 +1137,7 @@ struct ConflictBanner: View { .controlSize(.small).tint(Theme.accentDeep) .help("Opens the agent's pane") } + AnotherAgentButton(model: model, branch: b) default: ResolveButton(model: model, branch: b) } @@ -1147,6 +1148,16 @@ struct ConflictBanner: View { .background(tone.opacity(0.12)) .overlay(alignment: .bottom) { Rectangle().fill(tone.opacity(0.35)).frame(height: 1) } .accessibilityElement(children: .contain) + // Nothing else changes when an agent just asked has not started + // in time (resolveStartGrace), or as "asked 4m ago" ages: look + // again every few seconds while an agent has it. + .task(id: b.state.resolution ? b.name : "") { + guard b.state.resolution else { return } + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(5)) + model.objectWillChange.send() + } + } } } @@ -1198,6 +1209,30 @@ struct ResolveButton: View { } } +/// While one agent is resolving a conflict: hand it to another, started +/// in the branch's worktree with the same request. The first keeps +/// running — two agents in one checkout should not both be editing, so +/// the menu says so. +struct AnotherAgentButton: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let startable = model.store.startable(on: model.machine) + let who = resolverName(branch) ?? "the agent at it" + Menu("Another agent") { + Section("Start one in its worktree; \(who) keeps running") { + ForEach(startable, id: \.name) { a in Button(a.title) { model.askToResolve(branch, start: a.name) } } + } + } + .menuStyle(.borderedButton).fixedSize().controlSize(.small) + .disabled(startable.isEmpty) + .help("Asks a new agent, in the branch's worktree, to resolve the conflict instead. Stop \(who) first if it is still changing files.") + } +} + /// The side panel's word on a branch that conflicts with the base: the /// files, and an agent to ask. struct ConflictCard: View { @@ -1226,7 +1261,10 @@ struct ConflictCard: View { Text("and \(branch.conflicts.count - 6) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) } if (branch.state == .resolving || branch.state == .resolveWaiting), let r = branch.resolver, r.running { - Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) }.controlSize(.small) + HStack(spacing: 6) { + Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) }.controlSize(.small) + AnotherAgentButton(model: model, branch: branch) + } } else { ResolveButton(model: model, branch: branch) } diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift index 42c5f4ea..1ba48842 100644 --- a/macos/Sources/ConchKit/BranchGraph.swift +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -285,7 +285,7 @@ public func resolveHeadline(_ b: GraphBranch, base: String) -> String { switch b.state { case .resolving: return "\(who) is resolving the conflict with \(base)" case .resolveWaiting: return "\(who) is waiting on you while resolving \(b.name)" - case .resolveStopped(ended: true): return "The agent asked to resolve \(b.name) has ended; it still conflicts with \(base)" + case .resolveStopped(ended: true): return "The agent resolving \(b.name) ended; it still conflicts with \(base)" case .resolveStopped(ended: false): return "\(who) stopped; \(b.name) still conflicts with \(base)" default: return "\(b.name) conflicts with \(base)" } @@ -298,7 +298,7 @@ public func resolveDetail(_ b: GraphBranch, now: Date = Date()) -> String { let asked = b.ask?.files?.count ?? 0 if b.stoppedFiles > 0 { let n = b.stoppedFiles - parts.append(asked >= n ? "\(n) of \(asked) files left" : "\(n) file\(n == 1 ? "" : "s") left") + parts.append(asked > n ? "\(n) of \(asked) files left" : "\(n) file\(n == 1 ? "" : "s") left") } else if b.midRebase { parts.append("files resolved, the rebase not finished") } else { @@ -306,7 +306,8 @@ public func resolveDetail(_ b: GraphBranch, now: Date = Date()) -> String { } if let ask = b.ask, let at = ask.at { let who = ask.by == "autopilot" ? "the autopilot" : "you" - parts.append("\(who) asked \(agoText(at, now: now))") + let ago = agoText(at, now: now) + parts.append("\(who) asked \(ago == "now" ? "just now" : ago)") } return parts.joined(separator: " · ") } diff --git a/macos/Tests/ConchKitTests/ResolvingTests.swift b/macos/Tests/ConchKitTests/ResolvingTests.swift index 64983020..093646a3 100644 --- a/macos/Tests/ConchKitTests/ResolvingTests.swift +++ b/macos/Tests/ConchKitTests/ResolvingTests.swift @@ -94,7 +94,7 @@ private func pane(_ id: String, _ state: String, running: Bool = true) -> String let s = try resolving(stopped, panes: "[\(pane("p9", "done"))]")[0] #expect(resolveHeadline(s, base: "main") == "Claude stopped; feat still conflicts with main") let e = try resolving(stopped, panes: "[]")[0] - #expect(resolveHeadline(e, base: "main") == "The agent asked to resolve feat has ended; it still conflicts with main") + #expect(resolveHeadline(e, base: "main") == "The agent resolving feat ended; it still conflicts with main") let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"],"resolve":{"pane":"p9","by":"autopilot","at":"2027-01-15T07:00:00Z"}}"# let a = try resolving(coming, panes: "[\(pane("p9", "working"))]")[0] #expect(resolveDetail(a, now: Date(timeIntervalSince1970: 1_800_000_100)) == "not rebased yet · the autopilot asked 1h ago") @@ -123,3 +123,10 @@ private func pane(_ id: String, _ state: String, running: Bool = true) -> String #expect(branchWorktree(p, "b")?.path == "/w/b") #expect(branchWorktree(p, "nope") == nil) } + +// One file asked, one left: not "1 of 1"; and asked a moment ago. +@Test func resolvingWordsJustAsked() throws { + let one = #"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1},"resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z","files":["a.go"]}}"# + let b = try resolving(one, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveDetail(b, now: Date(timeIntervalSince1970: 1_800_000_020)) == "1 file left · you asked just now") +} From 566983204e7579af99f0740e6581c218faedf239 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 15:30:09 -0800 Subject: [PATCH 35/35] Docs: the Mac app guide back under its 700 words after the merge Co-Authored-By: Claude Opus 5.5 --- web/src/app/docs/mac-app/page.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 01526288..298a46e1 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -131,7 +131,7 @@ A web page in a tab beside the agents. ## Commits -History, agents' branches, conflicts (resolving, review, push), **CI**, **Autopilot**. +Agents' branches, conflicts, **CI**, **Autopilot**. **How:** **Commit Graph** on a project's or branch's menu.