Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: preserve late agent terminals and model catalogs (#1643)
Kafeifei6cdcadeab94a
diff --git a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.tsindex 5704623c0b..43629febcb 100644--- a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts+++ b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts@@ -215,6 +215,24 @@ describe('interrupted continuation enqueue contract', () => {);});+ it('keeps background substantive events out of interrupted-turn progress bookkeeping', () => {+ const progressStart = registerSource.indexOf(+ "if (event.turnScope !== 'background' && isSubstantiveProgressEvent(event))",+ );+ expect(progressStart).toBeGreaterThan(-1);+ const progressEnd = registerSource.indexOf(+ '\n }\n if (event.type === \'text\')',+ progressStart,+ );+ expect(progressEnd).toBeGreaterThan(progressStart);+ const progressBlock = registerSource.slice(progressStart, progressEnd);+ expect(progressBlock).toContain('interruptedTurnAutoResumeGuard.noteProgress(');+ expect(registerSource.indexOf('onToolUseEvent(', progressEnd)).toBeGreaterThan(progressEnd);+ expect(+ registerSource.indexOf('broadcastToAllWindows(MAKER_PUSH.EVENT', progressEnd),+ ).toBeGreaterThan(progressEnd);+ });+it('advertises interval null-clear support for mobile wire compatibility', () => {expect(registerSource).toMatch(/supportsScheduleIntervalNullClear:\s*true/);});diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex eac8f150d0..0e00c501a0 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -76,9 +76,11 @@ import {markAssistantTurnFailed,noteSessionClearBoundary,noteSessionAgentKind,+ noteAgentMeta,enqueueDurableWrite,noteTurnStarted,saveTurnStartedAtForDeferred,+ preserveTurnPersistStateForBackground,} from '../messagePersistBroadcaster.js';const SESSION = 'sess-tr';@@ -378,6 +380,281 @@ describe('tool_result 顺序:先 tool_result(摘要)后 tool_result_full(全文)});});+describe('background tool_result persistence', () => {+ it('reconstructs a completed-only background collab tool context', async () => {+ const lateMeta = { uuid: 'late-completed-only-turn' };+ const toolUsePersistId = onToolUseEvent(+ SESSION,+ {+ toolUseId: 'late-completed-only-child',+ toolName: 'collab:spawnAgent',+ input: { receiverThreadIds: ['child-thread'] },+ },+ lateMeta,+ 'background',+ );++ const fullResult = onToolResultFullEvent(+ SESSION,+ { toolUseId: 'late-completed-only-child', fullText: FULL },+ null,+ 'background',+ );+ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-completed-only-child'] },+ null,+ 'background',+ );++ await flushWrites();++ expect(fullResult).toEqual({ persistId: expect.any(String), content: FULL });+ expect(result).toEqual(fullResult);+ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ clientId: toolUsePersistId,+ role: 'tool_use',+ toolUseId: 'late-completed-only-child',+ agentMeta: lateMeta,+ }),+ broadcastGuard(),+ );+ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ role: 'tool_result',+ content: FULL,+ toolUseId: 'late-completed-only-child',+ agentMeta: lateMeta,+ }),+ broadcastGuard(),+ );+ });++ it('drops a completed-only background collab context owned by a pre-clear turn', async () => {+ const turnStartedAt = Date.parse('2026-06-20T10:05:00.000Z');+ const clearAt = Date.parse('2026-06-20T10:05:05.000Z');+ const lateItemAt = Date.parse('2026-06-20T10:05:10.000Z');+ noteSessionClearBoundary(SESSION, clearAt);+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(lateItemAt);++ const toolUsePersistId = onToolUseEvent(+ SESSION,+ {+ toolUseId: 'late-completed-only-cleared-child',+ toolName: 'collab:spawnAgent',+ input: { receiverThreadIds: ['child-thread'] },+ },+ null,+ 'background',+ turnStartedAt,+ );+ const fullResult = onToolResultFullEvent(+ SESSION,+ { toolUseId: 'late-completed-only-cleared-child', fullText: FULL },+ null,+ 'background',+ );+ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-completed-only-cleared-child'] },+ null,+ 'background',+ );+ try {+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(toolUsePersistId).toBeUndefined();+ expect(fullResult).toBeNull();+ expect(result).toBeNull();+ expect(createMessage).not.toHaveBeenCalled();+ });++ it('keeps a completed-only background collab context owned by a post-clear turn', async () => {+ const clearAt = Date.parse('2026-06-20T10:05:00.000Z');+ const turnStartedAt = Date.parse('2026-06-20T10:05:05.000Z');+ const lateItemAt = Date.parse('2026-06-20T10:05:10.000Z');+ noteSessionClearBoundary(SESSION, clearAt);+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(lateItemAt);++ const toolUsePersistId = onToolUseEvent(+ SESSION,+ {+ toolUseId: 'late-completed-only-post-clear-child',+ toolName: 'collab:spawnAgent',+ input: { receiverThreadIds: ['child-thread'] },+ },+ null,+ 'background',+ turnStartedAt,+ );+ const fullResult = onToolResultFullEvent(+ SESSION,+ { toolUseId: 'late-completed-only-post-clear-child', fullText: FULL },+ null,+ 'background',+ );+ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-completed-only-post-clear-child'] },+ null,+ 'background',+ );+ try {+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(toolUsePersistId).toEqual(expect.any(String));+ expect(fullResult).toEqual({ persistId: expect.any(String), content: FULL });+ expect(result).toEqual(fullResult);+ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ clientId: toolUsePersistId,+ role: 'tool_use',+ toolUseId: 'late-completed-only-post-clear-child',+ }),+ broadcastGuard(),+ );+ });++ it('keeps the completed turn context after the next turn resets live state', async () => {+ const oldMeta = { uuid: 'old-turn' };+ const nextMeta = { uuid: 'new-turn' };+ noteAgentMeta(SESSION, oldMeta);+ onToolUseEvent(+ SESSION,+ { toolUseId: 'late-child', toolName: 'collab:spawnAgent', input: {} },+ oldMeta,+ );+ preserveTurnPersistStateForBackground(SESSION);+ resetTurnPersistState(SESSION);+ // Simulate the next turn repopulating the live fallback before the old+ // child result arrives.+ noteAgentMeta(SESSION, nextMeta);+ onToolUseEvent(+ SESSION,+ { toolUseId: 'next-turn-tool', toolName: 'Read', input: {} },+ nextMeta,+ );++ const fullResult = onToolResultFullEvent(+ SESSION,+ { toolUseId: 'late-child', fullText: FULL },+ null,+ 'background',+ );+ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-child'] },+ null,+ 'background',+ );++ await flushWrites();++ expect(fullResult).toEqual({ persistId: expect.any(String), content: FULL });+ expect(result).toEqual(fullResult);+ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({+ role: 'tool_result',+ content: FULL,+ agentMeta: oldMeta,+ }),+ broadcastGuard(),+ );+ });++ it('retains an in-flight background context beyond four later turns', async () => {+ const oldMeta = { uuid: 'old-in-flight-turn' };+ noteAgentMeta(SESSION, oldMeta);+ onToolUseEvent(+ SESSION,+ { toolUseId: 'late-child-long', toolName: 'collab:spawnAgent', input: {} },+ oldMeta,+ );+ preserveTurnPersistStateForBackground(SESSION);+ resetTurnPersistState(SESSION);++ for (let i = 0; i < 5; i += 1) {+ const meta = { uuid: `later-turn-${i}` };+ noteAgentMeta(SESSION, meta);+ onToolUseEvent(+ SESSION,+ { toolUseId: `later-child-${i}`, toolName: 'collab:spawnAgent', input: {} },+ meta,+ );+ preserveTurnPersistStateForBackground(SESSION);+ resetTurnPersistState(SESSION);+ }++ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-child-long'] },+ null,+ 'background',+ );++ await flushWrites();++ expect(result).toEqual({ persistId: expect.any(String), content: SUMMARY });+ expect(createMessage).toHaveBeenCalledWith(+ SESSION,+ expect.objectContaining({ role: 'tool_result', agentMeta: oldMeta }),+ broadcastGuard(),+ );+ });++ it('drops a late background result whose parent tool_use predates session clear', async () => {+ const toolUseAt = Date.parse('2026-06-20T10:05:00.000Z');+ const clearAt = Date.parse('2026-06-20T10:05:05.000Z');+ const lateResultAt = Date.parse('2026-06-20T10:05:10.000Z');+ const nowSpy = vi.spyOn(Date, 'now');+ nowSpy.mockReturnValue(toolUseAt);+ onToolUseEvent(+ SESSION,+ { toolUseId: 'late-cleared-child', toolName: 'collab:spawnAgent', input: {} },+ { uuid: 'old-turn' },+ );+ preserveTurnPersistStateForBackground(SESSION);+ resetTurnPersistState(SESSION);+ await flushWrites();+ vi.clearAllMocks();+ noteSessionClearBoundary(SESSION, clearAt);+ nowSpy.mockReturnValue(lateResultAt);++ const result = onToolResultEvent(+ SESSION,+ { summary: SUMMARY, toolUseIds: ['late-cleared-child'] },+ null,+ 'background',+ );+ const fullResult = onToolResultFullEvent(+ SESSION,+ { toolUseId: 'late-cleared-child', fullText: FULL },+ null,+ 'background',+ );+ try {+ await flushWrites();+ } finally {+ nowSpy.mockRestore();+ }++ expect(result).toBeNull();+ expect(fullResult).toBeNull();+ expect(createMessage).not.toHaveBeenCalled();+ });+});+describe('tool_result 顺序:先 tool_result_full(全文)后 tool_result(摘要)', () => {it('全文先 buffer(无显示),摘要到达时建消息并用全文', async () => {const r1 = onToolResultFullEvent(SESSION, { toolUseId: 'tu_99', fullText: FULL }, null);diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.tsindex 564d77bd24..ed8b36963f 100644--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts@@ -23,6 +23,7 @@ const h = vi.hoisted(() => {// 填进来(userSendAt/updatedAt = 本次 ts),模拟正常路径。// 需要非默认结果(no-op/MAX updatedAt)的测试先 push 目标行再调函数。const selectResults: Array<Array<Record<string, unknown>>> = [];+ const updateErrors: unknown[] = [];const makeUpdateChain = () => {const chain: Record<string, unknown> = {};@@ -35,7 +36,10 @@ const h = vi.hoisted(() => {}return chain;};- chain.where = () => Promise.resolve(undefined);+ chain.where = () => {+ const error = updateErrors.shift();+ return error === undefined ? Promise.resolve(undefined) : Promise.reject(error);+ };return chain;};@@ -57,6 +61,7 @@ const h = vi.hoisted(() => {},updateSetCalls,selectResults,+ updateErrors,fakeDb: {update: vi.fn(() => makeUpdateChain()),select: vi.fn(() => makeSelectChain()),@@ -90,11 +95,16 @@ vi.mock('../agent-island/service.js', () => ({import { notifyAgentIslandSessionPatch } from '../localDb/agentIslandSessionPatch.js';import { clearSessionContextInDb, touchUserSendInDb, persistSessionFields } from '../localDb/ipc/sessions.js';+import {+ backgroundTurnPredatesSessionClear,+ noteSessionClearBoundary,+} from '../messagePersistBroadcaster.js';beforeEach(() => {vi.clearAllMocks();h.updateSetCalls.length = 0;h.selectResults.length = 0;+ h.updateErrors.length = 0;});describe('touchUserSendInDb 广播 sessions:patched(device-link 项目归属收敛)', () => {@@ -189,6 +199,36 @@ describe('clearSessionContextInDb 广播 sessions:patched(device-link /clear 收patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso },});});++ it('把 DB 读回的有效 clear 边界登记给晚到 background 过滤器', async () => {+ const sessionId = 'sess-clear-background-boundary';+ const requestedAt = 1_700_000_123_000;+ const effectiveAt = requestedAt + 5_000;+ noteSessionClearBoundary(sessionId, null);+ expect(backgroundTurnPredatesSessionClear(sessionId, effectiveAt - 1)).toBe(false);++ // 并发的较新 clear 可能已经把 DB 边界推进到 requestedAt 之后;内存过滤器+ // 必须采用 SELECT 读回的有效值,不能只记本次请求参数。+ h.selectResults.push([{ clearedAt: effectiveAt, updatedAt: effectiveAt }]);+ await clearSessionContextInDb(sessionId, requestedAt);++ expect(backgroundTurnPredatesSessionClear(sessionId, effectiveAt - 1)).toBe(true);+ expect(backgroundTurnPredatesSessionClear(sessionId, effectiveAt + 1)).toBe(false);+ noteSessionClearBoundary(sessionId, null);+ });++ it('DB 落库失败时仍先登记 host-owned clear 边界', async () => {+ const sessionId = 'sess-clear-background-boundary-db-failure';+ const requestedAt = 1_700_000_456_000;+ noteSessionClearBoundary(sessionId, null);+ h.updateErrors.push(new Error('db unavailable'));++ await expect(clearSessionContextInDb(sessionId, requestedAt)).rejects.toThrow('db unavailable');++ expect(backgroundTurnPredatesSessionClear(sessionId, requestedAt - 1)).toBe(true);+ expect(backgroundTurnPredatesSessionClear(sessionId, requestedAt + 1)).toBe(false);+ noteSessionClearBoundary(sessionId, null);+ });});describe('persistSessionFields(远程 set-* 回流:字段白名单 + 广播)', () => {diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 083cdc87ae..7f1f7cd569 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -782,6 +782,10 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):const ownerScope = captureOwnerScope();const ts =typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now();+ // Device-link /clear has no local renderer sessions:update call to populate+ // the main-process background-event boundary. Advance it before the DB await+ // so persistence failure still keeps old late events behind the clear.+ noteSessionClearBoundary(sessionId, ts);const db = getDbClient().drizzle;await db.update(sessions)@@ -801,6 +805,9 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):.limit(1);const effectiveClearedAt = updated?.clearedAt ?? ts;const effectiveUpdatedAt = updated?.updatedAt ?? effectiveClearedAt;+ // Concurrent clears can make SQLite return a newer monotonic boundary than+ // this request supplied. Mirror the effective value into the in-memory gate.+ noteSessionClearBoundary(sessionId, effectiveClearedAt);try {await removeTurnChangeSetsForSession(sessionId);} catch (error) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.tsindex 1d406c0205..473106f139 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts@@ -304,6 +304,35 @@ describe('InterruptedTurnAutoResumeGuard', () => {});});+ it('does not recharge exhausted retry budget from a late background tool event', () => {+ const g = createGuard();+ for (let i = 0; i < INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS; i += 1) {+ const decision = g.guard.onInterruptedTurn(SID, runInterruptedTurn(g));+ expect(decision.action).toBe('resume');+ if (decision.action !== 'resume') return;+ g.guard.noteAttemptEvent(SID, decision.attemptToken);+ g.guard.noteAttemptSettled(SID, decision.attemptToken);+ }+ expect(g.guard.onInterruptedTurn(SID, g.now()).action).toBe('exhausted');++ // This models the state-machine side of the listener guard; the source+ // contract test separately locks that register.ts uses the same condition.+ const lateBackgroundToolUse = { type: 'tool_use', turnScope: 'background' };+ if (+ lateBackgroundToolUse.turnScope !== 'background' &&+ isSubstantiveProgressEvent(lateBackgroundToolUse)+ ) {+ g.guard.noteProgress(SID);+ }++ expect(g.guard.onInterruptedTurn(SID, g.now() + 1)).toEqual({+ action: 'exhausted',+ reason: 'consecutive',+ consecutiveAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ episodeAttempts: INTERRUPTED_TURN_MAX_CONSECUTIVE_ATTEMPTS,+ });+ });+it('model output resets the consecutive counter (但会话累计只增)', () => {const g = createGuard();let lastAttemptToken = 0;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 2dce52d783..ed3e9bc1b9 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -317,6 +317,7 @@ import {readSessionWorkingDirFromDb,} from '../maker-host/session-storage.js';import {+ backgroundTurnPredatesSessionClear,clearSessionPersistState,consumeLastAssistantPersistId,consumeLastTopLevelAssistantPersistId,@@ -341,6 +342,7 @@ import {onToolResultEvent,onToolResultFullEvent,onToolUseEvent,+ preserveTurnPersistStateForBackground,markAutoResumeOutcome,onTurnErrorEvent,prepareSyntheticToolEventForBroadcast,@@ -3353,6 +3355,13 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// on-demand detail IPC; forwarding the raw diff through maker:event would duplicate a// potentially multi-megabyte payload to every renderer and device-link controller.if (event.type === 'turn_diff') return;+ if (+ event.turnScope === 'background'+ && Object.prototype.hasOwnProperty.call(event, 'backgroundTurnStartedAt')+ && backgroundTurnPredatesSessionClear(session.id, event.backgroundTurnStartedAt)+ ) {+ return;+ }// 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的// terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token// 盖到事件上,首个匹配 token 的事件即视为 provider accepted。@@ -3637,7 +3646,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidconst eventAgentMeta = (event as { agentMeta?: AgentMeta | null }).agentMeta ?? null;// 跟踪会话最近一次非空 agentMeta(镜像 renderer state.lastAgentMeta),给 interaction// 边界 flush 当兜底锚点,保 agent_meta 不丢(rewind/fork)。- if (eventAgentMeta) noteAgentMeta(session.id, eventAgentMeta);+ if (eventAgentMeta && event.turnScope !== 'background') noteAgentMeta(session.id, eventAgentMeta);let persistId: string | undefined;// tool_result 家族:main 解析出的权威内容,盖进 payload 让 renderer 即时显示// (Option C:内容重排状态机只在 main 一份,与落库同源同值)。@@ -3646,7 +3655,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 连续失败计数归零;人工介入周期的硬总上限不归零,保证始终有限。// 刻意只认这两类事件:thinking / status / 空消息都不算产出;guard 侧是 O(1)、// 无 IO、无日志,放在热路径安全。- if (isSubstantiveProgressEvent(event)) {+ // 晚到 background 事件仍需广播和持久化,但不能给当前中断回合充值。+ if (event.turnScope !== 'background' && isSubstantiveProgressEvent(event)) {const progressAttemptToken = event.turnAttemptToken;const accepted = interruptedTurnAutoResumeGuard.noteProgress(session.id,@@ -3673,17 +3683,20 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void} else if (event.type === 'tool_use') {// tool_use 边界:先 flush 在飞 assistant(保证 assistant 行先于其 tool_use 入队// 落库),再落 tool_use 本身,拿回 persistId 盖进 payload。两者都只入队、不阻塞。- flushAssistantBlock(session.id, eventAgentMeta);+ if (event.turnScope !== 'background') flushAssistantBlock(session.id, eventAgentMeta);persistId = onToolUseEvent(session.id,event.data as { toolUseId?: unknown; toolName?: unknown; input?: unknown },eventAgentMeta,+ event.turnScope === 'background' ? 'background' : 'turn',+ event.backgroundTurnStartedAt,);} else if (event.type === 'tool_result') {const r = onToolResultEvent(session.id,event.data as { summary?: unknown; toolUseIds?: unknown },eventAgentMeta,+ event.turnScope === 'background' ? 'background' : 'turn',);persistId = r?.persistId;resolvedContent = r?.content;@@ -3692,6 +3705,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidsession.id,event.data as { toolUseId?: unknown; fullText?: unknown },eventAgentMeta,+ event.turnScope === 'background' ? 'background' : 'turn',);persistId = r?.persistId;resolvedContent = r?.content;@@ -3889,6 +3903,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidif (!isContinuationBoundary) {markTurnEndedAfterPersistDrain(session.id);}+ preserveTurnPersistStateForBackground(session.id);resetTurnPersistState(session.id);// sidebar-card-mode: 摘要触发挪到本轮 assistant 块 flush 入队之后(原先在// done 早段、flush 之前触发,流式轮次会读到上一轮文本)。只在正常 done 触发。@@ -12806,6 +12821,7 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {// event used for bookkeeping but never expose them through the raw renderer channel.const rendererEvent = { ...event };delete rendererEvent.turnAttemptToken;+ delete rendererEvent.backgroundTurnStartedAt;if (!event.data || typeof event.data !== 'object') return rendererEvent;const data = event.data as Record<string, unknown>;diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 878448e30a..985a445143 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -76,6 +76,23 @@ export function noteSessionClearBoundary(sessionId: string, clearedAt: string |}}+/**+ * Background work belongs to an earlier provider turn, so its local turn-start+ * time—not the late event's arrival time—decides whether a /clear boundary+ * hides it. Missing/non-finite ownership is fail-closed only when a clear+ * boundary exists; sessions that were never cleared keep the legacy behavior.+ */+export function backgroundTurnPredatesSessionClear(+ sessionId: string,+ turnStartedAt: unknown,+): boolean {+ const clearBoundary = clearBoundaryBySession.get(sessionId);+ if (clearBoundary === undefined) return false;+ return typeof turnStartedAt !== 'number'+ || !Number.isFinite(turnStartedAt)+ || turnStartedAt <= clearBoundary;+}+type CreateDbMessageBody = Parameters<typeof createDbMessage>[1];type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;@@ -486,6 +503,109 @@ const toolUseCreatedAtBySession = new Map<string, Map<string, number>>();const toolUseInfoBySession = new Map<string, Map<string, { toolName: string; input: unknown }>>();const updatableToolUsePersistIdBySession = new Map<string, Map<string, string>>();+interface BackgroundTurnPersistState {+ agentMeta: AgentMeta | null;+ knownToolUseIds: Set<string>;+ pendingToolUseIds: Set<string>;+ toolUseCreatedAt: Map<string, number>;+ toolResultIdByToolUseId: Map<string, string>;+ pendingFullTextByToolUseId: Map<string, { text: string; createdAt: number }>;+ toolResultContentByClientId: Map<string, string>;+}++/**+ * Late child results are still useful after a parent turn has ended, but must+ * not borrow the next turn's persistence context. Keep snapshots keyed by the+ * in-flight collab tool ids for events explicitly marked `turnScope=background`.+ */+const backgroundTurnPersistStatesBySession = new Map<string, BackgroundTurnPersistState[]>();++export function preserveTurnPersistStateForBackground(sessionId: string): void {+ const knownToolUseIds = knownToolUseIdsBySession.get(sessionId) ?? new Set<string>();+ const toolUseInfo = toolUseInfoBySession.get(sessionId);+ const collabToolUseIds = new Set(+ [...knownToolUseIds].filter((toolUseId) =>+ toolUseInfo?.get(toolUseId)?.toolName.startsWith('collab:') === true,+ ),+ );+ const resultIds = toolResultIdByToolUseId.get(sessionId) ?? new Map<string, string>();+ const pendingToolUseIds = new Set(+ [...collabToolUseIds].filter((toolUseId) => !resultIds.has(toolUseId)),+ );+ // Only retain contexts that can still receive a late background result. A+ // completed collab result already has its normal persistence row and needs+ // no snapshot; this also keeps the state bounded by in-flight tool ids.+ if (pendingToolUseIds.size === 0) return;+ const snapshot: BackgroundTurnPersistState = {+ agentMeta: lastAgentMetaBySession.get(sessionId) ?? null,+ knownToolUseIds: new Set(collabToolUseIds),+ pendingToolUseIds,+ toolUseCreatedAt: new Map(+ [...(toolUseCreatedAtBySession.get(sessionId) ?? [])]+ .filter(([toolUseId]) => collabToolUseIds.has(toolUseId)),+ ),+ toolResultIdByToolUseId: new Map(+ [...resultIds].filter(([toolUseId]) => collabToolUseIds.has(toolUseId)),+ ),+ pendingFullTextByToolUseId: new Map(+ [...(pendingFullTextByToolUseId.get(sessionId) ?? [])]+ .filter(([toolUseId]) => collabToolUseIds.has(toolUseId)),+ ),+ toolResultContentByClientId: new Map(+ [...(toolResultContentByClientId.get(sessionId) ?? [])]+ .filter(([persistId]) => [...resultIds.values()].includes(persistId)),+ ),+ };+ const snapshots = backgroundTurnPersistStatesBySession.get(sessionId) ?? [];+ snapshots.push(snapshot);+ backgroundTurnPersistStatesBySession.set(sessionId, snapshots);+}++function backgroundStateForToolUse(+ sessionId: string,+ toolUseIds: string[],+): BackgroundTurnPersistState | null {+ const snapshots = backgroundTurnPersistStatesBySession.get(sessionId);+ if (!snapshots || snapshots.length === 0) return null;+ for (let i = snapshots.length - 1; i >= 0; i -= 1) {+ const state = snapshots[i];+ if (toolUseIds.some((id) =>+ state.knownToolUseIds.has(id) ||+ state.toolResultIdByToolUseId.has(id) ||+ state.pendingFullTextByToolUseId.has(id))) {+ return state;+ }+ }+ return null;+}++function backgroundResultPredatesSessionClear(+ sessionId: string,+ state: BackgroundTurnPersistState,+ toolUseIds: string[],+): boolean {+ const clearBoundary = clearBoundaryBySession.get(sessionId);+ if (clearBoundary === undefined) return false;+ return toolUseIds.some((toolUseId) => {+ const toolUseCreatedAt = state.toolUseCreatedAt.get(toolUseId);+ return toolUseCreatedAt !== undefined && toolUseCreatedAt <= clearBoundary;+ });+}++function releaseBackgroundStateForToolUses(+ sessionId: string,+ state: BackgroundTurnPersistState,+ toolUseIds: string[],+): void {+ for (const toolUseId of toolUseIds) state.pendingToolUseIds.delete(toolUseId);+ if (state.pendingToolUseIds.size !== 0 || state.pendingFullTextByToolUseId.size !== 0) return;+ const snapshots = backgroundTurnPersistStatesBySession.get(sessionId);+ if (!snapshots) return;+ const index = snapshots.indexOf(state);+ if (index >= 0) snapshots.splice(index, 1);+ if (snapshots.length === 0) backgroundTurnPersistStatesBySession.delete(sessionId);+}+function rememberToolUseId(sessionId: string, toolUseId: string, createdAt: number): void {let set = knownToolUseIdsBySession.get(sessionId);if (!set) {@@ -501,14 +621,23 @@ function rememberToolUseId(sessionId: string, toolUseId: string, createdAt: numbcreatedAtMap.set(toolUseId, createdAt);}-function clampAfterToolUse(sessionId: string, toolUseId: string, createdAt: number): number {- const toolUseCreatedAt = toolUseCreatedAtBySession.get(sessionId)?.get(toolUseId);+function clampAfterToolUse(+ sessionId: string,+ toolUseId: string,+ createdAt: number,+ createdAtMap = toolUseCreatedAtBySession.get(sessionId),+): number {+ const toolUseCreatedAt = createdAtMap?.get(toolUseId);if (toolUseCreatedAt === undefined || createdAt > toolUseCreatedAt) return createdAt;return toolUseCreatedAt + 1;}-function clampAfterLatestToolUse(sessionId: string, toolUseIds: string[], createdAt: number): number {- const createdAtMap = toolUseCreatedAtBySession.get(sessionId);+function clampAfterLatestToolUse(+ sessionId: string,+ toolUseIds: string[],+ createdAt: number,+ createdAtMap = toolUseCreatedAtBySession.get(sessionId),+): number {if (!createdAtMap) return createdAt;let latestToolUseCreatedAt: number | undefined;for (const toolUseId of toolUseIds) {@@ -545,10 +674,46 @@ export function onToolUseEvent(sessionId: string,data: { toolUseId?: unknown; toolName?: unknown; input?: unknown },agentMeta: AgentMeta | null,-): string {+ scope: 'turn' | 'background' = 'turn',+ backgroundTurnStartedAt?: number,+): string | undefined {const createdAt = Date.now();const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : '';const toolName = typeof data.toolName === 'string' ? data.toolName : '';++ if (scope === 'background') {+ if (backgroundTurnPredatesSessionClear(sessionId, backgroundTurnStartedAt)) {+ return undefined;+ }+ // A late completed-only collab item has no live-turn tool_use to snapshot.+ // Give its background result an isolated context instead of touching the+ // next turn's maps, metadata, or adjacent-message dedup state.+ if (toolUseId) {+ const state: BackgroundTurnPersistState = {+ agentMeta,+ knownToolUseIds: new Set([toolUseId]),+ pendingToolUseIds: new Set([toolUseId]),+ toolUseCreatedAt: new Map([[toolUseId, createdAt]]),+ toolResultIdByToolUseId: new Map(),+ pendingFullTextByToolUseId: new Map(),+ toolResultContentByClientId: new Map(),+ };+ const snapshots = backgroundTurnPersistStatesBySession.get(sessionId) ?? [];+ snapshots.push(state);+ backgroundTurnPersistStatesBySession.set(sessionId, snapshots);+ }+ const persistId = createId();+ enqueueVisibleDbMessage(`tool_use:${sessionId}:${persistId}`, sessionId, {+ clientId: persistId,+ role: 'tool_use',+ content: { toolUseId, toolName, input: data.input },+ toolUseId: toolUseId || undefined,+ agentMeta,+ createdAt,+ });+ return persistId;+ }+if (toolUseId) {rememberToolUseId(sessionId, toolUseId, createdAt);getOrCreateSessionMap(toolUseInfoBySession, sessionId).set(toolUseId, {@@ -765,15 +930,29 @@ export function onToolResultEvent(sessionId: string,data: { summary?: unknown; toolUseIds?: unknown },agentMeta: AgentMeta | null,+ scope: 'turn' | 'background' = 'turn',): { persistId: string; content: string } | null {const summary = typeof data.summary === 'string' ? data.summary : '';const ids = Array.isArray(data.toolUseIds)? data.toolUseIds.filter((x): x is string => typeof x === 'string' && x.length > 0): [];+ if (scope === 'background' && ids.length === 0) return null;- const idMap = getOrCreateSessionMap(toolResultIdByToolUseId, sessionId);- const pending = getOrCreateSessionMap(pendingFullTextByToolUseId, sessionId);- const contentMap = getOrCreateSessionMap(toolResultContentByClientId, sessionId);+ const backgroundState = scope === 'background'+ ? backgroundStateForToolUse(sessionId, ids)+ : null;+ if (scope === 'background' && !backgroundState) return null;+ if (backgroundState && backgroundResultPredatesSessionClear(sessionId, backgroundState, ids)) {+ releaseBackgroundStateForToolUses(sessionId, backgroundState, ids);+ return null;+ }+ const idMap = backgroundState?.toolResultIdByToolUseId ??+ getOrCreateSessionMap(toolResultIdByToolUseId, sessionId);+ const pending = backgroundState?.pendingFullTextByToolUseId ??+ getOrCreateSessionMap(pendingFullTextByToolUseId, sessionId);+ const contentMap = backgroundState?.toolResultContentByClientId ??+ getOrCreateSessionMap(toolResultContentByClientId, sessionId);+ const createdAtMap = backgroundState?.toolUseCreatedAt ?? toolUseCreatedAtBySession.get(sessionId);let createdAt = Date.now();let usedBufferedContent = false;@@ -783,13 +962,13 @@ export function onToolResultEvent(const buffered = pending.get(id);if (buffered && buffered.text.length > content.length) {content = buffered.text;- createdAt = clampAfterToolUse(sessionId, id, buffered.createdAt);+ createdAt = clampAfterToolUse(sessionId, id, buffered.createdAt, createdAtMap);usedBufferedContent = true;}pending.delete(id);}if (usedBufferedContent) {- createdAt = clampAfterLatestToolUse(sessionId, ids, createdAt);+ createdAt = clampAfterLatestToolUse(sessionId, ids, createdAt, createdAtMap);}const primaryToolUseId = ids[0];@@ -808,13 +987,15 @@ export function onToolResultEvent(const prev = contentMap.get(existing);// 内容没增长 → 不写库;renderer 已显示该条,返回现有内容即可(upsert 命中后无变化)。if (prev === undefined || content.length <= prev.length) {+ if (backgroundState) releaseBackgroundStateForToolUses(sessionId, backgroundState, ids);return { persistId: existing, content: prev ?? content };}contentMap.set(existing, content);enqueueWrite(`tool_result_update:${sessionId}:${existing}`, () =>updateDbMessageContent(sessionId, existing!, content),);- notePersistedMessage(sessionId, 'tool_result', existing);+ if (scope !== 'background') notePersistedMessage(sessionId, 'tool_result', existing);+ if (backgroundState) releaseBackgroundStateForToolUses(sessionId, backgroundState, ids);return { persistId: existing, content };}@@ -826,10 +1007,11 @@ export function onToolResultEvent(role: 'tool_result',content,toolUseId: primaryToolUseId,- agentMeta: toolResultMeta(sessionId, agentMeta),+ agentMeta: backgroundState ? backgroundState.agentMeta : toolResultMeta(sessionId, agentMeta),createdAt,});- notePersistedMessage(sessionId, 'tool_result', persistId);+ if (scope !== 'background') notePersistedMessage(sessionId, 'tool_result', persistId);+ if (backgroundState) releaseBackgroundStateForToolUses(sessionId, backgroundState, ids);return { persistId, content };}@@ -845,19 +1027,31 @@ export function onToolResultFullEvent(sessionId: string,data: { toolUseId?: unknown; fullText?: unknown },agentMeta: AgentMeta | null,+ scope: 'turn' | 'background' = 'turn',): { persistId: string; content: string } | null {const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : '';const fullText = typeof data.fullText === 'string' ? data.fullText : null;if (!toolUseId || fullText === null) return null; // guard,对齐老 renderer- const idMap = getOrCreateSessionMap(toolResultIdByToolUseId, sessionId);- const pending = getOrCreateSessionMap(pendingFullTextByToolUseId, sessionId);- const contentMap = getOrCreateSessionMap(toolResultContentByClientId, sessionId);+ const backgroundState = scope === 'background'+ ? backgroundStateForToolUse(sessionId, [toolUseId])+ : null;+ if (scope === 'background' && !backgroundState) return null;+ if (backgroundState && backgroundResultPredatesSessionClear(sessionId, backgroundState, [toolUseId])) {+ releaseBackgroundStateForToolUses(sessionId, backgroundState, [toolUseId]);+ return null;+ }+ const idMap = backgroundState?.toolResultIdByToolUseId ??+ getOrCreateSessionMap(toolResultIdByToolUseId, sessionId);+ const pending = backgroundState?.pendingFullTextByToolUseId ??+ getOrCreateSessionMap(pendingFullTextByToolUseId, sessionId);+ const contentMap = backgroundState?.toolResultContentByClientId ??+ getOrCreateSessionMap(toolResultContentByClientId, sessionId);const createdAt = Date.now();const target = idMap.get(toolUseId);if (!target) {- const known = knownToolUseIdsBySession.get(sessionId);+ const known = backgroundState?.knownToolUseIds ?? knownToolUseIdsBySession.get(sessionId);if (known?.has(toolUseId)) {// tool_use 已到但还没 tool_result 摘要 → 直接建一条带全文的 tool_result。const persistId = createId();@@ -869,10 +1063,15 @@ export function onToolResultFullEvent(role: 'tool_result',content: fullText,toolUseId,- agentMeta: toolResultMeta(sessionId, agentMeta),- createdAt,+ agentMeta: backgroundState ? backgroundState.agentMeta : toolResultMeta(sessionId, agentMeta),+ createdAt: clampAfterToolUse(+ sessionId,+ toolUseId,+ createdAt,+ backgroundState?.toolUseCreatedAt ?? toolUseCreatedAtBySession.get(sessionId),+ ),});- notePersistedMessage(sessionId, 'tool_result', persistId);+ if (scope !== 'background') notePersistedMessage(sessionId, 'tool_result', persistId);return { persistId, content: fullText };}// tool_use 也没到 → buffer,等 tool_result 摘要 / done 兜底消费;renderer 不显示。@@ -886,7 +1085,7 @@ export function onToolResultFullEvent(enqueueWrite(`tool_result_full:${sessionId}:${target}`, () =>updateDbMessageContent(sessionId, target, fullText),);- notePersistedMessage(sessionId, 'tool_result', target);+ if (scope !== 'background') notePersistedMessage(sessionId, 'tool_result', target);return { persistId: target, content: fullText };}@@ -1365,6 +1564,7 @@ export function onTurnErrorEvent(/** session 关闭时清掉该会话所有 per-session 持久化状态,避免 Map 泄漏 / 跨会话串状态。 */export function clearSessionPersistState(sessionId: string): void {assistantBlocks.delete(sessionId);+ backgroundTurnPersistStatesBySession.delete(sessionId);lastAgentMetaBySession.delete(sessionId);knownToolUseIdsBySession.delete(sessionId);toolUseCreatedAtBySession.delete(sessionId);diff --git a/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts b/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.tsindex 66164cee6d..ec4e3a16c6 100644--- a/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts@@ -45,7 +45,9 @@ function stubLocalCatalog() {let providerId = 'provider-old';let capabilityRevision = 'old';let unavailableAgent: string | null = null;+ let transientError: { agent: string; message: string } | null = null;const getCapabilities = vi.fn(async (agent: string) => {+ if (transientError?.agent === agent) throw new Error(transientError.message);if (agent === unavailableAgent) throw new Error(`Agent '${agent}' is not registered`);return caps(`${capabilityRevision}:${agent}`);});@@ -64,6 +66,11 @@ function stubLocalCatalog() {},setUnavailableAgent(agent: string | null): void {unavailableAgent = agent;+ transientError = null;+ },+ setAgentError(agent: string | null, message = 'temporary capability failure'): void {+ transientError = agent ? { agent, message } : null;+ unavailableAgent = null;},};}@@ -101,7 +108,10 @@ describe('useAgentCapabilities deviceId-aware cache', () => {it('本机目录快照在可选 Pi 不可用时仍返回 Claude Code 与 Codex 能力', async () => {const { getCapabilities } = stubElectron();getCapabilities.mockImplementation(async (agent: string) => {- if (agent === 'pi') throw new Error("Agent 'pi' is not registered");+ if (agent === 'pi')+ throw new Error(+ "[MAKER_NOT_FOUND] Agent 'pi' is not registered (available: claude-code, codex)",+ );return caps(`local:${agent}`);});const mod = await import('@/hooks/useAgentCapabilities');@@ -146,12 +156,13 @@ describe('useAgentCapabilities deviceId-aware cache', () => {expect(capabilities.getCachedCapabilities('pi')).toBeNull();});- it('Pi 不可用时用新 provider 快照替换 last-valid snapshot', async () => {+ it('Pi 变为不可用时清除旧能力,并用新 provider 快照替换核心能力', async () => {const harness = stubLocalCatalog();const catalog = await import('@/lib/localCatalogSnapshot');const providers = await import('@/lib/providersSnapshotStore');const capabilities = await import('@/hooks/useAgentCapabilities');await expect(catalog.refreshLocalCatalogSnapshot()).resolves.toBe(true);+ expect(capabilities.getCachedCapabilities('pi')?.availableModels[0].displayName).toBe('old:pi');harness.setSnapshot('provider-new', 'new');harness.setUnavailableAgent('pi');@@ -164,6 +175,28 @@ describe('useAgentCapabilities deviceId-aware cache', () => {expect(capabilities.getCachedCapabilities('codex')?.availableModels[0].displayName).toBe('new:codex',);+ expect(capabilities.getCachedCapabilities('pi')).toBeNull();+ });++ it('Pi 临时能力错误时联合刷新保留旧 provider 与三份 agent 快照', async () => {+ const harness = stubLocalCatalog();+ const catalog = await import('@/lib/localCatalogSnapshot');+ const providers = await import('@/lib/providersSnapshotStore');+ const capabilities = await import('@/hooks/useAgentCapabilities');+ await expect(catalog.refreshLocalCatalogSnapshot()).resolves.toBe(true);++ harness.setSnapshot('provider-new', 'new');+ harness.setAgentError('pi', 'Pi capability IPC failed');+ await expect(catalog.refreshLocalCatalogSnapshot()).resolves.toBe(false);++ expect(providers.getCachedProvidersSnapshot()?.providers).toEqual([{ id: 'provider-old' }]);+ expect(capabilities.getCachedCapabilities('claude-code')?.availableModels[0].displayName).toBe(+ 'old:claude-code',+ );+ expect(capabilities.getCachedCapabilities('codex')?.availableModels[0].displayName).toBe(+ 'old:codex',+ );+ expect(capabilities.getCachedCapabilities('pi')?.availableModels[0].displayName).toBe('old:pi');});it('核心 agent 失败时联合刷新保留 last-valid provider 与能力快照', async () => {diff --git a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.tsindex cbb8e03ab6..970adeb64c 100644--- a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts@@ -65,6 +65,16 @@ describe('refreshLocalCatalogSnapshot', () => {expect(mocks.warn).toHaveBeenCalledOnce();});+ it('keeps the last valid snapshot when capabilities loading fails', async () => {+ mocks.loadProviders.mockResolvedValueOnce({ providers: [{ id: 'provider-old' }] });+ mocks.loadCapabilities.mockRejectedValueOnce(new Error('Pi capability IPC failed'));++ await expect(refreshLocalCatalogSnapshot()).resolves.toBe(false);+ expect(mocks.commitProviders).not.toHaveBeenCalled();+ expect(mocks.commitCapabilities).not.toHaveBeenCalled();+ expect(mocks.warn).toHaveBeenCalledOnce();+ });+it('does not commit capabilities when the provider snapshot owner is stale', async () => {const providers = {dataOwnerId: 'owner-b',diff --git a/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx b/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsxindex 7718d31d9e..6e99f250ea 100644--- a/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx+++ b/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx@@ -49,6 +49,137 @@ function provider(id: string): ProviderView {}describe('remote model hook device ownership', () => {+ it('clears a mounted local capability hook when optional Pi becomes unavailable', async () => {+ let piAvailable = true;+ const getCapabilities = vi.fn(async (agentKind: string) => {+ if (agentKind === 'pi' && !piAvailable) {+ throw new Error("Agent 'pi' is not registered");+ }+ return capabilities(`local:${agentKind}`);+ });+ setElectronApi({ maker: { getCapabilities } });+ const mod = await import('@/hooks/useAgentCapabilities');+ await mod.preloadAllCapabilities();++ const frames: Array<ReturnType<typeof mod.useAgentCapabilities>> = [];+ function Probe() {+ frames.push(mod.useAgentCapabilities('pi'));+ return null;+ }++ const view = render(<Probe />);+ await waitFor(() =>+ expect(frames.at(-1)?.capabilities?.availableModels[0]?.displayName).toBe('local:pi'),+ );++ piAvailable = false;+ const generation = mod.beginLocalCapabilitiesRefresh();+ const entries = await mod.loadLocalCapabilitiesSnapshot();+ await act(async () => {+ expect(mod.commitLocalCapabilitiesSnapshot(generation, entries)).toBe(true);+ });++ await waitFor(() => {+ expect(frames.at(-1)?.capabilities).toBeNull();+ expect(frames.at(-1)?.loading).toBe(false);+ expect(frames.at(-1)?.error).toBeNull();+ });+ expect(mod.getCachedCapabilities('pi')).toBeNull();+ view.unmount();+ });++ it('does not let a pre-refresh Pi request revive a committed missing snapshot', async () => {+ let piUnavailable = false;+ let resolveStalePi!: (value: ReturnType<typeof capabilities>) => void;+ const stalePi = new Promise<ReturnType<typeof capabilities>>((resolve) => {+ resolveStalePi = resolve;+ });+ const getCapabilities = vi.fn((agentKind: string) => {+ if (agentKind === 'pi') {+ if (piUnavailable) return Promise.reject(new Error("Agent 'pi' is not registered"));+ return stalePi;+ }+ return Promise.resolve(capabilities(`local:${agentKind}`));+ });+ setElectronApi({ maker: { getCapabilities } });+ const mod = await import('@/hooks/useAgentCapabilities');++ const frames: Array<ReturnType<typeof mod.useAgentCapabilities>> = [];+ function Probe() {+ frames.push(mod.useAgentCapabilities('pi'));+ return null;+ }++ const view = render(<Probe />);+ await waitFor(() => expect(getCapabilities).toHaveBeenCalledWith('pi'));++ piUnavailable = true;+ const generation = mod.beginLocalCapabilitiesRefresh();+ const entries = await mod.loadLocalCapabilitiesSnapshot();+ await act(async () => {+ expect(mod.commitLocalCapabilitiesSnapshot(generation, entries)).toBe(true);+ });+ await waitFor(() => {+ expect(frames.at(-1)?.capabilities).toBeNull();+ expect(frames.at(-1)?.loading).toBe(false);+ });++ await act(async () => {+ resolveStalePi(capabilities('stale:pi'));+ await stalePi;+ await Promise.resolve();+ });++ expect(frames.at(-1)?.capabilities).toBeNull();+ expect(mod.getCachedCapabilities('pi')).toBeNull();+ view.unmount();+ });++ it('keeps a successful cache-miss result when a newer local refresh fails before commit', async () => {+ let resolveInitialPi!: (value: ReturnType<typeof capabilities>) => void;+ const initialPi = new Promise<ReturnType<typeof capabilities>>((resolve) => {+ resolveInitialPi = resolve;+ });+ let piRequests = 0;+ let failRefresh = false;+ const getCapabilities = vi.fn((agentKind: string) => {+ if (agentKind === 'pi' && piRequests++ === 0) return initialPi;+ if (agentKind === 'claude-code' && failRefresh) {+ return Promise.reject(new Error('temporary capability IPC failure'));+ }+ return Promise.resolve(capabilities(`refresh:${agentKind}`));+ });+ setElectronApi({ maker: { getCapabilities } });+ const mod = await import('@/hooks/useAgentCapabilities');++ const frames: Array<ReturnType<typeof mod.useAgentCapabilities>> = [];+ function Probe() {+ frames.push(mod.useAgentCapabilities('pi'));+ return null;+ }++ const view = render(<Probe />);+ await waitFor(() => expect(getCapabilities).toHaveBeenCalledWith('pi'));++ failRefresh = true;+ await act(async () => {+ await mod.refreshLocalCapabilities();+ });+ await act(async () => {+ resolveInitialPi(capabilities('initial:pi'));+ await initialPi;+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(frames.at(-1)?.capabilities?.availableModels[0]?.displayName).toBe('initial:pi');+ expect(frames.at(-1)?.loading).toBe(false);+ expect(frames.at(-1)?.error).toBeNull();+ });+ expect(mod.getCachedCapabilities('pi')?.availableModels[0]?.displayName).toBe('initial:pi');+ view.unmount();+ });+it('never renders the previous device capabilities under a newly selected device', async () => {const invoke = vi.fn((deviceId: string) => {if (deviceId === 'dev-a') return Promise.resolve(capabilities('Mac A'));diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex 6164abfbd0..0fcdb5b738 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -12,6 +12,7 @@ import {Workflow,} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { deriveAgentTaskStatus } from '@cindy/maker-shared/agent-task';import { useExpandedBlockMemory } from '@/hooks/useExpandedBlockMemory';import { Collapse } from '@/components/ui/collapse';@@ -29,7 +30,11 @@ import { useSidebarPanelReachable } from '@/features/cc-agent/embeddedSessionNavimport { cn } from '@/lib/utils';import { formatModelShortLabel } from '@/lib/modelShortLabel';import { CODEX_SUBAGENT_EFFORTS } from '../../../shared/subagentModelSettings';-import { PI_SUBAGENT_TOOL_NAME, subagentSpawnReceiptName } from '@cindy/maker-shared/agent-task';+import {+ PI_SUBAGENT_TOOL_NAME,+ subagentSpawnReceiptName,+ subagentSpawnResultIndicatesRunning,+} from '@cindy/maker-shared/agent-task';// 徽标可显示的思考强度档:协议全部合法档(效果词表 effortLevels 四语齐)。const EFFORT_BADGE_LEVELS = new Set<string>(['minimal', ...CODEX_SUBAGENT_EFFORTS]);@@ -199,9 +204,13 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session};}, [isWorkflow, update?.status, sessionId, workflowTaskId]);- const status =- update?.status ??- (isWorkflow ? (historyFileStatus ?? (result ? 'completed' : 'running')) : result ? 'completed' : 'running');+ const status = isWorkflow+ ? (update?.status ?? historyFileStatus ?? (result ? 'completed' : 'running'))+ : deriveAgentTaskStatus(update?.status, result, {+ resultIsLaunchReceipt:+ subagentSpawnReceiptName(toolCall?.toolName, toolCall?.toolInput, result) !== undefined+ || subagentSpawnResultIndicatesRunning(toolCall?.toolName, result),+ });const StatusIcon = statusIcon(status);const statusIconClassName = cn('text-[var(--text-secondary)]',diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex cc2048e767..1663db06e9 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -31,7 +31,15 @@ import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';import { SelectionQuoteButton } from './SelectionQuoteButton';import { useTranslation } from 'react-i18next';-import { isAgentPlanToolName, isDeliveryProseText } from '@cindy/maker-shared/message-render';+import {+ deriveAgentTaskStatus,+ subagentSpawnReceiptName,+ subagentSpawnResultIndicatesRunning,+} from '@cindy/maker-shared/agent-task';+import {+ isAgentPlanToolName,+ isDeliveryProseText,+} from '@cindy/maker-shared/message-render';// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';@@ -1499,11 +1507,17 @@ function isWorkChild(it: RenderItem): it is WorkChildItem {/** 运行中(未到终态)的子 Agent 卡片 —— 折叠时视为"可见锚点",绝不折进* 「已工作 Xs」工作组:任务没完成就归档会谎报终态时长(典型:后台 workflow* 子 Agent 仍在跑,父 turn 却已产出最终正文)。status 派生口径与 AgentTaskCard- * 完全一致(update.status 优先,否则有 result 视为 completed、无则 running),- * 保证"卡片显示运行中"与"是否折叠"永远同步。终态 = completed/failed/stopped。 */+ * 完全一致:配对的最终 result 会把 stale running 收敛为 completed,但不覆盖+ * failed/stopped 等明确终态,+ * 保证"卡片显示运行中"与"是否折叠"永远同步。 */+// A paired final result closes a stale running update; this must match AgentTaskCard.function isRunningAgentTask(it: RenderItem): boolean {if (it.type !== 'agent_task') return false;- const status = it.update?.status ?? (it.result ? 'completed' : 'running');+ const status = deriveAgentTaskStatus(it.update?.status, it.result, {+ resultIsLaunchReceipt:+ subagentSpawnReceiptName(it.toolCall?.toolName, it.toolCall?.toolInput, it.result) !== undefined+ || subagentSpawnResultIndicatesRunning(it.toolCall?.toolName, it.result),+ });return status === 'running';}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.tsindex e79438ea51..e0afc85803 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts@@ -122,6 +122,38 @@ describe('listSessionTasks 配对', () => {expect(running[0]).toMatchObject({ kind: 'agent', provider: 'codex', title: 'review it' });});+ it('uses the shared result status derivation and keeps V1 running receipts running', () => {+ const runningUpdate = makeUpdate({ taskId: 'task-running', parentToolUseId: 'toolu-running' });+ const completedUpdate = makeUpdate({ taskId: 'task-completed', parentToolUseId: 'toolu-completed' });+ const failedUpdate = makeUpdate({+ taskId: 'task-failed',+ parentToolUseId: 'toolu-failed',+ status: 'failed',+ });+ const { running, completed } = listSessionTasks({+ messages: [+ toolUse('c1', 'toolu-running', 'collab:spawnAgent'),+ toolResult('r1', 'toolu-running', 'child-thread: running'),+ toolUse('c2', 'toolu-completed', 'collab:spawnAgent'),+ toolResult('r2', 'toolu-completed', 'child-thread: completed'),+ toolUse('c3', 'toolu-failed', 'collab:spawnAgent'),+ toolResult('r3', 'toolu-failed', 'child-thread: failed'),+ ],+ taskUpdates: new Map([+ ...aliasedMap(runningUpdate),+ ...aliasedMap(completedUpdate),+ ...aliasedMap(failedUpdate),+ ]),+ isSessionStreaming: false,+ });++ expect(running).toMatchObject([{ taskId: 'task-running', status: 'running' }]);+ expect(completed).toEqual(expect.arrayContaining([+ expect.objectContaining({ taskId: 'task-completed', status: 'completed' }),+ expect.objectContaining({ taskId: 'task-failed', status: 'failed' }),+ ]));+ });+it('历史 workflow(无 update):从结果文本「Task ID: xxx」提取 taskId(详情读 wf 文件用)', () => {const { completed } = listSessionTasks({messages: [diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.tsindex fe8030833b..43c77eb495 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts@@ -5,8 +5,9 @@* - 工具识别 / update 配对口径 = MessageStream.buildRenderItems + findTaskUpdate:* 先 toolUseId 后 clientId 查 taskUpdates;tool_result 存在性 = toolUseId 查表* 命中,或紧邻其后的 tool_result 行(旧数据 toolUseId 缺失时的 adjacency 兜底)。- * - 状态推导口径 = AgentTaskCard:update?.status 优先,无 update 时有结果为- * completed、无结果为 running。+ * - 状态推导口径 = 非 workflow 任务复用 AgentTaskCard 的结果派生(终态结果会+ * 收口 running,V1 running 回执仍保留 running);workflow 仍以 update.status+ * 优先,无 update 时有结果为 completed、无结果按流式状态推导。* - 孤儿 update(map 里有、消息窗口内配不到 toolCall)只在会话运行中列出* (口径 = maker-shared/messageRender.appendOrphanAgentTasks 的 gating 注释:* 空闲态的孤儿是滑出分页窗口的陈旧残留,不得复播)。@@ -15,7 +16,12 @@* - 本文件签名是并行开发契约,不得改动。*/-import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';+import {+ deriveAgentTaskStatus,+ isAgentTaskToolName,+ subagentSpawnReceiptName,+ subagentSpawnResultIndicatesRunning,+} from '@cindy/maker-shared/agent-task';import type { Message } from '@/lib/ccAgent.types';import type { AgentTaskStatus, AgentTaskUpdate } from '@/lib/makerChatStore';@@ -327,8 +333,16 @@ export function listSessionTasks(input: {// running(事件可能尚未到达)—— 非流式 + 无 update + 无结果 = 强杀/崩溃留下// 的死任务(同步 Task 没有启动回执,永远不会有结果),断言 running 会让它// 永久转圈且无任何收口路径,按 stopped(被中断)呈现。- const status: AgentTaskStatus =- update?.status ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped');+ const resultText = typeof resultContent === 'string' ? resultContent : undefined;+ const status: AgentTaskStatus = isWorkflowTool+ ? update?.status ?? (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped')+ : update+ ? deriveAgentTaskStatus(update.status, resultText, {+ resultIsLaunchReceipt:+ subagentSpawnReceiptName(toolName, toolInput, resultText) !== undefined+ || subagentSpawnResultIndicatesRunning(toolName, resultText),+ })+ : (settled ? 'completed' : isSessionStreaming ? 'running' : 'stopped');const provider: SessionTaskItem['provider'] =update?.provider ?? (toolName.startsWith('collab:') ? 'codex' : 'claude-code');diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.tsindex 0bf3fe7366..d07e854f39 100644--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts@@ -261,11 +261,13 @@ function cacheKey(agentKind: AgentKind, deviceId?: string): CacheKey {}const cache = new Map<CacheKey, AgentCapabilities>();-const inflight = new Map<CacheKey, Promise<AgentCapabilities>>();+const inflight = new Map<CacheKey, Promise<AgentCapabilities | null>>();/** 本地能力刷新代际;使刷新前的在途 IPC 结果无法回写旧快照。 */let localGen = 0;+/** 已提交的本地快照 revision;失败刷新不会前进,用来区分缺失 tombstone 与未提交。 */+let localSnapshotRevision = 0;/** 已挂载 hook 的本地能力订阅者;刷新完成后一次性切到新快照,避免中途空白帧。 */-const localListeners = new Set<(agent: AgentKind, caps: AgentCapabilities) => void>();+const localListeners = new Set<(agent: AgentKind, caps: AgentCapabilities | null) => void>();/** 远程能力缓存事件;驱逐时先标 stale,成功 / 失败后再结束这一轮刷新。 */export type DeviceCapabilitiesEvent =| { status: 'loading' }@@ -309,7 +311,7 @@ export function subscribeDeviceCapabilities(async function fetchCapabilities(agentKind: AgentKind,deviceId?: string,-): Promise<AgentCapabilities> {+): Promise<AgentCapabilities | null> {const key = cacheKey(agentKind, deviceId);const cached = cache.get(key);if (cached) return cached;@@ -318,8 +320,11 @@ async function fetchCapabilities(// 捕获发起时的设备代际;回调里若代际已变(被 evict)则认为本次请求作废。const startGen = deviceId ? (deviceGen.get(deviceId) ?? 0) : localGen;+ const startLocalSnapshotRevision = localSnapshotRevision;const isCurrent = (): boolean =>- deviceId ? (deviceGen.get(deviceId) ?? 0) === startGen : localGen === startGen;+ deviceId+ ? (deviceGen.get(deviceId) ?? 0) === startGen+ : localGen === startGen && localSnapshotRevision === startLocalSnapshotRevision;let raw: Promise<AgentCapabilities>;if (deviceId) {@@ -343,9 +348,16 @@ async function fetchCapabilities(if (deviceId)notifyRemoteCapabilities(deviceId, agentKind, { status: 'ready', capabilities: caps });} else if (!deviceId) {- // 本地热刷新可能已原子换入更新快照;旧请求的调用方也应拿当前 cache,不能在- // listener 更新之后又把 hook state 覆盖回旧对象。刷新仍在途时保留旧对象,完成后再通知。- return cache.get(key) ?? caps;+ // 已提交的新快照优先:有值就返回当前 cache,明确删除则以 null 作为 tombstone。+ const current = cache.get(key);+ if (current) return current;+ if (localSnapshotRevision !== startLocalSnapshotRevision) return null;+ // 只有刷新代际变化、但最终没有快照提交时,成功的 cache-miss 结果仍然有效。+ // 若已有更新请求占住 inflight,则服从更新请求,避免旧结果抢先落缓存。+ const newer = inflight.get(key);+ if (newer) return newer;+ cache.set(key, caps);+ return caps;}return caps;})@@ -410,13 +422,13 @@ export function useAgentCapabilities(setError(null);};if (deviceId) return subscribeDeviceCapabilities(deviceId, agentKind, applyRemoteEvent);- const applySnapshot = (caps: AgentCapabilities): void => {+ const applySnapshot = (caps: AgentCapabilities | null): void => {setOwnerKey(key);setCapabilities(caps);setLoading(false);setError(null);};- const onRefresh = (refreshedAgent: AgentKind, caps: AgentCapabilities): void => {+ const onRefresh = (refreshedAgent: AgentKind, caps: AgentCapabilities | null): void => {if (refreshedAgent !== agentKind) return;applySnapshot(caps);};@@ -459,7 +471,7 @@ export function useAgentCapabilities(.then((caps) => {// 远程成功结果只经「当前代际 cache commit → listener」更新,避免 revision 前的// 旧 Promise 晚到后直接把已刷新的 hook state 覆盖回旧快照。- if (cancelled || deviceId) return;+ if (cancelled || deviceId || caps === null) return;setCapabilities(caps);}).catch((e: unknown) => {@@ -531,7 +543,12 @@ export function beginLocalCapabilitiesRefresh(): number {}/**- * 读取本地 agent 能力快照;核心 agent 失败向上抛,可选 Pi 的能力读取失败不阻断 provider 目录。+ * 读取本地 agent 能力快照;核心 agent 失败向上抛,只有明确的 Pi 未注册结果才不阻断 provider 目录。+ *+ * Pi 的 CLI 是 best-effort 下载的目录分发,开发机或网络受限时可能暂时缺失。+ * 明确未注册时不能让 `maker:get-capabilities('pi')` 的单点失败把 Claude/Codex+ * 模型目录整组回滚为空;但临时 IPC、序列化或解析错误必须向上抛,让联合刷新保留+ * 上一份完整快照。*/export async function loadLocalCapabilitiesSnapshot(): Promise<LocalCapabilitiesSnapshot> {const api = getMakerApi();@@ -541,7 +558,13 @@ export async function loadLocalCapabilitiesSnapshot(): Promise<LocalCapabilitiestry {return [agent, await api.getCapabilities(agent)] as const;} catch (error) {- if (agent !== 'pi') throw error;+ const message =+ error instanceof Error+ ? error.message+ : typeof error === 'object' && error !== null && 'message' in error+ ? String(error.message)+ : String(error);+ if (agent !== 'pi' || !message.includes("Agent 'pi' is not registered")) throw error;log.warn('optional Pi capabilities unavailable; continuing with core agents:', error);return null;}@@ -556,14 +579,18 @@ export function isLocalCapabilitiesRefreshCurrent(generation: number): boolean {return localGen === generation;}-/** 仅提交当前代际的可用能力快照,并在提交后统一通知 mounted hooks。 */+/** 仅提交当前代际的完整能力快照,并在提交后统一通知 mounted hooks。 */export function commitLocalCapabilitiesSnapshot(generation: number,entries: LocalCapabilitiesSnapshot,): boolean {if (!isLocalCapabilitiesRefreshCurrent(generation)) return false;- for (const [agent, caps] of entries) cache.set(cacheKey(agent), caps);- for (const [agent, caps] of entries) {+ localSnapshotRevision += 1;+ const snapshot = new Map(entries);+ for (const agent of ALL_AGENT_KINDS) {+ const caps = snapshot.get(agent) ?? null;+ if (caps) cache.set(cacheKey(agent), caps);+ else cache.delete(cacheKey(agent));for (const listener of localListeners) listener(agent, caps);}return true;diff --git a/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts b/apps/desktop/src/renderer/lib/localCatalogSnapshot.tsindex 70ac66511d..eb7400786c 100644--- a/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts+++ b/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts@@ -2,7 +2,7 @@* 本地 provider catalog 的 renderer 原子刷新协调器。** providers 与核心 agent capabilities 必须来自同一轮 main 快照:核心 IPC 全部成功、- * 且期间没有更新一代目录时才同步提交。可选 Pi 的能力读取失败时提交核心能力;其它失败+ * 且期间没有更新一代目录时才同步提交。明确未注册的可选 Pi 可从快照中省略;其它失败* 或乱序结果一律保留上一份有效快照。* device-link 的远端 capabilities 不经过这里,继续按 deviceId 独立缓存。*/diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 76fe5f2b9a..e730d6d91e 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -16654,6 +16654,598 @@ describe('CodexAgent turn lifecycle', () => {await handle.close();});+ it('REPRO: preserves a late collab-agent terminal update after the parent turn completes', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-late-collab-terminal-repro',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ handlers!.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'wait, then finish',+ agentsStates: {},+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'spawnAgent running...', isRunning: true },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_use',+ data: { toolUseId: 'collab-1', toolName: 'collab:spawnAgent' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-1', status: 'running' },+ });++ handlers!.descendantNotification?.('child-thread', 'thread/tokenUsage/updated', {+ threadId: 'child-thread',+ turnId: 'child-turn',+ tokenUsage: { total: { totalTokens: 21 } },+ });+ const activeTurnUpdate = await nextEvent(iterator);+ expect(activeTurnUpdate).toMatchObject({+ type: 'agent_task_update',+ data: {+ taskId: 'collab-1',+ status: 'running',+ usage: { totalTokens: 21 },+ },+ });+ expect(activeTurnUpdate).not.toHaveProperty('turnScope');+ expect(activeTurnUpdate).not.toHaveProperty('backgroundTurnStartedAt');++ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });++ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'wait, then finish',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result_full',+ turnScope: 'background',+ data: { toolUseId: 'collab-1', fullText: 'child-thread: completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result',+ turnScope: 'background',+ data: { toolUseIds: ['collab-1'] },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'collab-1', status: 'completed' },+ });++ // The carve-out is one-shot: a retried late item must not duplicate the+ // tool result or terminal task update.+ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'wait, then finish',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');+ await handle.close();+ });++ it('does not replay a normally handled collab terminal after the parent turn completes', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-normal-collab-terminal-retry',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ handlers!.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-normal',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish before the parent turn',+ agentsStates: {},+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({ type: 'status' });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'tool_use' });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-normal', status: 'running' },+ });++ const completedItem = {+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-normal',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish before the parent turn',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as const;+ handlers!.itemCompleted?.(completedItem as never);++ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result_full',+ data: { toolUseId: 'collab-normal' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result',+ data: { toolUseIds: ['collab-normal'] },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-normal', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-normal', status: 'running' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Generating...', isRunning: true },+ });++ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });++ handlers!.itemCompleted?.(completedItem as never);+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');+ await handle.close();+ });++ it('REPRO: reconstructs a late completed-only collab tool call', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-late-completed-only-collab',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ const turnStartedWindowStart = Date.now();+ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ const turnStartedWindowEnd = Date.now();+ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });++ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-completed-only',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish after the parent turn',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);++ const reconstructedToolUse = await nextEvent(iterator);+ expect(reconstructedToolUse).toMatchObject({+ type: 'tool_use',+ turnScope: 'background',+ data: {+ toolUseId: 'collab-completed-only',+ toolName: 'collab:spawnAgent',+ },+ });+ expect(reconstructedToolUse.backgroundTurnStartedAt).toEqual(expect.any(Number));+ expect(reconstructedToolUse.backgroundTurnStartedAt).toBeGreaterThanOrEqual(turnStartedWindowStart);+ expect(reconstructedToolUse.backgroundTurnStartedAt).toBeLessThanOrEqual(turnStartedWindowEnd);+ const reconstructedFullResult = await nextEvent(iterator);+ expect(reconstructedFullResult).toMatchObject({+ type: 'tool_result_full',+ turnScope: 'background',+ data: {+ toolUseId: 'collab-completed-only',+ fullText: 'child-thread: completed',+ },+ });+ const reconstructedResult = await nextEvent(iterator);+ expect(reconstructedResult).toMatchObject({+ type: 'tool_result',+ turnScope: 'background',+ data: { toolUseIds: ['collab-completed-only'] },+ });+ const reconstructedTaskUpdate = await nextEvent(iterator);+ expect(reconstructedTaskUpdate).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'collab-completed-only', status: 'completed' },+ });+ expect([+ reconstructedFullResult.backgroundTurnStartedAt,+ reconstructedResult.backgroundTurnStartedAt,+ reconstructedTaskUpdate.backgroundTurnStartedAt,+ ]).toEqual([+ reconstructedToolUse.backgroundTurnStartedAt,+ reconstructedToolUse.backgroundTurnStartedAt,+ reconstructedToolUse.backgroundTurnStartedAt,+ ]);++ await handle.close();+ });++ it('REPRO: preserves a late collab-agent terminal update after a terminal error', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-late-collab-terminal-error-repro',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ handlers!.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'wait, then finish',+ agentsStates: {},+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({ type: 'status' });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'tool_use' });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-1', status: 'running' },+ });++ handlers!.error?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ willRetry: false,+ error: { message: 'terminal error' },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'error' });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });++ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'wait, then finish',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result_full',+ turnScope: 'background',+ data: { toolUseId: 'collab-1', fullText: 'child-thread: completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result',+ turnScope: 'background',+ data: { toolUseIds: ['collab-1'] },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'collab-1', status: 'completed' },+ });++ // The terminal notification still performs the normal authoritative cleanup.+ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'failed', error: { message: 'terminal error' } },+ });+ await handle.close();+ });++ it('REPRO: scopes descendant updates from a completed parent turn as background', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-late-descendant-background-scope',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ const parentTurnStartedWindowStart = Date.now();+ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ const parentTurnStartedWindowEnd = Date.now();+ handlers!.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-1',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'keep working after the parent turn',+ agentsStates: { 'child-thread': { status: 'running' } },+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({ type: 'status' });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'tool_use' });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-1', status: 'running' },+ });++ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });++ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-next' },+ });++ handlers!.descendantNotification?.('child-thread', 'thread/tokenUsage/updated', {+ threadId: 'child-thread',+ turnId: 'child-turn',+ tokenUsage: { total: { totalTokens: 42 } },+ });+ const lateDescendantUpdate = await nextEvent(iterator);+ expect(lateDescendantUpdate).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: {+ taskId: 'collab-1',+ status: 'running',+ usage: { totalTokens: 42 },+ },+ });+ expect(lateDescendantUpdate.backgroundTurnStartedAt).toEqual(expect.any(Number));+ expect(lateDescendantUpdate.backgroundTurnStartedAt).toBeGreaterThanOrEqual(+ parentTurnStartedWindowStart,+ );+ expect(lateDescendantUpdate.backgroundTurnStartedAt).toBeLessThanOrEqual(+ parentTurnStartedWindowEnd,+ );++ await handle.close();+ });++ it('REPRO: reasserts the live running state for a late V1 spawn completion', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-late-collab-running-repro',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ expect(handlers).toBeDefined();+ const iterator = handle.events()[Symbol.asyncIterator]();++ const parentTurnStartedWindowStart = Date.now();+ handlers!.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent' },+ });+ const parentTurnStartedWindowEnd = Date.now();+ handlers!.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-running',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'keep working',+ agentsStates: {},+ },+ } as never);++ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'spawnAgent running...', isRunning: true },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_use',+ data: { toolUseId: 'collab-running', toolName: 'collab:spawnAgent' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ data: { taskId: 'collab-running', status: 'running' },+ });++ handlers!.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-parent', status: 'completed' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });++ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-running',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'keep working',+ agentsStates: { 'child-thread': { status: 'running' } },+ },+ } as never);++ const lateFullResult = await nextEvent(iterator);+ expect(lateFullResult).toMatchObject({+ type: 'tool_result_full',+ turnScope: 'background',+ data: { toolUseId: 'collab-running', fullText: 'child-thread: running' },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'tool_result',+ turnScope: 'background',+ data: { toolUseIds: ['collab-running'] },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'collab-running', status: 'completed' },+ });+ const replayedRunningUpdate = await nextEvent(iterator);+ expect(replayedRunningUpdate).toMatchObject({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'collab-running', status: 'running' },+ });+ expect(replayedRunningUpdate.backgroundTurnStartedAt).toBe(+ lateFullResult.backgroundTurnStartedAt,+ );+ expect(replayedRunningUpdate.backgroundTurnStartedAt).toBeGreaterThanOrEqual(+ parentTurnStartedWindowStart,+ );+ expect(replayedRunningUpdate.backgroundTurnStartedAt).toBeLessThanOrEqual(+ parentTurnStartedWindowEnd,+ );++ handlers!.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-parent',+ item: {+ type: 'collabAgentToolCall',+ id: 'collab-running',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'keep working',+ agentsStates: { 'child-thread': { status: 'running' } },+ },+ } as never);+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');+ await handle.close();+ });+it('emits the terminal boundary only once for duplicate turnCompleted notifications', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);@@ -18203,6 +18795,80 @@ describe('CodexAgent upstream-response-idle watchdog', () => {}});+ it('迟到的旧 turn collab 收口不重启新 turn idle 计时或注入前台状态', async () => {+ vi.useFakeTimers();+ try {+ const agent = new CodexAgent(createDeps());+ const host = installIdleHost(agent);+ const handle = await startIdleSession(agent, 'session-idle-late-collab-terminal');+ const seen = collectEvents(handle);+ await handle.send({ type: 'user', content: 'start background child' });+ const handlers = host.getThreadHandlers();+ if (!handlers) throw new Error('expected thread handlers');+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);+ handlers.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'old-spawn',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish after the parent turn',+ agentsStates: { 'child-thread': { status: 'running' } },+ },+ } as never);+ handlers.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'completed' },+ } as never);++ await handle.send({ type: 'user', content: 'new active turn' });+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);+ await vi.advanceTimersByTimeAsync(IDLE_MS / 2);++ const beforeLate = seen.length;+ handlers.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'old-spawn',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish after the parent turn',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);+ await vi.advanceTimersByTimeAsync(0);++ const lateEvents = seen.slice(beforeLate);+ expect(lateEvents).toContainEqual(expect.objectContaining({+ type: 'tool_result',+ turnScope: 'background',+ }));+ expect(lateEvents).not.toContainEqual(expect.objectContaining({+ type: 'status',+ data: expect.objectContaining({ status: 'Generating...' }),+ }));++ // 新 turn 从启动起静默满原始额度就必须收口;旧 turn 的 completed+ // 不能把已经消耗的一半 idle 配额重置成完整一轮。+ await vi.advanceTimersByTimeAsync(IDLE_MS / 2 + 1);+ expect(seen).toContainEqual(expect.objectContaining({+ type: 'error',+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),+ }));+ await handle.close();+ } finally {+ vi.useRealTimers();+ }+ });+it('interrupt 两次都超时也要收干净本地 turn 状态,会话保持可发(review 第二轮)', async () => {// app-server 彻底哑火时 interruptTurnForPermissionTighten 会两次 ack 超时后放弃,// 而它按设计不动 isTurnInFlight —— 若 watchdog 只依赖它,会话 isTurnRunning() 恒 true,@@ -18704,6 +19370,71 @@ describe('CodexAgent reconnect-stall watchdog', () => {}});+ it('迟到的 background terminal 不重置新 turn 的 reconnect deadline', async () => {+ vi.useFakeTimers();+ try {+ const agent = new CodexAgent(createDeps());+ const { handle, handlers, seen } = await startReconnectTurn(+ agent,+ 'session-reconnect-late-background-terminal',+ );+ handlers.itemStarted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'old-spawn',+ tool: 'spawnAgent',+ status: 'inProgress',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish later',+ agentsStates: { 'child-thread': { status: 'running' } },+ },+ } as never);+ handlers.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'completed' },+ } as never);+ await handle.send({ type: 'user', content: 'next' });+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);+ handlers.error?.({+ threadId: 'start-thread-id',+ turnId: 'turn-2',+ error: { message: 'Reconnecting... 1/5' },+ willRetry: true,+ } as never);++ await vi.advanceTimersByTimeAsync(60_000);+ handlers.itemCompleted?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'old-spawn',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'start-thread-id',+ receiverThreadIds: ['child-thread'],+ prompt: 'finish later',+ agentsStates: { 'child-thread': { status: 'completed' } },+ },+ } as never);++ await vi.advanceTimersByTimeAsync(60_001);+ 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 {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 2a2dfff3c7..903b1ca70f 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2920,6 +2920,10 @@ export class CodexAgent extends BaseAgent {compactionStormTracker.noteCompaction();memoryFlushController?.onCompactBoundary();};+ // Collab terminal notifications are one-shot across the whole handle lifetime.+ // The server can retry one after its parent turn/completed notification; remembering+ // normal completions too keeps that retry from looking like a first late terminal.+ const handledCollabTerminalItemIds = new Set<string>();const deferredTerminalTurnCompletions = new Map<string, TurnCompletedParams>();// 最近一次 thread/tokenUsage/updated 的 last 增量 + contextWindow,// 缓存供 turn end 日志读取 (协议本身不在 turn/completed 里带 usage)。@@ -3012,6 +3016,7 @@ export class CodexAgent extends BaseAgent {terminalSettled: boolean;capabilitySelectionText: string;sendGen: number;+ startedAtMs: number;}>();/** 每次 turn/start RPC 的自增序号, 作为登记表的键。 */let turnStartSeq = 0;@@ -3036,6 +3041,7 @@ export class CodexAgent extends BaseAgent {terminalSettled: false,capabilitySelectionText,sendGen: ownerSendGen,+ startedAtMs: Date.now(),});isTurnStartPending = true;return seq;@@ -3079,7 +3085,11 @@ export class CodexAgent extends BaseAgent {* 每一处清理同步, 漏一处就读到上一个 turn 的归属 —— 本 PR 已经在别的标量上踩过。* 键就是 turnId 本身, 旧条目不可能被当成另一个 turn 的答案。*/- const turnOriginByTurnId = new Map<string, { startSeq: number | null; sendGen: number }>();+ const turnOriginByTurnId = new Map<string, {+ startSeq: number | null;+ sendGen: number;+ startedAtMs: number;+ }>();const hasOtherInFlightStart = (seq: number): boolean => {for (const other of inFlightStarts.keys()) if (other !== seq) return true;@@ -3154,9 +3164,52 @@ export class CodexAgent extends BaseAgent {*/const capabilitySelectionTextByThreadId = new Map<string, string>();const descendantParentThreadByThreadId = new Map<string, string>();+ /**+ * Descendant notifications carry the child turn id, not the root turn that+ * spawned the child. Preserve that root ownership for the lifetime of the+ * handle so late child progress cannot attach itself to a newer root turn.+ */+ const rootTurnIdByDescendantThreadId = new Map<string, string>();/** A terminal child turn must not re-register tool provenance from late items. */const terminalDescendantTurnIds = new Set<string>();+ const propagateRootTurnToDescendants = (+ parentThreadId: string,+ rootTurnId: string,+ visited = new Set<string>(),+ ): void => {+ if (visited.has(parentThreadId)) return;+ visited.add(parentThreadId);+ for (const [childThreadId, parent] of descendantParentThreadByThreadId) {+ if (parent !== parentThreadId) continue;+ rootTurnIdByDescendantThreadId.set(childThreadId, rootTurnId);+ propagateRootTurnToDescendants(childThreadId, rootTurnId, visited);+ }+ };++ const descendantUpdateLifecycle = (+ descendantThreadId: string,+ ): Pick<AgentEvent, 'turnScope' | 'backgroundTurnStartedAt'> => {+ const rootTurnId = rootTurnIdByDescendantThreadId.get(descendantThreadId);+ if (+ rootTurnId+ && currentTurnId === rootTurnId+ && !completedTurnIds.has(rootTurnId)+ && !terminalErroredTurnIds.has(rootTurnId)+ ) {+ return {};+ }+ // Unknown ownership is safer as background: attaching it to the active+ // turn would mutate that turn's origin, attempt token, and watchdog. Its+ // missing start time also fails closed behind any later /clear boundary.+ return {+ turnScope: 'background',+ backgroundTurnStartedAt: rootTurnId+ ? turnOriginByTurnId.get(rootTurnId)?.startedAtMs ?? 0+ : 0,+ };+ };+const propagateCapabilitySelectionToDescendants = (parentThreadId: string,visited = new Set<string>(),@@ -3746,7 +3799,10 @@ export class CodexAgent extends BaseAgent {subagentModelFallback: host.getSubagentModelFallback?.(),});- const emitSubagentCardUpdate = (update: SubagentLiveCardUpdate): void => {+ const emitSubagentCardUpdate = (+ update: SubagentLiveCardUpdate,+ lifecycle: Pick<AgentEvent, 'turnScope' | 'backgroundTurnStartedAt'> = {},+ ): void => {// 子代理帧**不得**参与主 turn 的存活判定。eventQueue.push 上装了探针:每条事件都会刷新// upstreamIdleLastEventAt + armUpstreamIdle(),并喂给 observeReconnectStallEvent ——// 而 `agent_task_update` 正在 isReconnectRecoveryEvent 的白名单里(那对 Claude 的主线程@@ -3771,8 +3827,9 @@ export class CodexAgent extends BaseAgent {...(update.toolUses > 0 ? { toolUses: update.toolUses } : {}),durationMs: update.durationMs,},- },+ },source: 'codex',+ ...lifecycle,});} finally {emittingDescendantUpdate = false;@@ -3794,11 +3851,21 @@ export class CodexAgent extends BaseAgent {const registerDescendantThreadRouting = (childThreadId: string,parentThreadId: string,+ rootTurnId?: string,): void => {if (!childThreadId || childThreadId === parentThreadId) return;+ descendantParentThreadByThreadId.set(childThreadId, parentThreadId);+ const inheritedRootTurnId = rootTurnId+ ?? rootTurnIdByDescendantThreadId.get(parentThreadId);+ if (inheritedRootTurnId) {+ rootTurnIdByDescendantThreadId.set(childThreadId, inheritedRootTurnId);+ // A grandchild lineage may have arrived before the root spawn item.+ // Backfill the whole known subtree before host registration replays its+ // buffered notifications synchronously.+ propagateRootTurnToDescendants(childThreadId, inheritedRootTurnId);+ }// 测试用的 fake host 可能没有这个方法;真实 AppServerHost 恒有。host.registerDescendantLineage?.(childThreadId, parentThreadId);- descendantParentThreadByThreadId.set(childThreadId, parentThreadId);const inheritedSelection = capabilitySelectionTextByThreadId.get(parentThreadId)?? (parentThreadId === threadId && currentTurnId? capabilitySelectionTextByTurnId.get(currentTurnId)@@ -3838,11 +3905,11 @@ export class CodexAgent extends BaseAgent {return registration.childThreadIds;};- const registerSubagentSpawnLineage = (item: unknown): boolean => {+ const registerSubagentSpawnLineage = (item: unknown, rootTurnId: string): boolean => {const registration = readCodexSubagentSpawnRegistration(item);if (!registration) return false;for (const childThreadId of registration.childThreadIds) {- registerDescendantThreadRouting(childThreadId, threadId);+ registerDescendantThreadRouting(childThreadId, threadId, rootTurnId);}return true;};@@ -3913,7 +3980,12 @@ export class CodexAgent extends BaseAgent {nested.model,nested.failed === true,);- if (replayedNested) emitSubagentCardUpdate(replayedNested);+ if (replayedNested) {+ emitSubagentCardUpdate(+ replayedNested,+ descendantUpdateLifecycle(grandChildThreadId),+ );+ }}}}@@ -3930,7 +4002,7 @@ export class CodexAgent extends BaseAgent {}}const update = subagentLiveCards.handleDescendantNotification(childThreadId, method, params);- if (update) emitSubagentCardUpdate(update);+ if (update) emitSubagentCardUpdate(update, descendantUpdateLifecycle(childThreadId));if (method === 'turn/completed') {const status = record?.turn && typeof record.turn === 'object'@@ -3949,7 +4021,7 @@ export class CodexAgent extends BaseAgent {};/**- * 登记 spawn 映射,并回传"在 translator 之后重新声明真实聚合状态"的补发闭包。+ * 登记 spawn 映射,并回传"在 translator 之后重新声明真实聚合状态"的快照。** 发帧点必须在 translateItemNotification **之后**,两个理由:* - V2:translator 对 spawn 推一帧 status=running(无 usage),而重放出的状态可能@@ -3958,14 +4030,15 @@ export class CodexAgent extends BaseAgent {* status=completed —— 那只是 spawn 工具调用自己收口,子线程可能还在跑。不重新声明* 就会把运行中的子代理提前标成完成,还会抹掉先到的 failed/stopped(review)。*/- const noteSubagentSpawnItem = (item: unknown): (() => void) | null => {- if (!registerSubagentSpawnLineage(item)) return null;+ const noteSubagentSpawnItem = (+ item: unknown,+ rootTurnId: string,+ ): SubagentLiveCardUpdate | null => {+ if (!registerSubagentSpawnLineage(item, rootTurnId)) return null;// 先接 host 路由再进 tracker:registerDescendantLineage 会把子线程 TTL 缓冲里的// 早到通知同步补投进 handleDescendantNotification(tracker 缓冲),随后// noteSpawnItem 建卡时统一重放,首帧就带上真实用量。- const replayed = subagentLiveCards.noteSpawnItem(item);- if (!replayed) return null;- return () => emitSubagentCardUpdate(replayed);+ return subagentLiveCards.noteSpawnItem(item);};const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {if (closed) return;@@ -3978,6 +4051,7 @@ export class CodexAgent extends BaseAgent {capabilitySelectionTextByTurnId.clear();capabilitySelectionTextByThreadId.clear();descendantParentThreadByThreadId.clear();+ rootTurnIdByDescendantThreadId.clear();terminalDescendantTurnIds.clear();// 与 close() 同规:handle 被终止后子代理卡不会再有消费者。同样先收终态再清 ——// 这条路径(thread cleanup failure / 强制 retire)恰恰是最容易留下永久转圈卡的。@@ -5761,7 +5835,7 @@ export class CodexAgent extends BaseAgent {eventQueue.push = (ev: AgentEvent): boolean => {// 子代理卡帧只是"子线程有进展",不代表主 turn 还活着 —— 不参与静默计时与// reconnect 恢复判定,否则主 turn 哑火时会被子代理的心跳一直掩盖(review)。- if (!emittingDescendantUpdate) {+ if (!emittingDescendantUpdate && ev.turnScope !== 'background') {upstreamIdleLastEventType = ev.type;upstreamIdleLastEventAt = Date.now();armUpstreamIdle();@@ -6794,6 +6868,46 @@ export class CodexAgent extends BaseAgent {);};+ const collabTerminalItemKey = (+ turnId: string | null | undefined,+ item: unknown,+ ): string | undefined => {+ if (!turnId) return undefined;+ if (!item || typeof item !== 'object') return undefined;+ const candidate = item as { id?: unknown; type?: unknown; status?: unknown };+ if (+ candidate.type !== 'collabAgentToolCall' ||+ (candidate.status !== 'completed' && candidate.status !== 'failed') ||+ typeof candidate.id !== 'string' ||+ candidate.id.length === 0+ ) return undefined;+ return `${turnId}:${candidate.id}`;+ };++ const collabItemHasRunningAgentState = (item: unknown): boolean => {+ if (!item || typeof item !== 'object') return false;+ const record = item as { type?: unknown; agentsStates?: unknown };+ if (+ record.type !== 'collabAgentToolCall'+ || !record.agentsStates+ || typeof record.agentsStates !== 'object'+ ) return false;+ return Object.values(record.agentsStates as Record<string, unknown>).some((state) => {+ let label: unknown = typeof state === 'string' ? state : undefined;+ if (!label && state && typeof state === 'object') {+ const stateRecord = state as Record<string, unknown>;+ for (const key of ['status', 'state', 'phase']) {+ if (typeof stateRecord[key] === 'string') {+ label = stateRecord[key];+ break;+ }+ }+ }+ return typeof label === 'string'+ && /^(running|in[_-]?progress|started|active)$/i.test(label.trim());+ });+ };+const stopActiveRolloutPlanFallback = (): void => {const stop = stopRolloutPlanFallback;stopRolloutPlanFallback = null;@@ -8076,6 +8190,7 @@ export class CodexAgent extends BaseAgent {capabilitySelectionTextByTurnId.clear();capabilitySelectionTextByThreadId.clear();descendantParentThreadByThreadId.clear();+ rootTurnIdByDescendantThreadId.clear();terminalDescendantTurnIds.clear();stopActiveRolloutPlanFallback();resetUpstreamIdleForTurnEnd();@@ -8126,7 +8241,9 @@ export class CodexAgent extends BaseAgent {: undefined;registerDescendantThreadRouting(childThreadId, parentThreadId);const replayed = subagentLiveCards.noteDescendantThread(childThreadId, parentThreadId, childModel);- if (replayed) emitSubagentCardUpdate(replayed);+ if (replayed) {+ emitSubagentCardUpdate(replayed, descendantUpdateLifecycle(childThreadId));+ }},descendantNotification: handleDescendantNotification,turnStarted: (params) => {@@ -8182,9 +8299,15 @@ export class CodexAgent extends BaseAgent {const startedOwner = startedOwnerEntries.length === 1? startedOwnerEntries[0]: undefined;+ const existingTurnOrigin = turnOriginByTurnId.get(params.turn.id);turnOriginByTurnId.set(params.turn.id, {startSeq: startedOwner?.[0] ?? null,sendGen: startedOwner?.[1].sendGen ?? sendGeneration,+ startedAtMs:+ startedOwner?.[1].startedAtMs+ ?? (existingTurnOrigin+ ? existingTurnOrigin.startedAtMs+ : (startedOwnerEntries.length === 0 ? Date.now() : 0)),});// Notifications may arrive before the turn/start RPC response. Bind the// selector at the same unique-owner boundary as turnOrigin so an early@@ -8369,7 +8492,7 @@ export class CodexAgent extends BaseAgent {noteActiveToolContext(params.item, params.turnId);noteToolItemLifecycle(params.item, 'started');// 先登记再翻译:子线程通知可能紧随 spawn item 到达,映射就位才不丢首帧。- const emitReplayedSubagentUpdate = noteSubagentSpawnItem(params.item);+ const replayedSubagentUpdate = noteSubagentSpawnItem(params.item, params.turnId);pushItemStatus(params.item);translateItemNotification('started', params, eventQueue, {rt: translatorRt,@@ -8377,7 +8500,7 @@ export class CodexAgent extends BaseAgent {onCompactBoundary: handleCompactBoundary,});// 重放帧后发:translator 刚推的 running 帧不得把已重放出的终态盖回去。- emitReplayedSubagentUpdate?.();+ if (replayedSubagentUpdate) emitSubagentCardUpdate(replayedSubagentUpdate);},itemUpdated: (params) => {const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);@@ -8402,13 +8525,15 @@ export class CodexAgent extends BaseAgent {// (turn 缓冲、stale turn 丢弃、上游省略),映射就要一直等到 completed 才建立 —— 期间// 子线程的 item / token / turn 终态全被缓冲,卡片在整个运行期(可能好几分钟)没有实时// 数据,最后才一次性补上。那恰好是本 PR 要解决的问题本身(review)。- const emitReplayedSubagentUpdateOnUpdated = noteSubagentSpawnItem(params.item);+ const replayedSubagentUpdateOnUpdated = noteSubagentSpawnItem(params.item, params.turnId);translateItemNotification('updated', params, eventQueue, {rt: translatorRt,log,onCompactBoundary: handleCompactBoundary,});- emitReplayedSubagentUpdateOnUpdated?.();+ if (replayedSubagentUpdateOnUpdated) {+ emitSubagentCardUpdate(replayedSubagentUpdateOnUpdated);+ }},itemCompleted: (params) => {const reservedChildThreadIds = reserveSubagentSpawnLineage(params.item);@@ -8418,28 +8543,90 @@ export class CodexAgent extends BaseAgent {rememberPendingSpawnLineage(params.turnId, reservedChildThreadIds);return;}- if (shouldIgnoreStaleTurnEvent(params.turnId)) {+ const collabTerminalKey = collabTerminalItemKey(params.turnId, params.item);+ if (collabTerminalKey && handledCollabTerminalItemIds.has(collabTerminalKey)) {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}+ let isLateCollabTerminal = false;+ if (shouldIgnoreStaleTurnEvent(params.turnId)) {+ // A non-transport terminal error can close the logical turn before the+ // authoritative turn/completed arrives. Keep the same one-shot late+ // collab carve-out open for that error tombstone, otherwise the stale+ // guard would swallow the child's terminal item and leave its task card+ // running forever.+ if (+ !collabTerminalKey+ || (!completedTurnIds.has(params.turnId) && !terminalErroredTurnIds.has(params.turnId))+ ) {+ discardPendingSpawnLineageIds(reservedChildThreadIds);+ return;+ }+ isLateCollabTerminal = true;+ }if (interceptProposedPlanItem(params.item)) {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}+ if (collabTerminalKey) handledCollabTerminalItemIds.add(collabTerminalKey);if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);noteActiveToolContext(params.item, params.turnId);- noteToolItemLifecycle(params.item, 'completed');+ // This late item belongs to an already-terminal parent. The parent+ // cleanup already cleared its pending tools; touching the shared+ // lifecycle set here would re-arm the currently active turn's idle+ // watchdog with a fresh budget.+ if (!isLateCollabTerminal) noteToolItemLifecycle(params.item, 'completed');// 防御:spawn item 的 started phase 若被上游省略,completed 仍能补上映射。- const emitReplayedSubagentUpdateOnCompleted = noteSubagentSpawnItem(params.item);- translateItemNotification('completed', params, eventQueue, {+ const replayedSubagentUpdateOnCompleted = noteSubagentSpawnItem(+ params.item,+ params.turnId,+ );+ const itemEventQueue = isLateCollabTerminal+ ? {+ push: (event: AgentEvent) => eventQueue.push({+ ...event,+ turnScope: 'background',+ // Missing ownership fails closed only if a later /clear exists.+ backgroundTurnStartedAt:+ turnOriginByTurnId.get(params.turnId)?.startedAtMs ?? 0,+ }),+ end: () => eventQueue.end(),+ clear: () => eventQueue.clear(),+ get pending() { return eventQueue.pending; },+ [Symbol.asyncIterator]: () => eventQueue[Symbol.asyncIterator](),+ } as AsyncQueue<AgentEvent>+ : eventQueue;+ translateItemNotification('completed', params, itemEventQueue, {rt: translatorRt,log,onCompactBoundary: handleCompactBoundary,});- emitReplayedSubagentUpdateOnCompleted?.();+ // A late V1 spawn completion is the spawn tool closing, not necessarily+ // the child closing. Reassert a running compact state, or an explicit+ // failed/stopped tracker state; a completed replay would only duplicate+ // the translator's own frame.+ const shouldReplayLateSubagentState =+ collabItemHasRunningAgentState(params.item)+ || replayedSubagentUpdateOnCompleted?.status === 'failed'+ || replayedSubagentUpdateOnCompleted?.status === 'stopped';+ if (!isLateCollabTerminal || shouldReplayLateSubagentState) {+ if (replayedSubagentUpdateOnCompleted) {+ emitSubagentCardUpdate(+ replayedSubagentUpdateOnCompleted,+ isLateCollabTerminal+ ? {+ turnScope: 'background',+ backgroundTurnStartedAt:+ turnOriginByTurnId.get(params.turnId)?.startedAtMs ?? 0,+ }+ : {},+ );+ }+ }// item 完成后, 若 turn 仍在跑, 先回到 'Generating...' 兜底 — 下一条 item 起来会再覆盖。// turn/completed 在 turn 结束时会 push 'Done' 终态, 不需要在这里特判。- if (isTurnInFlight) pushStatus('Generating...');+ // 迟到的旧 turn 收口只允许发 background 结果,不能给当前 turn 注入前台状态。+ if (isTurnInFlight && !isLateCollabTerminal) pushStatus('Generating...');},turnPlanUpdated: (params) => {if (enqueueIfBufferedTurn(params.turnId, () => handlers.turnPlanUpdated?.(params))) return;@@ -8549,6 +8736,7 @@ export class CodexAgent extends BaseAgent {capabilitySelectionTextByTurnId.clear();capabilitySelectionTextByThreadId.clear();descendantParentThreadByThreadId.clear();+ rootTurnIdByDescendantThreadId.clear();terminalDescendantTurnIds.clear();submittedUserInputByTurn.clear();clearAllPendingUserInputInteractions();@@ -8836,6 +9024,7 @@ export class CodexAgent extends BaseAgent {capabilitySelectionTextByTurnId.clear();capabilitySelectionTextByThreadId.clear();descendantParentThreadByThreadId.clear();+ rootTurnIdByDescendantThreadId.clear();terminalDescendantTurnIds.clear();// 会话收口后子代理卡不再有消费者。清状态**之前**必须先把仍在跑的卡收成终态:// 之后后代通知永远不会再到,只清内部状态会让渲染端一直留着最后一帧 running,卡片@@ -9088,6 +9277,7 @@ export class CodexAgent extends BaseAgent {turnOriginByTurnId.set(resp.turn.id, {startSeq: ownerSeq,sendGen: startEntry.sendGen,+ startedAtMs: startEntry.startedAtMs,});}// 缓冲的歧义 started 对账 (codex R9 P2): 本响应确立在飞 RPC 的@@ -9170,7 +9360,14 @@ export class CodexAgent extends BaseAgent {capabilitySelectionText,);// 权威归属: 这个 turn 由本次 start 生出, 属于本轮 send。- turnOriginByTurnId.set(resp.turn.id, { startSeq: ownerSeq, sendGen: mySendGen });+ turnOriginByTurnId.set(resp.turn.id, {+ startSeq: ownerSeq,+ sendGen: mySendGen,+ startedAtMs:+ startEntry?.startedAtMs+ ?? turnOriginByTurnId.get(resp.turn.id)?.startedAtMs+ ?? Date.now(),+ });currentTurnId = resp.turn.id;isTurnInFlight = true;turnStartGeneration += 1; // 见声明处:延迟善后靠它判断"期间起过新 turn"diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 2c266c49f8..48c0d0019d 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -1749,6 +1749,18 @@ function handleCollabAgentToolCall(}// completed+ // Some app-server versions omit item/started and send only the terminal+ // collab snapshot. Reconstruct the tool-use boundary before the result so+ // the late background item still has a renderer/persistence anchor.+ const hadToolUse = ctx.rt.emittedToolUse.has(item.id);+ if (!hadToolUse) {+ ctx.rt.emittedToolUse.add(item.id);+ queue.push({+ type: 'tool_use',+ data: { toolUseId: item.id, toolName, input },+ source: 'codex',+ });+ }ctx.rt.emittedToolUse.delete(item.id);const isError = item.status === 'failed';const fullText = formatCodexAgentStatesSummary(item.agentsStates) ?? (isError ? 'failed' : item.status);diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex 90e44d8a95..04efc75e8f 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -477,6 +477,27 @@ describe('Session per-turn origin 打标', () => {expect(secondText?.turnAttemptToken).toBe(2);});+ it('background late child events stay visible without inheriting the next turn', async () => {+ const { handle, emit } = createControllableHandle();+ const session = makeSession(handle);+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));++ await session.send('first', { origin: SCHED_ORIGIN, turnAttemptToken: 1 });+ await emit({ type: 'done', data: {} });+ await session.send('second', { turnAttemptToken: 2 });+ await emit({+ type: 'agent_task_update',+ turnScope: 'background',+ data: { taskId: 'child-1', status: 'completed' },+ });++ const late = seen.find((event) => event.type === 'agent_task_update');+ expect(late).toMatchObject({ turnScope: 'background' });+ expect(late?.turnOrigin).toBeUndefined();+ expect(late?.turnAttemptToken).toBeUndefined();+ });+it('event loop crash emits a terminal error and closes the poisoned session', async () => {let releaseCrash!: () => void;const crashReady = new Promise<void>((resolve) => {diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 8385fdcfe1..8d83a4e0c7 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1182,15 +1182,17 @@ export class Session {* (review #944 第二轮)。*/private fanOutEvent(event: AgentEvent, observedGeneration = this.turnGeneration): void {- this.lastEventAt = Date.now();+ const isBackgroundEvent = event.turnScope === 'background';+ if (!isBackgroundEvent) this.lastEventAt = Date.now();this.lastEventType = event.type;const isCurrentGeneration = observedGeneration === this.turnGeneration;// fan-out 前打 turn origin(所有 listener 拿到同一份);事件对象由 translator// 每次新建、看门狗每次合成,不会串台。=== undefined 守卫:不覆盖 agent 自带的。- if (isCurrentGeneration && this.currentTurnOrigin && event.turnOrigin === undefined) {+ if (!isBackgroundEvent && isCurrentGeneration && this.currentTurnOrigin && event.turnOrigin === undefined) {event.turnOrigin = this.currentTurnOrigin;}if (+ !isBackgroundEvent &&isCurrentGeneration &&this.currentTurnAttemptToken !== null &&event.turnAttemptToken === undefined@@ -1240,6 +1242,10 @@ export class Session {for (const listener of this.eventListeners) {try { listener(listenerEvent); } catch (e) { this.logger.error('event listener threw', { error: String(e) }); }}+ // A late child update belongs to the completed parent turn. It remains+ // visible to listeners, but must not clear/adopt the current turn or keep+ // its zero-event watchdog alive.+ if (isBackgroundEvent) return;// turn 真正结束后清 origin,下一轮无 origin 的 turn 不被污染。// 关键:**只**在 done / 终止型 error 上清,**不要**在 status(isRunning=false)// 上清 —— translator 收尾是先 push end-status(isRunning=false)、紧接着 pushdiff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex a57af0f8eb..ebaef7bfa3 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -132,6 +132,20 @@ export interface AgentEvent {data: unknown;/** 事件来源标识,便于调试 */source?: 'claude-code' | 'codex' | 'pi';+ /**+ * Events that finish work owned by a completed turn can still arrive after a+ * later turn has started (for example, a V1 collab child). These are still+ * useful to render, but must not inherit the later turn's attribution or+ * watchdog state.+ */+ turnScope?: 'turn' | 'background';+ /**+ * Local start time of the turn that owns a background event. Main-process+ * persistence uses this lifecycle evidence to keep pre-clear late work from+ * repopulating a cleared conversation. Never expose it to renderer/device+ * boundaries.+ */+ backgroundTurnStartedAt?: number;/*** 本事件所属 turn 的发起来源,由 Session 在事件 fan-out 前打标(见 session.ts* 的 currentTurnOrigin)。turn 结束(isTerminalTurnEvent)后清空,不污染下一轮。diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.tsindex 5ebcc9ee14..b6c5b78721 100644--- a/packages/maker-shared/src/__tests__/agentTask.test.ts+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts@@ -294,6 +294,86 @@ describe('findAgentTaskUpdate', () => {});describe('buildAgentTaskCardModel', () => {+ it('REPRO: treats a paired final result as terminal when the live update is stale running', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'collab:spawnAgent',+ result: 'child-thread: completed',+ update: {+ provider: 'codex',+ taskId: 'collab-1',+ parentToolUseId: 'collab-1',+ status: 'running',+ },+ });++ expect(model.status).toBe('completed');+ });++ it('REPRO: keeps a V1 spawn running when its paired result is a running state summary', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'collab:spawnAgent',+ result: 'child-thread: running',+ update: {+ provider: 'codex',+ taskId: 'collab-1',+ parentToolUseId: 'collab-1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ });++ it('REPRO: keeps an async Claude Agent running for its launch receipt', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'Agent',+ toolInput: { run_in_background: true, prompt: 'keep working' },+ result: 'Async agent launched successfully.',+ update: {+ provider: 'claude-code',+ taskId: 'agent-1',+ parentToolUseId: 'agent-1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ });++ it.each(['in_progress', 'in-progress', 'started', 'active'])(+ 'keeps a V1 spawn running for the %s state summary',+ (state) => {+ const model = buildAgentTaskCardModel({+ toolName: 'collab:spawnAgent',+ result: `child-thread: ${state}`,+ update: {+ provider: 'codex',+ taskId: 'collab-1',+ parentToolUseId: 'collab-1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ },+ );++ it('preserves explicit failed and stopped terminal states when a result is present', () => {+ const input = {+ toolName: 'collab:spawnAgent',+ result: 'child-thread: terminal',+ update: {+ provider: 'codex' as const,+ taskId: 'collab-1',+ parentToolUseId: 'collab-1',+ },+ };+ expect(buildAgentTaskCardModel({ ...input, update: { ...input.update, status: 'failed' } }).status)+ .toBe('failed');+ expect(buildAgentTaskCardModel({ ...input, update: { ...input.update, status: 'stopped' } }).status)+ .toBe('stopped');+ });+it('falls back the title through update → tool input description → prompt', () => {expect(buildAgentTaskCardModel({ update: { provider: 'codex', taskId: 't', status: 'running', title: 'From update' } }).title).toBe('From update');diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.tsindex 22c76eacad..e4492a348a 100644--- a/packages/maker-shared/src/agentTask.ts+++ b/packages/maker-shared/src/agentTask.ts@@ -153,6 +153,21 @@ export interface AgentTaskUpdate {updatedAt?: string;}+/**+ * Derive the visible task status from the live update and its paired tool result.+ * A result is a terminal fact, so it closes a stale `running` update without+ * overriding an explicit failure or stopped state.+ */+export function deriveAgentTaskStatus(+ updateStatus: AgentTaskStatus | undefined,+ result?: string,+ options?: { resultIsLaunchReceipt?: boolean },+): AgentTaskStatus {+ const hasResult = typeof result === 'string' && result.trim().length > 0;+ if (updateStatus === 'running' && hasResult && !options?.resultIsLaunchReceipt) return 'completed';+ return updateStatus ?? (hasResult ? 'completed' : 'running');+}+/*** Tool names that spawn a sub-agent task: Claude `Task`/`Agent`, Codex collab agents,* PI `subagent`(Cindy 自有扩展注册的工具名,与 pi 社区惯例一致)。@@ -362,6 +377,29 @@ export function subagentSpawnReceiptName(return name && trimmed && trimmed === name ? name : undefined;}+/**+ * V1 `collab:spawnAgent` returns a compact child-state summary. A `running`+ * summary is a launch receipt for the spawn tool, not a terminal result for+ * the child task, so it must not close a stale running update.+ */+export function subagentSpawnResultIndicatesRunning(+ toolName: string | undefined,+ result: string | undefined,+): boolean {+ const trimmed = result?.trim() ?? '';+ // Claude's asynchronous Agent tool returns a textual launch receipt while the+ // child is still running. Treat it like the structured Codex V1 receipt so a+ // paired stale `running` update does not close the task prematurely.+ if ((toolName === 'Agent' || toolName === 'Task')+ && trimmed === 'Async agent launched successfully.') {+ return true;+ }+ if (toolName !== 'collab:spawnAgent') return false;+ return (result ?? '').split(/\r?\n/).some((line) =>+ /^[^:\n]+:\s*(?:running|in[_-]?progress|started|active)\s*$/i.test(line.trim()),+ );+}+export function buildAgentTaskCardModel(input: {toolName?: string;toolInput?: unknown;@@ -369,7 +407,11 @@ export function buildAgentTaskCardModel(input: {result?: string;}): AgentTaskCardModel {const { toolName, toolInput, update, result } = input;- const status: AgentTaskStatus = update?.status ?? (result ? 'completed' : 'running');+ const status = deriveAgentTaskStatus(update?.status, result, {+ resultIsLaunchReceipt:+ subagentSpawnReceiptName(toolName, toolInput, result) !== undefined+ || subagentSpawnResultIndicatesRunning(toolName, result),+ });const provider: 'claude-code' | 'codex' | 'pi' =update?.provider?? (toolName?.startsWith('collab:')diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.tsindex ea6786edf4..ba61d5b98d 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -1,7 +1,10 @@import {type AgentTaskUpdate,+ deriveAgentTaskStatus,findAgentTaskUpdate,isAgentTaskToolName,+ subagentSpawnReceiptName,+ subagentSpawnResultIndicatesRunning,} from './agentTask';import { HISTORY_GAP_SPLIT_MS } from './historyGap';@@ -1394,15 +1397,26 @@ function groupActiveWorkRuns<TMessage extends MessageRenderNormalizedMessage>(* 运行中(未到终态)的子 Agent 卡是折叠时的"可见锚点",绝不折进「工作过程」组:* 任务没完成就归档会谎报终态(典型:后台子 agent 仍在跑,父 turn 已产出最终正文)。* status 派生口径与 buildAgentTaskCardModel / 桌面 MessageStream 的 isRunningAgentTask- * 完全一致(update.status 优先;否则有配对工具结果 secondaryBody 视为 completed、- * 无则 running),保证「卡片显示运行中」与「是否折叠」永远同步。- * 终态 = completed/failed/stopped。+ * 完全一致:配对工具结果 secondaryBody 会把 stale running 收敛为 completed,+ * 但不覆盖 failed/stopped 等明确终态,保证「卡片显示运行中」与「是否折叠」永远同步。*/function isRunningAgentTaskItem<TMessage extends MessageRenderNormalizedMessage,>(item: MessageRenderItem<TMessage>): boolean {if (item.type !== 'agent_task') return false;- const status = item.update?.status ?? (item.toolCall?.secondaryBody ? 'completed' : 'running');+ const status = deriveAgentTaskStatus(item.update?.status, item.toolCall?.secondaryBody, {+ resultIsLaunchReceipt:+ item.toolCall !== undefined &&+ (subagentSpawnReceiptName(+ toolNameOf(item.toolCall.source),+ toolInputOf(item.toolCall.source),+ item.toolCall.secondaryBody,+ ) !== undefined+ || subagentSpawnResultIndicatesRunning(+ toolNameOf(item.toolCall.source),+ item.toolCall.secondaryBody,+ )),+ });return status === 'running';}