Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 用当前 generation 终态证据回收残留 activeTurn (#3383)
Chris Zhang57a266872237
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.tsindex 58e2b0e844..af6189e388 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@@ -611,6 +611,17 @@ function createHarness(opts?: {let liveRunningOverride: boolean | null | 'unknown' = null;let liveSessionPresentOverride: boolean | null | 'unknown' = null;let turnGeneration = 0;+ let observedCurrentTurnTerminal:+ | {+ kind: 'none' | 'done' | 'error';+ generation?: number;+ message?: string;+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ }+ | undefined = { kind: 'none' };+ let observedCurrentTurnTerminalThrows = false;let turnSessionIdentity: object = { instanceId: 'harness-session' };let pendingInteraction = false;let agentKind: AgentInputCreateOpts['agentKind'] | null = 'claude-code';@@ -618,6 +629,7 @@ function createHarness(opts?: {const sendToAgent = vi.fn<AgentInputCoordinatorDeps['sendToAgent']>(async (sessionId, _message, _createOpts, sendOpts) => {+ sendOpts.onVendorTurnReserved?.(turnGeneration);await persistQueuedUserMessage(sessionId, sendOpts);running = true;return sendSuccess();@@ -668,8 +680,10 @@ function createHarness(opts?: {>(() => resumableTurnErrorTakeover);// 纯判定(无副作用):这条 error 有没有可能被接管。host 侧接的是 isInterruptedTurnError,// 这里默认认所有带 sdkError='server_error' 的,够表达"候选 / 非候选"两种分支。- let resumableTurnErrorCandidate: (signals: { sdkError?: string }) => boolean = (signals) =>- signals.sdkError === 'server_error';+ let resumableTurnErrorCandidate: (signals: {+ sdkError?: string;+ reason?: string;+ }) => boolean = (signals) => signals.sdkError === 'server_error';const isResumableTurnErrorCandidate = vi.fn<NonNullable<AgentInputCoordinatorDeps['isResumableTurnErrorCandidate']>>((signals) => resumableTurnErrorCandidate(signals));@@ -745,6 +759,10 @@ function createHarness(opts?: {return true;},getTurnGeneration: () => turnGeneration,+ getObservedCurrentTurnTerminal: () => {+ if (observedCurrentTurnTerminalThrows) throw new Error('registry switched');+ return observedCurrentTurnTerminal;+ },getTurnSessionIdentity: () => turnSessionIdentity,reconcileTurnIdle,hasPendingInteraction: () => pendingInteraction,@@ -831,6 +849,24 @@ function createHarness(opts?: {setTurnGeneration(value: number) {turnGeneration = value;},+ setObservedCurrentTurnTerminal(+ value:+ | {+ kind: 'none' | 'done' | 'error';+ generation?: number;+ message?: string;+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ }+ | undefined,+ ) {+ observedCurrentTurnTerminal = value;+ observedCurrentTurnTerminalThrows = false;+ },+ setObservedCurrentTurnTerminalThrows(value = true) {+ observedCurrentTurnTerminalThrows = value;+ },getTurnSessionIdentity() {return turnSessionIdentity;},@@ -863,7 +899,9 @@ function createHarness(opts?: {resumableTurnErrorTakeover = value;},/** 改写"这条 error 有没有可能被接管"的纯判定(决定横幅与落库要不要先按住)。 */- setResumableTurnErrorCandidate(fn: (signals: { sdkError?: string }) => boolean) {+ setResumableTurnErrorCandidate(+ fn: (signals: { sdkError?: string; reason?: string }) => boolean,+ ) {resumableTurnErrorCandidate = fn;},persistQueueSnapshot,@@ -6436,6 +6474,167 @@ describe('AgentInputCoordinator steer transaction', () => {expect(projection.errorRetryText).toBe('second');});+ it('recovers a missed same-generation error when only paired done arrives during steer persist', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ h.setResumableTurnErrorCandidate((signals) => signals.reason === 'empty-response');+ const sid = 'steer-persist-missed-error-snapshot';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');+ const persistStarted = deferred<void>();+ const persistSucceeded = deferred<void>();+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });++ h.coordinator.enqueue(sid, first);+ await flush();+ const steerPromise = h.coordinator.steer(sid, second, { removeFromQueue: true });+ await persistStarted.promise;++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'Authorization: Bearer secret-token',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ persistSucceeded.resolve();+ await expect(steerPromise).resolves.toBe(true);+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery).toEqual({ kind: 'active-turn', item: second });+ expect(projection.error).toBe('Authorization: [REDACTED]');+ expect(JSON.stringify(projection)).not.toContain('secret-token');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ });++ it('recovers a missed same-generation error when steer persist settles on an idle turn', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ h.setResumableTurnErrorCandidate((signals) => signals.reason === 'empty-response');+ const sid = 'steer-idle-missed-error-snapshot';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');++ h.coordinator.enqueue(sid, first);+ await flush();+ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'Authorization: Bearer secret-token',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });++ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(true);+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery).toEqual({ kind: 'active-turn', item: second });+ expect(projection.error).toBe('Authorization: [REDACTED]');+ expect(JSON.stringify(projection)).not.toContain('secret-token');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ });++ it('does not success-settle a steer leftover when a later generation already replaced it', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ const sid = 'steer-idle-superseded-generation';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');+ const third = makeItem('q-3', 'third');+ const persistStarted = deferred<void>();+ const persistSucceeded = deferred<void>();+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });++ h.coordinator.enqueue(sid, first);+ await flush();+ const steerPromise = h.coordinator.steer(sid, second, { removeFromQueue: true });+ await persistStarted.promise;++ h.setTurnGeneration(1);+ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'done',+ generation: 1,+ });++ persistSucceeded.resolve();+ await expect(steerPromise).resolves.toBe(true);+ await flush();++ h.coordinator.enqueue(sid, third);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ });++ it('does not settle a deferred persist done against a later-generation error snapshot', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ const sid = 'steer-persist-done-error-generation-mismatch';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');+ const persistStarted = deferred<void>();+ const persistSucceeded = deferred<void>();+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });++ h.coordinator.enqueue(sid, first);+ await flush();+ const steerPromise = h.coordinator.steer(sid, second, { removeFromQueue: true });+ await persistStarted.promise;++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 2,+ message: 'later turn failed',+ });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 2,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ persistSucceeded.resolve();+ await expect(steerPromise).resolves.toBe(true);+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ });+it('suppresses stale steer persist failure after clearSession wins during persistence', async () => {const h = createHarness();h.setAgentKind('codex');@@ -6649,6 +6848,943 @@ describe('AgentInputCoordinator steer transaction', () => {expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-1']);});+ it('reclaims a leftover activeTurn when the live Session already observed the current terminal', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-lost-terminal-coordinator-only';+ 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);++ // Session + tracker both idle; only coordinator leftover activeTurn remains.+ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 0 });+ h.reconcileTurnIdle.mockImplementation(() => 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 from a later generation terminal', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-lost-terminal-generation-mismatch';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setTurnGeneration(2);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 2 });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-later-turn'));+ await flush();+ 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('binds leftover reclaim to the reserved generation, not the post-await latest generation', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-reserved-generation-not-latest';+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {+ sendOpts.onVendorTurnReserved?.(1);+ h.setTurnGeneration(2);+ await persistQueuedUserMessage(sessionId, sendOpts);+ h.setRunning(true);+ return sendSuccess();+ });+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 2 });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-later-turn'));+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 1 });+ h.coordinator.enqueue(sid, makeItem('q-3', 'queued-after-match'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'queued-after-later-turn',+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('forwards structured leftover error signals into resumable recovery', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-lost-terminal-empty-response';+ h.setResumableTurnErrorCandidate((signals) => signals.reason === 'empty-response');+ h.setResumableTurnErrorTakeover({+ error: 'empty response',+ attempt: 1,+ maxAttempts: 5,+ sessionTotal: 1,+ });+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'Authorization: Bearer secret-token',+ reason: 'empty-response',+ sdkError: 'server_error',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-error'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();++ const projection = latestProjection(h.projections);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.autoResumePending?.attempt).toBe(1);+ expect(projection.error).toBeNull();+ expect(JSON.stringify(projection)).not.toContain('secret-token');+ expect(h.onResumableTurnError).toHaveBeenCalledWith(+ sid,+ expect.objectContaining({+ reason: 'empty-response',+ sdkError: 'server_error',+ message: 'Authorization: [REDACTED]',+ }),+ expect.objectContaining({ clientId: 'q-1' }),+ );+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reclaim leftover activeTurn when the current-generation terminal probe is unavailable', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-terminal-probe-unknown';+ 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(false);+ h.setObservedCurrentTurnTerminal(undefined);+ h.coordinator.enqueue(sid, second);+ await flush();++ 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('does not reclaim leftover activeTurn when the terminal probe throws after Session-present succeeds', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-terminal-probe-throws';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(true);+ h.setObservedCurrentTurnTerminalThrows();+ h.reconcileTurnIdle.mockImplementation(() => {+ h.setRunning(false);+ return true;+ });+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-throw'));+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();++ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reclaim leftover activeTurn when the terminal probe is undefined and the tracker stays busy', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-terminal-probe-undefined-tracker-busy';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(true);+ h.setObservedCurrentTurnTerminal(undefined);+ h.reconcileTurnIdle.mockImplementation(() => {+ h.setRunning(false);+ return true;+ });+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-undefined'));+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();++ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('binds leftover steer reclaim to the generation captured at steer start', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'steer-binds-snapshot-generation';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ let releaseSteer!: () => void;+ h.steerToAgent.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ releaseSteer = resolve;+ }),+ );+ const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'injected'));+ await flush();+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);++ h.setTurnGeneration(1);+ releaseSteer();+ await expect(steerPromise).resolves.toBe(true);+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 1 });+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-later-done'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();++ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 1,+ message: 'later turn failed',+ });+ await vi.advanceTimersByTimeAsync(250);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps a planned-upgrade remote_daemon_closed silent when the paired done arrives', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-paired-done';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] daemon restarting',+ reason: 'remote_daemon_closed',+ });+ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ });+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-upgrade-done'));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery).toBeNull();+ expect(projection.error).toBeNull();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(projection.pendingQueue.map((q) => q.clientId)).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not recover a suppressed planned-upgrade error through leftover reconcile', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-leftover';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] daemon restarting',+ reason: 'remote_daemon_closed',+ });+ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-upgrade'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery).toBeNull();+ expect(projection.error).toBeNull();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('still recovers a real remote_daemon_closed that was not host-suppressed', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-unplanned-daemon-closed';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] unexpected',+ reason: 'remote_daemon_closed',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toContain('REMOTE_DAEMON_CLOSED');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('clears a planned-upgrade marker on Session close so a replacement instance cannot consume it', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-closed-replacement';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ instanceId: 'harness-session',+ });+ h.coordinator.onSessionClosed(sid);+ h.setTurnSessionIdentity({ instanceId: 'replacement-session' });+ h.setTurnGeneration(0);+ h.setRunning(false);+ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setObservedCurrentTurnTerminal({ kind: 'none' });++ h.coordinator.enqueue(sid, makeItem('q-2', 'after-rebuild'));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] unexpected after rebuild',+ reason: 'remote_daemon_closed',+ });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'replacement-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toContain('REMOTE_DAEMON_CLOSED');+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not consume a stale planned-upgrade marker after identity swap even without close', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-stale-instance';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ instanceId: 'harness-session',+ });+ h.setTurnSessionIdentity({ instanceId: 'replacement-session' });+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] unexpected after swap',+ reason: 'remote_daemon_closed',+ });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'replacement-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toContain('REMOTE_DAEMON_CLOSED');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reclaim leftover error as planned-upgrade after close + generation reuse', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-leftover-reuse';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ });+ h.coordinator.onSessionClosed(sid, { preserveInputBoundary: true });+ h.setTurnSessionIdentity({ instanceId: 'replacement-session' });+ h.setTurnGeneration(0);+ h.setRunning(false);+ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setObservedCurrentTurnTerminal({ kind: 'none' });++ h.coordinator.enqueue(sid, makeItem('q-2', 'after-rebuild'));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] unexpected leftover',+ reason: 'remote_daemon_closed',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, makeItem('q-3', 'queued-after-error'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toContain('REMOTE_DAEMON_CLOSED');+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(projection.pendingQueue.map((q) => q.clientId)).toEqual(['q-3']);+ } finally {+ vi.useRealTimers();+ }+ });++ it('still silences planned-upgrade close on the same Session instance', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-planned-upgrade-same-instance';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: '[REMOTE_DAEMON_CLOSED] daemon restarting',+ reason: 'remote_daemon_closed',+ });+ h.coordinator.noteSuppressedTerminalError(sid, {+ generation: 0,+ reason: 'remote_daemon_closed',+ instanceId: 'harness-session',+ });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery).toBeNull();+ expect(projection.error).toBeNull();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not treat an observed terminal error as a successful leftover settlement', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-lost-terminal-error';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'queued-after-error');++ h.coordinator.enqueue(sid, first);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'Authorization: Bearer secret-token',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);+ h.coordinator.enqueue(sid, second);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(250);+ await flush();++ const projection = latestProjection(h.projections);+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toBe('Authorization: [REDACTED]');+ expect(JSON.stringify(projection)).not.toContain('secret-token');+ expect(projection.pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({ kind: 'none' });+ h.coordinator.retryLastError(sid);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'first' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('routes a paired done through leftover error recovery before the 250ms reconcile', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-paired-done-before-error-reconcile';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'Authorization: Bearer secret-token',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ const projection = latestProjection(h.projections);+ expect(projection.recovery?.kind).toBe('active-turn');+ expect(projection.error).toBe('Authorization: [REDACTED]');+ expect(JSON.stringify(projection)).not.toContain('secret-token');+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(250);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');++ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({ kind: 'none' });+ h.coordinator.retryLastError(sid);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'first' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not settle leftover activeTurn as success when done arrives with a mismatched error snapshot', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-paired-done-error-generation-mismatch';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-mismatch'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 2,+ message: 'later turn failed',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 2,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps a pending Stop abort boundary when a later-generation terminal arrives', async () => {+ const h = createHarness();+ const sid = 'stop-abort-ignores-later-generation-terminal';+ const first = makeItem('q-1', 'first', {+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind: 'codex' },+ });+ const second = makeItem('q-2', 'second', {+ createOpts: { ...makeItem('tmp2', 'tmp2').createOpts, agentKind: 'codex' },+ });+ const abort = deferred<void>();+ h.setAgentKind('codex');+ h.abortSession.mockImplementationOnce(() => abort.promise);++ h.coordinator.enqueue(sid, first);+ await flush();+ h.coordinator.enqueue(sid, second);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });+ h.coordinator.resume(sid);+ await flush();+ expect(latestProjection(h.projections).queueAbortPending).toBe(true);++ h.setTurnGeneration(1);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 1 });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 1,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ expect(latestProjection(h.projections).queueAbortPending).toBe(true);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);+ expect(latestProjection(h.projections).recovery).toBeNull();++ h.coordinator.onTurnEvent(sid, 'error', 'later turn failed', undefined, {+ sessionTurnGeneration: 1,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ expect(latestProjection(h.projections).queueAbortPending).toBe(true);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setRunning(false);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 0 });+ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'second' });+ expect(latestProjection(h.projections).queueAbortPending).toBe(false);+ });++ it('does not settle leftover activeTurn from a later-generation done callback', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-direct-next-turn-done-mismatch';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-direct-send'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setTurnGeneration(2);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 2 });+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 2,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('settles leftover activeTurn when the matching generation done arrives after a later turn', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-late-matching-done-after-direct-send';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-direct-send'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setTurnGeneration(2);+ h.setObservedCurrentTurnTerminal({ kind: 'done', generation: 2 });+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 2,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.coordinator.onTurnEvent(sid, 'done', undefined, undefined, {+ sessionTurnGeneration: 0,+ sessionInstanceId: 'harness-session',+ });+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'queued-after-direct-send',+ });+ expect(latestProjection(h.projections).recovery).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not recover leftover activeTurn from a later-generation error callback', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-direct-next-turn-error-mismatch';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-direct-send'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(false);+ h.setTurnGeneration(2);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 2,+ message: 'later turn failed',+ });+ h.reconcileTurnIdle.mockImplementation(() => true);++ h.coordinator.onTurnEvent(sid, 'error', 'later turn failed', undefined, {+ sessionTurnGeneration: 2,+ sessionInstanceId: 'harness-session',+ });+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery).toBeNull();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'q-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('routes a leftover terminal error through recovery even when the tracker stays busy', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-lost-terminal-error-tracker-busy';+ h.coordinator.enqueue(sid, makeItem('q-1', 'first'));+ await flush();++ h.setLiveRunning(false);+ h.setLiveSessionPresent(true);+ h.setRunning(true);+ h.setObservedCurrentTurnTerminal({+ kind: 'error',+ generation: 0,+ message: 'provider failed',+ });+ h.reconcileTurnIdle.mockImplementation(() => {+ h.setRunning(false);+ return true;+ });+ h.coordinator.enqueue(sid, makeItem('q-2', 'queued-after-error'));+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();++ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);+ } finally {+ vi.useRealTimers();+ }+ });+it('does not reclaim leftover activeTurn in the post-send agent_start gap', async () => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex b876a0f7e5..28d4abd4c1 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -24,6 +24,7 @@* 它只提交 intent payload;排序、投递模式、回滚和持久化由本模块决定。*/+import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { isUnsupportedResponsesImageErrorPayload } from '@cindy/responses-chat-bridge';import { isPiImageInputUnsupportedError } from '../../shared/inputError.js';import { createLogger } from '../logger.js';@@ -206,6 +207,8 @@ export interface AgentInputSendOpts {expectedTurnSession?: object;/** Main-owned maker-core turn generation for a control-plane same-turn steer. */expectedTurnGeneration?: number;+ /** Session reservation 时回调本轮 vendor generation;必须在 send 返回前绑定 leftover。 */+ onVendorTurnReserved?: (generation: number) => void;persistUserMessage?: {clientId: string;content: string;@@ -278,6 +281,20 @@ export interface AgentInputCoordinatorDeps {isLiveSessionPresent?: (sessionId: string) => boolean | undefined;/** maker-core turn 代号;steer 跨 await 后据此验证仍属于开始时的同一 vendor turn。 */getTurnGeneration?: (sessionId: string) => number | null;+ /**+ * 当前 generation 已 fan-out 的产品终态类型。+ * undefined = probe 不可用;kind=none = 无当前 generation 终态(含 PI agent_start 空窗)。+ */+ getObservedCurrentTurnTerminal?: (+ sessionId: string,+ ) => {+ kind: 'none' | 'done' | 'error';+ generation?: number;+ message?: string;+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } | undefined;/** maker-core Session object identity; control-plane steer uses it to reject session reuse. */getTurnSessionIdentity?: (sessionId: string) => object | null;/**@@ -537,6 +554,8 @@ interface ActiveTurn {/** 当前 vendor turn 由哪条 Continue 合成项发起;同轮 steer 会继承它。 */continuationOwnerClientId: string | null;controlKind?: 'compact';+ /** maker-core turn generation captured at vendor dispatch; leftover reclaim must match it. */+ vendorTurnGeneration: number | null;}interface PendingCompactRequest {@@ -645,6 +664,18 @@ interface SessionInputState {staleLiveIdleSinceMs: number | null;/** Leftover terminal fence: Session incarnation + the generation that was reclaimed. */fencedStaleTerminal: { instanceId: string; generation: number } | null;+ /**+ * Host-intentionally ignored terminal (planned cc-mgr upgrade close).+ * Bound to the emitting Session incarnation + generation. Session still+ * records the error snapshot; leftover/paired-done must not re-synthesize+ * it as a user-visible recovery, and a replacement Session must not consume+ * a stale marker after generation restart.+ */+ suppressedTerminalError: {+ instanceId: string;+ generation: number;+ reason: string;+ } | null;/*** 发送撞上 CREDENTIAL_SWITCH_BUSY 后的可见等待态:队首保留,挡路会话 turn 结束* (onExternalTurnSettled)或兜底定时器触发自动重发。clientId 绑定等待中的那条@@ -711,6 +742,7 @@ function createInitialInputState(sessionRunningRetryToken: null,staleLiveIdleSinceMs: null,fencedStaleTerminal,+ suppressedTerminalError: null,credentialSwitchWait: null,credentialSwitchRetryTimer: null,credentialSwitchRetryGeneration: null,@@ -1729,6 +1761,7 @@ export class AgentInputCoordinator {pendingTerminalEvent: null,continuationOwnerClientId: null,controlKind: 'compact',+ vendorTurnGeneration: null,};state.activeTurn = active;this.emit(sessionId);@@ -1746,6 +1779,8 @@ export class AgentInputCoordinator {throwOnStartFailure: true,expectedClearBoundaryMs: active.clearBoundaryMs,expectedInputGeneration: active.generation,+ onVendorTurnReserved: (generation) =>+ this.captureReservedVendorGeneration(sessionId, active, generation),},);if (!this.isActiveTurnCurrent(sessionId, active)) return this.getProjection(sessionId);@@ -1774,7 +1809,7 @@ export class AgentInputCoordinator {this.scheduleDrain(sessionId, 'compact-not-dispatched');return this.getProjection(sessionId);}- active.dispatchLifecycle = 'dispatched';+ this.markActiveTurnDispatched(sessionId, active);if (active.pendingTerminalEvent) {this.settlePendingTerminalEventAfterPersist(sessionId, active);return this.getProjection(sessionId);@@ -2235,6 +2270,8 @@ export class AgentInputCoordinator {dispatchLifecycle: 'dispatched',pendingTerminalEvent: null,continuationOwnerClientId: null,+ vendorTurnGeneration:+ typeof steerVendorTurnGeneration === 'number' ? steerVendorTurnGeneration : null,};const persisted = await this.persistAcceptedUserMessage(sessionId, detachedAcceptedTurn);if (opts?.touchUserSend && persisted === 'persisted') this.touchUserSend(sessionId);@@ -2288,6 +2325,8 @@ export class AgentInputCoordinator {: sameVendorTurn? steerContinuationOwnerClientId: null,+ vendorTurnGeneration:+ typeof steerVendorTurnGeneration === 'number' ? steerVendorTurnGeneration : null,};this.emit(sessionId);@@ -2324,6 +2363,30 @@ export class AgentInputCoordinator {latest.activeTurn.delivery === 'steer' &&!this.deps.isTurnRunning(sessionId)) {+ const observedError = this.boundObservedTerminalError(sessionId, latest.activeTurn);+ const boundGeneration = latest.activeTurn.vendorTurnGeneration;+ const currentGeneration = this.deps.getTurnGeneration?.(sessionId);+ const boundGenerationSuperseded =+ typeof boundGeneration === 'number' &&+ typeof currentGeneration === 'number' &&+ currentGeneration !== boundGeneration;+ if (observedError) {+ latest.activeTurn.pendingTerminalEvent = {+ type: 'error',+ message: observedError.message,+ signals: observedError.signals,+ };+ this.settlePendingTerminalEventAfterPersist(sessionId, latest.activeTurn);+ } else if (boundGenerationSuperseded) {+ // N's error callback was missed and the probe now only has N+1.+ // Do not treat this as a successful leftover settlement.+ log.warn('steer idle short-circuit skipped; bound generation superseded', {+ sessionId,+ clientId: item.clientId,+ boundGeneration,+ currentGeneration,+ });+ } else {log.info('steer accepted but turn already settled; synthesizing closure', {sessionId,clientId: item.clientId,@@ -2338,6 +2401,7 @@ export class AgentInputCoordinator {latest.recovery = priorRecovery;}this.emit(sessionId);+ }}// steer accepted/removed may change the queue head while an older// SESSION_RUNNING timer is still armed. Rebind its policy now even though@@ -3109,6 +3173,26 @@ export class AgentInputCoordinator {return isMatchingFencedStaleTerminal(this.getState(sessionId).fencedStaleTerminal, meta);}+ noteSuppressedTerminalError(+ sessionId: string,+ meta: { generation?: number; reason?: string; instanceId?: string },+ ): void {+ if (typeof meta.generation !== 'number' || typeof meta.reason !== 'string' || meta.reason.length === 0) {+ return;+ }+ const instanceId =+ typeof meta.instanceId === 'string' && meta.instanceId.length > 0+ ? meta.instanceId+ : readSessionInstanceId(this.deps.getTurnSessionIdentity?.(sessionId));+ if (!instanceId) return;+ const state = this.getState(sessionId);+ state.suppressedTerminalError = {+ instanceId,+ generation: meta.generation,+ reason: meta.reason,+ };+ }+onTurnEvent(sessionId: string,type: 'done' | 'error',@@ -3128,6 +3212,26 @@ export class AgentInputCoordinator {}const active = state.activeTurn;state.staleLiveIdleSinceMs = null;+ // Ownership first. A later-generation terminal must not tear down the+ // pending Stop abort boundary that can still reclaim the leftover turn.+ if (+ active &&+ this.shouldIgnoreUnownedTerminal(+ active,+ meta,+ this.readObservedCurrentTurnTerminal(sessionId),+ )+ ) {+ log.warn('ignored terminal that does not belong to leftover activeTurn', {+ sessionId,+ type,+ clientId: active.item?.clientId ?? null,+ boundGeneration: active.vendorTurnGeneration ?? null,+ eventGeneration: meta?.sessionTurnGeneration ?? null,+ });+ this.emit(sessionId);+ return;+ }this.clearAbortReconcileRetry(state);state.queueAbortPending = false;state.abortBoundaryToken = null;@@ -3261,8 +3365,19 @@ export class AgentInputCoordinator {}if (active?.persisting) {// done 早于 DB 写入完成时不能先释放 drain,否则后续队列会越过一个- // 还没确定是否可恢复的已派发输入。- recordPendingTerminalEvent(active, { type: 'done' });+ // 还没确定是否可恢复的已派发输入。漏掉的同 generation error+ // 必须先写进 deferred terminal,否则落库后会按成功清掉 Retry。+ const deferredError = this.boundObservedTerminalError(sessionId, active);+ recordPendingTerminalEvent(+ active,+ deferredError+ ? {+ type: 'error',+ message: deferredError.message,+ signals: deferredError.signals,+ }+ : { type: 'done' },+ );this.emit(sessionId);return;}@@ -3284,6 +3399,46 @@ export class AgentInputCoordinator {this.emit(sessionId);return;}+ if (active && isActiveTurnDispatched(active)) {+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ if (observed?.kind === 'error') {+ if (this.observedMatchesBoundActiveTurn(active, observed)) {+ if (!this.consumeSuppressedObservedError(sessionId, observed)) {+ const signals: Omit<InterruptedTurnErrorSignals, 'message'> = {+ ...(observed.reason ? { reason: observed.reason } : {}),+ ...(observed.sdkError ? { sdkError: redactSensitiveText(observed.sdkError) } : {}),+ ...(typeof observed.errorStatus === 'number'+ ? { errorStatus: observed.errorStatus }+ : {}),+ };+ // Codex/Claude 失败收尾是 terminal error 后再补 done。漏掉的 error+ // 回调不能被这道配对 done 先清掉 leftover activeTurn,否则 250ms+ // reconcile 失去恢复对象,失败输入会被当成成功结算且没有 Retry。+ this.onTurnEvent(+ sessionId,+ 'error',+ redactSensitiveText(observed.message ?? 'Turn ended with an error'),+ Object.keys(signals).length > 0 ? signals : undefined,+ meta,+ );+ return;+ }+ // Planned-upgrade suppression consumed: fall through to the normal+ // successful done settlement. Returning here would leave leftover+ // activeTurn for 250ms reconcile, which then re-synthesizes Retry+ // because the marker is already gone.+ } else {+ log.warn('ignored turn-done while leftover activeTurn does not match observed error', {+ sessionId,+ clientId: active.item?.clientId,+ boundGeneration: active.vendorTurnGeneration ?? null,+ observedGeneration: observed.generation ?? null,+ });+ this.emit(sessionId);+ return;+ }+ }+ }state.activeTurn = null;// 同轮注入的 steer 在飞期间,老 turn 的 done 可能先到(注入前 turn 恰好收尾)。// marker 属于 steer 事务而不是老 turn,必须留到 steer() 自己 resolve/reject@@ -3329,6 +3484,10 @@ export class AgentInputCoordinator {opts?: { preserveInputBoundary?: boolean; preserveAutoResumeIntent?: boolean },): void {const state = this.getState(sessionId);+ // Planned-upgrade suppression is per Session incarnation. Replacement+ // Sessions restart generation; a leftover marker would silence a later+ // genuine remote_daemon_closed on the reused generation.+ state.suppressedTerminalError = null;if (!opts?.preserveAutoResumeIntent) {this.supersedePendingAutoResumeRecoveries(sessionId);}@@ -3592,23 +3751,159 @@ export class AgentInputCoordinator {* 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.+ * Leftover `activeTurn` is reclaimed as a successful settlement only when it+ * is already dispatched and we can prove the vendor turn ended successfully:+ * the Session object is missing; the live Session is idle while the desktop+ * tracker is still latched and no error terminal is known; or the current+ * generation has already observed a product `done`. A present Session with an+ * idle tracker and no terminal proof may still be in the Pi gap after+ * handle.send (reservation released, agent_start not yet observed). Known+ * error terminals never take this path. Pre-dispatch owners and unavailable+ * probes stay fail-closed.*/+ private readObservedCurrentTurnTerminal(+ sessionId: string,+ ): NonNullable<AgentInputCoordinatorDeps['getObservedCurrentTurnTerminal']> extends (+ sessionId: string,+ ) => infer R+ ? R+ : undefined {+ try {+ return this.deps.getObservedCurrentTurnTerminal?.(sessionId);+ } catch {+ return undefined;+ }+ }++ private isSuppressedObservedError(+ sessionId: string,+ observed: ReturnType<AgentInputCoordinator['readObservedCurrentTurnTerminal']>,+ ): boolean {+ const suppressed = this.getState(sessionId).suppressedTerminalError;+ if (!suppressed || observed?.kind !== 'error') return false;+ if (typeof observed.generation !== 'number') return false;+ if (suppressed.generation !== observed.generation) return false;+ if (observed.reason !== suppressed.reason) return false;+ const liveInstanceId = readSessionInstanceId(this.deps.getTurnSessionIdentity?.(sessionId));+ return liveInstanceId !== null && liveInstanceId === suppressed.instanceId;+ }++ private consumeSuppressedObservedError(+ sessionId: string,+ observed: ReturnType<AgentInputCoordinator['readObservedCurrentTurnTerminal']>,+ ): boolean {+ if (!this.isSuppressedObservedError(sessionId, observed)) return false;+ this.getState(sessionId).suppressedTerminalError = null;+ return true;+ }++ private bindActiveTurnVendorGeneration(sessionId: string, active: ActiveTurn): void {+ if (typeof active.vendorTurnGeneration === 'number') return;+ const vendorGeneration = this.deps.getTurnGeneration?.(sessionId);+ active.vendorTurnGeneration =+ typeof vendorGeneration === 'number' ? vendorGeneration : null;+ }++ private captureReservedVendorGeneration(+ sessionId: string,+ active: ActiveTurn,+ generation: number,+ ): void {+ if (!this.isActiveTurnCurrent(sessionId, active)) return;+ active.vendorTurnGeneration = generation;+ }++ private markActiveTurnDispatched(sessionId: string, active: ActiveTurn): void {+ active.dispatchLifecycle = 'dispatched';+ this.bindActiveTurnVendorGeneration(sessionId, active);+ }++ private observedMatchesBoundActiveTurn(+ active: ActiveTurn,+ observed: ReturnType<AgentInputCoordinator['readObservedCurrentTurnTerminal']>,+ ): boolean {+ if (!observed || observed.kind === 'none') return false;+ if (typeof observed.generation !== 'number') return false;+ if (typeof active.vendorTurnGeneration !== 'number') return false;+ return observed.generation === active.vendorTurnGeneration;+ }++ private boundObservedTerminalError(+ sessionId: string,+ active: ActiveTurn,+ ): {+ message: string;+ signals?: Omit<InterruptedTurnErrorSignals, 'message'>;+ } | null {+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ if (observed?.kind !== 'error') return null;+ if (!this.observedMatchesBoundActiveTurn(active, observed)) return null;+ if (this.isSuppressedObservedError(sessionId, observed)) return null;+ const signals: Omit<InterruptedTurnErrorSignals, 'message'> = {+ ...(observed.reason ? { reason: observed.reason } : {}),+ ...(observed.sdkError ? { sdkError: redactSensitiveText(observed.sdkError) } : {}),+ ...(typeof observed.errorStatus === 'number' ? { errorStatus: observed.errorStatus } : {}),+ };+ return {+ message: redactSensitiveText(observed.message ?? 'Turn ended with an error'),+ ...(Object.keys(signals).length > 0 ? { signals } : {}),+ };+ }++ private shouldIgnoreUnownedTerminal(+ active: ActiveTurn,+ meta: { sessionTurnGeneration?: number } | undefined,+ observed: ReturnType<AgentInputCoordinator['readObservedCurrentTurnTerminal']>,+ ): boolean {+ if (typeof active.vendorTurnGeneration !== 'number') return false;+ if (typeof meta?.sessionTurnGeneration === 'number') {+ return meta.sessionTurnGeneration !== active.vendorTurnGeneration;+ }+ if (observed && observed.kind !== 'none' && typeof observed.generation === 'number') {+ return observed.generation !== active.vendorTurnGeneration;+ }+ return false;+ }+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;+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ // Probe unavailable / throw is not `{ kind: 'none' }`. Falling through would+ // treat tracker latch as a successful leftover settlement.+ if (observed == null) return false;+ if (observed.kind === 'error') {+ return (+ this.isSuppressedObservedError(sessionId, observed) &&+ this.observedMatchesBoundActiveTurn(active, observed)+ );+ }+ if (observed.kind === 'done') return this.observedMatchesBoundActiveTurn(active, observed);return this.deps.isTurnRunning(sessionId) === true;}- private tryReconcileStaleDispatchBoundary(sessionId: string, state: SessionInputState): boolean {+ private canRecoverLeftoverActiveTurnError(+ sessionId: string,+ state: SessionInputState,+ ): boolean {+ const active = state.activeTurn;+ if (!active || !isActiveTurnDispatched(active)) return false;+ if (this.deps.isLiveSessionPresent?.(sessionId) !== true) return false;+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ return (+ observed?.kind === 'error' &&+ this.observedMatchesBoundActiveTurn(active, observed) &&+ !this.isSuppressedObservedError(sessionId, observed)+ );+ }++ private tryReconcileStaleDispatchBoundary(+ sessionId: string,+ state: SessionInputState,+ ): boolean {if (state.abortBoundaryToken ||state.queueAbortPending ||@@ -3628,13 +3923,14 @@ export class AgentInputCoordinator {const leftoverActiveTurn = state.activeTurn !== null;const trackerBusy = this.deps.isTurnRunning(sessionId);- const reclaimLeftover =- leftoverActiveTurn && this.canReclaimLeftoverActiveTurn(sessionId, state);- if (leftoverActiveTurn && !reclaimLeftover) {+ const reclaimLeftover = leftoverActiveTurn && this.canReclaimLeftoverActiveTurn(sessionId, state);+ const recoverLeftoverError =+ leftoverActiveTurn && this.canRecoverLeftoverActiveTurnError(sessionId, state);+ if (leftoverActiveTurn && !reclaimLeftover && !recoverLeftoverError) {state.staleLiveIdleSinceMs = null;return false;}- if (!trackerBusy && !reclaimLeftover) {+ if (!trackerBusy && !reclaimLeftover && !recoverLeftoverError) {state.staleLiveIdleSinceMs = null;return false;}@@ -3647,15 +3943,49 @@ export class AgentInputCoordinator {return false;}- if (trackerBusy || reclaimLeftover) {+ if (trackerBusy || reclaimLeftover || recoverLeftoverError) {const reconciled = this.deps.reconcileTurnIdle?.(sessionId) === true;if (!reconciled) return false;}+ if (recoverLeftoverError) {+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ const boundGeneration = state.activeTurn?.vendorTurnGeneration ?? null;+ const instanceId = readSessionInstanceId(this.deps.getTurnSessionIdentity?.(sessionId));+ log.warn('reconciling leftover dispatched activeTurn after vendor error', {+ sessionId,+ clientId: state.activeTurn?.item?.clientId ?? null,+ dispatchLifecycle: state.activeTurn?.dispatchLifecycle ?? null,+ boundGeneration,+ });+ state.staleLiveIdleSinceMs = null;+ const signals: Omit<InterruptedTurnErrorSignals, 'message'> = {+ ...(observed?.reason ? { reason: observed.reason } : {}),+ ...(observed?.sdkError ? { sdkError: redactSensitiveText(observed.sdkError) } : {}),+ ...(typeof observed?.errorStatus === 'number' ? { errorStatus: observed.errorStatus } : {}),+ };+ // Apply recovery before fencing. A same-generation meta would make+ // onTurnEvent treat this synthesized error as the leftover we just fenced.+ this.onTurnEvent(+ sessionId,+ 'error',+ redactSensitiveText(observed?.message ?? 'Turn ended with an error'),+ Object.keys(signals).length > 0 ? signals : undefined,+ );+ if (typeof boundGeneration === 'number' && instanceId) {+ const latest = this.getState(sessionId);+ latest.fencedStaleTerminal = { instanceId, generation: boundGeneration };+ }+ return true;+ }if (reclaimLeftover) {- const vendorGeneration = this.deps.getTurnGeneration?.(sessionId);+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ if (observed?.kind === 'error') {+ this.consumeSuppressedObservedError(sessionId, observed);+ }+ const boundGeneration = state.activeTurn?.vendorTurnGeneration ?? null;const instanceId = readSessionInstanceId(this.deps.getTurnSessionIdentity?.(sessionId));- if (typeof vendorGeneration === 'number' && instanceId) {- state.fencedStaleTerminal = { instanceId, generation: vendorGeneration };+ if (typeof boundGeneration === 'number' && instanceId) {+ state.fencedStaleTerminal = { instanceId, generation: boundGeneration };}log.warn('reconciling leftover dispatched activeTurn after vendor idle', {sessionId,@@ -3824,6 +4154,7 @@ export class AgentInputCoordinator {dispatchLifecycle: 'preparing',pendingTerminalEvent: null,continuationOwnerClientId: isUiContinuationItem(head) ? head.clientId : null,+ vendorTurnGeneration: null,};state.activeTurn = active;this.emit(sessionId);@@ -3893,6 +4224,8 @@ export class AgentInputCoordinator {messageUuid: active.messageUuid,userName: head.userName,throwOnStartFailure: true,+ onVendorTurnReserved: (generation) =>+ this.captureReservedVendorGeneration(sessionId, active, generation),...(head.autoResume && typeof head.autoResumeInfo?.sessionTotal === 'number'? { turnAttemptToken: head.autoResumeInfo.sessionTotal }: {}),@@ -3969,7 +4302,7 @@ export class AgentInputCoordinator {this.handleSendNotDispatched(sessionId, active, head, result);return;}- active.dispatchLifecycle = 'dispatched';+ this.markActiveTurnDispatched(sessionId, active);// 派发成功 = 凭证切换等待(若有)结束。this.clearCredentialSwitchWait(this.getState(sessionId));// vendor dispatch 已不可逆:此时再 durable-ack 旧中断。onAccepted 仍可能@@ -5448,8 +5781,40 @@ export class AgentInputCoordinator {}private settlePendingTerminalEventAfterPersist(sessionId: string, active: ActiveTurn): void {- const terminalEvent = active.pendingTerminalEvent;+ let terminalEvent = active.pendingTerminalEvent;if (!terminalEvent || !this.isActiveTurnCurrent(sessionId, active)) return;+ if (terminalEvent.type === 'done') {+ const deferredError = this.boundObservedTerminalError(sessionId, active);+ if (deferredError) {+ terminalEvent = {+ type: 'error',+ message: deferredError.message,+ signals: deferredError.signals,+ };+ } else {+ const observed = this.readObservedCurrentTurnTerminal(sessionId);+ if (+ observed?.kind === 'error' &&+ !this.observedMatchesBoundActiveTurn(active, observed)+ ) {+ log.warn(+ 'ignored deferred turn-done while leftover activeTurn does not match observed error',+ {+ sessionId,+ clientId: active.item?.clientId ?? null,+ boundGeneration: active.vendorTurnGeneration ?? null,+ observedGeneration: observed.generation ?? null,+ },+ );+ active.pendingTerminalEvent = null;+ this.emit(sessionId);+ return;+ }+ if (this.consumeSuppressedObservedError(sessionId, observed)) {+ // Planned-upgrade suppression: settle as successful done below.+ }+ }+ }active.pendingTerminalEvent = null;const state = this.getState(sessionId);state.activeTurn = null;diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex e84c21dd1d..cd37e543cf 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -46,6 +46,8 @@ type MakerSendOptions = {*/ackInterruptedTurnOnDispatch?: boolean;signal?: AbortSignal;+ /** Coordinator leftover reclaim: capture vendor generation at Session reservation. */+ onVendorTurnReserved?: (generation: number) => void;/*** scheduler 排队消息的来源标记(coordinator drain 透传,见 AgentInputSendOpts.origin)。* 打到 sess.send 的 origin(本轮 turnOrigin)并合进落库 user 消息 agentMeta.origin。@@ -943,6 +945,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakethrowOnStartFailure: so.throwOnStartFailure,turnAttemptToken: so.turnAttemptToken,signal: so.signal,+ ...(so.onVendorTurnReserved+ ? { onTurnReserved: so.onVendorTurnReserved }+ : {}),// scheduler 排队消息:origin 打到本轮 turnOrigin(IM 转播识别自动 turn),// 与 runner 直发路径的 session.send({ origin }) 语义对齐。...(so.origin ? { origin: so.origin } : {}),diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d62b46ee34..96a98787c5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4254,7 +4254,13 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// invalid api key / 401 的情形。本地会话(无 remoteHostId)无 auto-retry,不跳过。isRemoteAuthRetry = isRemoteAuthRetryErrorEvent(session, event);isGatewayProxyTokenRecovery = isGatewayProxyTokenRecoveryErrorEvent(session.id, event);- if (!isPlannedUpgradeClose) {+ if (isPlannedUpgradeClose) {+ agentInputCoordinatorHolder?.noteSuppressedTerminalError(session.id, {+ generation: event.sessionTurnGeneration,+ reason: 'remote_daemon_closed',+ instanceId: event.sessionInstanceId ?? session.instanceId,+ });+ } else {agentInputCoordinatorHolder?.onTurnEvent(session.id,'error',@@ -12885,6 +12891,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},getTurnGeneration: (sessionId) =>getStableSessionForTurnBoundary(sessionId)?.getTurnGeneration() ?? null,+ getObservedCurrentTurnTerminal: (sessionId) => {+ const lookup = lookupStableSessionForTurnBoundary(sessionId);+ if (lookup.status !== 'found') return undefined;+ try {+ return lookup.session.getObservedCurrentTurnTerminal();+ } catch {+ return undefined;+ }+ },getTurnSessionIdentity: (sessionId) => getStableSessionForTurnBoundary(sessionId) ?? null,reconcileTurnIdle: (sessionId) => {// steer 拿到 maker-core 权威 NO_ACTIVE_TURN、或 abort 已让 vendor 停止diff --git a/packages/maker-core/src/session-control.test.ts b/packages/maker-core/src/session-control.test.tsindex 3a59322a97..3f3d5f7951 100644--- a/packages/maker-core/src/session-control.test.ts+++ b/packages/maker-core/src/session-control.test.ts@@ -1,12 +1,13 @@import { describe, expect, it, vi } from 'vitest';import { Session } from './session.js';-import type { AgentSessionHandle } from './agents/base-agent.js';+import { TurnDispatchRejectedError, type AgentSessionHandle } from './agents/base-agent.js';import type {AgentEvent,InteractionDecision,InteractionRequest,InteractionResolver,+ SendOrigin,} from './types/events.js';function createLogger() {@@ -84,10 +85,13 @@ function createHandle(opts?: {};}-function createSession(stub: ReturnType<typeof createHandle>): Session {+function createSession(+ stub: ReturnType<typeof createHandle>,+ agentKind: Session['agentKind'] = 'claude-code',+): Session {return new Session({id: 'session-control',- agentKind: 'claude-code',+ agentKind,workDir: '/repo',handle: stub.handle,capabilities: {} as never,@@ -539,3 +543,766 @@ describe('Session graceful-stop control state', () => {expect(stub.requestGracefulStop).not.toHaveBeenCalled();});});++describe('Session current-generation terminal observation', () => {+ it('reports done until the next reservation, and keeps error ahead of a paired done tail', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const firstDone = waitForSessionEvent(session, 'done');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({ type: 'done', data: {} });+ await firstDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 1 });++ const secondSend = session.send('second');+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ await expect(secondSend).resolves.toEqual({ accepted: true });+ const secondError = waitForSessionEvent(session, 'error');+ stub.push({+ type: 'error',+ data: {+ message: 'Authorization: Bearer secret-token',+ isTerminal: true,+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ },+ });+ await secondError;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 2,+ message: 'Authorization: [REDACTED]',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });+ stub.push({ type: 'done', data: {} });+ await vi.waitFor(() => expect(session.isTurnRunning()).toBe(false));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 2,+ message: 'Authorization: [REDACTED]',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });+ });++ it('ignores background terminals when recording foreground evidence', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({ type: 'done', data: {}, turnScope: 'background' });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ const firstDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await firstDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 1 });+ });++ it('restores terminal evidence when a later send is rejected before dispatch', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ const firstDone = waitForSessionEvent(session, 'done');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({ type: 'done', data: {} });+ await firstDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 1 });++ stub.handle.send = vi.fn(async () => {+ throw new TurnDispatchRejectedError('provider rejected before acceptance');+ });+ await expect(session.send('second')).resolves.toEqual({+ accepted: false,+ reason: 'provider-rejected-before-dispatch',+ });+ expect(session.getTurnGeneration()).toBe(1);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 1 });+ });++ it('promotes a prior-generation terminal that arrives while a later send is rejected', async () => {+ const cases: Array<{+ event: AgentEvent;+ expected: ReturnType<Session['getObservedCurrentTurnTerminal']>;+ }> = [+ {+ event: { type: 'done', data: {} },+ expected: { kind: 'done', generation: 1 },+ },+ {+ event: {+ type: 'error',+ data: {+ message: 'Authorization: Bearer secret-token',+ isTerminal: true,+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ },+ },+ expected: {+ kind: 'error',+ generation: 1,+ message: 'Authorization: [REDACTED]',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ },+ },+ ];++ for (const testCase of cases) {+ const stub = createHandle();+ const session = createSession(stub);+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ stub.handle.isTurnRunning = () => false;+ stub.handle.send = vi.fn(async () => {+ throw new TurnDispatchRejectedError('provider rejected before acceptance');+ });++ await expect(+ session.send('second', {+ afterTurnReserved: async () => {+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ stub.push(testCase.event);+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ },+ }),+ ).resolves.toEqual({+ accepted: false,+ reason: 'provider-rejected-before-dispatch',+ });+ expect(session.getTurnGeneration()).toBe(1);+ expect(session.getObservedCurrentTurnTerminal()).toEqual(testCase.expected);+ }+ });++ it('promotes a prior-generation error that arrives during a rejected handle.send', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.handle.isTurnRunning = () => false;++ let rejectSend!: (error: Error) => void;+ const pendingSend = new Promise<void>((_, reject) => {+ rejectSend = reject;+ });+ stub.handle.send = vi.fn(() => pendingSend);++ const secondSend = session.send('second');+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ stub.push({+ type: 'error',+ data: {+ message: 'Authorization: Bearer secret-token',+ isTerminal: true,+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ rejectSend(new TurnDispatchRejectedError('provider rejected before acceptance'));+ await expect(secondSend).resolves.toEqual({+ accepted: false,+ reason: 'provider-rejected-before-dispatch',+ });+ expect(session.getTurnGeneration()).toBe(1);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'Authorization: [REDACTED]',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });+ await expect(session.send('third')).rejects.toMatchObject({ code: 'SESSION_RUNNING' });++ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'Authorization: [REDACTED]',+ reason: 'empty-response',+ sdkError: 'server_error',+ errorStatus: 529,+ });++ stub.handle.send = vi.fn(async () => undefined);+ await expect(session.send('third')).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ });++ it('does not adopt a late paired done while the next handle.send is still pending', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'turn failed',+ reason: 'empty-response',+ });++ let releaseSend!: () => void;+ const pendingSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ stub.handle.send = vi.fn(() => pendingSend);++ const secondSend = session.send('second');+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ releaseSend();+ await expect(secondSend).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ stub.push({ type: 'status', data: { isRunning: true } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });++ it('does not adopt a late paired done after handle.send flips running and releases reservation', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'turn failed',+ reason: 'empty-response',+ });++ let releaseSend!: () => void;+ const pendingSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ stub.handle.send = vi.fn(() => pendingSend);++ const secondSend = session.send('second');+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ stub.handle.isTurnRunning = () => true;+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ releaseSend();+ await expect(secondSend).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const secondError = waitForSessionEvent(session, 'error');+ stub.push({+ type: 'error',+ data: {+ message: 'n+1 failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await secondError;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 2,+ message: 'n+1 failed',+ reason: 'empty-response',+ });+ });++ it('does not let a leftover error rewrite an accepted later success after reservation release', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;++ let releaseSend!: () => void;+ const pendingSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ stub.handle.send = vi.fn(() => pendingSend);+ const secondSend = session.send('second');+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ stub.handle.isTurnRunning = () => true;+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ releaseSend();+ await expect(secondSend).resolves.toEqual({ accepted: true });++ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });++ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });++ it('does not fan-out a late leftover error after the current generation recorded done', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const seen: AgentEvent[] = [];+ session.onEvent((event) => {+ seen.push({ ...event });+ });+ const onTerminal = vi.fn();+ session.setTurnLifecycleObserver({+ beforeProviderStart() {},+ onUndispatched() {},+ onTerminal,+ });++ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;++ stub.handle.send = vi.fn(async () => undefined);+ await expect(session.send('second')).resolves.toEqual({ accepted: true });+ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ const terminalsAfterDone = onTerminal.mock.calls.length;+ const seenAfterDone = seen.length;++ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ expect(seen.slice(seenAfterDone).some((event) => event.type === 'error')).toBe(false);+ expect(onTerminal.mock.calls.length).toBe(terminalsAfterDone);+ expect(+ onTerminal.mock.calls.some((call) => call[0]?.event?.type === 'error'+ && (call[0]?.event?.data as { message?: string } | undefined)?.message === 'late prior error'),+ ).toBe(false);+ });++ it('still fans out a current-generation terminal error when no done snapshot exists', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const seen: AgentEvent[] = [];+ session.onEvent((event) => {+ seen.push({ ...event });+ });+ const onTerminal = vi.fn();+ session.setTurnLifecycleObserver({+ beforeProviderStart() {},+ onUndispatched() {},+ onTerminal,+ });++ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'current turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'current turn failed',+ reason: 'empty-response',+ });+ expect(seen.some((event) => event.type === 'error')).toBe(true);+ expect(onTerminal).toHaveBeenCalledWith(expect.objectContaining({+ turnGeneration: 1,+ isCurrentGeneration: true,+ event: expect.objectContaining({ type: 'error' }),+ }));+ });++ it('does not fan-out a reservation-window leftover error as the next generation', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const seen: AgentEvent[] = [];+ session.onEvent((event) => {+ seen.push({ ...event });+ });+ const onTerminal = vi.fn();+ session.setTurnLifecycleObserver({+ beforeProviderStart() {},+ onUndispatched() {},+ onTerminal,+ });++ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'turn failed',+ reason: 'empty-response',+ });++ let releaseSend!: () => void;+ const pendingSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ stub.handle.send = vi.fn(() => pendingSend);+ const secondSend = session.send('second');+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ const seenAfterReserve = seen.length;+ const terminalsAfterReserve = onTerminal.mock.calls.length;++ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ // In-flight error after N already observed error is N+1 start-failure.+ // Leftover fence only applies to terminals attributed to a prior generation.+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({+ kind: 'error',+ generation: 2,+ message: 'late prior error',+ });+ expect(session.getTurnGeneration()).toBe(2);+ expect(seen.slice(seenAfterReserve).some((event) => event.type === 'error')).toBe(true);+ expect(onTerminal.mock.calls.length).toBeGreaterThan(terminalsAfterReserve);+ expect(+ seen.some((event) =>+ event.type === 'error' &&+ event.sessionTurnGeneration === 2 &&+ (event.data as { message?: string }).message === 'late prior error'),+ ).toBe(true);++ releaseSend();+ await expect(secondSend).resolves.toEqual({ accepted: true });+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({+ kind: 'error',+ generation: 2,+ });+ });++ it('keeps N+1 origin and attempt token after a leftover paired done in the reservation window', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const seen: AgentEvent[] = [];+ session.onEvent((event) => {+ seen.push({ ...event });+ });+ const firstOrigin: SendOrigin = { kind: 'scheduler', scheduleId: 'n', scheduleName: 'n' };+ const nextOrigin: SendOrigin = { kind: 'scheduler', scheduleId: 'n1', scheduleName: 'n1' };++ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first', { origin: firstOrigin })).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;++ let releaseSend!: () => void;+ const pendingSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ stub.handle.send = vi.fn(() => pendingSend);+ const secondSend = session.send('second', {+ origin: nextOrigin,+ turnAttemptToken: 7,+ });+ await vi.waitFor(() => expect(stub.handle.send).toHaveBeenCalled());+ expect(session.getTurnGeneration()).toBe(2);++ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ expect(+ seen.some((event) => event.type === 'done' && event.sessionTurnGeneration === 2),+ ).toBe(false);++ releaseSend();+ await expect(secondSend).resolves.toEqual({ accepted: true });+ const secondText = waitForSessionEvent(session, 'text');+ stub.push({ type: 'text', data: { text: 'n+1', isFinal: false } });+ await secondText;+ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;++ const n1Events = seen.filter((event) => event.sessionTurnGeneration === 2);+ expect(n1Events.some((event) => event.type === 'text')).toBe(true);+ expect(n1Events.some((event) => event.type === 'done')).toBe(true);+ expect(n1Events.every((event) => event.turnOrigin)).toEqual(true);+ expect(n1Events.map((event) => event.turnOrigin)).toEqual(+ n1Events.map(() => nextOrigin),+ );+ expect(n1Events.every((event) => event.turnAttemptToken === 7)).toBe(true);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });++ it('binds an accepted result-only done when the prior paired done was lost', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'turn failed',+ reason: 'empty-response',+ });++ stub.handle.send = vi.fn(async () => undefined);+ await expect(session.send('second')).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });++ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });++ it('binds an accepted result-only done after the prior error tail is already attributed', async () => {+ const stub = createHandle();+ const session = createSession(stub, 'codex');+ const firstError = waitForSessionEvent(session, 'error');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({+ type: 'error',+ data: {+ message: 'turn failed',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await firstError;+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.push({ type: 'status', data: { isRunning: false } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ stub.handle.isTurnRunning = () => false;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'turn failed',+ reason: 'empty-response',+ });++ stub.handle.send = vi.fn(async () => undefined);+ await expect(session.send('second')).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });++ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });++ it('does not inherit a reservation-window terminal after a later send is accepted', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.handle.isTurnRunning = () => false;+ stub.handle.send = vi.fn(async () => undefined);++ await expect(+ session.send('second', {+ afterTurnReserved: async () => {+ stub.push({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ },+ }),+ ).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ });++ it('does not treat a late prior-generation error as the next reserved turn terminal', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ const firstDone = waitForSessionEvent(session, 'done');+ await expect(session.send('first')).resolves.toEqual({ accepted: true });+ stub.push({ type: 'done', data: {} });+ await firstDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 1 });++ stub.handle.isTurnRunning = () => false;+ stub.handle.send = vi.fn(async () => undefined);+ await expect(+ session.send('second', {+ afterTurnReserved: async () => {+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ stub.push({+ type: 'error',+ data: {+ message: 'late prior error',+ isTerminal: true,+ reason: 'empty-response',+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ },+ }),+ ).resolves.toEqual({ accepted: true });+ expect(session.getTurnGeneration()).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });++ const secondDone = waitForSessionEvent(session, 'done');+ stub.push({ type: 'done', data: {} });+ await secondDone;+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'done', generation: 2 });+ });+});diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex 6d0217796a..26f110278f 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -5,7 +5,7 @@* turn 终止后清空、下一轮不被污染、多 listener 一致。这是 IM 转播自动任务的地基* (共享 session 下区分"这一轮是谁发起的")。*/-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import path from 'node:path';import { Session } from './session.js';@@ -39,12 +39,21 @@ function createControllableHandle(opts?: {holdDispatch?: boolean;holdOnSend?: number;}) {- let push: ((e: AgentEvent) => void) | null = null;+ let waiter: ((e: AgentEvent | null) => void) | null = null;let turnRunning = false;let closeCalls = 0;let releaseDispatch: (() => void) | null = null;let sendCount = 0;- const buffered: AgentEvent[] = [];+ const pending: Array<AgentEvent | null> = [];+ const deliver = (event: AgentEvent | null) => {+ if (waiter) {+ const resolve = waiter;+ waiter = null;+ resolve(event);+ return;+ }+ pending.push(event);+ };const continuationStates = new Map<number, TurnContinuationState>();let interactionResolver: ((req: InteractionRequest) => Promise<InteractionDecision>) | null = null;let lastSendOptions: SendOptions | undefined;@@ -60,8 +69,7 @@ function createControllableHandle(opts?: {throw opts.sendError; // 模拟 dispatch 失败(SESSION_RUNNING race)}if (opts?.dispatchEvent && (opts.dispatchOnSend ?? 1) === sendCount) {- if (push) push(opts.dispatchEvent);- else buffered.push(opts.dispatchEvent);+ deliver(opts.dispatchEvent);}if (opts?.holdDispatch && (opts.holdOnSend ?? 1) === sendCount) {await new Promise<void>((resolve) => {@@ -77,12 +85,15 @@ function createControllableHandle(opts?: {turnRunning = false;},async *events() {- for (const e of buffered) yield e;- buffered.length = 0;for (;;) {- const next = await new Promise<AgentEvent | null>((resolve) => {- push = (e) => resolve(e);- });+ let next: AgentEvent | null;+ if (pending.length > 0) {+ next = pending.shift() ?? null;+ } else {+ next = await new Promise<AgentEvent | null>((resolve) => {+ waiter = resolve;+ });+ }if (next === null) return;yield next;}@@ -114,8 +125,7 @@ function createControllableHandle(opts?: {e.type === 'error' &&(e.data as { isTerminal?: unknown } | null | undefined)?.isTerminal === true;if ((e.type === 'done' || terminalError) && !opts.keepRunning) turnRunning = false;- if (push) push(e);- else buffered.push(e);+ deliver(e);await new Promise((r) => setTimeout(r, 0)); // 让事件循环把它 fan-out 出去},setTurnRunning(running: boolean) {@@ -128,8 +138,7 @@ function createControllableHandle(opts?: {releaseDispatch?.();},queue(event: AgentEvent) {- if (push) push(event);- else buffered.push(event);+ deliver(event);},closeCalls: () => closeCalls,lastSendOptions: () => lastSendOptions,@@ -363,7 +372,155 @@ describe('Session per-turn origin 打标', () => {await session.close();});- it('prior-turn next() still stamps an in-flight Codex start-failure as the new generation', async () => {+ it('does not let an unobserved prior error adopt an in-flight send as N+1', 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 vi.waitFor(() => {+ expect(+ seen.some((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed'),+ ).toBe(true);+ });+ const startFail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ releaseDispatch();+ await second;+ await session.close();+ });++ it('does not let leftover N running promote a later N error onto unaccepted N+1', 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: 'status', data: { isRunning: true }, source: 'codex' });+ await new Promise((resolve) => setTimeout(resolve, 0));+ const second = session.send('second');+ await new Promise((resolve) => setTimeout(resolve, 0));+ await emit({+ type: 'error',+ data: { message: 'first late failure', isTerminal: true },+ source: 'codex',+ });+ expect(+ seen.some((event) =>+ event.type === 'error' && event.sessionTurnGeneration === 2),+ ).toBe(false);+ expect(+ seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'first late failure')+ ?.sessionTurnGeneration,+ ).not.toBe(2);+ releaseDispatch();+ await second;+ await session.close();+ });++ it('keeps an in-flight N+1 start-failure after handle running releases the reservation', 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 originalSend = handle.send.bind(handle);+ handle.send = async (...args) => {+ setTurnRunning(true);+ return originalSend(...args);+ };+ 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 vi.waitFor(() => {+ expect(+ seen.some((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed'),+ ).toBe(true);+ });+ const startFail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ releaseDispatch();+ await second;+ await session.close();+ });++ it('keeps an in-flight N+1 start-failure before a leftover N error', 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 vi.waitFor(() => {+ expect(+ seen.some((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed'),+ ).toBe(true);+ });+ const startFail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });+ await emit({+ type: 'error',+ data: { message: 'first late failure', isTerminal: true },+ source: 'codex',+ });+ const late = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'first late failure');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ releaseDispatch();+ await second;+ await session.close();+ });++ it('still stamps an in-flight start-failure after the prior turn already observed done', async () => {const { handle, emit, setTurnRunning, releaseDispatch } = createControllableHandle({dispatchEvent: {type: 'error',@@ -380,6 +537,7 @@ describe('Session per-turn origin 打标', () => {await session.send('first');await emit({ type: 'text', data: { text: 'first progress', isFinal: false } });+ await emit({ type: 'done', data: {} });setTurnRunning(false);const second = session.send('second');await new Promise((resolve) => setTimeout(resolve, 0));@@ -393,6 +551,81 @@ describe('Session per-turn origin 打标', () => {await session.close();});+ it('fans out an in-flight N+1 start-failure after N already observed error', 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: 'error',+ data: { message: 'first failed', isTerminal: true },+ source: 'codex',+ });+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });+ setTurnRunning(false);+ const second = session.send('second');+ await vi.waitFor(() => {+ expect(+ seen.some((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed'),+ ).toBe(true);+ });+ const startFail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({ kind: 'error', generation: 2 });+ releaseDispatch();+ await second;+ await session.close();+ });++ it('records an in-flight N+1 start-failure after N went idle without a terminal', 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 } });+ await emit({ type: 'status', data: { isRunning: false }, source: 'codex' });+ setTurnRunning(false);+ expect(session.getObservedCurrentTurnTerminal()).toEqual({ kind: 'none' });+ const second = session.send('second');+ await vi.waitFor(() => {+ expect(+ seen.some((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed'),+ ).toBe(true);+ });+ const startFail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(startFail?.sessionTurnGeneration).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({ kind: 'error', generation: 2 });+ 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,@@ -434,8 +667,8 @@ describe('Session per-turn origin 打标', () => {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: 'status', data: { isRunning: true }, source: 'codex' });await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });expect(seen.some((event) => event.type === 'done')).toBe(false);@@ -523,6 +756,60 @@ describe('Session per-turn origin 打标', () => {await session.close();});+ it('lets a result-only N+1 done settle after leftover idle then current running', 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: 'status', data: { isRunning: true }, source: 'codex' });+ await emit({ type: 'done', data: {} });+ const liveDone = seen.find((event) => event.type === 'done');+ expect(liveDone?.sessionTurnGeneration).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({ kind: 'done', generation: 2 });+ releaseDispatch();+ await second;+ await session.close();+ });++ it('keeps an accepted result-only N+1 error after a leftover idle tail', 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' });+ releaseDispatch();+ await second;+ await emit({+ type: 'error',+ data: { message: 'second failed', isTerminal: true },+ source: 'codex',+ });+ const fail = seen.find((event) =>+ event.type === 'error' && (event.data as { message?: string }).message === 'second failed');+ expect(fail?.sessionTurnGeneration).toBe(2);+ expect(session.getObservedCurrentTurnTerminal()).toMatchObject({ kind: 'error', generation: 2 });+ 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,@@ -566,8 +853,8 @@ describe('Session per-turn origin 打标', () => {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: 'status', data: { isRunning: true }, source: 'codex' });await emit({ type: 'text', data: { text: 'second progress', isFinal: false } });expect(seen.some((event) => event.type === 'done')).toBe(false);@@ -1200,6 +1487,11 @@ describe('Session per-turn origin 打标', () => {expect(rawError.message).toBe('client_secret=[REDACTED]');expect(rawError.additionalDetails).toBe('key=[REDACTED]');}+ expect(session.getObservedCurrentTurnTerminal()).toEqual({+ kind: 'error',+ generation: 1,+ message: 'Authorization: [REDACTED]',+ });});it('preserves a non-secret auth status and redacts nested Codex error details', async () => {diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 3ddbbc1552..7ac3e03230 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -296,6 +296,8 @@ export interface SessionSendOptions extends SendOptions {* hook 完成后才启动 vendor handle。*/onAccepted?: () => void | Promise<void>;+ /** Reservation 建立后立刻回调本轮 turn generation;host 必须用它绑定 leftover,不能等 send 返回后再读最新 generation。 */+ onTurnReserved?: (turnGeneration: number) => void;/*** vendor dispatch 前最后一个同步边界。用于让 host 在底层可能产生新 turn* callback 之前,精确切换自己的 turn-scoped 状态。@@ -355,6 +357,8 @@ type TurnControlState = {type SendReservation = {generation: number;phase: 'accepting' | 'dispatching';+ /** handle.send() has resolved as accepted. Until then, late N terminals stay off N+1. */+ accepted: boolean;cancelled: boolean;abortController: AbortController;settled: Promise<SendReservationOutcome>;@@ -372,6 +376,7 @@ function createSendReservation(generation: number): SendReservation {return {generation,phase: 'accepting',+ accepted: false,cancelled: false,abortController: new AbortController(),settled,@@ -420,20 +425,56 @@ export class Session {* 开始等待、下一轮 dispatch 后才返回旧事件,不能用一个 bool 判断是否已收口。*/private terminalEventObservedGeneration: number | null = null;+ /** 与 terminalEventObservedGeneration 成对;同 generation 的 error 不被后续 done 尾巴改写。 */+ private terminalEventObservedKind: 'done' | 'error' | null = null;+ private terminalEventObservedErrorMessage: string | null = null;+ private terminalEventObservedErrorSignals: {+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } | null = null;+ /** Survives N+1 reservation clearing the current snapshot; leftover done must not adopt. */+ private lastObservedTerminalGeneration: number | null = null;+ private lastObservedTerminalKind: 'done' | 'error' | null = null;+ /**+ * N+1 reservation 窗口内观察到的前一轮前台终态。lost-callback 时 turn N 的+ * done/error 可能在直接 N+1 `handle.send()` 待处理期间才 fan-out;当时+ * `turnGeneration` 已是 N+1,不能写入当前 generation 快照。拒绝回滚时再提升+ * 到 N,避免 leftover `activeTurn` 永久失去回收证据。+ */+ private terminalObservedDuringReservation: {+ kind: 'done' | 'error';+ message: string | null;+ signals: {+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } | null;+ } | null = null;/** 终态 error 后等待 provider 尾部 done;避免旧尾事件冒领下一轮。 */private terminalErrorDrainGeneration: number | null = null;private terminalErrorDrainTimer: ReturnType<typeof setTimeout> | null = null;private sendReservation: SendReservation | null = null;+ /**+ * N+1 send that has reserved a generation but not yet accepted.+ * Survives `releaseSendReservationIfObserved()` clearing the reservation+ * after the handle flips running; leftover N tails must not adopt as N+1.+ */+ private unacceptedSendGeneration: number | 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;+ /** Last resolve() returned the in-flight send generation. */+ private lastResolvedInFlightSend = 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;+ /** Generation that already emitted foreground running. */+ private sawCurrentTurnRunningGeneration: number | null = null;/*** 当前进行中 turn 的发起来源(来自 send 的 opts.origin)。事件 fan-out 前打到* AgentEvent.turnOrigin 上,turn 终止(isTerminalTurnEvent)后清空 — 共享@@ -522,8 +563,129 @@ export class Session {return this.turnGeneration;}+ /**+ * 当前 turn generation 已 fan-out 的产品终态类型。+ * none:PI prompt accepted → agent_start 空窗、continuation claim 挡住的 SDK done、+ * 或尚无当前 generation 终态。Host 回收残留 activeTurn 必须认类型:done 才能当+ * 成功结算,error 必须走 recovery,不能靠 live idle + tracker idle 的超时猜测。+ */+ getObservedCurrentTurnTerminal(): {+ kind: 'none' | 'done' | 'error';+ generation?: number;+ message?: string;+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } {+ if (+ this.turnGeneration <= 0 ||+ this.terminalEventObservedGeneration !== this.turnGeneration ||+ this.terminalEventObservedKind == null+ ) {+ return { kind: 'none' };+ }+ if (this.terminalEventObservedKind === 'error') {+ return {+ kind: 'error',+ generation: this.turnGeneration,+ ...(this.terminalEventObservedErrorMessage+ ? { message: redactSensitiveText(this.terminalEventObservedErrorMessage) }+ : {}),+ ...(this.terminalEventObservedErrorSignals?.reason+ ? { reason: this.terminalEventObservedErrorSignals.reason }+ : {}),+ ...(this.terminalEventObservedErrorSignals?.sdkError+ ? { sdkError: redactSensitiveText(this.terminalEventObservedErrorSignals.sdkError) }+ : {}),+ ...(typeof this.terminalEventObservedErrorSignals?.errorStatus === 'number'+ ? { errorStatus: this.terminalEventObservedErrorSignals.errorStatus }+ : {}),+ };+ }+ return { kind: 'done', generation: this.turnGeneration };+ }++ private readRedactedTerminalErrorSnapshot(listenerEvent: AgentEvent): {+ message: string | null;+ signals: {+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } | null;+ } {+ const errorData = (listenerEvent.data ?? null) as {+ message?: unknown;+ reason?: unknown;+ sdkError?: unknown;+ errorStatus?: unknown;+ } | null;+ const errorMessage = errorData?.message;+ const signals: {+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } = {};+ if (typeof errorData?.reason === 'string' && errorData.reason.length > 0) {+ signals.reason = errorData.reason;+ }+ if (typeof errorData?.sdkError === 'string' && errorData.sdkError.length > 0) {+ signals.sdkError = redactSensitiveText(errorData.sdkError);+ }+ if (typeof errorData?.errorStatus === 'number' && Number.isFinite(errorData.errorStatus)) {+ signals.errorStatus = errorData.errorStatus;+ }+ return {+ message: typeof errorMessage === 'string' && errorMessage.length > 0 ? errorMessage : null,+ signals:+ signals.reason || signals.sdkError || signals.errorStatus !== undefined ? signals : null,+ };+ }++ private rememberReservationWindowPriorTerminal(+ event: AgentEvent,+ listenerEvent: AgentEvent,+ ): void {+ if (event.type === 'error') {+ const snapshot = this.readRedactedTerminalErrorSnapshot(listenerEvent);+ this.terminalObservedDuringReservation = {+ kind: 'error',+ message: snapshot.message,+ signals: snapshot.signals,+ };+ return;+ }+ if (event.type !== 'done') return;+ if (this.terminalObservedDuringReservation?.kind === 'error') return;+ this.terminalObservedDuringReservation = {+ kind: 'done',+ message: null,+ signals: null,+ };+ }++ private consumeReservationWindowPriorTerminal(): {+ kind: 'done' | 'error';+ message: string | null;+ signals: {+ reason?: string;+ sdkError?: string;+ errorStatus?: number;+ } | null;+ } | null {+ const snapshot = this.terminalObservedDuringReservation;+ this.terminalObservedDuringReservation = null;+ return snapshot;+ }+async send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult> {- const { afterTurnReserved, beforeProviderStart, onAccepted, onDispatching, ...handleOpts } = opts ?? {};+ const {+ afterTurnReserved,+ beforeProviderStart,+ onAccepted,+ onDispatching,+ onTurnReserved,+ ...handleOpts+ } = opts ?? {};const cancelledBeforeReservation = (): SessionSendResult | null =>handleOpts.signal?.aborted === true? { accepted: false, reason: 'cancelled-before-dispatch' }@@ -579,6 +741,14 @@ export class Session {// 新一轮 turn 的代号(见 turnGeneration):看门狗的善后动作据此判断"还是不是那个// 卡死的 turn",避免误杀宽限期内新起的健康 turn。const previousTurnGeneration = this.turnGeneration;+ const previousTerminalObservation = {+ generation: this.terminalEventObservedGeneration,+ kind: this.terminalEventObservedKind,+ message: this.terminalEventObservedErrorMessage,+ signals: this.terminalEventObservedErrorSignals+ ? { ...this.terminalEventObservedErrorSignals }+ : null,+ };this.turnGeneration += 1;if (previousTurnGeneration > 0 &&@@ -591,6 +761,9 @@ export class Session {const reservedTurnGeneration = this.turnGeneration;const reservation = createSendReservation(reservedTurnGeneration);this.sendReservation = reservation;+ this.unacceptedSendGeneration = reservedTurnGeneration;+ this.terminalObservedDuringReservation = null;+ onTurnReserved?.(reservedTurnGeneration);const cleanupExternalAbort = this.attachExternalCancellation(reservation, handleOpts.signal);// originInstalled:已越过 dispatch 边界、把本次 origin 装进 currentTurnOrigin。// turnDispatched:handle.send 成功、本次 send 真正成为运行中的 turn。@@ -605,6 +778,9 @@ export class Session {const finishCancelledBeforeDispatch = (): SessionSendResult | null => {if (!reservation.cancelled && this.sendReservation === reservation) return null;if (this.sendReservation === reservation) this.sendReservation = null;+ if (this.unacceptedSendGeneration === reservedTurnGeneration) {+ this.unacceptedSendGeneration = null;+ }return { accepted: false, reason: 'cancelled-before-dispatch' };};try {@@ -661,6 +837,9 @@ export class Session {this.currentTurnOrigin = handleOpts.origin ?? null;if (this.terminalErrorDrainGeneration === null) {this.terminalEventObservedGeneration = null;+ this.terminalEventObservedKind = null;+ this.terminalEventObservedErrorMessage = null;+ this.terminalEventObservedErrorSignals = null;}previousTurnAttemptToken = this.currentTurnAttemptToken;this.currentTurnAttemptToken =@@ -705,6 +884,8 @@ export class Session {// racing after that point may request abort, but cannot rewrite history// and report the turn as undispatched.turnDispatched = true;+ reservation.accepted = true;+ this.unacceptedSendGeneration = null;// turn 真正开始跑 → 起 stall 看门狗。后续每个事件都会重置它,done / 终态// error 会清掉它(见 armTurnStallWatchdog)。this.armTurnStallWatchdog();@@ -713,6 +894,9 @@ export class Session {if (this.sendReservation === reservation) {this.sendReservation = null;}+ if (this.unacceptedSendGeneration === reservedTurnGeneration) {+ this.unacceptedSendGeneration = null;+ }if (e instanceof TurnDispatchUnconfirmedError) {dispatchUnconfirmed = true;// Reserve Session shutdown before closing the handle. This suppresses@@ -733,6 +917,9 @@ export class Session {if (this.sendReservation === reservation) {this.sendReservation = null;}+ if (this.unacceptedSendGeneration === reservedTurnGeneration) {+ this.unacceptedSendGeneration = null;+ }// 装了 origin 但本次 send 没真正成为运行中的 turn(handle.send 抛错 / dispatch// 后被取消)→ **还原**到 dispatch 前的 origin(而非强制清 null)。// SESSION_RUNNING race:137 行 isTurnRunning 检查通过、但 handle.send 因底层已有@@ -756,6 +943,33 @@ export class Session {}}this.turnGeneration = previousTurnGeneration;+ const reservationWindowTerminal = this.consumeReservationWindowPriorTerminal();+ if (+ !dispatchUnconfirmed &&+ reservationWindowTerminal &&+ previousTurnGeneration > 0+ ) {+ this.terminalEventObservedGeneration = previousTurnGeneration;+ this.terminalEventObservedKind = reservationWindowTerminal.kind;+ this.terminalEventObservedErrorMessage = reservationWindowTerminal.message;+ this.terminalEventObservedErrorSignals = reservationWindowTerminal.signals;+ } else {+ this.terminalEventObservedGeneration = previousTerminalObservation.generation;+ this.terminalEventObservedKind = previousTerminalObservation.kind;+ this.terminalEventObservedErrorMessage = previousTerminalObservation.message;+ this.terminalEventObservedErrorSignals = previousTerminalObservation.signals;+ }+ this.lastObservedTerminalGeneration = this.terminalEventObservedGeneration;+ this.lastObservedTerminalKind = this.terminalEventObservedKind;+ // Confirmed rejection skips the generic tail fence above, but a+ // promoted/restored error still needs the same drain as a live error.+ if (+ this.terminalEventObservedKind === 'error' &&+ typeof this.terminalEventObservedGeneration === 'number' &&+ this.terminalEventObservedGeneration > 0+ ) {+ this.armTerminalErrorDrain(this.terminalEventObservedGeneration);+ }if (previousTurnGeneration > 0 &&this.terminalEventObservedGeneration !== previousTurnGeneration@@ -764,6 +978,8 @@ export class Session {} else {this.pendingPriorGeneration = null;}+ } else {+ this.terminalObservedDuringReservation = null;}if (turnLifecyclePrepared && !turnDispatched) {try {@@ -1088,6 +1304,7 @@ export class Session {closeSucceeded = true;} finally {this.sendReservation = null;+ this.unacceptedSendGeneration = null;this.currentTurnOrigin = null;this.currentTurnAttemptToken = null;this.turnControlState = null;@@ -1129,6 +1346,7 @@ export class Session {detachSucceeded = true;} finally {this.sendReservation = null;+ this.unacceptedSendGeneration = null;this.currentTurnOrigin = null;this.currentTurnAttemptToken = null;this.turnControlState = null;@@ -1807,7 +2025,10 @@ export class Session {return ((event.type === 'done' && !this.isSilentStopDoneEvent(event)) ||this.isIdleStatusEvent(event) ||- (isTerminalAgentErrorEvent(event) && this.staleTerminalQueuedGeneration !== null)+ (isTerminalAgentErrorEvent(event) && (+ this.staleTerminalQueuedGeneration !== null ||+ this.pendingPriorGeneration !== null+ )));}@@ -1828,33 +2049,94 @@ export class Session {observedGeneration: number,event: AgentEvent,): number {+ const attributed = (generation: number): number => {+ if (this.isForegroundRunningStatus(event)) {+ this.sawCurrentTurnRunningGeneration = generation;+ if (generation === this.turnGeneration) {+ this.pendingPriorGeneration = null;+ this.staleTerminalQueuedGeneration = null;+ }+ }+ return generation;+ };+ const inFlightGeneration =+ this.sendReservation?.generation ??+ (this.isUnacceptedCurrentSend() ? this.unacceptedSendGeneration : null);+ this.lastResolvedInFlightSend = false;+ const belongsToInFlightSend =+ this.insideProviderSendSync &&+ this.inFlightSendOwnsBlockedWait &&+ typeof inFlightGeneration === 'number' &&+ inFlightGeneration === this.turnGeneration &&+ this.turnControlState?.generation === inFlightGeneration;if (observedGeneration > waitStartGeneration) {+ // A wait that started on N can adopt N+1 progress, but a queued N+ // error must not ride that adoption into N+1. Errors emitted by the+ // active handle.send() stay on the in-flight generation.+ if (+ isTerminalAgentErrorEvent(event) &&+ this.pendingPriorGeneration !== null &&+ this.pendingPriorGeneration < this.turnGeneration &&+ this.lastObservedTerminalKind !== 'error' &&+ this.sawCurrentTurnRunningGeneration !== this.turnGeneration &&+ this.isUnacceptedCurrentSend() &&+ !belongsToInFlightSend+ ) {+ const prior = this.pendingPriorGeneration;+ this.pendingPriorGeneration = null;+ this.staleTerminalQueuedGeneration = null;+ return attributed(prior);+ }this.staleTerminalQueuedGeneration = null;- if (this.isNewTurnProgressEvent(event)) {+ if (+ this.isNewTurnProgressEvent(event) ||+ this.isForegroundRunningStatus(event) ||+ belongsToInFlightSend+ ) {this.pendingPriorGeneration = null;}- return observedGeneration;+ return attributed(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') {+ const leftoverUnobservedPriorError =+ isTerminalAgentErrorEvent(event) &&+ prior !== null &&+ this.sawCurrentTurnRunningGeneration !== this.turnGeneration &&+ this.isUnacceptedCurrentSend() &&+ (+ !belongsToInFlightSend ||+ this.sawCurrentTurnRunningGeneration === prior+ ) &&+ (event.data as { reason?: string } | undefined)?.reason !== 'session_event_loop_crashed';+ if (prior !== null && (leftoverDoneOrIdle || leftoverUnobservedPriorError) && waitStartGeneration !== 0) {+ if (event.type === 'done' || leftoverUnobservedPriorError) {this.pendingPriorGeneration = null;this.staleTerminalQueuedGeneration = null;} else {this.staleTerminalQueuedGeneration = prior;}- return prior;- }- const leftoverTail = this.isLeftoverTailEvent(event);- if (leftoverTail && this.staleTerminalQueuedGeneration !== null) {+ return attributed(prior);+ }+ const leftoverTail =+ this.isLeftoverTailEvent(event) &&+ !(+ belongsToInFlightSend &&+ isTerminalAgentErrorEvent(event) &&+ this.staleTerminalQueuedGeneration === null+ );+ if (+ leftoverTail &&+ this.staleTerminalQueuedGeneration !== null &&+ this.isUnacceptedCurrentSend()+ ) {const stamped = this.staleTerminalQueuedGeneration;if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {this.staleTerminalQueuedGeneration = null;}- return stamped;+ return attributed(stamped);}if (leftoverTail && waitStartGeneration > 0 && waitStartGeneration < this.turnGeneration) {if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {@@ -1862,18 +2144,25 @@ export class Session {} else {this.staleTerminalQueuedGeneration = waitStartGeneration;}- return waitStartGeneration;+ return attributed(waitStartGeneration);+ }+ // N already observed a terminal error. A later error/done in the N+1+ // unaccepted send window is leftover N, not an in-flight N+1 start-failure.+ if (+ !belongsToInFlightSend &&+ waitStartGeneration > 0 &&+ waitStartGeneration < this.turnGeneration &&+ this.lastObservedTerminalGeneration === waitStartGeneration &&+ this.lastObservedTerminalKind === 'error' &&+ (event.type === 'done' || isTerminalAgentErrorEvent(event))+ ) {+ this.staleTerminalQueuedGeneration = null;+ return attributed(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;+ this.lastResolvedInFlightSend = true;if (this.isNewTurnProgressEvent(event) ||event.type === 'done' ||@@ -1881,11 +2170,11 @@ export class Session {) {this.pendingPriorGeneration = null;}- return inFlightGeneration;+ return attributed(inFlightGeneration);}if (waitStartGeneration === 0 && this.turnGeneration > 0) {this.staleTerminalQueuedGeneration = null;- return this.turnGeneration;+ return attributed(this.turnGeneration);}if (this.isNewTurnProgressEvent(event)) {// New-turn tokens prove this generation owns later product terminals.@@ -1894,7 +2183,7 @@ export class Session {this.pendingPriorGeneration = null;this.staleTerminalQueuedGeneration = null;}- return waitStartGeneration;+ return attributed(waitStartGeneration);}private fanOutEvent(@@ -1908,6 +2197,7 @@ export class Session {if (event.sessionInstanceId === undefined) {event.sessionInstanceId = this.instanceId;}+ this.lastResolvedInFlightSend = false;if (event.sessionTurnGeneration === undefined) {event.sessionTurnGeneration = this.resolveSessionTurnGeneration(queuedGeneration,@@ -1923,6 +2213,15 @@ export class Session {const isCurrentGeneration =resolvedGeneration === this.turnGeneration &&observedGeneration === this.turnGeneration;+ // In-flight start-failure is stamped N+1 from an older wait. Snapshot and+ // probe must still settle the current send even when observed stays on N.+ const settleAsCurrentGeneration =+ isCurrentGeneration ||+ (+ this.lastResolvedInFlightSend &&+ resolvedGeneration === this.turnGeneration &&+ (this.agentKind === 'codex' || this.agentKind === 'pi')+ );this.observeTurnControl(event, resolvedGeneration);// fan-out 前打 turn origin(所有 listener 拿到同一份);事件对象由 translator// 每次新建、看门狗每次合成,不会串台。=== undefined 守卫:不覆盖 agent 自带的。@@ -1956,13 +2255,53 @@ export class Session {// to it: Codex can enqueue the previous turn's terminal error after flipping// its handle idle. Only runEventLoop's generation adoption may transfer// ownership to the new attempt.- const terminalBoundaryObserved = isCurrentGeneration && isTerminal;- if (terminalBoundaryObserved) {+ const preDispatchReservation = this.isPreDispatchReservation();+ const sameGenerationError =+ this.terminalEventObservedGeneration === this.turnGeneration &&+ this.terminalEventObservedKind === 'error';+ const sameGenerationDone =+ this.terminalEventObservedGeneration === this.turnGeneration &&+ this.terminalEventObservedKind === 'done';+ // A late leftover error must not replace N+1's result-only success,+ // nor fan-out as a current-generation failure to lifecycle / IPC listeners.+ const lateErrorAfterDoneSnapshot = event.type === 'error' && sameGenerationDone;+ const reservationWindowLeftover =+ isTerminal &&+ !isBackgroundEvent &&+ this.isUnacceptedCurrentSend() &&+ resolvedGeneration !== this.turnGeneration &&+ (+ (+ this.lastObservedTerminalKind === 'error' &&+ this.lastObservedTerminalGeneration !== null &&+ this.lastObservedTerminalGeneration < this.turnGeneration+ ) ||+ (+ this.pendingPriorGeneration !== null &&+ this.pendingPriorGeneration < this.turnGeneration &&+ isTerminalAgentErrorEvent(event) &&+ this.sawCurrentTurnRunningGeneration !== this.turnGeneration &&+ resolvedGeneration !== this.turnGeneration+ )+ );+ const terminalBoundaryObserved =+ settleAsCurrentGeneration && isTerminal && !isBackgroundEvent && !preDispatchReservation;+ if (terminalBoundaryObserved && !lateErrorAfterDoneSnapshot && !reservationWindowLeftover) {this.terminalEventObservedGeneration = this.turnGeneration;- if (event.type === 'done') {- this.clearTerminalErrorDrain();- } else if (event.type === 'error') {+ this.lastObservedTerminalGeneration = this.turnGeneration;+ this.lastObservedTerminalKind = event.type === 'error' ? 'error' : 'done';+ if (event.type === 'error') {+ this.terminalEventObservedKind = 'error';this.armTerminalErrorDrain(this.turnGeneration);+ } else {+ // Codex 失败收尾是 terminal error 后再补 done。同 generation 的成功尾巴+ // 不得把已记录的 error 改写成 done,否则 Host 会把失败当成功结算。+ if (!sameGenerationError) {+ this.terminalEventObservedKind = 'done';+ this.terminalEventObservedErrorMessage = null;+ this.terminalEventObservedErrorSignals = null;+ }+ this.clearTerminalErrorDrain();}} else if (this.agentKind === 'codex' &&@@ -1975,14 +2314,46 @@ export class Session {// event. That status drains the provider tail, but it is not itself a// generation boundary for ordinary status events.this.clearTerminalErrorDrain();+ } else if (+ event.type === 'done' &&+ !isBackgroundEvent &&+ this.terminalErrorDrainGeneration !== null &&+ this.lastObservedTerminalKind === 'error' &&+ this.terminalErrorDrainGeneration === this.lastObservedTerminalGeneration+ ) {+ // Rolled-back / leftover paired done still belongs to the promoted error.+ this.clearTerminalErrorDrain();}const listenerEvent = redactEventForListeners(event);- if (isCurrentGeneration && isTerminal && !isBackgroundEvent) {+ if (+ terminalBoundaryObserved &&+ event.type === 'error' &&+ this.terminalEventObservedKind === 'error'+ ) {+ const snapshot = this.readRedactedTerminalErrorSnapshot(listenerEvent);+ this.terminalEventObservedErrorMessage = snapshot.message;+ this.terminalEventObservedErrorSignals = snapshot.signals;+ } else if (+ isTerminal &&+ !isBackgroundEvent &&+ this.isUnacceptedCurrentSend() &&+ (!settleAsCurrentGeneration || preDispatchReservation)+ ) {+ // N 的终态在 N+1 reservation / handle.send 窗口到达:先记在窗口快照里,+ // 等拒绝回滚再提升。成功派发的 N+1 不得继承这份证据。+ // Reservation 可能已因 handle running 被释放,仍按未接受 generation 记。+ this.rememberReservationWindowPriorTerminal(event, listenerEvent);+ }+ if (isCurrentGeneration && isTerminal && !isBackgroundEvent && !lateErrorAfterDoneSnapshot && !reservationWindowLeftover) {this.clearTurnControl(resolvedGeneration);}const isLeftoverProductTerminal =!isBackgroundEvent &&- resolvedGeneration < this.turnGeneration &&+ (+ resolvedGeneration < this.turnGeneration ||+ lateErrorAfterDoneSnapshot ||+ reservationWindowLeftover+ ) &&(isTerminal || this.isIdleStatusEvent(event));if (isTerminal && !isBackgroundEvent && !isLeftoverProductTerminal) {try {@@ -2028,7 +2399,7 @@ export class Session {// 它只结束当前 SDK turn,产品层 Agent 仍在执行;其余到达 Session 的 done /// 终止型 error 才代表产品 turn 已结束,必须清 origin,避免后续 standalone// auto-compact 等后台 turn 继承 goal/scheduler origin。- if (isCurrentGeneration && isTerminal) {+ if (isCurrentGeneration && isTerminal && !isLeftoverProductTerminal) {this.currentTurnOrigin = null;this.currentTurnAttemptToken = null;// 终态之后不再计 stall 额度。@@ -2304,13 +2675,21 @@ export class Session {let observedGeneration = awaitingGeneration;if (awaitingCanAdoptNextGeneration &&- this.turnGeneration === awaitingGeneration + 1+ this.turnGeneration === awaitingGeneration + 1 &&+ !this.isPreDispatchReservation() &&+ !this.shouldHoldGenerationAdoption(event, awaitingGeneration)) {// Only a next() that started while logically idle may follow the next send.// Capturing that fact before awaiting is essential. The terminal drain may// already be armed when a watchdog-generated error precedes this pending// next(); adopting the exact next generation lets the provider's tail done// clear that fence. The fence itself prevents any later generation entering.+ // Do not adopt while N+1 is still reserved / before provider dispatch:+ // a late N terminal would otherwise be cached as N+1 evidence.+ // After handle.send() accepts, a no-progress done is N+1's result-only+ // terminal when N's paired done was lost. Leftover paired done is still+ // held while the send is pending. In-flight start-failure errors still+ // belong to this send.observedGeneration = this.turnGeneration;}if (this.terminationStarted) continue;@@ -2377,6 +2756,7 @@ export class Session {this.clearTurnStallWatchdog();this.cancelSendReservation(this.sendReservation);this.sendReservation = null;+ this.unacceptedSendGeneration = null;this.currentTurnOrigin = null;this.currentTurnAttemptToken = null;this.turnControlState = null;@@ -2434,6 +2814,50 @@ export class Session {}}+ private isPreDispatchReservation(): boolean {+ return (+ this.sendReservation !== null &&+ this.sendReservation.generation === this.turnGeneration &&+ this.sendReservation.phase === 'accepting'+ );+ }++ private shouldHoldGenerationAdoption(+ event: AgentEvent,+ awaitingGeneration: number,+ ): boolean {+ // Only a wait that already saw N's terminal can mis-adopt leftover done as N+1.+ if (awaitingGeneration <= 0) return false;+ if (this.lastObservedTerminalGeneration !== awaitingGeneration) return false;+ // Only an error-then-paired-done leftover can look like N+1 success.+ if (this.lastObservedTerminalKind !== 'error') return false;+ if (this.isNewTurnProgressEvent(event) || this.isForegroundRunningStatus(event)) {+ return false;+ }+ if (this.isSilentStopDoneEvent(event)) return false;+ if (event.type !== 'done') return false;+ // Hold leftover paired done only while N+1 is not yet accepted.+ // After accept, a no-progress done is N+1's result-only terminal when N's+ // paired done was lost; lastObserved staying `error` must not swallow it.+ // Pending handle.send / accepting reservation still fence the old tail,+ // including after reservation is released because the handle flipped running.+ return this.isUnacceptedCurrentSend();+ }++ private isUnacceptedCurrentSend(): boolean {+ const reservation = this.sendReservation;+ if (reservation && reservation.generation === this.turnGeneration) {+ return !reservation.accepted;+ }+ return this.unacceptedSendGeneration === this.turnGeneration;+ }++ private isForegroundRunningStatus(event: AgentEvent): boolean {+ if (event.turnScope === 'background') return false;+ if (event.type !== 'status') return false;+ return (event.data as { isRunning?: unknown } | null | undefined)?.isRunning === true;+ }+private createSessionRunningError(): Error {const err = new Error(`SESSION_RUNNING: Session ${this.id} is already running a turn`);(err as { code?: string }).code = 'SESSION_RUNNING';