Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(maker-core,desktop): 唤醒桥接与 continuation claim 增加超时对账 (#2999)

Lizi08034e20ab77
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
index 59cf9c722a..bd3fe68cb2 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts
@@ -76,7 +76,12 @@ vi.mock('@/lib/makerTransport', () => ({
isRemoteSessionSticky: (sessionId: string) => sessionId.startsWith('remote-'),
}));
-import { EMPTY_SESSION_STATE, handleStreamEvent, makerChatStore } from '@/lib/makerChatStore';
+import {
+ EMPTY_SESSION_STATE,
+ handleStreamEvent,
+ makerChatStore,
+ WAKE_BRIDGE_RECONCILE_MS,
+} from '@/lib/makerChatStore';
import type { SessionChatState } from '@/lib/makerChatStore';
describe('makerChatStore agent task updates', () => {
@@ -587,6 +592,76 @@ describe('getRunningSnapshot 后台 subagent 折算(真 store)', () => {
}
});
+ it('唤醒桥接超时对账:wake turn 永不启动时清桥接收口,不再永久转圈', async () => {
+ // 2026-08-18 事故形态:后台子 agent 在主 turn 运行中完成,上游 CLI 把
+ // task-notification 当 mid-turn 附件消费 —— 主轮 Done 后桥接(pendingTaskWake)
+ // 死等一个永远不会来的 isRunning:true,sidebar 永久转圈。修复:桥接挂起时起
+ // 对账定时器,宽限期内无 wake turn 启动即清空桥接,让 running 快照收敛为事实
+ // (任务卡早已显示终态,不丢信息)。
+ const sid = `wake-reconcile-${Math.random().toString(36).slice(2, 8)}`;
+ vi.useFakeTimers();
+ try {
+ // turn start + 子任务启动 + 主 turn 内终态 → 桥接置位 + 跨主 turn 标记
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });
+ applyTask(sid, { taskId: 't1', status: 'completed' });
+ expect(makerChatStore.getSnapshot(sid).pendingTaskWake).toBe(1);
+
+ // 主轮 Done:桥接按设计跨过 Done 存活,等待 wake turn —— 此刻起对账表
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, false, 'Done'));
+ const afterMainDone = makerChatStore.getSnapshot(sid);
+ expect(afterMainDone.pendingTaskWake).toBe(1);
+ expect(afterMainDone.pendingTaskWakeDuringTurn).toBe(0);
+ expect(makerChatStore.getRunningSnapshot().get(sid)?.isRunning).toBe(true);
+
+ // 宽限期内(差 1ms):桥接必须仍在,不得提前收口
+ await vi.advanceTimersByTimeAsync(WAKE_BRIDGE_RECONCILE_MS - 1);
+ expect(makerChatStore.getSnapshot(sid).pendingTaskWake).toBe(1);
+ expect(makerChatStore.getRunningSnapshot().get(sid)?.isRunning).toBe(true);
+
+ // 越过宽限且无 wake turn 启动 → 桥接清空,running 快照收敛
+ await vi.advanceTimersByTimeAsync(2_000);
+ const afterReconcile = makerChatStore.getSnapshot(sid);
+ expect(afterReconcile.pendingTaskWake).toBe(0);
+ expect(afterReconcile.pendingTaskWakeDuringTurn).toBe(0);
+ expect(afterReconcile.pendingTaskWakeStarted).toBe(false);
+ expect(makerChatStore.getRunningSnapshot().get(sid)?.isRunning ?? false).toBe(false);
+ } finally {
+ // 恢复真实时钟前先冲掉 fake 定时器:getRunningSnapshot 的 transition 清理是
+ // setTimeout(0) + 模块级 _stopTransitionClearScheduled 标志,不冲掉会把标志
+ // 留在 true,泄漏到后续真实时钟用例(transition 永不清除)。
+ await vi.advanceTimersByTimeAsync(10).catch(() => undefined);
+ vi.useRealTimers();
+ makerChatStore.purgeSession(sid);
+ }
+ });
+
+ it('唤醒桥接超时对账:宽限期内 wake turn 启动 → 定时器解除,不误伤健康路径', async () => {
+ const sid = `wake-reconcile-ok-${Math.random().toString(36).slice(2, 8)}`;
+ vi.useFakeTimers();
+ try {
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });
+ applyTask(sid, { taskId: 't1', status: 'completed' });
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, false, 'Done'));
+ expect(makerChatStore.getSnapshot(sid).pendingTaskWake).toBe(1);
+
+ // 宽限期内 wake turn 启动(isRunning:true)→ 桥接正常消费、定时器解除
+ await vi.advanceTimersByTimeAsync(5_000);
+ makerChatStore.__applyStatusUpdateForTest(sid, statusUpdate(sid, true));
+ expect(makerChatStore.getSnapshot(sid).pendingTaskWake).toBe(0);
+
+ // 再快进远超宽限:不得出现「事后清算」打断仍在跑的 wake turn
+ await vi.advanceTimersByTimeAsync(WAKE_BRIDGE_RECONCILE_MS * 2);
+ expect(makerChatStore.getSnapshot(sid).pendingTaskWake).toBe(0);
+ expect(makerChatStore.getRunningSnapshot().get(sid)?.isRunning).toBe(true);
+ } finally {
+ await vi.advanceTimersByTimeAsync(10).catch(() => undefined);
+ vi.useRealTimers();
+ makerChatStore.purgeSession(sid);
+ }
+ });
+
it('LRU 降级/重开后重建的 running wake 任务终态 → 不误标跨主 turn,wake 失败仍能清桥接', async () => {
// Codex P1:renderer 错过主 turn 终态 Done(如 LRU 降级/重开后
// seedBackgroundTaskSnapshots 重建 running local_agent)时,agentStatus.status 仍是
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 8d9c882040..acbb33fb12 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -3269,6 +3269,7 @@ function _purgeSession(sessionId: string): void {
// 交接中的迟到 continuation,且不写入 /clear 的历史时间边界。
bumpRendererClearGeneration(sessionId);
cancelRemoteOptimisticSendsForSessionPurge(sessionId);
+ clearWakeBridgeReconcileTimer(sessionId);
sessions.delete(sessionId);
localSentUserMessageIds.delete(sessionId);
pendingLocalRetryIntents.delete(sessionId);
@@ -3553,6 +3554,49 @@ function setState(
if (!hasDeferredStateWork()) clearDeferredStateNotificationTimer();
}
+/**
+ * 唤醒桥接对账(见 pendingTaskWake 字段注释):桥接在「wake 任务终态 → wake turn
+ * 启动」的窗口里撑住 running 快照,但上游 CLI 在「后台子 agent 于主 turn 运行中完成」
+ * 的时机会把 task-notification 当 mid-turn 附件消费掉,续跑 turn 永远不会来 —— 桥接
+ * 便在主 turn Done 之后无限期等待,sidebar 永久转圈。桥接挂起(计数 > 0 且会话非
+ * running)时起表:宽限期内 isTurnStart 照常消费计数(isRunning 翻 true 即解除);
+ * 超时仍未启动则清空桥接,让 running 快照收敛为事实 —— 任务卡早已显示终态,不丢信息。
+ */
+export const WAKE_BRIDGE_RECONCILE_MS = 60_000;
+const wakeBridgeReconcileTimers = new Map<string, ReturnType<typeof setTimeout>>();
+
+function clearWakeBridgeReconcileTimer(sessionId: string): void {
+ const timer = wakeBridgeReconcileTimers.get(sessionId);
+ if (!timer) return;
+ clearTimeout(timer);
+ wakeBridgeReconcileTimers.delete(sessionId);
+}
+
+function scheduleWakeBridgeReconciliation(sessionId: string): void {
+ const state = sessions.get(sessionId);
+ if (!state || state.pendingTaskWake <= 0 || state.agentStatus.isRunning) {
+ clearWakeBridgeReconcileTimer(sessionId);
+ return;
+ }
+ // 已在计时:保持首次挂起时刻的截止线,后续无关事件不刷新窗口。
+ if (wakeBridgeReconcileTimers.has(sessionId)) return;
+ const timer = setTimeout(() => {
+ wakeBridgeReconcileTimers.delete(sessionId);
+ // slice 可能已被 clearSession / LRU 逐出;setState 会重建 slice,先探测再动。
+ if (!sessions.has(sessionId)) return;
+ setState(sessionId, (s) => {
+ if (s.pendingTaskWake <= 0 || s.agentStatus.isRunning) return s;
+ return {
+ ...s,
+ pendingTaskWake: 0,
+ pendingTaskWakeDuringTurn: 0,
+ pendingTaskWakeStarted: false,
+ };
+ });
+ }, WAKE_BRIDGE_RECONCILE_MS);
+ wakeBridgeReconcileTimers.set(sessionId, timer);
+}
+
function notify(sessionId: string): void {
emitStateNotifications(sessionId);
}
@@ -6120,6 +6164,7 @@ function dispatchStreamEventPayload(
} as CCAgentStreamEvent;
supersedeInputProjectionOnTerminalEvent(sessionId, streamEvent);
setState(sessionId, (s) => handleStreamEvent(s, streamEvent), { deferNotification });
+ scheduleWakeBridgeReconciliation(sessionId);
}
function clearTextDeltaFlushTimer(): void {
@@ -6505,6 +6550,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
}
setState(sessionId, (s) => handleStatusUpdate(s, update));
+ scheduleWakeBridgeReconciliation(sessionId);
return;
}
@@ -14441,6 +14487,7 @@ export const makerChatStore = {
__applyStreamEventForTest: (sessionId: string, event: CCAgentStreamEvent): void => {
supersedeInputProjectionOnTerminalEvent(sessionId, event);
setState(sessionId, (s) => handleStreamEvent(s, event));
+ scheduleWakeBridgeReconciliation(sessionId);
},
/** Exposed for tests only: 把 status update 打进真实 store。 */
__applyStatusUpdateForTest: (sessionId: string, update: CCAgentStatusUpdate): void => {
@@ -14448,6 +14495,7 @@ export const makerChatStore = {
supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
}
setState(sessionId, (s) => handleStatusUpdate(s, update));
+ scheduleWakeBridgeReconciliation(sessionId);
},
/** Exposed for tests only. */
__hydratePersistedMessageForTest: hydratePersistedMessage,
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
index e0436ddb83..eca7067ede 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
@@ -78,7 +78,7 @@ vi.mock('../../shared/async-queue.js', async (importOriginal) => {
};
});
-import { ClaudeCodeAgent } from '../index.js';
+import { ClaudeCodeAgent, WAKE_CONTRACT_GRACE_MS } from '../index.js';
import { Session } from '../../../session.js';
const tempDirs: string[] = [];
@@ -595,6 +595,80 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {
await handle.close().catch(() => undefined);
});
+ it('wake contract reconciliation cancels an awaiting claim whose tasks are all terminal without continuation activity', async () => {
+ vi.useFakeTimers();
+ try {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await vi.advanceTimersByTimeAsync(0);
+ stream.emit(turnResult('waiting'));
+ await vi.advanceTimersByTimeAsync(0);
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(taskEvents(events).length).toBeGreaterThanOrEqual(2);
+
+ // 宽限期内:claim 仍在按 task_notification 续跑契约等待,不得提前收口。
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+ expect(events.filter(isProductTerminal)).toHaveLength(0);
+
+ // 快进越过宽限窗口且无任何续跑活动:契约失守 → 取消 claim 并补合成终态。
+ await vi.advanceTimersByTimeAsync(WAKE_CONTRACT_GRACE_MS + 1_000);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(events.filter(isProductTerminal).length).toBe(1);
+ expect(
+ events.find(
+ (event) => event.type === 'done' && event.turnContinuationId === undefined,
+ )?.data,
+ ).toMatchObject({ reason: 'turn_continuation_cancelled' });
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ // 对账不是用户 Stop:不得触碰 stopTask / interrupt。
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('wake contract reconciliation stands down once the continuation activates', async () => {
+ vi.useFakeTimers();
+ try {
+ const { handle, stream, events } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await vi.advanceTimersByTimeAsync(0);
+ stream.emit(turnResult('waiting'));
+ await vi.advanceTimersByTimeAsync(0);
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+
+ // 健康路径:续跑段在宽限期内激活,对账定时器随之解除。
+ stream.emit(assistantText('automatic continuation started'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('active');
+
+ await vi.advanceTimersByTimeAsync(WAKE_CONTRACT_GRACE_MS + 60_000);
+ expect(events.filter(isProductTerminal)).toHaveLength(0);
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('active');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('graceful stop lets an already active continuation finish through its interrupted result', async () => {
const { handle, stream, events, fakeQuery } = await startSessionWithStream();
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index fb1895655d..1c68c18771 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -678,6 +678,13 @@ function isInvalidCompactPreservedSegmentForkError(err: unknown): boolean {
* 少停不误停,启发式后台活动检测兜底)。
*/
const WAKE_BACKGROUND_TASK_TYPES: ReadonlySet<string> = new Set(['local_agent', 'local_workflow']);
+/**
+ * Wake 契约对账宽限:claim 内全部 wake 任务到终态(completed/failed)后,留给 SDK
+ * 启动自动续跑段的窗口。健康路径里 dequeue → 顶层活动只需数秒;宽限内没有任何
+ * 激活即判定契约失守(CLI 在「子代理于主 turn 运行中完成」时会把通知当 mid-turn
+ * 附件消费,续跑段永远不会来),取消 claim 收口产品 turn。只影响终态低频路径。
+ */
+export const WAKE_CONTRACT_GRACE_MS = 60_000;
// ── 能力声明 ──────────────────────────────────────────────────────────────────
@@ -3563,6 +3570,14 @@ export class ClaudeCodeAgent extends BaseAgent {
*/
let stopTerminalEmittedGeneration: number | null = null;
let continuationCancellationRequiresQueryRebuild = false;
+ // Wake 契约对账定时器:见 WAKE_CONTRACT_GRACE_MS。claim 激活 / 取消 / 结算 /
+ // 丢弃 / query 换代时必须清掉,防止陈旧定时器误杀后继 claim。
+ let wakeContractReconcileTimer: NodeJS.Timeout | null = null;
+ const clearWakeContractReconciliation = (): void => {
+ if (!wakeContractReconcileTimer) return;
+ clearTimeout(wakeContractReconcileTimer);
+ wakeContractReconcileTimer = null;
+ };
const continuationClaims = new Map<number, ContinuationClaim>();
const continuationListeners = new Set<(
continuationId: number,
@@ -3600,6 +3615,7 @@ export class ClaudeCodeAgent extends BaseAgent {
claim.state = 'cancelled';
claim.settled = true;
activeContinuationId = null;
+ clearWakeContractReconciliation();
log.info('turn continuation cancelled', { reason, continuationId: claim.id });
emitContinuationState(claim.id, 'cancelled');
releaseSettledContinuationClaim(claim);
@@ -3610,6 +3626,7 @@ export class ClaudeCodeAgent extends BaseAgent {
if (!claim || claim.state !== 'active') return;
claim.settled = true;
activeContinuationId = null;
+ clearWakeContractReconciliation();
log.info('turn continuation settled without a follow-up turn', {
reason,
continuationId: claim.id,
@@ -3617,6 +3634,7 @@ export class ClaudeCodeAgent extends BaseAgent {
releaseSettledContinuationClaim(claim);
};
const discardActiveContinuation = (reason: string, forceRelease = false): void => {
+ clearWakeContractReconciliation();
if (continuationClaims.size > 0) {
log.debug('discarding turn continuation claims', {
reason,
@@ -3705,6 +3723,9 @@ export class ClaudeCodeAgent extends BaseAgent {
continuationClaims.set(claim.id, claim);
activeContinuationId = claim.id;
event.turnContinuationId = claim.id;
+ // 从 active 前任 carry 出来的 completed/failed 任务可能已全部终态 —— 下一
+ // 个 continuation 段同样受 wake 契约保护,创建即武装对账。
+ armWakeContractReconciliation(claim);
// 探针:claim 创建是「continuation 悬挂」vs「done 未到达」的关键区分点。
// 只记 id / taskId / state 枚举,不记消息文本与 task prompt(脱敏红线)。
log.info('turn continuation claim created', {
@@ -3723,6 +3744,9 @@ export class ClaudeCodeAgent extends BaseAgent {
const states = [...claim.tasks.values()];
// A completed/failed wake task still has the SDK continuation contract;
// only an all-stopped group proves that a second `done` cannot arrive.
+ // (All-terminal-but-not-stopped groups fall through here and rely on the
+ // timed WAKE_CONTRACT_GRACE_MS reconciliation above: no continuation
+ // activity within the grace window means the contract is broken.)
// Authority model: q.interrupt ACK is required when user Stop has no
// provider confirmation and must revoke a completed/failed continuation
// contract itself. An all-stopped snapshot is already provider-confirmed
@@ -3818,7 +3842,11 @@ export class ClaudeCodeAgent extends BaseAgent {
(prev?.wake || claim.tasks.has(taskId))
) {
claim.tasks.set(taskId, status);
- if (claim.state === 'awaiting') return reconcileActiveContinuation();
+ if (claim.state === 'awaiting') {
+ const cancelledClaim = reconcileActiveContinuation();
+ if (!cancelledClaim) armWakeContractReconciliation(claim);
+ return cancelledClaim;
+ }
}
}
return null;
@@ -3844,6 +3872,43 @@ export class ClaudeCodeAgent extends BaseAgent {
continuationCancellationRequiresQueryRebuild = true;
}
};
+ const claimTasksAllTerminal = (claim: ContinuationClaim): boolean => {
+ if (claim.tasks.size === 0) return false;
+ for (const state of claim.tasks.values()) {
+ if (state === 'running') return false;
+ }
+ return true;
+ };
+ /**
+ * Wake 契约对账:awaiting claim 的全部任务都到终态后,按 task_notification 续跑
+ * 契约顶层 continuation 段应随即开始。起表等待 WAKE_CONTRACT_GRACE_MS,期间
+ * claim 激活/结算/取消/换代都会清表;超时仍未激活即判定契约失守,走与用户 Stop
+ * 相同的取消路径(合成 turn_continuation_cancelled 终态 + cancelled-tail fence),
+ * 让宿主侧收口产品 turn,不再无限等待。
+ */
+ const armWakeContractReconciliation = (claim: ContinuationClaim): void => {
+ if (claim.state !== 'awaiting' || !claimTasksAllTerminal(claim)) return;
+ clearWakeContractReconciliation();
+ wakeContractReconcileTimer = setTimeout(() => {
+ wakeContractReconcileTimer = null;
+ const current = activeContinuationClaim();
+ if (
+ !current ||
+ current.id !== claim.id ||
+ current.state !== 'awaiting' ||
+ !claimTasksAllTerminal(current)
+ ) {
+ return;
+ }
+ log.info('wake contract unfulfilled: all wake tasks terminal without continuation activity', {
+ continuationId: current.id,
+ tasks: [...current.tasks.entries()],
+ });
+ cancelActiveContinuation('wake_contract_unfulfilled');
+ emitCancelledContinuationBoundary(current, 'wake_contract_unfulfilled');
+ }, WAKE_CONTRACT_GRACE_MS);
+ (wakeContractReconcileTimer as unknown as { unref?: () => void }).unref?.();
+ };
const releaseEventAccounting = (event: AgentEvent): void => {
if (event.turnContinuationId !== undefined) {
@@ -3882,6 +3947,7 @@ export class ClaudeCodeAgent extends BaseAgent {
continuationClaims.clear();
continuationListeners.clear();
pendingContinuationTerminalBoundaries = 0;
+ clearWakeContractReconciliation();
}
};
// 逐个发起 stopTask,但不在这里等待 RPC:interrupt 必须先按控制通道顺序发出。
@@ -4338,6 +4404,7 @@ export class ClaudeCodeAgent extends BaseAgent {
consumeTaskNotificationsForActiveSegment(claim);
claim.state = 'active';
emitContinuationState(claim.id, 'active');
+ clearWakeContractReconciliation();
}
log.debug('SDK ▶ turn activity without send — marking auto-continued turn in-flight', {
rawType,