From 51b7c16d9d40b613dbbce52ef5fd1702cc3cb81e Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 20:03:23 -0500 Subject: [PATCH 1/4] Keep chats with background work awake; track resumed background agents Claude Code reports a SendMessage resume as a fresh task_started with the same task_id but the SendMessage call's tool_use_id, so the Agent card stayed 'completed' for the whole resumed run. Resolve task events by task_id back to the original Agent record, and attach the resumed run's report to that card. Background Bash emits the same task_started/task_notification pair (task_type local_bash), so AutoSleepMonitor now skips any session with a running detached task. Running tasks are settled when the process exits so a dead one can't pin a tab awake forever. Task lifecycle events are now logged. Co-Authored-By: Claude Opus 5.5 --- src/main/auto-sleep-monitor.test.ts | 151 +++++++++++++++++++++++++++ src/main/auto-sleep-monitor.ts | 11 +- src/main/json-claude-manager.test.ts | 34 ++++++ src/main/json-claude-manager.ts | 40 ++++++- src/shared/state/json-claude.test.ts | 69 ++++++++++++ src/shared/state/json-claude.ts | 92 +++++++++++++++- 6 files changed, 388 insertions(+), 9 deletions(-) create mode 100644 src/main/auto-sleep-monitor.test.ts diff --git a/src/main/auto-sleep-monitor.test.ts b/src/main/auto-sleep-monitor.test.ts new file mode 100644 index 000000000..924a5dfa3 --- /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 61ba83ce1..3f827466e 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 @@ -32,12 +33,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 +53,12 @@ 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). + if (session && hasRunningBackgroundTask(session)) continue 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 cfd30a504..430952c88 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 38ded0065..7cac09ab8 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,29 @@ 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. + 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 +1696,7 @@ export class JsonClaudeManager implements ChatProvider { payload: { sessionId: instance.sessionId, toolUseId, + ...(agentId ? { agentId } : {}), status: failed ? 'failed' : 'completed', timestamp: Date.now(), ...(usage ? { usage } : {}) diff --git a/src/shared/state/json-claude.test.ts b/src/shared/state/json-claude.test.ts index 0f8c85347..7f38b1ab5 100644 --- a/src/shared/state/json-claude.test.ts +++ b/src/shared/state/json-claude.test.ts @@ -1670,6 +1670,75 @@ 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 failed', () => { + const state = launch(seedSession(initialJsonClaude)) + const next = jsonClaudeReducer(state, { + type: 'jsonClaude/sessionStateChanged', + payload: { sessionId: SID, state: 'exited' } + }) + expect(next.sessions[SID].backgroundAgents[TOOL_USE].status).toBe('failed') + }) + + 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 f047697e5..2ec7ed36e 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -448,12 +448,18 @@ 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 + /** 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 status: 'running' | 'completed' | 'failed' startedAt: number completedAt?: number @@ -769,6 +775,7 @@ export type JsonClaudeEvent = toolUseId: string agentId: string description: string + taskType?: string timestamp: number } } @@ -777,6 +784,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 +879,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 +936,60 @@ function patchBackgroundAgent( } } +// No completedAt: the reducer runs in main and every renderer, so a +// Date.now() here would diverge between mirrors. +function settleRunningAgents( + agents: Record +): Record { + const out: Record = {} + for (const [key, agent] of Object.entries(agents)) { + out[key] = + agent.status === 'running' + ? { ...agent, status: 'failed' } + : 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 +1049,20 @@ 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. + const backgroundAgents = + next === 'exited' && hasRunningBackgroundTask(session) + ? settleRunningAgents(session.backgroundAgents) + : session.backgroundAgents return { ...state, sessions: { ...state.sessions, [session.sessionId]: { ...session, + backgroundAgents, state: next, exitCode: exitCode ?? session.exitCode, exitReason: exitReason ?? session.exitReason From 0407050a32789013608a90526c47431d784357f0 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Wed, 25 Nov 2026 20:22:37 -0500 Subject: [PATCH 2/4] Show sub-agent approval prompts in the Subagents column and agent peek MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A background agent blocked on an approval only showed a ⚠ in the sidebar; the actionable prompt lived inside its Task card, usually far up the transcript. collectAgents now records each agent's own pending tool_use ids, and the Subagents column card (outside its disclosure) and the agent peek render the same approval card the chat does. The collapsed column's chip turns amber while any subagent is blocked. Questions (AskUserQuestion) point back to the chat instead of mounting a second autofocusing copy. Co-Authored-By: Claude Opus 5.5 --- .../components/AgentApprovalCards.tsx | 49 +++++++++++++++++++ src/renderer/components/AgentPeek.tsx | 13 +++++ src/renderer/components/ChatAgentColumn.tsx | 34 +++++++++++-- .../components/JsonClaudeAgentsPanel.tsx | 1 + .../components/agent-column-rows.test.ts | 1 + src/renderer/components/agent-column-rows.ts | 1 + src/shared/state/json-claude-agents.test.ts | 19 +++++++ src/shared/state/json-claude-agents.ts | 12 +++-- 8 files changed, 124 insertions(+), 6 deletions(-) create mode 100644 src/renderer/components/AgentApprovalCards.tsx diff --git a/src/renderer/components/AgentApprovalCards.tsx b/src/renderer/components/AgentApprovalCards.tsx new file mode 100644 index 000000000..c2d30370c --- /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 a4046cee7..58329a8aa 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 5f7168b5a..6e42136dc 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 && ( setPeekId(null)} diff --git a/src/renderer/components/agent-column-rows.test.ts b/src/renderer/components/agent-column-rows.test.ts index d75704d68..0b51428ac 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 0c7ae94f5..33efbcbb3 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 4afbf3784..97e5f5ad9 100644 --- a/src/shared/state/json-claude-agents.test.ts +++ b/src/shared/state/json-claude-agents.test.ts @@ -478,6 +478,25 @@ describe('collectAgents', () => { ) }) + 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 12c3638b3..0d1d00485 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[] @@ -245,7 +250,7 @@ export function collectAgents( 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 +259,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 +355,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 } : {}) } From 0ea731dfecbcdf39c71646a1682935f691a6b37b Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 26 Nov 2026 11:49:23 -0500 Subject: [PATCH 3/4] Address review: rebuild resumed agents' summaries, interrupted on exit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - collectAgents no longer reuses a settled summary once its lifecycle record has moved, so a SendMessage resume shows as running with its new steps and pending approvals instead of the pre-resume snapshot. - Tasks still running when the process exits settle as 'interrupted', not 'failed' — a sleep isn't an error. - AutoSleepMonitor documents that background work keeps a tab awake with no upper bound, and logs the skip once per stretch. - Note why the task key is resolved in both manager and reducer; narrow the peek's session id instead of passing ''. Co-Authored-By: Claude Opus 5.5 --- src/main/auto-sleep-monitor.ts | 22 ++++++- src/main/json-claude-manager.ts | 4 ++ .../components/JsonClaudeAgentsPanel.tsx | 4 +- src/shared/state/json-claude-agents.test.ts | 63 +++++++++++++++++++ src/shared/state/json-claude-agents.ts | 13 +++- src/shared/state/json-claude.test.ts | 4 +- src/shared/state/json-claude.ts | 8 ++- 7 files changed, 110 insertions(+), 8 deletions(-) diff --git a/src/main/auto-sleep-monitor.ts b/src/main/auto-sleep-monitor.ts index 3f827466e..271e6ef32 100644 --- a/src/main/auto-sleep-monitor.ts +++ b/src/main/auto-sleep-monitor.ts @@ -15,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 @@ -58,7 +61,24 @@ export class AutoSleepMonitor { // 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). - if (session && hasRunningBackgroundTask(session)) continue + // + // 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.ts b/src/main/json-claude-manager.ts index 7cac09ab8..a7103e57e 100644 --- a/src/main/json-claude-manager.ts +++ b/src/main/json-claude-manager.ts @@ -1676,6 +1676,10 @@ export class JsonClaudeManager implements ChatProvider { 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) diff --git a/src/renderer/components/JsonClaudeAgentsPanel.tsx b/src/renderer/components/JsonClaudeAgentsPanel.tsx index f40d3eccb..921632c20 100644 --- a/src/renderer/components/JsonClaudeAgentsPanel.tsx +++ b/src/renderer/components/JsonClaudeAgentsPanel.tsx @@ -259,9 +259,9 @@ export function JsonClaudeAgentsPanel({ )} - {peeked && ( + {peeked && focusedTabId && ( setPeekId(null)} diff --git a/src/shared/state/json-claude-agents.test.ts b/src/shared/state/json-claude-agents.test.ts index 97e5f5ad9..72f74cccc 100644 --- a/src/shared/state/json-claude-agents.test.ts +++ b/src/shared/state/json-claude-agents.test.ts @@ -478,6 +478,69 @@ 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([ diff --git a/src/shared/state/json-claude-agents.ts b/src/shared/state/json-claude-agents.ts index 0d1d00485..572bf7d86 100644 --- a/src/shared/state/json-claude-agents.ts +++ b/src/shared/state/json-claude-agents.ts @@ -244,8 +244,19 @@ 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[] = [] diff --git a/src/shared/state/json-claude.test.ts b/src/shared/state/json-claude.test.ts index 7f38b1ab5..bfc9f0fd1 100644 --- a/src/shared/state/json-claude.test.ts +++ b/src/shared/state/json-claude.test.ts @@ -1721,13 +1721,13 @@ describe('jsonClaudeReducer background agents', () => { expect(agents[TOOL_USE].completedAt).toBe(4000) }) - it('sessionStateChanged to exited marks running tasks failed', () => { + 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' } }) - expect(next.sessions[SID].backgroundAgents[TOOL_USE].status).toBe('failed') + expect(next.sessions[SID].backgroundAgents[TOOL_USE].status).toBe('interrupted') }) it('sessionStateChanged to a live state leaves running tasks alone', () => { diff --git a/src/shared/state/json-claude.ts b/src/shared/state/json-claude.ts index 2ec7ed36e..07d24ddf7 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -460,7 +460,9 @@ export interface JsonClaudeBackgroundAgent { * emits the same task_started/task_notification pair. Missing on * records from before the field existed. */ taskType?: string - status: 'running' | 'completed' | 'failed' + /** '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. */ @@ -945,7 +947,7 @@ function settleRunningAgents( for (const [key, agent] of Object.entries(agents)) { out[key] = agent.status === 'running' - ? { ...agent, status: 'failed' } + ? { ...agent, status: 'interrupted' } : agent } return out @@ -1052,6 +1054,8 @@ export function jsonClaudeReducer( // 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) From d9e1e005d8f31f15bb764342e6a5c924697c24a6 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 26 Nov 2026 11:54:30 -0500 Subject: [PATCH 4/4] Stop an interrupted task's elapsed clock at the process exit The exited state event now carries a timestamp, which the reducer stamps as completedAt on tasks it settles as interrupted. Without it the right panel and peek kept ticking the elapsed time of a dead agent. Co-Authored-By: Claude Opus 5.5 --- src/main/json-claude-manager.ts | 7 ++++++- src/shared/state/json-claude.test.ts | 4 +++- src/shared/state/json-claude.ts | 18 +++++++++++++----- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/main/json-claude-manager.ts b/src/main/json-claude-manager.ts index a7103e57e..ef540fe57 100644 --- a/src/main/json-claude-manager.ts +++ b/src/main/json-claude-manager.ts @@ -2241,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/shared/state/json-claude.test.ts b/src/shared/state/json-claude.test.ts index bfc9f0fd1..c54960190 100644 --- a/src/shared/state/json-claude.test.ts +++ b/src/shared/state/json-claude.test.ts @@ -1725,9 +1725,11 @@ describe('jsonClaudeReducer background agents', () => { const state = launch(seedSession(initialJsonClaude)) const next = jsonClaudeReducer(state, { type: 'jsonClaude/sessionStateChanged', - payload: { sessionId: SID, state: 'exited' } + 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', () => { diff --git a/src/shared/state/json-claude.ts b/src/shared/state/json-claude.ts index 07d24ddf7..b71c2abc0 100644 --- a/src/shared/state/json-claude.ts +++ b/src/shared/state/json-claude.ts @@ -619,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 } } | { @@ -938,16 +941,21 @@ function patchBackgroundAgent( } } -// No completedAt: the reducer runs in main and every renderer, so a -// Date.now() here would diverge between mirrors. +// 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 + 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' } + ? { + ...agent, + status: 'interrupted', + ...(timestamp !== undefined ? { completedAt: timestamp } : {}) + } : agent } return out @@ -1058,7 +1066,7 @@ export function jsonClaudeReducer( // off — usually by a sleep the user chose. const backgroundAgents = next === 'exited' && hasRunningBackgroundTask(session) - ? settleRunningAgents(session.backgroundAgents) + ? settleRunningAgents(session.backgroundAgents, event.payload.timestamp) : session.backgroundAgents return { ...state,