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(desktop): drain queued input after a stale idle turn (#3240)

Chris Zhang3422f38e4a7c
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index df681cb199..354bde1ea4 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -61,6 +61,32 @@ describe('maker:event hot path ordering', () => {
expect(wireSessionSource).toContain('installInteractionLifecycleObserver(session, null);');
});
+ it('rejects a fenced leftover terminal before register-side turn effects', () => {
+ expect(source).toContain('delete rendererEvent.sessionTurnGeneration');
+ expect(source).toContain('delete rendererEvent.sessionInstanceId');
+ const wireSessionSource = extractWireSessionSource();
+ expectOrder(
+ wireSessionSource,
+ 'isFencedStaleSessionTerminal(session.id, event)',
+ 'ghostSessionTap.handleEvent(',
+ );
+ expectOrder(
+ wireSessionSource,
+ 'isFencedStaleSessionTerminal(session.id, event)',
+ 'consumeClaudeOpusPlanMismatch(',
+ );
+ expectOrder(
+ wireSessionSource,
+ 'isFencedStaleSessionTerminal(session.id, event)',
+ 'finalizeTurnChangeSet(',
+ );
+ expectOrder(
+ wireSessionSource,
+ 'isFencedStaleSessionTerminal(session.id, event)',
+ 'shouldMarkTurnStatusIdleAfterBroadcast = true',
+ );
+ });
+
it('broadcasts EVENT before usage/context/island/idle side effects', () => {
const wireSessionSource = extractWireSessionSource();
@@ -147,7 +173,7 @@ describe('maker:event hot path ordering', () => {
const observerHelperStart = source.indexOf('function notifyGoalIdleAfterTurnSettled(');
const observerHelperEnd = source.indexOf('\n}\n', observerHelperStart) + 2;
const observerHelperSource = source.slice(observerHelperStart, observerHelperEnd);
- const reconcileStart = source.indexOf('const reconcileSessionTurnIdle =');
+ const reconcileStart = source.indexOf('const sealLostTerminalPersistState =');
const reconcileEnd = source.indexOf('\n\n const readDirectAbortTurnId =', reconcileStart);
const reconcileSource = source.slice(reconcileStart, reconcileEnd);
const directAbortStart = source.indexOf('ipcMain.handle(MAKER_INVOKE.ABORT_SESSION');
@@ -170,21 +196,28 @@ describe('maker:event hot path ordering', () => {
expect(reconcileStart).toBeGreaterThanOrEqual(0);
expect(reconcileEnd).toBeGreaterThan(reconcileStart);
- expectOrder(
- reconcileSource,
+ const liveIdleStart = reconcileSource.indexOf(
'sessionTurnActivityTracker.setSessionInTurn(sessionId, false);',
- 'notifyGoalIdleAfterTurnSettled(sessionId);',
);
+ expect(liveIdleStart).toBeGreaterThanOrEqual(0);
+ expect(
+ reconcileSource.indexOf('notifyGoalIdleAfterTurnSettled(sessionId);', liveIdleStart),
+ ).toBeGreaterThan(liveIdleStart);
expectOrder(
reconcileSource,
- 'markTurnEndedAfterPersistDrain(sessionId);',
- 'clearCodexPlanRowsForSession(sessionId);',
+ 'flushAssistantBlock(sessionId, null);',
+ 'consumeLastAssistantPersistId(sessionId);',
);
expectOrder(
reconcileSource,
'clearCodexPlanRowsForSession(sessionId);',
'resetTurnPersistState(sessionId);',
);
+ expectOrder(
+ reconcileSource,
+ 'sealLostTerminalPersistState(sessionId);',
+ 'sessionTurnActivityTracker.deleteSession(sessionId);',
+ );
// ABORT_SESSION reconciles from finally, so vendor abort rejection still reaches the
// shared idle wake-up once the exact Session/generation boundary proves idle.
@@ -202,7 +235,12 @@ describe('maker:event hot path ordering', () => {
"return reconcileSessionTurnIdle(sessionId, 'authoritative-idle');",
);
expect(coordinatorSource).toContain('isLiveTurnRunning: (sessionId) =>');
- expect(coordinatorSource).toContain('if (!sess) return undefined;');
+ expect(coordinatorSource).toContain('isLiveSessionPresent: (sessionId) =>');
+ expect(source).toContain('lookupStableSessionForTurnBoundary');
+ expect(source).toContain("status: 'unavailable'");
+ expect(coordinatorSource).toContain("if (lookup.status === 'unavailable') return undefined;");
+ expect(coordinatorSource).toContain("if (lookup.status === 'missing') return false;");
+ expect(coordinatorSource).toContain("return lookup.status === 'found';");
});
it('does not latch product-turn bookkeeping on background status events', () => {
@@ -695,18 +733,25 @@ describe('maker:event hot path ordering', () => {
});
it('uses the wired Session snapshot while reconciling owner-boundary aborts', () => {
- const stableLookupStart = source.indexOf('const getStableSessionForTurnBoundary =');
- const stableLookupEnd = source.indexOf('\n const reconcileSessionTurnIdle =', stableLookupStart);
+ const stableLookupStart = source.indexOf('const lookupStableSessionForTurnBoundary =');
+ const stableLookupEnd = source.indexOf('\n const getStableSessionForTurnBoundary =', stableLookupStart);
const stableLookupSource = source.slice(stableLookupStart, stableLookupEnd);
- const reconcileStart = stableLookupEnd;
+ const reconcileStart = source.indexOf('const sealLostTerminalPersistState =');
const reconcileEnd = source.indexOf('\n\n const inputCoordinator:', reconcileStart);
const reconcileSource = source.slice(reconcileStart, reconcileEnd);
expect(stableLookupStart).toBeGreaterThanOrEqual(0);
expect(stableLookupEnd).toBeGreaterThan(stableLookupStart);
expect(stableLookupSource).toContain('wiredSessionsById.get(sessionId)?.session');
- expectOrder(stableLookupSource, 'if (wired) return wired;', 'return maker.getSession(sessionId) ?? null;');
- expect(stableLookupSource).toContain('return null;');
+ expectOrder(
+ stableLookupSource,
+ 'if (wired) return { status: \'found\', session: wired };',
+ 'return sess ? { status: \'found\', session: sess } : { status: \'missing\' };',
+ );
+ expect(stableLookupSource).toContain("return { status: 'unavailable' };");
+ expect(source).toContain(
+ "return lookup.status === 'found' ? lookup.session : null;",
+ );
expect(reconcileStart).toBeGreaterThanOrEqual(0);
expect(reconcileEnd).toBeGreaterThan(reconcileStart);
@@ -716,8 +761,8 @@ describe('maker:event hot path ordering', () => {
expectOrder(reconcileSource, 'flushAssistantBlock(sessionId, null);', 'consumeLastAssistantPersistId(sessionId);');
expectOrder(reconcileSource, 'consumeLastAssistantPersistId(sessionId);', 'consumeLastTopLevelAssistantPersistId(sessionId);');
expectOrder(reconcileSource, 'consumeLastTopLevelAssistantPersistId(sessionId);', 'markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId)');
- expectOrder(reconcileSource, 'markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId)', 'markTurnEndedAfterPersistDrain(sessionId);');
- expectOrder(reconcileSource, 'markTurnEndedAfterPersistDrain(sessionId);', 'resetTurnPersistState(sessionId);');
+ expectOrder(reconcileSource, 'sealLostTerminalPersistState(sessionId);', 'sessionTurnActivityTracker.deleteSession(sessionId);');
+ expectOrder(reconcileSource, 'clearCodexPlanRowsForSession(sessionId);', 'resetTurnPersistState(sessionId);');
});
it('keeps direct abort reconciliation fail-closed across owner replacement and new turns', () => {
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 7a59f7d3bb..db300790e4 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -2202,6 +2202,40 @@ describe('consumeLastAssistantPersistId(per-turn 费用挂载的目标消息追
expect(consumeLastAssistantPersistId(SESSION)).toBeUndefined();
});
+ it('missing-session lost-terminal seal does not concatenate the next turn onto leftover stream text', async () => {
+ const deadId = onAssistantTextEvent(
+ SESSION,
+ { text: 'dead-turn-fragment', isFinal: false },
+ null,
+ );
+ expect(deadId).toEqual(expect.any(String));
+
+ // Same persist boundary as reconcileSessionTurnIdle's missing lookup.
+ flushAssistantBlock(SESSION, null);
+ consumeLastAssistantPersistId(SESSION);
+ consumeLastTopLevelAssistantPersistId(SESSION);
+ resetTurnPersistState(SESSION);
+
+ const nextId = onAssistantTextEvent(
+ SESSION,
+ { text: 'next-turn-only', isFinal: false },
+ null,
+ );
+ expect(nextId).not.toBe(deadId);
+ flushAssistantBlock(SESSION, null);
+ await flushWrites();
+
+ const assistantCreates = (createMessage as unknown as { mock: { calls: unknown[][] } }).mock.calls
+ .filter((c) => (c[1] as { role?: string }).role === 'assistant');
+ expect(assistantCreates).toHaveLength(2);
+ expect(assistantCreates[0]?.[1]).toEqual(
+ expect.objectContaining({ clientId: deadId, content: 'dead-turn-fragment' }),
+ );
+ expect(assistantCreates[1]?.[1]).toEqual(
+ expect.objectContaining({ clientId: nextId, content: 'next-turn-only' }),
+ );
+ });
+
it('clearSessionPersistState 清理追踪(session 关闭防泄漏)', () => {
onAssistantTextEvent(SESSION, { text: 'gone', isFinal: true }, null);
clearSessionPersistState(SESSION);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index d280071b49..c539e0ce69 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -171,8 +171,9 @@ function createHarness(opts?: {
}) {
let running = false;
let liveRunningOverride: boolean | null | 'unknown' = null;
+ let liveSessionPresentOverride: boolean | null | 'unknown' = null;
let turnGeneration = 0;
- let turnSessionIdentity: object = {};
+ let turnSessionIdentity: object = { instanceId: 'harness-session' };
let pendingInteraction = false;
let agentKind: AgentInputCreateOpts['agentKind'] | null = 'claude-code';
const projections: AgentInputProjection[] = [];
@@ -299,6 +300,12 @@ function createHarness(opts?: {
if (liveRunningOverride === 'unknown') return undefined;
return liveRunningOverride === null ? running : liveRunningOverride;
},
+ isLiveSessionPresent: () => {
+ if (liveSessionPresentOverride === 'unknown') return undefined;
+ if (liveSessionPresentOverride !== null) return liveSessionPresentOverride;
+ if (liveRunningOverride === 'unknown') return undefined;
+ return true;
+ },
getTurnGeneration: () => turnGeneration,
getTurnSessionIdentity: () => turnSessionIdentity,
reconcileTurnIdle,
@@ -380,6 +387,9 @@ function createHarness(opts?: {
setLiveRunning(value: boolean | null | 'unknown') {
liveRunningOverride = value;
},
+ setLiveSessionPresent(value: boolean | null | 'unknown') {
+ liveSessionPresentOverride = value;
+ },
setTurnGeneration(value: number) {
turnGeneration = value;
},
@@ -6117,12 +6127,18 @@ describe('AgentInputCoordinator steer transaction', () => {
await flush();
expect(h.sendToAgent).toHaveBeenCalledTimes(1);
- h.setLiveRunning(false);
+ // Session.send reservation keeps live busy before agent_start.
+ h.setLiveRunning(true);
h.setRunning(true);
h.coordinator.enqueue(sid, second);
await flush();
await vi.advanceTimersByTimeAsync(250);
await flush();
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ await flush();
expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
expect(h.sendToAgent).toHaveBeenCalledTimes(1);
@@ -6195,6 +6211,342 @@ describe('AgentInputCoordinator steer transaction', () => {
expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-1']);
});
+ it('does not reclaim leftover activeTurn in the post-send agent_start gap', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-agent-start-gap';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'queued-after-idle');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ // sendReservation already released, handle not streaming yet, tracker idle.
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(false);
+ h.coordinator.enqueue(sid, second);
+ await flush();
+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ await flush();
+
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reclaims a dispatched leftover activeTurn when the live Session is idle but tracker stays busy', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-lost-terminal-live-idle';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'queued-after-idle');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(true);
+ h.reconcileTurnIdle.mockImplementation(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.enqueue(sid, second);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: 'queued-after-idle',
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not reclaim leftover activeTurn when idle reconcile fails', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-reconcile-fail-keeps-boundary';
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(true);
+ h.reconcileTurnIdle.mockImplementation(() => false);
+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-idle'));
+ await flush();
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('ignores a late terminal from a reclaimed leftover turn after the next turn starts', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-fence-late-terminal';
+ h.setTurnGeneration(4);
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(true);
+ h.reconcileTurnIdle.mockImplementation(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.enqueue(sid, makeItem('q-2', 'second'));
+ await flush();
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ expect(
+ h.coordinator.isFencedStaleTerminal(sid, {
+ sessionTurnGeneration: 0,
+ sessionInstanceId: 'harness-session',
+ }),
+ ).toBe(true);
+ expect(
+ h.coordinator.isFencedStaleTerminal(sid, {
+ sessionTurnGeneration: 5,
+ sessionInstanceId: 'harness-session',
+ }),
+ ).toBe(false);
+ h.coordinator.onTurnEvent(sid, 'error', 'old turn died late', undefined, {
+ sessionTurnGeneration: 0,
+ sessionInstanceId: 'harness-session',
+ });
+ await flush();
+ expect(latestProjection(h.projections).error).toBeNull();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {
+ sessionTurnGeneration: 4,
+ sessionInstanceId: 'harness-session',
+ });
+ await flush();
+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the leftover terminal fence across clearSession', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-fence-survives-clear';
+ h.setTurnGeneration(4);
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(true);
+ h.reconcileTurnIdle.mockImplementation(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.enqueue(sid, makeItem('q-2', 'second'));
+ await flush();
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.coordinator.clearSession(sid);
+ expect(
+ h.coordinator.isFencedStaleTerminal(sid, {
+ sessionTurnGeneration: 4,
+ sessionInstanceId: 'harness-session',
+ }),
+ ).toBe(true);
+
+ h.setRunning(false);
+ h.setLiveRunning(false);
+ h.coordinator.enqueue(sid, makeItem('q-3', 'after-clear'));
+ await flush();
+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {
+ sessionTurnGeneration: 4,
+ sessionInstanceId: 'harness-session',
+ });
+ await flush();
+ expect(latestProjection(h.projections).error).toBeNull();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not fence a replacement Session terminal that reuses the same generation number', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-fence-session-identity';
+ h.setTurnGeneration(1);
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));
+ await flush();
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(true);
+ h.setRunning(true);
+ h.reconcileTurnIdle.mockImplementation(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.enqueue(sid, makeItem('q-2', 'second'));
+ await flush();
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.setTurnSessionIdentity({ instanceId: 'replacement-session' });
+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {
+ sessionTurnGeneration: 1,
+ sessionInstanceId: 'replacement-session',
+ });
+ h.setRunning(false);
+ await flush();
+ h.coordinator.enqueue(sid, makeItem('q-3', 'third'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(3);
+ expect(h.sendToAgent.mock.calls[2]?.[1]).toEqual({
+ type: 'user',
+ content: 'third',
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not timeout-clear a pre-dispatch activeTurn even after the Session unloads', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-pre-dispatch-active-turn';
+ let finishFirst: ((value: AgentInputSendResult) => void) | undefined;
+ h.sendToAgent.mockImplementationOnce(
+ () =>
+ new Promise<AgentInputSendResult>((resolve) => {
+ finishFirst = resolve;
+ }),
+ );
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(false);
+ h.setRunning(false);
+ h.coordinator.enqueue(sid, makeItem('q-2', 'second'));
+ await flush();
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
+
+ finishFirst?.(sendSuccess());
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reclaims a dispatched leftover activeTurn only after the Session is gone', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-unloaded-active-turn';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'queued-after-unload');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ h.setLiveRunning(false);
+ h.setLiveSessionPresent(false);
+ h.setRunning(false);
+ h.reconcileTurnIdle.mockReturnValue(true);
+ h.coordinator.enqueue(sid, second);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: 'queued-after-unload',
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reconciles a stale tracker after the live Session process is gone', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'drain-unloaded-tracker';
+ h.setRunning(true);
+ h.setLiveRunning(false);
+ h.reconcileTurnIdle.mockImplementation(() => {
+ h.setRunning(false);
+ return true;
+ });
+
+ h.coordinator.enqueue(sid, makeItem('q-1', 'queued-after-unload'));
+ await flush();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('recovers from a zombie turn: NO_ACTIVE_TURN reconciles stale busy state and dispatches the fallback', async () => {
// 场景: q-1 已派发但 turn 异常死亡 (done 事件丢失) —— coordinator 的
// activeTurn 和 host busy tracker 双双 stale。修复前: 插话 → fallback →
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 14e9804870..622649fd97 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -270,6 +270,12 @@ export interface AgentInputCoordinatorDeps {
isTurnRunning: (sessionId: string) => boolean;
/** Live Session only — must not OR the desktop tracker. undefined = probe unavailable. */
isLiveTurnRunning?: (sessionId: string) => boolean | undefined;
+ /**
+ * Whether a live Session object exists. Distinct from isLiveTurnRunning:
+ * found+idle is present=true/running=false; process gone is present=false;
+ * owner-boundary lookup failure is undefined and must stay fail-closed.
+ */
+ isLiveSessionPresent?: (sessionId: string) => boolean | undefined;
/** maker-core turn 代号;steer 跨 await 后据此验证仍属于开始时的同一 vendor turn。 */
getTurnGeneration?: (sessionId: string) => number | null;
/** maker-core Session object identity; control-plane steer uses it to reject session reuse. */
@@ -637,6 +643,8 @@ interface SessionInputState {
* flips idle; reconcile only after SESSION_RUNNING_RETRY_DELAY_MS.
*/
staleLiveIdleSinceMs: number | null;
+ /** Leftover terminal fence: Session incarnation + the generation that was reclaimed. */
+ fencedStaleTerminal: { instanceId: string; generation: number } | null;
/**
* 发送撞上 CREDENTIAL_SWITCH_BUSY 后的可见等待态:队首保留,挡路会话 turn 结束
* (onExternalTurnSettled)或兜底定时器触发自动重发。clientId 绑定等待中的那条
@@ -669,6 +677,7 @@ interface PendingAutoResumeRecovery {
function createInitialInputState(
generation = 0,
clearBoundaryMs: number | null = null,
+ fencedStaleTerminal: { instanceId: string; generation: number } | null = null,
): SessionInputState {
return {
pendingQueue: [],
@@ -701,6 +710,7 @@ function createInitialInputState(
sessionRunningRetryDelayMs: null,
sessionRunningRetryToken: null,
staleLiveIdleSinceMs: null,
+ fencedStaleTerminal,
credentialSwitchWait: null,
credentialSwitchRetryTimer: null,
credentialSwitchRetryGeneration: null,
@@ -709,6 +719,25 @@ function createInitialInputState(
clearBoundaryMs,
};
}
+
+function readSessionInstanceId(identity: object | null | undefined): string | null {
+ if (!identity || typeof identity !== 'object') return null;
+ const id = (identity as { instanceId?: unknown }).instanceId;
+ return typeof id === 'string' && id.length > 0 ? id : null;
+}
+
+export function isMatchingFencedStaleTerminal(
+ fence: { instanceId: string; generation: number } | null | undefined,
+ meta?: { sessionTurnGeneration?: number; sessionInstanceId?: string },
+): boolean {
+ if (!fence) return false;
+ return (
+ typeof meta?.sessionTurnGeneration === 'number' &&
+ typeof meta.sessionInstanceId === 'string' &&
+ meta.sessionInstanceId === fence.instanceId &&
+ meta.sessionTurnGeneration <= fence.generation
+ );
+}
/**
* 首次进入 main 队列边界时冻结原始合成指令意图。IPC payload 属不可信输入,
* 因此即使 renderer 带了同名字段也必须从当下原始 text 重新计算。
@@ -2936,7 +2965,10 @@ export class AgentInputCoordinator {
// 显式清上下文:强制开启持久化闸门,让 emit 写出空快照(删行),
// 即使此前该会话从未触发恢复(否则旧快照残留,下次打开会诈尸)。
this.restoredQueueSessions.add(sessionId);
- this.states.set(sessionId, createInitialInputState(prev.generation + 1, clearBoundaryMs));
+ this.states.set(
+ sessionId,
+ createInitialInputState(prev.generation + 1, clearBoundaryMs, prev.fencedStaleTerminal),
+ );
this.emit(sessionId);
return this.getProjection(sessionId);
}
@@ -2947,13 +2979,30 @@ export class AgentInputCoordinator {
* coordinator 里做那个判断——它是「这条错误是什么」的领域知识,属于 host 侧的
* interruptedTurnAutoResume;coordinator 只负责回答「有没有可续跑的目标」。
*/
+ isFencedStaleTerminal(
+ sessionId: string,
+ meta?: { sessionTurnGeneration?: number; sessionInstanceId?: string },
+ ): boolean {
+ return isMatchingFencedStaleTerminal(this.getState(sessionId).fencedStaleTerminal, meta);
+ }
+
onTurnEvent(
sessionId: string,
type: 'done' | 'error',
message?: string,
signals?: Omit<InterruptedTurnErrorSignals, 'message'>,
+ meta?: { sessionTurnGeneration?: number; sessionInstanceId?: string },
): void {
const state = this.getState(sessionId);
+ if (this.isFencedStaleTerminal(sessionId, meta)) {
+ log.debug('ignored stale terminal after leftover turn reclaim', {
+ sessionId,
+ type,
+ eventGeneration: meta?.sessionTurnGeneration ?? null,
+ sessionInstanceId: meta?.sessionInstanceId ?? null,
+ });
+ return;
+ }
const active = state.activeTurn;
state.staleLiveIdleSinceMs = null;
this.clearAbortReconcileRetry(state);
@@ -3416,12 +3465,26 @@ export class AgentInputCoordinator {
/**
* Live Session idle + host tracker still busy is an invariant break.
- * Reconcile the tracker so queued input can drain without a user Stop / steer.
- * Do not call this while a send is in flight, an activeTurn still owns the
- * generation, a permission card is up, or abort/steer already owns the boundary.
- * Dispatched-but-not-started turns (Pi may accept a prompt before agent_start)
- * must wait for real lifecycle events — do not synthesize done.
+ * Reconcile so queued input can drain without Stop / steer.
+ * Do not call this while a send is in flight, a permission card is up, or
+ * abort/steer already owns the boundary.
+ *
+ * Leftover `activeTurn` is reclaimed only when it is already dispatched and
+ * we can prove the vendor turn is gone: the Session object is missing, or the
+ * live Session is idle while the desktop tracker is still latched. A present
+ * Session with an idle tracker may still be in the Pi gap after handle.send
+ * (reservation released, agent_start not yet observed). Pre-dispatch owners
+ * and unavailable probes stay fail-closed.
*/
+ private canReclaimLeftoverActiveTurn(sessionId: string, state: SessionInputState): boolean {
+ const active = state.activeTurn;
+ if (!active || !isActiveTurnDispatched(active)) return false;
+ const present = this.deps.isLiveSessionPresent?.(sessionId);
+ if (present === false) return true;
+ if (present !== true) return false;
+ return this.deps.isTurnRunning(sessionId) === true;
+ }
+
private tryReconcileStaleDispatchBoundary(
sessionId: string,
state: SessionInputState,
@@ -3432,8 +3495,7 @@ export class AgentInputCoordinator {
state.queueInteractionLocks.length > 0 ||
state.steeringQueueClientIds.length > 0 ||
state.pendingExternalTerminalDone ||
- this.deps.hasPendingInteraction(sessionId) ||
- state.activeTurn !== null
+ this.deps.hasPendingInteraction(sessionId)
) {
state.staleLiveIdleSinceMs = null;
return false;
@@ -3444,13 +3506,19 @@ export class AgentInputCoordinator {
return false;
}
- if (!this.deps.isTurnRunning(sessionId)) {
+ const leftoverActiveTurn = state.activeTurn !== null;
+ const trackerBusy = this.deps.isTurnRunning(sessionId);
+ const reclaimLeftover = leftoverActiveTurn && this.canReclaimLeftoverActiveTurn(sessionId, state);
+ if (leftoverActiveTurn && !reclaimLeftover) {
+ state.staleLiveIdleSinceMs = null;
+ return false;
+ }
+ if (!trackerBusy && !reclaimLeftover) {
state.staleLiveIdleSinceMs = null;
return false;
}
// Handle may already be idle while status/done is still queued in Session.
- // Extra drains in this window must not confirm; wait the existing 250ms retry.
if (state.staleLiveIdleSinceMs == null) {
state.staleLiveIdleSinceMs = Date.now();
}
@@ -3458,8 +3526,24 @@ export class AgentInputCoordinator {
return false;
}
- const reconciled = this.deps.reconcileTurnIdle?.(sessionId) === true;
- if (!reconciled) return false;
+ if (trackerBusy || reclaimLeftover) {
+ const reconciled = this.deps.reconcileTurnIdle?.(sessionId) === true;
+ if (!reconciled) return false;
+ }
+ if (reclaimLeftover) {
+ const vendorGeneration = this.deps.getTurnGeneration?.(sessionId);
+ const instanceId = readSessionInstanceId(this.deps.getTurnSessionIdentity?.(sessionId));
+ if (typeof vendorGeneration === 'number' && instanceId) {
+ state.fencedStaleTerminal = { instanceId, generation: vendorGeneration };
+ }
+ log.warn('reconciling leftover dispatched activeTurn after vendor idle', {
+ sessionId,
+ clientId: state.activeTurn?.item?.clientId ?? null,
+ dispatchLifecycle: state.activeTurn?.dispatchLifecycle ?? null,
+ fencedStaleTerminal: state.fencedStaleTerminal,
+ });
+ state.activeTurn = null;
+ }
state.staleLiveIdleSinceMs = null;
return true;
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 7c481f1f3f..84859bf1af 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3665,6 +3665,30 @@ async function handleSilentStopTurnEnd(
}
}
+function isFencedStaleProductTerminal(event: AgentEvent): boolean {
+ if (event.type === 'done') return true;
+ if (isTerminalTurnErrorEvent(event)) return true;
+ if (event.type !== 'status') return false;
+ const data = event.data as { isRunning?: unknown } | null | undefined;
+ return data?.isRunning === false;
+}
+
+function isFencedStaleSessionTerminal(
+ sessionId: string,
+ event: AgentEvent,
+): boolean {
+ if (isTurnContinuationBoundaryEvent(event) || event.turnScope === 'background') {
+ return false;
+ }
+ return (
+ isFencedStaleProductTerminal(event) &&
+ agentInputCoordinatorHolder?.isFencedStaleTerminal(sessionId, {
+ sessionTurnGeneration: event.sessionTurnGeneration,
+ sessionInstanceId: event.sessionInstanceId,
+ }) === true
+ );
+}
+
export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void {
if (!session) return;
const existing = wiredSessionsById.get(session.id);
@@ -3746,6 +3770,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
registration.disposers.push(
session.onEvent((event: AgentEvent) => {
+ if (isFencedStaleSessionTerminal(session.id, event)) return;
noteTurnDiffEvent(session.id, event, session.remoteHostId !== null);
ghostSessionTap.handleEvent(
event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },
@@ -3768,6 +3793,15 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
) {
return;
}
+ if (isFencedStaleSessionTerminal(session.id, event)) {
+ log.debug('ignored stale terminal after leftover turn reclaim', {
+ sessionId: session.id,
+ eventType: event.type,
+ sessionTurnGeneration: event.sessionTurnGeneration ?? null,
+ sessionInstanceId: event.sessionInstanceId ?? null,
+ });
+ return;
+ }
// 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的
// terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token
// 盖到事件上,首个匹配 token 的事件即视为 provider accepted。
@@ -3977,7 +4011,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 兜底: 有些 vendor 的 done 不必先发 status:isRunning=false。
// 但 idle 恢复不能挡在 EVENT broadcast 前,否则隐藏窗口可能在 done
// 还没进入 renderer 时就重新被 Chromium 节流。
- agentInputCoordinatorHolder?.onTurnEvent(session.id, 'done');
+ agentInputCoordinatorHolder?.onTurnEvent(session.id, 'done', undefined, undefined, {
+ sessionTurnGeneration: event.sessionTurnGeneration,
+ sessionInstanceId: event.sessionInstanceId,
+ });
} else {
// silent-stop 自动续跑:translator 判定本 turn 被上游空内容消息静默收尾时在
// done.data 附加 silentStop 标记(见 maker-core translator)。延迟一拍再决策,
@@ -4061,6 +4098,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
? { errorStatus: errData.errorStatus }
: {}),
},
+ {
+ sessionTurnGeneration: event.sessionTurnGeneration,
+ sessionInstanceId: event.sessionInstanceId,
+ },
);
}
}
@@ -11487,24 +11528,34 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
* whether work is still running; the desktop tracker is only an event-driven
* view and can remain stale across owner-boundary teardown.
*/
- const getStableSessionForTurnBoundary = (sessionId: string): WiredSession | null => {
+ type StableSessionLookup =
+ | { status: 'found'; session: WiredSession }
+ | { status: 'missing' }
+ | { status: 'unavailable' };
+
+ const lookupStableSessionForTurnBoundary = (sessionId: string): StableSessionLookup => {
const wired = wiredSessionsById.get(sessionId)?.session;
- if (wired) return wired;
+ if (wired) return { status: 'found', session: wired };
try {
- return maker.getSession(sessionId) ?? null;
+ const sess = maker.getSession(sessionId);
+ return sess ? { status: 'found', session: sess } : { status: 'missing' };
} catch (err) {
- // Dynamic Maker intentionally fails closed while an account owner is
- // being replaced. A missing stable wiring snapshot means we cannot
- // authoritatively reconcile this session yet; callers must retain their
- // boundary and wait for the normal close/settle path.
+ // Dynamic Maker throws PRECONDITION_FAILED while an account owner is
+ // being replaced. Callers that need fail-closed must not treat this as
+ // "session process gone".
log.warn('session lookup unavailable during turn-boundary reconciliation', {
sessionId,
error: err instanceof Error ? err.message : String(err),
});
- return null;
+ return { status: 'unavailable' };
}
};
+ const getStableSessionForTurnBoundary = (sessionId: string): WiredSession | null => {
+ const lookup = lookupStableSessionForTurnBoundary(sessionId);
+ return lookup.status === 'found' ? lookup.session : null;
+ };
+
/**
* Finalize an exact retry owner that never crossed vendor dispatch.
* Technical failure surfaces the suppressed error; explicit cancellation
@@ -11527,9 +11578,57 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return true;
};
+ const sealLostTerminalPersistState = (sessionId: string): void => {
+ // Same persist boundary as a lost-terminal live-idle reconcile. The next
+ // turn on this sessionId must not append to a half-open streaming block.
+ flushAssistantBlock(sessionId, null);
+ const abortedAssistantPersistId = consumeLastAssistantPersistId(sessionId);
+ const abortedBoundaryAssistantPersistId = consumeLastTopLevelAssistantPersistId(sessionId);
+ flushOrphanToolResults(sessionId, null);
+ if (abortedAssistantPersistId) {
+ pendingFailedTurnAssistantPersistId.set(sessionId, abortedAssistantPersistId);
+ }
+ if (abortedBoundaryAssistantPersistId) {
+ void markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId);
+ }
+ clearCodexPlanRowsForSession(sessionId);
+ resetTurnPersistState(sessionId);
+ };
+
const reconcileSessionTurnIdle = (sessionId: string, source: string): boolean => {
- const sess = getStableSessionForTurnBoundary(sessionId);
- if (!sess) return false;
+ const lookup = lookupStableSessionForTurnBoundary(sessionId);
+ if (lookup.status === 'unavailable') return false;
+ if (lookup.status === 'missing') {
+ const trackerStale =
+ sessionTurnActivityTracker.isSessionInTurn(sessionId) ||
+ sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);
+ sealLostTerminalPersistState(sessionId);
+ if (trackerStale) {
+ log.warn('reconciling stale session turn boundary after session unload', {
+ sessionId,
+ source,
+ });
+ }
+ sessionTurnActivityTracker.deleteSession(sessionId);
+ void sessionTurnLeaseTracker.markTurnEnded(sessionId);
+ notifyGoalIdleAfterTurnSettled(sessionId);
+ try {
+ markTurnEndedAfterPersistDrain(sessionId);
+ noteClaudeSessionTurnState(sessionId, false);
+ settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);
+ deferredCodexRestartHolder?.onSessionSettled();
+ agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);
+ } catch (err) {
+ log.warn('stale session turn side-effect cleanup failed', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ return true;
+ }
+ const sess = lookup.session;
let liveSessionIdle = false;
try {
liveSessionIdle = !sess.isTurnRunning();
@@ -11543,20 +11642,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
if (!liveSessionIdle) return false;
// The vendor is authoritative that this turn is over, but no terminal event
- // reached the host. Flush and fail-seal the latest top-level Assistant before
- // releasing the boundary; otherwise its last progress line is later treated
- // as a legacy final answer by title regeneration. Preserve the last Assistant
- // id for a rare late paired done so usage attribution still has a target.
- flushAssistantBlock(sessionId, null);
- const abortedAssistantPersistId = consumeLastAssistantPersistId(sessionId);
- const abortedBoundaryAssistantPersistId = consumeLastTopLevelAssistantPersistId(sessionId);
- flushOrphanToolResults(sessionId, null);
- if (abortedAssistantPersistId) {
- pendingFailedTurnAssistantPersistId.set(sessionId, abortedAssistantPersistId);
- }
- if (abortedBoundaryAssistantPersistId) {
- void markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId);
- }
+ // reached the host. Seal persist state before releasing the boundary;
+ // otherwise its last progress line is later treated as a legacy final
+ // answer by title regeneration.
+ sealLostTerminalPersistState(sessionId);
const trackerStale =
sessionTurnActivityTracker.isSessionInTurn(sessionId) ||
sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);
@@ -11588,11 +11677,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// The marker write is best-effort and ordered behind pending message
// persistence. It may retry/settle after an owner boundary is available.
markTurnEndedAfterPersistDrain(sessionId);
- // This is a logical turn boundary even though the vendor terminal event
- // was lost. Drop the cross-segment plan ownership here so a later turn's
- // id-less terminal error cannot fail-stamp an older plan.
- clearCodexPlanRowsForSession(sessionId);
- resetTurnPersistState(sessionId);
noteClaudeSessionTurnState(sessionId, false);
settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);
deferredCodexRestartHolder?.onSessionSettled();
@@ -12032,14 +12116,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return isSessionTurnDispatchBoundaryBusy(sessionTurnActivityTracker, sessionId, sess);
},
isLiveTurnRunning: (sessionId) => {
+ const lookup = lookupStableSessionForTurnBoundary(sessionId);
+ if (lookup.status === 'unavailable') return undefined;
+ if (lookup.status === 'missing') return false;
try {
- const sess = getStableSessionForTurnBoundary(sessionId);
- if (!sess) return undefined;
- return sess.isTurnRunning();
+ return lookup.session.isTurnRunning();
} catch {
return undefined;
}
},
+ isLiveSessionPresent: (sessionId) => {
+ const lookup = lookupStableSessionForTurnBoundary(sessionId);
+ if (lookup.status === 'unavailable') return undefined;
+ return lookup.status === 'found';
+ },
getTurnGeneration: (sessionId) =>
getStableSessionForTurnBoundary(sessionId)?.getTurnGeneration() ?? null,
getTurnSessionIdentity: (sessionId) => getStableSessionForTurnBoundary(sessionId) ?? null,
@@ -15217,6 +15307,8 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {
const rendererEvent = { ...event };
delete rendererEvent.turnAttemptToken;
delete rendererEvent.backgroundTurnStartedAt;
+ delete rendererEvent.sessionTurnGeneration;
+ delete rendererEvent.sessionInstanceId;
if (!event.data || typeof event.data !== 'object') return rendererEvent;
const data = event.data as Record<string, unknown>;
diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.ts
index 8abd14a9a6..6d0217796a 100644
--- a/packages/maker-core/src/session.origin.test.ts
+++ b/packages/maker-core/src/session.origin.test.ts
@@ -355,12 +355,348 @@ describe('Session per-turn origin 打标', () => {
type: 'error',
turnOrigin: SCHED_ORIGIN,
turnAttemptToken: 9,
+ sessionTurnGeneration: 1,
+ sessionInstanceId: session.instanceId,
}));
releaseDispatch();
await send;
await session.close();
});
+ it('prior-turn next() still stamps an in-flight Codex start-failure as the new generation', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ dispatchEvent: {
+ type: 'error',
+ data: { message: 'second failed', isTerminal: true },
+ source: 'codex',
+ },
+ dispatchOnSend: 2,
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const startFail = seen.find((event) =>
+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');
+ expect(startFail?.sessionTurnGeneration).toBe(2);
+ expect(startFail?.sessionInstanceId).toBe(session.instanceId);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('keeps a leftover terminal on queued generation after handle.send yields', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });
+ await emit({ type: 'done', data: {}, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+
+ expect(seen.some((event) => event.type === 'status' || event.type === 'done')).toBe(false);
+ const secondText = seen.find((event) => event.type === 'text' && (event.data as { text?: string }).text === 'second progress');
+ expect(secondText?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('keeps leftover done on the prior generation after a new-turn running status', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: true }, source: 'codex' });
+ await emit({ type: 'done', data: { reason: 'old-tail' }, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+
+ expect(seen.some((event) => event.type === 'done')).toBe(false);
+ expect(seen.find((event) => event.type === 'text' && (event.data as { text?: string }).text === 'second progress')?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('does not stamp a zero-output done as leftover after a completed prior turn', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ await emit({ type: 'done', data: {}, source: 'codex' });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: true }, source: 'codex' });
+ await emit({ type: 'done', data: {}, source: 'codex' });
+
+ const dones = seen.filter((event) => event.type === 'done');
+ expect(dones[0]?.sessionTurnGeneration).toBe(1);
+ expect(dones[1]?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('stamps a silent-stop done as the new generation even without progress tokens', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: true }, source: 'claude-code' });
+ await emit({ type: 'done', data: { silentStop: true }, source: 'claude-code' });
+
+ const silentStop = seen.find((event) => event.type === 'done');
+ expect(silentStop?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('keeps a leftover terminal error on the prior generation after leftover idle', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });
+ await emit({
+ type: 'error',
+ data: { message: 'first late failure', isTerminal: true },
+ source: 'codex',
+ });
+
+ expect(seen.some((event) =>
+ event.type === 'error' && (event.data as { message?: string }).message === 'first late failure')).toBe(false);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('stamps an immediate new-turn 401 after running as the live generation', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: true }, source: 'codex' });
+ await emit({
+ type: 'error',
+ data: { message: 'quota exceeded', isTerminal: true },
+ source: 'codex',
+ });
+
+ const fail = seen.find((event) =>
+ event.type === 'error' && (event.data as { message?: string }).message === 'quota exceeded');
+ expect(fail?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('does not let a leftover terminal clear the live turn origin', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second', { origin: SCHED_ORIGIN });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: true }, source: 'codex' });
+ await emit({ type: 'done', data: { reason: 'old-tail' }, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+
+ expect(seen.some((event) => event.type === 'done')).toBe(false);
+ const secondText = seen.find((event) =>
+ event.type === 'text' && (event.data as { text?: string }).text === 'second progress');
+ expect(secondText?.sessionTurnGeneration).toBe(2);
+ expect(secondText?.turnOrigin).toEqual(SCHED_ORIGIN);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('does not let a leftover idle-only tail claim the new turn done after tokens', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+ await emit({ type: 'done', data: { reason: 'new-turn' }, source: 'codex' });
+
+ const done = seen.find((event) => event.type === 'done');
+ expect(done?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('does not treat a background tool result as new-turn progress', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });
+ await emit({
+ type: 'tool_result_full',
+ data: { toolUseId: 'collab-1', result: 'old collab' },
+ source: 'codex',
+ turnScope: 'background',
+ });
+ await emit({ type: 'done', data: { reason: 'old-tail' }, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+
+ expect(seen.some((event) => event.type === 'done')).toBe(false);
+ expect(seen.find((event) => event.type === 'text' && (event.data as { text?: string }).text === 'second progress')?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('keeps leftover done on the unresolved generation after a cancelled reservation', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const controller = new AbortController();
+ await expect(session.send('cancelled', {
+ signal: controller.signal,
+ afterTurnReserved: () => controller.abort(),
+ })).resolves.toEqual({
+ accepted: false,
+ reason: 'cancelled-before-dispatch',
+ });
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'done', data: { reason: 'old-tail' }, source: 'codex' });
+ await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });
+
+ expect(seen.some((event) => event.type === 'done')).toBe(false);
+ expect(seen.find((event) => event.type === 'text' && (event.data as { text?: string }).text === 'second progress')?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
+ it('treats a standalone image as new-turn progress before leftover done', async () => {
+ const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });
+ await emit({
+ type: 'image',
+ data: { kind: 'imageGeneration', result: 'data:image/png;base64,xx' },
+ source: 'codex',
+ });
+ await emit({ type: 'done', data: { reason: 'new-turn' }, source: 'codex' });
+
+ const done = seen.find((event) => event.type === 'done');
+ expect(done?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
it('排队中的旧 Codex terminal error 不能冒领随后 dispatch 的 attempt token', async () => {
const { handle, emit, queue, setTurnRunning, releaseDispatch } = createControllableHandle({
dispatchEvent: {
@@ -399,6 +735,34 @@ describe('Session per-turn origin 打标', () => {
await session.close();
});
+ it('clears leftover prior after an in-flight terminal so the live done can settle', async () => {
+ const { handle, emit, queue, setTurnRunning, releaseDispatch } = createControllableHandle({
+ holdDispatch: true,
+ holdOnSend: 2,
+ });
+ const session = makeSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push({ ...event }));
+
+ await session.send('first');
+ await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });
+ setTurnRunning(false);
+ queue({
+ type: 'error',
+ data: { message: 'first late failure', isTerminal: true },
+ source: 'codex',
+ });
+ const second = session.send('second');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await emit({ type: 'done', data: { reason: 'new-turn' }, source: 'codex' });
+
+ const liveDone = seen.find((event) => event.type === 'done');
+ expect(liveDone?.sessionTurnGeneration).toBe(2);
+ releaseDispatch();
+ await second;
+ await session.close();
+ });
+
it('terminal error 后先排空尾部,再允许新 attempt', async () => {
const { handle, emit } = createControllableHandle();
const session = makeSession(handle);
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 7a56636859..2a9f3246e6 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -424,6 +424,16 @@ export class Session {
private terminalErrorDrainGeneration: number | null = null;
private terminalErrorDrainTimer: ReturnType<typeof setTimeout> | null = null;
private sendReservation: SendReservation | null = null;
+ /** True while runEventLoop is blocked in iterator.next(). */
+ private eventLoopAwaiting = false;
+ /** The blocked next() that was pending when the current send entered handle.send. */
+ private inFlightSendOwnsBlockedWait = false;
+ /** True from handle.send() start until that send settles. */
+ private insideProviderSendSync = false;
+ /** Keep a leftover status/done tail on the generation that started it. */
+ private staleTerminalQueuedGeneration: number | null = null;
+ /** Previous turn generation, kept until leftover tail or new-turn progress. */
+ private pendingPriorGeneration: number | null = null;
/**
* 当前进行中 turn 的发起来源(来自 send 的 opts.origin)。事件 fan-out 前打到
* AgentEvent.turnOrigin 上,turn 终止(isTerminalTurnEvent)后清空 — 共享
@@ -570,6 +580,14 @@ export class Session {
// 卡死的 turn",避免误杀宽限期内新起的健康 turn。
const previousTurnGeneration = this.turnGeneration;
this.turnGeneration += 1;
+ if (
+ previousTurnGeneration > 0 &&
+ this.terminalEventObservedGeneration !== previousTurnGeneration
+ ) {
+ this.pendingPriorGeneration = previousTurnGeneration;
+ } else {
+ this.pendingPriorGeneration = null;
+ }
const reservedTurnGeneration = this.turnGeneration;
const reservation = createSendReservation(reservedTurnGeneration);
this.sendReservation = reservation;
@@ -652,10 +670,15 @@ export class Session {
try {
this.beginTurnControl(reservedTurnGeneration);
onDispatching?.();
- await this.handle.send(msg, {
- ...handleOpts,
- signal: reservation.abortController.signal,
- });
+ this.insideProviderSendSync = true;
+ try {
+ await this.handle.send(msg, {
+ ...handleOpts,
+ signal: reservation.abortController.signal,
+ });
+ } finally {
+ this.insideProviderSendSync = false;
+ }
} catch (e) {
if (e instanceof TurnDispatchRejectedError) {
// The provider returned a trustworthy rejection before accepting any
@@ -699,6 +722,7 @@ export class Session {
this.currentTurnOrigin = previousTurnOrigin;
this.currentTurnAttemptToken = previousTurnAttemptToken;
this.turnGeneration = previousTurnGeneration;
+ this.pendingPriorGeneration = null;
originInstalled = false;
}
await this.close();
@@ -719,15 +743,26 @@ export class Session {
// turn 的剩余事件(含 done)继续带正确 origin。若这里强行清 null,正在跑的
// turn 的 done 会丢 origin → IM 转播收不到 done → 转播卡永不 finalize、残留
// state 污染下一轮(见 PR #129 review)。
- if (originInstalled && !turnDispatched) {
- this.currentTurnOrigin = previousTurnOrigin;
- this.currentTurnAttemptToken = previousTurnAttemptToken;
+ if (!turnDispatched) {
+ if (originInstalled) {
+ this.currentTurnOrigin = previousTurnOrigin;
+ this.currentTurnAttemptToken = previousTurnAttemptToken;
+ originInstalled = false;
+ // Confirmed provider rejection cannot produce a turn tail, so it may
+ // immediately reuse the rolled-back generation. Other failures retain
+ // the bounded tail fence before another turn can enter.
+ if (!dispatchConfirmedUndispatched) {
+ this.armTerminalErrorDrain(previousTurnGeneration);
+ }
+ }
this.turnGeneration = previousTurnGeneration;
- // Confirmed provider rejection cannot produce a turn tail, so it may
- // immediately reuse the rolled-back generation. Other failures retain
- // the bounded tail fence before another turn can enter.
- if (!dispatchConfirmedUndispatched) {
- this.armTerminalErrorDrain(previousTurnGeneration);
+ if (
+ previousTurnGeneration > 0 &&
+ this.terminalEventObservedGeneration !== previousTurnGeneration
+ ) {
+ this.pendingPriorGeneration = previousTurnGeneration;
+ } else {
+ this.pendingPriorGeneration = null;
}
}
if (turnLifecyclePrepared && !turnDispatched) {
@@ -1603,6 +1638,7 @@ export class Session {
gracefulStopState: 'none',
gracefulStopPromise: null,
};
+ this.inFlightSendOwnsBlockedWait = this.eventLoopAwaiting;
}
private clearTurnControl(generation: number): void {
@@ -1751,12 +1787,139 @@ export class Session {
* 并像用户插话一样暂停 goal,scheduler 的 IM 转播则直接忽略,卡片永不 finalize
* (review #944 第二轮)。
*/
- private fanOutEvent(event: AgentEvent, observedGeneration = this.turnGeneration): void {
+ private isIdleStatusEvent(event: AgentEvent): boolean {
+ if (event.type !== 'status') return false;
+ const data = event.data as { isRunning?: unknown } | null | undefined;
+ return data?.isRunning === false;
+ }
+
+ private isSilentStopDoneEvent(event: AgentEvent): boolean {
+ if (event.type !== 'done') return false;
+ const data = event.data as { silentStop?: unknown } | null | undefined;
+ return data?.silentStop === true;
+ }
+
+ private isLeftoverTailEvent(event: AgentEvent): boolean {
+ return (
+ (event.type === 'done' && !this.isSilentStopDoneEvent(event)) ||
+ this.isIdleStatusEvent(event) ||
+ (isTerminalAgentErrorEvent(event) && this.staleTerminalQueuedGeneration !== null)
+ );
+ }
+
+ private isNewTurnProgressEvent(event: AgentEvent): boolean {
+ if (event.turnScope === 'background') return false;
+ return (
+ event.type === 'text' ||
+ event.type === 'thinking' ||
+ event.type === 'image' ||
+ event.type === 'tool_use' ||
+ event.type === 'tool_result' ||
+ event.type === 'tool_result_full'
+ );
+ }
+
+ private resolveSessionTurnGeneration(
+ waitStartGeneration: number,
+ observedGeneration: number,
+ event: AgentEvent,
+ ): number {
+ if (observedGeneration > waitStartGeneration) {
+ this.staleTerminalQueuedGeneration = null;
+ if (this.isNewTurnProgressEvent(event)) {
+ this.pendingPriorGeneration = null;
+ }
+ return observedGeneration;
+ }
+ const prior = this.pendingPriorGeneration;
+ const leftoverDoneOrIdle =
+ (event.type === 'done' && !this.isSilentStopDoneEvent(event)) ||
+ this.isIdleStatusEvent(event);
+ if (prior !== null && leftoverDoneOrIdle && waitStartGeneration !== 0) {
+ if (event.type === 'done') {
+ this.pendingPriorGeneration = null;
+ this.staleTerminalQueuedGeneration = null;
+ } else {
+ this.staleTerminalQueuedGeneration = prior;
+ }
+ return prior;
+ }
+ const leftoverTail = this.isLeftoverTailEvent(event);
+ if (leftoverTail && this.staleTerminalQueuedGeneration !== null) {
+ const stamped = this.staleTerminalQueuedGeneration;
+ if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {
+ this.staleTerminalQueuedGeneration = null;
+ }
+ return stamped;
+ }
+ if (leftoverTail && waitStartGeneration > 0 && waitStartGeneration < this.turnGeneration) {
+ if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {
+ this.staleTerminalQueuedGeneration = null;
+ } else {
+ this.staleTerminalQueuedGeneration = waitStartGeneration;
+ }
+ return waitStartGeneration;
+ }
+ const inFlightGeneration = this.sendReservation?.generation;
+ const belongsToInFlightSend =
+ this.insideProviderSendSync &&
+ this.inFlightSendOwnsBlockedWait &&
+ typeof inFlightGeneration === 'number' &&
+ inFlightGeneration === this.turnGeneration &&
+ this.turnControlState?.generation === inFlightGeneration;
+ if (belongsToInFlightSend) {
+ this.inFlightSendOwnsBlockedWait = false;
+ this.staleTerminalQueuedGeneration = null;
+ if (
+ this.isNewTurnProgressEvent(event) ||
+ event.type === 'done' ||
+ isTerminalAgentErrorEvent(event)
+ ) {
+ this.pendingPriorGeneration = null;
+ }
+ return inFlightGeneration;
+ }
+ if (waitStartGeneration === 0 && this.turnGeneration > 0) {
+ this.staleTerminalQueuedGeneration = null;
+ return this.turnGeneration;
+ }
+ if (this.isNewTurnProgressEvent(event)) {
+ // New-turn tokens prove this generation owns later product terminals.
+ // Drop a leftover idle-only tail too: if that old done is lost, the
+ // live done must not inherit staleQueued and get fenced.
+ this.pendingPriorGeneration = null;
+ this.staleTerminalQueuedGeneration = null;
+ }
+ return waitStartGeneration;
+ }
+
+ private fanOutEvent(
+ event: AgentEvent,
+ observedGeneration = this.turnGeneration,
+ queuedGeneration = observedGeneration,
+ ): void {
const isBackgroundEvent = event.turnScope === 'background';
if (!isBackgroundEvent) this.lastEventAt = Date.now();
this.lastEventType = event.type;
- const isCurrentGeneration = observedGeneration === this.turnGeneration;
- this.observeTurnControl(event, observedGeneration);
+ if (event.sessionInstanceId === undefined) {
+ event.sessionInstanceId = this.instanceId;
+ }
+ if (event.sessionTurnGeneration === undefined) {
+ event.sessionTurnGeneration = this.resolveSessionTurnGeneration(
+ queuedGeneration,
+ observedGeneration,
+ event,
+ );
+ }
+ const resolvedGeneration = event.sessionTurnGeneration ?? observedGeneration;
+ // Both the source stamp and the dequeued wait must name this turn.
+ // A leftover tail can be stamped N while next() recaptures N+1, or the
+ // reverse when an in-flight start-failure adopts the new generation from
+ // an older wait. Current-turn cleanup requires agreement.
+ const isCurrentGeneration =
+ resolvedGeneration === this.turnGeneration &&
+ observedGeneration === this.turnGeneration;
+ this.observeTurnControl(event, resolvedGeneration);
// fan-out 前打 turn origin(所有 listener 拿到同一份);事件对象由 translator
// 每次新建、看门狗每次合成,不会串台。=== undefined 守卫:不覆盖 agent 自带的。
if (!isBackgroundEvent && isCurrentGeneration && this.currentTurnOrigin && event.turnOrigin === undefined) {
@@ -1811,32 +1974,38 @@ export class Session {
}
const listenerEvent = redactEventForListeners(event);
if (isCurrentGeneration && isTerminal && !isBackgroundEvent) {
- this.clearTurnControl(observedGeneration);
+ this.clearTurnControl(resolvedGeneration);
}
- if (isTerminal && !isBackgroundEvent) {
+ const isLeftoverProductTerminal =
+ !isBackgroundEvent &&
+ resolvedGeneration < this.turnGeneration &&
+ (isTerminal || this.isIdleStatusEvent(event));
+ if (isTerminal && !isBackgroundEvent && !isLeftoverProductTerminal) {
try {
const pending = this.turnLifecycleObserver?.onTerminal({
- turnGeneration: observedGeneration,
+ turnGeneration: resolvedGeneration,
event: listenerEvent,
isCurrentGeneration,
});
if (pending) {
void Promise.resolve(pending).catch((error) => {
this.logger.warn('turn lifecycle terminal cleanup failed', {
- turnGeneration: observedGeneration,
+ turnGeneration: resolvedGeneration,
error: String(error),
});
});
}
} catch (error) {
this.logger.warn('turn lifecycle terminal cleanup failed', {
- turnGeneration: observedGeneration,
+ turnGeneration: resolvedGeneration,
error: String(error),
});
}
}
- for (const listener of this.eventListeners) {
- try { listener(listenerEvent); } catch (e) { this.logger.error('event listener threw', { error: String(e) }); }
+ if (!isLeftoverProductTerminal) {
+ 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
@@ -2118,7 +2287,13 @@ export class Session {
const awaitingCanAdoptNextGeneration =
awaitingGeneration === 0 ||
this.terminalEventObservedGeneration === awaitingGeneration;
- const result = await iterator.next();
+ this.eventLoopAwaiting = true;
+ let result: IteratorResult<AgentEvent>;
+ try {
+ result = await iterator.next();
+ } finally {
+ this.eventLoopAwaiting = false;
+ }
if (result.done) break;
const event = result.value;
this.releaseSendReservationIfObserved();
@@ -2137,7 +2312,7 @@ export class Session {
if (this.terminationStarted) continue;
// origin 打标与终态清理都收在 fanOutEvent 里(看门狗合成的事件共用同一语义,
// 见那里的注释)。关闭门一旦占住,旧 handle 的迟到事件不得再改写业务状态。
- this.fanOutEvent(event, observedGeneration);
+ this.fanOutEvent(event, observedGeneration, awaitingGeneration);
}
} catch (e) {
this.logger.error('event loop crashed', { error: String(e) });
diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.ts
index 7410c16e1b..9f789e1cd2 100644
--- a/packages/maker-core/src/session.turn-stall.test.ts
+++ b/packages/maker-core/src/session.turn-stall.test.ts
@@ -260,6 +260,33 @@ describe('Session turn stall watchdog', () => {
}
});
+ it('stamps dequeued terminals with the queued generation and Session instance', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((ev) => seen.push(ev));
+
+ await session.send('first');
+ expect(session.getTurnGeneration()).toBe(1);
+ stub.endTurn();
+ await session.send('second');
+ expect(session.getTurnGeneration()).toBe(2);
+ stub.endTurn();
+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' } as AgentEvent);
+ await vi.advanceTimersByTimeAsync(0);
+
+ const done = seen.find((ev) => ev.type === 'done');
+ // The constructor wait starts at generation 0; the send that is current
+ // when that wait finally dequeues owns the event.
+ expect(done?.sessionTurnGeneration).toBe(2);
+ expect(done?.sessionInstanceId).toBe(session.instanceId);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('合成的超时 error 带 turnOrigin,并在 fan-out 后清空(review 第二轮)', async () => {
// 不带 origin 的话:goal-host 把它归类成 origin:'other' 并像用户插话一样暂停 goal,
// scheduler 的 IM 转播则直接忽略这条终态,卡片永不 finalize。
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index d3e2890072..72817a7c71 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -167,6 +167,14 @@ export interface AgentEvent {
turnOrigin?: SendOrigin;
/** Host-owned per-turn correlation for lifecycle bookkeeping; never comes from vendor metadata. */
turnAttemptToken?: number;
+ /**
+ * Session.turnGeneration captured when runEventLoop started the next() that
+ * dequeued this event. Adoption of a later generation must not overwrite it,
+ * so a leftover terminal keeps the older value after the next send. Host-only.
+ */
+ sessionTurnGeneration?: number;
+ /** Session.instanceId of the incarnation that dequeued this event. Host-only. */
+ sessionInstanceId?: string;
/**
* Provider-owned claim attached synchronously to a `done` boundary when that
* boundary has an automatic continuation. Consumers pass it back to the