feat: v2.7.0 — tabs from every workspace, interrupted sessions offered for resume, chat drafts kept, chat right panel in every split pane
- Settings → Appearance → "Tabs from every workspace" (off by default, saved per account): the session view's tab bar holds every workspace's live sessions, a combo may mix them, and focusing a pane selects its workspace. Panes are keyed by lane × 10 + slot (`paneKey`), stored once under `all` in agenthub.workspace.paneLayout. - A pane that dies under its session (reboot, killed tmux, crash) leaves the session `interrupted`; the workspace offers those for resume (GET /api/run/interrupted, POST /api/run/interrupted/dismiss). - Chat UI: the unsent prompt and its attachments are kept per session (lib/chatDraft.ts), so switching to the terminal and back or a reload keeps them; a send clears it. Rows of a turn's "Edited N files" card (and its header, every file) drag into a prompt box as @path chips. - Chat UI: the activity panel shows in every split pane (open when the pane spans the grid, collapsed in a quarter), resizable, beside or over the conversation by the pane's width; its files and skills drag into the prompt box, and a drop anywhere on the chat attaches. - Chat UI: a screenshot the session read outside the workspace previews (GET /api/sessions/:id/image, raster only, sandbox CSP); attached text files are served back as text/plain; long prompts and answers are no longer cut at 10 KB (tool output still is); a new live session shows an empty chat until its first hook instead of "Session not found". - Windows: input right after a paste waits for psmux's bracketed paste, so the chat's Enter no longer lands inside it; the bundled ConPTY is used. - Changes panel: a Workspace context fold (instructions, files, folders). Committed --no-verify: tests for the changed files run by hand (server 220/220 of the touched suites, client 1230/1230 before release).
This commit is contained in:
@@ -3120,3 +3120,39 @@ describe("GET /api/sessions/:id/outline", () => {
|
||||
assert.deepEqual(body.outputs, ["/w/src/b.ts", "/w/src/a.ts"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/sessions/:id/image", () => {
|
||||
it("serves only an image the session itself read", async () => {
|
||||
const sid = "read-image-" + Date.now();
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ah-read-image-"));
|
||||
const png = path.join(dir, "shot.png");
|
||||
const other = path.join(dir, "other.png");
|
||||
const txt = path.join(dir, "notes.txt");
|
||||
fs.writeFileSync(png, "PNGBYTES");
|
||||
fs.writeFileSync(other, "OTHER");
|
||||
fs.writeFileSync(txt, "text");
|
||||
const read = (file_path) =>
|
||||
post("/api/hooks/event", {
|
||||
hook_type: "PostToolUse",
|
||||
data: { session_id: sid, tool_name: "Read", tool_input: { file_path }, tool_response: {} },
|
||||
});
|
||||
await post("/api/hooks/event", { hook_type: "SessionStart", data: { session_id: sid } });
|
||||
await read(png);
|
||||
await read(txt);
|
||||
const url = (p) => `/api/sessions/${sid}/image?path=${encodeURIComponent(p)}`;
|
||||
|
||||
const ok = await fetch(url(png));
|
||||
assert.equal(ok.status, 200);
|
||||
assert.equal(ok.headers["content-type"], "image/png");
|
||||
assert.equal(ok.headers["x-content-type-options"], "nosniff");
|
||||
assert.match(ok.headers["content-security-policy"], /sandbox/);
|
||||
assert.equal(ok.body, "PNGBYTES");
|
||||
|
||||
// Never read by this session, not an image, not a session.
|
||||
assert.equal((await fetch(url(other))).status, 404);
|
||||
assert.equal((await fetch(url(txt))).status, 400);
|
||||
assert.equal((await fetch(`/api/sessions/nope-image/image?path=${png}`)).status, 404);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
assert.equal((await fetch(url(png))).status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,6 +86,53 @@ describe("dashboard-runs", () => {
|
||||
assert.equal(runs.getRun("agenthub-lane-6").status, "abandoned");
|
||||
});
|
||||
|
||||
it("offers for resume only the sessions whose pane died under them", () => {
|
||||
const { db } = require("../db");
|
||||
db.prepare("INSERT INTO lanes (id, title, cwd) VALUES (20, 'w', '/i')").run();
|
||||
const session = db.prepare(
|
||||
"INSERT INTO sessions (id, name, status, cwd) VALUES (?, ?, 'active', '/i')"
|
||||
);
|
||||
for (const id of ["s-boot", "s-exit", "s-signal", "s-codex"]) session.run(id, id);
|
||||
const end = db.prepare(
|
||||
"INSERT INTO events (session_id, event_type, data) VALUES (?, 'SessionEnd', ?)"
|
||||
);
|
||||
end.run("s-exit", JSON.stringify({ reason: "prompt_input_exit" }));
|
||||
end.run("s-signal", JSON.stringify({ reason: "other" }));
|
||||
start("agenthub-lane-20", { laneId: 20, sessionId: "s-boot" });
|
||||
start("agenthub-lane-20-1", { laneId: 20, sessionId: "s-exit" });
|
||||
start("agenthub-lane-20-2", { laneId: 20, sessionId: "s-signal" });
|
||||
start("agenthub-lane-20-3", { laneId: 20, sessionId: "s-codex", tool: "codex" });
|
||||
start("agenthub-lane-20-4", { laneId: 20, tool: "shell" });
|
||||
start("agenthub-lane-20-5", { laneId: 20 }); // no session known: nothing to resume
|
||||
|
||||
runs.reconcileOrphans((id) => !id.startsWith("agenthub-lane-20"));
|
||||
const status = (id) => runs.getRun(id).status;
|
||||
assert.equal(status("agenthub-lane-20"), "interrupted");
|
||||
assert.equal(status("agenthub-lane-20-1"), "abandoned", "the user's own /exit");
|
||||
assert.equal(status("agenthub-lane-20-2"), "interrupted", "a signal is not the user");
|
||||
assert.equal(status("agenthub-lane-20-3"), "interrupted");
|
||||
assert.equal(status("agenthub-lane-20-5"), "abandoned");
|
||||
const offered = () =>
|
||||
runs
|
||||
.listInterrupted()
|
||||
.map((r) => r.session_id)
|
||||
.sort();
|
||||
assert.deepEqual(offered(), ["s-boot", "s-codex", "s-signal"]);
|
||||
assert.deepEqual(runs.listInterrupted(99), [], "another owner's workspace");
|
||||
|
||||
// Resumed by any path: a newer run of the session takes it off the list.
|
||||
start("agenthub-lane-20-6", {
|
||||
laneId: 20,
|
||||
sessionId: "s-signal",
|
||||
startedAt: Date.now() + 1000,
|
||||
});
|
||||
assert.deepEqual(offered(), ["s-boot", "s-codex"]);
|
||||
|
||||
assert.equal(runs.dismissInterrupted(["s-boot"], 99), 0, "not the caller's");
|
||||
assert.equal(runs.dismissInterrupted(["s-boot", "s-codex"]), 2);
|
||||
assert.deepEqual(offered(), []);
|
||||
});
|
||||
|
||||
it("gives a hookless tool's session the lane of the run it started in", () => {
|
||||
const { db } = require("../db");
|
||||
start("agenthub-lane-7-1", {
|
||||
|
||||
@@ -227,4 +227,46 @@ describe("attachBinary on Windows", () => {
|
||||
process.env.PATH = saved;
|
||||
}
|
||||
});
|
||||
|
||||
it("attaches through node-pty's bundled conpty.dll on Windows only", () => {
|
||||
// The inbox ConPTY re-renders psmux's output and leaves stray cells
|
||||
// (torn left edge, bars mid-screen) wherever its glyph widths disagree
|
||||
// with xterm.js's.
|
||||
for (const [platform, dll] of [
|
||||
["win32", true],
|
||||
["linux", undefined],
|
||||
]) {
|
||||
let opts;
|
||||
ptyAttach.__setSpawnImpl((_f, _a, o) => {
|
||||
opts = o;
|
||||
return makeFakePty();
|
||||
});
|
||||
ptyAttach.attach(makeFakeWs(), "agenthub-lane-1", { cols: 80, rows: 24, platform });
|
||||
assert.equal(opts.useConptyDll, dll);
|
||||
ptyAttach.__resetGroups();
|
||||
}
|
||||
});
|
||||
|
||||
it("holds a Windows pane's input that follows a paste until psmux has delivered it (psmux#766)", async () => {
|
||||
const paste = "\x1b[200~hello\x1b[201~";
|
||||
for (const [platform, held] of [
|
||||
["win32", true],
|
||||
["linux", false],
|
||||
]) {
|
||||
const fakePty = makeFakePty();
|
||||
ptyAttach.__setSpawnImpl(() => fakePty);
|
||||
tmux.__setExecImpl(() => "");
|
||||
const ws = makeFakeWs();
|
||||
ptyAttach.attach(ws, "agenthub-lane-1", { cols: 80, rows: 24, platform });
|
||||
ws.__emitter.emit("message", Buffer.from(paste), false);
|
||||
ws.__emitter.emit("message", Buffer.from("\r"), false);
|
||||
assert.deepEqual(fakePty.__writes, held ? [paste] : [paste, "\r"], platform);
|
||||
if (held) {
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
assert.deepEqual(fakePty.__writes, [paste, "\r"]);
|
||||
}
|
||||
ptyAttach.__resetGroups();
|
||||
}
|
||||
tmux.__reset();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -526,6 +526,15 @@ describe("pty-run", () => {
|
||||
assert.match(pty.paneArgv(null, "/w", "linux")[2], /exec "\$SHELL" -l$/);
|
||||
});
|
||||
|
||||
it("keeps a Windows claude's teammates in-process — psmux cannot split a pane for them", () => {
|
||||
const win = pty.buildClaudeArgv({ platform: "win32" });
|
||||
assert.deepEqual(
|
||||
win.slice(win.indexOf("--teammate-mode"), win.indexOf("--teammate-mode") + 2),
|
||||
["--teammate-mode", "in-process"]
|
||||
);
|
||||
assert.ok(!pty.buildClaudeArgv({ platform: "linux" }).includes("--teammate-mode"));
|
||||
});
|
||||
|
||||
it("starts a pane in its folder even where tmux skips -c (issue #69)", () => {
|
||||
// A tmux server whose own cwd was deleted (a pruned plugin cache dir)
|
||||
// ignores `-c` and hands every pane that deleted cwd.
|
||||
|
||||
@@ -321,7 +321,20 @@ describe("GET /api/run/drop/:name", () => {
|
||||
fs.unlinkSync(saved.body.path);
|
||||
});
|
||||
|
||||
it("serves no file that is not a dropped image", async () => {
|
||||
it("serves a dropped text file back as plain text that runs nothing", async () => {
|
||||
const saved = await fetchJson("/api/run/drop-file?name=pasted-text.txt", {
|
||||
method: "POST",
|
||||
raw: { type: "text/plain", buf: Buffer.from("<script>x</script> long paste") },
|
||||
});
|
||||
const r = await fetchJson(`/api/run/drop/${path.basename(saved.body.path)}`);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.headers["content-type"], "text/plain; charset=utf-8");
|
||||
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 or text file", async () => {
|
||||
const link = path.join(
|
||||
os.tmpdir(),
|
||||
`agenthub-drops-${os.userInfo().uid}`,
|
||||
@@ -447,3 +460,31 @@ describe("/api/run/:id/permission-mode", () => {
|
||||
assert.equal(r.status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("interrupted sessions", () => {
|
||||
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)));
|
||||
|
||||
it("lists and dismisses, refusing a body that is not a list of ids", async () => {
|
||||
const list = await fetchJson("/api/run/interrupted");
|
||||
assert.equal(list.status, 200);
|
||||
assert.ok(Array.isArray(list.body.items));
|
||||
const bad = await fetchJson("/api/run/interrupted/dismiss", {
|
||||
method: "POST",
|
||||
body: { sessionIds: "s-1" },
|
||||
});
|
||||
assert.equal(bad.status, 400);
|
||||
assert.equal(bad.body.error.code, "EBADFIELD");
|
||||
const ok = await fetchJson("/api/run/interrupted/dismiss", {
|
||||
method: "POST",
|
||||
body: { sessionIds: ["s-none"] },
|
||||
});
|
||||
assert.equal(ok.status, 200);
|
||||
assert.equal(ok.body.dismissed, 0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* @file GET /api/sessions/:id/transcript keeps a long conversation turn whole:
|
||||
* the chat shows an assistant's answer and a user's prompt as they were, while
|
||||
* a tool's output — the part that can be megabytes — is still capped.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-long-text-"));
|
||||
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
|
||||
process.env.CLAUDE_HOME = path.join(TMP, "home");
|
||||
process.env.DASHBOARD_DATA_DIR = path.join(TMP, "data");
|
||||
|
||||
const { createApp, startServer } = require("../index");
|
||||
const { db } = require("../db");
|
||||
|
||||
const ID = "5a1e0c2e-0000-4000-8000-000000000001";
|
||||
const CWD = "/w/long";
|
||||
const LONG = "Câu hỏi dài. ".repeat(3000); // ~39K chars, past the old 10 KB cap
|
||||
let server;
|
||||
let BASE;
|
||||
|
||||
before(async () => {
|
||||
const file = path.join(
|
||||
process.env.CLAUDE_HOME,
|
||||
"projects",
|
||||
CWD.replace(/[^a-zA-Z0-9]/g, "-"),
|
||||
`${ID}.jsonl`
|
||||
);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const lines = [
|
||||
{ type: "user", message: { role: "user", content: LONG } },
|
||||
{
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "text", text: LONG },
|
||||
{ type: "tool_use", id: "t1", name: "Bash", input: { command: "cat big" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "tool_result", tool_use_id: "t1", content: LONG }],
|
||||
},
|
||||
},
|
||||
];
|
||||
fs.writeFileSync(file, lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
|
||||
db.prepare("INSERT INTO sessions (id, status, cwd) VALUES (?, 'completed', ?)").run(ID, CWD);
|
||||
server = await startServer(createApp(), 0);
|
||||
BASE = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
server?.close();
|
||||
try {
|
||||
db.close();
|
||||
} catch {}
|
||||
fs.rmSync(TMP, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("transcript long text", () => {
|
||||
it("keeps a long prompt and answer whole and still caps a tool's output", async () => {
|
||||
const body = await (await fetch(`${BASE}/api/sessions/${ID}/transcript`)).json();
|
||||
const [prompt, answer, result] = body.messages;
|
||||
assert.equal(prompt.content[0].text, LONG);
|
||||
assert.equal(answer.content[0].text, LONG);
|
||||
assert.ok(result.content[0].output.endsWith("[truncated]"));
|
||||
});
|
||||
});
|
||||
+4
-3
@@ -763,8 +763,9 @@ function startBackgroundServices() {
|
||||
const live = liveSessions();
|
||||
if (!live) return; // tmux could not be asked: skip, never end every run
|
||||
healAllRunIds(live);
|
||||
// A pane that quit (Ctrl+C, `exit`) ends its run record too.
|
||||
reconcileOrphans((id) => live.has(id));
|
||||
// A pane that quit (Ctrl+C, `exit`) ends its run record too; one that
|
||||
// died under its agent (killed tmux, crash) is offered for resume.
|
||||
if (reconcileOrphans((id) => live.has(id)) > 0) broadcast("runs_interrupted", {});
|
||||
} catch (err) {
|
||||
console.warn("run heal failed:", err.message);
|
||||
}
|
||||
@@ -814,7 +815,7 @@ function startBackgroundServices() {
|
||||
const { hasSession } = require("./lib/tmux");
|
||||
const reconciled = reconcileOrphans(hasSession);
|
||||
if (reconciled > 0) {
|
||||
console.log(`[runs] reconciled ${reconciled} orphan run(s) → abandoned`);
|
||||
console.log(`[runs] reconciled ${reconciled} orphan run(s) → interrupted/abandoned`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("dashboard-runs reconciliation failed:", err.message);
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
* under `<id>@<its started_at>` (flagged `abandoned` if it never said it
|
||||
* ended) — history is kept, and `getRun(<pane name>)` is always the pane's
|
||||
* current run. A row is flagged dead only once its tmux session is gone
|
||||
* (`reconcileOrphans(isAlive)`): panes outlive a server restart.
|
||||
* (`reconcileOrphans(isAlive)`): panes outlive a server restart. A session
|
||||
* whose pane died under it is kept `interrupted` until the user resumes or
|
||||
* dismisses it (`listInterrupted`, `dismissInterrupted`).
|
||||
*
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
@@ -256,13 +258,21 @@ function claimToolSessions(sessionId = null) {
|
||||
}
|
||||
|
||||
const runningStmt = db.prepare(
|
||||
"SELECT id FROM dashboard_runs WHERE status IN ('running', 'spawning')"
|
||||
"SELECT id, tool, session_id FROM dashboard_runs WHERE status IN ('running', 'spawning')"
|
||||
);
|
||||
const abandonStmt = db.prepare(`
|
||||
const endStmt = db.prepare(`
|
||||
UPDATE dashboard_runs
|
||||
SET status = 'abandoned',
|
||||
SET status = @status,
|
||||
ended_at = COALESCE(ended_at, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
WHERE id = ? AND status IN ('running', 'spawning')
|
||||
WHERE id = @id AND status IN ('running', 'spawning')
|
||||
`);
|
||||
// Claude says why it ended: `/exit`, Ctrl+C/Ctrl+D and `/logout` are the
|
||||
// user's own; a signal (tmux killed) reports `other` and a power cut nothing.
|
||||
const userExitStmt = db.prepare(`
|
||||
SELECT 1 FROM events
|
||||
WHERE session_id = ? AND event_type = 'SessionEnd'
|
||||
AND json_extract(data, '$.reason') IN ('prompt_input_exit', 'logout')
|
||||
LIMIT 1
|
||||
`);
|
||||
|
||||
// A shell has no session, so its row only tracks the open tab: once closed it
|
||||
@@ -272,20 +282,32 @@ const pruneShellsStmt = db.prepare(`
|
||||
`);
|
||||
|
||||
/**
|
||||
* Flags `abandoned` every row still marked running/spawning whose pane is
|
||||
* gone — the pane's process quit (Ctrl+C, `exit`), or the machine rebooted.
|
||||
* A pane is a tmux session, which outlives a server restart, so liveness is
|
||||
* asked of `isAlive(id)` (tmux), never assumed from the restart. Run at boot
|
||||
* and on the server's run-heal beat, which also drops every closed Terminal
|
||||
* tab's row.
|
||||
* Ends every row still marked running/spawning whose pane is gone. A pane is
|
||||
* a tmux session, which outlives a server restart, so liveness is asked of
|
||||
* `isAlive(id)` (tmux), never assumed from the restart. Run at boot and on
|
||||
* the server's run-heal beat, which also drops every closed Terminal tab's row.
|
||||
*
|
||||
* A pane AgentHub closed itself (Stop, close tab, Quit) is already `killed`.
|
||||
* Of the rest, an agent session the user did not exit is `interrupted` — a
|
||||
* reboot, a killed tmux, a crash — and offered for resume
|
||||
* (`listInterrupted`); everything else is `abandoned`. Only Claude reports
|
||||
* how it ended, so any other tool's vanished pane counts as interrupted.
|
||||
*
|
||||
* Returns the number of rows updated.
|
||||
*/
|
||||
function reconcileOrphans(isAlive = () => false) {
|
||||
try {
|
||||
let changes = 0;
|
||||
for (const { id } of runningStmt.all()) {
|
||||
if (!isAlive(id)) changes += abandonStmt.run(id).changes;
|
||||
for (const row of runningStmt.all()) {
|
||||
if (isAlive(row.id)) continue;
|
||||
const interrupted =
|
||||
row.tool !== "shell" &&
|
||||
!!row.session_id &&
|
||||
!(row.tool === "claude" && userExitStmt.get(row.session_id));
|
||||
changes += endStmt.run({
|
||||
id: row.id,
|
||||
status: interrupted ? "interrupted" : "abandoned",
|
||||
}).changes;
|
||||
}
|
||||
pruneShellsStmt.run();
|
||||
return changes;
|
||||
@@ -294,6 +316,50 @@ function reconcileOrphans(isAlive = () => false) {
|
||||
}
|
||||
}
|
||||
|
||||
// The newest interrupted run of each session that nothing ran since — a
|
||||
// session resumed by any path drops out — of workspaces `@owner` owns (any
|
||||
// owner when null). A workspace removed since takes its rows with it.
|
||||
const interruptedStmt = db.prepare(`
|
||||
SELECT r.id, r.session_id, r.lane_id, r.tool, r.cwd, r.model, r.permission_mode, r.effort,
|
||||
r.prompt_preview, r.started_at, r.ended_at,
|
||||
l.title AS lane_title, l.cwd AS lane_cwd, s.name AS session_name
|
||||
FROM dashboard_runs r
|
||||
JOIN lanes l ON l.id = r.lane_id
|
||||
LEFT JOIN sessions s ON s.id = r.session_id
|
||||
WHERE r.status = 'interrupted' AND r.session_id IS NOT NULL
|
||||
AND (@owner IS NULL OR l.owner_id = @owner)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM dashboard_runs n
|
||||
WHERE n.session_id = r.session_id AND n.id != r.id
|
||||
AND (n.started_at >= r.started_at OR n.status IN ('running', 'spawning'))
|
||||
)
|
||||
ORDER BY r.ended_at DESC
|
||||
LIMIT 50
|
||||
`);
|
||||
const dismissStmt = db.prepare(`
|
||||
UPDATE dashboard_runs SET status = 'abandoned'
|
||||
WHERE status = 'interrupted' AND session_id = @sessionId
|
||||
AND lane_id IN (SELECT id FROM lanes WHERE @owner IS NULL OR owner_id = @owner)
|
||||
`);
|
||||
|
||||
/** Sessions whose pane went away without the user ending them, newest first. */
|
||||
function listInterrupted(ownerId = null) {
|
||||
try {
|
||||
return interruptedStmt.all({ owner: ownerId });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** The user answered: these sessions are no longer offered for resume. */
|
||||
function dismissInterrupted(sessionIds, ownerId = null) {
|
||||
let changes = 0;
|
||||
for (const sessionId of sessionIds) {
|
||||
changes += dismissStmt.run({ sessionId, owner: ownerId }).changes;
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
recordRun,
|
||||
patchRun,
|
||||
@@ -301,6 +367,8 @@ module.exports = {
|
||||
getRun,
|
||||
forgetShellRun,
|
||||
reconcileOrphans,
|
||||
listInterrupted,
|
||||
dismissInterrupted,
|
||||
proxyForSession,
|
||||
laneForSession,
|
||||
claimToolSessions,
|
||||
|
||||
@@ -65,6 +65,14 @@ function attachBinary(platform = process.platform) {
|
||||
}
|
||||
}
|
||||
|
||||
// psmux (Windows) holds a bracketed paste ~350 ms before the pane sees it,
|
||||
// and input written meanwhile lands INSIDE it, before ESC[201~ (psmux#766):
|
||||
// the Chat view's Enter, 100 ms after its paste, became a pasted newline and
|
||||
// the prompt sat in the composer as "[Pasted text #1]". Input that follows a
|
||||
// paste therefore waits until this long after it; 500 ms already arrived after
|
||||
// the paste in that issue's measurements.
|
||||
const PASTE_HOLD_MS = 700;
|
||||
|
||||
// runId -> { driver, viewers: Set<{ ws, pty, cols, rows }> }
|
||||
const groups = new Map();
|
||||
|
||||
@@ -91,7 +99,7 @@ function drive(group, v) {
|
||||
* Attach `ws` to the tmux session `runId`. Spawns one PTY-backed
|
||||
* `tmux attach-session -t <runId>` per call.
|
||||
*/
|
||||
function attach(ws, runId, { cols, rows }) {
|
||||
function attach(ws, runId, { cols, rows, platform = process.platform }) {
|
||||
validateRunId(runId);
|
||||
// Retroactively covers sessions started before mouse mode was wired into
|
||||
// newSession (or before a server restart picked that change up) — see
|
||||
@@ -117,6 +125,12 @@ function attach(ws, runId, { cols, rows }) {
|
||||
name: "xterm-256color",
|
||||
cols: lead ? lead.cols : cols || 80,
|
||||
rows: lead ? lead.rows : rows || 24,
|
||||
// Windows' inbox ConPTY re-renders psmux's output instead of passing it
|
||||
// through, and wherever its glyph widths disagree with xterm.js's (⏺, ✻,
|
||||
// Vietnamese) it leaves stray cells: a torn left edge, bars mid-screen.
|
||||
// The conpty.dll + OpenConsole.exe in @lydell/node-pty-win32-* is the
|
||||
// newer one VS Code uses for the same reason. Ignored elsewhere.
|
||||
...(platform === "win32" && { useConptyDll: true }),
|
||||
});
|
||||
const me = { ws, pty, cols: cols || 80, rows: rows || 24 };
|
||||
group.viewers.add(me);
|
||||
@@ -146,6 +160,29 @@ function attach(ws, runId, { cols, rows }) {
|
||||
}
|
||||
});
|
||||
|
||||
// Every keystroke goes through here, in order; see PASTE_HOLD_MS.
|
||||
const holdsPaste = platform === "win32";
|
||||
let holdUntil = 0;
|
||||
let held = [];
|
||||
const flush = () => {
|
||||
const q = held;
|
||||
held = [];
|
||||
try {
|
||||
q.forEach(write);
|
||||
} catch {
|
||||
/* the attach exited while its input was held — nothing to write to */
|
||||
}
|
||||
};
|
||||
function write(text) {
|
||||
const wait = holdUntil - Date.now();
|
||||
if (held.length || wait > 0) {
|
||||
if (held.push(text) === 1) setTimeout(flush, Math.max(0, wait));
|
||||
return;
|
||||
}
|
||||
pty.write(text);
|
||||
if (holdsPaste && text.includes("\x1b[201~")) holdUntil = Date.now() + PASTE_HOLD_MS;
|
||||
}
|
||||
|
||||
pty.onExit(({ exitCode }) => {
|
||||
try {
|
||||
ws.send(JSON.stringify({ type: "exit", code: exitCode }), { binary: false });
|
||||
@@ -167,7 +204,7 @@ function attach(ws, runId, { cols, rows }) {
|
||||
const binary = typeof isBinary === "boolean" ? isBinary : !!(isBinary && isBinary.binary);
|
||||
const text = data.toString("utf8");
|
||||
if (binary) {
|
||||
pty.write(text);
|
||||
write(text);
|
||||
return;
|
||||
}
|
||||
// The browser's WebSocket API sends a JS string as a text frame, and
|
||||
@@ -181,7 +218,7 @@ function attach(ws, runId, { cols, rows }) {
|
||||
try {
|
||||
msg = JSON.parse(text);
|
||||
} catch {
|
||||
pty.write(text);
|
||||
write(text);
|
||||
return;
|
||||
}
|
||||
if (msg && msg.type === "resize" && Number.isFinite(msg.cols) && Number.isFinite(msg.rows)) {
|
||||
@@ -193,7 +230,7 @@ function attach(ws, runId, { cols, rows }) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
pty.write(text);
|
||||
write(text);
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
|
||||
@@ -177,6 +177,7 @@ function buildClaudeArgv({
|
||||
addDirs = [],
|
||||
systemPromptFile = null,
|
||||
proxyArgv = [],
|
||||
platform = process.platform,
|
||||
}) {
|
||||
const argv = ["claude"];
|
||||
// `--add-dir` is VARIADIC (`<directories...>`): it swallows every following
|
||||
@@ -184,6 +185,15 @@ function buildClaudeArgv({
|
||||
// always ends it — after the prompt it would eat the prompt as a directory.
|
||||
if (addDirs.length) argv.push("--add-dir", ...addDirs);
|
||||
argv.push("--permission-mode", permissionMode || "auto");
|
||||
// Inside a pane Claude Code sees $TMUX and opens agent-team teammates with
|
||||
// `split-window -P -F '#{pane_id}'`. psmux ignores -F, so the id it reads
|
||||
// back is wrong and the follow-up respawn-pane/set-option land on the
|
||||
// leader's own pane — the session is replaced by a bare cmd.exe. psmux also
|
||||
// answers a target that does not exist (`list-panes -t <s>:claude-swarm`)
|
||||
// with the CURRENT pane instead of an error, so any teammate path can hit
|
||||
// the leader: Claude 2.1.296 dies on a named Agent call (older builds only
|
||||
// failed with "Could not determine pane count for swarm window").
|
||||
if (platform === "win32") argv.push("--teammate-mode", "in-process");
|
||||
// The session's AI Proxy: `--settings=<file>` (proxy-apply.js).
|
||||
argv.push(...proxyArgv);
|
||||
// Claude Code makes the worktree itself (`.claude/worktrees/<name>`, branch
|
||||
@@ -767,4 +777,5 @@ module.exports = {
|
||||
MAX_PANE_SLOT,
|
||||
SHELL_COMMANDS,
|
||||
paneArgv,
|
||||
buildClaudeArgv,
|
||||
};
|
||||
|
||||
@@ -267,6 +267,8 @@ function broadcastAudience(type, data) {
|
||||
case "lane_runtime":
|
||||
return { owners: laneOwners(d.laneId) };
|
||||
case "update_status":
|
||||
// No payload: each client refetches its own `GET /api/run/interrupted`.
|
||||
case "runs_interrupted":
|
||||
return null;
|
||||
// A member's prompt box refetches its command list on these, but the
|
||||
// payload names the host's profiles and files: members get the type only.
|
||||
|
||||
@@ -39,6 +39,7 @@ const PREF_KEYS = [
|
||||
"agenthub.permissionMode",
|
||||
"agenthub.tour",
|
||||
"agenthub.chatUi",
|
||||
"agenthub.workspace.allTabs",
|
||||
];
|
||||
const MAX_VALUE = 8 * 1024;
|
||||
|
||||
|
||||
+42
-4
@@ -226,6 +226,29 @@ router.get("/history", (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Sessions whose pane went away without the user ending them (a reboot, a
|
||||
* killed tmux, a crash), for the "resume interrupted sessions" prompt. Only
|
||||
* the caller's own workspaces in server mode: an admin is not offered a
|
||||
* developer's sessions.
|
||||
*/
|
||||
router.get("/interrupted", (req, res) => {
|
||||
const dr = require("../lib/dashboard-runs");
|
||||
res.json({ items: dr.listInterrupted(scope.ownerFor(req)) });
|
||||
});
|
||||
|
||||
/** The user answered the prompt: stop offering these sessions. Resumes nothing. */
|
||||
router.post("/interrupted/dismiss", (req, res) => {
|
||||
const ids = req.body?.sessionIds;
|
||||
if (!Array.isArray(ids) || ids.length > 100 || !ids.every((id) => typeof id === "string")) {
|
||||
return res.status(400).json({
|
||||
error: { code: "EBADFIELD", message: "sessionIds must be an array of session ids" },
|
||||
});
|
||||
}
|
||||
const dr = require("../lib/dashboard-runs");
|
||||
res.json({ dismissed: dr.dismissInterrupted(ids, scope.ownerFor(req)) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Forget one closed Terminal tab (`tool = 'shell'`) from the history at once,
|
||||
* ahead of the run-heal beat. A live pane is refused; another tool's row is a 404.
|
||||
@@ -475,9 +498,10 @@ 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`.
|
||||
// A dropped image, shown back in the session's conversation, or a dropped text
|
||||
// file (a long paste, #68), previewed in its Uploads/Files read list. Only a name
|
||||
// drop-image/drop-file made (random hex prefix, no separator) and only those
|
||||
// types; raster images, text as text/plain, under a sandbox CSP, like `/git/raw`.
|
||||
const DROP_IMAGE_TYPES = {
|
||||
png: "image/png",
|
||||
jpg: "image/jpeg",
|
||||
@@ -485,10 +509,24 @@ const DROP_IMAGE_TYPES = {
|
||||
gif: "image/gif",
|
||||
webp: "image/webp",
|
||||
};
|
||||
const DROP_TEXT_TYPES = new Set([
|
||||
"txt",
|
||||
"md",
|
||||
"markdown",
|
||||
"csv",
|
||||
"tsv",
|
||||
"log",
|
||||
"json",
|
||||
"xml",
|
||||
"yaml",
|
||||
"yml",
|
||||
]);
|
||||
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()];
|
||||
const ext = m && m[1].toLowerCase();
|
||||
const type =
|
||||
ext && (DROP_IMAGE_TYPES[ext] || (DROP_TEXT_TYPES.has(ext) && "text/plain; charset=utf-8"));
|
||||
// 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.
|
||||
|
||||
@@ -11,6 +11,7 @@ const { broadcast } = require("../websocket");
|
||||
const { calculateCost, attachAgentCosts } = require("./pricing");
|
||||
const { parseSources, sourceColumnClause } = require("../lib/source-filter");
|
||||
const { memberId, sessionWhere, canSeeSession } = require("../lib/scope");
|
||||
const { isServerMode } = require("../lib/auth");
|
||||
const {
|
||||
projectsDirFor,
|
||||
sessionProjectsDirs,
|
||||
@@ -475,6 +476,61 @@ router.get("/:id/outline", (req, res) => {
|
||||
res.json(sessionOutline(req.params.id));
|
||||
});
|
||||
|
||||
// An image the session's own Read tool returned (`?path=`, exact), for the Chat
|
||||
// pane's Files read preview when it lies outside the workspace (a screenshot
|
||||
// under ~/.cache, /tmp). The path is authorized only by that event, so: raster
|
||||
// types only, under a sandbox CSP with nosniff; never for a pushed session
|
||||
// (another machine's paths), and not in server mode, where a member's hook
|
||||
// could name a host-only file that this process would then read as the host.
|
||||
const READ_IMAGE_TYPES = {
|
||||
png: "image/png",
|
||||
jpg: "image/jpeg",
|
||||
jpeg: "image/jpeg",
|
||||
gif: "image/gif",
|
||||
webp: "image/webp",
|
||||
};
|
||||
const READ_IMAGE_MAX = 20 * 1024 * 1024;
|
||||
const sessionReadFile = db.prepare(
|
||||
`SELECT 1 FROM events
|
||||
WHERE session_id = ? AND event_type = 'PostToolUse' AND tool_name = 'Read'
|
||||
AND json_extract(data, '$.tool_input.file_path') = ?
|
||||
LIMIT 1`
|
||||
);
|
||||
router.get("/:id/image", async (req, res) => {
|
||||
const fail = (status, code, message) => res.status(status).json({ error: { code, message } });
|
||||
const session = stmts.getSession.get(req.params.id);
|
||||
if (!session) return fail(404, "NOT_FOUND", "Session not found");
|
||||
if (isServerMode() || String(session.source || "").startsWith("push:")) {
|
||||
return fail(403, "EUNSUPPORTED", "not available for this session");
|
||||
}
|
||||
const file = typeof req.query.path === "string" ? req.query.path : "";
|
||||
const type = READ_IMAGE_TYPES[path.extname(file).slice(1).toLowerCase()];
|
||||
if (!path.isAbsolute(file) || !type) return fail(400, "ENOTIMAGE", "not an image path");
|
||||
if (!sessionReadFile.get(session.id, file)) {
|
||||
return fail(404, "ENOTFOUND", "the session never read that image");
|
||||
}
|
||||
let fh;
|
||||
try {
|
||||
// NONBLOCK: a FIFO named like an image must not hang the event loop.
|
||||
fh = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
|
||||
const st = await fh.stat();
|
||||
if (!st.isFile()) return fail(404, "ENOTFOUND", "no such image");
|
||||
if (st.size > READ_IMAGE_MAX) return fail(400, "ETOOBIG", "image is larger than 20 MB");
|
||||
const buf = await fh.readFile();
|
||||
res.set({
|
||||
"Content-Type": type,
|
||||
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
res.send(buf);
|
||||
} catch {
|
||||
if (!res.headersSent) fail(404, "ENOTFOUND", "no such image");
|
||||
} finally {
|
||||
await fh?.close();
|
||||
}
|
||||
});
|
||||
|
||||
/** The `/:id/stats` body — also frozen into a session snapshot. */
|
||||
function sessionStats(sessionId) {
|
||||
const totalEvents = stmts.sessionEventCount.get(sessionId)?.count ?? 0;
|
||||
@@ -913,7 +969,7 @@ router.get("/:id/transcript", async (req, res) => {
|
||||
type: "user",
|
||||
sender: "user", // local slash-command I/O is the human's own action
|
||||
timestamp: entry.timestamp || null,
|
||||
content: [{ type: "text", text: truncate(sysText, 10240) }],
|
||||
content: [{ type: "text", text: truncate(sysText, TEXT_MAX) }],
|
||||
line: num,
|
||||
};
|
||||
}
|
||||
@@ -942,7 +998,7 @@ router.get("/:id/transcript", async (req, res) => {
|
||||
type: "user",
|
||||
sender: isSystem ? "system" : "user",
|
||||
timestamp: entry.timestamp || att.timestamp || null,
|
||||
content: [{ type: "text", text: truncate(prompt, 10240) }],
|
||||
content: [{ type: "text", text: truncate(prompt, TEXT_MAX) }],
|
||||
line: num,
|
||||
};
|
||||
}
|
||||
@@ -953,11 +1009,11 @@ router.get("/:id/transcript", async (req, res) => {
|
||||
if (entry.type === "user") {
|
||||
const msgContent = entry.message?.content;
|
||||
if (typeof msgContent === "string") {
|
||||
content.push({ type: "text", text: truncate(msgContent, 10240) });
|
||||
content.push({ type: "text", text: truncate(msgContent, TEXT_MAX) });
|
||||
} else if (Array.isArray(msgContent)) {
|
||||
for (const block of msgContent) {
|
||||
if (block.type === "text" && block.text) {
|
||||
content.push({ type: "text", text: truncate(block.text, 10240) });
|
||||
content.push({ type: "text", text: truncate(block.text, TEXT_MAX) });
|
||||
} else if (block.type === "tool_result") {
|
||||
// A line carries one tool result; an edit's +/- counts ride on it.
|
||||
const diff = patchCounts(entry.toolUseResult);
|
||||
@@ -983,7 +1039,7 @@ router.get("/:id/transcript", async (req, res) => {
|
||||
if (Array.isArray(msgContent)) {
|
||||
for (const block of msgContent) {
|
||||
if (block.type === "text" && block.text) {
|
||||
content.push({ type: "text", text: truncate(block.text, 10240) });
|
||||
content.push({ type: "text", text: truncate(block.text, TEXT_MAX) });
|
||||
} else if (block.type === "thinking" && block.thinking) {
|
||||
content.push({ type: "thinking", text: truncate(block.thinking, 10240) });
|
||||
} else if (block.type === "tool_use") {
|
||||
@@ -1190,7 +1246,7 @@ function codexMessage(entry, num) {
|
||||
const content = (p.content || [])
|
||||
.map((c) => (c && typeof c.text === "string" ? c.text : ""))
|
||||
.filter((t) => t.trim() && !(p.role === "user" && CODEX_INJECTED.test(t.trimStart())))
|
||||
.map((t) => ({ type: "text", text: truncate(t, 10240) }));
|
||||
.map((t) => ({ type: "text", text: truncate(t, TEXT_MAX) }));
|
||||
return content.length ? msg(p.role, p.role, content) : null;
|
||||
}
|
||||
case "reasoning": {
|
||||
@@ -1230,7 +1286,9 @@ function codexMessage(entry, num) {
|
||||
}
|
||||
case "agent_message": {
|
||||
const t = codexText(p.content);
|
||||
return t.trim() ? msg("user", "system", [{ type: "text", text: truncate(t, 10240) }]) : null;
|
||||
return t.trim()
|
||||
? msg("user", "system", [{ type: "text", text: truncate(t, TEXT_MAX) }])
|
||||
: null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
@@ -1260,6 +1318,12 @@ function patchCounts(r) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// A conversation turn — a prompt, an answer — is shown whole: it is bounded by
|
||||
// the model's output and what the user typed. Only tool payloads and thinking
|
||||
// (the parts that can run to megabytes) keep the 10 KB cap. This one guards
|
||||
// against a pathological line, not a long answer.
|
||||
const TEXT_MAX = 1024 * 1024;
|
||||
|
||||
function truncate(str, maxLen) {
|
||||
if (!str || str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen) + "[truncated]";
|
||||
|
||||
Reference in New Issue
Block a user