Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 后台 Subagent 卡片状态改由 subagent_runs 判定 (#5124)
Dash006879954fa4
diff --git a/apps/desktop/src/renderer/__tests__/subagentDurableStatusRenderItems.test.ts b/apps/desktop/src/renderer/__tests__/subagentDurableStatusRenderItems.test.tsnew file mode 100644index 0000000000..f14669e0cc--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/subagentDurableStatusRenderItems.test.ts@@ -0,0 +1,76 @@+/**+ * subagentDurableStatusRenderItems.test.ts+ * ---------------------------------------------------------------------------+ * A running background Agent card must stay visible in the chat, not be folded+ * into the finished work group, even when the launch receipt's wording is one+ * the text matcher does not recognise (Claude Code 2.1.280 changed it once).+ * The host's `subagent_runs` status is the structural source that decides.+ */++import { describe, expect, it } from 'vitest';+import { buildSubagentRunStatusIndex } from '@cindy/maker-shared/agent-task';++import { buildRenderItems, groupWorkRuns } from '../components/chat/MessageStream';+import type { AgentTaskUpdate, ChatMessage } from '@/lib/makerChatStore';++const at = (seconds: number): string =>+ new Date(Date.UTC(2026, 8, 26, 12, 0, seconds)).toISOString();++const messages: ChatMessage[] = [+ { clientId: 'u1', role: 'user', content: '帮我调研一下', createdAt: at(0) },+ {+ clientId: 'agent-call',+ role: 'tool_use',+ content: '',+ toolUseId: 'toolu_bg',+ toolName: 'Agent',+ toolInput: { description: 'background research', prompt: 'research' },+ createdAt: at(1),+ },+ {+ clientId: 'agent-receipt',+ role: 'tool_result',+ content: 'Background agent queued (a receipt wording nobody has matched yet)',+ toolUseId: 'toolu_bg',+ createdAt: at(2),+ },+ {+ clientId: 'a1',+ role: 'assistant',+ content: '已经派出一个后台调研,完成后会通知我。',+ createdAt: at(3),+ turnCompleted: true,+ },+];++const runningUpdate: AgentTaskUpdate = {+ provider: 'claude-code',+ taskId: 'agent-1',+ parentToolUseId: 'toolu_bg',+ status: 'running',+};+const taskUpdates = new Map<string, AgentTaskUpdate>([+ ['agent-1', runningUpdate],+ ['toolu_bg', runningUpdate],+]);++function topLevelAgentTask(items: ReturnType<typeof groupWorkRuns>) {+ return items.find((item) => item.type === 'agent_task');+}++describe('buildRenderItems — durable Subagent status', () => {+ it('keeps a running background Agent visible when subagent_runs says it is running', () => {+ const { items } = buildRenderItems(messages, taskUpdates, undefined, {+ subagentRunStatuses: buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu_bg', logicalAgentId: 'agent-1', status: 'running' },+ ]),+ });+ const card = topLevelAgentTask(groupWorkRuns(items, false));+ expect(card).toMatchObject({ type: 'agent_task', durableStatus: 'running' });+ });++ it('without the durable record an unknown receipt still reads as finished work (fallback path)', () => {+ const { items } = buildRenderItems(messages, taskUpdates);+ expect(topLevelAgentTask(groupWorkRuns(items, false))).toBeUndefined();+ });+});diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex c06ff808f3..b25ed01710 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';import {deriveAgentTaskStatus,formatAgentTaskTitle,+ type AgentTaskStatus,type AgentTaskTerminalStatus,} from '@cindy/maker-shared/agent-task';@@ -56,6 +57,8 @@ interface AgentTaskCardProps {update?: AgentTaskUpdate;result?: string;persistedStatus?: AgentTaskTerminalStatus;+ /** Host `subagent_runs` status for this call; see deriveAgentTaskStatus. */+ durableStatus?: AgentTaskStatus;/*** subagent-model-chip: 子代理实际跑的模型 raw id,由 MessageStream 用* parentToolUseId→model 映射(从子消息 agentMeta 反查)解析后传入,作为@@ -162,6 +165,7 @@ export function AgentTaskCard({update,result,persistedStatus,+ durableStatus,subagentModel,sessionId,sessionAgentKind,@@ -241,6 +245,7 @@ export function AgentTaskCard({? (update?.status ?? historyFileStatus ?? (result ? 'completed' : 'running')): deriveAgentTaskStatus(update?.status, result, {persistedStatus,+ durableStatus,resultIsLaunchReceipt:subagentSpawnReceiptName(toolCall?.toolName, toolCall?.toolInput, result) !== undefined|| subagentSpawnResultIndicatesRunning(toolCall?.toolName, result),@@ -277,6 +282,11 @@ export function AgentTaskCard({const spawnReceiptName = subagentSpawnReceiptName(toolCall?.toolName, toolCall?.toolInput, result);const resultIsPiLaunchReceipt = isPiDurableSubagent&& subagentSpawnResultIndicatesRunning(toolCall?.toolName, result);+ // Claude's async receipt is internal metadata addressed to the model (agentId,+ // output file); it is never the task's summary.+ const resultIsClaudeLaunchReceipt = !isPiDurableSubagent+ && provider === 'claude-code'+ && subagentSpawnResultIndicatesRunning(toolCall?.toolName, result);// 判据与抑制规则同 maker-shared 的 buildAgentTaskCardModel:有 live update 时不显示// 「已启动」句子(title + 状态已表达),否则 codex 卡会比 Claude 卡多一行冗余文案。// PI/Claude detached tool_result 也是启动回执;终态卡必须优先显示后续 durable@@ -287,7 +297,9 @@ export function AgentTaskCard({: t('chat.agentTask.subagentStarted', { name: formatAgentTaskTitle(provider, spawnReceiptName) })): resultIsPiLaunchReceipt? detailText(update?.summary, result)- : detailText(result, update?.summary);+ : resultIsClaudeLaunchReceipt+ ? detailText(update?.summary)+ : detailText(result, update?.summary);const piResultNeedsCollapse = Boolean(isPiDurableSubagent&& summarydiff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 60075a4bea..b06a8d7ad3 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -78,7 +78,11 @@ import {} from './markdownImageTargets';// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。-import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';+import {+ isAgentTaskToolName,+ lookupSubagentRunStatus,+ type SubagentRunStatusIndex,+} from '@cindy/maker-shared/agent-task';import type {AgentTaskUpdate,@@ -439,6 +443,8 @@ interface MessageStreamProps {/** The task shell remains, but all prior message content was intentionally cleared. */historyCleared?: boolean;taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;+ /** Host `subagent_runs` status of this task's Subagents (local tasks only). */+ subagentRunStatuses?: SubagentRunStatusIndex;/** Kept for API compatibility. v2 — no longer threaded into render items* (AgentActionsBlock + ThinkingCard manage their own per-block expand* state via useExpandedBlockMemory). The session-level "is streaming"@@ -1463,6 +1469,8 @@ export function buildRenderItems(/** Keep the stored preparation report out of its own task's visible timeline. */cindyMakeSessionId?: string;cindyMakeCompletionInComposer?: boolean;+ /** Durable Subagent status; a terminal record outranks the paired result text. */+ subagentRunStatuses?: SubagentRunStatusIndex;},): {items: RenderItem[];@@ -1957,6 +1965,11 @@ export function buildRenderItems(j++;}const update = findTaskUpdate(taskUpdates, msg);+ const durableStatus = lookupSubagentRunStatus(+ opts?.subagentRunStatuses,+ msg.toolUseId,+ update,+ );if (msg.toolUseId) renderedTaskKeys.add(msg.toolUseId);if (update?.taskId) renderedTaskKeys.add(update.taskId);if (update?.parentToolUseId) renderedTaskKeys.add(update.parentToolUseId);@@ -1966,6 +1979,7 @@ export function buildRenderItems(toolCall: msg,update,...(msg.agentTaskStatus ? { persistedStatus: msg.agentTaskStatus } : {}),+ ...(durableStatus ? { durableStatus } : {}),...(result !== undefined && !shouldHideToolResult(toolName, result) ? { result } : {}),...(resultTsMs !== undefined ? { resultTsMs } : {}),});@@ -2246,10 +2260,12 @@ export function buildRenderItems(continue;}seenTaskIds.add(update.taskId);+ const durableStatus = lookupSubagentRunStatus(opts?.subagentRunStatuses, undefined, update);const item: AgentTaskRenderItem = {type: 'agent_task',key: `task-update-${primaryKey}`,update,+ ...(durableStatus ? { durableStatus } : {}),};const itemMs = renderItemStartMs(item);if (itemMs === null) {@@ -2300,6 +2316,7 @@ export function buildCachedRenderItems(opts?.turnChangeSets,opts?.workingDir,opts?.botSessionId,+ opts?.subagentRunStatuses,];const index = recentRenderProjections.findIndex((entry) =>entry.dependencies.every((value, i) => Object.is(value, dependencies[i])),@@ -2518,6 +2535,7 @@ function renderWorkGroupChild(update={item.update}result={item.result}persistedStatus={item.persistedStatus}+ durableStatus={item.durableStatus}sessionAgentKind={props.agentKind}{...(props.sessionId ? { sessionId: props.sessionId } : {})}subagentModel={@@ -2584,6 +2602,7 @@ export function MessageStream({historyLoaded,historyCleared = false,taskUpdates,+ subagentRunStatuses,isSessionStreaming = false,continuationTurnClientId = null,continuationInFlightProjectionCapability = 'unknown',@@ -2839,6 +2858,7 @@ export function MessageStream({markdownImageTargetCache: markdownImageTargetCacheRef.current,cindyMakeSessionId,cindyMakeCompletionInComposer,+ subagentRunStatuses,});if (historyView && historySnapshot?.ready) {const results = new Map(built.singleResultMap);@@ -2864,6 +2884,7 @@ export function MessageStream({markdownImageTargetCache: markdownImageTargetCacheRef.current,cindyMakeSessionId,cindyMakeCompletionInComposer,+ subagentRunStatuses,});for (const [key, value] of chunk.singleResultMap) results.set(key, value);return groupWorkRuns(chunk.items, isSessionStreaming);@@ -2919,6 +2940,7 @@ export function MessageStream({handoff,isSessionStreaming,taskUpdates,+ subagentRunStatuses,ghostCardSnapshot,historyLoaded,hasMoreMessages,@@ -5963,6 +5985,7 @@ export function MessageStream({update={item.update}result={item.result}persistedStatus={item.persistedStatus}+ durableStatus={item.durableStatus}sessionAgentKind={agentKind}{...(sessionId ? { sessionId } : {})}subagentModel={diff --git a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts b/apps/desktop/src/renderer/components/chat/messageWorkGroups.tsindex 55a9de45b3..14f4a8404c 100644--- a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts+++ b/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts@@ -3,6 +3,7 @@ import {deriveAgentTaskStatus,subagentSpawnReceiptName,subagentSpawnResultIndicatesRunning,+ type AgentTaskStatus,type AgentTaskTerminalStatus,} from '@cindy/maker-shared/agent-task';import {@@ -51,6 +52,8 @@ export type AgentTaskRenderItem = {update?: AgentTaskUpdate;result?: string;persistedStatus?: AgentTaskTerminalStatus;+ /** Host `subagent_runs` status for this call (local tasks); see deriveAgentTaskStatus. */+ durableStatus?: AgentTaskStatus;/** 对应 tool_result 的 createdAt(ms)。历史会话没有 live taskUpdates 时,item 的结束* 时间只能靠它 —— 否则跑了半小时以上的 Agent/Task 会让紧随其后的最终答复被空洞守卫* 误判(#676 review)。与 tool_segment 的 resultTsMap 同源。 */@@ -188,6 +191,7 @@ function isRunningAgentTask(it: RenderItem): boolean {if (it.type !== 'agent_task') return false;const status = deriveAgentTaskStatus(it.update?.status, it.result, {persistedStatus: it.persistedStatus,+ durableStatus: it.durableStatus,resultIsLaunchReceipt:subagentSpawnReceiptName(it.toolCall?.toolName, it.toolCall?.toolInput, it.result) !==undefined || subagentSpawnResultIndicatesRunning(it.toolCall?.toolName, it.result),diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 6d57236bbc..4bd9034263 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -40,6 +40,7 @@ import {} from '@cindy/model-providers';import type { SubagentRunsListResponse } from '@cindy/maker-shared/subagent-workspace';import { useProportionalWidth } from '@/hooks/useProportionalWidth';+import { useSubagentRunStatusIndex } from '@/hooks/useSubagentRunStatusIndex';import {Activity,AlertCircle,@@ -1056,6 +1057,13 @@ export function CCAgentSessionView({// 冷启动 / bootstrap 竞态期间宁可暂时禁用系统文件打开,也不能把被控端 file:// 交给控制端。const rightSidebarDeviceLinkDeviceId =remoteDeviceId ?? session?.deviceLinkDeviceId ?? (session ? null : undefined);+ // Durable Subagent status for the chat cards. Wait until ownership resolves:+ // an unresolved task must not read this machine's store for a remote task.+ const subagentRunStatuses = useSubagentRunStatusIndex({+ sessionId,+ deviceId: rightSidebarDeviceLinkDeviceId,+ enabled: rightSidebarDeviceLinkDeviceId !== undefined,+ });/*** Does this task own durable Pi Subagent runs?@@ -4740,6 +4748,7 @@ export function CCAgentSessionView({historyLoaded={historyLoaded}historyCleared={Boolean(session?.clearedAt)}taskUpdates={taskUpdates}+ subagentRunStatuses={subagentRunStatuses}isSessionStreaming={isStreaming}continuationTurnClientId={continuationTurnClientId}continuationInFlightProjectionCapability={continuationInFlightProjectionCapability}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsxindex 37495aac69..0fc936f642 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx@@ -53,6 +53,7 @@ import { Spinner } from '@/components/ui/spinner';import { Tip } from '@/components/ui/tooltip';import { isSidebarWindow } from '@/lib/sidebarWindow';import { getSessionDeviceId, useRemoteDevices } from '@/features/device-link/remoteProjectsStore';+import { useSubagentRunStatusIndex } from '@/hooks/useSubagentRunStatusIndex';import { makerChatStore, EMPTY_TASK_UPDATES } from '@/lib/makerChatStore';import type { AgentTaskUpdate, ChatMessage } from '@/lib/makerChatStore';import {@@ -551,6 +552,11 @@ export function BackgroundTasksBody({// 本机会话恒 'local',零开销;断连翻转的那次重跑失败降级空表,无害。const remoteDevices = useRemoteDevices();const sessionDeviceId = sessionId ? getSessionDeviceId(sessionId) : undefined;+ const subagentRunStatuses = useSubagentRunStatusIndex({+ sessionId,+ deviceId: sessionDeviceId,+ enabled: visible,+ });const deviceConnectivity = sessionDeviceId? `${sessionDeviceId}:${remoteDevices.find((d) => d.deviceId === sessionDeviceId)?.connected ? '1' : '0'@@ -603,8 +609,9 @@ export function BackgroundTasksBody({messages: inputs.messages as unknown as readonly Message[],taskUpdates: inputs.taskUpdates,isSessionStreaming: inputs.isStreaming,+ subagentRunStatuses,}),- [inputs],+ [inputs, subagentRunStatuses],);// 历史 workflow 行的终态修正:workflow 的 tool_result 是启动回执(失败也存在),diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.tsindex e0afc85803..947fb883a1 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts@@ -7,6 +7,8 @@import { describe, expect, it } from 'vitest';+import { buildSubagentRunStatusIndex } from '@cindy/maker-shared/agent-task';+import type { Message } from '@/lib/ccAgent.types';import type { AgentTaskUpdate } from '@/lib/makerChatStore';@@ -405,6 +407,74 @@ describe('listSessionTasks 历史条目状态推导', () => {});});+describe('listSessionTasks 共用 subagent_runs 状态', () => {+ const receipt = 'Background agent launched (receipt wording the text matcher does not know)';++ it('durable running 让未知措辞的启动回执不再把运行中的 Agent 判成 completed', () => {+ const { running, completed } = listSessionTasks({+ messages: [+ toolUse('c1', 'toolu-bg', 'Agent', { description: 'bg agent' }),+ toolResult('r1', 'toolu-bg', receipt),+ ],+ taskUpdates: aliasedMap(makeUpdate({ taskId: 'agent-1', parentToolUseId: 'toolu-bg' })),+ isSessionStreaming: false,+ subagentRunStatuses: buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu-bg', logicalAgentId: 'agent-1', status: 'running' },+ ]),+ });+ expect(completed).toHaveLength(0);+ expect(running[0]).toMatchObject({ title: 'bg agent', status: 'running' });+ });++ it('无 live update 的历史行采用 durable 终态,不再一律涂成 completed', () => {+ const { completed } = listSessionTasks({+ messages: [+ toolUse('c1', 'toolu-bg', 'Agent', { description: 'bg agent' }),+ toolResult('r1', 'toolu-bg', receipt),+ ],+ taskUpdates: undefined,+ isSessionStreaming: false,+ subagentRunStatuses: buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu-bg', status: 'failed' },+ ]),+ });+ expect(completed[0]).toMatchObject({ status: 'failed' });+ });++ it('调用滑出消息窗口的孤儿 update 同样采用 durable 终态,不再留在「运行中」', () => {+ const update = makeUpdate({ taskId: 'agent-1', parentToolUseId: 'toolu-gone' });+ const input = {+ messages: [],+ taskUpdates: aliasedMap(update),+ subagentRunStatuses: buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu-gone', status: 'failed' },+ ]),+ };+ // 空闲态:终态孤儿是陈旧残留,不列出。+ expect(listSessionTasks({ ...input, isSessionStreaming: false })).toEqual({+ running: [],+ completed: [],+ });+ // 运行中:作为 LIVE 占位列在终态区。+ const live = listSessionTasks({ ...input, isSessionStreaming: true });+ expect(live.running).toHaveLength(0);+ expect(live.completed[0]).toMatchObject({ taskId: 'agent-1', status: 'failed' });+ });++ it('后台 Bash 孤儿不查 subagent_runs', () => {+ const update = makeUpdate({ taskId: 'bash-1', parentToolUseId: 'toolu-b', taskType: 'local_bash' });+ const { running } = listSessionTasks({+ messages: [],+ taskUpdates: aliasedMap(update),+ isSessionStreaming: false,+ subagentRunStatuses: buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu-b', status: 'completed' },+ ]),+ });+ expect(running[0]).toMatchObject({ taskId: 'bash-1', status: 'running' });+ });+});+// ---------------------------------------------------------------------------// 后台 Bash 识别// ---------------------------------------------------------------------------diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.tsindex 43c77eb495..71278953f8 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts@@ -19,8 +19,11 @@import {deriveAgentTaskStatus,isAgentTaskToolName,+ lookupSubagentRunStatus,+ normalizeAgentTaskTerminalStatus,subagentSpawnReceiptName,subagentSpawnResultIndicatesRunning,+ type SubagentRunStatusIndex,} from '@cindy/maker-shared/agent-task';import type { Message } from '@/lib/ccAgent.types';@@ -263,8 +266,10 @@ export function listSessionTasks(input: {messages: readonly Message[];taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined;isSessionStreaming: boolean;+ /** Host `subagent_runs` status; same source and precedence as the chat cards. */+ subagentRunStatuses?: SubagentRunStatusIndex;}): SessionTaskLists {- const { messages, taskUpdates, isSessionStreaming } = input;+ const { messages, taskUpdates, isSessionStreaming, subagentRunStatuses } = input;// Pass 0:tool_result 的 toolUseId 查表(与 buildRenderItems Pass 0 同口径)。// 同时留住结果内容引用:历史 workflow(update 已随重载清空)从结果文本里@@ -334,15 +339,20 @@ export function listSessionTasks(input: {// 的死任务(同步 Task 没有启动回执,永远不会有结果),断言 running 会让它// 永久转圈且无任何收口路径,按 stopped(被中断)呈现。const resultText = typeof resultContent === 'string' ? resultContent : undefined;+ const durableStatus = isWorkflowTool+ ? undefined+ : lookupSubagentRunStatus(subagentRunStatuses, toolUseId, update);const status: AgentTaskStatus = isWorkflowTool? update?.status ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped'): update? deriveAgentTaskStatus(update.status, resultText, {+ durableStatus,resultIsLaunchReceipt:subagentSpawnReceiptName(toolName, toolInput, resultText) !== undefined|| subagentSpawnResultIndicatesRunning(toolName, resultText),})- : (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped');+ : normalizeAgentTaskTerminalStatus(durableStatus)+ ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped');const provider: SessionTaskItem['provider'] =update?.provider ?? (toolName.startsWith('collab:') ? 'codex' : 'claude-code');@@ -375,7 +385,14 @@ export function listSessionTasks(input: {const seenTaskIds = new Set<string>();let orphanOrder = messages.length;for (const update of taskUpdates.values()) {- if (!isSessionStreaming && update.status !== 'running') continue;+ // 与配对行同一状态口径:subagent_runs 的终态收口 stale running(调用滑出+ // 消息窗口时,聊天里的孤儿卡同样采用它)。后台 Bash / workflow 不进该表。+ const durableStatus =+ update.taskType === 'local_bash' || update.taskType === 'local_workflow'+ ? undefined+ : lookupSubagentRunStatus(subagentRunStatuses, undefined, update);+ const status = deriveAgentTaskStatus(update.status, undefined, { durableStatus });+ if (!isSessionStreaming && status !== 'running') continue;const primaryKey = update.parentToolUseId ?? update.taskId;if (seenTaskIds.has(update.taskId) ||@@ -391,7 +408,7 @@ export function listSessionTasks(input: {taskId: update.taskId,kind,title: deriveTitle(kind, update, undefined),- status: update.status,+ status,provider: update.provider,update,orderIndex: orphanOrder++,diff --git a/apps/desktop/src/renderer/hooks/__tests__/useSubagentRunStatusIndex.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useSubagentRunStatusIndex.test.tsnew file mode 100644index 0000000000..3c066aaf33--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useSubagentRunStatusIndex.test.ts@@ -0,0 +1,137 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { SubagentRun, SubagentRunsListResponse } from '@cindy/maker-shared/subagent-workspace';++import { useSubagentRunStatusIndex } from '../useSubagentRunStatusIndex';++type ChangeListener = (+ payload: { sessionId: string; runId: string | null },+ stamp?: unknown,+) => void;++function run(partial: Partial<SubagentRun> & Pick<SubagentRun, 'id' | 'status'>): SubagentRun {+ return {+ parentSessionId: 's1',+ provider: 'claude-code',+ logicalAgentId: partial.id,+ identityAliases: [],+ providerRunIds: [],+ capabilities: {} as SubagentRun['capabilities'],+ startedAt: 1,+ updatedAt: 1,+ ...partial,+ };+}++function installApi(pages: Record<string, SubagentRunsListResponse>) {+ const listeners = new Set<ChangeListener>();+ const list = vi.fn(+ async (input: { sessionId: string; cursor?: string }) =>+ pages[`${input.sessionId}:${input.cursor ?? ''}`] ?? { supported: true, runs: [] },+ );+ const api = {+ list,+ onChanged: vi.fn((listener: ChangeListener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }),+ };+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ localDb: { subagentRuns: api },+ };+ return { list, listeners };+}++afterEach(() => {+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+});++describe('useSubagentRunStatusIndex', () => {+ it('reads every page and indexes runs by their parent tool-use id', async () => {+ installApi({+ 's1:': {+ supported: true,+ runs: [run({ id: 'r1', parentToolUseId: 'toolu_1', status: 'running' })],+ nextCursor: 'c2',+ },+ 's1:c2': {+ supported: true,+ runs: [run({ id: 'r2', parentToolUseId: 'toolu_2', status: 'failed' })],+ },+ });+ const { result } = renderHook(() => useSubagentRunStatusIndex({ sessionId: 's1' }));+ await waitFor(() => expect(result.current.get('toolu_2')).toBe('failed'));+ expect(result.current.get('toolu_1')).toBe('running');+ });++ it('re-reads on a change push for its own task only', async () => {+ const pages: Record<string, SubagentRunsListResponse> = {+ 's1:': {+ supported: true,+ runs: [run({ id: 'r1', parentToolUseId: 'toolu_1', status: 'running' })],+ },+ };+ const { list, listeners } = installApi(pages);+ const { result } = renderHook(() => useSubagentRunStatusIndex({ sessionId: 's1' }));+ await waitFor(() => expect(result.current.get('toolu_1')).toBe('running'));++ pages['s1:'] = {+ supported: true,+ runs: [run({ id: 'r1', parentToolUseId: 'toolu_1', status: 'completed', updatedAt: 2 })],+ };+ const callsBefore = list.mock.calls.length;+ act(() => {+ for (const listener of listeners) listener({ sessionId: 'other', runId: null });+ });+ act(() => {+ for (const listener of listeners) listener({ sessionId: 's1', runId: 'r1' });+ });+ await waitFor(() => expect(result.current.get('toolu_1')).toBe('completed'));+ expect(list.mock.calls.length).toBe(callsBefore + 1);+ });++ it('falls back to the live status when a later refresh fails', async () => {+ const { list, listeners } = installApi({+ 's1:': {+ supported: true,+ runs: [run({ id: 'r1', parentToolUseId: 'toolu_1', status: 'completed' })],+ },+ });+ const { result } = renderHook(() => useSubagentRunStatusIndex({ sessionId: 's1' }));+ await waitFor(() => expect(result.current.get('toolu_1')).toBe('completed'));++ list.mockRejectedValueOnce(new Error('db busy'));+ act(() => {+ for (const listener of listeners) listener({ sessionId: 's1', runId: 'r1' });+ });+ await waitFor(() => expect(result.current.size).toBe(0));+ });++ it('does not read this machine for a device-link task', () => {+ const { list } = installApi({});+ const { result } = renderHook(() =>+ useSubagentRunStatusIndex({ sessionId: 's1', deviceId: 'device-2' }),+ );+ expect(list).not.toHaveBeenCalled();+ expect(result.current.size).toBe(0);+ });++ it('never shows the previous task while the next task is still loading', async () => {+ installApi({+ 's1:': {+ supported: true,+ runs: [run({ id: 'r1', parentToolUseId: 'toolu_1', status: 'running' })],+ },+ });+ const { result, rerender } = renderHook(+ ({ sessionId }) => useSubagentRunStatusIndex({ sessionId }),+ { initialProps: { sessionId: 's1' } },+ );+ await waitFor(() => expect(result.current.get('toolu_1')).toBe('running'));+ rerender({ sessionId: 's2' });+ expect(result.current.get('toolu_1')).toBeUndefined();+ // Let the s2 read settle inside act so it cannot leak into the next test.+ await waitFor(() => expect(result.current.size).toBe(0));+ });+});diff --git a/apps/desktop/src/renderer/hooks/useSubagentRunStatusIndex.ts b/apps/desktop/src/renderer/hooks/useSubagentRunStatusIndex.tsnew file mode 100644index 0000000000..00e9a41fac--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useSubagentRunStatusIndex.ts@@ -0,0 +1,115 @@+/**+ * useSubagentRunStatusIndex — the host's durable `subagent_runs` status for one+ * task, indexed by every id a spawning tool call can be matched by.+ *+ * `subagent_runs` is written from structured lifecycle events (Claude+ * `async_launched` / `task_notification`, Codex and PI observations), so it does+ * not depend on the wording of a launch receipt. Chat cards and the background+ * task panel read it through {@link deriveAgentTaskStatus}'s `durableStatus`.+ *+ * Local tasks only: the device-link list is deliberately narrowed to PI runs on+ * the data-owning device, so a remote task gets an empty index and keeps the+ * existing live-update + receipt-text derivation.+ */++import { useEffect, useState } from 'react';+import {+ buildSubagentRunStatusIndex,+ type SubagentRunStatusIndex,+} from '@cindy/maker-shared/agent-task';+import type { SubagentRun, SubagentRunsListResponse } from '@cindy/maker-shared/subagent-workspace';++import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { isCurrentSubagentRunsChange } from '@/features/right-sidebar/plugins/subagents/subagentChangeFence';++const EMPTY_INDEX: SubagentRunStatusIndex = new Map();+/** The host clamps list pages to 100; a task with more runs keeps its newest 1000. */+const LIST_PAGE_LIMIT = 100;+const MAX_LIST_PAGES = 10;+const CHANGE_DEBOUNCE_MS = 50;++function sameStatusIndex(a: SubagentRunStatusIndex, b: SubagentRunStatusIndex): boolean {+ if (a.size !== b.size) return false;+ for (const [key, status] of a) {+ if (b.get(key) !== status) return false;+ }+ return true;+}++export function useSubagentRunStatusIndex(input: {+ sessionId: string | null | undefined;+ /** Data-owning device of a device-link task; null/undefined = this machine. */+ deviceId?: string | null;+ enabled?: boolean;+}): SubagentRunStatusIndex {+ const { sessionId, deviceId, enabled = true } = input;+ const local = !(typeof deviceId === 'string' && deviceId.length > 0);+ const [state, setState] = useState<{ sessionId: string; index: SubagentRunStatusIndex } | null>(+ null,+ );++ useEffect(() => {+ if (!enabled || !local || !sessionId) return;+ const api = window.electronAPI?.localDb?.subagentRuns;+ if (!api) return;+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ // Each read supersedes the previous one; only the newest may publish.+ let readSeq = 0;++ const read = async (): Promise<void> => {+ const seq = ++readSeq;+ const owner = getDataOwnerGeneration();+ const runs: SubagentRun[] = [];+ let cursor: string | undefined;+ for (let page = 0; page < MAX_LIST_PAGES; page++) {+ const request = { sessionId, limit: LIST_PAGE_LIMIT, ...(cursor ? { cursor } : {}) };+ const response = (await api.list(request)) as SubagentRunsListResponse;+ if (disposed || seq !== readSeq || !isDataOwnerGenerationCurrent(owner)) return;+ if (!response.supported) break;+ runs.push(...response.runs);+ cursor = response.nextCursor;+ if (!cursor) break;+ }+ const index = runs.length > 0 ? buildSubagentRunStatusIndex(runs) : EMPTY_INDEX;+ // Progress pushes usually leave every status unchanged; keep the old Map+ // so the chat's render projection cache is not invalidated for nothing.+ setState((previous) =>+ previous?.sessionId === sessionId && sameStatusIndex(previous.index, index)+ ? previous+ : { sessionId, index },+ );+ };+ const refresh = (): void => {+ const seq = readSeq + 1;+ const owner = getDataOwnerGeneration();+ void read().catch(() => {+ // A failed re-read must not leave an older index in force: its terminal+ // statuses would outrank a resumed run's live `running` update. Drop to+ // the empty index so rendering falls back to the live derivation.+ if (disposed || seq !== readSeq || !isDataOwnerGenerationCurrent(owner)) return;+ setState({ sessionId, index: EMPTY_INDEX });+ });+ };++ refresh();+ const unsubscribe = api.onChanged((payload, ownerStamp) => {+ if (!isCurrentSubagentRunsChange(payload, ownerStamp, sessionId)) return;+ if (timer) clearTimeout(timer);+ timer = setTimeout(refresh, CHANGE_DEBOUNCE_MS);+ });+ return () => {+ disposed = true;+ if (timer) clearTimeout(timer);+ unsubscribe();+ };+ }, [enabled, local, sessionId]);++ // Keyed by the task it was read for, so switching tasks never shows the+ // previous task's statuses while the new read is in flight.+ if (!enabled || !local || !sessionId || state?.sessionId !== sessionId) return EMPTY_INDEX;+ return state.index;+}diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.tsindex 4611d53b22..cc8d84790f 100644--- a/packages/maker-shared/src/__tests__/agentTask.test.ts+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts@@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest';import {applyAgentTaskUpdateEvent,buildAgentTaskCardModel,+ buildSubagentRunStatusIndex,deriveAgentTaskStatus,findAgentTaskUpdate,isAgentTaskToolName,isSubagentSpawnToolName,+ lookupSubagentRunStatus,mergeAgentTaskUpdate,PI_SUBAGENT_TOOL_NAME,normalizeAgentTaskUpdate,@@ -17,6 +19,16 @@ import {const NOW = '2026-06-24T00:00:00.000Z';+/** Verbatim async launch receipt from Claude Code 2.1.280 (agent/output ids shortened). */+const CLAUDE_2_1_280_ASYNC_RECEIPT = [+ 'Async agent launched successfully. (This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)',+ "agentId: aedc178c75c770875 (internal ID - do not mention to user. Use SendMessage with to: 'aedc178c75c770875', summary: '<5-10 word recap>' to continue this agent.)",+ 'The agent is working in the background. You will be notified automatically when it completes. You know nothing about its results until that notification arrives — do not report, assume, or predict them; continue other work or respond to the user in the meantime.',+ "Do not duplicate this agent's work — avoid working with the same files or topics it is using.",+ 'output_file: /private/tmp/claude-501/project/session/tasks/aedc178c75c770875.output',+ 'Do NOT Read or tail this file via the shell tool — it is the full subagent JSONL transcript and reading it will overflow your context. If the user asks for progress, say the agent is still running; you\'ll get a completion notification.',+].join('\n');+describe('isAgentTaskToolName', () => {it('matches Task / Agent / collab:* and nothing else', () => {expect(isAgentTaskToolName('Task')).toBe(true);@@ -61,6 +73,18 @@ describe('subagentSpawnResultIndicatesRunning', () => {expect(subagentSpawnResultIndicatesRunning('subagent', undefined)).toBe(false);});+ it('recognises the Claude Code 2.1.280 async launch receipt', () => {+ expect(subagentSpawnResultIndicatesRunning('Agent', CLAUDE_2_1_280_ASYNC_RECEIPT)).toBe(true);+ expect(subagentSpawnResultIndicatesRunning('Task', CLAUDE_2_1_280_ASYNC_RECEIPT)).toBe(true);+ });++ it('does not treat a final Agent answer that quotes the receipt opener as a launch', () => {+ expect(subagentSpawnResultIndicatesRunning(+ 'Agent',+ 'Async agent launched successfully. That is what the log said; the fix is done.',+ )).toBe(false);+ });+it('recognises the durable PI launch receipt', () => {expect(subagentSpawnResultIndicatesRunning('subagent',@@ -113,6 +137,65 @@ describe('deriveAgentTaskStatus', () => {persistedStatus: 'cancelled' as never,})).toBe('completed');});++ it('keeps a live running task running when the durable run is running, whatever the result text', () => {+ expect(deriveAgentTaskStatus('running', 'Some future receipt wording', {+ durableStatus: 'running',+ })).toBe('running');+ });++ it('lets a durable terminal run outrank a stale running update and the result text', () => {+ expect(deriveAgentTaskStatus('running', 'Some future receipt wording', {+ durableStatus: 'failed',+ })).toBe('failed');+ expect(deriveAgentTaskStatus(undefined, 'receipt', { durableStatus: 'stopped' })).toBe('stopped');+ });++ it('does not let a durable running record pin a spinner without a live update', () => {+ expect(deriveAgentTaskStatus(undefined, 'receipt', { durableStatus: 'running' })).toBe('completed');+ });++ it('lets a live terminal update close a durable run that has not caught up yet', () => {+ expect(deriveAgentTaskStatus('completed', 'receipt', { durableStatus: 'running' })).toBe('completed');+ });++ it('keeps the persisted tool-call status above the durable run', () => {+ expect(deriveAgentTaskStatus('running', 'x', {+ persistedStatus: 'completed',+ durableStatus: 'running',+ })).toBe('completed');+ });+});++describe('buildSubagentRunStatusIndex / lookupSubagentRunStatus', () => {+ it('indexes a run under its parent tool-use id, logical id and aliases', () => {+ const index = buildSubagentRunStatusIndex([{+ parentToolUseId: 'toolu_1',+ logicalAgentId: 'agent-1',+ identityAliases: ['alias-1'],+ status: 'running',+ updatedAt: 1,+ }]);+ expect(lookupSubagentRunStatus(index, 'toolu_1')).toBe('running');+ expect(lookupSubagentRunStatus(index, undefined, { taskId: 'agent-1' })).toBe('running');+ expect(lookupSubagentRunStatus(index, undefined, { taskId: 'x', parentToolUseId: 'alias-1' }))+ .toBe('running');+ expect(lookupSubagentRunStatus(index, 'toolu_other')).toBeUndefined();+ expect(lookupSubagentRunStatus(undefined, 'toolu_1')).toBeUndefined();+ });++ it('keeps the most recently updated run when two runs share an alias', () => {+ const index = buildSubagentRunStatusIndex([+ { parentToolUseId: 'toolu_1', status: 'running', updatedAt: 20 },+ { parentToolUseId: 'toolu_1', status: 'completed', updatedAt: 10 },+ ]);+ expect(lookupSubagentRunStatus(index, 'toolu_1')).toBe('running');+ });++ it('skips runs with an unknown status', () => {+ const index = buildSubagentRunStatusIndex([{ parentToolUseId: 'toolu_1', status: 'queued' }]);+ expect(index.size).toBe(0);+ });});describe('mergeAgentTaskUpdate', () => {@@ -388,6 +471,40 @@ describe('buildAgentTaskCardModel', () => {expect(model.status).toBe('running');});+ it('REPRO: keeps a Claude Code 2.1.280 async Agent running and hides its receipt', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'Agent',+ toolInput: { prompt: 'keep working' },+ result: CLAUDE_2_1_280_ASYNC_RECEIPT,+ update: {+ provider: 'claude-code',+ taskId: 'aedc178c75c770875',+ parentToolUseId: 'toolu_1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ expect(model.summary).toBeUndefined();+ });++ it('keeps an async Agent running from the durable run even if the receipt wording changes again', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'Agent',+ toolInput: { prompt: 'keep working' },+ result: 'Background agent queued. id=abc',+ durableStatus: 'running',+ update: {+ provider: 'claude-code',+ taskId: 'abc',+ parentToolUseId: 'toolu_1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ });+it('REPRO: recognizes the full async Claude Agent launch receipt', () => {const model = buildAgentTaskCardModel({toolName: 'Agent',diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.tsindex 2906af84c2..dda4cfa28f 100644--- a/packages/maker-shared/src/agentTask.ts+++ b/packages/maker-shared/src/agentTask.ts@@ -167,6 +167,12 @@ export interface AgentTaskUpdate {* Derive the visible task status from the live update and its paired tool result.* A result is a terminal fact, so it closes a stale `running` update without* overriding an explicit failure or stopped state.+ *+ * `durableStatus` is the host's `subagent_runs` record for the same task, which+ * is built from structured lifecycle events rather than result text. A terminal+ * record is authoritative. A `running` record only proves the paired result is a+ * launch receipt; the live update still decides whether the task is running, so+ * a record left behind by a process that died never pins a spinner.*/export function deriveAgentTaskStatus(updateStatus: AgentTaskStatus | undefined,@@ -174,15 +180,71 @@ export function deriveAgentTaskStatus(options?: {resultIsLaunchReceipt?: boolean;persistedStatus?: AgentTaskTerminalStatus;+ durableStatus?: AgentTaskStatus;},): AgentTaskStatus {const persistedStatus = normalizeAgentTaskTerminalStatus(options?.persistedStatus);if (persistedStatus) return persistedStatus;+ const durableTerminalStatus = normalizeAgentTaskTerminalStatus(options?.durableStatus);+ if (durableTerminalStatus) return durableTerminalStatus;+ const resultIsLaunchReceipt =+ options?.resultIsLaunchReceipt === true || options?.durableStatus === 'running';const hasResult = typeof result === 'string' && result.trim().length > 0;- if (updateStatus === 'running' && hasResult && !options?.resultIsLaunchReceipt) return 'completed';+ if (updateStatus === 'running' && hasResult && !resultIsLaunchReceipt) return 'completed';return updateStatus ?? (hasResult ? 'completed' : 'running');}+/**+ * Durable `subagent_runs` status, keyed by every id a spawning tool call or its+ * live update may carry (parent tool-use id, harness task id, Cindy aliases).+ */+export type SubagentRunStatusIndex = ReadonlyMap<string, AgentTaskStatus>;++export interface SubagentRunStatusSource {+ parentToolUseId?: string;+ logicalAgentId?: string;+ identityAliases?: readonly string[];+ status: string;+ updatedAt?: number;+}++/** When several runs claim one alias, the most recently updated run wins. */+export function buildSubagentRunStatusIndex(+ runs: readonly SubagentRunStatusSource[],+): SubagentRunStatusIndex {+ const index = new Map<string, AgentTaskStatus>();+ const updatedAtByKey = new Map<string, number>();+ for (const run of runs) {+ const status = run.status === 'running' ? 'running' : normalizeAgentTaskTerminalStatus(run.status);+ if (!status) continue;+ const updatedAt = typeof run.updatedAt === 'number' ? run.updatedAt : 0;+ const keys = [run.parentToolUseId, run.logicalAgentId, ...(run.identityAliases ?? [])];+ for (const key of keys) {+ if (typeof key !== 'string' || key.length === 0) continue;+ const previous = updatedAtByKey.get(key);+ if (previous !== undefined && previous > updatedAt) continue;+ index.set(key, status);+ updatedAtByKey.set(key, updatedAt);+ }+ }+ return index;+}++/** First durable status found under the call's tool-use id or its update's ids. */+export function lookupSubagentRunStatus(+ index: SubagentRunStatusIndex | undefined,+ toolUseId: string | undefined,+ update?: Pick<AgentTaskUpdate, 'taskId' | 'parentToolUseId'>,+): AgentTaskStatus | undefined {+ if (!index || index.size === 0) return undefined;+ for (const key of [toolUseId, update?.parentToolUseId, update?.taskId]) {+ if (typeof key !== 'string' || key.length === 0) continue;+ const status = index.get(key);+ if (status) return status;+ }+ return undefined;+}+/*** Tool names that spawn a sub-agent task: Claude `Task`/`Agent`, Codex collab agents,* PI `subagent`(Cindy 自有扩展注册的工具名,与 pi 社区惯例一致)。@@ -417,11 +479,15 @@ export function subagentSpawnResultIndicatesRunning(&& trimmed === 'Cindy subagent launched. The agent is working in the background.') {return true;}+ // Claude Code 2.1.280 appends a notice to the first line (`Async agent+ // launched successfully. (This tool result is internal metadata …)`) and to+ // the agentId line, so match the lines by prefix instead of exact text.if ((toolName === 'Agent' || toolName === 'Task')&& (trimmed === 'Async agent launched successfully.'|| (- trimmed.startsWith('Async agent launched successfully.\nagentId: ')+ trimmed.startsWith('Async agent launched successfully.')+ && /\nagentId: \S/.test(trimmed)&& trimmed.includes('\nThe agent is working in the background.')))) {@@ -451,10 +517,12 @@ export function buildAgentTaskCardModel(input: {update?: AgentTaskUpdate;result?: string;persistedStatus?: AgentTaskTerminalStatus;+ durableStatus?: AgentTaskStatus;}): AgentTaskCardModel {- const { toolName, toolInput, update, result, persistedStatus } = input;+ const { toolName, toolInput, update, result, persistedStatus, durableStatus } = input;const status = deriveAgentTaskStatus(update?.status, result, {persistedStatus,+ durableStatus,resultIsLaunchReceipt:subagentSpawnReceiptName(toolName, toolInput, result) !== undefined|| subagentSpawnResultIndicatesRunning(toolName, result),@@ -483,7 +551,12 @@ export function buildAgentTaskCardModel(input: {const spawnedAgentName = update ? undefined : formatAgentTaskTitle(provider, spawnReceiptName);// 启动回执命中时 summary 不携带裸路径(路径已在 spawnedAgentName / title 中),// 否则手机端会把 agentPath 原样当摘要展示。- const summary = spawnReceiptName ? detailText(update?.summary) : detailText(result, update?.summary);+ // Claude 异步 Agent 的启动回执是写给模型的内部元数据(agentId / output 文件),不当摘要展示。+ const claudeLaunchReceipt = (toolName === 'Agent' || toolName === 'Task')+ && subagentSpawnResultIndicatesRunning(toolName, result);+ const summary = spawnReceiptName || claudeLaunchReceipt+ ? detailText(update?.summary)+ : detailText(result, update?.summary);return {status,provider,