Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 自动重试错误不进入灵动岛 (#1453)

Dashda5b4ec7c692
diff --git a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
index 05e7b17378..bf5d5aeded 100644
--- a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
+++ b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
@@ -102,6 +102,9 @@ describe('interrupted continuation enqueue contract', () => {
expect(discardedHook).toMatch(
/settleUndispatchedAutoResumeOutcome\(sessionId, item\)/,
);
+ expect(discardedHook).toMatch(
+ /finalizeUndispatchedClaimedRetry\(sessionId, item, ['"]cancelled['"]\)/,
+ );
expect(discardedHook).toMatch(
/interruptedTurnAutoResumeGuard\.noteResumeSendFailed\(sessionId\)/,
);
@@ -128,6 +131,24 @@ describe('interrupted continuation enqueue contract', () => {
expect(registerSource.slice(undispatchedStart, undispatchedEnd)).toMatch(
/settleUndispatchedAutoResumeOutcome\(sessionId, item\)/,
);
+ expect(registerSource.slice(undispatchedStart, undispatchedEnd)).toMatch(
+ /finalizeUndispatchedClaimedRetry\(sessionId, item, disposition\)/,
+ );
+
+ const finalizeStart = registerSource.indexOf('const finalizeUndispatchedClaimedRetry = (');
+ const finalizeEnd = registerSource.indexOf('\n };', finalizeStart);
+ expect(finalizeStart).toBeGreaterThan(-1);
+ expect(finalizeEnd).toBeGreaterThan(finalizeStart);
+ const finalizeHelper = registerSource.slice(finalizeStart, finalizeEnd);
+ expect(finalizeHelper).toMatch(
+ /surfaceSuppressedErrorForRetry\(sessionId, item\.clientId\)/,
+ );
+ expect(finalizeHelper).toMatch(
+ /flushSuppressedErrorForRetry\(\s*sessionId,\s*item\.clientId,?\s*\)/,
+ );
+ expect(finalizeHelper).toMatch(
+ /handleAgentIslandSessionStopped\(getStableSessionForTurnBoundary\(sessionId\) \?\? sessionId\)/,
+ );
});
it('fails a pending scheduler auto-resume before dispatching unrelated user input', () => {
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 2fce3d6a7f..35b7e8a430 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -88,6 +88,57 @@ describe('maker:event hot path ordering', () => {
);
});
+ it('keeps auto-resume-owned terminal errors out of Agent Island until they are final', () => {
+ const handler = source.match(
+ /function handleAgentIslandEventAfterBroadcast\([\s\S]*?\n}\n\nfunction surfaceSuppressedAutoResumeErrorInAgentIsland/,
+ )?.[0];
+ expect(handler).toBeTruthy();
+ if (!handler) return;
+
+ expectOrder(handler, 'service.deferRemoteAuthRetryError(meta, event);', 'const terminalError =');
+ expect(handler).toContain('agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true');
+ expect(handler).toContain('agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true');
+ expect(handler).toContain(
+ 'autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id)',
+ );
+ expect(handler).toContain(
+ 'autoResumeBookkeeping.shouldSuppressAgentIslandCompletionTail(session.id)',
+ );
+ expect(handler).toContain('(terminalError && autoResumeOwnsError)');
+ expect(handler).toContain(
+ '(isAgentIslandCompletionTail(event) && autoResumeOwnsCompletionTail)',
+ );
+ expectOrder(handler, 'const autoResumeOwnsError =', 'service.handleAgentEvent(meta, event);');
+ expect(handler).not.toContain('suppressErrorSound');
+
+ expect(source).toContain('surfaceSuppressedAutoResumeErrorInAgentIsland(sessionId, detail)');
+ expect(source).toContain("data: { ...detail, isTerminal: true }");
+ expect(source).toContain(
+ 'autoResumeBookkeeping.claimSuppressedErrorForRetry(sessionId, clientId, source);',
+ );
+ expect(source).toContain('if (!attempt.isCurrent()) {');
+ expect(source).toContain(
+ 'autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(sessionId);',
+ );
+ expect(source).toContain(
+ 'autoResumeBookkeeping.markReplacementDispatching(sessionId, clientId);',
+ );
+ expect(source).toContain(
+ 'autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);',
+ );
+ expect(source).toContain('onRejectedUserTurn: (sessionId, item) => {');
+ expect(source).toContain('commitUserPromptPreview: (sessionId, clientId) => {');
+ expect(source).toContain(
+ 'autoResumeBookkeeping.discardSuppressedErrorForRetry(sessionId, clientId);',
+ );
+ expect(source).toContain(
+ 'autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);',
+ );
+ expect(source).not.toContain(
+ 'autoResumeBookkeeping.discardSuppressedError(sessionId);',
+ );
+ });
+
it('only status/done/error paths request idle restore', () => {
const wireSessionSource = extractWireSessionSource();
const statusIdleAssignments = [...wireSessionSource.matchAll(/shouldMarkTurnStatusIdleAfterBroadcast = true;/g)]
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 9860617c58..9a481f670f 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -481,8 +481,12 @@ describe('sendToSession ordering', () => {
expect(makerSendCreateDbMessageBlock).toContain('const result = await enqueueDurableWrite');
expect(makerSendCreateDbMessageBlock).not.toContain('notifyAgentIslandUserPrompt(');
expect(makerSendPreviewHookBlock).toContain('previewUserPrompt: (session, content, options) => {');
- expect(makerSendPreviewHookBlock).toContain('notifyAgentIslandUserPrompt(session, content, options);');
- expect(makerSendPreviewHookBlock).toContain('dispatchUserPromptPreview: (sessionId) => {');
+ expect(makerSendPreviewHookBlock).toContain(
+ 'const previewed = notifyAgentIslandUserPrompt(session, content, {',
+ );
+ expect(makerSendPreviewHookBlock).toContain(
+ 'dispatchUserPromptPreview: (sessionId, clientId) => {',
+ );
expect(makerSendPreviewHookBlock).toContain('dispatchAgentIslandUserPrompt(sessionId);');
expect(makerSendPreviewHookBlock).toContain('commitUserPromptPreview: (sessionId, clientId) => {');
expect(makerSendPreviewHookBlock).toContain('rollbackUserPromptPreview: (sessionId, clientId, source) => {');
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index bf51a36ec4..221ffcc6c3 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -2214,6 +2214,63 @@ describe('AgentIslandService native publishing', () => {
});
});
+ it('uses the same replacement boundary when auto-resume withheld the old error', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+ service.setSoundSettings({
+ enabled: true,
+ sounds: {
+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,
+ complete: customSound('complete.wav'),
+ },
+ });
+ const meta = { sessionId: 'auto-resume-replacement', agentKind: 'claude-code' as const };
+ service.handleUserPrompt(meta, 'first turn');
+ service.handleUserPrompt(meta, 'continue automatically', {
+ clientId: 'auto-retry-1',
+ replacesCurrentTurn: true,
+ });
+ service.handleUserPromptDispatching(meta.sessionId);
+ playSound.mockClear();
+
+ service.handleAgentEvent(
+ meta,
+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },
+ );
+ service.handleAgentEvent(
+ meta,
+ { type: 'done', source: 'claude-code', data: { reason: 'turn_interrupted' } },
+ );
+
+ expect(playSound).not.toHaveBeenCalled();
+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ sessionId: meta.sessionId,
+ phase: 'running',
+ });
+
+ service.handleAgentEvent(
+ meta,
+ { type: 'status', source: 'claude-code', data: { isRunning: true, status: 'Thinking...' } },
+ );
+ service.handleAgentEvent(
+ meta,
+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },
+ );
+
+ expect(playSound).toHaveBeenCalledTimes(1);
+ expect(playSound).toHaveBeenCalledWith(customSound('complete.wav'));
+ });
+
it('accepts replacement-turn interaction requests before its running status arrives', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
@@ -2636,77 +2693,6 @@ describe('AgentIslandService native publishing', () => {
});
});
- it('keeps an auto-resumed failure transition silent and restores it if recovery does not start', async () => {
- const { AgentIslandService } = await import('../service.js');
- const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
- void state;
- void frameOrFrames;
- return true;
- });
- const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
- const service = new AgentIslandService({
- getMainWindow: () => null,
- nativeHost: { failed: false, publish, playSound },
- });
- syncEnabledForTest(service, publish);
- service.setSoundSettings({
- enabled: true,
- sounds: {
- ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,
- error: customSound('error.wav'),
- },
- });
- const meta = { sessionId: 'auto-resume', agentKind: 'claude-code' };
- service.handleUserPrompt(meta, 'run tests');
- playSound.mockClear();
-
- service.handleAgentEvent(meta, terminalErrorEvent('connection closed mid-response'), {
- suppressErrorSound: true,
- });
-
- expect(playSound).not.toHaveBeenCalled();
- expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
- sessionId: 'auto-resume',
- phase: 'error',
- detail: 'connection closed mid-response',
- });
- service.restoreTaskFailureSound(meta.sessionId);
- expect(playSound).toHaveBeenCalledTimes(1);
- expect(playSound).toHaveBeenCalledWith(customSound('error.wav'));
- });
-
- it('keeps an auto-resumed failure silent through the initial enabled sync', async () => {
- const { AgentIslandService } = await import('../service.js');
- const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
- void state;
- void frameOrFrames;
- return true;
- });
- const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
- const service = new AgentIslandService({
- getMainWindow: () => null,
- nativeHost: { failed: false, publish, playSound },
- });
- service.setSoundSettings({
- enabled: true,
- sounds: {
- ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,
- error: customSound('error.wav'),
- },
- });
- const meta = { sessionId: 'pre-sync-auto-resume', agentKind: 'claude-code' };
- service.handleUserPrompt(meta, 'run tests');
- service.handleAgentEvent(meta, terminalErrorEvent('connection closed before sync'), {
- suppressErrorSound: true,
- });
- service.setEnabled(true);
-
- expect(playSound).not.toHaveBeenCalled();
- service.restoreTaskFailureSound(meta.sessionId);
- expect(playSound).toHaveBeenCalledTimes(1);
- expect(playSound).toHaveBeenCalledWith(customSound('error.wav'));
- });
-
it('allows a remote daemon close inside the upgrade window to converge to completed', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index d9641863cc..7a88c89f30 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -148,11 +148,8 @@ interface AgentIslandUserPromptDebugMeta {
source?: string;
clientId?: string;
notifiedAt?: number;
-}
-
-interface AgentIslandEventOptions {
- /** The host is automatically recovering this failure, so this transition stays silent. */
- suppressErrorSound?: boolean;
+ /** The prompt replaces a failed turn whose terminal event was intentionally withheld. */
+ replacesCurrentTurn?: boolean;
}
export interface AgentIslandServiceDeps {
@@ -247,7 +244,6 @@ export class AgentIslandService {
private readonly silencedRunHadAttention = new Map<string, boolean>();
private readonly silencedRunClearTimers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly mutedCompletionSoundSessionIds = new Set<string>();
- private readonly mutedErrorSoundSessionIds = new Set<string>();
private readonly stoppedSessionIds = new Set<string>();
private readonly replacementTurnPendingSessionIds = new Set<string>();
private readonly replacementTurnDispatchingSessionIds = new Set<string>();
@@ -515,7 +511,6 @@ export class AgentIslandService {
this.hiddenPublished = false;
if (!wasSynced && !enabled) {
this.mutedCompletionSoundSessionIds.clear();
- this.mutedErrorSoundSessionIds.clear();
this.clearPublishTimer();
this.hiddenPublished = true;
return;
@@ -566,7 +561,6 @@ export class AgentIslandService {
this.metadataLoading.clear();
this.lastSoundDisplayState = null;
this.soundCooldownUntilByEvent.clear();
- this.mutedErrorSoundSessionIds.clear();
this.silencedRunSessionIds.clear();
this.silencedSessionRunIds.clear();
this.silencedRunHadAttention.clear();
@@ -616,7 +610,6 @@ export class AgentIslandService {
handleAgentEvent(
meta: AgentIslandSessionMeta,
event: AgentEvent,
- options: AgentIslandEventOptions = {},
): void {
const hydrated = this.hydrateMeta(meta);
const providerTurnId = providerTurnIdFromAgentEvent(event);
@@ -731,26 +724,9 @@ export class AgentIslandService {
return;
}
this.clearStreamingPreviewPublishTimer();
- if (isTerminalAgentErrorEvent(event) && options.suppressErrorSound === true) {
- // Keep the mute through the initial enabled-state sync. A sound-capable
- // publish consumes it immediately; no retry or delivery lifecycle is stored.
- this.mutedErrorSoundSessionIds.add(hydrated.sessionId);
- }
this.publish();
}
- /** Automatic recovery did not start; notify only while the failure still needs attention. */
- restoreTaskFailureSound(sessionId: string): void {
- this.mutedErrorSoundSessionIds.delete(sessionId);
- if (!this.enabledSynced || !this.enabled) return;
- const now = Date.now();
- const displayState = buildAgentIslandDisplayState(this.state, now);
- if (!displayState.visible || displayState.smartSuppressed) return;
- const session = displayState.sessions.find((candidate) => candidate.sessionId === sessionId);
- if (!session?.attention || session.phase !== 'error') return;
- this.playConfiguredSound('error', now);
- }
-
handleScheduleEvent(event: SchedulerEvent): void {
if (event.type === 'silenced') {
this.markSilencedScheduleRun(event.runId, event.sessionId);
@@ -787,7 +763,7 @@ export class AgentIslandService {
}
}
- handleUserPrompt(meta: AgentIslandSessionMeta, prompt: string, debugMeta: AgentIslandUserPromptDebugMeta = {}): void {
+ handleUserPrompt(meta: AgentIslandSessionMeta, prompt: string, debugMeta: AgentIslandUserPromptDebugMeta = {}): boolean {
const receivedAt = Date.now();
const hydrated = this.hydrateMeta(meta);
const previousInteractionEpoch = this.interactionEpochBySession.get(hydrated.sessionId);
@@ -795,12 +771,16 @@ export class AgentIslandService {
const wasReplacementTurnPending = this.replacementTurnPendingSessionIds.has(hydrated.sessionId);
const wasReplacementTurnDispatching =
this.replacementTurnDispatchingSessionIds.has(hydrated.sessionId);
- const deferInteractionEpochUntilDispatch = wasStopped || wasReplacementTurnPending;
+ const startsReplacementTurn = debugMeta.replacesCurrentTurn === true;
+ const deferInteractionEpochUntilDispatch =
+ startsReplacementTurn || wasStopped || wasReplacementTurnPending;
if (!deferInteractionEpochUntilDispatch) {
this.advanceInteractionEpoch(hydrated.sessionId);
}
if (wasStopped) {
this.stoppedSessionIds.delete(hydrated.sessionId);
+ }
+ if (wasStopped || startsReplacementTurn) {
this.replacementTurnPendingSessionIds.add(hydrated.sessionId);
}
if (deferInteractionEpochUntilDispatch) {
@@ -841,11 +821,12 @@ export class AgentIslandService {
this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);
}
this.restoreInteractionEpoch(hydrated.sessionId, previousInteractionEpoch);
- return;
+ return false;
}
this.ensureMetadata(hydrated.sessionId);
this.syncSessionAttention(hydrated.sessionId);
this.publish();
+ return true;
}
commitUserPrompt(sessionId: string, clientId: string | undefined): void {
@@ -1288,7 +1269,6 @@ export class AgentIslandService {
next,
this.mutedCompletionSoundSessionIds,
new Set(this.silencedSessionRunIds.keys()),
- this.mutedErrorSoundSessionIds,
);
if (!event) return;
this.playConfiguredSound(event, now);
@@ -1435,7 +1415,6 @@ export class AgentIslandService {
}
if (!this.enabled) {
this.mutedCompletionSoundSessionIds.clear();
- this.mutedErrorSoundSessionIds.clear();
this.clearStreamingPreviewPublishTimer();
this.lastSoundDisplayState = withAgentIslandConfig(
buildAgentIslandDisplayState(this.state, now),
@@ -1468,7 +1447,6 @@ export class AgentIslandService {
this.scheduleNextPublish(now);
this.playSoundForDisplayTransition(this.lastSoundDisplayState, displayState, now);
this.mutedCompletionSoundSessionIds.clear();
- this.mutedErrorSoundSessionIds.clear();
this.lastSoundDisplayState = displayState;
if (this.nativeHost.failed) {
@@ -2209,7 +2187,6 @@ function getAgentIslandSoundEventForTransition(
next: AgentIslandDisplayState,
mutedCompletionSessionIds: ReadonlySet<string> = new Set(),
mutedStartSessionIds: ReadonlySet<string> = new Set(),
- mutedErrorSessionIds: ReadonlySet<string> = new Set(),
): AgentIslandSoundEvent | null {
const previousById = new Map(previous?.sessions.map((session) => [session.sessionId, session]) ?? []);
for (const session of next.sessions) {
@@ -2219,7 +2196,6 @@ function getAgentIslandSoundEventForTransition(
}
for (const session of next.sessions) {
if (!session.attention || session.phase !== 'error') continue;
- if (mutedErrorSessionIds.has(session.sessionId)) continue;
const prev = previousById.get(session.sessionId);
if (prev?.phase !== 'error') return 'error';
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 3f71b57bec..6db419a76c 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
@@ -225,6 +225,9 @@ function createHarness() {
const onDiscardedQueuedMessage = vi.fn<
NonNullable<AgentInputCoordinatorDeps['onDiscardedQueuedMessage']>
>(() => {});
+ const onRejectedUserTurn = vi.fn<
+ NonNullable<AgentInputCoordinatorDeps['onRejectedUserTurn']>
+ >(() => {});
const supersedeRetriedUserTurn = vi.fn<
NonNullable<AgentInputCoordinatorDeps['supersedeRetriedUserTurn']>
>(async () => []);
@@ -235,6 +238,7 @@ function createHarness() {
onUiRetry,
onUserEnqueue,
onDiscardedQueuedMessage,
+ onRejectedUserTurn,
supersedeRetriedUserTurn,
isTurnRunning: () => running,
getTurnGeneration: () => turnGeneration,
@@ -289,6 +293,7 @@ function createHarness() {
onUiRetry,
onUserEnqueue,
onDiscardedQueuedMessage,
+ onRejectedUserTurn,
supersedeRetriedUserTurn,
setRunning(value: boolean) {
running = value;
@@ -2764,6 +2769,10 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-1' });
expect(projection.errorRetryText).toBe('first');
expect(mocks.createMessage).not.toHaveBeenCalled();
+ expect(h.onRejectedUserTurn).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ clientId: 'q-1' }),
+ );
h.coordinator.retryLastError(sid);
await flush();
@@ -3207,7 +3216,7 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.error).toBe('turn/start failed');
expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });
expect(projection.errorRetryText).toBe('first');
- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first);
+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');
});
it('recovers a persisted turn when terminal error arrives before send resolves', async () => {
@@ -3351,7 +3360,7 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.error).toContain('cancelled-before-dispatch');
expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });
expect(projection.errorRetryText).toBe('first');
- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first);
+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');
});
it('keeps a persisted ordinary send recoverable when a host failure is reported late', async () => {
@@ -3382,7 +3391,7 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.error).toContain('WORKDIR_MISSING');
expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });
expect(projection.errorRetryText).toBe('first');
- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first);
+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');
});
it('keeps ordinary send DB writes linear while draining queued turns', async () => {
@@ -3444,7 +3453,8 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.pendingQueue).toEqual([second]);
expect(projection.error).toContain('cancelled-before-dispatch');
expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });
- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first);
+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'cancelled');
+ expect(h.onRejectedUserTurn).not.toHaveBeenCalled();
h.coordinator.resume(sid);
await flush();
@@ -3615,7 +3625,7 @@ describe('AgentInputCoordinator send transaction', () => {
expect(projection.pendingQueue).toEqual([second]);
expect(projection.error).toBeNull();
expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });
- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first);
+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'cancelled');
h.coordinator.resume(sid);
await flush();
@@ -4458,6 +4468,10 @@ describe('AgentInputCoordinator steer transaction', () => {
expect.objectContaining({ clientId: 'q-2' }),
expect.objectContaining({ ghostId: 'g-1' }),
);
+ expect(h.onRejectedUserTurn).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ clientId: 'q-2' }),
+ );
expect(mocks.createMessage).toHaveBeenCalledTimes(1);
const projection = latestProjection(h.projections);
expect(projection.pendingQueue).toHaveLength(0);
@@ -7142,11 +7156,13 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
const sid = 'takeover-cleared-by-clear-error';
h.setResumableTurnErrorTakeover(TAKEOVER_INFO);
await failAfterDispatch(h, sid);
+ h.onUserEnqueue.mockClear();
h.coordinator.clearError(sid);
await flush();
expect(h.coordinator.isAutoResumePending(sid)).toBe(false);
+ expect(h.onUserEnqueue, 'host 必须先释放退避簿记与 Agent Island filter').toHaveBeenCalledWith(sid);
});
it('recovery 已被用户清掉时 autoRetryLastError 返回 false(调用方据此回滚额度)', async () => {
@@ -7195,7 +7211,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
releasePersist();
await flush();
- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid);
+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: false });
});
it('在途重试的刹车:await 读库期间接管态被清(会话关闭)→ 判 superseded,不补发', async () => {
@@ -7290,7 +7306,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
const projection = latestProjection(h.projections);
expect(projection.autoResumePending ?? null).toBeNull();
expect(projection.error, '不接管就得把横幅还给用户').toBe(truncationMessage);
- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid);
+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: true });
});
it('延后结算:候选窗口里用户自己发了消息 → 不接管、不消耗额度,回落成常规错误', async () => {
@@ -7322,7 +7338,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
expect(projection.autoResumePending ?? null, '用户已接手 → 不该再显示重连').toBeNull();
expect(projection.error, '回落成常规错误呈现,让用户自己决定要不要续跑').toBe(truncationMessage);
expect(h.onResumableTurnError, '连问都不该问(不消耗额度)').not.toHaveBeenCalled();
- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid);
+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: false });
});
it('退避窗口里用户自己发了消息 → autoRetryLastError 判 superseded(不抢在他前面代发)', async () => {
@@ -7396,7 +7412,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
rejectPersist(new Error('disk full'));
await flush();
- expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid);
+ expect(h.onResumableTurnErrorDiscarded).toHaveBeenCalledWith(sid, { surfaceError: true });
expect(h.onResumableTurnError, '落库失败就没有可续跑的目标,不该消耗额度').not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
index d654110ec9..3ff12d0879 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoResumeBookkeeping.test.ts
@@ -21,13 +21,15 @@ function createHarness() {
const outcomes: Array<{ sessionId: string; clientId: string; outcome: AutoResumeOutcome }> = [];
const guardRollbacks: string[] = [];
const abandons: Array<{ sessionId: string; message?: string }> = [];
+ const surfaced: Array<{ sessionId: string; detail: SuppressedTurnError }> = [];
const deps: AutoResumeBookkeepingDeps = {
persistSuppressedError: (sessionId, detail) => persisted.push({ sessionId, detail }),
+ surfaceSuppressedError: (sessionId, detail) => surfaced.push({ sessionId, detail }),
markOutcome: (sessionId, clientId, outcome) => outcomes.push({ sessionId, clientId, outcome }),
rollbackGuardPendingResume: (sessionId) => guardRollbacks.push(sessionId),
abandonTakeover: (sessionId, message) => abandons.push({ sessionId, ...(message !== undefined ? { message } : {}) }),
};
- return { book: new AutoResumeBookkeeping(deps), persisted, outcomes, guardRollbacks, abandons };
+ return { book: new AutoResumeBookkeeping(deps), persisted, surfaced, outcomes, guardRollbacks, abandons };
}
beforeEach(() => {
@@ -56,6 +58,7 @@ describe('被压住的错误详情:必有人补落', () => {
]);
expect(h.book.flushSuppressedError('s1'), '已经落过就不该再落一遍').toBe(false);
expect(h.persisted).toHaveLength(1);
+ expect(h.surfaced, '普通补落只恢复历史,不应通知其它错误表面').toEqual([]);
});
it('stash 只收字符串字段(非字符串一律丢弃,不把 undefined 写进 content)', () => {
@@ -68,28 +71,131 @@ describe('被压住的错误详情:必有人补落', () => {
it('自愈成功 → discard 丢弃详情,历史里只留活动行', () => {
const h = createHarness();
h.book.stashSuppressedError('s1', { message: 'boom' });
+ expect(h.book.hasSuppressedError('s1')).toBe(true);
h.book.discardSuppressedError('s1');
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
expect(h.book.flushSuppressedError('s1')).toBe(false);
expect(h.persisted).toEqual([]);
+ expect(h.surfaced).toEqual([]);
});
- it('finalize:补落 + 结算 failed + 清接管态;surfaceBanner 决定横幅带不带 message', () => {
+ it('surface:补落并只向其它错误表面通知一次', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'boom' });
+
+ expect(h.book.surfaceSuppressedError('s1')).toBe(true);
+ expect(h.book.surfaceSuppressedError('s1')).toBe(false);
+ expect(h.persisted).toEqual([{ sessionId: 's1', detail: { message: 'boom' } }]);
+ expect(h.surfaced).toEqual([{ sessionId: 's1', detail: { message: 'boom' } }]);
+ });
+
+ it('replacement 归属按 clientId 锁定,别的队列项不能释放旧错误', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+
+ expect(h.book.claimSuppressedErrorForRetry('s1', 'retry-1')).toBe(true);
+ expect(h.book.claimSuppressedErrorForRetry('s1', 'retry-2')).toBe(false);
+ expect(h.book.isSuppressedErrorClaimedByRetry('s1', 'retry-1')).toBe(true);
+ expect(h.book.discardSuppressedErrorForRetry('s1', 'retry-2')).toBe(false);
+ expect(h.book.hasSuppressedError('s1')).toBe(true);
+
+ expect(h.book.discardSuppressedErrorForRetry('s1', 'retry-1')).toBe(true);
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
+ expect(h.persisted).toEqual([]);
+ });
+
+ it('preview 后把 completion tail 交给 Agent Island,rollback 后重新接回', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(true);
+ expect(h.book.markReplacementPreviewed('s1', 'retry-1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(false);
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(true);
+
+ expect(h.book.rollbackReplacementPreview('s1', 'retry-1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(true);
+ expect(h.book.surfaceSuppressedErrorForRetry('s1', 'retry-1')).toBe(true);
+ expect(h.persisted).toEqual([
+ { sessionId: 's1', detail: { message: 'old interruption' } },
+ ]);
+ expect(h.surfaced).toEqual([
+ { sessionId: 's1', detail: { message: 'old interruption' } },
+ ]);
+ });
+
+ it('Island preview 不可用时 dispatch 仍切开新错误归属,但继续兜住旧 completion tail', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+
+ expect(h.book.markReplacementDispatching('s1', 'retry-1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(false);
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(true);
+
+ h.book.rollbackReplacementPreview('s1', 'retry-1');
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(true);
+ });
+
+ it('replacement dispatch 后新错误独立接管,旧 owner 不能删掉它', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+ h.book.markReplacementPreviewed('s1', 'retry-1');
+ expect(h.book.markReplacementDispatching('s1', 'retry-1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(false);
+
+ // sendToAgent 可在返回前同步发出 replacement 自己的 retryable error。
+ h.book.stashSuppressedError('s1', { message: 'new interruption' });
+ expect(h.persisted, '旧 transient error 已被 replacement 取代,不应补回历史').toEqual([]);
+ expect(h.book.isSuppressedErrorClaimedByRetry('s1', 'retry-1')).toBe(false);
+ expect(h.book.discardSuppressedErrorForRetry('s1', 'retry-1')).toBe(false);
+
+ expect(h.book.surfaceSuppressedError('s1')).toBe(true);
+ expect(h.persisted).toEqual([
+ { sessionId: 's1', detail: { message: 'new interruption' } },
+ ]);
+ expect(h.surfaced).toEqual([
+ { sessionId: 's1', detail: { message: 'new interruption' } },
+ ]);
+ });
+
+ it('replacement 的同步不可续跑终态可直接丢弃旧 dispatch owner', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+ h.book.markReplacementPreviewed('s1', 'retry-1');
+ h.book.markReplacementDispatching('s1', 'retry-1');
+
+ expect(h.book.discardReplacementProvenByProviderEvent('s1')).toBe(true);
+ expect(h.book.discardReplacementProvenByProviderEvent('s1')).toBe(false);
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
+ expect(h.persisted).toEqual([]);
+ expect(h.surfaced).toEqual([]);
+ });
+
+ it('finalize:补落 + 呈现失败 + 结算 failed + 清接管态', () => {
const h = createHarness();
h.book.stashSuppressedError('s1', { message: 'boom' });
h.book.registerPendingOutcome('s1', 'c-1');
- h.book.finalizeSuppressedError('s1', { surfaceBanner: true });
+ h.book.finalizeSuppressedError('s1', { surfaceError: true });
expect(h.persisted).toHaveLength(1);
+ expect(h.surfaced).toEqual([{ sessionId: 's1', detail: { message: 'boom' } }]);
expect(h.outcomes).toEqual([{ sessionId: 's1', clientId: 'c-1', outcome: 'failed' }]);
expect(h.abandons).toEqual([{ sessionId: 's1', message: 'boom' }]);
});
- it('finalize(surfaceBanner=false):仍补落,但不把横幅弹回来(用户已自己接手)', () => {
+ it('finalize(surfaceError=false):仍补落,但不重新呈现错误(用户已自己接手)', () => {
const h = createHarness();
h.book.stashSuppressedError('s1', { message: 'boom' });
- h.book.finalizeSuppressedError('s1', { surfaceBanner: false });
+ h.book.finalizeSuppressedError('s1', { surfaceError: false });
expect(h.persisted).toHaveLength(1);
+ expect(h.surfaced).toEqual([]);
expect(h.abandons).toEqual([{ sessionId: 's1' }]);
});
});
@@ -173,6 +279,7 @@ describe('退避排期:必可撤销、必只认自己那次', () => {
h.book.stashSuppressedError('s1', { message: 'second interruption' });
expect(h.persisted.map((p) => p.detail.message)).toEqual(['first interruption']);
+ expect(h.surfaced, '被新一轮顶替只补历史,不能拿旧错误打扰用户').toEqual([]);
h.book.schedule('s1', 3_000, vi.fn());
// 第二条仍在压制中,等它自己的结局。
@@ -221,6 +328,61 @@ describe('退避排期:必可撤销、必只认自己那次', () => {
setTimeoutSpy.mockRestore();
clearTimeoutSpy.mockRestore();
});
+
+ it('timer 已 fire 后 Manual Retry 接管 → 旧 async completion 不能终结新 owner', async () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ h.book.schedule('s1', 1_000, async (attempt) => {
+ await gate;
+ if (attempt.isCurrent()) {
+ h.book.finalizeSuppressedError('s1', { surfaceError: false });
+ }
+ });
+
+ vi.advanceTimersByTime(1_000);
+ await Promise.resolve();
+ expect(h.book.hasSchedule('s1'), 'async 判定期间仍须保留可撤销 lease').toBe(true);
+
+ expect(h.book.claimSuppressedErrorForRetry('s1', 'manual-retry', 'manual')).toBe(true);
+ expect(h.book.hasSchedule('s1')).toBe(false);
+ expect(h.guardRollbacks).toEqual(['s1']);
+
+ release();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(h.book.isSuppressedErrorClaimedByRetry('s1', 'manual-retry')).toBe(true);
+ expect(h.persisted, '旧 completion 不得补落或删除手动 replacement 的错误').toEqual([]);
+ });
+
+ it('clearError / 新输入接管 → 同步释放旧 Island filter,已 fire 回调随即失效', async () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ h.book.schedule('s1', 1_000, async (attempt) => {
+ await gate;
+ if (attempt.isCurrent()) {
+ h.book.finalizeSuppressedError('s1', { surfaceError: false });
+ }
+ });
+
+ vi.advanceTimersByTime(1_000);
+ await Promise.resolve();
+ expect(h.book.supersedeUnclaimedErrorForUserIntervention('s1')).toBe(true);
+ expect(h.book.shouldSuppressAgentIslandError('s1')).toBe(false);
+ expect(h.book.shouldSuppressAgentIslandCompletionTail('s1')).toBe(false);
+ expect(h.persisted).toEqual([
+ { sessionId: 's1', detail: { message: 'old interruption' } },
+ ]);
+
+ release();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(h.persisted, '失效的旧回调不得重复 disposition').toHaveLength(1);
+ expect(h.surfaced).toEqual([]);
+ });
});
describe('会话终止收尾', () => {
@@ -237,6 +399,7 @@ describe('会话终止收尾', () => {
expect(h.persisted, 'teardown 不能把压住的错误行悄悄丢掉').toEqual([
{ sessionId: 's1', detail: { message: 'boom' } },
]);
+ expect(h.surfaced, '会话已经终止,不应再向用户呈现旧错误').toEqual([]);
expect(h.guardRollbacks).toEqual(['s1']);
expect(h.abandons, '会话已被用户终止 → 只清接管态,不弹横幅').toEqual([{ sessionId: 's1' }]);
expect(h.outcomes).toEqual([{ sessionId: 's1', clientId: 'c-1', outcome: 'failed' }]);
@@ -268,4 +431,52 @@ describe('会话终止收尾', () => {
expect(h.outcomes).toEqual([]);
expect(h.guardRollbacks).toEqual([]);
});
+
+ it('teardown 会补落仅进入 dispatching、尚无 accepted/provider 证明的旧错误', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+ h.book.markReplacementPreviewed('s1', 'retry-1');
+ h.book.markReplacementDispatching('s1', 'retry-1');
+
+ h.book.teardown('s1');
+
+ expect(h.persisted).toEqual([
+ { sessionId: 's1', detail: { message: 'old interruption' } },
+ ]);
+ expect(h.surfaced).toEqual([]);
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
+ });
+
+ it('dispatching 后 teardown 与迟到 rollback 只补落旧错误一次', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+ h.book.markReplacementPreviewed('s1', 'retry-1');
+ h.book.markReplacementDispatching('s1', 'retry-1');
+
+ h.book.teardown('s1');
+ expect(h.book.rollbackReplacementPreview('s1', 'retry-1')).toBe(false);
+ expect(h.book.surfaceSuppressedErrorForRetry('s1', 'retry-1')).toBe(false);
+
+ expect(h.persisted).toEqual([
+ { sessionId: 's1', detail: { message: 'old interruption' } },
+ ]);
+ expect(h.surfaced).toEqual([]);
+ });
+
+ it('teardown 不复活已有 provider event 证明取代的旧错误', () => {
+ const h = createHarness();
+ h.book.stashSuppressedError('s1', { message: 'old interruption' });
+ h.book.claimSuppressedErrorForRetry('s1', 'retry-1');
+ h.book.markReplacementPreviewed('s1', 'retry-1');
+ h.book.markReplacementDispatching('s1', 'retry-1');
+ h.book.discardReplacementProvenByProviderEvent('s1');
+
+ h.book.teardown('s1');
+
+ expect(h.persisted).toEqual([]);
+ expect(h.surfaced).toEqual([]);
+ expect(h.book.hasSuppressedError('s1')).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 4c64e0bb09..0242129a73 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -150,7 +150,7 @@ describe('maker SEND transaction', () => {
{ shouldBroadcast },
);
expect(onPersisted).toHaveBeenCalled();
- expect(deps.dispatchUserPromptPreview).toHaveBeenCalledWith('session-1');
+ expect(deps.dispatchUserPromptPreview).toHaveBeenCalledWith('session-1', 'client-1');
expect(deps.commitUserPromptPreview).toHaveBeenCalledWith('session-1', 'client-1');
expect(deps.rollbackUserPromptPreview).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 67e668a8f7..ee6c888c9c 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -283,8 +283,13 @@ export interface AgentInputCoordinatorDeps {
/**
* 一条被 `isAutoResumeDeferred` 按住的 error 最终**没能走到决策**(用户气泡持久化失败等),
* host 必须把压住的 error 行补落,否则那次中断在历史里彻底消失(不变量 I2)。
+ * `surfaceError` 只在这条 error 本身成为最终用户可见失败时为 true;被新输入或另一条
+ * 技术错误顶替时只补历史,不能再拿旧错误打扰用户。
*/
- onResumableTurnErrorDiscarded?: (sessionId: string) => void;
+ onResumableTurnErrorDiscarded?: (
+ sessionId: string,
+ options: { surfaceError: boolean },
+ ) => void;
/** 在 vendor dispatch 前读取用户选中的本地/在线会话引用。 */
resolveSessionReferences?: (
refs: AgentInputQueuedMessage['sessionRefs'],
@@ -322,10 +327,22 @@ export interface AgentInputCoordinatorDeps {
beforeDispatchUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;
/**
* Called when a user row crossed the persistence boundary but never reached
- * vendor dispatch. Hosts use this to discard turn-start side effects that
- * would otherwise be consumed by a later retry/turn.
+ * vendor dispatch. `cancelled` is an explicit user lifecycle boundary
+ * (Stop/remove/clear/new input); `failed` means the attempted delivery itself
+ * failed and remains user-visible. Hosts use this to finalize retry ownership
+ * and discard turn-start side effects that would otherwise leak into a later turn.
+ */
+ onUndispatchedUserTurn?: (
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ disposition: 'cancelled' | 'failed',
+ ) => void;
+ /**
+ * The delivery pipeline rejected this item for a technical/policy reason
+ * before vendor dispatch. Unlike Stop/remove/clear, this is a real failed
+ * attempt rather than explicit user cancellation.
*/
- onUndispatchedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;
+ onRejectedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;
onAcceptedQueuedMessage?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;
/**
* Awaited only after vendor dispatch is irreversible (`accepted=true`).
@@ -356,7 +373,8 @@ export interface AgentInputCoordinatorDeps {
*/
onUiRetry?: (sessionId: string, clientId: string, source: 'manual' | 'auto') => void;
/**
- * 用户/上游用一条**新**消息接管了这个会话(enqueue 或 steer 回落为普通 turn)。
+ * 用户接管了这个会话(新消息 enqueue、steer 回落为普通 turn,或在自动退避中
+ * clearError 以继续既有队列)。
*
* hook-control 用它作废该会话的待续跑记账: 会话已经被别的内容推进, 再把结果接回
* 渠道那条旧消息只会显示无关输出。判据刻意用**入口**而不是消息文本 ——
@@ -1334,6 +1352,7 @@ export class AgentInputCoordinator {
if (cur.pendingQueue.length === 0) cur.queuePaused = false;
}
this.deps.onUserMessageBlocked?.(sessionId, item, verdict);
+ this.notifyRejectedUserTurn(sessionId, item);
this.deps.onDiscardedQueuedMessage?.(sessionId, item);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'steer-ghost-blocked');
@@ -1831,6 +1850,9 @@ export class AgentInputCoordinator {
clearError(sessionId: string): AgentInputProjection {
const state = this.getState(sessionId);
const shouldDrainTail = state.recovery?.kind === 'active-turn';
+ // clearError can immediately wake an already queued turn. Release the old
+ // backoff owner before that drain, or its Island filter can swallow the new tail.
+ if (state.autoResumePending) this.deps.onUserEnqueue?.(sessionId);
state.error = null;
state.stickyError = null;
// 用户显式收下了这条错误 → 自愈提示也该撤掉(退避到点后的复核会发现 recovery
@@ -2540,6 +2562,7 @@ export class AgentInputCoordinator {
if (verdict.action === 'block') {
this.getState(sessionId).activeTurn = null;
this.deps.onUserMessageBlocked?.(sessionId, head, verdict);
+ this.notifyRejectedUserTurn(sessionId, head);
this.deps.onDiscardedQueuedMessage?.(sessionId, head);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'ghost-hook-blocked');
@@ -2703,6 +2726,7 @@ export class AgentInputCoordinator {
reason,
error: latest.error,
});
+ this.notifyRejectedUserTurn(sessionId, head);
this.emit(sessionId);
return;
}
@@ -2720,7 +2744,8 @@ export class AgentInputCoordinator {
// (review #944 第十轮 P1)。
latest.activeTurn = null;
}
- this.notifyUndispatchedUserTurn(sessionId, head);
+ this.notifyRejectedUserTurn(sessionId, head);
+ this.notifyUndispatchedUserTurn(sessionId, head, 'failed');
this.emit(sessionId);
// 派发边界刚刚放开,队里可能还压着别的消息 —— 用户那条路靠 clearError 顺带唤醒,
// scheduler 这条没有人点,必须自己唤一次。
@@ -2770,6 +2795,11 @@ export class AgentInputCoordinator {
clientId: item.clientId,
...logFields,
});
+ const cancelledByUserBoundary =
+ latest.queueAbortPending &&
+ result.kind === 'session-dispatch' &&
+ result.reason === 'cancelled-before-dispatch';
+ if (!cancelledByUserBoundary) this.notifyRejectedUserTurn(sessionId, item);
this.emit(sessionId);
return;
}
@@ -2784,7 +2814,16 @@ export class AgentInputCoordinator {
// 注:isPromptTracked 用的 hasQueuedItemWhere 默认不含 recovery,所以摘掉它不会影响
// runner 的排队存活探测。
const schedulerOrigin = this.setActiveTurnRecovery(latest, item) === 'dropped-scheduler';
- this.notifyUndispatchedUserTurn(sessionId, item);
+ const cancelledByUserBoundary =
+ latest.queueAbortPending &&
+ result.kind === 'session-dispatch' &&
+ result.reason === 'cancelled-before-dispatch';
+ if (!cancelledByUserBoundary) this.notifyRejectedUserTurn(sessionId, item);
+ this.notifyUndispatchedUserTurn(
+ sessionId,
+ item,
+ cancelledByUserBoundary ? 'cancelled' : 'failed',
+ );
if (latest.queueAbortPending && result.kind === 'session-dispatch' && result.reason === 'cancelled-before-dispatch') {
latest.queueAbortPending = false;
}
@@ -3064,7 +3103,7 @@ export class AgentInputCoordinator {
// 同 onTurnEvent / handleSendNotDispatched:scheduler 的 prompt 不留重试入口
// (判据内建在 setActiveTurnRecovery,第十八轮 P1)。
const schedulerOrigin = this.setActiveTurnRecovery(state, item) === 'dropped-scheduler';
- this.notifyUndispatchedUserTurn(sessionId, item);
+ this.notifyUndispatchedUserTurn(sessionId, item, 'failed');
log.warn(
schedulerOrigin
? 'session closed before dispatch after persistence; dropped scheduler prompt (no user retry)'
@@ -3106,7 +3145,7 @@ export class AgentInputCoordinator {
const item = active.item;
if (!item) return;
if (active.persisted) {
- this.notifyUndispatchedUserTurn(sessionId, item);
+ this.notifyUndispatchedUserTurn(sessionId, item, 'cancelled');
// 第六条终态路径(本轮自查补上,不是等 reviewer 报的):用户 Stop 赢在 pre-vendor
// await 窗口。scheduler 的 prompt 同样不留重试入口 —— runner 会按 abort 收口这一轮,
// 克隆重跑没有 FireContext 回调也不计 run 账(判据内建在 setActiveTurnRecovery)。
@@ -3571,21 +3610,28 @@ export class AgentInputCoordinator {
*/
private discardOnStaleActiveTurn(sessionId: string, active: ActiveTurn): boolean {
if (this.isActiveTurnCurrent(sessionId, active)) return false;
- this.discardDeferredResumableCandidate(sessionId, active);
+ this.discardDeferredResumableCandidate(sessionId, active, { surfaceError: false });
return true;
}
- private discardDeferredResumableCandidate(sessionId: string, active: ActiveTurn): void {
+ private discardDeferredResumableCandidate(
+ sessionId: string,
+ active: ActiveTurn,
+ options: { surfaceError: boolean } = { surfaceError: true },
+ ): void {
const pending = active.pendingTerminalEvent;
if (pending?.type !== 'error' || pending.resumableCandidate !== true) return;
active.pendingTerminalEvent = null;
- this.notifyResumableTurnErrorDiscarded(sessionId);
+ this.notifyResumableTurnErrorDiscarded(sessionId, options);
}
- /** 被按住的 error 没能走到决策 → 通知 host 补落 error 行(不变量 I2)。 */
- private notifyResumableTurnErrorDiscarded(sessionId: string): void {
+ /** 被按住的 error 没能走到决策 → 通知 host 按最终 disposition 释放它(不变量 I2)。 */
+ private notifyResumableTurnErrorDiscarded(
+ sessionId: string,
+ options: { surfaceError: boolean },
+ ): void {
try {
- this.deps.onResumableTurnErrorDiscarded?.(sessionId);
+ this.deps.onResumableTurnErrorDiscarded?.(sessionId, options);
} catch (err) {
log.warn('onResumableTurnErrorDiscarded failed', { sessionId, error: errorMessage(err) });
}
@@ -3603,9 +3649,13 @@ export class AgentInputCoordinator {
if (!cancelledPrepared && (hadPendingTakeover || surfacedMessage)) this.emit(sessionId);
}
- private notifyUndispatchedUserTurn(sessionId: string, item: AgentInputQueuedMessage): void {
+ private notifyUndispatchedUserTurn(
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ disposition: 'cancelled' | 'failed',
+ ): void {
try {
- this.deps.onUndispatchedUserTurn?.(sessionId, item);
+ this.deps.onUndispatchedUserTurn?.(sessionId, item, disposition);
} catch (err) {
log.warn('onUndispatchedUserTurn failed', {
sessionId,
@@ -3615,6 +3665,18 @@ export class AgentInputCoordinator {
}
}
+ private notifyRejectedUserTurn(sessionId: string, item: AgentInputQueuedMessage): void {
+ try {
+ this.deps.onRejectedUserTurn?.(sessionId, item);
+ } catch (err) {
+ log.warn('onRejectedUserTurn failed', {
+ sessionId,
+ clientId: item.clientId,
+ error: errorMessage(err),
+ });
+ }
+ }
+
private isTurnGenerationCurrent(sessionId: string, active: ActiveTurn): boolean {
return this.getState(sessionId).generation === active.generation;
}
@@ -3702,7 +3764,9 @@ export class AgentInputCoordinator {
});
if (outcome === 'dropped-scheduler') {
state.error = terminalEvent.message ?? state.error;
- if (deferredPersistSuppressed) this.notifyResumableTurnErrorDiscarded(sessionId);
+ if (deferredPersistSuppressed) {
+ this.notifyResumableTurnErrorDiscarded(sessionId, { surfaceError: true });
+ }
// 与 onTurnEvent 的 persisted 分支同款处置:没有 recovery 挡住"紧随的 done",
// 必须用配对标记吃掉它,否则失败呈现会被 done 擦成"已完成"(第二十一轮 P1)。
// recovery 不留 → 没有"用户点 clearError / Retry"这个唤醒源,队里压着的消息
@@ -3735,7 +3799,11 @@ export class AgentInputCoordinator {
state.error = null;
} else {
state.error = terminalEvent.message ?? state.error;
- if (deferredPersistSuppressed) this.notifyResumableTurnErrorDiscarded(sessionId);
+ if (deferredPersistSuppressed) {
+ this.notifyResumableTurnErrorDiscarded(sessionId, {
+ surfaceError: terminalEvent.supersededByUser !== true,
+ });
+ }
if (schedulerItem) {
state.recovery = null;
this.markPendingExternalTerminalDone(sessionId, state);
diff --git a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
index ad3bbb8966..06d0a79fd3 100644
--- a/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
+++ b/apps/desktop/src/main/maker-ipc/autoResumeBookkeeping.ts
@@ -29,9 +29,29 @@ export interface SuppressedTurnError {
sdkError?: string;
}
+interface SuppressedTurnErrorEntry {
+ detail: SuppressedTurnError;
+ /** The retry queue item that will replace the failed turn. */
+ retryOwnerClientId: string | null;
+ /**
+ * Agent Island tail ownership and vendor dispatch are separate boundaries:
+ * preview can fail while dispatch still proceeds (for example Island is
+ * disabled), and a rejected dispatch rolls both boundaries back.
+ */
+ islandReplacementPreviewed: boolean;
+ replacementDispatching: boolean;
+}
+
+export interface AutoResumeScheduleAttempt {
+ /** Still owns this session after the timer fires and while async retry work awaits. */
+ isCurrent: () => boolean;
+}
+
export interface AutoResumeBookkeepingDeps {
/** 把压住的 error 行补落进历史。**不负责横幅** —— 横幅由 abandonTakeover 决定。 */
persistSuppressedError: (sessionId: string, detail: SuppressedTurnError) => void;
+ /** 这条错误已确定需要呈现给用户;由 host 同步到聊天之外的错误表面(如 Agent Island)。 */
+ surfaceSuppressedError?: (sessionId: string, detail: SuppressedTurnError) => void;
/** 回填一条自动续跑记录的结果(`agentMeta.autoResumeOutcome`)。 */
markOutcome: (sessionId: string, clientId: string, outcome: AutoResumeOutcome) => void;
/** 回滚守卫的 pendingResume(不回滚会让该会话之后的中断永远被判成「上一次还在路上」)。 */
@@ -50,7 +70,7 @@ export class AutoResumeBookkeeping {
* 接管期间刻意**不落 error 行**:自愈成功时用户看到的应该是聊天流里一条低调的活动行,
* 而不是一张红色错误卡 + 一条活动行。最终没救回来时用这份详情补落。
*/
- private readonly suppressedErrors = new Map<string, SuppressedTurnError>();
+ private readonly suppressedErrors = new Map<string, SuppressedTurnErrorEntry>();
/**
* 已落库、但还不知道结果的自动续跑消息(sessionId → clientId)。
@@ -60,10 +80,10 @@ export class AutoResumeBookkeeping {
*/
private readonly pendingOutcomes = new Map<string, string>();
- /** 已排期、还没到点的退避定时器(sessionId → 句柄 + 排期令牌)。 */
+ /** 待触发或正在异步判定的退避 attempt(sessionId → 句柄 + ownership 令牌)。 */
private readonly schedules = new Map<
string,
- { timer: ReturnType<typeof setTimeout>; token: number }
+ { timer: ReturnType<typeof setTimeout> | null; token: number }
>();
/** 排期令牌自增源(全局单调;只用来判「是不是我那次」,跨会话共享无妨)。 */
@@ -84,15 +104,74 @@ export class AutoResumeBookkeeping {
* 正在压制中的自己补落出来,红色错误卡与活动行同时出现,本功能也就白做了。
*/
stashSuppressedError(sessionId: string, data: unknown): void {
- this.flushSuppressedError(sessionId);
+ const previous = this.suppressedErrors.get(sessionId);
+ if (previous?.replacementDispatching) {
+ // The replacement has crossed the vendor boundary. A terminal error that
+ // arrives now belongs to that new attempt; the older transient error was
+ // successfully replaced and must not be restored beside it.
+ this.suppressedErrors.delete(sessionId);
+ } else {
+ this.flushSuppressedError(sessionId);
+ }
const d = (data ?? {}) as { message?: unknown; reason?: unknown; sdkError?: unknown };
this.suppressedErrors.set(sessionId, {
- ...(typeof d.message === 'string' ? { message: d.message } : {}),
- ...(typeof d.reason === 'string' ? { reason: d.reason } : {}),
- ...(typeof d.sdkError === 'string' ? { sdkError: d.sdkError } : {}),
+ detail: {
+ ...(typeof d.message === 'string' ? { message: d.message } : {}),
+ ...(typeof d.reason === 'string' ? { reason: d.reason } : {}),
+ ...(typeof d.sdkError === 'string' ? { sdkError: d.sdkError } : {}),
+ },
+ retryOwnerClientId: null,
+ islandReplacementPreviewed: false,
+ replacementDispatching: false,
});
}
+ /** Bind the suppressed failure to the exact retry queue item that will replace it. */
+ claimSuppressedErrorForRetry(
+ sessionId: string,
+ clientId: string,
+ source: 'manual' | 'auto' = 'auto',
+ ): boolean {
+ // Manual Retry transfers the failure to a user-owned queue item. Invalidate
+ // even an already-fired backoff attempt before assigning the new owner.
+ if (source === 'manual') this.cancelSchedule(sessionId);
+ const entry = this.suppressedErrors.get(sessionId);
+ if (!entry) return false;
+ if (entry.retryOwnerClientId !== null && entry.retryOwnerClientId !== clientId) return false;
+ entry.retryOwnerClientId = clientId;
+ return true;
+ }
+
+ isSuppressedErrorClaimedByRetry(sessionId: string, clientId: string | undefined): boolean {
+ if (!clientId) return false;
+ return this.suppressedErrors.get(sessionId)?.retryOwnerClientId === clientId;
+ }
+
+ /** Agent Island accepted the replacement prompt and can now absorb the old completion tail. */
+ markReplacementPreviewed(sessionId: string, clientId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (entry?.retryOwnerClientId !== clientId) return false;
+ entry.islandReplacementPreviewed = true;
+ return true;
+ }
+
+ /** The replacement is about to enter vendor code; later errors belong to the new attempt. */
+ markReplacementDispatching(sessionId: string, clientId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (entry?.retryOwnerClientId !== clientId) return false;
+ entry.replacementDispatching = true;
+ return true;
+ }
+
+ /** Preview rollback returns tail ownership to bookkeeping until failure disposition runs. */
+ rollbackReplacementPreview(sessionId: string, clientId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (entry?.retryOwnerClientId !== clientId) return false;
+ entry.islandReplacementPreviewed = false;
+ entry.replacementDispatching = false;
+ return true;
+ }
+
/**
* 只把压住的 error 行补落(不碰接管态、不弹横幅)。没有压住任何东西时是 no-op。
*
@@ -101,10 +180,62 @@ export class AutoResumeBookkeeping {
* 中断都必须在历史里留下痕迹。
*/
flushSuppressedError(sessionId: string): boolean {
- const suppressed = this.suppressedErrors.get(sessionId);
- if (!suppressed) return false;
+ return this.releaseSuppressedError(sessionId, false);
+ }
+
+ /** 把压住的错误一次性补落,并通知 host 将它呈现到其它用户可见表面。 */
+ surfaceSuppressedError(sessionId: string): boolean {
+ return this.releaseSuppressedError(sessionId, true);
+ }
+
+ private releaseSuppressedError(sessionId: string, surfaceError: boolean): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (!entry) return false;
+ this.suppressedErrors.delete(sessionId);
+ this.deps.persistSuppressedError(sessionId, entry.detail);
+ if (surfaceError) this.deps.surfaceSuppressedError?.(sessionId, entry.detail);
+ return true;
+ }
+
+ private releaseSuppressedErrorForRetry(
+ sessionId: string,
+ clientId: string,
+ disposition: 'flush' | 'surface' | 'discard',
+ ): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (entry?.retryOwnerClientId !== clientId) return false;
+ if (disposition === 'discard') {
+ this.suppressedErrors.delete(sessionId);
+ return true;
+ }
+ return this.releaseSuppressedError(sessionId, disposition === 'surface');
+ }
+
+ /** A claimed retry was explicitly removed before persistence (Stop / clear / policy block). */
+ flushSuppressedErrorForRetry(sessionId: string, clientId: string): boolean {
+ return this.releaseSuppressedErrorForRetry(sessionId, clientId, 'flush');
+ }
+
+ /** A claimed retry persisted but failed to dispatch, so the original failure is final. */
+ surfaceSuppressedErrorForRetry(sessionId: string, clientId: string): boolean {
+ return this.releaseSuppressedErrorForRetry(sessionId, clientId, 'surface');
+ }
+
+ /** A claimed retry crossed the irreversible dispatch boundary. */
+ discardSuppressedErrorForRetry(sessionId: string, clientId: string): boolean {
+ return this.releaseSuppressedErrorForRetry(sessionId, clientId, 'discard');
+ }
+
+ /**
+ * A provider running/terminal signal can synchronously arrive before
+ * Session.send returns accepted. Combined with replacementDispatching, that
+ * signal proves the old transient error was replaced. Dispatching alone is
+ * not proof: vendor send can still reject or the Session can close first.
+ */
+ discardReplacementProvenByProviderEvent(sessionId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ if (entry?.replacementDispatching !== true) return false;
this.suppressedErrors.delete(sessionId);
- this.deps.persistSuppressedError(sessionId, suppressed);
return true;
}
@@ -113,19 +244,48 @@ export class AutoResumeBookkeeping {
this.suppressedErrors.delete(sessionId);
}
+ /** 是否仍有一条失败轮的终态等待 disposition;供同轮 completion tail 共用这一边界。 */
+ hasSuppressedError(sessionId: string): boolean {
+ return this.suppressedErrors.has(sessionId);
+ }
+
+ /** Before preview, bookkeeping itself must keep the failed turn's completion tail out. */
+ shouldSuppressAgentIslandCompletionTail(sessionId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ return entry !== undefined && !entry.islandReplacementPreviewed;
+ }
+
+ /** After dispatch begins, an error belongs to the replacement attempt rather than the old one. */
+ shouldSuppressAgentIslandError(sessionId: string): boolean {
+ const entry = this.suppressedErrors.get(sessionId);
+ return entry !== undefined && !entry.replacementDispatching;
+ }
+
+ /**
+ * A new user action replaces an unclaimed backoff attempt. End the old
+ * ownership synchronously so the next turn cannot inherit its Island filters.
+ * Claimed entries remain owned by their exact queue-item disposition.
+ */
+ supersedeUnclaimedErrorForUserIntervention(sessionId: string): boolean {
+ this.cancelSchedule(sessionId);
+ const entry = this.suppressedErrors.get(sessionId);
+ if (!entry || entry.retryOwnerClientId !== null) return false;
+ return this.flushSuppressedError(sessionId);
+ }
+
/**
* 自愈没成 → 补落 error 行 + 结算待确认记录 + 清接管态,并按需把横幅回落出来。
*
- * `surfaceBanner=false` 用于「退避窗口内用户自己接手了」:那时再弹一条横幅只是打扰,
+ * `surfaceError=false` 用于「退避窗口内用户自己接手了」:那时再弹错误只是打扰,
* 但错误行仍要补落。
*/
- finalizeSuppressedError(sessionId: string, opts: { surfaceBanner: boolean }): void {
+ finalizeSuppressedError(sessionId: string, opts: { surfaceError: boolean }): void {
// 自愈到此为止 → 上一条续跑记录的结果就是失败。
this.settleOutcome(sessionId, 'failed');
- const suppressed = this.suppressedErrors.get(sessionId);
- this.suppressedErrors.delete(sessionId);
- if (suppressed) this.deps.persistSuppressedError(sessionId, suppressed);
- this.deps.abandonTakeover(sessionId, opts.surfaceBanner ? suppressed?.message : undefined);
+ const suppressed = this.suppressedErrors.get(sessionId)?.detail;
+ if (opts.surfaceError) this.surfaceSuppressedError(sessionId);
+ else this.flushSuppressedError(sessionId);
+ this.deps.abandonTakeover(sessionId, opts.surfaceError ? suppressed?.message : undefined);
this.deps.onAutoResumeFailed?.(sessionId);
}
@@ -173,7 +333,11 @@ export class AutoResumeBookkeeping {
* 每次排期带令牌,回调只认自己那次:否则旧回调会在它自己更早的到点时刻用新一轮的状态
* 提前打出重试,还会把新句柄一起删掉,teardown 从此取消不了任何东西(codex P1)。
*/
- schedule(sessionId: string, delayMs: number, run: () => void): void {
+ schedule(
+ sessionId: string,
+ delayMs: number,
+ run: (attempt: AutoResumeScheduleAttempt) => void | Promise<void>,
+ ): void {
this.supersedeSchedule(sessionId);
const token = ++this.scheduleSeq;
const timer = setTimeout(() => {
@@ -182,8 +346,34 @@ export class AutoResumeBookkeeping {
this.deps.log?.('interrupted-turn auto-resume callback superseded; ignoring', { sessionId });
return;
}
- this.schedules.delete(sessionId);
- run();
+ // Keep the lease cancellable while async retry classification is in flight.
+ scheduled.timer = null;
+ const attempt: AutoResumeScheduleAttempt = {
+ isCurrent: () => this.schedules.get(sessionId)?.token === token,
+ };
+ const complete = () => {
+ if (attempt.isCurrent()) this.schedules.delete(sessionId);
+ };
+ try {
+ const result = run(attempt);
+ if (result && typeof result.then === 'function') {
+ void Promise.resolve(result).then(complete, (error: unknown) => {
+ complete();
+ this.deps.log?.('interrupted-turn auto-resume callback rejected', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ } else {
+ complete();
+ }
+ } catch (error) {
+ complete();
+ this.deps.log?.('interrupted-turn auto-resume callback threw', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
}, delayMs);
this.schedules.set(sessionId, { timer, token });
}
@@ -192,22 +382,22 @@ export class AutoResumeBookkeeping {
private supersedeSchedule(sessionId: string): void {
const scheduled = this.schedules.get(sessionId);
if (!scheduled) return;
- clearTimeout(scheduled.timer);
+ if (scheduled.timer !== null) clearTimeout(scheduled.timer);
this.schedules.delete(sessionId);
this.deps.log?.('interrupted-turn auto-resume schedule superseded by a newer one', { sessionId });
}
- /** 会话终止 → 撤掉排期并把守卫的 pendingResume 回滚;没有排期时是 no-op。 */
+ /** 终止当前 attempt 并回滚守卫的 pendingResume;没有 attempt 时是 no-op。 */
cancelSchedule(sessionId: string): void {
const scheduled = this.schedules.get(sessionId);
if (!scheduled) return;
- clearTimeout(scheduled.timer);
+ if (scheduled.timer !== null) clearTimeout(scheduled.timer);
this.schedules.delete(sessionId);
this.deps.rollbackGuardPendingResume(sessionId);
- this.deps.log?.('interrupted-turn auto-resume cancelled (session terminated)', { sessionId });
+ this.deps.log?.('interrupted-turn auto-resume attempt cancelled', { sessionId });
}
- /** 仅测试与诊断用:该会话此刻有没有排期。 */
+ /** 仅测试与诊断用:该会话此刻有没有待触发或正在判定的 attempt。 */
hasSchedule(sessionId: string): boolean {
return this.schedules.has(sessionId);
}
@@ -218,13 +408,12 @@ export class AutoResumeBookkeeping {
* 会话被终止(/clear、abort、「全部停止」、关闭)时的收尾。四件事必须一起做,
* 顺序也重要:
*
- * 1. **先补落**被压住的错误行 —— 后面就没人管它了,删掉即等于那次中断消失
- * (copilot review)。`/clear` 的场景由落库侧既有的清空竞态 cap 兜住,不会把错误行
- * 写进一个已经被清空的对话。
+ * 1. **先补落**仍存在的错误。accepted=true 与实际 provider running/terminal signal
+ * 会在各自的权威边界提前删掉旧 owner;仅进入 dispatching 仍可能 reject/close,
+ * 不能按毫秒时序把那条历史静默丢掉。`/clear` 的补落由既有清空竞态 cap 兜住。
* 2. 撤排期(含回滚守卫额度)。
- * 3. 清 coordinator 接管态 —— 这也是「已经 fire、正在 await 读库」那次重试的**唯一
- * 刹车**:定时器一 fire 就摘掉了,此后撤排期已无从取消,而会话关闭刻意保留
- * recovery(手动重试入口),只有接管态被清才能让 coordinator 在 await 后收手。
+ * 3. 清 coordinator 接管态 —— attempt lease 已能挡住 late completion;这一步继续作为
+ * coordinator 自己在 await 后的复核,并撤掉用户看到的「重新连接中」。
* 4. 把悬空的待确认记录钉成 failed。
*/
teardown(sessionId: string): void {
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index f2fd3d36c8..81bb11536e 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -152,7 +152,7 @@ export interface MakerSendTransactionDeps {
content: unknown,
options: { source: string; clientId?: string },
): void;
- dispatchUserPromptPreview?(sessionId: string): void;
+ dispatchUserPromptPreview?(sessionId: string, clientId: string | undefined): void;
commitUserPromptPreview?(sessionId: string, clientId: string | undefined): void;
rollbackUserPromptPreview?(sessionId: string, clientId: string | undefined, source: string): void;
isSessionRunningError(err: unknown): boolean;
@@ -626,7 +626,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
: undefined,
onDispatching: () => {
if (userPromptPreviewSessionId) {
- deps.dispatchUserPromptPreview?.(userPromptPreviewSessionId);
+ deps.dispatchUserPromptPreview?.(
+ userPromptPreviewSessionId,
+ userPromptPreviewClientId ?? undefined,
+ );
}
},
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 484fb5e343..510a8531b7 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -584,7 +584,10 @@ import {
publishUiTurnUndispatched,
} from './uiContinuationSignal.js';
import { readSilentStopAutoResumeSettings } from '../maker-host/silent-stop-auto-resume-store.js';
-import { AutoResumeBookkeeping } from './autoResumeBookkeeping.js';
+import {
+ AutoResumeBookkeeping,
+ type SuppressedTurnError,
+} from './autoResumeBookkeeping.js';
import {
InterruptedTurnAutoResumeGuard,
isAutoResumeUserMessage,
@@ -745,6 +748,8 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({
// 3–20 秒之后),onTurnErrorEvent 无 agentMeta 时按 register 记录的 turnDedupId 做多窗
// dedup(saveTurnStartedAtForDeferred 已在压住那一刻存好 turn 开始时刻)。
persistSuppressedError: (sessionId, detail) => onTurnErrorEvent(sessionId, detail, null),
+ surfaceSuppressedError: (sessionId, detail) =>
+ surfaceSuppressedAutoResumeErrorInAgentIsland(sessionId, detail),
markOutcome: (sessionId, clientId, outcome) => {
void markAutoResumeOutcome(sessionId, clientId, outcome);
},
@@ -2359,15 +2364,25 @@ function handleAgentIslandEventAfterBroadcast(
return;
}
const terminalError = event.type === 'error' && isTerminalTurnErrorEvent(event);
- const suppressErrorSound = terminalError && (
+ const autoResumePendingOrDeferred =
agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||
- agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true
- );
- service.handleAgentEvent(meta, event, {
- // The auto-resume decision owns this one failure transition. A later
- // retry failure is evaluated independently and sounds normally if final.
- suppressErrorSound,
- });
+ agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true;
+ const autoResumeOwnsError =
+ autoResumePendingOrDeferred ||
+ autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id);
+ const autoResumeOwnsCompletionTail =
+ autoResumePendingOrDeferred ||
+ autoResumeBookkeeping.shouldSuppressAgentIslandCompletionTail(session.id);
+ if (
+ (terminalError && autoResumeOwnsError) ||
+ (isAgentIslandCompletionTail(event) && autoResumeOwnsCompletionTail)
+ ) {
+ // Auto-resume owns both the error and its provider completion tail. Do not
+ // let either enter Agent Island; the existing suppressed-error lifecycle
+ // will surface the real error once if recovery is ultimately rejected.
+ return;
+ }
+ service.handleAgentEvent(meta, event);
} catch (error) {
log.warn('Agent Island event update failed after maker event broadcast', {
sessionId: session.id,
@@ -2377,6 +2392,35 @@ function handleAgentIslandEventAfterBroadcast(
}
}
+function isAgentIslandCompletionTail(event: AgentEvent): boolean {
+ if (event.type === 'done') return true;
+ if (event.type !== 'status') return false;
+ const data = event.data as { isRunning?: unknown } | undefined;
+ return data?.isRunning === false;
+}
+
+function surfaceSuppressedAutoResumeErrorInAgentIsland(
+ sessionId: string,
+ detail: SuppressedTurnError,
+): void {
+ if (!shouldNotifyAgentIslandForSession(sessionId)) return;
+ try {
+ const service = getAgentIslandService();
+ if (!service) return;
+ const wired = wiredSessionsById.get(sessionId)?.session;
+ const meta = wired ? sessionMetaForIsland(wired) : { sessionId };
+ service.handleAgentEvent(meta, redactEventForRenderer({
+ type: 'error',
+ data: { ...detail, isTerminal: true },
+ }));
+ } catch (error) {
+ log.warn('Agent Island suppressed auto-resume error restore failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
function isRemoteAuthRetryErrorEvent(
session: { agentKind?: unknown; remoteHostId?: unknown },
event: AgentEvent,
@@ -2452,17 +2496,18 @@ function handleAgentIslandSessionClosedAfterCleanup(
}
function handleAgentIslandSessionStopped(
- session: { id: string; getCurrentTurnId?: () => string | null },
+ session: string | { id: string; getCurrentTurnId?: () => string | null },
): void {
- if (!shouldNotifyAgentIslandForSession(session.id)) return;
+ const sessionId = typeof session === 'string' ? session : session.id;
+ if (!shouldNotifyAgentIslandForSession(sessionId)) return;
try {
getAgentIslandService()?.handleSessionStopped(
- session.id,
- session.getCurrentTurnId?.() ?? null,
+ sessionId,
+ typeof session === 'string' ? null : (session.getCurrentTurnId?.() ?? null),
);
} catch (error) {
- log.warn('Agent Island session stop update failed before provider abort', {
- sessionId: session.id,
+ log.warn('Agent Island session stop update failed', {
+ sessionId,
error: error instanceof Error ? error.message : String(error),
});
}
@@ -2483,16 +2528,21 @@ function clearSuppressedOrcaWorkerAgentIslandSession(sessionId: string): void {
function notifyAgentIslandUserPrompt(
session: { id: string; agentKind?: unknown; workDir?: unknown; workspaceKind?: unknown },
content: unknown,
- options: { source: string; clientId?: string } = { source: 'unknown' },
-): void {
- if (!shouldNotifyAgentIslandForSession(session.id)) return;
+ options: { source: string; clientId?: string; replacesCurrentTurn?: boolean } = {
+ source: 'unknown',
+ },
+): boolean {
+ if (!shouldNotifyAgentIslandForSession(session.id)) return false;
const prompt = extractAgentIslandPromptText(content);
- if (!prompt) return;
+ if (!prompt) return false;
try {
- getAgentIslandService()?.handleUserPrompt(sessionMetaForIsland(session), prompt, {
+ const service = getAgentIslandService();
+ if (!service) return false;
+ return service.handleUserPrompt(sessionMetaForIsland(session), prompt, {
source: options.source,
clientId: options.clientId,
notifiedAt: Date.now(),
+ replacesCurrentTurn: options.replacesCurrentTurn,
});
} catch (error) {
log.warn('Agent Island prompt preview update failed after user message persistence', {
@@ -2501,6 +2551,7 @@ function notifyAgentIslandUserPrompt(
clientId: options.clientId,
error: error instanceof Error ? error.message : String(error),
});
+ return false;
}
}
@@ -2971,6 +3022,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
contextWindow?: number;
};
if (data.isRunning === true) {
+ // replacement 已进入 vendor 后,running 是新 attempt 的权威起点。不要依赖
+ // sendToAgent 返回后的 onDispatched 回调:provider 可同步发事件并先清 activeTurn。
+ autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);
// 新 turn 启动: 上一轮未配对的失败记账交接 id 已无归属, 丢弃防错配。
pendingFailedTurnAssistantPersistId.delete(session.id);
// 记录 turn 开始时刻,供 onTurnErrorEvent 判断 error 是否属于 /clear 之前的旧 turn。
@@ -3290,6 +3344,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// (它自己那份 set 发生在接管成立时),不存就无从补落。同 clientId 内容,覆盖无害。
if (autoResumeSuppressesPersist) {
autoResumeBookkeeping.stashSuppressedError(session.id, attributedEvent.data);
+ } else if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {
+ // replacement 可在 sendToAgent 返回前同步失败并让 coordinator 的 activeTurn
+ // 失效;这个新终态已经取代旧中断,按 dispatch phase 直接清旧 owner。
+ autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);
}
// deferred 路径保存 turn 开始时刻:isRemoteAuthRetry 时 onTurnErrorEvent 被跳过,
// renderer 会稍后调 persistTurnErrorDeferred IPC。在 resetTurnPersistState 清掉
@@ -7723,15 +7781,37 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await ackSessionTurnEndedDurable(sessionId, endedAt);
},
previewUserPrompt: (session, content, options) => {
- notifyAgentIslandUserPrompt(session, content, options);
+ const replacesCurrentTurn = autoResumeBookkeeping.isSuppressedErrorClaimedByRetry(
+ session.id,
+ options.clientId,
+ );
+ const previewed = notifyAgentIslandUserPrompt(session, content, {
+ ...options,
+ ...(replacesCurrentTurn ? { replacesCurrentTurn: true } : {}),
+ });
+ if (previewed && replacesCurrentTurn && options.clientId) {
+ autoResumeBookkeeping.markReplacementPreviewed(session.id, options.clientId);
+ }
},
- dispatchUserPromptPreview: (sessionId) => {
+ dispatchUserPromptPreview: (sessionId, clientId) => {
dispatchAgentIslandUserPrompt(sessionId);
+ if (clientId) {
+ autoResumeBookkeeping.markReplacementDispatching(sessionId, clientId);
+ }
},
commitUserPromptPreview: (sessionId, clientId) => {
commitAgentIslandUserPrompt(sessionId, clientId);
+ if (clientId) {
+ // Session.send has returned accepted=true. This is the exact authoritative
+ // success boundary even when synchronous provider events already made the
+ // coordinator active turn stale before onDispatchedUserTurn can run.
+ autoResumeBookkeeping.discardSuppressedErrorForRetry(sessionId, clientId);
+ }
},
rollbackUserPromptPreview: (sessionId, clientId, source) => {
+ if (clientId) {
+ autoResumeBookkeeping.rollbackReplacementPreview(sessionId, clientId);
+ }
rollbackAgentIslandUserPrompt(sessionId, clientId, source);
},
isSessionRunningError,
@@ -7927,6 +8007,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
};
+ /**
+ * Finalize an exact retry owner that never crossed vendor dispatch.
+ *
+ * Technical delivery failure surfaces the suppressed error once. Explicit user
+ * cancellation persists it without attention and closes the replacement Island
+ * lifecycle, so delayed provider tails cannot turn the cancelled retry into a
+ * false success. Both queued discard and persisted/pre-dispatch cancellation use
+ * this boundary; keeping the disposition here prevents those paths from drifting.
+ */
+ const finalizeUndispatchedClaimedRetry = (
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ disposition: 'cancelled' | 'failed',
+ ): boolean => {
+ if (disposition === 'failed') {
+ return autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);
+ }
+ const cancelledClaimedRetry = autoResumeBookkeeping.flushSuppressedErrorForRetry(
+ sessionId,
+ item.clientId,
+ );
+ if (!cancelledClaimedRetry) return false;
+ handleAgentIslandSessionStopped(getStableSessionForTurnBoundary(sessionId) ?? sessionId);
+ return true;
+ };
+
const reconcileSessionTurnIdle = (sessionId: string, source: string): boolean => {
const sess = getStableSessionForTurnBoundary(sessionId);
if (!sess) return false;
@@ -8122,10 +8228,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 两处必须同判据 —— 否则会出现"按住了却永远不接管"或"没按住却接管"的错配。
isResumableTurnErrorCandidate: (signals: InterruptedTurnErrorSignals) =>
isInterruptedTurnError(signals),
- // 被按住的 error 最终没接管 → 只补落 error 行(横幅 coordinator 自己设)。
- onResumableTurnErrorDiscarded: (sessionId: string) => {
- autoResumeBookkeeping.flushSuppressedError(sessionId);
- getAgentIslandService()?.restoreTaskFailureSound(sessionId);
+ // 被按住的 error 最终没接管:统一从 bookkeeping 释放。真正成为最终失败时同步到
+ // Agent Island;被用户接手或被另一条技术错误顶替时只补历史,不再打扰用户。
+ onResumableTurnErrorDiscarded: (
+ sessionId: string,
+ options: { surfaceError: boolean },
+ ) => {
+ if (options.surfaceError) autoResumeBookkeeping.surfaceSuppressedError(sessionId);
+ else autoResumeBookkeeping.flushSuppressedError(sessionId);
},
onResumableTurnError: (
sessionId: string,
@@ -8169,46 +8279,53 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (schedulerRunId) beginSchedulerAutoResume(sessionId, schedulerRunId);
// 排期的撤旧、补落与令牌都在 AutoResumeBookkeeping.schedule 里(带单测),这里只给
// 退避时长和到点要干的事。
- autoResumeBookkeeping.schedule(sessionId, decision.delayMs, () => {
- void (async () => {
- try {
- // 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery
- // 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),
- // autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚
- // pendingResume。
- const outcome = await inputCoordinator.autoRetryLastError(sessionId);
- if (outcome !== 'resumed') {
- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);
- // superseded = 用户自己接手了,别再弹横幅打扰(但中断要补进历史);
- // no-progress = 零产出、按设计不自动续跑,这是一次没人接手的真失败,
- // 必须把横幅还给用户,否则被静默吞掉(copilot review)。
- autoResumeBookkeeping.finalizeSuppressedError(sessionId, {
- surfaceBanner: outcome === 'no-progress',
- });
- if (outcome === 'no-progress') {
- getAgentIslandService()?.restoreTaskFailureSound(sessionId);
- }
- log.debug('interrupted-turn auto-resume not dispatched', { sessionId, outcome });
- return;
- }
- // 入队成功后沿用普通聊天语义丢弃被压住的错误;Schedule 的 run 接管标记
- // 不能在这里清:resumed 只表示续跑项已经进队。标记会在续跑项即将进入
- // vendor 前清掉,让同步返回的新 terminal error 只能靠**本 attempt**重新接管;
- // 派发前被 Stop / clear / ghost block 丢弃时仍由 discard/undispatched 回调
- // 立即失败同一个 run。
- autoResumeBookkeeping.discardSuppressedError(sessionId);
- log.info('interrupted-turn auto-resume dispatched', { sessionId });
- } catch (err) {
- interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);
- // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。
- autoResumeBookkeeping.finalizeSuppressedError(sessionId, { surfaceBanner: true });
- getAgentIslandService()?.restoreTaskFailureSound(sessionId);
- log.warn('interrupted-turn auto-resume failed', {
+ autoResumeBookkeeping.schedule(sessionId, decision.delayMs, async (attempt) => {
+ try {
+ // 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery
+ // 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),
+ // autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚
+ // pendingResume。
+ const outcome = await inputCoordinator.autoRetryLastError(sessionId);
+ // Timer fire 不是 ownership 终点。上面的 DB 判定 await 期间,用户可能已用
+ // Manual Retry / clearError / 新输入接管;旧回调不得再 disposition 新 owner。
+ if (!attempt.isCurrent()) {
+ log.debug('interrupted-turn auto-resume completion superseded', {
sessionId,
- error: err instanceof Error ? err.message : String(err),
+ outcome,
});
+ return;
}
- })();
+ if (outcome !== 'resumed') {
+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);
+ // superseded = 用户自己接手了,别再弹横幅打扰(但中断要补进历史);
+ // no-progress = 零产出、按设计不自动续跑,这是一次没人接手的真失败,
+ // 必须把横幅还给用户,否则被静默吞掉(copilot review)。
+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, {
+ surfaceError: outcome === 'no-progress',
+ });
+ log.debug('interrupted-turn auto-resume not dispatched', { sessionId, outcome });
+ return;
+ }
+ // resumed 只表示续跑项已经进队;被压住的错误继续由那条 item 的 clientId
+ // 持有,直到灵动岛建立 replacement-turn 边界并真正跨过 vendor dispatch。
+ // Schedule 的 run 接管标记也不能在这里清:它会在续跑项即将进入
+ // vendor 前清掉,让同步返回的新 terminal error 只能靠**本 attempt**重新接管;
+ // 派发前被 Stop / clear / ghost block 丢弃时仍由 discard/undispatched 回调
+ // 立即失败同一个 run。
+ log.info('interrupted-turn auto-resume dispatched', { sessionId });
+ } catch (err) {
+ if (!attempt.isCurrent()) {
+ log.debug('interrupted-turn auto-resume rejection superseded', { sessionId });
+ return;
+ }
+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId);
+ // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。
+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, { surfaceError: true });
+ log.warn('interrupted-turn auto-resume failed', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
});
// 回传展示信息:coordinator 存进 autoResumePending → projection → 活动行
// (「重新连接中 attempt/maxAttempts」+ 展开详情里的原因与会话累计)。
@@ -8308,6 +8425,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 失败 turn 重试 → hook 侧把这一轮接回渠道那条已收口的消息。source 区分
// 人工与自动续跑:只有真人接手才作废 scheduler waiter,自动路径不能取消自己。
onUiRetry: (sessionId, clientId, source) => {
+ autoResumeBookkeeping.claimSuppressedErrorForRetry(sessionId, clientId, source);
if (source === 'manual') {
// UI continuation can dispatch before the scheduler backoff callback.
// Retire that pending waiter first so it cannot consume the manual retry.
@@ -8319,15 +8437,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 用 enqueue 入口而不是消息文本: 零产出重试重发的是原文, 文本上无从区分,
// 而它走 unshift 不经这里, 于是不会把自己的回流作废掉。
onUserEnqueue: (sessionId) => {
+ // 同步撤掉 timer / in-flight lease 与未认领的 Island filter,新 turn 不继承旧失败。
+ autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(sessionId);
// The user turn can dispatch before the backoff callback observes that its
// recovery was superseded. Fail the scheduler waiter synchronously so it
// cannot consume that unrelated turn's text/done as this run's result.
failPendingSchedulerAutoResume(sessionId);
publishUiSessionIntervention(sessionId);
},
+ // 技术硬失败 / policy block 与用户 Stop/clear 是两种 disposition:前者没有人接手,
+ // 被压住的中断就是最终错误,必须一次性恢复到历史与 Agent Island。
+ onRejectedUserTurn: (sessionId, item) => {
+ autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);
+ },
// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。
onDiscardedQueuedMessage: (sessionId, item) => {
orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);
+ // 通用 discard 只做非打扰补落:Stop / clear / remove 不应复活旧错误;policy block
+ // 已先经 onRejectedUserTurn surface,这里按 clientId 会安全 no-op。
+ finalizeUndispatchedClaimedRetry(sessionId, item, 'cancelled');
// 持久化中的项在这里被取消后不会再走 onUndispatchedUserTurn,复用同一结算出口。
settleUndispatchedAutoResumeOutcome(sessionId, item);
// 排队心跳被丢弃 → 通知 runner 按 aborted 收尾对应 run,不让 fire 永久挂起。
@@ -8404,10 +8532,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
publishUiTurnDispatching(sessionId, item.clientId);
return gitSnapshotCoordinator?.onTurnStart(sessionId);
},
- onUndispatchedUserTurn: (sessionId, item) => {
+ onUndispatchedUserTurn: (sessionId, item, disposition) => {
// 目标轮落库了却没能 dispatch(取消 / 失败): 记账该立刻还回去, 而不是等超时。
publishUiTurnUndispatched(sessionId, item.clientId);
gitSnapshotCoordinator?.onTurnAbort(sessionId);
+ // persisted/pre-dispatch 与仍在队列的取消共用同一个 exact-owner 终局;技术失败
+ // 必须 surface,用户接管则进入 stopped,二者不能再靠调用路径隐式推断。
+ finalizeUndispatchedClaimedRetry(sessionId, item, disposition);
// 自动续跑那条消息已落库、却最终没派出去 → 这次重连就是失败。**必须在这里钉死**:
// 它不会产生任何 turn 事件,新加的终态结算路径够不到它,待确认记录于是悬空,被之后
// 任何一个无关的 text / tool 事件误标成「已重新连接」(codex P1)。