feat: v2.6.0 — Chat UI composer (+ menu, project files, activity panel, permission mode, Stop), git on a workspace's extra folders (#70), long paste as a file (#68), S3 server mode (experimental)

Chat UI:
- Each Claude/Codex session keeps its own chat/terminal view; Settings only
  sets how new sessions open.
- Composer + menu: upload, project files and folders (#54, also dragged from
  the Files/Changes tree), context files, recent uploads, skills, plugins.
- Activity side panel (progress, outputs, files read, uploads, memory,
  skills, connectors) with a file preview; edited-file counts per turn.
- Permission-mode chip (Shift+Tab steps, read back from the pane:
  server/lib/pane-mode.js, GET|POST /api/run/:id/permission-mode).
- Stop (Esc) while the main agent works; the status is checked per agent
  (with session_id /api/agents ignores its status filter) and re-read every
  5 s while Stop shows.
- Dropped images shown in the conversation (GET /api/run/drop/:name, the
  requester's own drop dir), full-size viewer.
- A plain-text paste over 5,000 characters is attached as pasted-text.txt,
  so no prompt reaches tmux/argv limits (#68).

Changes panel: every /api/lanes/:id/git* route takes ?source=<lane_sources
id> (sourceFolder; ENOSOURCE otherwise) and a folder picker switches the
whole panel to a workspace's extra folder (#70).

Server mode S3 (one Linux user per account) — experimental, verified with
fake sudo plus a P6 managed-settings spike on a test account:
- member tmux listing runs in the background (cached, 15 s => unknown);
- transcript snapshot copy is async, chunked, temp file + rename;
- Express Layer patch only on Express 4;
- tmux capturePane/sendKey go to the member's own server.

Docs: the multi-user design moved in as docs/plans/server-mode/README.md
(the AgentHub-Server repo is gone); S3-PLAN P6 result; LANES/API/openapi.
This commit is contained in:
2026-10-09 15:51:19 +07:00
parent ce773a3f5a
commit fa156d6a59
114 changed files with 5831 additions and 885 deletions
+3
View File
@@ -764,6 +764,9 @@ HTTP surface for the tmux-backed terminal run: one session per workspace, named
| `GET` | `/api/run/cwds` | Suggested cwds (dashboard, home, recent from sessions) |
| `POST` | `/api/run/drop-image` | An image dropped on the Workspace terminal. Raw body, `Content-Type` one of `image/png\|jpeg\|gif\|webp`, ≤20 MB. Saved `0600` under `<data dir>/drops/` (`0700`, never a guessable name in the shared tmp; S3: the member's own `~/.agenthub/handoff/drops/`) with a RANDOM name (nothing from the request names the file); files older than a day are pruned on each write. Answers `{ path }`, which `TerminalView` pastes into the pane — what a local terminal does on a drop, and how `claude` attaches the image. 400 for any other type |
| `POST` | `/api/run/drop-file?name=…` | Any file (or image) dropped on the Workspace terminal or pasted/dropped into a prompt box. Raw body of any type, ≤20 MB, same directory (S3: `?laneId=` saves it AS the account that workspace's panes run as, so the pane can read it), `0600` and day-old pruning as `drop-image`. The name is the file's own, reduced to a `[A-Za-z0-9._-]` basename behind a random 16-hex prefix (so it can neither leave the directory nor collide, and space-joined paths stay parseable). Answers `{ path }`; 400 for an empty body or a name that sanitizes to nothing. The client uses this for every drop; `drop-image` is kept for API callers |
| `GET` | `/api/run/drop/:name` | A dropped IMAGE served back, so a chat turn shows the picture instead of its path. Only a name `drop-image`/`drop-file` made (16-hex prefix, no separator) with a png/jpg/gif/webp extension, only a regular file in the REQUESTER's drop dir (S3: their member account's, owned by that account — an admin viewing a member's session gets the name chip, not the image); under `nosniff` and a `sandbox` CSP like `/git/raw`. 404 otherwise, and once the day-old prune removed it |
| `GET` | `/api/run/:id/permission-mode` | A live **claude** pane's permission mode, read off the mode line Claude Code prints under its prompt (`server/lib/pane-mode.js`): `{ mode }` — `default`, `acceptEdits`, `plan`, `auto`, `bypassPermissions`, `dontAsk`, or `null` while a menu hides it. 404 for a pane that is not running, 400 `EUNSUPPORTED` for a non-claude pane |
| `POST` | `/api/run/:id/permission-mode` | `{ mode }` → steps the pane there with Shift+Tab, the only way a running session changes mode, reading every step back before the next key. `{ mode }` on success; 400 `EBADMODE` outside the five settable modes; 409 `EMODEUNKNOWN` (no mode line — nothing is pressed — or a step did not change it), `EMODEUNAVAILABLE` (not in this session's cycle, e.g. Bypass in a session not started with it; the pane is back on its starting mode), `EBUSY` (a change is already running on that pane) |
| `GET` | `/api/run/files?cwd=…&q=…` | Fuzzy file search inside `cwd` for the run panel's `@`-file autocomplete. Skips `node_modules`, `.git`, `dist`, `build`, `.next`, `.cache`, `coverage`, `vendor`, etc. Cwd is required and must exist; results are capped and ranked by basename match |
| `POST` | `/api/run` | Create-or-adopt the workspace's tmux session. Body: `{ laneId, cwd, initialPrompt?, model?, permissionMode?, effort?, resumeSessionId? }`. The CLI comes from the workspace row, never from the body. An existing session whose pane sits at a shell prompt gets the argv typed into it; a pane already running a program is adopted unchanged |
| `GET` | `/api/run/:id` | One run handle, or 404 once its tmux session is gone |
+85
View File
@@ -3035,3 +3035,88 @@ describe("Nested Agent Spawning", () => {
);
});
});
describe("GET /api/sessions/:id/outline", () => {
it("reads progress, outputs and context off the session's tool events", async () => {
const sid = "outline-" + Date.now();
const pre = (tool_name, tool_input, tool_response) =>
post("/api/hooks/event", {
hook_type: "PostToolUse",
data: { session_id: sid, tool_name, tool_input, tool_response },
});
await post("/api/hooks/event", { hook_type: "SessionStart", data: { session_id: sid } });
await pre(
"TaskCreate",
{ subject: "Parse plan" },
{ task: { id: "1", subject: "Parse plan" } }
);
await pre(
"TaskCreate",
{ subject: "Parse plan" },
{ task: { id: "1", subject: "Parse plan" } }
);
await pre(
"TaskCreate",
{ subject: "Build report" },
{ task: { id: "2", subject: "Build report" } }
);
await pre("TaskUpdate", { taskId: "1", status: "completed" });
await pre("TaskUpdate", { taskId: "2", status: "in_progress" });
await pre("Write", { file_path: "/w/a.xlsx", content: "x" });
await pre("Write", { file_path: "/w/b.md", content: "x" });
await pre("Write", { file_path: "/w/a.xlsx", content: "y" });
await pre("Skill", { skill: "xlsx" });
await pre("Skill", { skill: "xlsx" });
await pre("mcp__plugin_vercel_vercel__list_projects", {});
const res = await fetch(`/api/sessions/${sid}/outline`);
assert.equal(res.status, 200);
assert.deepEqual(res.body.progress, [
{ id: "1", subject: "Parse plan", status: "completed" },
{ id: "2", subject: "Build report", status: "in_progress" },
]);
assert.deepEqual(res.body.outputs, ["/w/a.xlsx", "/w/b.md"]);
assert.deepEqual(res.body.skills, ["xlsx"]);
assert.deepEqual(res.body.mcp, ["vercel_vercel"]);
// A TodoWrite replaces the list wholesale.
await pre("TodoWrite", { todos: [{ content: "Verify", status: "pending" }] });
const again = await fetch(`/api/sessions/${sid}/outline`);
assert.deepEqual(again.body.progress, [{ id: "0", subject: "Verify", status: "pending" }]);
assert.equal((await fetch("/api/sessions/nope-outline/outline")).status, 404);
});
it("splits what a session used (uploads, files, memory) from what it changed", async () => {
const sid = "outline-used-" + Date.now();
const pre = (tool_name, tool_input) =>
post("/api/hooks/event", {
hook_type: "PostToolUse",
data: { session_id: sid, tool_name, tool_input, tool_response: {} },
});
const drop = "/tmp/agenthub-drops-1000/0123456789abcdef-minutes.xlsx";
await post("/api/hooks/event", { hook_type: "SessionStart", data: { session_id: sid } });
await post("/api/hooks/event", {
hook_type: "UserPromptSubmit",
data: {
session_id: sid,
prompt: `compare these ${drop}\n/tmp/agenthub-drops-1000/fedcba9876543210.png`,
},
});
const mem = "/home/u/.claude/projects/-w/memory/release.md";
await pre("Read", { file_path: drop });
await pre("Read", { file_path: "/w/src/a.ts" });
await pre("Read", { file_path: "/w/src/c.ts" });
await pre("Read", { file_path: mem });
await pre("Edit", { file_path: "/w/src/a.ts", old_string: "a", new_string: "b" });
await pre("MultiEdit", { file_path: "/w/src/b.ts", edits: [] });
await pre("Write", { file_path: mem, content: "x" });
const { body } = await fetch(`/api/sessions/${sid}/outline`);
assert.deepEqual(body.uploads, ["/tmp/agenthub-drops-1000/fedcba9876543210.png", drop]);
// a.ts was read, then edited: an output, no longer a file it only used.
assert.deepEqual(body.files, ["/w/src/c.ts"]);
assert.deepEqual(body.memory, [mem]);
assert.deepEqual(body.outputs, ["/w/src/b.ts", "/w/src/a.ts"]);
});
});
+64
View File
@@ -2017,6 +2017,70 @@ describe("a session's own worktree (claude --worktree)", () => {
});
});
describe("an extra folder's own repo (?source=)", () => {
const { execFileSync } = require("child_process");
const gitEnv = Object.fromEntries(
Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_"))
);
const gitIn = (dir, ...args) =>
execFileSync("git", ["-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", ...args], {
encoding: "utf8",
env: gitEnv,
});
let ws, extra, laneId, otherLaneId, sourceId, fileSourceId;
before(async () => {
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "lane-src-git-")));
ws = path.join(root, "ws");
extra = path.join(root, "extra");
for (const dir of [ws, extra]) {
fs.mkdirSync(dir);
gitIn(dir, "init", "-q", "-b", "main");
fs.writeFileSync(path.join(dir, "a.txt"), "a\n");
gitIn(dir, "add", ".");
gitIn(dir, "commit", "-qm", "init");
}
laneId = (await request("POST", "/api/lanes", { cwd: ws })).body.lane.id;
otherLaneId = (await request("POST", "/api/lanes", { cwd: extra })).body.lane.id;
const src = require("../lib/lane-sources");
sourceId = src.addFolder(laneId, extra).id;
fileSourceId = require("../db")
.db.prepare(
"INSERT INTO lane_sources (lane_id, kind, path, name, added_at) VALUES (?, 'file', ?, 'f', '2026-10-09T00:00:00Z')"
)
.run(laneId, path.join(extra, "a.txt")).lastInsertRowid;
});
it("reads and writes git in the extra folder, never falling back", async () => {
fs.writeFileSync(path.join(extra, "only-in-extra.txt"), "x\n");
const inExtra = await request("GET", `/api/lanes/${laneId}/git/changes?source=${sourceId}`);
assert.ok(inExtra.body.files.some((f) => f.path === "only-in-extra.txt"));
const facts = await request("GET", `/api/lanes/${laneId}/git?source=${sourceId}`);
assert.equal(facts.body.base, "main");
const main = await request("GET", `/api/lanes/${laneId}/git/changes`);
assert.ok(!main.body.files.some((f) => f.path === "only-in-extra.txt"));
const ok = await request("POST", `/api/lanes/${laneId}/git/stage?source=${sourceId}`, {
paths: ["only-in-extra.txt"],
});
assert.equal(ok.status, 200);
assert.match(gitIn(extra, "diff", "--cached", "--name-only"), /only-in-extra\.txt/);
});
it("answers ENOSOURCE for a source that is not this workspace's folder", async () => {
for (const id of ["nope", "999999", String(fileSourceId)]) {
const r = await request("POST", `/api/lanes/${laneId}/git/stage?source=${id}`, {
paths: ["only-in-extra.txt"],
});
assert.equal(r.status, 404, id);
assert.equal(r.body.error.code, "ENOSOURCE", id);
}
// Another workspace's request may not borrow this one's source id.
const r = await request("GET", `/api/lanes/${otherLaneId}/git/changes?source=${sourceId}`);
assert.equal(r.status, 404);
assert.equal(r.body.error.code, "ENOSOURCE");
});
});
// The server, not a stale client list, picks the tab and refuses a second pane
// on a session one already holds.
describe("start: slot auto and a session already live", () => {
+175 -2
View File
@@ -2,7 +2,8 @@
/**
* @file run.test.js
* @description Route tests for the terminal-run feature: same-origin guard,
* laneId/cwd validation, spawn/kill/list against a mocked tmux backend.
* laneId/cwd validation, spawn/kill/list against a mocked tmux backend, a
* dropped image served back, and a live pane's permission mode.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after, beforeEach } = require("node:test");
@@ -55,7 +56,7 @@ function fetchJson(p, opts = {}) {
} catch {
parsed = raw;
}
resolve({ status: res.statusCode, body: parsed });
resolve({ status: res.statusCode, body: parsed, headers: res.headers });
});
}
);
@@ -209,6 +210,27 @@ describe("/api/run", () => {
});
});
describe("GET /api/run/files", () => {
let srv;
const DIR = path.join(TMP, "files-proj");
before(async () => {
fs.mkdirSync(path.join(DIR, "src", "lib"), { recursive: true });
fs.writeFileSync(path.join(DIR, "src", "lib", "a.js"), "");
srv = http.createServer(createApp());
await new Promise((r) => srv.listen(0, r));
BASE = `http://127.0.0.1:${srv.address().port}`;
});
after(() => new Promise((r) => srv.close(r)));
const list = async (qs) =>
(await fetchJson(`/api/run/files?cwd=${encodeURIComponent(DIR)}${qs}`)).body.items;
it("lists files only, unless dirs=1 adds the folders with a trailing slash", async () => {
assert.deepEqual(await list(""), ["src/lib/a.js"]);
assert.deepEqual(await list("&dirs=1"), ["src/", "src/lib/", "src/lib/a.js"]);
assert.deepEqual(await list("&dirs=1&q=lib"), ["src/lib/", "src/lib/a.js"]);
});
});
describe("POST /api/run/drop-image", () => {
let srv;
before(async () => {
@@ -274,3 +296,154 @@ describe("POST /api/run/drop-image", () => {
assert.equal(r.status, 400);
});
});
describe("GET /api/run/drop/:name", () => {
let srv;
before(async () => {
srv = http.createServer(createApp());
await new Promise((r) => srv.listen(0, r));
BASE = `http://127.0.0.1:${srv.address().port}`;
});
after(() => new Promise((r) => srv.close(r)));
const PNG = Buffer.from("89504e470d0a1a0a0000", "hex");
it("serves a dropped image back as an image that runs nothing", async () => {
const saved = await fetchJson("/api/run/drop-image", {
method: "POST",
raw: { type: "image/png", buf: PNG },
});
const r = await fetchJson(`/api/run/drop/${path.basename(saved.body.path)}`);
assert.equal(r.status, 200);
assert.equal(r.headers["content-type"], "image/png");
assert.equal(r.headers["x-content-type-options"], "nosniff");
assert.match(r.headers["content-security-policy"], /sandbox/);
fs.unlinkSync(saved.body.path);
});
it("serves no file that is not a dropped image", async () => {
const link = path.join(
os.tmpdir(),
`agenthub-drops-${os.userInfo().uid}`,
"fedcba9876543210.png"
);
fs.rmSync(link, { force: true });
fs.symlinkSync("/etc/passwd", link);
const pdf = await fetchJson("/api/run/drop-file?name=a.pdf", {
method: "POST",
raw: { type: "application/pdf", buf: Buffer.from("%PDF") },
});
for (const name of [
path.basename(pdf.body.path), // a drop, but no image
"0123456789abcdef.png", // the right shape, never dropped
"..%2F..%2Fetc%2Fpasswd",
"passwd.png", // no random prefix
"fedcba9876543210.png", // a link planted under a drop's name
]) {
const r = await fetchJson(`/api/run/drop/${name}`);
assert.equal(r.status, 404, name);
}
fs.unlinkSync(pdf.body.path);
fs.unlinkSync(link);
});
});
describe("/api/run/:id/permission-mode", () => {
let srv;
before(async () => {
srv = http.createServer(createApp());
await new Promise((r) => srv.listen(0, r));
BASE = `http://127.0.0.1:${srv.address().port}`;
});
after(() => new Promise((r) => srv.close(r)));
beforeEach(() => tmux.__reset());
// A live claude pane whose mode line follows Shift+Tab around Claude Code's cycle.
const LINES = {
default: " ⏸ manual mode on · ← for agents",
acceptEdits: " ⏵⏵ accept edits on (shift+tab to cycle) · ← for agents",
plan: " ⏸ plan mode on (shift+tab to cycle) · ← for agents",
auto: " ⏵⏵ auto mode on (shift+tab to cycle) · ← for agents",
};
function fakePane(start) {
const cycle = ["default", "acceptEdits", "plan", "auto"];
const state = { mode: start, presses: 0 };
tmux.__setExecImpl((args) => {
if (args[0] === "capture-pane") return `❯ \n${"─".repeat(20)}\n${LINES[state.mode]}\n`;
if (args[0] === "send-keys" && args.at(-1) === "BTab") {
state.presses++;
state.mode = cycle[(cycle.indexOf(state.mode) + 1) % cycle.length];
}
return "";
});
return state;
}
it("GET reads the mode off the pane", async () => {
fakePane("plan");
const r = await fetchJson("/api/run/agenthub-lane-9/permission-mode");
assert.equal(r.status, 200);
assert.equal(r.body.mode, "plan");
});
it("POST presses Shift+Tab until the pane shows the mode asked for", async () => {
const state = fakePane("default");
const r = await fetchJson("/api/run/agenthub-lane-9/permission-mode", {
method: "POST",
body: { mode: "auto" },
});
assert.equal(r.status, 200);
assert.equal(r.body.mode, "auto");
assert.equal(state.presses, 3);
});
it("POST of a mode not in the cycle ends where it started, and says so", async () => {
const state = fakePane("acceptEdits");
const r = await fetchJson("/api/run/agenthub-lane-9/permission-mode", {
method: "POST",
body: { mode: "bypassPermissions" },
});
assert.equal(r.status, 409);
assert.equal(r.body.error.code, "EMODEUNAVAILABLE");
assert.equal(state.mode, "acceptEdits");
});
it("POST presses nothing when the mode line cannot be read", async () => {
let presses = 0;
tmux.__setExecImpl((args) => {
if (args[0] === "capture-pane") return "Select model\n❯ 1. Default\n";
if (args[0] === "send-keys") presses++;
return "";
});
const r = await fetchJson("/api/run/agenthub-lane-9/permission-mode", {
method: "POST",
body: { mode: "plan" },
});
assert.equal(r.status, 409);
assert.equal(r.body.error.code, "EMODEUNKNOWN");
assert.equal(presses, 0);
});
it("POST refuses a mode outside the allowlist", async () => {
fakePane("default");
const r = await fetchJson("/api/run/agenthub-lane-9/permission-mode", {
method: "POST",
body: { mode: "dontAsk; rm -rf ~" },
});
assert.equal(r.status, 400);
assert.equal(r.body.error.code, "EBADMODE");
});
it("answers 404 for a pane that is not running", async () => {
tmux.__setExecImpl((args) => {
if (args[0] === "has-session") {
const e = new Error("gone");
e.status = 1;
throw e;
}
return "";
});
const r = await fetchJson("/api/run/agenthub-lane-999/permission-mode");
assert.equal(r.status, 404);
});
});
@@ -185,6 +185,15 @@ describe("server mode", () => {
body: { prefs: { "agenthub.chatUi": null } },
});
assert.deepEqual((await call("GET", "/api/me/prefs", { cookie: boss })).body.prefs, {});
// The appearance (useTheme's storage keys) follows the account too.
const look = {
theme: "light",
"agenthub.theme.light": "canvas",
"agenthub.theme.dark": "darcula",
};
const saved = await call("PUT", "/api/me/prefs", { cookie: ana, body: { prefs: look } });
assert.equal(saved.status, 200);
assert.deepEqual(saved.body.prefs, look);
});
it("checks a WebSocket upgrade's login and Origin", async () => {
@@ -143,6 +143,12 @@ describe("server mode", () => {
assert.equal((await get("/api/lanes", "alice")).counts.total, 1);
assert.deepEqual(await laneIds("boss"), [LANE_A, LANE_B]);
assert.deepEqual(await laneIds("ana"), [LANE_A, LANE_B]);
// Each carries its owner's name, for the staff sidebar's per-user groups.
const owners = (await get("/api/lanes", "ana")).lanes.map((l) => [l.id, l.owner_name]);
assert.deepEqual(owners.sort(), [
[LANE_A, "alice"],
[LANE_B, "bob"],
]);
assert.deepEqual(
(await get("/api/workspaces", "bob")).lanes.map((l) => l.id),
[LANE_B]
+4 -1
View File
@@ -461,7 +461,10 @@ describe("a member's huge or sparse files", () => {
assert.equal(renames, 1);
const copy = path.join(getTranscriptSnapshotDir(), `${sid}.jsonl`);
assert.ok(fs.readFileSync(copy).equals(fs.readFileSync(src)));
assert.ok(warned.some((w) => w.includes("agent-x.jsonl")), JSON.stringify(warned));
assert.ok(
warned.some((w) => w.includes("agent-x.jsonl")),
JSON.stringify(warned)
);
assert.deepEqual(
fs.readdirSync(getTranscriptSnapshotDir()).filter((f) => f.endsWith(".tmp")),
[]
@@ -414,3 +414,47 @@ describe("GET /:id/transcript — mid-turn queued user messages (attachment/queu
assert.equal(bySnippet("and update the docs").sender, "user");
});
});
describe("GET /:id/transcript — what the chat needs to show live work", () => {
it("carries each assistant line's stop_reason and an edit result's +/- lines", async () => {
const cwd = "/tmp/cam-live-work";
const sid = "cccc1111-2222-3333-4444-555566667777";
writeTranscript(cwd, sid, [
{ type: "user", message: { role: "user", content: "fix it" } },
{
type: "assistant",
message: {
role: "assistant",
stop_reason: "tool_use",
content: [{ type: "tool_use", id: "e1", name: "Edit", input: { file_path: "/w/a.ts" } }],
},
},
{
type: "user",
message: {
role: "user",
content: [{ type: "tool_result", tool_use_id: "e1", content: "ok" }],
},
toolUseResult: {
filePath: "/w/a.ts",
structuredPatch: [{ lines: [" a", "-b", "+c", "+d"] }],
},
},
{
type: "assistant",
message: {
role: "assistant",
stop_reason: "end_turn",
content: [{ type: "text", text: "done" }],
},
},
]);
await req("POST", "/api/sessions", { id: sid, cwd });
const { body } = await req("GET", `/api/sessions/${sid}/transcript?limit=200`);
const [, call, result, done] = body.messages;
assert.equal(call.stop_reason, "tool_use");
assert.equal(done.stop_reason, "end_turn");
assert.deepEqual(result.content[0].diff, { added: 2, removed: 1 });
});
});
+33 -1
View File
@@ -18,7 +18,7 @@ const fs = require("node:fs");
const TEST_DB = path.join(os.tmpdir(), `transcript-sender-${Date.now()}-${process.pid}.db`);
process.env.DASHBOARD_DB_PATH = TEST_DB;
const { classifyTranscriptSender } = require("../routes/sessions");
const { classifyTranscriptSender, patchCounts } = require("../routes/sessions");
const { db } = require("../db");
after(() => {
@@ -136,3 +136,35 @@ describe("classifyTranscriptSender — subagent transcript", () => {
assert.equal(classifyTranscriptSender(assistant(), true), "assistant");
});
});
describe("patchCounts — the +/- lines of a Write/Edit result", () => {
it("counts a structuredPatch's added and removed lines, not its context", () => {
const r = {
filePath: "/w/a.ts",
structuredPatch: [
{
oldStart: 1,
oldLines: 3,
newStart: 1,
newLines: 4,
lines: [" a", "-b", "+c", "+d", " e"],
},
{ oldStart: 9, oldLines: 1, newStart: 10, newLines: 0, lines: ["-z"] },
],
};
assert.deepEqual(patchCounts(r), { added: 2, removed: 2 });
});
it("counts a created file's lines as added", () => {
assert.deepEqual(patchCounts({ type: "create", content: "a\nb\nc\n", structuredPatch: [] }), {
added: 3,
removed: 0,
});
});
it("answers null for a result that is no edit", () => {
assert.equal(patchCounts({ stdout: "ok" }), null);
assert.equal(patchCounts("text"), null);
assert.equal(patchCounts(undefined), null);
});
});
+23
View File
@@ -106,6 +106,28 @@ function addFolder(laneId, input, { allowed = () => true } = {}) {
return insertSource(laneId, "folder", resolved, path.basename(resolved) || resolved, null);
}
/**
* An extra folder's directory for the git routes (`?source=<id>`): only a
* `folder` row of THIS workspace that is still a directory — the request names
* a row id, never a path.
* @throws ENOSOURCE otherwise.
*/
function sourceFolder(laneId, sourceId) {
const row = /^\d+$/.test(String(sourceId))
? db
.prepare("SELECT path FROM lane_sources WHERE id = ? AND lane_id = ? AND kind = 'folder'")
.get(Number(sourceId), laneId)
: null;
let dir = null;
try {
dir = row && fs.statSync(row.path).isDirectory() ? fs.realpathSync(row.path) : null;
} catch {
/* gone since it was added */
}
if (!dir) throw fail("ENOSOURCE", "that folder is not one of this workspace's folders");
return dir;
}
/** A file name AgentHub can store: no directory part, no control or path characters. */
function safeName(raw) {
const base = path.basename(String(raw || "")).replace(/[^\p{L}\p{N}._ -]/gu, "_");
@@ -338,6 +360,7 @@ module.exports = {
contextDir,
listSources,
addFolder,
sourceFolder,
addFile,
removeSource,
removeLaneContext,
+7
View File
@@ -736,6 +736,12 @@ function inferredDisplayStage(lane) {
return lane.detected_stage;
}
/** The owner's username — the staff sidebar groups workspaces by it. */
function ownerName(id) {
if (id == null) return null;
return db.prepare("SELECT username FROM users WHERE id = ?").get(id)?.username ?? null;
}
function lanePayload(lane, ageSec = null) {
const pipeline = getPipeline(lane.pipeline);
const since = lane.stage_since ? Date.parse(lane.stage_since) : NaN;
@@ -749,6 +755,7 @@ function lanePayload(lane, ageSec = null) {
delete row.instructions;
return {
...row,
owner_name: ownerName(lane.owner_id),
pipeline_name: pipeline.name,
pipeline_skill: pipeline.skill || "",
pipeline_nodes:
+97
View File
@@ -0,0 +1,97 @@
/**
* @file pane-mode.js
* @description A live `claude` pane's permission mode, read off the pane and
* changed the only way Claude Code offers to a running session: Shift+Tab,
* which steps through its cycle (Manual → Accept edits → Plan → Auto, Bypass
* too when the session was allowed it). Every step is VERIFIED on the mode
* line Claude Code prints under its prompt before the next key goes in, so it
* stops on exactly the mode asked for — and presses nothing at all while that
* line cannot be read (a menu or dialog is open, where Shift+Tab means
* something else). A mode not in this session's cycle brings it back to where
* it began. One change at a time per pane. Only this pane is touched: the
* mode belongs to the session, not to an account.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const tmux = require("./tmux");
// Claude Code 2.1.x: "⏸ manual mode on · ← for agents",
// "⏵⏵ accept edits on (shift+tab to cycle)". The marker keeps a sentence in
// the conversation that merely mentions a mode from counting.
const LINE =
/(?:⏸|⏵⏵)\s+(manual mode|accept edits|plan mode|auto mode|bypass permissions|don't ask) on\b/;
const MODES = {
"manual mode": "default",
"accept edits": "acceptEdits",
"plan mode": "plan",
"auto mode": "auto",
"bypass permissions": "bypassPermissions",
"don't ask": "dontAsk",
};
const SETTABLE = new Set(["default", "acceptEdits", "plan", "auto", "bypassPermissions"]);
// Longest cycle Claude Code has: its six modes.
const MAX_PRESSES = 6;
/** The mode on the pane's bottom lines, or null when none is shown. */
function parseMode(screen) {
const lines = String(screen)
.split("\n")
.filter((l) => l.trim())
.slice(-4)
.reverse();
for (const l of lines) {
const m = LINE.exec(l);
if (m) return MODES[m[1]];
}
return null;
}
function readMode(runId) {
try {
return parseMode(tmux.capturePane(runId));
} catch {
return null;
}
}
const fail = (code, message) => Object.assign(new Error(message), { code });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// The mode once it differs from `from` — or what the pane shows at the deadline.
async function nextMode(runId, from, waitMs) {
const until = Date.now() + waitMs;
for (;;) {
const now = readMode(runId);
if ((now && now !== from) || Date.now() >= until) return now;
await sleep(50);
}
}
const busy = new Set();
/** Steps `runId`'s mode to `target`; resolves with the mode now shown. */
async function setMode(runId, target, { waitMs = 2000 } = {}) {
if (!SETTABLE.has(target))
throw fail("EBADMODE", `mode must be one of: ${[...SETTABLE].join(", ")}`);
if (busy.has(runId)) throw fail("EBUSY", "the mode is already being changed");
busy.add(runId);
try {
const start = readMode(runId);
if (!start) throw fail("EMODEUNKNOWN", "the pane shows no mode line — close its menu first");
let cur = start;
for (let i = 0; i < MAX_PRESSES && cur !== target; i++) {
tmux.sendKey(runId, "BTab");
const next = await nextMode(runId, cur, waitMs);
if (!next || next === cur) throw fail("EMODEUNKNOWN", "the mode did not change as expected");
cur = next;
if (cur === start) break;
}
if (cur !== target)
throw fail("EMODEUNAVAILABLE", `${target} is not available in this session`);
return cur;
} finally {
busy.delete(runId);
}
}
module.exports = { parseMode, readMode, setMode };
+15 -2
View File
@@ -11,8 +11,9 @@
* takes over an idle pane with `respawn-pane -- <argv>` rather than typing a
* quoted line into that pane's shell, which keeps an API key passed in `env`
* out of the pane's rendered text, its scrollback and the user's shell history.
* `sendText` is the one primitive that does send keystrokes — a pane running an
* interactive chat program that reads stdin as a message, not a shell.
* `sendText` is the one primitive that sends typed text — a pane running an
* interactive chat program that reads stdin as a message, not a shell — and
* `sendKey` presses one named key (Shift+Tab for `pane-mode.js`), never text.
*
* Server mode, one Linux user per account (S3): a member's panes live on THAT
* member's tmux server, socket `<home>/.agenthub/tmux/sock` (`run-as.js`), so
@@ -547,6 +548,16 @@ function pasteText(name, text) {
onServerOf(name, ["send-keys", "-t", pane(name), "Enter"]);
}
/** The pane's visible screen as plain text (no escape sequences). */
function capturePane(name) {
return String(onServerOf(name, ["capture-pane", "-p", "-t", pane(name)]));
}
/** Press ONE named key (`BTab`, `Escape`) in the pane — a key name, never text. */
function sendKey(name, key) {
onServerOf(name, ["send-keys", "-t", pane(name), key]);
}
/** Idempotent — a session that's already gone is not an error. */
function killSession(name) {
try {
@@ -657,6 +668,8 @@ module.exports = {
sendCommand,
sendText,
pasteText,
capturePane,
sendKey,
killSession,
listSessions,
liveSessions,
+3 -2
View File
@@ -715,11 +715,12 @@ const paths = {
tags: ["Lanes"],
summary: "Suggest a commit message for the staged changes",
description:
"Runs the user's `claude` CLI (`-p --safe-mode --no-session-persistence --tools \"\" --model haiku`) on the STAGED diff of the lane's cwd (or `?session=` worktree), sent on stdin with the last ten commit subjects; a `settings.local.json` is never included. Reads only — nothing is staged or committed, no tool runs and no session is saved. Same-origin, since each call spends the user's Claude quota. 400 ENOSTAGED when nothing is staged, 400 ENOTOOL when `claude` is not on PATH, 502 EAI when the CLI fails, answers empty or runs past 120 s.",
"Runs the user's `claude` CLI (`-p --safe-mode --no-session-persistence --tools \"\" --model haiku`) on the STAGED diff of the lane's cwd (or `?session=` worktree, or `?source=` extra folder), sent on stdin with the last ten commit subjects; a `settings.local.json` is never included. Reads only — nothing is staged or committed, no tool runs and no session is saved. Same-origin, since each call spends the user's Claude quota. 400 ENOSTAGED when nothing is staged, 400 ENOTOOL when `claude` is not on PATH, 502 EAI when the CLI fails, answers empty or runs past 120 s.",
operationId: "suggestLaneCommitMessage",
parameters: [
{ name: "id", in: "path", required: true, schema: { type: "integer" } },
{ name: "session", in: "query", required: false, schema: { type: "string" } },
{ name: "source", in: "query", required: false, schema: { type: "integer" } },
],
responses: {
200: {
@@ -736,7 +737,7 @@ const paths = {
},
400: { description: "ENOSTAGED / ENOTOOL / ENOWORKTREE" },
403: { description: "Cross-origin request refused" },
404: { description: "No such workspace" },
404: { description: "No such workspace, or ENOSOURCE" },
502: { description: "EAI — the claude CLI failed" },
},
},
+63
View File
@@ -432,12 +432,26 @@ function createOpenApiSpec() {
},
output: { type: "string", description: "Tool output text when type === tool_result." },
is_error: { type: "boolean" },
diff: {
type: "object",
description:
"On the tool_result of a Write/Edit/MultiEdit: the lines it added and removed (Claude Code's structuredPatch; every line of a file it created).",
properties: {
added: { type: "integer" },
removed: { type: "integer" },
},
},
},
},
TranscriptMessage: {
type: "object",
required: ["type", "content"],
properties: {
stop_reason: {
type: "string",
description:
"Assistant lines only: why the model stopped — `end_turn` closes the turn, `tool_use` means a tool call (and more work) follows.",
},
type: {
type: "string",
enum: ["user", "assistant", "session_event"],
@@ -1595,6 +1609,55 @@ function createOpenApiSpec() {
},
},
},
"/api/sessions/{id}/outline": {
get: {
tags: ["Sessions"],
summary: "Get a session's plan, outputs and what it used",
description:
"Read off the session's successful tool calls (PostToolUse events) and its prompts: `progress` is its TaskCreate/TaskUpdate plan (a TodoWrite replaces it wholesale), `outputs` the paths it wrote or edited with Write/Edit/MultiEdit/NotebookEdit, `files` the paths it only read, `uploads` the files attached to its prompts through the composer (`/api/run/drop-*` paths), `memory` the Claude Code memory files (`.claude/**/memory/`) it read or wrote — the path lists newest first, a memory file in `memory` only —, `skills` the skills it invoked and `mcp` the MCP servers it called. Powers the activity panel of a Chat pane shown alone.",
operationId: "getSessionOutline",
parameters: [{ $ref: "#/components/parameters/SessionIdPath" }],
responses: {
200: {
description: "The session's outline",
content: {
"application/json": {
schema: {
type: "object",
properties: {
progress: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string" },
subject: { type: "string" },
status: { type: "string" },
},
},
},
outputs: { type: "array", items: { type: "string" } },
files: { type: "array", items: { type: "string" } },
uploads: { type: "array", items: { type: "string" } },
memory: { type: "array", items: { type: "string" } },
skills: { type: "array", items: { type: "string" } },
mcp: { type: "array", items: { type: "string" } },
},
},
},
},
},
404: {
description: "Session not found",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
},
},
},
"/api/sessions/{id}/transcripts": {
get: {
tags: ["Sessions"],
+18 -5
View File
@@ -15,6 +15,7 @@ const path = require("node:path");
const { db } = require("../db");
const lanesLib = require("../lib/lanes");
const { sessionWorktree, removeSessionWorktree } = require("../lib/session-worktree");
const { sourceFolder } = require("../lib/lane-sources");
const { suggestCommitMessage } = require("../lib/commit-message");
const aiTools = require("../lib/ai-tools");
const {
@@ -951,8 +952,9 @@ router.get("/:id/git", async (req, res) => {
available: true,
...(await gitFacts(t.cwd)),
// What the Changes panel's "vs base" compares against: the lane's own
// base, else the repo's default branch.
base: t.lane.base_branch || (await defaultBranch(t.cwd)),
// base, else the repo's default branch (an extra folder is another
// repo: always its own default branch).
base: (!t.source && t.lane.base_branch) || (await defaultBranch(t.cwd)),
...(t.worktree ? { worktree: t.worktree } : {}),
});
} catch {
@@ -1702,13 +1704,24 @@ function gitErrorCode(err) {
* Which tree a git route works in: the workspace's own folder, or — with
* `?session=<id>` — that session's worktree (`claude --worktree`), resolved by
* `sessionWorktree` from the session ROW (owned by this workspace, registered
* by `git worktree list`), never from a path in the request. An unresolvable
* session is a 400, not a silent fall back to the main folder: a commit or a
* discard must never land in the wrong tree.
* by `git worktree list`), or — with `?source=<id>` — one of the workspace's
* extra folders, resolved by `sourceFolder` from its `lane_sources` ROW; never
* from a path in the request. An unresolvable session (400) or source (404,
* like another workspace's row) is never a silent fall back to the main
* folder: a commit or a discard must never land in the wrong tree.
*/
async function gitTargetOr404(req, res) {
const lane = laneOr404(req, res);
if (!lane) return null;
if (req.query.source !== undefined) {
try {
const cwd = sourceFolder(lane.id, req.query.source);
return { lane, cwd, worktree: null, source: true };
} catch (err) {
res.status(404).json({ error: { code: err.code, message: err.message } });
return null;
}
}
const session = req.query.session;
if (session === undefined) return { lane, cwd: lane.cwd, worktree: null };
try {
+14 -9
View File
@@ -1,13 +1,15 @@
/**
* @file me.js
* @description `/api/me` — the signed-in account's own UI preferences and its
* first-run setup (docs/plans/onboarding). The browser keeps these in
* localStorage; this stores the same keys per ACCOUNT (`user_prefs`), so they
* follow it to any browser and the setup wizard shows once per account.
* Local mode is one account, `local`. Only the keys in `PREF_KEYS` are kept,
* each a string of at most 8 KB — this is a preferences store, not a blob
* store. Writes are same-origin and touch only the caller's own row.
* `agenthub.chatUi` ("1") opens Claude/Codex sessions as a chat (`PaneChat`).
* @description `/api/me` — the signed-in account's own UI preferences
* (`user_prefs`) and its first-run setup (docs/plans/onboarding), so they
* follow it to any browser, differ between the accounts of one dashboard, and
* the setup wizard shows once per account. Local mode is one account,
* `local`; server mode keys a row `u<id>` by the login cookie — the request
* never names an account. Only the keys in `PREF_KEYS` are kept, each a
* string of at most 8 KB, and a PUT merges into the row (`null` removes a
* key). Writes are same-origin and touch only the caller's own row.
* `agenthub.chatUi` ("1") opens Claude/Codex sessions as a chat (`PaneChat`);
* the appearance keys are `useTheme`'s own (`theme`, `agenthub.theme.dark|light`).
*
* S3 (one Linux user per account): an account's dark/light choice also becomes
* the theme in their own Claude Code settings, written as them.
@@ -92,7 +94,10 @@ router.put("/prefs", sameOriginGuard, (req, res) => {
}
if (v === null) delete prefs[k];
else if (typeof v === "string" && v.length <= MAX_VALUE) prefs[k] = v;
else return res.status(400).json({ error: { code: "EBADPREFS", message: `${k}: a short string` } });
else
return res
.status(400)
.json({ error: { code: "EBADPREFS", message: `${k}: a short string` } });
}
upsert.run(key, JSON.stringify(prefs));
if ("theme" in patch) followClaudeTheme(req, patch.theme);
+97 -3
View File
@@ -3,7 +3,9 @@
* @description HTTP routes for the dashboard's terminal-run feature. Starts,
* resumes, kills, and lists tmux-backed sessions for `claude` or `codex` (one per lane),
* streamed to the client over a dedicated WebSocket path (see
* server/websocket.js `/ws-pty/:runId`) rather than this REST surface.
* server/websocket.js `/ws-pty/:runId`) rather than this REST surface. Also
* saves files dropped on a pane or a prompt box (and serves a dropped image
* back for the chat), and reads/steps a live claude pane's permission mode.
*
* Security model:
* - Local-first dashboard. The dashboard server is expected to bind to
@@ -31,6 +33,7 @@ const { sameOriginGuard } = require("../lib/same-origin");
const aiTools = require("../lib/ai-tools");
const { resumeProxy } = require("../lib/proxy-apply");
const scope = require("../lib/scope");
const paneMode = require("../lib/pane-mode");
const router = Router();
@@ -331,6 +334,8 @@ router.get("/files", (req, res) => {
}
if (!insideOwnWorkspace(req, cwd)) return refuseFolder(res);
const q = typeof req.query.q === "string" ? req.query.q.toLowerCase() : "";
// The composer's "Add from project" also attaches folders (`dir/`).
const dirs = req.query.dirs === "1";
const SKIP_DIRS = new Set([
"node_modules",
".git",
@@ -364,7 +369,9 @@ router.get("/files", (req, res) => {
if (ent.name.startsWith(".") && ent.name !== ".env" && ent.name !== ".gitignore") continue;
if (ent.isDirectory()) {
if (SKIP_DIRS.has(ent.name)) continue;
walk(path.join(dir, ent.name), rel ? `${rel}/${ent.name}` : ent.name);
const relDir = rel ? `${rel}/${ent.name}` : ent.name;
if (dirs && (!q || relDir.toLowerCase().includes(q))) results.push(`${relDir}/`);
walk(path.join(dir, ent.name), relDir);
} else if (ent.isFile()) {
const relPath = rel ? `${rel}/${ent.name}` : ent.name;
if (!q || relPath.toLowerCase().includes(q)) {
@@ -451,7 +458,9 @@ router.post("/", (req, res) => {
return res.status(201).json(handle);
} catch (err) {
// A busy pane is a conflict with live state, not a malformed request.
if (["ERUNLIVE", "ENOTSHARED", "EMEMBERGONE", "EOWNERFOLDER", "ECWDACCOUNT"].includes(err.code)) {
if (
["ERUNLIVE", "ENOTSHARED", "EMEMBERGONE", "EOWNERFOLDER", "ECWDACCOUNT"].includes(err.code)
) {
return res.status(409).json({ error: { code: err.code, message: err.message } });
}
// Nor is a host missing tmux: the request was fine, the dependency is not
@@ -466,6 +475,91 @@ router.post("/", (req, res) => {
}
});
// A dropped image, shown back in the session's conversation. Only a name
// drop-image/drop-file made (random hex prefix, no separator) and only an image
// type; raster only and under a sandbox CSP, like `/git/raw`.
const DROP_IMAGE_TYPES = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
};
router.get("/drop/:name", (req, res) => {
const name = String(req.params.name);
const m = /^[0-9a-f]{16}(?:-[A-Za-z0-9._-]+)?\.([A-Za-z]+)$/.exec(name);
const type = m && DROP_IMAGE_TYPES[m[1].toLowerCase()];
// Opened first, then checked on the descriptor (no window to swap the name
// for a link after the check): a regular file this account wrote. NOFOLLOW
// refuses a link outright; NONBLOCK keeps a FIFO from hanging the loop.
// S3: the requester's own drop dir, owned by their member account — so an
// admin viewing a member's session gets the name chip, not the image.
let fd = null;
try {
if (type) {
const { dir, member } = dropDir(req);
fd = fs.openSync(
path.join(dir, name),
fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0)
);
const st = fs.fstatSync(fd);
const uid = member
? member.uid
: typeof process.getuid === "function"
? process.getuid()
: st.uid;
if (!st.isFile() || st.uid !== uid) {
fs.closeSync(fd);
fd = null;
}
}
} catch {
/* pruned, never dropped, or a link */
}
if (fd === null) {
return res.status(404).json({ error: { code: "ENOTFOUND", message: "no such image" } });
}
res.set({
"Content-Type": type,
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, max-age=86400",
});
fs.createReadStream(null, { fd }).pipe(res);
});
// A live claude pane, or the 404/400 already sent.
function claudePane(req, res) {
const handle = scope.canSeeRun(req, req.params.id) ? runs.getRun(req.params.id) : null;
if (!handle || handle.status === "gone") {
res.status(404).json({ error: { code: "ENOTFOUND", message: "run not found" } });
return null;
}
if (handle.tool !== "claude") {
res.status(400).json({
error: { code: "EUNSUPPORTED", message: "only a claude pane has a permission mode" },
});
return null;
}
return handle;
}
router.get("/:id/permission-mode", (req, res) => {
const handle = claudePane(req, res);
if (handle) res.json({ mode: paneMode.readMode(handle.id) });
});
router.post("/:id/permission-mode", async (req, res) => {
const handle = claudePane(req, res);
if (!handle) return;
try {
res.json({ mode: await paneMode.setMode(handle.id, String(req.body?.mode ?? "")) });
} catch (err) {
const status = err.code === "EBADMODE" ? 400 : err.code ? 409 : 500;
res.status(status).json({ error: { code: err.code || "EINTERNAL", message: err.message } });
}
});
router.get("/:id", (req, res) => {
const handle = scope.canSeeRun(req, req.params.id) ? runs.getRun(req.params.id) : null;
if (!handle || handle.status === "gone") {
+149 -1
View File
@@ -357,6 +357,123 @@ router.get("/:id/stats", (req, res) => {
res.json(sessionStats(req.params.id));
});
const OUTLINE_TOOLS = [
"TaskCreate",
"TaskUpdate",
"TodoWrite",
"Write",
"Edit",
"MultiEdit",
"NotebookEdit",
"Read",
"Skill",
];
const outlineEvents = db.prepare(
`SELECT tool_name, data FROM events
WHERE session_id = ?
AND ((event_type = 'PostToolUse'
AND (tool_name IN (${OUTLINE_TOOLS.map(() => "?").join(",")})
OR (tool_name >= 'mcp__' AND tool_name < 'mcp_\`')))
OR event_type = 'UserPromptSubmit')
ORDER BY id`
);
// A file the composer attached (`/api/run/drop-*` names it), as its path is
// pasted into the prompt; and a Claude Code memory file.
const UPLOAD_RE =
/(?:^|\s)(\S*\/agenthub-drops-\d+\/[0-9a-f]{16}(?:-[A-Za-z0-9._-]+)?\.[A-Za-z0-9]+)/g;
const isUpload = (p) => /\/agenthub-drops-\d+\//.test(p);
const isMemory = (p) => /\/\.claude\/.*\/memory\//.test(p);
/** Records `p` once, newest last. */
const touch = (set, p) => {
set.delete(p);
set.add(p);
};
/** The `/:id/outline` body: the session's plan, the files it wrote or edited
* (`outputs`), what it used — the files it read, the files attached to its
* prompts (`uploads`), the memory files it read or wrote, skills and MCP
* servers — read off its successful tool calls (`PostToolUse`) and prompts.
* A `TodoWrite` replaces the plan wholesale; `TaskCreate` / `TaskUpdate` edit
* it by task id (a hook posted twice changes nothing). Lists are newest first,
* except skills and MCP servers (first use first). */
function sessionOutline(sessionId) {
let tasks = new Map();
const outputs = new Set();
const files = new Set();
const uploads = new Set();
const memory = new Set();
const skills = new Set();
const mcp = new Set();
for (const e of outlineEvents.all(sessionId, ...OUTLINE_TOOLS)) {
let d;
try {
d = JSON.parse(e.data);
} catch {
continue;
}
const input = d?.tool_input || {};
const t = e.tool_name;
const p = input.file_path || input.notebook_path;
if (!t) {
// A prompt: the paths it carries of files the composer attached.
for (const m of String(d?.prompt ?? "").matchAll(UPLOAD_RE)) touch(uploads, m[1]);
} else if (typeof p === "string" && isMemory(p)) {
touch(memory, p);
} else if (t === "Read") {
if (typeof p === "string" && !isUpload(p) && !outputs.has(p)) touch(files, p);
} else if (t === "TodoWrite" && Array.isArray(input.todos)) {
tasks = new Map(
input.todos.map((x, i) => [
String(i),
{ id: String(i), subject: String(x?.content ?? ""), status: x?.status || "pending" },
])
);
} else if (t === "TaskCreate") {
const id = d?.tool_response?.task?.id;
if (id != null && !tasks.has(String(id)))
tasks.set(String(id), {
id: String(id),
subject: String(input.subject ?? ""),
status: "pending",
});
} else if (t === "TaskUpdate") {
const task = tasks.get(String(input.taskId));
if (!task) continue;
if (input.status === "deleted") tasks.delete(task.id);
else {
if (input.status) task.status = input.status;
if (input.subject) task.subject = String(input.subject);
}
} else if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(t)) {
if (typeof p === "string") {
touch(outputs, p);
files.delete(p); // a file it changed is an output, not just used
}
} else if (t === "Skill") {
if (typeof input.skill === "string") skills.add(input.skill);
} else {
const server = t.slice(5, t.lastIndexOf("__"));
if (server) mcp.add(server.replace(/^plugin_/, ""));
}
}
return {
progress: [...tasks.values()],
outputs: [...outputs].reverse(),
files: [...files].reverse(),
uploads: [...uploads].reverse(),
memory: [...memory].reverse(),
skills: [...skills],
mcp: [...mcp],
};
}
router.get("/:id/outline", (req, res) => {
if (!stmts.getSession.get(req.params.id)) {
return res.status(404).json({ error: { code: "NOT_FOUND", message: "Session not found" } });
}
res.json(sessionOutline(req.params.id));
});
/** The `/:id/stats` body — also frozen into a session snapshot. */
function sessionStats(sessionId) {
const totalEvents = stmts.sessionEventCount.get(sessionId)?.count ?? 0;
@@ -550,7 +667,9 @@ router.get("/:id/transcripts", async (req, res) => {
const metaPath = path.join(dir, file.replace(".jsonl", ".meta.json"));
if (fs.existsSync(metaPath)) {
try {
meta = JSON.parse(require("../lib/run-as").readFileSafe(metaPath, "utf8", { max: 1 << 20 }));
meta = JSON.parse(
require("../lib/run-as").readFileSafe(metaPath, "utf8", { max: 1 << 20 })
);
} catch {
/* ignore */
}
@@ -839,6 +958,8 @@ router.get("/:id/transcript", async (req, res) => {
if (block.type === "text" && block.text) {
content.push({ type: "text", text: truncate(block.text, 10240) });
} else if (block.type === "tool_result") {
// A line carries one tool result; an edit's +/- counts ride on it.
const diff = patchCounts(entry.toolUseResult);
content.push({
type: "tool_result",
id: block.tool_use_id || null,
@@ -849,6 +970,7 @@ router.get("/:id/transcript", async (req, res) => {
10240
),
is_error: !!block.is_error,
...(diff ? { diff } : {}),
});
}
}
@@ -891,6 +1013,8 @@ router.get("/:id/transcript", async (req, res) => {
if (entry.type === "assistant") {
if (msg.model) message.model = msg.model;
// "end_turn" closes the turn; "tool_use" means more work follows.
if (typeof msg.stop_reason === "string") message.stop_reason = msg.stop_reason;
if (msg.usage) {
message.usage = {
input_tokens: msg.usage.input_tokens || 0,
@@ -1112,6 +1236,29 @@ function codexMessage(entry, num) {
}
}
/** The +/- line counts of a Write/Edit/MultiEdit result (`toolUseResult`):
* its `structuredPatch` hunks' `+`/`-` lines, or every line of a file it
* created. Null for any other result. */
function patchCounts(r) {
if (!r || typeof r !== "object") return null;
if (Array.isArray(r.structuredPatch) && r.structuredPatch.length) {
let added = 0;
let removed = 0;
for (const h of r.structuredPatch) {
for (const l of Array.isArray(h?.lines) ? h.lines : []) {
if (typeof l !== "string") continue;
if (l.startsWith("+")) added++;
else if (l.startsWith("-")) removed++;
}
}
return { added, removed };
}
if (r.type === "create" && typeof r.content === "string") {
return { added: r.content.split("\n").length - (r.content.endsWith("\n") ? 1 : 0), removed: 0 };
}
return null;
}
function truncate(str, maxLen) {
if (!str || str.length <= maxLen) return str;
return str.slice(0, maxLen) + "[truncated]";
@@ -1128,3 +1275,4 @@ module.exports = router;
module.exports.sessionStats = sessionStats;
// Exported for unit tests — sender attribution is correctness-critical.
module.exports.classifyTranscriptSender = classifyTranscriptSender;
module.exports.patchCounts = patchCounts;