chat: pin background tasks above the input and let you look inside them
Background tasks already had a row in the transcript, but a row scrolls away — and a
task started ten minutes ago is precisely the one you want to keep an eye on. The same
`role: 'task'` rows now also drive a tray docked above the chat input: a chip per task,
running ones pulsing, finished ones dismissable.
Clicking a chip opens what the task is actually doing right now. Nothing about that
crosses the wire between `task:started` and the notification, so it is read from the
file Claude Code streams the task into:
$TMPDIR/claude-<uid>/<project-slug>/<session-uuid>/tasks/<task-id>.output
For a backgrounded shell that file IS the log; for an agent it is a symlink to the
subagent's own transcript, which is ordinary session JSONL and so parses with the
reader we already had. Both kinds are therefore reachable from one directory.
Resolution is by task id alone, deliberately: the client learns a task id from
`task:started` and nothing else — officer's per-connection session key is not Claude's
session uuid, and the uuid only arrives with the turn result, long after the tray needs
to show the task. A task that has not written anything yet answers 200 `{kind:'pending'}`
rather than 404, because that is the ordinary first second of a task's life.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ import {
|
||||
loadClaudeSessionById,
|
||||
deleteClaudeSession,
|
||||
renameClaudeSession,
|
||||
loadBackgroundTask,
|
||||
} from './claude-sessions';
|
||||
import {
|
||||
listOpenCodeSessions,
|
||||
@@ -99,6 +100,18 @@ chatRouter.patch('/sessions/:id/title', async (ctx) => {
|
||||
return ctx.json({ ok: true });
|
||||
});
|
||||
|
||||
// GET /chat/tasks/:id — what a background task is doing right now: a subagent's own trace, or the tail of
|
||||
// a backgrounded shell's log. Polled by the tray above the chat input while the task is running.
|
||||
//
|
||||
// A task that has not written anything yet answers 200 with `{ kind: 'pending' }`, not 404. The tray asks
|
||||
// the moment `task:started` arrives, which is routinely before the file exists, and a 404 there would be
|
||||
// an error state for the most ordinary thing that can happen.
|
||||
chatRouter.get('/tasks/:id', (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const detail = loadBackgroundTask(email, ctx.req.param('id'));
|
||||
return ctx.json(detail ?? { kind: 'pending' });
|
||||
});
|
||||
|
||||
// GET /chat/models — Claude tiers only (the runner is the `claude` CLI).
|
||||
chatRouter.get('/models', async (ctx: Context) => {
|
||||
try {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
openSync,
|
||||
readSync,
|
||||
closeSync,
|
||||
realpathSync,
|
||||
} from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { DATA_PATH } from '../../data-path';
|
||||
@@ -291,6 +292,107 @@ export function renameClaudeSession(email: string, cwd: string, sessionId: strin
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Background tasks ──
|
||||
// A background task (run_in_background, Monitor, a backgrounded subagent) reports nothing over the wire
|
||||
// between `task:started` and its notification — the only thing that knows what it is doing is the file
|
||||
// Claude Code streams it into:
|
||||
//
|
||||
// $TMPDIR/claude-<uid>/<project-slug>/<session-uuid>/tasks/<task-id>.output
|
||||
//
|
||||
// For a shell task that file IS the output. For an agent task it is a SYMLINK to the subagent's own
|
||||
// transcript under ~/.claude/projects/<slug>/<session>/subagents/agent-<task-id>.jsonl — which is the
|
||||
// same JSONL format as any other session, so the parser above reads it unchanged. Both kinds are
|
||||
// reachable from the one directory, which is why we look there first; the projects tree is the fallback
|
||||
// for when /tmp has been cleared out from under a still-referenced agent transcript.
|
||||
//
|
||||
// Resolution is by task id ALONE, deliberately. The client learns a task id from `task:started` and
|
||||
// nothing else — officer's per-connection session key is not Claude's session uuid, and the uuid only
|
||||
// arrives with the turn `result`, long after the tray needs to show the task.
|
||||
|
||||
/** Task ids come from Claude, but they reach us through a URL — never let one address a parent. */
|
||||
const TASK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
||||
|
||||
/** How much of a shell task's log to return. It is a tail: the end is the part that is still moving. */
|
||||
const LOG_TAIL_BYTES = 64 * 1024;
|
||||
|
||||
/** Per tool result. A background agent's greps run to megabytes and the tray shows a preview, not a file. */
|
||||
const OUTPUT_CAP = 4000;
|
||||
|
||||
export type BackgroundTaskDetail =
|
||||
| { kind: 'agent'; messages: ClaudeChatMessage[] }
|
||||
| { kind: 'log'; text: string; truncated: boolean };
|
||||
|
||||
function findTaskOutput(email: string, taskId: string): string | null {
|
||||
const tmpRoot = process.env.TMPDIR ?? '/tmp';
|
||||
const candidates: [string, string][] = [
|
||||
[tmpRoot, `claude-*/*/*/tasks/${taskId}.output`],
|
||||
[claudeProjectsDir(email), `*/*/subagents/agent-${taskId}.jsonl`],
|
||||
];
|
||||
for (const [root, pattern] of candidates) {
|
||||
try {
|
||||
for (const rel of new Bun.Glob(pattern).scanSync({ cwd: root, followSymlinks: false, onlyFiles: false })) {
|
||||
return join(root, rel);
|
||||
}
|
||||
} catch {
|
||||
/* root doesn't exist — try the next one */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The tail of a file, as text, without reading the whole thing. */
|
||||
function tailFile(filePath: string, bytes: number): { text: string; truncated: boolean } {
|
||||
const size = statSync(filePath).size;
|
||||
const start = Math.max(0, size - bytes);
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
fd = openSync(filePath, 'r');
|
||||
const buf = Buffer.alloc(size - start);
|
||||
const n = readSync(fd, buf, 0, buf.length, start);
|
||||
let text = buf.toString('utf-8', 0, n);
|
||||
// A byte offset lands mid-line (and possibly mid-codepoint); drop the partial head.
|
||||
if (start > 0) text = text.slice(text.indexOf('\n') + 1);
|
||||
return { text, truncated: start > 0 };
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a background task is doing right now. Returns null when nothing has been written yet — which is
|
||||
* the normal state for the first second or two of a task's life, not an error.
|
||||
*/
|
||||
export function loadBackgroundTask(email: string, taskId: string): BackgroundTaskDetail | null {
|
||||
if (!TASK_ID_RE.test(taskId)) return null;
|
||||
const found = findTaskOutput(email, taskId);
|
||||
if (!found) return null;
|
||||
|
||||
let target = found;
|
||||
try {
|
||||
target = realpathSync(found);
|
||||
} catch {
|
||||
return null; // a dangling symlink — the task registered before its transcript existed
|
||||
}
|
||||
|
||||
if (target.endsWith('.jsonl')) {
|
||||
const detail = parseClaudeTranscript(target, taskId);
|
||||
if (!detail) return null;
|
||||
const messages = detail.messages.map((m) =>
|
||||
m.role === 'tool' && m.output && m.output.length > OUTPUT_CAP
|
||||
? { ...m, output: `${m.output.slice(0, OUTPUT_CAP)}\n… (truncated)` }
|
||||
: m,
|
||||
);
|
||||
return { kind: 'agent', messages };
|
||||
}
|
||||
|
||||
try {
|
||||
const { text, truncated } = tailFile(target, LOG_TAIL_BYTES);
|
||||
return { kind: 'log', text, truncated };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Working directories (pwds) ──
|
||||
// Every dir you've run Claude in shows up as a project group under ~/.claude/projects. We read the
|
||||
// real `cwd` back from each group's transcripts so the UI can offer "jump to any project's sessions".
|
||||
|
||||
Reference in New Issue
Block a user