The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop interrupted sessions and stale history from pinning subagent rows
Brooklyn Nicholsonac30353148cd
diff --git a/apps/desktop/src/app/agents/index.tsx b/apps/desktop/src/app/agents/index.tsxindex 36034712525..ec1207731d0 100644--- a/apps/desktop/src/app/agents/index.tsx+++ b/apps/desktop/src/app/agents/index.tsx@@ -14,8 +14,8 @@ import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'import {$subagentsBySession,- allSubagents,buildSubagentTree,+ subagentsForPanel,type SubagentNode,type SubagentStatus,type SubagentStreamEntry@@ -83,11 +83,17 @@ interface AgentsViewProps {export function AgentsView({ onClose }: AgentsViewProps) {const { t } = useI18n()const subagentsBySession = useStore($subagentsBySession)-- // Aggregate every session, matching the status-bar indicator — a subagent- // running in a background session must still be visible here, or the two- // desync ("Agents N running" vs an empty tree).- const tree = useMemo(() => buildSubagentTree(allSubagents(subagentsBySession)), [subagentsBySession])+ const activeSessionId = useStore($activeSessionId)++ // Aggregate every session for live work, terminal rows only for the+ // session the user is in — matching the status-bar indicator, so a subagent+ // running in a background session stays visible (the two can never desync,+ // "Agents N running" vs an empty tree) while finished history from inactive+ // sessions no longer accumulates forever (#75505).+ const tree = useMemo(+ () => buildSubagentTree(subagentsForPanel(subagentsBySession, activeSessionId)),+ [subagentsBySession, activeSessionId]+ )return (<Panel closeLabel={t.agents.close} onClose={onClose}>diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-subagent-interrupt.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-subagent-interrupt.test.tsnew file mode 100644index 00000000000..29b673cbca1--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-subagent-interrupt.test.ts@@ -0,0 +1,72 @@+import { type GatewayEvent } from '@hermes/shared'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $subagentsBySession, clearSessionSubagents } from '@/store/subagents'++import { handleToolEvent } from './tools'+import type { GatewayEventContext } from './types'++// #75505 root cause 2: a Stop interrupts the parent TURN, not the children.+// A delegation finishing in the background fires `subagent.complete` after the+// interrupt; the SUBAGENT_EVENT_TYPES guard dropped it and the row spun+// 'running' forever. Terminal completions must land; live progress must not.+const sid = 'stopped-session'++function subagentEvent(type: string, payload: Record<string, unknown>): GatewayEvent {+ return { type, session_id: sid, seq: 1, payload } as GatewayEvent+}++function deliver(event: GatewayEvent, interrupted: boolean) {+ const nativeSubagentSessionsRef = { current: new Set<string>([sid]) }++ return handleToolEvent({+ event,+ payload: event.payload,+ sessionId: sid,+ occurredAt: 1,+ isActiveEvent: false,+ deps: {+ flushQueuedDeltas: vi.fn(),+ nativeSubagentSessionsRef,+ sessionInterrupted: () => interrupted,+ updateSessionState: vi.fn(),+ upsertToolCall: vi.fn()+ }+ } as unknown as GatewayEventContext)+}++describe('subagent events across an interrupted session', () => {+ beforeEach(() => {+ deliver(subagentEvent('subagent.start', { status: 'running', subagent_id: 'sa-1', goal: 'audit files', task_index: 0 }), false)+ })++ afterEach(() => {+ clearSessionSubagents(sid)+ $subagentsBySession.set({})+ })++ it('a terminal subagent.complete still lands after Stop instead of leaving the row running forever', () => {+ deliver(subagentEvent('subagent.complete', { status: 'completed', subagent_id: 'sa-1', summary: 'done', task_index: 0 }), true)++ const row = $subagentsBySession.get()[sid]?.[0]+ expect(row?.status).toBe('completed')+ expect(row?.summary).toBe('done')+ })++ it('live progress and non-terminal completions stay suppressed after Stop', () => {+ deliver(subagentEvent('subagent.progress', { status: 'running', subagent_id: 'sa-1', text: 'still going', task_index: 0 }), true)+ deliver(subagentEvent('subagent.complete', { status: 'running', subagent_id: 'sa-1', task_index: 0 }), true)++ const row = $subagentsBySession.get()[sid]?.[0]+ expect(row?.status).toBe('running')+ expect(row?.stream).toHaveLength(0)+ })++ it('a completion carrying no status stays behind the interrupted guard (fail closed, no zombie repaint)', () => {+ deliver(subagentEvent('subagent.complete', { subagent_id: 'sa-1', task_index: 0 }), true)++ // A payload without a recognized terminal status is not trusted past the+ // interrupt; the pane-gated subagent.list reconcile remains its fallback.+ expect($subagentsBySession.get()[sid]?.[0]?.status).toBe('running')+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.tsindex b96f83e091e..e28ccd4ba64 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts@@ -6,7 +6,7 @@ import { refreshBackgroundProcesses } from '@/store/composer-status'import { flashPetActivity, setPetActivity } from '@/store/pet'import { recordPreviewArtifact, reofferPreviewArtifact } from '@/store/preview-status'import { $sessionStates, storedSessionIdForRuntimeId } from '@/store/session-states'-import { pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'+import { isTerminalSubagentCompletion, pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'import { reportMcpToolResult } from '@/store/suggestion-providers/repair'import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'import { restoreSessionTodosFromSnapshot } from '@/store/todos'@@ -156,7 +156,16 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {}if (SUBAGENT_EVENT_TYPES.has(event.type)) {- if (sessionId && payload && !sessionInterrupted(sessionId)) {+ // A Stop interrupts the parent TURN, not the children: a delegation can+ // still be finishing in the background, and its `subagent.complete` is the+ // only thing that terminalizes the row. Dropping it leaves a permanently+ // 'running' spinner (#75505). Terminal completions are accepted past the+ // interrupt; only live progress keeps the guard, so a stopped turn's+ // late mid-flight frames still can't repaint its stream. upsertSubagent's+ // retired-id and terminal-status guards make a stale completion a no-op.+ const acceptWhileInterrupted = isTerminalSubagentCompletion(event.type, payload)++ if (sessionId && payload && (!sessionInterrupted(sessionId) || acceptWhileInterrupted)) {if (!nativeSubagentSessionsRef.current.has(sessionId)) {pruneDelegateFallbackSubagents(sessionId)}diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsxindex 063def2c469..7e33f3c3126 100644--- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx+++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx@@ -140,16 +140,24 @@ export function useStatusbarItems({const primaryTurnStartedAt = useStore($turnStartedAt)// The indicator must speak the same scope as the Spawn-tree panel it opens:- // every session's subagents, never background system actions. Only two- // COUNTS are read, so select scalars — a whole-map `useStore` re-ran this- // hook (rebuilding all ~9 statusbar items) on every subagent progress tick- // in ANY session, including background ones.+ // running/queued from every session (never background system actions), plus+ // terminal rows only for the session the user is in — the scope+ // `subagentsForPanel` derives, so the count and the tree can never disagree+ // and finished history from inactive sessions stops accumulating (#75505).+ // Only two COUNTS are read, so select scalars — a whole-map `useStore` re-ran+ // this hook (rebuilding all ~9 statusbar items) on every subagent progress+ // tick in ANY session, including background ones.const subagentsRunning = useStoreSelector($subagentsBySession, bySession =>Object.values(bySession).reduce((sum, items) => sum + activeSubagentCount(items), 0))+ // Terminal rows only from the session the user is in — the panel drops other+ // sessions' finished history (#75505), so the count the indicator shows must+ // not resurrect it. Live running/queued rows stay cross-session above.const subagentsFailed = useStoreSelector($subagentsBySession, bySession =>- Object.values(bySession).reduce((sum, items) => sum + failedSubagentCount(items), 0)+ Object.entries(bySession)+ .filter(([sid]) => sid === primaryActiveSessionId)+ .reduce((sum, [, items]) => sum + failedSubagentCount(items), 0))// Backend truth for the free-tier chip. Refreshed on the ambient statusdiff --git a/apps/desktop/src/store/subagents.test.ts b/apps/desktop/src/store/subagents.test.tsindex e2b538c22ef..20ecd19f8dc 100644--- a/apps/desktop/src/store/subagents.test.ts+++ b/apps/desktop/src/store/subagents.test.ts@@ -3,13 +3,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import {$subagentsBySession,activeSubagentCount,- allSubagents,buildSubagentTree,clearSessionSubagents,failedSubagentCount,+ isTerminalSubagentCompletion,pruneDelegateFallbackSubagents,pruneFinishedSessionSubagents,reconcileSubagentSnapshot,+ subagentsForPanel,upsertSubagent} from './subagents'@@ -28,6 +29,29 @@ describe('subagent store', () => {expect(item?.summary).toBe('done')})+ it('accepts a terminal subagent.complete for an interrupted session, and still drops live progress', () => {+ upsertSubagent('stopped', { goal: 'finishing', status: 'running', subagent_id: 'sa-1', task_index: 0 })++ // Stop interrupts the turn, not the children: the completion must land.+ expect(isTerminalSubagentCompletion('subagent.complete', { status: 'completed' })).toBe(true)+ expect(isTerminalSubagentCompletion('subagent.complete', { status: 'timeout' })).toBe(true)+ expect(isTerminalSubagentCompletion('subagent.complete', { status: 'cancelled' })).toBe(true)+ upsertSubagent(+ 'stopped',+ { status: 'completed', subagent_id: 'sa-1', task_index: 0, summary: 'done after Stop' },+ false,+ 'subagent.complete'+ )+ expect(listFor('stopped')[0]?.status).toBe('completed')+ expect(listFor('stopped')[0]?.summary).toBe('done after Stop')++ // Non-terminal completions and live progress keep the interrupted guard.+ expect(isTerminalSubagentCompletion('subagent.complete', { status: 'running' })).toBe(false)+ expect(isTerminalSubagentCompletion('subagent.complete', {})).toBe(false)+ expect(isTerminalSubagentCompletion('subagent.progress', { status: 'running' })).toBe(false)+ expect(isTerminalSubagentCompletion('subagent.start', { status: 'completed' })).toBe(false)+ })+it('keeps completed children retired across turn pruning, late frames, and roster refreshes', () => {const finished = { subagent_id: 'finished', goal: 'Finished task', status: 'running' }const live = { subagent_id: 'live', goal: 'Background task', status: 'queued' }@@ -176,24 +200,34 @@ describe('subagent store', () => {})// Contract: the status-bar "Agents" indicator and the Spawn-tree panel read- // the same scope — every session's subagents — so a count can never point at- // an empty tree (the desync behind "Agents (N)" vs "No live subagents").- it('counts running/failed across every session, matching the aggregated tree', () => {+ // the same scope — every session's LIVE subagents plus terminal rows only+ // from the session the user is in — so a count can never point at an empty+ // tree, and finished history from inactive sessions stops accumulating (#75505).+ it('keeps live rows from every session, terminal rows only for the session in view', () => {upsertSubagent('s1', { goal: 'a', status: 'running', subagent_id: 'a', task_index: 0 })upsertSubagent('s1', { goal: 'b', status: 'failed', subagent_id: 'b', task_index: 1 })upsertSubagent('s2', { goal: 'c', status: 'running', subagent_id: 'c', task_index: 0 })upsertSubagent('s2', { goal: 'd', status: 'failed', subagent_id: 'd', task_index: 1 })- const flat = allSubagents($subagentsBySession.get())+ const active = 's1'+ const panel = subagentsForPanel($subagentsBySession.get(), active)const indicatorRunning = Object.values($subagentsBySession.get()).reduce((n, l) => n + activeSubagentCount(l), 0)- const indicatorFailed = Object.values($subagentsBySession.get()).reduce((n, l) => n + failedSubagentCount(l), 0)- const tree = buildSubagentTree(flat)+ const indicatorFailed = Object.entries($subagentsBySession.get())+ .filter(([sid]) => sid === active)+ .reduce((n, [, l]) => n + failedSubagentCount(l), 0)- // The active-session-only filter would have reported 1/1 here, not 2/2.+ // The active-session-only filter would have reported 1/1 here, not 2/1.expect(indicatorRunning).toBe(2)- expect(indicatorFailed).toBe(2)- expect(tree).toHaveLength(4)- expect(indicatorRunning + indicatorFailed).toBe(tree.length)+ expect(indicatorFailed).toBe(1)+ expect(panel.map(item => item.id)).toEqual(['a', 'b', 'c'])+ expect(indicatorRunning + indicatorFailed).toBe(panel.length)+ })++ it('an inactive session keeps only its live rows in the panel scope', () => {+ upsertSubagent('past', { goal: 'history', status: 'completed', subagent_id: 'h', task_index: 0 })+ upsertSubagent('past', { goal: 'still running', status: 'running', subagent_id: 'live', task_index: 1 })++ expect(subagentsForPanel($subagentsBySession.get(), 'other').map(item => item.id)).toEqual(['live'])})it('clears one session without touching another', () => {diff --git a/apps/desktop/src/store/subagents.ts b/apps/desktop/src/store/subagents.tsindex 3bd1652b8bc..d1915d6f78b 100644--- a/apps/desktop/src/store/subagents.ts+++ b/apps/desktop/src/store/subagents.ts@@ -397,6 +397,20 @@ export function upsertSubagent(sid: string, payload: SubagentPayload, createIfMisetSessionSubagents(sid, list, nextList)}+// Statuses that end a subagent run. The store's asStatus normalizes the last+// three to failed/interrupted, so the event path treats them as terminal too.+const SUBAGENT_TERMINAL_STATUSES = new Set(['completed', 'failed', 'interrupted', 'timeout', 'error', 'cancelled', 'canceled'])++/** True only for a `subagent.complete` carrying a status that ends the run —+ * the one event the interrupted-session guard in the message-stream must let+ * through (#75505). */+export const isTerminalSubagentCompletion = (+ eventType: string,+ payload: Record<string, unknown> | undefined | null+): boolean =>+ eventType === 'subagent.complete' &&+ SUBAGENT_TERMINAL_STATUSES.has(typeof payload?.status === 'string' ? payload.status : '')+export function buildSubagentTree(items: readonly SubagentProgress[]): SubagentNode[] {const nodes = new Map<string, SubagentNode>()@@ -428,6 +442,20 @@ export function buildSubagentTree(items: readonly SubagentProgress[]): SubagentNexport const activeSubagentCount = (items: readonly SubagentProgress[]) =>items.filter(item => item.status === 'queued' || item.status === 'running').length+/** Spawn-tree panel scope (#75505): running/queued rows from EVERY session —+ * cross-session visibility is the point, a background session's live work+ * must stay visible — but terminal rows only for the session the user is in.+ * The status-bar indicator counts the same way, so the count and the tree it+ * opens can never disagree, while finished history from inactive sessions+ * stops accumulating forever. */+export const subagentsForPanel = (+ bySession: Record<string, SubagentProgress[]>,+ activeSessionId: string | null+): SubagentProgress[] =>+ Object.entries(bySession).flatMap(([sid, items]) =>+ sid === activeSessionId ? items : items.filter(item => item.status === 'running' || item.status === 'queued')+ )+export const failedSubagentCount = (items: readonly SubagentProgress[]) =>items.filter(item => item.status === 'failed' || item.status === 'interrupted').length