diff --git a/src/main/auto-sleep-monitor.test.ts b/src/main/auto-sleep-monitor.test.ts new file mode 100644 index 00000000..924a5dfa --- /dev/null +++ b/src/main/auto-sleep-monitor.test.ts @@ -0,0 +1,151 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('./debug', () => ({ + log: () => {} +})) +vi.mock('./perf-log', () => ({ + perfLog: () => {} +})) + +import { Store } from './store' +import { AutoSleepMonitor } from './auto-sleep-monitor' +import { initialState, type AppState } from '../shared/state' +import type { PanesFSM } from './panes-fsm' + +const WT = '/wt/a' +const TAB = 'chat-1' +const AGENT_TOOL_USE = 'toolu_agent' +const MINUTE = 60_000 +const LAST_ACTIVE = 1_000_000 + +function makeStore(): Store { + const state: AppState = { + ...initialState, + settings: { ...initialState.settings, autoSleepMinutes: 10 }, + terminals: { + ...initialState.terminals, + panes: { + [WT]: { + type: 'leaf', + id: 'p1', + tabs: [{ id: TAB, type: 'json-claude', label: 'Chat' }], + activeTabId: TAB + } + }, + statuses: { [TAB]: 'waiting' }, + lastActive: { [WT]: LAST_ACTIVE } + } + } + const store = new Store(state) + store.dispatch({ + type: 'jsonClaude/sessionStarted', + payload: { sessionId: TAB, worktreePath: WT } + }) + store.dispatch({ + type: 'jsonClaude/sessionStateChanged', + payload: { sessionId: TAB, state: 'running' } + }) + store.dispatch({ + type: 'jsonClaude/backgroundAgentLaunched', + payload: { + sessionId: TAB, + toolUseId: AGENT_TOOL_USE, + agentId: 'a123', + description: 'long job', + taskType: 'local_agent', + timestamp: LAST_ACTIVE + } + }) + return store +} + +function makeMonitor(store: Store) { + const sleepJsonClaudeTab = vi.fn() + const monitor = new AutoSleepMonitor(store, { sleepJsonClaudeTab } as unknown as PanesFSM) + return { monitor, sleepJsonClaudeTab } +} + +describe('AutoSleepMonitor', () => { + it('does not sleep an idle tab with a running background agent', () => { + const store = makeStore() + const { monitor, sleepJsonClaudeTab } = makeMonitor(store) + monitor.sweep(LAST_ACTIVE + 30 * MINUTE) + expect(sleepJsonClaudeTab).not.toHaveBeenCalled() + }) + + it('sleeps the tab once the agent settles and it has been idle past the threshold', () => { + const store = makeStore() + const { monitor, sleepJsonClaudeTab } = makeMonitor(store) + store.dispatch({ + type: 'jsonClaude/backgroundAgentSettled', + payload: { + sessionId: TAB, + toolUseId: AGENT_TOOL_USE, + agentId: 'a123', + status: 'completed', + timestamp: LAST_ACTIVE + MINUTE + } + }) + // Under the threshold: still awake. + monitor.sweep(LAST_ACTIVE + 5 * MINUTE) + expect(sleepJsonClaudeTab).not.toHaveBeenCalled() + monitor.sweep(LAST_ACTIVE + 30 * MINUTE) + expect(sleepJsonClaudeTab).toHaveBeenCalledWith(WT, TAB) + }) + + it('does not sleep while a resumed agent is running again', () => { + const store = makeStore() + const { monitor, sleepJsonClaudeTab } = makeMonitor(store) + store.dispatch({ + type: 'jsonClaude/backgroundAgentSettled', + payload: { + sessionId: TAB, + toolUseId: AGENT_TOOL_USE, + agentId: 'a123', + status: 'completed', + timestamp: LAST_ACTIVE + MINUTE + } + }) + // SendMessage resume: same task id, the SendMessage call's tool_use id. + store.dispatch({ + type: 'jsonClaude/backgroundAgentLaunched', + payload: { + sessionId: TAB, + toolUseId: 'toolu_sendmessage', + agentId: 'a123', + description: 'long job', + taskType: 'local_agent', + timestamp: LAST_ACTIVE + 2 * MINUTE + } + }) + monitor.sweep(LAST_ACTIVE + 30 * MINUTE) + expect(sleepJsonClaudeTab).not.toHaveBeenCalled() + }) + + it('does not sleep while a background Bash task is running', () => { + const store = makeStore() + const { monitor, sleepJsonClaudeTab } = makeMonitor(store) + store.dispatch({ + type: 'jsonClaude/backgroundAgentSettled', + payload: { + sessionId: TAB, + toolUseId: AGENT_TOOL_USE, + status: 'completed', + timestamp: LAST_ACTIVE + MINUTE + } + }) + store.dispatch({ + type: 'jsonClaude/backgroundAgentLaunched', + payload: { + sessionId: TAB, + toolUseId: 'toolu_bash', + agentId: 'bvn3zclfg', + description: 'sleep 600', + taskType: 'local_bash', + timestamp: LAST_ACTIVE + 2 * MINUTE + } + }) + monitor.sweep(LAST_ACTIVE + 30 * MINUTE) + expect(sleepJsonClaudeTab).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/auto-sleep-monitor.ts b/src/main/auto-sleep-monitor.ts index 61ba83ce..271e6ef3 100644 --- a/src/main/auto-sleep-monitor.ts +++ b/src/main/auto-sleep-monitor.ts @@ -1,6 +1,7 @@ import type { Store } from './store' import type { PanesFSM } from './panes-fsm' import { getLeaves } from '../shared/state/terminals' +import { hasRunningBackgroundTask } from '../shared/state/json-claude' import { log } from './debug' const SWEEP_INTERVAL_MS = 60_000 @@ -14,6 +15,9 @@ export class AutoSleepMonitor { private store: Store private panesFSM: PanesFSM private timer: NodeJS.Timeout | null = null + /** Tabs already logged as kept awake by background work, so the skip + * is logged once per stretch rather than every minute. */ + private keptAwake = new Set() constructor(store: Store, panesFSM: PanesFSM) { this.store = store @@ -32,12 +36,12 @@ export class AutoSleepMonitor { } } - private sweep(): void { + /** @internal exposed for tests. */ + sweep(now: number = Date.now()): void { const state = this.store.getSnapshot().state const minutes = state.settings.autoSleepMinutes if (!Number.isFinite(minutes) || minutes <= 0) return const thresholdMs = minutes * 60_000 - const now = Date.now() for (const [wtPath, tree] of Object.entries(state.terminals.panes)) { const lastActive = state.terminals.lastActive[wtPath] if (typeof lastActive !== 'number') continue @@ -52,6 +56,29 @@ export class AutoSleepMonitor { // mid-spawn would race the JsonClaudeManager's create(). const session = state.jsonClaude.sessions[tab.id] if (session?.state === 'connecting') continue + // A turn can end with a detached Agent or run_in_background + // Bash still going; the tab reads 'waiting' but killing the + // process would kill that work too. Bash counts because Claude + // Code reports it through the same task_started/notification + // pair (see json-claude-manager.ts). + // + // No upper bound, deliberately: a backgrounded dev server or + // `tail -f` never settles, so its tab stays awake until the + // process exits. Killing the user's server would be worse than + // not sleeping. The cost is that a dropped task_notification + // (a Claude Code bug or protocol change) pins the tab too — + // hence the log line, so that's diagnosable from debug.log. + if (session && hasRunningBackgroundTask(session)) { + if (!this.keptAwake.has(tab.id)) { + this.keptAwake.add(tab.id) + log( + 'auto-sleep', + `skip tab=${tab.id} wt=${wtPath}: running background task` + ) + } + continue + } + this.keptAwake.delete(tab.id) log( 'auto-sleep', `sleep tab=${tab.id} wt=${wtPath} idleMs=${now - lastActive}` diff --git a/src/main/json-claude-manager.test.ts b/src/main/json-claude-manager.test.ts index cfd30a50..430952c8 100644 --- a/src/main/json-claude-manager.test.ts +++ b/src/main/json-claude-manager.test.ts @@ -817,6 +817,40 @@ describe('JsonClaudeManager', () => { expect(results[results.length - 1]?.content).toBe('Exact stdout: alpha') }) + // Recorded from Claude Code 2.1.327: a SendMessage resume re-runs the + // same task_id under the SendMessage call's tool_use_id. + it('a SendMessage resume re-runs and re-settles the original Agent card', () => { + const { store, feed } = setup() + const SEND_ID = 'toolu_sendmessage' + feed(started) + feed({ + type: 'system', + subtype: 'task_notification', + task_id: TASK_ID, + tool_use_id: TOOL_USE_ID, + status: 'completed', + summary: 'hi' + }) + feed({ ...started, tool_use_id: SEND_ID, prompt: 'now sleep 25' }) + expect(Object.keys(agents(store) ?? {})).toEqual([TOOL_USE_ID]) + expect(agents(store)?.[TOOL_USE_ID]?.status).toBe('running') + feed({ + type: 'system', + subtype: 'task_notification', + task_id: TASK_ID, + tool_use_id: SEND_ID, + status: 'completed', + summary: 'done' + }) + expect(agents(store)?.[TOOL_USE_ID]?.status).toBe('completed') + const entries = + store.getSnapshot().state.jsonClaude.sessions['sess-bg']?.entries ?? [] + const results = entries + .flatMap((e) => e.blocks ?? []) + .filter((b) => b.type === 'tool_result' && b.toolUseId === TOOL_USE_ID) + expect(results[results.length - 1]?.content).toBe('done') + }) + it('ignores a task event with no tool_use_id', () => { const { store, feed } = setup() feed({ type: 'system', subtype: 'task_started', task_id: TASK_ID }) diff --git a/src/main/json-claude-manager.ts b/src/main/json-claude-manager.ts index 38ded006..ef540fe5 100644 --- a/src/main/json-claude-manager.ts +++ b/src/main/json-claude-manager.ts @@ -34,7 +34,7 @@ import type { JsonClaudePermissionMode, JsonClaudeSessionState } from '../shared/state/json-claude' -import { parseUserTurn } from '../shared/state/json-claude' +import { parseUserTurn, resolveBackgroundAgentKey } from '../shared/state/json-claude' import { writeResultImage } from './json-claude-attachments' import type { ClaudeLaunchSettings } from './claude-launch' import { log } from './debug' @@ -1625,9 +1625,27 @@ export class JsonClaudeManager implements ChatProvider { // actual work streams inline on this same stdout carrying // parent_tool_use_id, so nesting already works — only the card's // running/settled status needs wiring. + // + // What Claude Code 2.1.x actually emits (probed against the bundled + // binary): + // - Background Bash gets the same pair, with task_type 'local_bash' + // and tool_use_id = the Bash call, so it lands in backgroundAgents + // too. Bash launched by a sub-agent carries owned_by_subagent. + // - A SendMessage resume of a finished agent emits a fresh + // task_started with the SAME task_id but tool_use_id = the + // SendMessage call; its task_notification does likewise. The + // reducer maps it back to the Agent call by task_id. The resumed + // agent's inline activity still carries the original Agent id as + // parent_tool_use_id. + // - task_updated / task_progress / background_tasks_changed also + // arrive; the pair above is enough, so they're ignored. if (type === 'system' && subtype === 'task_started') { const toolUseId = parsed['tool_use_id'] const agentId = parsed['task_id'] + log( + 'json-claude', + `task_started sessionId=${instance.sessionId} tool_use_id=${String(toolUseId)} task_id=${String(agentId)} task_type=${String(parsed['task_type'])}` + ) if (typeof toolUseId !== 'string' || typeof agentId !== 'string') return this.store.dispatch({ type: 'jsonClaude/backgroundAgentLaunched', @@ -1639,14 +1657,33 @@ export class JsonClaudeManager implements ChatProvider { typeof parsed['description'] === 'string' ? (parsed['description'] as string) : '', + ...(typeof parsed['task_type'] === 'string' + ? { taskType: parsed['task_type'] as string } + : {}), timestamp: Date.now() } }) return } if (type === 'system' && subtype === 'task_notification') { - const toolUseId = parsed['tool_use_id'] - if (typeof toolUseId !== 'string') return + const rawToolUseId = parsed['tool_use_id'] + const agentId = + typeof parsed['task_id'] === 'string' ? (parsed['task_id'] as string) : undefined + log( + 'json-claude', + `task_notification sessionId=${instance.sessionId} tool_use_id=${String(rawToolUseId)} task_id=${String(agentId)} status=${String(parsed['status'])}` + ) + if (typeof rawToolUseId !== 'string') return + // A resume's notification names the SendMessage call; its report + // belongs on the Agent card, which is what the user is watching. + // Resolved here because toolResultAttached below needs the Agent + // id. The backgroundAgentSettled reducer resolves again so the + // event stays correct for any other dispatcher (tests, replay); + // after this pass that second resolve is a no-op, not dead code. + const session = this.store.getSnapshot().state.jsonClaude.sessions[instance.sessionId] + const toolUseId = session + ? resolveBackgroundAgentKey(session, rawToolUseId, agentId) + : rawToolUseId const failed = parsed['status'] !== 'completed' const rawUsage = parsed['usage'] as Record | undefined const num = (v: unknown): number | undefined => @@ -1663,6 +1700,7 @@ export class JsonClaudeManager implements ChatProvider { payload: { sessionId: instance.sessionId, toolUseId, + ...(agentId ? { agentId } : {}), status: failed ? 'failed' : 'completed', timestamp: Date.now(), ...(usage ? { usage } : {}) @@ -2203,7 +2241,12 @@ export class JsonClaudeManager implements ChatProvider { ): void { this.store.dispatch({ type: 'jsonClaude/sessionStateChanged', - payload: { sessionId, state, ...extra } + payload: { + sessionId, + state, + ...extra, + ...(state === 'exited' ? { timestamp: Date.now() } : {}) + } }) } diff --git a/src/renderer/components/AgentApprovalCards.tsx b/src/renderer/components/AgentApprovalCards.tsx new file mode 100644 index 00000000..c2d30370 --- /dev/null +++ b/src/renderer/components/AgentApprovalCards.tsx @@ -0,0 +1,49 @@ +import { QUESTION_TOOL_NAME } from '../../shared/state/json-claude' +import { useJsonClaudeApprovals } from '../hooks/useJsonClaudeApprovals' +import { JsonClaudeApprovalCard } from './JsonClaudeApprovalCard' + +/** The approval prompts one sub-agent is blocked on, for the Subagents + * column and the agent peek. The same prompt also renders inside the + * agent's Task card in the transcript, but for a background agent that + * card is usually far up the scrollback — so without this the only sign + * was a ⚠ on a card that couldn't do anything about it. Resolving either + * copy resolves the request; the other unmounts with it. + * + * Reads the approvals itself rather than taking them as props so an + * auto-review update repaints the card without breaking the agent + * card's memo, which only fingerprints the ids. */ +export function AgentApprovalCards({ + sessionId, + toolUseIds +}: { + sessionId: string + toolUseIds: readonly string[] +}): JSX.Element | null { + const { pending, resolve } = useJsonClaudeApprovals(sessionId) + if (toolUseIds.length === 0) return null + const mine = pending.filter((a) => a.toolUseId && toolUseIds.includes(a.toolUseId)) + if (mine.length === 0) return null + return ( +
+ {mine.map((approval) => + // The question card autofocuses and keeps a local draft, so a + // second copy would steal focus from the transcript's and split + // the answer across two inputs. Point at the one that exists. + approval.toolName === QUESTION_TOOL_NAME ? ( +
+ Asking you a question. Answer it in the chat. +
+ ) : ( + resolve(approval.requestId, result)} + /> + ) + )} +
+ ) +} diff --git a/src/renderer/components/AgentPeek.tsx b/src/renderer/components/AgentPeek.tsx index a4046cee..58329a8a 100644 --- a/src/renderer/components/AgentPeek.tsx +++ b/src/renderer/components/AgentPeek.tsx @@ -8,6 +8,7 @@ import { formatElapsed } from '../../shared/state/json-claude-agents' import { AgentStepLine } from './AgentStepLine' +import { AgentApprovalCards } from './AgentApprovalCards' import { AgentStatusDot, agentStatusLabel } from './AgentStatusDot' /** How much of a text block to show inline in the feed. The peek is a @@ -16,6 +17,8 @@ import { AgentStatusDot, agentStatusLabel } from './AgentStatusDot' const TEXT_PREVIEW = 600 interface AgentPeekProps { + /** Session the agent belongs to, for its pending approvals. */ + sessionId: string agent: AgentSummary /** Live clock, passed down so every peek and panel row ticks off the * same interval rather than each mounting its own. */ @@ -32,6 +35,7 @@ interface AgentPeekProps { * agent hard. Here every step gets exactly one line, newest at the * bottom, and the view follows along. */ export function AgentPeek({ + sessionId, agent, now, onClose, @@ -124,6 +128,15 @@ export function AgentPeek({ )} + {agent.pendingApprovalToolUseIds.length > 0 && ( +
+ +
+ )} +
{ diff --git a/src/renderer/components/ChatAgentColumn.tsx b/src/renderer/components/ChatAgentColumn.tsx index 5f7168b5..6e42136d 100644 --- a/src/renderer/components/ChatAgentColumn.tsx +++ b/src/renderer/components/ChatAgentColumn.tsx @@ -9,6 +9,7 @@ import { type AgentSummary } from '../../shared/state/json-claude-agents' import { AgentPeek } from './AgentPeek' +import { AgentApprovalCards } from './AgentApprovalCards' import { Chevron } from './json-mode-cards/ChatRow' import { AgentStatusDot, agentStatusLabel } from './AgentStatusDot' import { AgentStepLine } from './AgentStepLine' @@ -122,6 +123,7 @@ function useFollowTail(slack: number, enabled = true) { } interface CardProps { + sessionId: string agent: AgentSummary depth: number /** Only passed to running cards. Settled elapsed times are fixed, so a @@ -137,6 +139,7 @@ interface CardProps { * type scale — so an agent reads the same here as it does inline in the * transcript. */ function AgentCardImpl({ + sessionId, agent, depth, now, @@ -216,6 +219,18 @@ function AgentCardImpl({ + {/* Outside the disclosure: a blocked agent stays blocked whether + or not its card is open, so the prompt can't hide behind the + chevron. */} + {agent.pendingApprovalToolUseIds.length > 0 && ( +
+ +
+ )} + {expanded && (
{agent.prompt && ( @@ -273,6 +288,7 @@ function AgentCardImpl({ const AgentCard = memo(AgentCardImpl, (a, b) => { if ( + a.sessionId !== b.sessionId || a.depth !== b.depth || a.expanded !== b.expanded || a.onToggle !== b.onToggle || @@ -288,12 +304,14 @@ const AgentCard = memo(AgentCardImpl, (a, b) => { * re-renders (per streamed token, via the session hook) stop here when * the row list hasn't changed. */ const AgentFeed = memo(function AgentFeed({ + sessionId, rows, now, isExpanded, onToggle, onPeek }: { + sessionId: string rows: readonly Row[] now: number isExpanded: (agent: AgentSummary) => boolean @@ -313,6 +331,7 @@ const AgentFeed = memo(function AgentFeed({ {rows.map(({ agent, depth }) => ( 0 ? `${running} running` : `${agents.length} done` + // A blocked agent can't make progress until someone answers, and with + // the column collapsed nothing else on screen says so. + const blocked = agents.some((a) => a.pendingApprovalToolUseIds.length > 0) const peek = peeked && ( setPeekId(null)} @@ -418,10 +441,14 @@ function ChatAgentColumnLive({
- {peeked && ( + {peeked && focusedTabId && ( setPeekId(null)} diff --git a/src/renderer/components/agent-column-rows.test.ts b/src/renderer/components/agent-column-rows.test.ts index d75704d6..0b51428a 100644 --- a/src/renderer/components/agent-column-rows.test.ts +++ b/src/renderer/components/agent-column-rows.test.ts @@ -17,6 +17,7 @@ function agent( toolCount: 0, childAgentCount: 0, hasPendingApproval: false, + pendingApprovalToolUseIds: [], steps: [], ...extra } diff --git a/src/renderer/components/agent-column-rows.ts b/src/renderer/components/agent-column-rows.ts index 0c7ae94f..33efbcbb 100644 --- a/src/renderer/components/agent-column-rows.ts +++ b/src/renderer/components/agent-column-rows.ts @@ -41,6 +41,7 @@ export function fingerprint(a: AgentSummary): string { return [ a.status, a.hasPendingApproval ? 1 : 0, + a.pendingApprovalToolUseIds.join(','), a.steps.length, last?.key ?? '', last?.text?.length ?? 0, diff --git a/src/shared/state/json-claude-agents.test.ts b/src/shared/state/json-claude-agents.test.ts index 4afbf378..72f74ccc 100644 --- a/src/shared/state/json-claude-agents.test.ts +++ b/src/shared/state/json-claude-agents.test.ts @@ -478,6 +478,88 @@ describe('collectAgents', () => { ) }) + it('does not reuse a settled summary once a resume makes it run again', () => { + const bg = (status: 'running' | 'completed', startedAt: number, completedAt?: number) => ({ + t1: { + agentId: 'a1', + toolUseId: 't1', + description: 'Bg', + status, + startedAt, + ...(completedAt !== undefined ? { completedAt } : {}) + } + }) + const before = [ + launch('t1', 'Bg', { background: true }), + childWork('t1', [{ type: 'text', text: 'hi' }], 1500, 'c1'), + toolResult('t1', 'hi') + ] + const settled = collectAgents( + session(before, { backgroundAgents: bg('completed', 1000, 2000) }) + ) + expect(settled[0].status).toBe('completed') + + // SendMessage resume: same record flipped back to running, and the + // resumed run's activity still carries the Agent id as its parent. + const after = [ + ...before, + childWork( + 't1', + [{ type: 'tool_use', id: 'x1', name: 'Bash', input: { command: 'sleep 25' } }], + 3000, + 'c2' + ) + ] + const resumed = collectAgents( + session(after, { backgroundAgents: bg('running', 2500) }), + new Set(['x1']), + settled + ) + expect(resumed[0]).not.toBe(settled[0]) + expect(resumed[0].status).toBe('running') + expect(resumed[0].steps.at(-1)?.toolName).toBe('Bash') + expect(resumed[0].pendingApprovalToolUseIds).toEqual(['x1']) + }) + + it('still reuses a settled summary whose lifecycle record is unchanged', () => { + const s = session( + [launch('t1', 'Bg', { background: true }), toolResult('t1', 'done')], + { + backgroundAgents: { + t1: { + agentId: 'a1', + toolUseId: 't1', + description: 'Bg', + status: 'completed', + startedAt: 1000, + completedAt: 2000 + } + } + } + ) + const first = collectAgents(s) + expect(collectAgents(s, undefined, first)[0]).toBe(first[0]) + }) + + it('lists only an agent’s own pending calls, not its descendants’', () => { + const agents = collectAgents( + session([ + launch('t1', 'Parent', { background: true }), + launch('t2', 'Child', { parentToolUseId: 't1', entryId: 'e2' }), + childWork('t1', [ + { type: 'tool_use', id: 'p1', name: 'Write', input: { file_path: '/a' } } + ]), + childWork('t2', [ + { type: 'tool_use', id: 'x9', name: 'Bash', input: { command: 'rm' } }, + { type: 'tool_use', id: 'x10', name: 'Bash', input: { command: 'ls' } } + ], 2000, 'c2') + ]), + new Set(['p1', 'x9']) + ) + expect(agents.find((a) => a.toolUseId === 't1')!.pendingApprovalToolUseIds).toEqual(['p1']) + expect(agents.find((a) => a.toolUseId === 't2')!.pendingApprovalToolUseIds).toEqual(['x9']) + }) + it('sorts running agents first (oldest first), then settled newest-first', () => { const agents = collectAgents( session([ diff --git a/src/shared/state/json-claude-agents.ts b/src/shared/state/json-claude-agents.ts index 12c3638b..572bf7d8 100644 --- a/src/shared/state/json-claude-agents.ts +++ b/src/shared/state/json-claude-agents.ts @@ -72,6 +72,11 @@ export interface AgentSummary { usage?: { totalTokens?: number; toolUses?: number; durationMs?: number } /** True when this agent, or anything below it, is awaiting approval. */ hasPendingApproval: boolean + /** tool_use ids of this agent's own calls that are awaiting approval — + * not its descendants', which sit on their own cards. Lets the + * Subagents column put the approval prompt on the card itself, since + * a background agent's Task card is usually far up the transcript. */ + pendingApprovalToolUseIds: string[] /** Chronological activity feed. The peek view renders this directly; * the panel renders only its last element as the "currently" line. */ steps: AgentStep[] @@ -239,13 +244,24 @@ export function collectAgents( const summaries: AgentSummary[] = launches.map((site) => { // Settled last time, and still present in entries — nothing about it // can have changed, so skip rebuilding its step feed entirely. + // Unless the lifecycle record has moved since: a SendMessage resume + // flips a settled agent back to running under the same key, and + // reusing the old summary would freeze its status, steps and + // pending approvals at the pre-resume snapshot. const cached = reusable.get(site.toolUseId) - if (cached) return cached + const bgNow = session.backgroundAgents?.[site.toolUseId] + if ( + cached && + (!bgNow || + (bgNow.status === cached.status && bgNow.completedAt === cached.completedAt)) + ) { + return cached + } const childEntries = childEntriesByParent.get(site.toolUseId) ?? [] const steps: AgentStep[] = [] let toolCount = 0 - let hasPendingApproval = false + const pendingApprovalToolUseIds: string[] = [] for (const entry of childEntries) { if (!entry.blocks) continue @@ -254,7 +270,7 @@ export function collectAgents( const key = `${entry.entryId}-${b.id ?? b.toolUseId ?? i}` if (b.type === 'tool_use') { toolCount += 1 - if (b.id && pendingToolUseIds?.has(b.id)) hasPendingApproval = true + if (b.id && pendingToolUseIds?.has(b.id)) pendingApprovalToolUseIds.push(b.id) const nested = isSubAgentToolName(b.name) && b.id && launchById.has(b.id) ? b.id @@ -350,7 +366,8 @@ export function collectAgents( toolCount, childAgentCount: childAgentCounts.get(site.toolUseId) ?? 0, ...(bg?.usage ? { usage: bg.usage } : {}), - hasPendingApproval, + hasPendingApproval: pendingApprovalToolUseIds.length > 0, + pendingApprovalToolUseIds, steps, ...(result ? { result: result.content, resultIsError: result.isError } : {}) } diff --git a/src/shared/state/json-claude.test.ts b/src/shared/state/json-claude.test.ts index 0f8c8534..c5496019 100644 --- a/src/shared/state/json-claude.test.ts +++ b/src/shared/state/json-claude.test.ts @@ -1670,6 +1670,77 @@ describe('jsonClaudeReducer background agents', () => { expect(next).toBe(state) }) + function settle(state: JsonClaudeState, toolUseId: string, timestamp: number): JsonClaudeState { + return jsonClaudeReducer(state, { + type: 'jsonClaude/backgroundAgentSettled', + payload: { + sessionId: SID, + toolUseId, + agentId: 'aece96b04cf6ba1c8', + status: 'completed', + timestamp, + usage: { toolUses: 3 } + } + }) + } + + function resume(state: JsonClaudeState): JsonClaudeState { + // What Claude Code emits on a SendMessage resume: same task_id, but + // tool_use_id is the SendMessage call's. + return jsonClaudeReducer(state, { + type: 'jsonClaude/backgroundAgentLaunched', + payload: { + sessionId: SID, + toolUseId: 'toolu_sendmessage', + agentId: 'aece96b04cf6ba1c8', + description: 'resumed', + taskType: 'local_agent', + timestamp: 3000 + } + }) + } + + it('backgroundAgentLaunched for a resumed task flips the original record back to running', () => { + const next = resume(settle(launch(seedSession(initialJsonClaude)), TOOL_USE, 2000)) + const agents = next.sessions[SID].backgroundAgents + expect(Object.keys(agents)).toEqual([TOOL_USE]) + expect(agents[TOOL_USE].status).toBe('running') + expect(agents[TOOL_USE].startedAt).toBe(3000) + expect(agents[TOOL_USE].completedAt).toBeUndefined() + expect(agents[TOOL_USE].usage).toBeUndefined() + expect(agents[TOOL_USE].description).toBe('Source U of A financial deadlines') + expect(agents[TOOL_USE].taskType).toBe('local_agent') + }) + + it('backgroundAgentSettled for a resumed task settles the original record by task id', () => { + const resumed = resume(settle(launch(seedSession(initialJsonClaude)), TOOL_USE, 2000)) + const next = settle(resumed, 'toolu_sendmessage', 4000) + const agents = next.sessions[SID].backgroundAgents + expect(Object.keys(agents)).toEqual([TOOL_USE]) + expect(agents[TOOL_USE].status).toBe('completed') + expect(agents[TOOL_USE].completedAt).toBe(4000) + }) + + it('sessionStateChanged to exited marks running tasks interrupted', () => { + const state = launch(seedSession(initialJsonClaude)) + const next = jsonClaudeReducer(state, { + type: 'jsonClaude/sessionStateChanged', + payload: { sessionId: SID, state: 'exited', timestamp: 5000 } + }) + expect(next.sessions[SID].backgroundAgents[TOOL_USE].status).toBe('interrupted') + // Stops the elapsed clock at the exit instead of ticking forever. + expect(next.sessions[SID].backgroundAgents[TOOL_USE].completedAt).toBe(5000) + }) + + it('sessionStateChanged to a live state leaves running tasks alone', () => { + const state = launch(seedSession(initialJsonClaude)) + const next = jsonClaudeReducer(state, { + type: 'jsonClaude/sessionStateChanged', + payload: { sessionId: SID, state: 'running' } + }) + expect(next.sessions[SID].backgroundAgents).toBe(state.sessions[SID].backgroundAgents) + }) + it('sessionStarted preserves background agents across a respawn', () => { const next = seedSession(launch(seedSession(initialJsonClaude))) expect(next.sessions[SID].backgroundAgents[TOOL_USE].status).toBe('running') diff --git a/src/shared/state/json-claude.ts b/src/shared/state/json-claude.ts index f047697e..b71c2abc 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -448,13 +448,21 @@ export interface JsonClaudeChatEntry { * separate transcript that SubagentTailer follows. Without this record * the Task card would look instantly-complete-with-no-activity. */ export interface JsonClaudeBackgroundAgent { - /** Claude Code's internal id for the detached agent. */ + /** Claude Code's task id (`task_id`) — the agentId for an agent, the + * shell id for a background Bash. Stable across a SendMessage resume. */ agentId: string /** tool_use id of the launching Task call. Also this map's key, and the * `parentToolUseId` stamped on every tailed child entry. */ toolUseId: string description: string - status: 'running' | 'completed' | 'failed' + /** Claude Code's `task_type`: 'local_agent', 'local_bash', …. Despite + * this record's name, every detached task gets one — background Bash + * emits the same task_started/task_notification pair. Missing on + * records from before the field existed. */ + taskType?: string + /** 'interrupted' only ever comes from the process exiting under a + * running task (sleep, crash, restart) — Claude never reports it. */ + status: 'running' | 'completed' | 'failed' | 'interrupted' startedAt: number completedAt?: number /** Totals reported in the completion notification's block. */ @@ -611,6 +619,9 @@ export type JsonClaudeEvent = state: JsonClaudeSessionState exitCode?: number | null exitReason?: string | null + /** When it happened. Stamped onto tasks an exit interrupts as + * their completedAt, so their elapsed time stops at the exit. */ + timestamp?: number } } | { @@ -769,6 +780,7 @@ export type JsonClaudeEvent = toolUseId: string agentId: string description: string + taskType?: string timestamp: number } } @@ -777,6 +789,9 @@ export type JsonClaudeEvent = payload: { sessionId: string toolUseId: string + /** task_id, used to find the original record when `toolUseId` is + * a resume's SendMessage id. See resolveBackgroundAgentKey. */ + agentId?: string status: 'completed' | 'failed' timestamp: number usage?: { totalTokens?: number; toolUses?: number; durationMs?: number } @@ -869,6 +884,36 @@ function applyBlockTextDelta( } } +/** The map key a task event belongs under. A SendMessage resume re-runs + * the same task (same `task_id`) but its task_started/task_notification + * carry the SendMessage call's tool_use_id, not the Agent call's. Keying + * by that id would leave the Agent card "completed" for the whole + * resumed run, so fall back to the record that already owns this task + * id. Linear in the session's task count, which is small and only + * walked on task lifecycle events. */ +export function resolveBackgroundAgentKey( + session: Pick, + toolUseId: string, + agentId: string | undefined +): string { + if (session.backgroundAgents[toolUseId] || !agentId) return toolUseId + for (const [key, agent] of Object.entries(session.backgroundAgents)) { + if (agent.agentId === agentId) return key + } + return toolUseId +} + +/** Whether any detached task (agent or background Bash) is still in + * flight — killing the process now would kill it too. */ +export function hasRunningBackgroundTask( + session: Pick +): boolean { + for (const agent of Object.values(session.backgroundAgents)) { + if (agent.status === 'running') return true + } + return false +} + function patchBackgroundAgent( state: JsonClaudeState, sessionId: string, @@ -896,24 +941,65 @@ function patchBackgroundAgent( } } +// completedAt comes from the event, never Date.now(): the reducer runs in +// main and every renderer, and a local clock would diverge between them. +function settleRunningAgents( + agents: Record, + timestamp: number | undefined +): Record { + const out: Record = {} + for (const [key, agent] of Object.entries(agents)) { + out[key] = + agent.status === 'running' + ? { + ...agent, + status: 'interrupted', + ...(timestamp !== undefined ? { completedAt: timestamp } : {}) + } + : agent + } + return out +} + export function jsonClaudeReducer( state: JsonClaudeState, event: JsonClaudeEvent ): JsonClaudeState { switch (event.type) { case 'jsonClaude/backgroundAgentLaunched': { - const { sessionId, toolUseId, agentId, description, timestamp } = + const { sessionId, agentId, description, taskType, timestamp } = event.payload + const session = state.sessions[sessionId] + if (!session) return state + const toolUseId = resolveBackgroundAgentKey( + session, + event.payload.toolUseId, + agentId + ) + const existing = session.backgroundAgents[toolUseId] + // A resume keeps the original description: the resume's + // task_started repeats it anyway, and the Agent card is labelled + // by the launch. return patchBackgroundAgent(state, sessionId, toolUseId, () => ({ agentId, toolUseId, - description, + description: existing?.description || description, + ...((taskType ?? existing?.taskType) + ? { taskType: taskType ?? existing?.taskType } + : {}), status: 'running', startedAt: timestamp })) } case 'jsonClaude/backgroundAgentSettled': { - const { sessionId, toolUseId, status, timestamp, usage } = event.payload + const { sessionId, agentId, status, timestamp, usage } = event.payload + const session = state.sessions[sessionId] + if (!session) return state + const toolUseId = resolveBackgroundAgentKey( + session, + event.payload.toolUseId, + agentId + ) return patchBackgroundAgent(state, sessionId, toolUseId, (existing) => existing ? { @@ -973,12 +1059,22 @@ export function jsonClaudeReducer( const session = state.sessions[event.payload.sessionId] if (!session) return state const { state: next, exitCode, exitReason } = event.payload + // Detached tasks live in the Claude process, so they die with it. + // Leaving them 'running' would show a phantom spinner forever and + // keep AutoSleepMonitor from ever sleeping the respawned tab. + // 'interrupted', not 'failed': the task didn't error, it was cut + // off — usually by a sleep the user chose. + const backgroundAgents = + next === 'exited' && hasRunningBackgroundTask(session) + ? settleRunningAgents(session.backgroundAgents, event.payload.timestamp) + : session.backgroundAgents return { ...state, sessions: { ...state.sessions, [session.sessionId]: { ...session, + backgroundAgents, state: next, exitCode: exitCode ?? session.exitCode, exitReason: exitReason ?? session.exitReason