Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(codex): 子代理卡补齐实时状态,与 Claude 子代理卡形态统一 (#1438)
Chris Zhang0d118ee37784
diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex c39832297d..a037c826c5 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -209,8 +209,12 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session// 原文),用户可见句子在这里按 locale 组装。判据与 mobile 卡模型共用// maker-shared 的 subagentSpawnReceiptName,不在端上内联复制。const spawnReceiptName = subagentSpawnReceiptName(toolCall?.toolName, toolCall?.toolInput, result);+ // 判据与抑制规则同 maker-shared 的 buildAgentTaskCardModel:有 live update 时不显示+ // 「已启动」句子(title + 状态已表达),否则 codex 卡会比 Claude 卡多一行冗余文案。const summary = spawnReceiptName- ? t('chat.agentTask.subagentStarted', { name: spawnReceiptName })+ ? (update+ ? detailText(update.summary)+ : t('chat.agentTask.subagentStarted', { name: spawnReceiptName })): detailText(result, update?.summary);const duration = formatDuration(update?.usage?.durationMs);const provider = update?.provider ?? (toolCall?.toolName?.startsWith('collab:') ? 'codex' : 'claude-code');diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsxnew file mode 100644index 0000000000..a8b1d5ba2d--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsx@@ -0,0 +1,121 @@+// @vitest-environment jsdom+//+// Codex 子代理卡与 Claude 子代理卡的形态一致性回归。+//+// Cindy 的子代理 UI 只有一张卡(AgentTaskCard):Claude 靠 SDK 的 task_progress 驱动,+// Codex 此前没有数据源、只能渲染一句「已启动」就地收口。补上子线程实时事件后,两者必须+// 长得一样 —— 同样的 provider·状态·tokens·工具调用数·耗时,且 codex 不多出冗余文案。++import { render } from '@testing-library/react';+import type { ReactNode } from 'react';+import { describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ vars && Object.keys(vars).length > 0 ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++vi.mock('@/hooks/useExpandedBlockMemory', () => ({+ useExpandedBlockMemory: () => ({ expanded: false, setExpanded: vi.fn() }),+}));++vi.mock('@/lib/makerTransport', () => ({+ getWorkflowProgressFor: vi.fn(async () => null),+ isRemoteSessionSticky: () => false,+}));++vi.mock('@/features/right-sidebar/lib/openBackgroundTasksTab', () => ({+ openBackgroundTasksTab: vi.fn(),+}));++vi.mock('@/features/right-sidebar/plugins/background-tasks/listSessionTasks', () => ({+ extractWorkflowTaskId: () => undefined,+}));++vi.mock('@/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip', () => ({+ WorkflowAgentStrip: () => null,+}));++vi.mock('@/features/cc-agent/embeddedSessionNavigation', () => ({+ useSidebarPanelReachable: () => false,+}));++vi.mock('@/components/ui/collapse', () => ({+ Collapse: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++vi.mock('@/lib/modelShortLabel', () => ({+ formatModelShortLabel: (model?: string | null) => model ?? undefined,+}));++import { AgentTaskCard } from '../AgentTaskCard';+import type { AgentTaskUpdate, ChatMessage } from '@/hooks/useCCAgentChat';++function spawnToolCall(): ChatMessage {+ return {+ clientId: 'c1',+ role: 'tool_use',+ content: '',+ toolUseId: 'spawn-1',+ toolName: 'collab:spawn',+ toolInput: { name: '/root/scout', agentThreadId: 't-2' },+ } as unknown as ChatMessage;+}++const liveCodexUpdate: AgentTaskUpdate = {+ provider: 'codex',+ taskId: 'spawn-1',+ parentToolUseId: 'spawn-1',+ status: 'running',+ title: '/root/scout',+ usage: { totalTokens: 143615, toolUses: 25, durationMs: 170_000 },+};++describe('AgentTaskCard codex subagent live state', () => {+ it('shows the same meta row as a claude subagent card', () => {+ const { container } = render(+ <AgentTaskCard toolCall={spawnToolCall()} result="/root/scout" update={liveCodexUpdate} />,+ );+ const text = container.textContent ?? '';++ expect(text).toContain('chat.agentTask.provider.codex');+ expect(text).toContain('chat.agentTask.status.running');+ // tokens / 工具调用数 / 耗时三项都由 update.usage 驱动,与 Claude 卡同一渲染路径。+ expect(text).toContain('chat.agentTask.tokens');+ expect(text).toContain('chat.agentTask.toolUses');+ expect(text).toContain('2m 50s');+ });++ it('drops the "已启动" receipt once live state exists, and never leaks the raw agent path as summary', () => {+ const { container } = render(+ <AgentTaskCard toolCall={spawnToolCall()} result="/root/scout" update={liveCodexUpdate} />,+ );+ const text = container.textContent ?? '';++ // 冗余文案:title 与运行状态已经表达了「已启动」,Claude 卡在运行中也没有这行。+ expect(text).not.toContain('chat.agentTask.subagentStarted');+ // 标题仍是子代理名(agentPath),但不得作为 summary 再出现一次。+ expect(text.match(/\/root\/scout/g) ?? []).toHaveLength(1);+ });++ it('keeps the localized receipt for history replay (no live update)', () => {+ // 历史回放拿不到 live update(agent_task_update 不落库),回执是唯一可读摘要。+ const { container } = render(<AgentTaskCard toolCall={spawnToolCall()} result="/root/scout" />);+ expect(container.textContent ?? '').toContain('chat.agentTask.subagentStarted');+ });++ it('renders terminal codex subagent state instead of staying stuck on running', () => {+ const { container } = render(+ <AgentTaskCard+ toolCall={spawnToolCall()}+ result="/root/scout"+ update={{ ...liveCodexUpdate, status: 'completed' }}+ />,+ );+ const text = container.textContent ?? '';+ expect(text).toContain('chat.agentTask.status.completed');+ expect(text).not.toContain('chat.agentTask.status.running');+ });+});diff --git a/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.tsnew file mode 100644index 0000000000..976f3a29ae--- /dev/null+++ b/packages/maker-core/src/agents/codex/__tests__/subagentLiveCards.test.ts@@ -0,0 +1,681 @@+import { describe, expect, it } from 'vitest';++import { createSubagentLiveCardTracker } from '../subagent-live-cards.js';+import { readCodexSubagentSpawnRegistration } from '../translator.js';++/** V2(codex 0.145):spawn 只发瞬时 subAgentActivity,带 agentThreadId。 */+function v2SpawnItem(id: string, agentThreadId: string, agentPath?: string) {+ return {+ type: 'subAgentActivity',+ id,+ kind: 'started',+ agentThreadId,+ ...(agentPath ? { agentPath } : {}),+ };+}++/** V1(老模型 / 自定义接入模型):spawn 走 collabAgentToolCall,目标在 receiverThreadIds。 */+function v1SpawnItem(id: string, receiverThreadIds: string[]) {+ return {+ type: 'collabAgentToolCall',+ id,+ tool: 'spawnAgent',+ senderThreadId: 'root-1',+ receiverThreadIds,+ prompt: 'survey the repo rules',+ };+}++function toolItem(id: string, type = 'commandExecution') {+ return { item: { id, type } };+}++describe('readCodexSubagentSpawnRegistration', () => {+ it('maps V2 subAgentActivity to its child thread', () => {+ expect(readCodexSubagentSpawnRegistration(v2SpawnItem('i-1', 't-child', '/root/scout'))).toEqual({+ taskId: 'i-1',+ childThreadIds: ['t-child'],+ agentPath: '/root/scout',+ });+ });++ it('maps V1 collab spawn to every receiver thread', () => {+ expect(readCodexSubagentSpawnRegistration(v1SpawnItem('i-2', ['t-a', 't-b']))).toEqual({+ taskId: 'i-2',+ childThreadIds: ['t-a', 't-b'],+ });+ });++ it('ignores non-spawn collab tools and non-started activity', () => {+ expect(+ readCodexSubagentSpawnRegistration({+ type: 'collabAgentToolCall',+ id: 'i-3',+ tool: 'wait',+ receiverThreadIds: ['t-a'],+ }),+ ).toBeNull();+ // interacted / interrupted 是 followup·中断的伴生事件,不是新子代理启动。+ expect(+ readCodexSubagentSpawnRegistration({ ...v2SpawnItem('i-4', 't-c'), kind: 'interacted' }),+ ).toBeNull();+ expect(readCodexSubagentSpawnRegistration({ type: 'commandExecution', id: 'i-5' })).toBeNull();+ expect(readCodexSubagentSpawnRegistration(null)).toBeNull();+ });++ it('ignores spawn items without any resolvable child thread', () => {+ // 拿不到子线程 id 就无法把实时事件归到卡上,不能瞎登记。+ expect(readCodexSubagentSpawnRegistration({ type: 'subAgentActivity', id: 'i-6', kind: 'started' })).toBeNull();+ expect(readCodexSubagentSpawnRegistration({ ...v1SpawnItem('i-7', []) })).toBeNull();+ });+});++describe('createSubagentLiveCardTracker', () => {+ it('aggregates tokens / tool uses / duration onto the spawn card taskId', () => {+ let clock = 1_000;+ const tracker = createSubagentLiveCardTracker({ now: () => clock });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child', '/root/scout'));++ clock = 3_500;+ const afterTool = tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1'));+ expect(afterTool).toEqual({+ taskId: 'card-1',+ status: 'running',+ agentPath: '/root/scout',+ totalTokens: 0,+ toolUses: 1,+ durationMs: 2_500,+ });++ const afterUsage = tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 12_345 } },+ });+ expect(afterUsage?.totalTokens).toBe(12_345);+ expect(afterUsage?.toolUses).toBe(1);+ });++ it('counts a tool item once even when both phases arrive', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1'))?.toolUses).toBe(1);+ // 同 id 的 completed 不再计数(重复计数会让工具数虚高一倍)。+ expect(tracker.handleDescendantNotification('t-child', 'item/completed', toolItem('x-1'))).toBeNull();+ // 只发 completed 的 item(如 imageView)仍要计入。+ expect(+ tracker.handleDescendantNotification('t-child', 'item/completed', toolItem('x-2', 'imageView'))?.toolUses,+ ).toBe(2);+ });++ it('does not count non-tool items as tool uses', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ for (const type of ['agentMessage', 'reasoning', 'plan', 'userMessage', 'subAgentActivity']) {+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem(`x-${type}`, type))).toBeNull();+ }+ });++ it('maps turn status onto the card status', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));++ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'failed' } })?.status,+ ).toBe('failed');+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'interrupted' } })?.status,+ ).toBe('stopped');+ // followup 让同一子代理重新开跑 → 卡片回到 running。+ expect(tracker.handleDescendantNotification('t-child', 'turn/started', { turn: { id: 'tr-2' } })?.status)+ .toBe('running');+ });++ it('aggregates every receiver of one V1 spawn into a single shared card', () => {+ // 同一次 spawnAgent 扇出多个 receiverThreadIds,但它们共用一张卡:计数必须挂在+ // taskId 上按线程分量累计,否则后到的快照会把先到的覆盖成更小值(用量回退)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']));++ expect(tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'))).toMatchObject({+ taskId: 'card-v1',+ toolUses: 1,+ });+ // 第二个 receiver 的工具调用是累加,不是覆盖。+ expect(tracker.handleDescendantNotification('t-b', 'item/started', toolItem('x-2'))).toMatchObject({+ taskId: 'card-v1',+ toolUses: 2,+ });++ // token 是各线程累计快照之和;同线程再报只覆盖自己那份,不重复相加。+ expect(+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 100 } },+ })?.totalTokens,+ ).toBe(100);+ expect(+ tracker.handleDescendantNotification('t-b', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 40 } },+ })?.totalTokens,+ ).toBe(140);+ expect(+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 130 } },+ })?.totalTokens,+ ).toBe(170);+ });++ it('keeps a multi-receiver card running until every receiver is terminal', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']));++ // sibling 先收口不得把整张卡误报成完成。+ expect(+ tracker.handleDescendantNotification('t-a', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('running');+ expect(+ tracker.handleDescendantNotification('t-b', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');+ });++ it('reports the worst terminal outcome across receivers, regardless of arrival order', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b', 't-c']));+ tracker.handleDescendantNotification('t-c', 'turn/completed', { turn: { status: 'interrupted' } });+ tracker.handleDescendantNotification('t-a', 'turn/completed', { turn: { status: 'completed' } });+ // failed 最后到也必须胜出(stopped / completed 不得掩盖失败)。+ expect(+ tracker.handleDescendantNotification('t-b', 'turn/completed', { turn: { status: 'failed' } })?.status,+ ).toBe('failed');+ });++ it('replays child notifications that arrived before the spawn item was registered', () => {+ // 乱序:子线程 thread/started 已建立 lineage,但父线程的 spawn item 还没被处理。+ // 这些通知此前会被直接丢弃 —— 首个工具调用 / 初始 token / 甚至终态永久缺失。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });++ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1'))).toBeNull();+ expect(+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 500 } },+ }),+ ).toBeNull();++ const replayed = tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child', '/root/scout'));+ expect(replayed).toMatchObject({+ taskId: 'card-1',+ agentPath: '/root/scout',+ status: 'running',+ toolUses: 1,+ totalTokens: 500,+ });+ // 重放后继续增量,不重复计数。+ expect(tracker.handleDescendantNotification('t-child', 'item/completed', toolItem('x-1'))).toBeNull();+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-2'))?.toolUses).toBe(2);+ });++ it('replays an early terminal notification instead of leaving the card stuck running', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'failed' } });+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))?.status).toBe('failed');+ });++ it('re-asserts the live aggregate when the same spawn is noted again (V1 completed phase)', () => {+ // V1 的 spawn 是 collabAgentToolCall:translator 在 completed phase 会无条件推一帧+ // status=completed(spawn 工具调用自己收口,不代表子代理跑完)。noteSpawnItem 必须回传+ // 当前聚合快照,让调用方在 translator 之后把真实状态重新声明一次 —— 否则仍在跑的子线程+ // 被提前标成完成,先到的 failed/stopped 也会被抹掉。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']));+ tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'));+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 700 } },+ });++ // 同一 spawn 再次登记(completed phase):计数不清零,且回传真实的 running 聚合。+ const reasserted = tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']));+ expect(reasserted).toMatchObject({+ taskId: 'card-v1',+ status: 'running',+ toolUses: 1,+ totalTokens: 700,+ });++ // 已收到的失败终态同样不得被合成的 completed 抹掉。+ tracker.handleDescendantNotification('t-a', 'turn/completed', { turn: { status: 'failed' } });+ tracker.handleDescendantNotification('t-b', 'turn/completed', { turn: { status: 'completed' } });+ expect(tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a', 't-b']))?.status).toBe('failed');+ });++ it('never overwrites a failed spawn terminal state with a running aggregate', () => {+ // V1 的 spawn 以 status:'failed' 收口时,translator 已推过 failed 帧。此前"已登记就回传+ // 快照"会补一帧聚合状态,而那时子线程还标着 running → 真实失败被盖回运行中(review)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a']));+ tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'));++ // completed phase 带 status:'failed' → 不补发任何帧。+ expect(+ tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a']), status: 'failed' }),+ ).toBeNull();++ // 且线程已被标成 failed:迟到的子线程通知不会把卡片翻回 running。+ expect(tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-2'))?.status)+ .toBe('failed');+ });++ it('still re-asserts the aggregate when the spawn itself succeeded', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a']));+ tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'));+ // 成功收口仍要重新声明真实聚合(子线程还在跑 → running),否则被合成 completed 盖掉。+ expect(+ tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a']), status: 'completed' }),+ ).toMatchObject({ taskId: 'card-v1', status: 'running', toolUses: 1 });+ });++ it('returns null for a fresh spawn with nothing buffered, and for non-spawn items', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ // 全新 spawn 且无早到通知:没有需要重新声明的状态,不发多余帧。+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toBeNull();+ expect(tracker.noteSpawnItem({ type: 'commandExecution', id: 'x' })).toBeNull();+ });++ it('does not buffer notifications it would never consume', () => {+ // 缓冲只为我们真正消费的 method 服务,别给无关线程攒垃圾。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.handleDescendantNotification('t-child', 'thread/status/changed', { status: 'idle' });+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toBeNull();+ });++ it('ignores unknown threads, unknown methods and malformed payloads', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(tracker.handleDescendantNotification('t-other', 'item/started', toolItem('x-1'))).toBeNull();+ expect(tracker.handleDescendantNotification('t-child', 'thread/status/changed', {})).toBeNull();+ expect(tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {})).toBeNull();+ expect(+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: Number.NaN } },+ }),+ ).toBeNull();+ expect(tracker.handleDescendantNotification('t-child', 'item/started', { item: { type: 'commandExecution' } }))+ .toBeNull();+ });++ it('keeps counters across both spawn phases but rebinds on re-spawn', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1'));+ // 同一 spawn 的 completed phase 再次登记不得清零计数。+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-2'))?.toolUses).toBe(2);++ // 换成新卡(resume/再 spawn 同线程)则重新起算,避免把上一张卡的用量算进新卡。+ tracker.noteSpawnItem(v2SpawnItem('card-2', 't-child'));+ const rebound = tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-3'));+ expect(rebound?.taskId).toBe('card-2');+ expect(rebound?.toolUses).toBe(1);+ });++ it('bounds tracked threads, evicting settled cards first', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0, maxTrackedCards: 2 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-done'));+ tracker.handleDescendantNotification('t-done', 'turn/completed', { turn: { status: 'completed' } });+ tracker.noteSpawnItem(v2SpawnItem('card-2', 't-live'));+ tracker.noteSpawnItem(v2SpawnItem('card-3', 't-new'));++ expect(tracker.size).toBe(2);+ // 已收口的先被淘汰,仍在跑的子代理卡不掉线。+ expect(tracker.handleDescendantNotification('t-done', 'item/started', toolItem('x-1'))).toBeNull();+ expect(tracker.handleDescendantNotification('t-live', 'item/started', toolItem('x-2'))?.taskId).toBe('card-2');+ expect(tracker.handleDescendantNotification('t-new', 'item/started', toolItem('x-3'))?.taskId).toBe('card-3');+ });++ it('folds nested subagents into the ancestor card via lineage', () => {+ // 孙线程的 spawn item 只出现在**子线程自己**的事件流里,主线程的 itemStarted 看不到,+ // 所以 noteSpawnItem 不可能登记它。必须靠血缘并入父线程所属的卡,否则孙线程的工具调用+ // 与 token 全部落进 pending 且再无登记路径可重放。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child', '/root/scout'));++ // 子 → 孙+ expect(tracker.noteDescendantThread('t-grand', 't-child')).toBeNull();+ expect(tracker.handleDescendantNotification('t-grand', 'item/started', toolItem('g-1'))).toMatchObject({+ taskId: 'card-1',+ toolUses: 1,+ });+ // 孙 → 曾孙:任意深度都归到同一张根卡。+ tracker.noteDescendantThread('t-great', 't-grand');+ expect(tracker.handleDescendantNotification('t-great', 'item/started', toolItem('gg-1'))?.toolUses).toBe(2);++ // token 按线程分量求和(子 + 孙各自的累计快照)。+ tracker.handleDescendantNotification('t-child', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 100 } },+ });+ expect(+ tracker.handleDescendantNotification('t-grand', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 30 } },+ })?.totalTokens,+ ).toBe(130);++ // 只有全部代际终态后卡片才收口。+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } });+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'completed' } });+ expect(+ tracker.handleDescendantNotification('t-great', 'turn/completed', { turn: { status: 'failed' } })?.status,+ ).toBe('failed');+ });++ it('replays a nested thread\'s notifications buffered before its lineage was known', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));++ // 孙线程通知先到(血缘还没建立)→ 缓冲,不产帧。+ expect(tracker.handleDescendantNotification('t-grand', 'item/started', toolItem('g-1'))).toBeNull();+ expect(+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'failed' } }),+ ).toBeNull();++ // 血缘建立时重放:工具数与终态都补回来(否则卡片会永久停在 running)。+ const replayed = tracker.noteDescendantThread('t-grand', 't-child');+ expect(replayed).toMatchObject({ taskId: 'card-1', toolUses: 1 });+ // 子线程仍在跑 → 整卡仍 running;孙的 failed 已记在它自己那份状态里。+ expect(replayed?.status).toBe('running');+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('failed');+ });++ it('ignores lineage for threads unrelated to any subagent card', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ // 父线程不属于任何卡(例如主线程的后代未经 spawn 登记)→ 无副作用。+ expect(tracker.noteDescendantThread('t-x', 't-unknown')).toBeNull();+ expect(tracker.noteDescendantThread('', 't-child')).toBeNull();+ expect(tracker.noteDescendantThread('t-same', 't-same')).toBeNull();+ expect(tracker.size).toBe(0);+ });++ it('locks the failed spawn terminal state against late turn lifecycle notifications', () => {+ // 上一轮只把「当下已知的线程」标成 failed,而 applyNotification 的 turn/started 会无条件+ // 写回 running、turn/completed 会写 completed —— 迟到的 turn 生命周期通知照样能把卡片+ // 从失败翻回运行中/已完成,覆盖 translator 的失败帧(review)。这里守终态闩。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v1SpawnItem('card-v1', ['t-a']));+ expect(tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a']), status: 'failed' })).toBeNull();++ // 迟到的 turn/started:线程状态被改回 running,但卡片状态由闩锁定。+ expect(tracker.handleDescendantNotification('t-a', 'turn/started', {})?.status).toBe('failed');+ // 迟到的 turn/completed(成功收口)同样不得翻案。+ expect(+ tracker.handleDescendantNotification('t-a', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('failed');+ // 闩上之后仍继续吸收用量:派发失败但子线程已经烧掉的 token 该算进去。+ expect(+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 512 } },+ }),+ ).toMatchObject({ status: 'failed', totalTokens: 512 });+ });++ it('keeps the failed latch for threads that only register after the failure', () => {+ // 失败先到、子线程后到(乱序):新并入的线程不能把卡片拉回 running。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ expect(tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a', 't-b']), status: 'failed' })).toBeNull();+ expect(tracker.handleDescendantNotification('t-b', 'turn/started', {})?.status).toBe('failed');+ // 后代线程经血缘并入,同样是 failed。+ expect(tracker.noteDescendantThread('t-grand', 't-a')?.status ?? 'failed').toBe('failed');+ expect(+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('failed');+ });++ it('buffers lineage whose parent is not attributed yet, then recursively attaches it', () => {+ // 乱序最狠的一种:子线程 thread/started 早于根线程的 spawn item,而它在归属前就派了孙线程。+ // 那条「孙 → 子」血缘此刻无从判断归属,以前直接丢弃 —— 之后 noteSpawnItem 只绑直接子线程,+ // 孙线程已缓冲的工具/token/终态再也没机会重放(卡片漏计,还可能提前显示完成)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });++ // 1) 血缘先到,父线程 t-child 尚未归属任何卡 → 必须缓冲而不是丢弃。+ expect(tracker.noteDescendantThread('t-grand', 't-child')).toBeNull();+ // 2) 孙线程的事件也先到 → 进通知缓冲。+ expect(tracker.handleDescendantNotification('t-grand', 'item/started', toolItem('g-1'))).toBeNull();+ expect(+ tracker.handleDescendantNotification('t-grand', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 300 } },+ }),+ ).toBeNull();++ // 3) spawn item 终于到达:直接子线程 + 缓冲的孙线程一起入卡,孙的用量被重放回来。+ const registered = tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(registered).toMatchObject({ taskId: 'card-1', toolUses: 1, totalTokens: 300 });++ // 4) 孙线程确已在卡上:它的后续通知直接命中(不再进缓冲),且子线程收口时孙线程仍在跑+ // → 整卡不得提前完成。+ expect(+ tracker.handleDescendantNotification('t-grand', 'item/started', toolItem('g-2')),+ ).toMatchObject({ toolUses: 2 });+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('running');+ expect(+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');+ });++ it('recursively attaches a multi-generation lineage chain buffered before registration', () => {+ // 曾孙:t-great → t-grand → t-child → (spawn) card-1,三条血缘全在归属前到达。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ expect(tracker.noteDescendantThread('t-great', 't-grand')).toBeNull();+ expect(tracker.noteDescendantThread('t-grand', 't-child')).toBeNull();+ tracker.handleDescendantNotification('t-great', 'item/started', toolItem('gg-1'));++ // 一次 spawn 登记应沿链递归补绑到曾孙,并重放它的工具计数。+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toMatchObject({+ taskId: 'card-1',+ toolUses: 1,+ });+ // 曾孙已在卡上:后续通知直接命中,且它没收口前整卡不算完成。+ expect(+ tracker.handleDescendantNotification('t-great', 'item/started', toolItem('gg-2')),+ ).toMatchObject({ toolUses: 2 });+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } });+ expect(+ tracker.handleDescendantNotification('t-grand', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('running');+ expect(+ tracker.handleDescendantNotification('t-great', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');+ });++ it('survives a cyclic lineage claim without recursing forever', () => {+ // 血缘理论上是树,但通知来自外部进程,不能假定。环不得让补绑无限递归。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteDescendantThread('t-b', 't-a');+ tracker.noteDescendantThread('t-a', 't-b');+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-a'))).toBeNull();+ // 两条线程都已入卡,状态可正常推进。+ expect(tracker.handleDescendantNotification('t-b', 'item/started', toolItem('c-1'))).toMatchObject({+ taskId: 'card-1',+ toolUses: 1,+ });+ });++ it('re-opens a card that already looked completed when a late descendant joins', () => {+ // 孙线程在子线程收口之后才并入:卡片已显示 completed,但孙还在跑 —— 必须发帧改回 running,+ // 否则用户看到的是"完成"而子代理其实还在烧 token。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');+ expect(tracker.noteDescendantThread('t-grand', 't-child')?.status).toBe('running');+ });++ it('bounds the unattributed lineage buffer', () => {+ // 绝大多数 descendantThreadStarted 的父线程与子代理无关(主线程自己的后代),缓冲必须有界。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ for (let i = 0; i < 200; i += 1) tracker.noteDescendantThread(`c-${i}`, `p-${i}`);+ for (let i = 0; i < 200; i += 1) tracker.noteDescendantThread(`x-${i}`, 'p-shared');+ // 无卡产生,且不抛错;有界性由内部常量保证(此处守的是"不崩、不建卡")。+ expect(tracker.size).toBe(0);+ });++ it('keeps tool item dedup ids after the card settles (turn/completed may precede item/completed)', () => {+ // app-server 允许 turn/completed 先发、后台收尾的 item/completed 随后才到。原来 snapshot()+ // 一收口就清 countedItemIds,那条迟到的 completed 会被当成新工具再加一次 → 工具数虚高(review)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(+ tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1')),+ ).toMatchObject({ toolUses: 1 });++ // 先收口(此时会产生一次终态快照)。+ expect(+ tracker.handleDescendantNotification('t-child', 'turn/completed', { turn: { status: 'completed' } })?.status,+ ).toBe('completed');++ // 同一个 item 的迟到 completed:必须被去重掉,工具数保持 1。+ expect(tracker.handleDescendantNotification('t-child', 'item/completed', toolItem('x-1'))).toBeNull();+ // 用一条真正的新 item 确认计数基线没有被污染(应为 2,而不是把 x-1 重复算成 3)。+ expect(+ tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-2')),+ ).toMatchObject({ toolUses: 2 });+ });++ it('re-emits replayed usage when the spawn itself failed', () => {+ // V1 spawn 的 started phase 缺失/晚到:子线程的工具与 token 先进缓冲,随后只收到+ // status:'failed' 的 completed item。原来失败分支无条件 return null,而 translator 的+ // failed 帧不带 usage —— 这些已重放的计数永远不会显示(review)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'));+ tracker.handleDescendantNotification('t-a', 'thread/tokenUsage/updated', {+ tokenUsage: { total: { totalTokens: 1234 } },+ });++ const failed = tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a']), status: 'failed' });+ // 有重放内容 → 补发快照,且状态由终态闩锁定为 failed(不会把失败盖回运行中)。+ expect(failed).toMatchObject({ taskId: 'card-v1', status: 'failed', toolUses: 1, totalTokens: 1234 });+ });++ it('still emits nothing when a failed spawn had no buffered usage to replay', () => {+ // 没有可重放的内容就别多发一帧 —— translator 的 failed 帧已经到位。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ expect(tracker.noteSpawnItem({ ...v1SpawnItem('card-v1', ['t-a']), status: 'failed' })).toBeNull();+ tracker.noteSpawnItem(v1SpawnItem('card-v2', ['t-b']));+ expect(tracker.noteSpawnItem({ ...v1SpawnItem('card-v2', ['t-b']), status: 'failed' })).toBeNull();+ });++ it('counts every tool item type the real codex protocol defines, and only those', () => {+ // 这份名单是对**真实 codex 0.145 二进制**导出的 schema 逐项核对出来的+ // (`codex app-server generate-json-schema` → ThreadItem 18 个变体)。`sleep` 就是核对时+ // 补上的:schema 写明它是 "Display item emitted by the interruptible `clock.sleep` tool",+ // 手工构造的单测永远发现不了漏计 —— 因为漏的那类事件我根本没想到要构造。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ const toolTypes = [+ 'commandExecution', 'mcpToolCall', 'dynamicToolCall', 'webSearch',+ 'fileChange', 'imageView', 'imageGeneration', 'collabAgentToolCall', 'sleep',+ ];+ toolTypes.forEach((type, i) => {+ expect(+ tracker.handleDescendantNotification('t-child', 'item/started', toolItem(`t-${i}`, type)),+ ).toMatchObject({ toolUses: i + 1 });+ });+ // 非工具产出不得计数(否则子代理每说一句话都算一次工具调用)。+ for (const type of ['userMessage', 'agentMessage', 'reasoning', 'plan', 'hookPrompt',+ 'enteredReviewMode', 'exitedReviewMode', 'contextCompaction', 'subAgentActivity']) {+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem(`n-${type}`, type)))+ .toBeNull();+ }+ });+++ it('counts a child tool whose first visible phase is item/updated', () => {+ // 长跑工具的首个可见阶段可能就是 updated(与主线程 spawn 路径同因:started 可能缺失)。+ // 原来聚合器只认 started / completed,且 CONSUMED_METHODS 也不缓冲 updated —— 于是长跑工具+ // 在 completed 到达前不计数,会话若先中断则永久漏计(review)。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ expect(+ tracker.handleDescendantNotification('t-child', 'item/updated', toolItem('long-1')),+ ).toMatchObject({ toolUses: 1 });+ // 同一 item 后续的 updated / completed 不得重复计数(去重靠 item id)。+ expect(tracker.handleDescendantNotification('t-child', 'item/updated', toolItem('long-1'))).toBeNull();+ expect(tracker.handleDescendantNotification('t-child', 'item/completed', toolItem('long-1'))).toBeNull();+ expect(+ tracker.handleDescendantNotification('t-child', 'item/updated', toolItem('long-2')),+ ).toMatchObject({ toolUses: 2 });+ });++ it('buffers a pre-registration item/updated instead of dropping it', () => {+ // spawn 尚未登记时 updated 必须进缓冲,否则登记后重放不出来 —— 同上一条的另一半。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ expect(tracker.handleDescendantNotification('t-child', 'item/updated', toolItem('early-1'))).toBeNull();+ expect(tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'))).toMatchObject({ toolUses: 1 });+ });+++ it('emits a terminal snapshot for still-running cards at shutdown', () => {+ // tracker 只靠后代 turn/completed 写终态,而 transport error / 强制 retire / thread cleanup+ // failure 之后那些通知**永远不会再到**。只清内部状态的话渲染端会一直留着最后一帧 running,+ // 卡片永久转圈(review)。+ let clock = 1_000;+ const tracker = createSubagentLiveCardTracker({ now: () => clock });+ tracker.noteSpawnItem(v2SpawnItem('card-run', 't-a'));+ tracker.handleDescendantNotification('t-a', 'item/started', toolItem('x-1'));+ tracker.noteSpawnItem(v2SpawnItem('card-done', 't-b'));+ tracker.handleDescendantNotification('t-b', 'turn/completed', { turn: { status: 'completed' } });++ clock = 5_000;+ const drained = tracker.drainRunningForShutdown();+ // 只收仍在跑的那张;已收口的不重复发。+ expect(drained).toHaveLength(1);+ expect(drained[0]).toMatchObject({ taskId: 'card-run', status: 'stopped', toolUses: 1 });+ // 幂等:再 drain 一次不该又冒出来。+ expect(tracker.drainRunningForShutdown()).toHaveLength(0);+ });++ it('closes out a card whose child threads never registered', () => {+ // spawn 刚认出、子线程还没 started 就断连:threads 为空时 aggregateStatus 返回 running,+ // 不补占位就还是转圈。+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem({ ...v1SpawnItem('card-empty', ['t-x']), receiverThreadIds: ['t-x'] });+ // 手动把线程集合清空以模拟"登记了卡但线程还没建立"的窗口。+ const drained = tracker.drainRunningForShutdown();+ expect(drained).toHaveLength(1);+ expect(drained[0].status).toBe('stopped');+ });++ it('dates the card from the first buffered evidence, not from registration time', () => {+ // spawn 的 started/updated 缺失或晚到时,子线程其实已经跑了一段。用建卡时刻当起点会把+ // 已消耗的时长整段漏掉 —— 长跑子代理甚至显示接近 0ms(review)。+ let clock = 1_000;+ const tracker = createSubagentLiveCardTracker({ now: () => clock });+ // 先到的子线程证据(此时还没有 spawn 登记)。+ tracker.handleDescendantNotification('t-late', 'item/started', toolItem('early-1'));++ clock = 61_000; // 子线程已经跑了 60 秒,spawn item 才到+ const registered = tracker.noteSpawnItem(v2SpawnItem('card-late', 't-late'));+ expect(registered?.durationMs).toBe(60_000);+ });++ it('falls back to now() when there is no earlier evidence', () => {+ let clock = 7_000;+ const tracker = createSubagentLiveCardTracker({ now: () => clock });+ tracker.noteSpawnItem(v2SpawnItem('card-fresh', 't-fresh'));+ clock = 7_500;+ expect(+ tracker.handleDescendantNotification('t-fresh', 'item/started', toolItem('y-1'))?.durationMs,+ ).toBe(500);+ });++ it('clear() drops all tracking (session close)', () => {+ const tracker = createSubagentLiveCardTracker({ now: () => 0 });+ tracker.noteSpawnItem(v2SpawnItem('card-1', 't-child'));+ tracker.clear();+ expect(tracker.size).toBe(0);+ expect(tracker.handleDescendantNotification('t-child', 'item/started', toolItem('x-1'))).toBeNull();+ });+});diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.tsindex d2042822c7..ee12f69de3 100644--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts@@ -483,3 +483,299 @@ describe('AppServerHost descendant thread routing', () => {await host.shutdown();});});++describe('AppServerHost descendant notification routing', () => {+ it('routes descendant item/tokenUsage/turn notifications to the root descendant channel only', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const descendantNotification = vi.fn();+ const itemStarted = vi.fn();+ const tokenUsageUpdated = vi.fn();+ const turnCompleted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantNotification,+ itemStarted,+ tokenUsageUpdated,+ turnCompleted,+ });++ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' } },+ });++ const childItem = {+ method: 'item/started',+ params: { threadId: 'child-thread', turnId: 'turn-c1', item: { id: 'i-1', type: 'commandExecution' } },+ };+ const childUsage = {+ method: 'thread/tokenUsage/updated',+ params: { threadId: 'child-thread', turnId: 'turn-c1', tokenUsage: { total: { totalTokens: 42 } } },+ };+ const grandchildTurn = {+ method: 'turn/completed',+ params: { threadId: 'grandchild-thread', turn: { id: 'turn-g1', status: 'completed' } },+ };+ transport.emit(childItem);+ transport.emit(childUsage);+ transport.emit(grandchildTurn);++ expect(descendantNotification.mock.calls).toEqual([+ ['child-thread', 'item/started', childItem.params],+ ['child-thread', 'thread/tokenUsage/updated', childUsage.params],+ ['grandchild-thread', 'turn/completed', grandchildTurn.params],+ ]);+ // 关键隔离:子线程事件绝不能进主线程 handler —— 否则子代理的 exec 会被渲染成+ // 主会话自己的工具调用,并污染主 turn 的 usage 与状态机。+ expect(itemStarted).not.toHaveBeenCalled();+ expect(tokenUsageUpdated).not.toHaveBeenCalled();+ expect(turnCompleted).not.toHaveBeenCalled();++ // 主线程自己的同名事件照旧走主通道。+ transport.emit({+ method: 'item/started',+ params: { threadId: 'root-thread', turnId: 'turn-r1', item: { id: 'i-2', type: 'commandExecution' } },+ });+ expect(itemStarted).toHaveBeenCalledTimes(1);+ expect(descendantNotification).toHaveBeenCalledTimes(3);++ await subscription.release();+ transport.emit(childItem);+ expect(descendantNotification).toHaveBeenCalledTimes(3);+ // thread/started 只走专用的 descendantThreadStarted,不重复出现在本通道。+ expect(descendantNotification.mock.calls.some(([, method]) => method === 'thread/started')).toBe(false);++ await host.shutdown();+ });++ it('keeps buffering notifications for threads with no known lineage', async () => {+ // 未知线程仍走 TTL 缓冲(解 subscribe 竞争);只有血缘已知的子线程才就地收口。+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ transport.emit({+ method: 'item/started',+ params: { threadId: 'late-thread', turnId: 'turn-1', item: { id: 'i-1', type: 'commandExecution' } },+ });++ const itemStarted = vi.fn();+ const descendantNotification = vi.fn();+ const subscription = host.subscribeThread('late-thread', { itemStarted, descendantNotification });+ expect(itemStarted).toHaveBeenCalledTimes(1);+ expect(descendantNotification).not.toHaveBeenCalled();++ await subscription.release();+ await host.shutdown();+ });+});+describe('AppServerHost buffered descendant notification replay', () => {+ it('replays a child thread\'s pre-subscribe item/usage/turn notifications in arrival order', async () => {+ // thread/started 与该 child 的 item / usage / turn 全部早于 root 的 subscribeThread 到达时,+ // 它们分别缓存在 **child id** 下。root 侧的 drain 只排空 root id 的队列,这些永远排不到 →+ // 早期工具数、token 丢失,漏掉 turn/completed 还会让卡片永久停在 running(codex review)。+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ // 订阅之前:child 与 grandchild 的血缘 + 各自的业务通知全部先到。+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });+ const childItem = {+ method: 'item/started',+ params: { threadId: 'child-thread', turnId: 't1', item: { id: 'i-1', type: 'commandExecution' } },+ };+ const childUsage = {+ method: 'thread/tokenUsage/updated',+ params: { threadId: 'child-thread', turnId: 't1', tokenUsage: { total: { totalTokens: 99 } } },+ };+ const childTurnEnd = {+ method: 'turn/completed',+ params: { threadId: 'child-thread', turn: { id: 't1', status: 'completed' } },+ };+ transport.emit(childItem);+ transport.emit(childUsage);+ transport.emit(childTurnEnd);+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' } },+ });+ transport.emit({+ method: 'item/started',+ params: { threadId: 'grandchild-thread', turnId: 't2', item: { id: 'i-2', type: 'mcpToolCall' } },+ });++ const descendantNotification = vi.fn();+ const descendantThreadStarted = vi.fn();+ const itemStarted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantNotification,+ descendantThreadStarted,+ itemStarted,+ });++ // 血缘照旧重建(child + grandchild)。+ expect(descendantThreadStarted).toHaveBeenCalledTimes(2);+ // 关键:child 的三条业务通知按到达顺序补投,grandchild 的也补投。+ expect(descendantNotification.mock.calls).toEqual([+ ['child-thread', 'item/started', childItem.params],+ ['child-thread', 'thread/tokenUsage/updated', childUsage.params],+ ['child-thread', 'turn/completed', childTurnEnd.params],+ [+ 'grandchild-thread',+ 'item/started',+ { threadId: 'grandchild-thread', turnId: 't2', item: { id: 'i-2', type: 'mcpToolCall' } },+ ],+ ]);+ // thread/started 不进本通道(有专用 handler),也不得重复投递业务通知到主线程通道。+ expect(descendantNotification.mock.calls.some(([, method]) => method === 'thread/started')).toBe(false);+ expect(itemStarted).not.toHaveBeenCalled();++ // 补投过一次后不再重复:同一批不会因后续血缘重建被投第二遍。+ descendantNotification.mockClear();+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'great-grandchild', parentThreadId: 'grandchild-thread' } },+ });+ expect(descendantNotification).not.toHaveBeenCalled();++ await subscription.release();+ await host.shutdown();+ });++ it('rescans buffered lineage when a live thread/started unlocks an already-buffered grandchild', async () => {+ // 与上一例的区别:root **已经订阅**,而孙线程的 thread/started 先于父线程到达。此时孙的+ // 血缘无从判断 → 连同它的业务通知一起缓存在孙自己的 id 下。父线程随后建立血缘时,原实现+ // 只排空父线程那一条队列(而且按契约跳过 thread/started),不再扫待解析的后代血缘 →+ // 孙线程的 tool / token / 终态通知一直烂在缓冲区,卡片漏计并可能持续显示运行中(review)。+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const descendantNotification = vi.fn();+ const descendantThreadStarted = vi.fn();+ const itemStarted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantNotification,+ descendantThreadStarted,+ itemStarted,+ });++ // 逆序:孙先到(父线程此刻还没有血缘),连它的业务通知一起被缓冲。+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' } },+ });+ const grandchildItem = {+ method: 'item/started',+ params: { threadId: 'grandchild-thread', turnId: 't2', item: { id: 'i-2', type: 'mcpToolCall' } },+ };+ const grandchildTurnEnd = {+ method: 'turn/completed',+ params: { threadId: 'grandchild-thread', turn: { id: 't2', status: 'completed' } },+ };+ transport.emit(grandchildItem);+ transport.emit(grandchildTurnEnd);+ expect(descendantThreadStarted).not.toHaveBeenCalled();+ expect(descendantNotification).not.toHaveBeenCalled();++ // 父线程血缘到达:必须顺带把孙线程解锁并补投它的缓冲通知。+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });++ expect(descendantThreadStarted).toHaveBeenCalledTimes(2);+ expect(descendantNotification.mock.calls).toEqual([+ ['grandchild-thread', 'item/started', grandchildItem.params],+ ['grandchild-thread', 'turn/completed', grandchildTurnEnd.params],+ ]);+ // 后代通知不得漏进主线程通道(否则子代理的工具会被渲染成主会话自己的调用)。+ expect(itemStarted).not.toHaveBeenCalled();++ // 孙线程血缘已建立:它之后的通知直接走 descendant 通道,不再进缓冲。+ descendantNotification.mockClear();+ transport.emit({+ method: 'item/started',+ params: { threadId: 'grandchild-thread', turnId: 't3', item: { id: 'i-3', type: 'webSearch' } },+ });+ expect(descendantNotification).toHaveBeenCalledTimes(1);++ await subscription.release();+ await host.shutdown();+ });++ it('resolves a deep buffered lineage chain from a single live thread/started', async () => {+ // 三代逆序:曾孙 → 孙 全部先到,最后才到子线程对 root 的血缘。一次重建要沿链解开。+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const descendantNotification = vi.fn();+ const descendantThreadStarted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantNotification,+ descendantThreadStarted,+ });++ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'great-grandchild', parentThreadId: 'grandchild-thread' } },+ });+ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'grandchild-thread', parentThreadId: 'child-thread' } },+ });+ transport.emit({+ method: 'item/started',+ params: { threadId: 'great-grandchild', turnId: 't9', item: { id: 'i-9', type: 'commandExecution' } },+ });+ expect(descendantThreadStarted).not.toHaveBeenCalled();++ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });++ // child + grandchild + great-grandchild 三代血缘全部建立,曾孙的工具通知补投到位。+ expect(descendantThreadStarted).toHaveBeenCalledTimes(3);+ expect(descendantNotification.mock.calls).toEqual([+ [+ 'great-grandchild',+ 'item/started',+ { threadId: 'great-grandchild', turnId: 't9', item: { id: 'i-9', type: 'commandExecution' } },+ ],+ ]);++ await subscription.release();+ await host.shutdown();+ });+});diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.tsindex 31379bccfb..79bd4e456d 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -123,6 +123,16 @@ function extractThreadId(method: string, params: unknown): string | null {export interface ThreadEventHandlers {threadStarted?: (params: ThreadStartedNotification['params']) => void;descendantThreadStarted?: (params: ThreadStartedNotification['params']) => void;+ /**+ * 子线程(子代理)自己的 notification,按 lineage 归到 root 订阅者。+ *+ * 刻意**不复用** dispatchToHandlers 的主线程通道:主线程 handler 带 turn 级簿记+ * (stale turn 判定、currentTurnId、status 推送、usageTracker 记账),子线程事件+ * 灌进去会把子代理的 exec/文件改动渲染成主会话自己的工具调用,并污染主 turn 的+ * 用量与状态机。这里只投递原始 method + params,由上层聚合成子代理卡的实时状态;+ * 上层不关心的 method 自行忽略。+ */+ descendantNotification?: (childThreadId: string, method: string, params: unknown) => void;turnStarted?: (params: TurnStartedNotification['params']) => void;turnCompleted?: (params: TurnCompletedNotification['params']) => void;/** 每次 turn 都会推一次 (turn 完成前), 与 turn/completed 在同 turnId 下成对出现。 */@@ -259,6 +269,8 @@ export class AppServerHost {private readonly lineageRoots = new Map<string, string>();/** 找不到 subscriber 时按 threadId 暂存的 notification, drain on subscribe。 */private readonly buffered = new Map<string, BufferedNotification[]>();+ /** 血缘迭代重建的重入闸(routeDescendantThreadStarted 与重建互相调用)。 */+ private replayingDescendantLineage = false;/*** 账号配额最近一次 snapshot, 给新 subscribeThread 立即重放 — 用户打开新 codex* session 时不必等下次 turn 完成才看到 chip 数据。整个 host 生命周期共享一份 (账号级)。@@ -772,6 +784,33 @@ export class AppServerHost {this.dispatchToHandlers(handlers, method, params);return;}+ // 已知的子线程(子代理):app-server 对连接内所有 loaded thread 主动推送,过滤全在+ // 本地。此前这里只按 subscribers 精确匹配,子线程的 item/tokenUsage/turn 事件因此+ // 全部落进 TTL 缓冲后被丢弃 —— 子代理在 UI 上没有任何实时状态。改为按 lineage 归到+ // root 的独立 descendant 通道(不进主线程 dispatch,见 descendantNotification 注释)。+ // thread/started 不进这条通道:它已由上面的 routeDescendantThreadStarted 经专用的+ // descendantThreadStarted handler 投递过。两条通道送同一事件会诱发重复处理,且+ // 它仍需按原样落缓冲 —— replayBufferedDescendantThreadStarts 靠子线程 id 下的+ // 缓冲项重建迟到订阅的孙线程血缘。+ const rootThreadId = method === 'thread/started' ? undefined : this.lineageRoots.get(threadId);+ if (rootThreadId && rootThreadId !== threadId) {+ const rootHandlers = this.subscribers.get(rootThreadId);+ if (rootHandlers?.descendantNotification) {+ try {+ rootHandlers.descendantNotification(threadId, method, params);+ } catch (e) {+ this.logger.error('descendant notification handler threw', {+ rootThreadId,+ childThreadId: threadId,+ method,+ message: (e as Error).message,+ });+ }+ }+ // 血缘已知就地收口:root 不消费时直接丢弃,不进缓冲(缓冲只为解 subscribe 竞争,+ // 子线程 id 永远不会被 subscribe,堆在那里只会等 TTL 到点白白清一遍)。+ return;+ }// subscribe 还没到 — 暂存 + TTL 清理。Codex 协议保证 server 内同 thread 顺序,// drain 时按到达顺序 dispatch 不会乱。this.bufferNotification(threadId, method, params);@@ -803,41 +842,100 @@ export class AppServerHost {if (!handlers) return;this.lineageRoots.set(childThreadId, rootThreadId);- if (!handlers.descendantThreadStarted) return;- try {- handlers.descendantThreadStarted(params);- } catch (e) {- this.logger.error('descendant thread handler threw', {- rootThreadId,- parentThreadId,- childThreadId,- message: (e as Error).message,- });+ if (handlers.descendantThreadStarted) {+ try {+ handlers.descendantThreadStarted(params);+ } catch (e) {+ this.logger.error('descendant thread handler threw', {+ rootThreadId,+ parentThreadId,+ childThreadId,+ message: (e as Error).message,+ });+ }+ }+ // 血缘刚建立:该子线程在此之前到达的 item / tokenUsage / turn 通知都缓存在**它自己的+ // id** 下(那时既不是 subscriber 也没有 lineage)。root 侧的 drain 只排空 root id 的队列,+ // 这些永远排不到 → 早期工具数、token 丢失,漏掉 turn/completed 还会让卡片永久停在+ // running(codex review)。这里按到达顺序补投进 descendant 通道。+ this.drainBufferedDescendantNotifications(childThreadId, rootThreadId, handlers);+ // 本次血缘建立可能解锁**孙**线程:孙的 thread/started 缓存在它自己的 id 下,上面的 drain+ // 只排空 childThreadId 的队列,而且它按契约会跳过 thread/started —— 不再扫一遍,孙线程的+ // 血缘永远建不起来,它的 tool / token / 终态通知会一直烂在缓冲区直到过期(卡片漏计,并+ // 可能一直显示运行中或提前完成)(review)。复用 root 订阅时那套迭代重建。+ this.replayBufferedDescendantThreadStarts(rootThreadId);+ }++ /**+ * 把某子线程在血缘建立前缓存的通知按原顺序补投给 root 的 descendant 通道。+ * `thread/started` 跳过 —— 它已由 routeDescendantThreadStarted 经专用 handler 投递过,+ * 而且 descendantNotification 的契约里不含它。+ */+ private drainBufferedDescendantNotifications(+ childThreadId: string,+ rootThreadId: string,+ handlers: ThreadEventHandlers,+ ): void {+ const buffered = this.buffered.get(childThreadId);+ if (!buffered) return;+ // 先删再投:补投过程中若又触发别的血缘重建,不会把同一批重复投一遍。+ this.buffered.delete(childThreadId);+ if (!handlers.descendantNotification) return;+ for (const item of buffered) {+ if (item.method === 'thread/started') continue;+ try {+ handlers.descendantNotification(childThreadId, item.method, item.params);+ } catch (e) {+ this.logger.error('buffered descendant notification handler threw', {+ rootThreadId,+ childThreadId,+ method: item.method,+ message: (e as Error).message,+ });+ }}}private replayBufferedDescendantThreadStarts(rootThreadId: string): void {+ // 重入保护:本方法会调用 routeDescendantThreadStarted,而后者现在又会回调本方法。+ // 嵌套再扫一遍是纯重复劳动(外层的 for(;;) 本来就会继续迭代直到没有新发现),+ // 深血缘下还会退化成 O(深度²)。让嵌套调用直接返回,由最外层那次跑完。+ if (this.replayingDescendantLineage) return;+ this.replayingDescendantLineage = true;+ try {+ this.replayBufferedDescendantThreadStartsInner(rootThreadId);+ } finally {+ this.replayingDescendantLineage = false;+ }+ }++ private replayBufferedDescendantThreadStartsInner(rootThreadId: string): void {// thread/started is buffered under the child id. A root subscription therefore// cannot drain those entries directly; rebuild the lineage iteratively so an// already-buffered child can unlock an already-buffered grandchild as well.for (;;) {- let discovered = 0;+ // 先快照本轮的候选再处理:routeDescendantThreadStarted 现在会把该 child 的缓冲队列+ // 排空并**从 this.buffered 删除**,边迭代边删同一个 Map 容易漏项。+ const candidates: ThreadStartedNotification['params'][] = [];for (const notifications of this.buffered.values()) {for (const item of notifications) {if (item.method !== 'thread/started') continue;- const params = item.params as ThreadStartedNotification['params'];- const childThreadId = params.thread?.id;- const parentThreadId = params.thread?.parentThreadId;- if (- !childThreadId- || !parentThreadId- || this.lineageRoots.has(childThreadId)- || this.lineageRoots.get(parentThreadId) !== rootThreadId- ) continue;- this.routeDescendantThreadStarted(params);- if (this.lineageRoots.get(childThreadId) === rootThreadId) discovered += 1;+ candidates.push(item.params as ThreadStartedNotification['params']);}}+ let discovered = 0;+ for (const params of candidates) {+ const childThreadId = params.thread?.id;+ const parentThreadId = params.thread?.parentThreadId;+ if (+ !childThreadId+ || !parentThreadId+ || this.lineageRoots.has(childThreadId)+ || this.lineageRoots.get(parentThreadId) !== rootThreadId+ ) continue;+ this.routeDescendantThreadStarted(params);+ if (this.lineageRoots.get(childThreadId) === rootThreadId) discovered += 1;+ }if (discovered === 0) return;}}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex f1aef067d1..32d043ea70 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -17062,6 +17062,60 @@ describe('CodexAgent reconnect-stall watchdog', () => {}});++ it('子代理进展不算主 turn 恢复:reconnect deadline 照旧到点收口', async () => {+ // eventQueue.push 的探针会刷新 upstreamIdleLastEventAt + armUpstreamIdle(),并把事件喂给+ // observeReconnectStallEvent —— 而 `agent_task_update` 就在 isReconnectRecoveryEvent 的+ // 白名单里(那对 Claude 主线程的 Task 更新是对的)。于是子线程一有进展就清掉 reconnect+ // deadline:主 turn 其实已经哑火,却因为子代理还在跑而永远检测不出来(review)。+ vi.useFakeTimers();+ try {+ const agent = new CodexAgent(createDeps());+ const { handle, handlers, seen } = await startReconnectTurn(+ agent,+ 'session-reconnect-descendant',+ );+ // spawn 登记必须发生在 reconnect 提示**之前**:itemStarted 是主线程事件,它本身就是+ // 合法的主 turn 进展、会清掉 deadline(第一版测试把它放在后面,于是测的是"主线程事件+ // 清了 deadline",而不是"子代理帧不该清")。+ handlers.descendantThreadStarted?.({+ thread: { id: 'child-1', parentThreadId: 'start-thread-id' },+ } as never);+ handlers.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: { id: 'spawn-1', type: 'subAgentActivity', kind: 'started', agentThreadId: 'child-1', agentPath: '/scout' },+ } as never);++ emitReconnect(handlers, 1);++ // 此后主线程一条事件都不发,只有子代理持续产出进展(每 30s 一次工具调用)。+ for (let i = 0; i < 4; i += 1) {+ await vi.advanceTimersByTimeAsync(30_000);+ handlers.descendantNotification?.('child-1', 'item/started', {+ threadId: 'child-1',+ turnId: 'child-turn',+ item: { id: `child-tool-${i}`, type: 'commandExecution' },+ });+ }++ // 卡片确实在更新(证明子代理帧真的流过来了,不是测试没生效)。+ expect(seen.filter((e) => e.type === 'agent_task_update').length).toBeGreaterThan(0);+ // 关键:deadline 不被子代理帧续命,照旧到点收口。+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS + 1);+ expect(seen).toContainEqual(expect.objectContaining({+ type: 'error',+ data: expect.objectContaining({+ reason: 'codex_reconnect_stalled',+ isTerminal: true,+ }),+ }));+ await handle.close();+ } finally {+ vi.useRealTimers();+ }+ });+it('后续 2/5、3/5 只更新进度,不延长首次提示建立的总 deadline', async () => {vi.useFakeTimers();try {@@ -17820,4 +17874,182 @@ describe('CodexAgent context window reporting', () => {await handle.close();});++ it('registers the subagent spawn mapping on item/updated, not just started/completed', async () => {+ // V1 的 spawn 是长跑 item(started → updated* → completed)。started 那帧若没到我们手里+ // (turn 缓冲、stale turn 丢弃、上游省略),原实现要等到 completed 才建立映射 —— 期间子线程+ // 的 item / token / 终态全被缓冲,卡片在整个运行期没有实时数据,最后才一次性补上。那正是本+ // PR 要解决的问题本身(review)。这里**只发 updated**,不发 started。+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-subagent-updated',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const handlers = host.getThreadHandlers();+ if (!handlers?.itemUpdated || !handlers.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected item/descendant handlers');+ }+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-sa' } });++ // 跳过 started,直接发 updated —— 映射必须在这一帧就建立。+ handlers.itemUpdated({+ threadId: 'start-thread-id',+ turnId: 'turn-sa',+ item: {+ id: 'spawn-item-1',+ type: 'collabAgentToolCall',+ tool: 'spawnAgent',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread-1'],+ status: 'inProgress',+ agentsStates: [],+ },+ });++ // 映射已就位 → 子线程的实时事件应当当场路由成卡片更新,而不是被缓冲到 completed。+ handlers.descendantThreadStarted({+ thread: { id: 'child-thread-1', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-thread-1', 'item/started', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-1',+ item: { id: 'child-tool-1', type: 'commandExecution' },+ });+ handlers.descendantNotification('child-thread-1', 'thread/tokenUsage/updated', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-1',+ tokenUsage: { total: { totalTokens: 4_242 } },+ });++ await vi.waitFor(() => {+ const updates = events.filter((e) => e.type === 'agent_task_update');+ expect(updates.length).toBeGreaterThan(0);+ });+ const updates = events+ .filter((e) => e.type === 'agent_task_update')+ .map((e) => e.data as { taskId?: string; status?: string; usage?: { totalTokens?: number; toolUses?: number } });+ // 运行期就能看到真实聚合(工具数与 token),不是等 completed 才补。+ expect(updates.some((u) => u.taskId === 'spawn-item-1')).toBe(true);+ const last = updates.filter((u) => u.taskId === 'spawn-item-1').at(-1);+ expect(last?.usage?.toolUses).toBe(1);+ expect(last?.usage?.totalTokens).toBe(4_242);+ expect(last?.status).toBe('running');++ await handle.close();+ });++ it('closes out running subagent cards when the transport dies (app-server crash / IO disconnect)', async () => {+ // 普通 transport 断连(app-server 崩溃 / stdio 断开)会作废订阅:后代通知**永远不会再到**,+ // 而 tracker 的终态只由后代 turn/completed 写入。原来这条路径只广播 error 并清主线程缓存,+ // 子代理卡就停在最后一帧 running —— 进程早死了,界面还在原地转圈(review)。close() 与+ // cleanup-failure 已复用同一套终态快照 + 清 tracker,这里补的是断连入口。+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-subagent-transport-drop',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const handlers = host.getThreadHandlers();+ if (!handlers?.itemStarted || !handlers.descendantThreadStarted || !handlers.descendantNotification) {+ throw new Error('expected item/descendant handlers');+ }+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-sa' } });+ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId: 'turn-sa',+ item: {+ id: 'spawn-item-1',+ type: 'collabAgentToolCall',+ tool: 'spawnAgent',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread-1'],+ status: 'inProgress',+ agentsStates: [],+ },+ });+ handlers.descendantThreadStarted({ thread: { id: 'child-thread-1', parentThreadId: 'start-thread-id' } });+ handlers.descendantNotification('child-thread-1', 'item/started', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-1',+ item: { id: 'child-tool-1', type: 'commandExecution' },+ });+ handlers.descendantNotification('child-thread-1', 'thread/tokenUsage/updated', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-1',+ tokenUsage: { total: { totalTokens: 1_234 } },+ });++ const cardFrames = () =>+ events+ .filter((e) => e.type === 'agent_task_update')+ .map(+ (e) => e.data as { taskId?: string; status?: string; usage?: { totalTokens?: number; toolUses?: number } },+ )+ .filter((u) => u.taskId === 'spawn-item-1');+ const flush = async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));+ };++ await vi.waitFor(() => {+ expect(cardFrames().at(-1)?.status).toBe('running');+ });++ // app-server 崩了:willRetry=false + scope=transport,turnId 为空(server 已经说不出是哪个 turn)。+ handlers.error?.({+ threadId: 'start-thread-id',+ turnId: '',+ willRetry: false,+ scope: 'transport',+ error: { message: 'app-server transport closed unexpectedly' },+ });++ await vi.waitFor(() => {+ expect(cardFrames().at(-1)?.status).toBe('stopped');+ });+ // 收口帧必须带上已聚合的真实用量,不能退化成空快照(否则用户看到「已停止 + 0 token」)。+ const terminal = cardFrames().at(-1);+ expect(terminal?.usage?.toolUses).toBe(1);+ expect(terminal?.usage?.totalTokens).toBe(1_234);++ const afterTerminal = cardFrames().length;+ // tracker 与 lineage 都已清:再来一次断连不重复投递终态;迟到的后代通知也不能让这张卡+ // 复活回 running 继续转圈(断连后子线程 id 已无归属,通知只会落进缓冲区自然淘汰)。+ handlers.error?.({+ threadId: 'start-thread-id',+ turnId: '',+ willRetry: false,+ scope: 'transport',+ error: { message: 'app-server transport closed unexpectedly' },+ });+ handlers.descendantNotification('child-thread-1', 'turn/started', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-2',+ });+ handlers.descendantNotification('child-thread-1', 'thread/tokenUsage/updated', {+ threadId: 'child-thread-1',+ turnId: 'child-turn-2',+ tokenUsage: { total: { totalTokens: 9_999 } },+ });+ await flush();+ expect(cardFrames()).toHaveLength(afterTerminal);++ // close() 走的是同一套 drain,清过之后必须幂等,不补第二帧终态。+ await handle.close();+ await flush();+ expect(cardFrames()).toHaveLength(afterTerminal);+ });});diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex a79d410a9e..e869129c99 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -112,6 +112,10 @@ import {extractRolloutUpdatePlanFunctionCallEvent,type CodexRuntimeState,} from './translator.js';+import {+ createSubagentLiveCardTracker,+ type SubagentLiveCardUpdate,+} from './subagent-live-cards.js';import {TurnRetryTracker,RETRY_ESCALATION_MAX_ELAPSED_MS,@@ -3105,12 +3109,87 @@ export class CodexAgent extends BaseAgent {}descendantMcpThreadIds.clear();};++ // ── 子代理卡实时状态(V1 / V2 双轨) ──────────────────────────────────────+ // 子代理跑在自己的 thread 里,app-server 把子线程的 item / tokenUsage / turn 通知+ // 一并推给本连接;host 按 lineage 归到 root 后经 descendantNotification 投到这里+ // (刻意不进主线程 dispatch,否则子代理的 exec 会被渲染成主会话自己的工具调用)。+ // 聚合逻辑在 subagent-live-cards.ts(纯函数、可单测),这里只负责把快照按 spawn 卡+ // 的同一 taskId 发成 agent_task_update —— 卡片本体与 Claude 子代理共用+ // AgentTaskCard,本改动只补 Codex 侧缺失的数据源,不新建 UI。+ /**+ * 正在发子代理卡帧 —— eventQueue.push 的探针据此跳过主 turn 存活判定。+ * 只在同步的 emitSubagentCardUpdate 内为 true(见那里的注释)。+ */+ let emittingDescendantUpdate = false;+ const subagentLiveCards = createSubagentLiveCardTracker();++ const emitSubagentCardUpdate = (update: SubagentLiveCardUpdate): void => {+ // 子代理帧**不得**参与主 turn 的存活判定。eventQueue.push 上装了探针:每条事件都会刷新+ // upstreamIdleLastEventAt + armUpstreamIdle(),并喂给 observeReconnectStallEvent ——+ // 而 `agent_task_update` 正在 isReconnectRecoveryEvent 的白名单里(那对 Claude 的主线程+ // Task 更新是对的,不能从白名单里删)。于是子线程一有进展就会重置主线程的静默计时、+ // 清掉 reconnect deadline:主 turn 其实已经哑火,却因为子代理还在跑而永远检测不出来+ // (review)。子线程有进展 ≠ 主 turn 已恢复。+ //+ // push 是同步的,所以这个标志在 set 与 clear 之间不会被别的事件穿插。+ emittingDescendantUpdate = true;+ try {+ eventQueue.push({+ type: 'agent_task_update',+ data: {+ provider: 'codex',+ taskId: update.taskId,+ parentToolUseId: update.taskId,+ status: update.status,+ ...(update.agentPath ? { title: update.agentPath } : {}),+ usage: {+ ...(update.totalTokens > 0 ? { totalTokens: update.totalTokens } : {}),+ ...(update.toolUses > 0 ? { toolUses: update.toolUses } : {}),+ durationMs: update.durationMs,+ },+ },+ source: 'codex',+ });+ } finally {+ emittingDescendantUpdate = false;+ }+ };++ const handleDescendantNotification = (+ childThreadId: string,+ method: string,+ params: unknown,+ ): void => {+ const update = subagentLiveCards.handleDescendantNotification(childThreadId, method, params);+ if (update) emitSubagentCardUpdate(update);+ };++ /**+ * 登记 spawn 映射,并回传"在 translator 之后重新声明真实聚合状态"的补发闭包。+ *+ * 发帧点必须在 translateItemNotification **之后**,两个理由:+ * - V2:translator 对 spawn 推一帧 status=running(无 usage),而重放出的状态可能+ * 已是终态 —— 先发会被那帧 running 盖回去(store 字段级 merge,usage 不丢但 status 丢);+ * - V1:spawn 是 collabAgentToolCall,translator 在 completed phase 会无条件推一帧+ * status=completed —— 那只是 spawn 工具调用自己收口,子线程可能还在跑。不重新声明+ * 就会把运行中的子代理提前标成完成,还会抹掉先到的 failed/stopped(review)。+ */+ const noteSubagentSpawnItem = (item: unknown): (() => void) | null => {+ const replayed = subagentLiveCards.noteSpawnItem(item);+ if (!replayed) return null;+ return () => emitSubagentCardUpdate(replayed);+ };const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {if (closed) return;closed = true;resetUpstreamIdleForTurnEnd();unregisterCodexMcpContext(threadId);unregisterDescendantCodexMcpContexts();+ // 与 close() 同规:handle 被终止后子代理卡不会再有消费者。同样先收终态再清 ——+ // 这条路径(thread cleanup failure / 强制 retire)恰恰是最容易留下永久转圈卡的。+ for (const update of subagentLiveCards.drainRunningForShutdown()) emitSubagentCardUpdate(update);+ subagentLiveCards.clear();abandonBufferedTurns(reason);abandonPendingCapabilitySteers();try { dismissAllPending(reason, 'deny'); } catch (e) { log.warn('dismissAllPending threw', { error: String(e) }); }@@ -4840,10 +4919,14 @@ export class CodexAgent extends BaseAgent {// 装探针:此处仍远早于 handlers 注册(事件开始流动),不会漏掉任何一条。const rawEventQueuePush = eventQueue.push;eventQueue.push = (ev: AgentEvent): boolean => {- upstreamIdleLastEventType = ev.type;- upstreamIdleLastEventAt = Date.now();- armUpstreamIdle();- observeReconnectStallEvent(ev);+ // 子代理卡帧只是"子线程有进展",不代表主 turn 还活着 —— 不参与静默计时与+ // reconnect 恢复判定,否则主 turn 哑火时会被子代理的心跳一直掩盖(review)。+ if (!emittingDescendantUpdate) {+ upstreamIdleLastEventType = ev.type;+ upstreamIdleLastEventAt = Date.now();+ armUpstreamIdle();+ observeReconnectStallEvent(ev);+ }return rawEventQueuePush(ev);};@@ -7084,7 +7167,13 @@ export class CodexAgent extends BaseAgent {parentThreadId,childThreadId,});+ // 嵌套子代理:孙线程的 spawn item 只出现在**子线程自己**的事件流里,主线程的+ // itemStarted 看不到,所以只能靠血缘把它并进父线程所属的那张卡 —— 否则孙线程的+ // 工具调用与 token 全部进 pending 且再也没有登记路径可以重放(greptile P1)。+ const replayed = subagentLiveCards.noteDescendantThread(childThreadId, parentThreadId);+ if (replayed) emitSubagentCardUpdate(replayed);},+ descendantNotification: handleDescendantNotification,turnStarted: (params) => {// turn/start RPC 已失败(超时/拒绝)但 daemon 实际已建 turn — 迟到的孤儿// turnStarted 不得重新激活已报终态错误的会话 (greptile P1): 立墓碑 +@@ -7263,6 +7352,8 @@ export class CodexAgent extends BaseAgent {if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);noteActiveToolContext(params.item, params.turnId);noteToolItemLifecycle(params.item, 'started');+ // 先登记再翻译:子线程通知可能紧随 spawn item 到达,映射就位才不丢首帧。+ const emitReplayedSubagentUpdate = noteSubagentSpawnItem(params.item);pushItemStatus(params.item);translateItemNotification('started', params, eventQueue, {rt: translatorRt,@@ -7271,6 +7362,8 @@ export class CodexAgent extends BaseAgent {? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }: {}),});+ // 重放帧后发:translator 刚推的 running 帧不得把已重放出的终态盖回去。+ emitReplayedSubagentUpdate?.();},itemUpdated: (params) => {if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemUpdated?.(params), {@@ -7280,6 +7373,12 @@ export class CodexAgent extends BaseAgent {if (interceptProposedPlanItem(params.item)) return;if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);noteActiveToolContext(params.item, params.turnId);+ // updated 也要登记映射,顺序与 started / completed 一致(先登记 → 翻译 → 后发重放帧)。+ // V1 的 spawn 是长跑 item(started → updated* → completed):started 那帧若没到我们手里+ // (turn 缓冲、stale turn 丢弃、上游省略),映射就要一直等到 completed 才建立 —— 期间+ // 子线程的 item / token / turn 终态全被缓冲,卡片在整个运行期(可能好几分钟)没有实时+ // 数据,最后才一次性补上。那恰好是本 PR 要解决的问题本身(review)。+ const emitReplayedSubagentUpdateOnUpdated = noteSubagentSpawnItem(params.item);translateItemNotification('updated', params, eventQueue, {rt: translatorRt,log,@@ -7287,6 +7386,7 @@ export class CodexAgent extends BaseAgent {? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }: {}),});+ emitReplayedSubagentUpdateOnUpdated?.();},itemCompleted: (params) => {if (enqueueIfBufferedTurn(params.turnId, () => handlers.itemCompleted?.(params), {@@ -7297,6 +7397,8 @@ export class CodexAgent extends BaseAgent {if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);noteActiveToolContext(params.item, params.turnId);noteToolItemLifecycle(params.item, 'completed');+ // 防御:spawn item 的 started phase 若被上游省略,completed 仍能补上映射。+ const emitReplayedSubagentUpdateOnCompleted = noteSubagentSpawnItem(params.item);translateItemNotification('completed', params, eventQueue, {rt: translatorRt,log,@@ -7304,6 +7406,7 @@ export class CodexAgent extends BaseAgent {? { onCompactBoundary: () => memoryFlushController?.onCompactBoundary() }: {}),});+ emitReplayedSubagentUpdateOnCompleted?.();// item 完成后, 若 turn 仍在跑, 先回到 'Generating...' 兜底 — 下一条 item 起来会再覆盖。// turn/completed 在 turn 结束时会 push 'Done' 终态, 不需要在这里特判。if (isTurnInFlight) pushStatus('Generating...');@@ -7405,6 +7508,12 @@ export class CodexAgent extends BaseAgent {const isTransportError = params.scope === 'transport';if (isTransportError) {subscriptionInvalidatedByTransport = true;+ // 订阅已作废(app-server 崩了 / IO 断开)→ 后代通知**永远不会再到**,而 tracker 只靠+ // 后代 turn/completed 写终态。不在这里收口,渲染端会一直留着最后一帧 running:进程+ // 早就死了,子代理卡还在原地转圈(review)。这条路径与 close() / cleanup-failure 是+ // 同一类,只是入口不同 —— 复用同一套终态快照 + 清 tracker。+ for (const update of subagentLiveCards.drainRunningForShutdown()) emitSubagentCardUpdate(update);+ subagentLiveCards.clear();dismissAllPendingUserInput('transport_error');activeToolContexts.clear();submittedUserInputByTurn.clear();@@ -7688,6 +7797,11 @@ export class CodexAgent extends BaseAgent {resetUpstreamIdleForTurnEnd();unregisterCodexMcpContext(threadId);unregisterDescendantCodexMcpContexts();+ // 会话收口后子代理卡不再有消费者。清状态**之前**必须先把仍在跑的卡收成终态:+ // 之后后代通知永远不会再到,只清内部状态会让渲染端一直留着最后一帧 running,卡片+ // 永久转圈(review)。+ for (const update of subagentLiveCards.drainRunningForShutdown()) emitSubagentCardUpdate(update);+ subagentLiveCards.clear();// close 时 buffer 里可能还有等对账的挂起请求 (codex R17 P2):// 统一按拒绝释放, 否则 handler 永远悬挂, dispatchServerRequest// 永不返回, server 侧请求卡死。diff --git a/packages/maker-core/src/agents/codex/subagent-live-cards.ts b/packages/maker-core/src/agents/codex/subagent-live-cards.tsnew file mode 100644index 0000000000..05325948d2--- /dev/null+++ b/packages/maker-core/src/agents/codex/subagent-live-cards.ts@@ -0,0 +1,545 @@+/**+ * Codex 子代理卡的实时状态聚合(V1 / V2 双轨通用)。+ *+ * 背景:子代理跑在自己的 thread 里,app-server 会把子线程的 item / tokenUsage / turn+ * 通知一并推给本连接(过滤全在客户端本地)。`AppServerHost` 按 lineage 把它们归到 root+ * 订阅者的 `descendantNotification` 通道 —— 刻意不走主线程 dispatch,否则子代理的+ * exec / 文件改动会被渲染成主会话自己的工具调用,还会污染主 turn 的用量与状态机。+ *+ * 本模块把那条原始通知流聚合成子代理卡需要的三个数字(tokens / 工具调用数 / 耗时)与+ * 状态,由调用方按同一 `taskId` 发 `agent_task_update`。卡片本体与 Claude 子代理共用+ * `AgentTaskCard`,这里只负责补齐 Codex 侧此前缺失的数据源,不引入新的 UI 概念。+ *+ * 四条容易踩空的语义,单测各有覆盖:+ * - **一次 spawn 可能扇出多个子线程**(V1 `spawnAgent` 的 `receiverThreadIds`),但它们+ * 共用同一张卡。聚合状态必须挂在 taskId 上、按 thread 分量累计,否则各线程用自己的+ * 计数器发同一个 taskId,后到的快照会把先到的覆盖成更小的值(token/工具数回退),+ * 且任一 sibling 先收口就会把整张卡误报成完成。+ * - **通知可能早于 spawn 登记到达**(子线程 `thread/started` 建立 lineage 后,父线程的+ * spawn item 还没被处理)。这类通知先缓冲,登记后重放,否则首个工具调用、初始 token+ * 甚至终态会永久缺失。+ * - **血缘边本身也可能早于归属到达**:子线程尚未归属时它就派出了孙线程。那条「孙 → 子」+ * 血缘是孙线程**唯一**的入卡途径(孙线程的 spawn item 只在子线程自己的事件流里,主线程+ * 看不到),丢了不会有第二次机会 —— 必须缓冲,并在父线程归属时**递归**补绑整条链。+ * - **spawn 自身失败是终态**:派发失败后子线程迟到的 `turn/started` / `turn/completed`+ * 不得把卡片翻回 running/completed。靠卡上的终态闩,不能只改当下已知线程的状态。+ *+ * 设计约束:+ * - **纯聚合、零 IO**:落在 translator/event-loop 热路径上,每条通知只做 Map 查 + 计数。+ * - **有界**:跟踪条目与缓冲都封顶,长会话大量 spawn 不无界增长。+ * - **不猜**:认不出的 method / item 一律忽略并返回 null,不合成任何状态。+ */++import { readCodexSubagentSpawnRegistration } from './translator.js';++export type SubagentLiveCardStatus = 'running' | 'completed' | 'failed' | 'stopped';++/** 一次聚合结果:调用方据此发 `agent_task_update`(字段与 `AgentTaskUsage` 对齐)。 */+export interface SubagentLiveCardUpdate {+ taskId: string;+ status: SubagentLiveCardStatus;+ agentPath?: string;+ /** 本卡全部子线程的累计 token 之和;未知为 0。 */+ totalTokens: number;+ /** 本卡全部子线程内的工具类 item 数;未知为 0。 */+ toolUses: number;+ durationMs: number;+}++export interface SubagentLiveCardTracker {+ /**+ * 主线程 item 里认出 spawn → 登记「子线程 id → 子代理卡 taskId」。+ *+ * 返回聚合快照 = 调用方应在 translator 之后发一帧 `agent_task_update` 把真实状态重新+ * 声明一次(两种情形:有早到通知/血缘被重放出状态;或该 taskId 已在跟踪 —— 此时+ * translator 的合成 `completed` 帧必须被真实聚合状态盖回去)。+ *+ * 返回 null = 非 spawn item,或 **spawn 自身失败**(translator 已推过 failed 帧,再补一帧+ * 只会把失败盖回运行中;此时卡片被上终态闩,后续子线程通知也翻不了案)。+ */+ noteSpawnItem(item: unknown): SubagentLiveCardUpdate | null;+ /**+ * 登记「子线程 → 其父线程」的血缘(host 的 `descendantThreadStarted` 对**每一代**都触发)。+ *+ * 嵌套子代理必须靠它:孙线程的 spawn item 出现在**子线程自己**的事件流里,主线程的+ * itemStarted 钩子永远看不到,所以 noteSpawnItem 不可能登记孙线程。父线程已归属某张卡时,+ * 把子线程并入同一张卡并重放其早到缓冲。+ *+ * 父线程**尚未**归属时不能丢弃:那可能只是 spawn item 还没到(乱序),而这条边是孙线程唯一+ * 的入卡途径 —— 先缓冲,父线程归属时递归补绑整条链。真正与子代理无关的血缘会自然淘汰。+ *+ * 返回聚合快照 = 有早到通知被重放出状态,**或**新线程并入改变了聚合状态(例如已显示完成的+ * 卡因为孙线程仍在跑而必须回到 running);否则 null。+ */+ noteDescendantThread(childThreadId: string, parentThreadId: string): SubagentLiveCardUpdate | null;+ /**+ * 消费一条子线程通知。返回聚合快照表示卡片需要刷新;返回 null = 与子代理卡无关+ * (不关心的 method、无效载荷),或该子线程尚未登记(已缓冲,等 spawn 到达后重放)。+ */+ handleDescendantNotification(+ childThreadId: string,+ method: string,+ params: unknown,+ ): SubagentLiveCardUpdate | null;+ /**+ * 连接/会话收口前,为所有**仍在跑**的卡产出终态快照(`stopped`)。+ *+ * 必须在 `clear()` 之前调用并把返回的帧发出去:tracker 只靠后代的 `turn/completed` 写终态,+ * 而 transport error / 强制 retire / thread cleanup failure 之后那些通知**永远不会再到**。+ * 光清内部状态的话,桌面与手机的 task-update map 会一直留着最后一帧 `running` —— 进程早就+ * 死了、或者用户已经重连,卡还在原地转圈(review)。+ */+ drainRunningForShutdown(): SubagentLiveCardUpdate[];+ /** 会话收口时清空(与 descendant MCP context 注销同点调用)。 */+ clear(): void;+ /** 诊断/测试用:当前跟踪的子代理卡数。 */+ readonly size: number;+}++/**+ * 计入「工具调用次数」的子线程 item 类型(排除 agentMessage / reasoning / plan 等非工具产出)。+ *+ * 这份名单已对**真实 codex 二进制**导出的协议 schema 逐项核对过(见 PR 说明的实测记录):+ * `codex app-server generate-json-schema` 的 `ThreadItem` 共 18 个变体,这里的 8 个全部存在+ * (无拼写错误),`sleep` 是核对时补上的 —— schema 里写明它是 "Display item emitted by the+ * interruptible `clock.sleep` tool",属工具调用,漏掉会少计一次。其余未计入的+ * (userMessage / hookPrompt / agentMessage / plan / reasoning / enteredReviewMode /+ * exitedReviewMode / contextCompaction / subAgentActivity)确非工具产出。+ */+const TOOL_ITEM_TYPES = new Set([+ 'commandExecution',+ 'mcpToolCall',+ 'dynamicToolCall',+ 'webSearch',+ 'fileChange',+ 'imageView',+ 'imageGeneration',+ 'collabAgentToolCall',+ 'sleep',+]);++/** 我们会消费的 method —— 只有这些值得在 spawn 登记前缓冲。 */+const CONSUMED_METHODS = new Set([+ 'item/started',+ // updated 也必须消费:长跑工具的首个可见阶段可能就是 updated(与主线程 spawn 路径同因),+ // 不收就会在 completed 到达前不计数,会话若先中断则永久漏计。去重靠 countedItemIds 的+ // item id,同一 item 的 started/updated/completed 只会计一次。+ 'item/updated',+ 'item/completed',+ 'thread/tokenUsage/updated',+ 'turn/started',+ 'turn/completed',+]);++const DEFAULT_MAX_TRACKED_CARDS = 64;+/** 早到通知的缓冲上限(线程数 × 每线程条数),防永不登记的线程无界堆积。 */+const MAX_PENDING_THREADS = 32;+const MAX_PENDING_PER_THREAD = 64;+/** 未归属血缘边的缓冲上限(父线程数 × 每父线程子线程数),同样防无界堆积。 */+const MAX_PENDING_LINEAGE_PARENTS = 32;+const MAX_PENDING_LINEAGE_CHILDREN = 32;+/**+ * 单卡工具 item 去重登记的条数上限。去重登记必须活到卡片淘汰(turn/completed 可能早于+ * 后台 item/completed,提前清会让迟到的 completed 重复计数),所以只能按条数封顶。+ */+const MAX_COUNTED_ITEM_IDS = 4096;++interface ThreadState {+ status: SubagentLiveCardStatus;+ /** 该子线程最新的**累计** token(tokenUsage.total 是快照,按线程覆盖而非相加)。 */+ totalTokens: number;+}++interface TrackedCard {+ taskId: string;+ agentPath?: string;+ startedAt: number;+ toolUses: number;+ /** 已计数的 item id:部分 item 只发 completed(如 imageView),据此防重复计数。 */+ countedItemIds: Set<string>;+ /** 同一次 spawn 的全部子线程(V1 可能多 receiver);状态与 token 分量按线程存。 */+ threads: Map<string, ThreadState>;+ /**+ * spawn 工具调用**自身**失败 → 卡片终态闩。一旦置位,任何子线程生命周期通知都不得再把+ * 状态翻回 running/completed:派发失败就是失败,子线程后续说什么都不改变这个结论(review)。+ */+ spawnFailed: boolean;+}++interface PendingNotification {+ method: string;+ params: unknown;+}++export function createSubagentLiveCardTracker(opts: {+ now?: () => number;+ maxTrackedCards?: number;+} = {}): SubagentLiveCardTracker {+ const now = opts.now ?? (() => Date.now());+ const maxTrackedCards = opts.maxTrackedCards ?? DEFAULT_MAX_TRACKED_CARDS;+ const cards = new Map<string, TrackedCard>();+ const taskIdByThread = new Map<string, string>();+ const pending = new Map<string, PendingNotification[]>();+ /**+ * 尚未归属任何卡的血缘边:`父线程 id → 子线程 id 集合`。+ *+ * 子线程的 `thread/started` 可能早于根线程的 spawn item 到达,而它在归属前就可能已经派出+ * 孙线程 —— 那条「孙 → 子」血缘此刻无从判断归属。以前直接丢弃,后果是父线程登记时只绑直接+ * 子线程,孙线程已缓冲的工具/token/终态永远不会重放:卡片漏计,还可能在孙线程仍在跑时提前+ * 显示完成(review)。这里先记下,父线程一归属就**递归**补绑整条血缘链。+ */+ const pendingLineage = new Map<string, Set<string>>();+ /**+ * 子线程**第一次被看见**的时刻(第一条缓冲通知或第一条未归属血缘边)。+ *+ * 建卡时 `startedAt` 不能直接用 now():spawn 的 started/updated 阶段可能缺失或晚到,等到+ * completed 才建卡时子线程其实已经跑了一段时间,而那段时间的通知都在缓冲里(没有时间戳)。+ * 用 now() 会把已消耗的时长整段漏掉 —— 长跑子代理甚至显示接近 0ms(review)。既然这套实现+ * 明确支持"通知早于 spawn 登记",起点就必须回溯到最早那条证据。+ */+ const firstSeenAt = new Map<string, number>();++ const noteFirstSeen = (threadId: string): void => {+ if (!firstSeenAt.has(threadId)) firstSeenAt.set(threadId, now());+ };++ /** 建卡时的起点:本次 spawn 的子线程里最早被看见的那个时刻,没有证据时才用当前时间。 */+ const earliestSeen = (threadIds: readonly string[]): number => {+ let earliest = now();+ for (const id of threadIds) {+ const seen = firstSeenAt.get(id);+ if (seen !== undefined && seen < earliest) earliest = seen;+ }+ return earliest;+ };++ const isTerminal = (status: SubagentLiveCardStatus): boolean => status !== 'running';++ const aggregateStatus = (card: TrackedCard): SubagentLiveCardStatus => {+ // 终态闩优先于一切子线程状态:spawn 自身失败就是失败。+ if (card.spawnFailed) return 'failed';+ let sawFailed = false;+ let sawStopped = false;+ for (const thread of card.threads.values()) {+ // 任一子线程仍在跑 → 整张卡仍在跑。sibling 先收口不得把卡提前收成完成。+ if (thread.status === 'running') return 'running';+ if (thread.status === 'failed') sawFailed = true;+ else if (thread.status === 'stopped') sawStopped = true;+ }+ if (card.threads.size === 0) return 'running';+ if (sawFailed) return 'failed';+ if (sawStopped) return 'stopped';+ return 'completed';+ };++ const snapshot = (card: TrackedCard): SubagentLiveCardUpdate => {+ let totalTokens = 0;+ for (const thread of card.threads.values()) totalTokens += thread.totalTokens;+ const status = aggregateStatus(card);+ // 这里**不能**因为收口就清 countedItemIds:app-server 允许 turn/completed 先发、后台+ // 收尾的 item/completed 随后才到(codex/index.ts 的终态墓碑注释写明了这个顺序)。清掉+ // 之后那条迟到的 completed 会被当成一个新工具再加一次,卡片最终工具数虚高(review)。+ // 去重登记改为跟卡同生命周期(dropCard 时随卡一起释放),只按条数封顶防长跑子代理无界增长。+ return {+ taskId: card.taskId,+ status,+ ...(card.agentPath ? { agentPath: card.agentPath } : {}),+ totalTokens,+ toolUses: card.toolUses,+ durationMs: Math.max(0, now() - card.startedAt),+ };+ };++ const pruneCards = (): void => {+ if (cards.size < maxTrackedCards) return;+ for (const [taskId, card] of cards) {+ if (isTerminal(aggregateStatus(card))) {+ dropCard(taskId);+ return;+ }+ }+ // 全在跑:淘汰最早插入的一张(Map 保序)。宁可丢最老的实时数据也不无界增长。+ const oldest = cards.keys().next();+ if (!oldest.done) dropCard(oldest.value);+ };++ const dropCard = (taskId: string): void => {+ const card = cards.get(taskId);+ if (card) {+ for (const childThreadId of card.threads.keys()) {+ if (taskIdByThread.get(childThreadId) === taskId) taskIdByThread.delete(childThreadId);+ }+ }+ cards.delete(taskId);+ };++ /** 把某子线程从它当前归属的卡上解绑(resume / 再 spawn 同线程时改绑到新卡)。 */+ const unbindThread = (childThreadId: string): void => {+ const previousTaskId = taskIdByThread.get(childThreadId);+ if (previousTaskId === undefined) return;+ taskIdByThread.delete(childThreadId);+ const previousCard = cards.get(previousTaskId);+ if (!previousCard) return;+ previousCard.threads.delete(childThreadId);+ if (previousCard.threads.size === 0) cards.delete(previousTaskId);+ };++ const bufferPending = (childThreadId: string, method: string, params: unknown): void => {+ if (!CONSUMED_METHODS.has(method)) return;+ noteFirstSeen(childThreadId);+ let queue = pending.get(childThreadId);+ if (!queue) {+ if (pending.size >= MAX_PENDING_THREADS) {+ // 淘汰最早缓冲的线程(它很可能永远不会被登记 —— 比如不属于任何子代理卡的后代)。+ const oldest = pending.keys().next();+ if (!oldest.done) pending.delete(oldest.value);+ }+ queue = [];+ pending.set(childThreadId, queue);+ }+ if (queue.length >= MAX_PENDING_PER_THREAD) queue.shift();+ queue.push({ method, params });+ };++ /** 记下一条尚未能判断归属的血缘边,等父线程归属后补绑。 */+ const bufferLineage = (childThreadId: string, parentThreadId: string): void => {+ noteFirstSeen(childThreadId);+ let children = pendingLineage.get(parentThreadId);+ if (!children) {+ if (pendingLineage.size >= MAX_PENDING_LINEAGE_PARENTS) {+ // 淘汰最早缓冲的父线程 —— 绝大多数是主线程自己的后代,永远不会归属任何子代理卡。+ const oldest = pendingLineage.keys().next();+ if (!oldest.done) pendingLineage.delete(oldest.value);+ }+ children = new Set<string>();+ pendingLineage.set(parentThreadId, children);+ }+ if (children.size >= MAX_PENDING_LINEAGE_CHILDREN && !children.has(childThreadId)) return;+ children.add(childThreadId);+ };++ /** 应用一条通知到卡上;返回是否产生了变化(无变化不必发帧)。 */+ const applyNotification = (+ card: TrackedCard,+ thread: ThreadState,+ method: string,+ params: unknown,+ ): boolean => {+ switch (method) {+ case 'item/started':+ case 'item/updated':+ case 'item/completed': {+ const item = (params as { item?: { type?: unknown; id?: unknown } } | null)?.item;+ const itemType = typeof item?.type === 'string' ? item.type : '';+ const itemId = typeof item?.id === 'string' ? item.id : '';+ if (!itemId || !TOOL_ITEM_TYPES.has(itemType)) return false;+ if (card.countedItemIds.has(itemId)) return false;+ // 按插入序淘汰最老的 id(Set 保序)。上限远大于任何真实迟到窗口 —— 被淘汰的 id 只在+ // "几千个工具调用之前那一条的 completed 现在才到"时才会重复计数,现实中不发生。+ if (card.countedItemIds.size >= MAX_COUNTED_ITEM_IDS) {+ const oldest = card.countedItemIds.values().next();+ if (!oldest.done) card.countedItemIds.delete(oldest.value);+ }+ card.countedItemIds.add(itemId);+ card.toolUses += 1;+ return true;+ }+ case 'thread/tokenUsage/updated': {+ const total = (params as { tokenUsage?: { total?: { totalTokens?: unknown } } } | null)+ ?.tokenUsage?.total?.totalTokens;+ if (typeof total !== 'number' || !Number.isFinite(total)) return false;+ // total 是该线程的累计快照 → 覆盖本线程分量,卡片总量由各线程求和。+ thread.totalTokens = total;+ return true;+ }+ case 'turn/started':+ thread.status = 'running';+ return true;+ case 'turn/completed': {+ const turnStatus = (params as { turn?: { status?: unknown } } | null)?.turn?.status;+ thread.status = turnStatus === 'failed'+ ? 'failed'+ : turnStatus === 'interrupted'+ ? 'stopped'+ : turnStatus === 'inProgress'+ ? 'running'+ : 'completed';+ return true;+ }+ default:+ return false;+ }+ };++ /**+ * 把一个子线程并入卡:绑定 → 重放它的早到通知 → **递归**补绑它在归属前自己派出的后代。+ *+ * 递归是必需的,不是保险:孙线程的 spawn item 只出现在子线程自己的事件流里,主线程的+ * itemStarted 钩子永远看不到,所以除了这条路径没有别的机会把孙线程并进卡。+ *+ * `visited` 防环:血缘理论上是树,但通知来自外部进程,不能假定它一定是树。+ * 返回是否有内容被重放(调用方据此判断要不要发帧)。+ */+ const attachThread = (card: TrackedCard, childThreadId: string, visited: Set<string>): boolean => {+ if (visited.has(childThreadId)) return false;+ visited.add(childThreadId);++ if (taskIdByThread.get(childThreadId) !== card.taskId) unbindThread(childThreadId);+ if (!card.threads.has(childThreadId)) {+ // 已上终态闩的卡,新并入的线程直接算失败,别让它把卡拉回 running。+ card.threads.set(childThreadId, {+ status: card.spawnFailed ? 'failed' : 'running',+ totalTokens: 0,+ });+ }+ taskIdByThread.set(childThreadId, card.taskId);+ const thread = card.threads.get(childThreadId)!;++ let replayed = false;+ const queued = pending.get(childThreadId);+ if (queued) {+ pending.delete(childThreadId);+ for (const entry of queued) {+ if (applyNotification(card, thread, entry.method, entry.params)) replayed = true;+ }+ }++ const descendants = pendingLineage.get(childThreadId);+ if (descendants) {+ pendingLineage.delete(childThreadId);+ for (const grandChildId of descendants) {+ if (attachThread(card, grandChildId, visited)) replayed = true;+ }+ }+ return replayed;+ };++ return {+ noteSpawnItem(item: unknown): SubagentLiveCardUpdate | null {+ const registration = readCodexSubagentSpawnRegistration(item);+ if (!registration) return null;++ const existing = cards.get(registration.taskId);+ const card: TrackedCard = existing ?? {+ taskId: registration.taskId,+ ...(registration.agentPath ? { agentPath: registration.agentPath } : {}),+ startedAt: earliestSeen(registration.childThreadIds),+ toolUses: 0,+ countedItemIds: new Set<string>(),+ threads: new Map<string, ThreadState>(),+ spawnFailed: false,+ };+ if (!existing) {+ pruneCards();+ cards.set(card.taskId, card);+ }++ // spawn **本身**收口为失败:translator 已推过 failed 帧,这里绝不能再补一帧聚合快照+ // —— 那时子线程还标着 running,会把真实的失败终态盖回成运行中。上终态闩(而不是只把+ // 当下已知的线程标 failed):迟到的 turn/started / turn/completed 会把线程状态改回+ // running/completed,只标线程状态挡不住(review)。闩上之后仍继续吸收 token / 工具计数+ // —— 派发失败但子线程已经烧掉的量该算进去,只是状态恒为 failed。+ if (registration.failed) {+ card.spawnFailed = true;+ const visited = new Set<string>();+ let replayedOnFailure = false;+ for (const childThreadId of registration.childThreadIds) {+ if (attachThread(card, childThreadId, visited)) replayedOnFailure = true;+ const thread = card.threads.get(childThreadId);+ if (thread) thread.status = 'failed';+ }+ // started phase 缺失或晚到时,子线程的工具/token 通知会先进缓冲、由上面的 attachThread+ // 重放出来;若此后再无通知,无条件返回 null 就意味着这些用量永远不显示 —— 而 translator+ // 的 failed 帧本身不带 usage(review)。有了 spawnFailed 闩,snapshot() 恒为 failed,+ // 补发这一帧不会重现"把失败盖回运行中"的老问题。+ return replayedOnFailure ? snapshot(card) : null;+ }++ const visited = new Set<string>();+ let replayed = false;+ for (const childThreadId of registration.childThreadIds) {+ if (attachThread(card, childThreadId, visited)) replayed = true;+ }++ // 已登记过的 spawn(同一 collabAgentToolCall 的 started/completed 两个 phase 都会到+ // 这里)**必须无条件回传快照**:translator 在 completed phase 会无条件推一帧+ // status=completed —— 那是 spawn 工具调用自己收口,不代表子代理跑完。调用方在+ // translator 之后重发本快照,真实聚合状态才不会被那帧合成的 completed 覆盖,否则仍在+ // 跑的子线程会被提前标成完成,先到的 failed/stopped 也会被抹掉。+ // (attachThread 幂等:已在卡上的线程不会被重置计数。)+ if (existing) return snapshot(card);+ return replayed ? snapshot(card) : null;+ },++ noteDescendantThread(childThreadId: string, parentThreadId: string): SubagentLiveCardUpdate | null {+ if (!childThreadId || !parentThreadId || childThreadId === parentThreadId) return null;+ const taskId = taskIdByThread.get(parentThreadId);+ if (taskId === undefined) {+ // 父线程还没归属:**不能丢**。它可能只是 spawn item 尚未到达(乱序),而本次血缘正是+ // 孙线程唯一的入卡途径 —— 丢了就再没有第二次机会。先缓冲,父线程归属时递归补绑。+ bufferLineage(childThreadId, parentThreadId);+ return null;+ }+ const card = cards.get(taskId);+ if (!card) return null;+ // 已并入同一张卡:幂等,不重置计数。+ if (taskIdByThread.get(childThreadId) === taskId && card.threads.has(childThreadId)) return null;++ // 新线程并入会改变聚合状态(比如把已显示完成的卡拉回 running —— 孙线程还在跑,卡片就+ // 不该说完成),所以发帧条件不只看有没有重放内容,还看聚合状态是否因此改变。+ const before = aggregateStatus(card);+ const replayed = attachThread(card, childThreadId, new Set<string>());+ return replayed || aggregateStatus(card) !== before ? snapshot(card) : null;+ },++ handleDescendantNotification(+ childThreadId: string,+ method: string,+ params: unknown,+ ): SubagentLiveCardUpdate | null {+ const taskId = taskIdByThread.get(childThreadId);+ if (taskId === undefined) {+ // spawn item 还没被处理(乱序):缓冲等重放,别丢掉首个工具调用或终态。+ bufferPending(childThreadId, method, params);+ return null;+ }+ const card = cards.get(taskId);+ const thread = card?.threads.get(childThreadId);+ if (!card || !thread) return null;+ if (!applyNotification(card, thread, method, params)) return null;+ return snapshot(card);+ },++ drainRunningForShutdown(): SubagentLiveCardUpdate[] {+ const out: SubagentLiveCardUpdate[] = [];+ for (const card of cards.values()) {+ if (isTerminal(aggregateStatus(card))) continue;+ // 会话没了不代表子代理"失败"了 —— 它是被中断的,所以报 stopped 而不是 failed。+ // 直接改线程状态而不是在 snapshot 里特判:这样 aggregateStatus 自然收敛到 stopped,+ // 也保住了 spawnFailed 闩的优先级(派发本身失败过的卡仍报 failed)。+ for (const thread of card.threads.values()) {+ if (thread.status === 'running') thread.status = 'stopped';+ }+ if (card.threads.size === 0) {+ // 一个线程都还没登记上的卡(spawn 刚认出、子线程尚未 started):补一个占位线程,+ // 否则 aggregateStatus 对空集合返回 running,这张卡还是会留在转圈状态。+ card.threads.set('__shutdown__', { status: 'stopped', totalTokens: 0 });+ }+ out.push(snapshot(card));+ }+ return out;+ },++ clear(): void {+ cards.clear();+ taskIdByThread.clear();+ pending.clear();+ pendingLineage.clear();+ firstSeenAt.clear();+ },++ get size(): number {+ return cards.size;+ },+ };+}diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex ba3b9a5533..8f2a1bfd57 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -1167,7 +1167,7 @@ describe('translateItemNotification subAgentActivity', () => {};}- it('renders a self-closing spawn card for kind=started (0.145 v2 emits no collab item)', async () => {+ it('renders a running spawn card for kind=started (0.145 v2 emits no collab item)', async () => {const rt = newCodexRuntimeState();const q = createAsyncQueue<AgentEvent>();const ctx = makeCtx(rt);@@ -1179,6 +1179,7 @@ describe('translateItemNotification subAgentActivity', () => {'tool_use','tool_result_full','tool_result',+ 'agent_task_update',]);expect(events[0].data).toMatchObject({toolUseId: 'spawn-1',@@ -1191,6 +1192,15 @@ describe('translateItemNotification subAgentActivity', () => {fullText: '/root/survey_startup',isError: false,});+ // tool_result 就地收口(不留悬空工具调用),卡片状态由 update 主导 → 仍显示运行中,+ // 后续 tokens / 工具数 / 终态由子线程通知按同一 taskId 增量刷新。+ expect(events[3].data).toMatchObject({+ provider: 'codex',+ taskId: 'spawn-1',+ parentToolUseId: 'spawn-1',+ status: 'running',+ title: '/root/survey_startup',+ });});it('dedupes the started/completed phase pair and releases the dedupe entry', async () => {diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex f24bb3011c..b52698951f 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -1564,16 +1564,19 @@ function handleCollabAgentToolCall(});}-// ── subAgentActivity → tool_use + tool_result(spawn 可见性) ────────────────+// ── subAgentActivity → tool_use + agent_task_update(spawn 可见性) ───────────// codex 0.145 multi-agent v2:spawn_agent 不发 collabAgentToolCall,只发瞬时// SubAgentActivityItem(kind=started/interacted/interrupted,无完成事件——子代理// 的等待与收口由后续 wait_agent 的 collab 卡承载)。不处理它,子代理启动在 UI// 完全不可见(实测:探索型任务 spawn 3 个子代理,等待窗口内聊天流零卡片)。-// started 渲染成一张即时收口的「子代理已启动」卡;interacted 是 followup/send-// 调用的伴生事件、interrupted 由 interrupt 调用自身承载,均显式静默不再落-// unhandled 告警。协议只给 id/kind/agentThreadId/agentPath,没有 prompt/model/-// effort(上游 main 已改为 spawn 直发 collabAgentToolCall 富卡,vendored codex-// 升级后自动走上面 handleCollabAgentToolCall,本函数届时按 id 去重自然让位)。+// started 渲染成子代理卡并置 running:卡片本体与 Claude 子代理共用+// AgentTaskCard,后续 tokens / 工具调用数 / 耗时与终态由 codex/index.ts 消费子+// 线程 notification 后按同一 taskId 增量更新(见 descendantNotification)。+// interacted 是 followup/send 调用的伴生事件、interrupted 由 interrupt 调用自身+// 承载,均显式静默不再落 unhandled 告警。协议只给 id/kind/agentThreadId/+// agentPath,没有 prompt/model/effort(上游 main 已改为 spawn 直发+// collabAgentToolCall 富卡,vendored codex 升级后自动走上面+// handleCollabAgentToolCall,本函数届时按 id 去重自然让位)。interface SubAgentActivityItem {type: 'subAgentActivity';@@ -1583,6 +1586,59 @@ interface SubAgentActivityItem {agentPath?: string;}+/**+ * 从 spawn 类 item 抽出「子线程 id → 子代理卡 taskId」的登记信息,双轨通用:+ * - V2(0.145):`subAgentActivity` kind=started,带 agentThreadId+ * - V1 与上游 main:`collabAgentToolCall` 的 spawn 工具,派发目标在 receiverThreadIds+ *+ * 放在 translator 是因为 item 形状知识归它所有;codex/index.ts 只消费结果,不再+ * 自己 narrow item 字段。返回 null = 不是 spawn(调用方直接忽略)。+ */+export function readCodexSubagentSpawnRegistration(item: unknown): {+ taskId: string;+ childThreadIds: string[];+ agentPath?: string;+ /**+ * spawn **本身**收口为失败(V1 `collabAgentToolCall.status === 'failed'`)。+ * translator 此时已推过 failed 帧,聚合器据此不得再用快照(仍是 running)盖回去。+ * V2 的 subAgentActivity 没有 status 字段,恒为 undefined。+ */+ failed?: boolean;+} | null {+ if (!item || typeof item !== 'object') return null;+ const record = item as Record<string, unknown>;+ const taskId = typeof record.id === 'string' && record.id ? record.id : null;+ if (!taskId) return null;++ if (record.type === 'subAgentActivity') {+ if (record.kind !== 'started') return null;+ const childThreadId = typeof record.agentThreadId === 'string' ? record.agentThreadId : '';+ if (!childThreadId) return null;+ return {+ taskId,+ childThreadIds: [childThreadId],+ ...(typeof record.agentPath === 'string' && record.agentPath ? { agentPath: record.agentPath } : {}),+ };+ }++ if (record.type === 'collabAgentToolCall') {+ // 工具名两轨拼写不同(V1 spawnAgent / 上游 main spawn),都以 spawn 前缀判定。+ const tool = typeof record.tool === 'string' ? record.tool : '';+ if (!tool.toLowerCase().startsWith('spawn')) return null;+ const receivers = Array.isArray(record.receiverThreadIds)+ ? record.receiverThreadIds.filter((id): id is string => typeof id === 'string' && id.length > 0)+ : [];+ if (receivers.length === 0) return null;+ return {+ taskId,+ childThreadIds: receivers,+ ...(record.status === 'failed' ? { failed: true } : {}),+ };+ }++ return null;+}+function handleSubAgentActivity(phase: ItemPhase,item: SubAgentActivityItem,@@ -1620,6 +1676,19 @@ function handleSubAgentActivity(data: { summary: 'started', toolUseIds: [item.id] },source: 'codex',});+ // 卡片置 running:tool_result 已就地收口(不留悬空工具调用),而 AgentTaskCard 的+ // status 以 update 优先,子代理仍显示为运行中,直到子线程 turn 收口把它翻成终态。+ queue.push({+ type: 'agent_task_update',+ data: {+ provider: 'codex',+ taskId: item.id,+ parentToolUseId: item.id,+ status: 'running',+ ...(agentPath ? { title: agentPath } : {}),+ },+ source: 'codex',+ });}function toCodexTaskUpdate(diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.tsindex 5efb5e4146..599e909d04 100644--- a/packages/maker-shared/src/__tests__/agentTask.test.ts+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts@@ -312,6 +312,30 @@ describe('buildAgentTaskCardModel', () => {expect(model.provider).toBe('codex');});+ it('drops the spawn receipt once live subagent state exists (card parity with claude)', () => {+ // 子线程送来 tokens / 工具数后,title + 运行状态已表达同样信息;再显示+ // 「Subagent X 已启动」会让 codex 卡比 Claude 子代理卡多一行冗余文案。+ const model = buildAgentTaskCardModel({+ toolName: 'collab:spawn',+ toolInput: { name: '/root/survey_startup', agentThreadId: 't-2' },+ result: '/root/survey_startup',+ update: {+ provider: 'codex',+ taskId: 'spawn-1',+ status: 'running',+ title: '/root/survey_startup',+ usage: { totalTokens: 1200, toolUses: 3, durationMs: 4200 },+ },+ });+ expect(model.spawnedAgentName).toBeUndefined();+ // 裸 agentPath 同样不许漏进 summary。+ expect(model.summary).toBeUndefined();+ expect(model.status).toBe('running');+ expect(model.totalTokens).toBe(1200);+ expect(model.toolUses).toBe(3);+ expect(model.durationMs).toBe(4200);+ });+it('leaves future rich collab:spawn results (agentsStates summaries) untouched', () => {const model = buildAgentTaskCardModel({toolName: 'collab:spawn',diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.tsindex 9c26ea12e9..9cae6009c8 100644--- a/packages/maker-shared/src/agentTask.ts+++ b/packages/maker-shared/src/agentTask.ts@@ -364,10 +364,15 @@ export function buildAgentTaskCardModel(input: {const description = compactText(update?.description ?? readInputString(toolInput, ['prompt', 'description', 'task']),);- const spawnedAgentName = subagentSpawnReceiptName(toolName, toolInput, result);+ const spawnReceiptName = subagentSpawnReceiptName(toolName, toolInput, result);+ // 有实时 update(子线程送来的 tokens / 工具调用数 / 终态)时不再暴露启动回执:+ // title 与运行状态已经表达了同样的信息,再显示「Subagent X 已启动」会让 codex 卡+ // 比 Claude 子代理卡多出一行冗余文案 —— 两者共用同一张卡,形态必须一致。历史回放+ // 拿不到 live update,回执仍是唯一可读摘要,保留原样。+ const spawnedAgentName = update ? undefined : spawnReceiptName;// 启动回执命中时 summary 不携带裸路径(路径已在 spawnedAgentName / title 中),// 否则手机端会把 agentPath 原样当摘要展示。- const summary = spawnedAgentName ? detailText(update?.summary) : detailText(result, update?.summary);+ const summary = spawnReceiptName ? detailText(update?.summary) : detailText(result, update?.summary);return {status,provider,