Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md

Large diffs are not rendered by default.

83 changes: 83 additions & 0 deletions bridge/background-shells.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { constants } from "node:fs";
import { open, readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

const OUTPUT_LIMIT = 16 * 1024;

export async function readOutput(file) {
if (!file) return null;
try {
const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK);
try {
const info = await handle.stat();
if (!info.isFile()) return null;
const buffer = Buffer.alloc(Math.min(info.size, OUTPUT_LIMIT));
const { bytesRead } = await handle.read(buffer, 0, buffer.length, info.size - buffer.length);
return buffer.toString("utf8", 0, bytesRead);
} finally {
await handle.close();
}
} catch {
return null;
}
}

export async function liveOutput(cwd, sessionId, taskId) {
if (typeof process.getuid !== "function" || ![sessionId, taskId].every((id) => /^[a-z0-9_-]+$/i.test(id))) {
return null;
}
// Claude's live output directory is private to the CLI. The final notification supplies its own path.
const base = process.env.CLAUDE_CODE_TMPDIR?.trim() || (process.platform === "darwin" ? "/tmp" : tmpdir());
const root = resolve(cwd, base, `claude-${process.getuid()}`);
const projects = await readdir(root, { withFileTypes: true }).catch(() => []);
for (const project of projects) {
if (!project.isDirectory()) continue;
const output = await readOutput(join(root, project.name, sessionId, "tasks", `${taskId}.output`));
if (output !== null) return output;
}
return null;
}

export class BackgroundShells {
tasks = new Map();
active = new Map();

update(message) {
const id = message.task_id;
if (message.subtype === "background_tasks_changed") {
this.active = new Map();
for (const task of message.tasks) {
if (task.task_type !== "local_bash" || task.ambient) continue;
const shell = { id: task.task_id, label: task.description, run: task.run_id, backgrounded: true };
this.tasks.set(shell.id, shell);
this.active.set(shell.id, shell);
}
return true;
}
if (!id) return false;
const known = this.tasks.get(id);
if (known?.run && message.run_id && message.run_id < known.run) return false;
if (message.subtype === "task_started" && message.task_type === "local_bash" && !message.ambient) {
const shell = { id, label: message.description, run: message.run_id, backgrounded: message.is_backgrounded || known?.backgrounded === true };
this.tasks.set(id, shell);
if (message.is_backgrounded) this.active.set(id, shell);
return message.is_backgrounded === true;
}
if (message.subtype === "task_updated" && known && message.patch.is_backgrounded) {
known.backgrounded = true;
this.active.set(id, known);
return true;
}
return false;
}

finish(message) {
const id = message.task_id;
const shell = this.tasks.get(id);
if (!shell || (shell.run && message.run_id && shell.run !== message.run_id)) return null;
this.tasks.delete(id);
this.active.delete(id);
return shell;
}
}
45 changes: 45 additions & 0 deletions bridge/background-shells.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { BackgroundShells, readOutput } from "./background-shells.mjs";

test("a shell that moves to the background retains its identity through completion", () => {
const shells = new BackgroundShells();
const start = { subtype: "task_started", task_id: "shell", task_type: "local_bash", run_id: "2", description: "Tests" };
assert.equal(shells.update(start), false);
assert.equal(shells.active.size, 0);
assert.equal(shells.update({ subtype: "task_updated", task_id: "shell", run_id: "2", patch: { is_backgrounded: true } }), true);
assert.equal(shells.active.get("shell").label, "Tests");
assert.equal(shells.finish({ task_id: "shell", run_id: "1" }), null);
assert.equal(shells.active.size, 1);
assert.equal(shells.update({ subtype: "background_tasks_changed", tasks: [] }), true);
assert.equal(shells.active.size, 0);
assert.equal(shells.finish({ task_id: "shell", run_id: "2" }).backgrounded, true);
});

test("the roster excludes ambient tasks and tasks other than shells", () => {
const shells = new BackgroundShells();
shells.update({ subtype: "background_tasks_changed", tasks: [
{ task_id: "one", task_type: "local_bash", description: "Build" },
{ task_id: "two", task_type: "local_bash", ambient: true },
{ task_id: "three", task_type: "local_agent" },
] });
assert.deepEqual([...shells.active.keys()], ["one"]);
});

test("output is bounded to the latest 16 KiB of a regular file", async () => {
const dir = await mkdtemp(join(tmpdir(), "m4code-shell-output-"));
try {
const file = join(dir, "shell.output");
await writeFile(file, `header${"x".repeat(16 * 1024 - 4)}tail`);
const output = await readOutput(file);
assert.equal(output.length, 16 * 1024);
assert.equal(output.slice(-4), "tail");
assert.equal(await readOutput(dir), null);
assert.equal(await readOutput(join(dir, "missing")), null);
} finally {
await rm(dir, { recursive: true });
}
});
81 changes: 57 additions & 24 deletions bridge/claude.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { BackgroundShells, liveOutput, readOutput } from "./background-shells.mjs";

import { getSessionMessages, listSessions, query } from "@anthropic-ai/claude-agent-sdk";

Expand Down Expand Up @@ -279,7 +280,14 @@ async function finishTurn(session, result) {
if (turn) {
const failed = result.is_error && !session.cancelled;
if (failed) turn.reject(new Error(result.result || (result.errors ?? []).join("\n") || "Claude Code stopped with an error."));
else turn.resolve({ stopReason: stopReason(session, result), ...steersBack(session, turn, receipt) });
else {
if (session.cancelled) {
for (const uuid of receipt?.still_queued ?? []) {
if (turn.steers.has(uuid) && !turn.shown.has(uuid)) session.dropping.add(uuid);
}
}
turn.resolve({ stopReason: stopReason(session, result) });
}
}
// The context size is only shown, so the turn ends without waiting for it.
session.query
Expand All @@ -288,35 +296,45 @@ async function finishTurn(session, result) {
.catch(() => {});
}

/**
* The steers the turn ends without having answered, in the reply's `_meta.m4code`. `unread` are those Claude had not
* read when the user stopped the turn: Claude Code keeps them and would run them as a turn of their own, which the
* user just asked to stop, so the bridge stops that turn too (`dropping`) and m4code puts their text back in the
* message box. `resend` are those Claude dropped unread on its own, which m4code sends as the next turn.
*/
function steersBack(session, turn, receipt) {
const stillQueued = new Set(receipt?.still_queued ?? []);
const unread = [...turn.waiting].filter((uuid) => turn.steers.has(uuid) && !turn.shown.has(uuid) && stillQueued.has(uuid));
for (const uuid of unread) session.dropping.add(uuid);
const back = {};
if (unread.length) back.unread = unread.map((uuid) => turn.steers.get(uuid));
if (turn.dropped.length) back.resend = turn.dropped;
return Object.keys(back).length ? { _meta: { m4code: back } } : {};
}

/** Claude Code says it took a steer off its queue without reading it (the states t3code treats the same way). */
function steerDropped(session, m) {
const turn = session.turn;
if (!turn || session.cancelled || !["cancelled", "discarded", "refused"].includes(m.state) || !turn.steers.has(m.command_uuid)) return;
if (!turn.waiting.delete(m.command_uuid)) return;
turn.dropped.push(turn.steers.get(m.command_uuid));
turn.steers.delete(m.command_uuid);
if (turn.waiting.size === 0 && turn.held) return finishTurn(session, turn.held);
}

function publishShells(session) {
const shells = [...session.shells.active.values()].map(({ id, label }) => ({ id, label }));
update(session.id, { sessionUpdate: "_m4code/background_shells", shells });
}

async function finishShell(session, message) {
const shell = session.shells.finish(message);
if (!shell?.backgrounded) return;
publishShells(session);
const output = await readOutput(message.output_file);
update(session.id, {
sessionUpdate: "tool_call",
toolCallId: `background-shell-${shell.id}`,
kind: "execute",
_meta: { m4code: { backgroundShell: true } },
title: shell.label,
status: message.status === "completed" ? "completed" : "failed",
content: [{ type: "content", content: { type: "text", text: [message.summary, output].filter(Boolean).join("\n\n") } }],
});
}

/** The session's messages from the SDK, as updates to m4code, until the session ends. */
async function pump(session) {
let errorText;
try {
for await (const m of session.query) {
if (m.type === "system") {
if (session.shells.update(m)) publishShells(session);
if (m.subtype === "task_notification") await finishShell(session, m);
}
if (session.dropping.size && !session.turn) {
if (m.type === "result") {
for (const uuid of answeredBy(m) ?? [...session.dropping]) session.dropping.delete(uuid);
Expand Down Expand Up @@ -371,19 +389,21 @@ async function pump(session) {
}
}
} catch (error) {
errorText = error?.message ?? String(error);
session.turn?.reject(error);
session.turn = null;
}
// Claude Code ended with a turn still open, such as one held for a steer it never answered.
session.turn?.reject(new Error("Claude Code stopped before it finished the turn."));
session.turn = null;
sessions.delete(session.id);
update(session.id, { sessionUpdate: "_m4code/session_ended", error: errorText });
}

async function open(params, resume) {
const id = resume ?? randomUUID();
const extra = params._meta?.claudeCode?.options ?? {};
const session = { id, cwd: params.cwd, inbox: new Inbox(), tools: new Map(), streamed: new Set(), turn: null, cancelled: false, interrupted: null, dropping: new Set(), dropInterrupted: false, dropsDone: null, mode: "default", model: "", effort: "medium", models: [] };
const session = { id, cwd: params.cwd, inbox: new Inbox(), tools: new Map(), streamed: new Set(), shells: new BackgroundShells(), turn: null, cancelled: false, interrupted: null, dropping: new Set(), dropInterrupted: false, dropsDone: null, mode: "default", model: "", effort: "medium", models: [] };
session.query = query({
prompt: session.inbox,
options: {
Expand Down Expand Up @@ -457,28 +477,40 @@ const handlers = {
"session/prompt": async (p) => {
const s = sessions.get(p.sessionId);
if (!s) throw new Error("That session has ended.");
if (s.turn) throw new Error("A turn is already running.");
if (s.turn || s.preparing) throw new Error("A turn is already running.");
s.cancelled = false;
s.preparing = true;
// Steers the user stopped still run in Claude Code first; this message waits until they are gone, so their
// output and result can't be taken for its own.
await afterDropped(s);
s.preparing = false;
if (s.cancelled) return { stopReason: "cancelled" };
const text = (p.prompt ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
const uuid = randomUUID();
const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), shown: new Set(), dropped: [], held: null }));
const done = new Promise((resolve, reject) => (s.turn = { resolve, reject, waiting: new Set([uuid]), steers: new Map(), shown: new Set(), held: null }));
s.inbox.push(userMessage(s, text, uuid));
return done;
},
"_m4code/steer": async (p) => {
const s = sessions.get(p.sessionId);
if (!s) throw new Error("That session has ended.");
if (!s.turn || s.cancelled) throw new Error("No turn is running.");
const uuid = randomUUID();
const uuid = p.id;
s.turn.waiting.add(uuid);
s.turn.steers.set(uuid, p.text);
// "next" waits for the tool calls running to finish; "now" would cancel them, as t3code found.
s.inbox.push(userMessage(s, p.text, uuid, "next"));
return {};
},
"_m4code/background_shell": async (p) => {
const session = sessions.get(p.sessionId);
if (!session?.shells.active.has(p.taskId)) throw new Error("That background shell has ended.");
if (p.action === "stop") {
await session.query.stopTask(p.taskId);
return {};
}
return { output: await liveOutput(session.cwd, session.id, p.taskId) };
},
"session/set_mode": async (p) => {
const s = sessions.get(p.sessionId);
await s.query.setPermissionMode(p.modeId);
Expand Down Expand Up @@ -530,7 +562,7 @@ function showSteer(session, uuid) {
const text = turn?.steers.get(uuid);
if (text === undefined || turn.shown.has(uuid)) return;
turn.shown.add(uuid);
update(session.id, { sessionUpdate: "user_message_chunk", content: { type: "text", text }, _meta: { m4code: { steer: true } } });
update(session.id, { sessionUpdate: "user_message_chunk", content: { type: "text", text }, _meta: { m4code: { steer: uuid } } });
}

/** Every steer not shown yet, oldest first: Claude is about to answer them, or just did. */
Expand All @@ -540,8 +572,9 @@ function showWaitingSteers(session, only) {

function cancel(p) {
const s = sessions.get(p.sessionId);
if (!s?.turn) return;
if (!s || (!s.turn && !s.preparing)) return;
s.cancelled = true;
if (!s.turn) return;
s.interrupted = s.query.interrupt().catch(() => undefined);
}

Expand Down
8 changes: 6 additions & 2 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ test-app:
lint:
cargo clippy --locked --all-targets -- -D warnings

# Test the Claude bridge's handling of background shells.
test-bridge:
node bridge/background-shells.test.mjs

# ---- Mod (Claude Code plugin in mod/) -------------------------------------------------------------

# Tests for the mod: the *.test.ts files in mod/hooks. Needs the `claude` CLI on PATH.
Expand Down Expand Up @@ -50,7 +54,7 @@ web-preview:
# ---- Everything -----------------------------------------------------------------------------------

# Every test: the app and the mod.
test: test-app test-mod
test: test-app test-bridge test-mod

# What CI checks, plus the mod and the web build.
ci: build test-app web-build test-mod
ci: build test-app test-bridge web-build test-mod
11 changes: 8 additions & 3 deletions src/app/agent_handoff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,13 @@ impl Workspace {
target.update(cx, |view, _| view.relinquish_record());
}
self.live.retain(|live| live.id != id);
if let (Some(source), Some(draft)) = (pending.source.view.thread(), pending.draft) {
source.update(cx, |view, cx| view.paste_text(&draft, window, cx));
if let Some(source) = pending.source.view.thread() {
source.update(cx, |view, cx| {
view.restore_queue_after_handoff(cx);
if let Some(draft) = pending.draft {
view.paste_text(&draft, window, cx);
}
});
}
self.live.push(pending.source);
self.toast(format!("Handoff failed; the original session is still open. {error}"), true, cx);
Expand All @@ -145,7 +150,7 @@ impl Workspace {
target.update(cx, |view, _| view.relinquish_record());
}
if let Some(source) = pending.source.view.thread() {
source.read(cx).stop();
source.update(cx, |view, _| view.stop());
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/app/headless/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ fn handing_a_session_to_another_agent() {
);
ws.read_with(&cx, |ws, _| {
let rec = ws.store.session(&first).unwrap();
assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Codex, &cwd));
assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Claude, &cwd));
});
wait(&mut cx, "the hand-off message", &|_, _| {
std::fs::read_to_string(&prompts).is_ok_and(|p| {
Expand All @@ -678,6 +678,10 @@ fn handing_a_session_to_another_agent() {
&& p.contains("User's next message:\nimplement step 2")
})
});
ws.read_with(&cx, |ws, _| {
let rec = ws.store.session(&first).unwrap();
assert_eq!((rec.claude.as_ref().unwrap().harness, &rec.cwd), (crate::harness::Harness::Codex, &cwd));
});
}

/// A session of each agent through ACP (Claude Code through the SDK bridge): it starts, names itself, and answers a message in the thread.
Expand Down
5 changes: 4 additions & 1 deletion src/app/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ impl Workspace {
if let Some(err) = view.read(cx).start_error() {
ws.toast(format!("Could not start the shell: {err}"), true, cx);
}
let shell_had_focus = view.focus_handle(cx).is_focused(window);
ws.shells.remove(&owner);
ws.focus_active(window, cx);
if shell_had_focus {
ws.focus_active(window, cx);
}
cx.notify();
}
});
Expand Down
Loading
Loading