Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(agents): async subagent cards flipped to done instantly with no output

enes86bfd1b8cbe0
diff --git a/src/main/context-tail.test.ts b/src/main/context-tail.test.ts
index 98fd44068..7c0c11f6d 100644
--- a/src/main/context-tail.test.ts
+++ b/src/main/context-tail.test.ts
@@ -1,5 +1,8 @@
-import { describe, expect, it } from 'vitest'
-import { parseLatestUsage } from './context-tail'
+import { describe, expect, it, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { createContextTail, parseLatestUsage, parseTaskNotifications } from './context-tail'
describe('parseLatestUsage', () => {
it('returns the LAST assistant usage in the text (sum of input + cache tokens)', () => {
@@ -15,3 +18,64 @@ describe('parseLatestUsage', () => {
expect(parseLatestUsage('')).toBeNull()
})
})
+
+// A queue-operation transcript line carrying a completed async subagent's notification,
+// shaped like the real ones Claude Code writes into the parent .jsonl.
+function notificationLine(toolUseId: string, result = 'agent findings'): string {
+ const content = [
+ '<task-notification>',
+ '<task-id>a3ff80d</task-id>',
+ `<tool-use-id>${toolUseId}</tool-use-id>`,
+ '<output-file>/tmp/tasks/a3ff80d.output</output-file>',
+ '<status>completed</status>',
+ '<summary>Agent "Explore" finished</summary>',
+ `<result>${result}</result>`,
+ '</task-notification>'
+ ].join('\n')
+ return JSON.stringify({ type: 'queue-operation', operation: 'enqueue', content })
+}
+
+describe('parseTaskNotifications', () => {
+ it('extracts toolUseId, status, summary and result from a queue-operation line', () => {
+ const [n] = parseTaskNotifications(notificationLine('tu1', 'found 3 files'))
+ expect(n).toMatchObject({
+ toolUseId: 'tu1',
+ status: 'completed',
+ summary: 'Agent "Explore" finished',
+ result: 'found 3 files'
+ })
+ })
+
+ it('ignores unrelated lines, attachment echoes of the notification, and garbled JSON', () => {
+ const text = [
+ 'garbled',
+ JSON.stringify({ type: 'assistant', message: {} }),
+ // the same notification is echoed later as an attachment line — must not double-fire
+ JSON.stringify({ type: 'attachment', attachment: { type: 'queued_command', prompt: '<task-notification><tool-use-id>tu1</tool-use-id></task-notification>' } }),
+ notificationLine('tu2')
+ ].join('\n')
+ const ns = parseTaskNotifications(text)
+ expect(ns).toHaveLength(1)
+ expect(ns[0].toolUseId).toBe('tu2')
+ })
+})
+
+describe('createContextTail — task notifications', () => {
+ it('fires onTaskNotification even when the line lands torn across two reads', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-'))
+ const file = path.join(dir, 'sess.jsonl')
+ const line = notificationLine('tu-torn')
+ fs.writeFileSync(file, line.slice(0, 40)) // first half, no newline
+ const onTaskNotification = vi.fn()
+ const win = { isDestroyed: () => false, webContents: { send: vi.fn() } } as never
+ const tail = createContextTail(win, { onTaskNotification })
+ tail.track('s1', file)
+ await new Promise((r) => setTimeout(r, 1200)) // ≥1 poll sees the partial line
+ fs.appendFileSync(file, line.slice(40) + '\n')
+ await new Promise((r) => setTimeout(r, 1300)) // next poll completes it
+ expect(onTaskNotification).toHaveBeenCalledTimes(1)
+ expect(onTaskNotification.mock.calls[0][0]).toBe('s1')
+ expect(onTaskNotification.mock.calls[0][1]).toMatchObject({ toolUseId: 'tu-torn' })
+ tail.untrack('s1')
+ }, 8000)
+})
diff --git a/src/main/context-tail.ts b/src/main/context-tail.ts
index ae4db3158..108e48bde 100644
--- a/src/main/context-tail.ts
+++ b/src/main/context-tail.ts
@@ -7,6 +7,7 @@ import { type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
import type { ContextWindowUsage } from '../shared/types'
import { cachedWindowFor, resolveModelWindow } from './model-window'
+import { splitCompleteLines } from './subagent-tail'
const POLL_MS = 1000
// Cap the initial read: a resumed Claude transcript can be many MB, and reading the whole file
@@ -41,6 +42,57 @@ export function parseLatestUsage(text: string): { used: number; model: string |
return found ? { used: usedTokens, model } : null
}
+/**
+ * A completed async subagent, announced back to the parent session as a queued
+ * `<task-notification>` prompt (a `queue-operation` transcript line). Carries the spawning
+ * tool_use_id, so it's the end signal the async launch's PostToolUse never was.
+ */
+export interface TaskNotification {
+ toolUseId: string
+ status?: string
+ summary?: string
+ result?: string
+}
+
+const tag = (content: string, name: string): string | undefined => {
+ const m = content.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`))
+ return m ? m[1].trim() : undefined
+}
+
+/** Scan transcript lines for queued <task-notification>s. Pure. */
+export function parseTaskNotifications(text: string): TaskNotification[] {
+ const out: TaskNotification[] = []
+ for (const line of text.split('\n')) {
+ const s = line.trim()
+ // Cheap pre-filter; the attachment echo of the same notification is skipped by the
+ // type check below so each completion fires exactly once.
+ if (!s || !s.includes('task-notification') || !s.includes('queue-operation')) continue
+ let o: { type?: string; content?: unknown }
+ try {
+ o = JSON.parse(s)
+ } catch {
+ continue
+ }
+ if (o.type !== 'queue-operation' || typeof o.content !== 'string') continue
+ if (!o.content.includes('<task-notification>')) continue
+ const toolUseId = tag(o.content, 'tool-use-id')
+ if (!toolUseId) continue
+ out.push({
+ toolUseId,
+ status: tag(o.content, 'status'),
+ summary: tag(o.content, 'summary'),
+ // <result> holds the agent's full final text — match greedily to its LAST closing tag.
+ result: o.content.match(/<result>([\s\S]*)<\/result>/)?.[1]?.trim()
+ })
+ }
+ return out
+}
+
+export interface ContextTailOptions {
+ /** Fired when a tracked session's transcript announces a completed async subagent. */
+ onTaskNotification?: (sessionId: string, n: TaskNotification) => void
+}
+
interface Tracked {
path: string
offset: number
@@ -53,6 +105,12 @@ interface Tracked {
lastWindow: number
/** An async read is in flight — the next tick skips this session instead of double-reading. */
reading: boolean
+ /**
+ * Bytes past the last newline of the previous read — a line caught mid-write, held back and
+ * prepended to the next read (see subagent-tail.ts). Without it a torn <task-notification>
+ * line would be lost and its subagent card stuck on working forever. Reset on offset jumps.
+ */
+ carry: Buffer | null
}
export interface ContextTail {
@@ -62,7 +120,7 @@ export interface ContextTail {
pathFor(sessionId: string | undefined): string | undefined
}
-export function createContextTail(win: BrowserWindow): ContextTail {
+export function createContextTail(win: BrowserWindow, opts?: ContextTailOptions): ContextTail {
const sessions = new Map<string, Tracked>()
let timer: ReturnType<typeof setInterval> | null = null
@@ -95,20 +153,21 @@ export function createContextTail(win: BrowserWindow): ContextTail {
// file not created yet / unreadable — skip the byte read, still reconcile below
}
if (size >= 0) {
+ const before = t.offset
if (size < t.offset) t.offset = 0 // truncated/rotated → re-read from start
// First read of a large transcript: skip to the last INITIAL_READ_CAP bytes.
if (t.offset === 0 && size > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAP
// Cap deltas too: a huge append burst (resume/compact rewriting MBs between ticks)
// shouldn't allocate it all — only the LATEST usage matters, so jump to the tail.
if (size - t.offset > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAP
+ if (t.offset !== before) t.carry = null // offset jumped — the held bytes don't precede it
if (size > t.offset) {
- let chunk = ''
+ let buf: Buffer
try {
const fd = await fs.promises.open(t.path, 'r')
try {
- const buf = Buffer.alloc(size - t.offset)
+ buf = Buffer.alloc(size - t.offset)
await fd.read(buf, 0, buf.length, t.offset)
- chunk = buf.toString('utf-8')
t.offset = size
} finally {
await fd.close()
@@ -116,11 +175,21 @@ export function createContextTail(win: BrowserWindow): ContextTail {
} catch {
return
}
- const latest = parseLatestUsage(chunk)
+ // Usage parses the whole read (carry included) — it tolerates torn lines and the
+ // latest value wins, so it must not wait for a newline. Notifications scan
+ // COMPLETE lines only, with the torn tail carried into the next read, so a torn
+ // <task-notification> is completed later instead of being lost.
+ const combined = t.carry?.length ? Buffer.concat([t.carry, buf]) : buf
+ const { text: complete, carry } = splitCompleteLines(combined)
+ t.carry = carry
+ const latest = parseLatestUsage(combined.toString('utf-8'))
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
}
+ if (opts?.onTaskNotification) {
+ for (const n of parseTaskNotifications(complete)) opts.onTaskNotification(sessionId, n)
+ }
}
}
@@ -161,6 +230,7 @@ export function createContextTail(win: BrowserWindow): ContextTail {
if (existing.path !== transcriptPath) {
existing.path = transcriptPath
existing.offset = 0
+ existing.carry = null
}
return
}
@@ -173,7 +243,8 @@ export function createContextTail(win: BrowserWindow): ContextTail {
lastUsed: 0,
lastModel: null,
lastWindow: 0,
- reading: false
+ reading: false,
+ carry: null
}
sessions.set(sessionId, t)
void read(sessionId, t) // immediate first value (resumed sessions already have content)
diff --git a/src/main/index.ts b/src/main/index.ts
index 899b93bdd..eac3f385f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,7 +16,8 @@ import { hookServer } from './agents/hook-server'
import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'
import { installManagedAgentHooks } from './agents/hooks'
import { createSubagentTail } from './subagent-tail'
-import { createContextTail } from './context-tail'
+import { createContextTail, type TaskNotification } from './context-tail'
+import { isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
import {
readTranscriptLines,
readChatMessages,
@@ -368,7 +369,27 @@ app.whenReady().then(async () => {
// A raw listener drives the transcript-tailing features (context meter + subagent transcript),
// which need the raw transcript_path the NormalizedAgentEvent intentionally drops.
const subagentTail = createSubagentTail(win)
- const contextTail = createContextTail(win)
+ // Async subagents (Claude's default) end via a <task-notification> queued into the PARENT
+ // transcript — their PostToolUse is only a launch ack (see the raw listener below). The
+ // context tails already read that transcript, so they surface the notification here and we
+ // emit the synthetic subagent-end the hooks never send, then release the transcript tail.
+ const onTaskNotification = (sessionId: string, n: TaskNotification): void => {
+ let nodeId: string | undefined
+ for (const [nid, sid] of nodeContextSession) if (sid === sessionId) nodeId = nid
+ if (!nodeId) return
+ sendToMain(IPC.agentStatus, {
+ nodeId,
+ agentId: 'claude',
+ sessionId,
+ kind: 'subagent-end',
+ toolUseId: n.toolUseId,
+ result: n.result
+ } satisfies NormalizedAgentEvent)
+ subagentTail.finish(n.toolUseId)
+ remoteSubagentTail.untrack(n.toolUseId)
+ nodeSubagents.get(nodeId)?.delete(n.toolUseId)
+ }
+ const contextTail = createContextTail(win, { onTaskNotification })
// Remote (SSH-project) counterparts: a node whose pty runs on a remote host has its Claude
// transcript on that host, so its meter / subagent transcript / search must read over the
// project's ControlMaster. One RemoteFile bound to the SSH-project manager's own ssh runner
@@ -378,7 +399,7 @@ app.whenReady().then(async () => {
const remoteFile = new RemoteFile((args) =>
sshProjectManager ? sshProjectManager.sshRun(args) : Promise.resolve({ code: 1, stdout: '' })
)
- const remoteContextTail = createRemoteContextTail(win, remoteFile)
+ const remoteContextTail = createRemoteContextTail(win, remoteFile, { onTaskNotification })
const remoteSubagentTail = createRemoteSubagentTail(win, remoteFile)
// Remote transcript ref learned from the hook raw-listener, keyed by sessionId — lets the
// search/chat read handlers (which receive only sessionId + cwd) read remotely without a
@@ -514,7 +535,11 @@ app.whenReady().then(async () => {
transcript_path?: string
tool_name?: string
tool_use_id?: string
+ tool_response?: { status?: string; isAsync?: boolean }
}
+ // An async subagent's PostToolUse is only the launch ack — keep tailing its transcript;
+ // the real end (task-notification via the context tails) releases it.
+ const asyncLaunch = p.hook_event_name === 'PostToolUse' && isAsyncSubagentLaunch(p.tool_response)
// REMOTE node: route to the remote tails/search, jailing the path under the project's remote
// ~/.claude/projects. Diverges from the local path ONLY when the node has a live ssh remote.
const rt = nodeId ? ptyManager.sshRemoteForNode(nodeId) : undefined
@@ -553,13 +578,21 @@ app.whenReady().then(async () => {
set.add(toolUseId)
nodeSubagents.set(nodeId, set)
}
- } else if (p.hook_event_name === 'PostToolUse') {
+ } else if (p.hook_event_name === 'PostToolUse' && !asyncLaunch) {
// Only cancel an in-flight resolve; if it already settled, adding here would leak.
if (remoteSubagentResolving.has(toolUseId)) remoteSubagentCancel.add(toolUseId)
remoteSubagentTail.untrack(toolUseId)
if (nodeId) nodeSubagents.get(nodeId)?.delete(toolUseId)
}
}
+ // Session over → release any still-tracked async subagent tails for this node.
+ if (p.hook_event_name === 'SessionEnd' && nodeId) {
+ for (const toolUseId of nodeSubagents.get(nodeId) ?? []) {
+ if (remoteSubagentResolving.has(toolUseId)) remoteSubagentCancel.add(toolUseId)
+ remoteSubagentTail.untrack(toolUseId)
+ }
+ nodeSubagents.delete(nodeId)
+ }
return
}
const transcriptPath = safeTranscriptPath(p.transcript_path)
@@ -577,11 +610,17 @@ app.whenReady().then(async () => {
set.add(p.tool_use_id)
nodeSubagents.set(nodeId, set)
}
- } else if (p.hook_event_name === 'PostToolUse') {
+ } else if (p.hook_event_name === 'PostToolUse' && !asyncLaunch) {
subagentTail.finish(p.tool_use_id)
if (nodeId) nodeSubagents.get(nodeId)?.delete(p.tool_use_id)
}
}
+ // Session over → release any still-tracked async subagent tails for this node (their
+ // task-notifications will never arrive once the session is gone).
+ if (p.hook_event_name === 'SessionEnd' && nodeId) {
+ for (const toolUseId of nodeSubagents.get(nodeId) ?? []) subagentTail.finish(toolUseId)
+ nodeSubagents.delete(nodeId)
+ }
})
// Releasing tails on node close: pty:destroy fires when the user clicks × (persistKey = node
diff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.ts
index 864e79278..39a994a61 100644
--- a/src/main/remote-context-tail.test.ts
+++ b/src/main/remote-context-tail.test.ts
@@ -52,11 +52,39 @@ describe('createRemoteContextTail', () => {
tail.untrack('sess2')
})
+ it('fires onTaskNotification for a <task-notification> line in the remote transcript', async () => {
+ const { win } = fakeWin()
+ const notif = JSON.stringify({
+ type: 'queue-operation',
+ operation: 'enqueue',
+ content: '<task-notification>\n<tool-use-id>tu-remote</tool-use-id>\n<status>completed</status>\n<result>remote done</result>\n</task-notification>'
+ })
+ let served = false
+ const remoteFile = {
+ readTail: vi.fn(async () => line(10, 'claude-opus-4-8') + '\n'),
+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
+ if (served) return { text: '', newOffset: o }
+ served = true
+ return { text: notif + '\n', newOffset: o + Buffer.byteLength(notif + '\n') }
+ })
+ }
+ const onTaskNotification = vi.fn()
+ const tail = createRemoteContextTail(win, remoteFile as never, { onTaskNotification })
+ tail.track('sess4', ref)
+ await new Promise((r) => setTimeout(r, 1200)) // first read + one poll tick
+ expect(onTaskNotification).toHaveBeenCalledTimes(1)
+ expect(onTaskNotification.mock.calls[0][0]).toBe('sess4')
+ expect(onTaskNotification.mock.calls[0][1]).toMatchObject({ toolUseId: 'tu-remote', result: 'remote done' })
+ tail.untrack('sess4')
+ }, 5000)
+
it('only pushes again when the usage changes', async () => {
const { win, send } = fakeWin()
- let nextFrom = line(200, 'claude-opus-4-8')
+ // Realistic JSONL: records are newline-terminated (the tail carries a torn trailing
+ // line into the next read, so un-delimited records would garble on purpose).
+ let nextFrom = line(200, 'claude-opus-4-8') + '\n'
const remoteFile = {
- readTail: vi.fn(async () => line(100, 'claude-opus-4-8')),
+ readTail: vi.fn(async () => line(100, 'claude-opus-4-8') + '\n'),
readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
const text = nextFrom
nextFrom = ''
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index f4b1b0b30..258fa15ba 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -8,7 +8,8 @@ import { type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
import type { ContextWindowUsage } from '../shared/types'
import { cachedWindowFor, resolveModelWindow } from './model-window'
-import { parseLatestUsage } from './context-tail'
+import { parseLatestUsage, parseTaskNotifications, type ContextTailOptions } from './context-tail'
+import { splitCompleteLines } from './subagent-tail'
import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'
const POLL_MS = 1000
@@ -29,6 +30,8 @@ interface Tracked {
lastUsed: number
lastModel: string | null
lastWindow: number
+ /** Partial trailing line held back until the next read completes it (see subagent-tail.ts). */
+ carry: Buffer | null
}
export interface RemoteContextTail {
@@ -38,10 +41,33 @@ export interface RemoteContextTail {
pathFor(sessionId: string | undefined): string | undefined
}
-export function createRemoteContextTail(win: BrowserWindow, remoteFile: RemoteFile): RemoteContextTail {
+export function createRemoteContextTail(
+ win: BrowserWindow,
+ remoteFile: RemoteFile,
+ opts?: ContextTailOptions
+): RemoteContextTail {
const sessions = new Map<string, Tracked>()
let timer: ReturnType<typeof setInterval> | null = null
+ // Usage parses the whole read (carry included) — it tolerates torn lines and the latest
+ // value wins, so it must not wait for a newline. Notifications scan COMPLETE lines only,
+ // with the torn tail carried into the next read (see subagent-tail.ts), so a torn
+ // <task-notification> is completed later instead of being lost.
+ const scan = (sessionId: string, t: Tracked, read: string): void => {
+ const buf = Buffer.from(read)
+ const combined = t.carry?.length ? Buffer.concat([t.carry, buf]) : buf
+ const { text: complete, carry } = splitCompleteLines(combined)
+ t.carry = carry
+ const latest = parseLatestUsage(combined.toString('utf-8'))
+ if (latest) {
+ t.used = latest.used
+ t.model = latest.model ?? t.model
+ }
+ if (opts?.onTaskNotification) {
+ for (const n of parseTaskNotifications(complete)) opts.onTaskNotification(sessionId, n)
+ }
+ }
+
const push = (sessionId: string, t: Tracked): void => {
if (win.isDestroyed()) return
const usedPercent = Math.min(100, Math.max(0, (t.used / t.window) * 100))
@@ -67,21 +93,11 @@ export function createRemoteContextTail(win: BrowserWindow, remoteFile: RemoteFi
// remote size, so advance the offset by the bytes we actually received.
const text = await remoteFile.readTail(t.ref, INITIAL_READ_CAP)
t.offset = Buffer.byteLength(text)
- const latest = parseLatestUsage(text)
- if (latest) {
- t.used = latest.used
- t.model = latest.model ?? t.model
- }
+ scan(sessionId, t, text)
} else {
const { text, newOffset } = await remoteFile.readFrom(t.ref, t.offset)
t.offset = newOffset
- if (text) {
- const latest = parseLatestUsage(text)
- if (latest) {
- t.used = latest.used
- t.model = latest.model ?? t.model
- }
- }
+ if (text) scan(sessionId, t, text)
}
} finally {
t.reading = false
@@ -116,6 +132,7 @@ export function createRemoteContextTail(win: BrowserWindow, remoteFile: RemoteFi
if (existing.ref.path !== ref.path) {
existing.ref = ref
existing.offset = 0
+ existing.carry = null
}
return
}
@@ -128,7 +145,8 @@ export function createRemoteContextTail(win: BrowserWindow, remoteFile: RemoteFi
reading: false,
lastUsed: 0,
lastModel: null,
- lastWindow: 0
+ lastWindow: 0,
+ carry: null
}
sessions.set(sessionId, t)
void read(sessionId, t) // immediate first value (resumed sessions already have content)
diff --git a/src/renderer/state/agentNodes.test.ts b/src/renderer/state/agentNodes.test.ts
new file mode 100644
index 000000000..6b6c73fc0
--- /dev/null
+++ b/src/renderer/state/agentNodes.test.ts
@@ -0,0 +1,28 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { useAgentNodes } from './agentNodes'
+
+describe('useAgentNodes.finish', () => {
+ beforeEach(() => {
+ useAgentNodes.setState({ byId: {}, activityById: {}, positions: {}, sizes: {}, expanded: {} })
+ })
+
+ it('keeps an explicit durationMs from the hook stats', () => {
+ useAgentNodes.getState().start('tu1', { parentNodeId: 'n1' })
+ useAgentNodes.getState().finish('tu1', { durationMs: 4200, tokens: 10 })
+ expect(useAgentNodes.getState().byId['tu1']).toMatchObject({ state: 'done', durationMs: 4200, tokens: 10 })
+ })
+
+ // Async subagents end via a <task-notification> that carries no timing stats — the card
+ // should still show a duration, computed from its own startedAt.
+ it('falls back to elapsed-since-start when the end event has no durationMs', () => {
+ useAgentNodes.getState().start('tu2', { parentNodeId: 'n1' })
+ useAgentNodes.setState((s) => ({
+ byId: { ...s.byId, tu2: { ...s.byId.tu2, startedAt: Date.now() - 5000 } }
+ }))
+ useAgentNodes.getState().finish('tu2', { result: 'done via notification' })
+ const v = useAgentNodes.getState().byId['tu2']
+ expect(v.state).toBe('done')
+ expect(v.durationMs).toBeGreaterThanOrEqual(4500)
+ expect(v.durationMs).toBeLessThan(20000)
+ })
+})
diff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.ts
index c333b5526..154e139ae 100644
--- a/src/renderer/state/agentNodes.ts
+++ b/src/renderer/state/agentNodes.ts
@@ -74,7 +74,10 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
set((s) => {
const prev = s.byId[toolUseId]
if (!prev || prev.state === 'done') return s
- return { byId: { ...s.byId, [toolUseId]: { ...prev, state: 'done', ...result } } }
+ // Async subagents end via a <task-notification> that carries no timing stats — fall
+ // back to the card's own elapsed time so the duration doesn't vanish on completion.
+ const durationMs = result.durationMs ?? Date.now() - prev.startedAt
+ return { byId: { ...s.byId, [toolUseId]: { ...prev, state: 'done', ...result, durationMs } } }
}),
appendActivity: (toolUseId, chunk) =>
diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.ts
index 780dde14f..f967eef29 100644
--- a/src/shared/agents/normalize.test.ts
+++ b/src/shared/agents/normalize.test.ts
@@ -25,6 +25,55 @@ describe('normalizeClaude — turn-end signals', () => {
})
})
+describe('normalizeClaude — async subagents', () => {
+ it('PostToolUse for a sync subagent → subagent-end with stats', () => {
+ const e = normalizeClaude(
+ env({
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Task',
+ tool_use_id: 'tu1',
+ tool_response: { content: [{ type: 'text', text: 'the answer' }], totalDurationMs: 1200 }
+ })
+ )
+ expect(e).toMatchObject({ kind: 'subagent-end', toolUseId: 'tu1', durationMs: 1200, result: 'the answer' })
+ })
+
+ // Claude Code launches subagents async by default: PostToolUse fires ~immediately with a
+ // launch acknowledgment ({isAsync, status:'async_launched'}), NOT the finished result. That
+ // must not end the card — the real end arrives later via the parent's <task-notification>.
+ it('PostToolUse for an async launch → NOT subagent-end (card stays working)', () => {
+ const e = normalizeClaude(
+ env({
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Task',
+ tool_use_id: 'tu1',
+ tool_response: { isAsync: true, status: 'async_launched', agentId: 'a1' }
+ })
+ )
+ expect(e?.kind).not.toBe('subagent-end')
+ expect(e).toMatchObject({ kind: 'state', state: 'working' })
+ })
+
+ it('UserPromptSubmit → working with newTurn', () => {
+ const e = normalizeClaude(env({ hook_event_name: 'UserPromptSubmit', prompt: 'do things' }))
+ expect(e).toMatchObject({ kind: 'state', state: 'working', newTurn: true, task: 'do things' })
+ })
+
+ // A completed async subagent is delivered back as a queued <task-notification> prompt.
+ // That is not a genuine user turn: flagging it newTurn would clear the whole subagent
+ // fan-out at the exact moment one of the cards completes.
+ it('UserPromptSubmit of a <task-notification> → working but NOT a new turn', () => {
+ const e = normalizeClaude(
+ env({
+ hook_event_name: 'UserPromptSubmit',
+ prompt: '<task-notification>\n<task-id>a1</task-id>\n<tool-use-id>tu1</tool-use-id>\n</task-notification>'
+ })
+ )
+ expect(e).toMatchObject({ kind: 'state', state: 'working' })
+ expect(e?.newTurn).toBeFalsy()
+ })
+})
+
describe('normalizeClaude — permission signals', () => {
it('PermissionRequest → blocked', () => {
const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest' }))
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index a54b481f9..a2860f54f 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -64,6 +64,7 @@ interface ClaudePayload {
}
tool_response?: {
status?: string
+ isAsync?: boolean
content?: { type?: string; text?: string }[]
totalDurationMs?: number
totalTokens?: number
@@ -71,6 +72,16 @@ interface ClaudePayload {
}
}
+/**
+ * Claude Code launches subagents async by default: the Task/Agent PostToolUse fires
+ * ~immediately with a launch acknowledgment, not the finished result. Treating that as the
+ * subagent's end flips the card to done seconds after it starts, with no output. The real
+ * end arrives later as a <task-notification> in the parent transcript.
+ */
+export function isAsyncSubagentLaunch(r: { status?: string; isAsync?: boolean } | undefined): boolean {
+ return r?.status === 'async_launched' || r?.isAsync === true
+}
+
export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | null {
const p = env.payload as ClaudePayload
const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.session_id }
@@ -88,6 +99,8 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu
taskLabel: p.tool_input?.description ?? p.tool_input?.prompt
}
}
+ // Async launch acknowledgment — the subagent just started, it didn't finish.
+ if (isAsyncSubagentLaunch(p.tool_response)) return { ...base, kind: 'state', state: 'working' }
return {
...base,
kind: 'subagent-end',
@@ -123,6 +136,12 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu
}
if (ev === 'UserPromptSubmit') {
+ // A completed async subagent is delivered back as a queued <task-notification> prompt.
+ // That's not a genuine user turn — flagging it newTurn would clear the subagent fan-out
+ // at the exact moment one of the cards completes.
+ if ((p.prompt ?? '').trimStart().startsWith('<task-notification>')) {
+ return { ...base, kind: 'state', state: 'working' }
+ }
return { ...base, kind: 'state', state: 'working', task: p.prompt, newTurn: true }
}
if (ev === 'Stop') {