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): recover stuck session input queues (#1268)

Dashc8f33db6fd5a
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 0dcea5fbf9..df4b69aaf8 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -221,7 +221,7 @@ describe('maker:event hot path ordering', () => {
expect(coordinatorAbortEnd).toBeGreaterThan(coordinatorAbortStart);
expectOrder(
coordinatorAbortSource,
- 'const sess = maker.getSession(sessionId);',
+ 'const sess = getStableSessionForTurnBoundary(sessionId);',
'if (!sess) return;',
);
expectOrder(
@@ -238,9 +238,10 @@ describe('maker:event hot path ordering', () => {
expect(directAbortEnd).toBeGreaterThan(directAbortStart);
expectOrder(
directAbortSource,
- 'const sess = maker.getSession(sessionId);',
+ 'const sess = getStableSessionForTurnBoundary(sessionId);',
'if (!sess) return;',
);
+ expect(directAbortSource).not.toContain('const sess = maker.getSession(sessionId);');
expectOrder(
directAbortSource,
'if (!sess) return;',
@@ -251,6 +252,24 @@ describe('maker:event hot path ordering', () => {
'handleAgentIslandSessionStopped(sess);',
'await sess.abort();',
);
+ expect(directAbortSource).toContain(
+ 'const directAbortBoundary = beginDirectAbortReconciliation(sessionId, sess);',
+ );
+ expectOrder(
+ directAbortSource,
+ 'const directAbortBoundary = beginDirectAbortReconciliation(sessionId, sess);',
+ 'await sess.abort();',
+ );
+ expect(directAbortSource).toContain(
+ "reconcileDirectAbortBoundary(sessionId, directAbortBoundary, 'direct-abort');",
+ );
+ expect(directAbortSource).not.toContain("reconcileSessionTurnIdle(sessionId, 'direct-abort');");
+ expect(directAbortSource).not.toContain('if (!sess.isTurnRunning())');
+ expectOrder(
+ directAbortSource,
+ "reconcileDirectAbortBoundary(sessionId, directAbortBoundary, 'direct-abort');",
+ "cleanupPendingInteractionsForSession(sessionId, 'session_aborted');",
+ );
expect(hookAbortStart).toBeGreaterThanOrEqual(0);
expect(hookAbortEnd).toBeGreaterThan(hookAbortStart);
expectOrder(
@@ -273,6 +292,45 @@ describe('maker:event hot path ordering', () => {
);
});
+ it('uses the wired Session snapshot while reconciling owner-boundary aborts', () => {
+ const stableLookupStart = source.indexOf('const getStableSessionForTurnBoundary =');
+ const stableLookupEnd = source.indexOf('\n const reconcileSessionTurnIdle =', stableLookupStart);
+ const stableLookupSource = source.slice(stableLookupStart, stableLookupEnd);
+ const reconcileStart = stableLookupEnd;
+ const reconcileEnd = source.indexOf('\n\n const inputCoordinator:', reconcileStart);
+ const reconcileSource = source.slice(reconcileStart, reconcileEnd);
+
+ expect(stableLookupStart).toBeGreaterThanOrEqual(0);
+ expect(stableLookupEnd).toBeGreaterThan(stableLookupStart);
+ expect(stableLookupSource).toContain('wiredSessionsById.get(sessionId)?.session');
+ expectOrder(stableLookupSource, 'if (wired) return wired;', 'return maker.getSession(sessionId) ?? null;');
+ expect(stableLookupSource).toContain('return null;');
+
+ expect(reconcileStart).toBeGreaterThanOrEqual(0);
+ expect(reconcileEnd).toBeGreaterThan(reconcileStart);
+ expect(reconcileSource).toContain('if (!liveSessionIdle) return false;');
+ expect(reconcileSource).not.toContain('if (!trackerStale && !hadZombieInteraction) return false;');
+ expect(reconcileSource).toContain('confirmed live session idle during turn-boundary reconciliation');
+ });
+
+ it('keeps direct abort reconciliation fail-closed across owner replacement and new turns', () => {
+ const helperStart = source.indexOf('const readDirectAbortTurnId =');
+ const helperEnd = source.indexOf('\n\n const inputCoordinator:', helperStart);
+ const helperSource = source.slice(helperStart, helperEnd);
+ const wireSessionSource = extractWireSessionSource();
+ const closedBlock = wireSessionSource.slice(wireSessionSource.indexOf("if (status === 'closed') {"));
+
+ expect(source).toContain('const sessionTurnBoundaryGenerationById = new Map<string, number>();');
+ expect(source).toContain('const directAbortReconcileBoundaries = new Map<string, DirectAbortReconcileBoundary>();');
+ expect(helperSource).toContain('wiredSessionsById.get(sessionId)?.session !== boundary.session');
+ expect(helperSource).toContain('currentSessionTurnBoundaryGeneration(sessionId) !== boundary.generation');
+ expect(helperSource).toContain('direct-abort-retry');
+ expect(helperSource).toContain('cancelDirectAbortReconciliation(sessionId, boundary);');
+ expect(wireSessionSource).toContain('if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);');
+ expect(closedBlock).toContain('cancelDirectAbortReconciliation(session.id);');
+ expect(closedBlock).toContain('sessionTurnBoundaryGenerationById.delete(session.id);');
+ });
+
it('keeps Codex subscription value out of real session cost totals', () => {
const wireSessionSource = extractWireSessionSource();
const codexDoneIndex = wireSessionSource.indexOf("event.type === 'done' && event.source === 'codex'");
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 154aca7148..d37c5ea76a 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
@@ -165,7 +165,7 @@ function createHarness() {
const steerToAgent = vi.fn<AgentInputCoordinatorDeps['steerToAgent']>(async () => {});
const abortSession = vi.fn<AgentInputCoordinatorDeps['abortSession']>(async () => {});
const getSdkSessionId = vi.fn<AgentInputCoordinatorDeps['getSdkSessionId']>(async () => 'sdk-session');
- const reconcileTurnIdle = vi.fn<NonNullable<AgentInputCoordinatorDeps['reconcileTurnIdle']>>(() => {});
+ const reconcileTurnIdle = vi.fn<NonNullable<AgentInputCoordinatorDeps['reconcileTurnIdle']>>(() => false);
const beforeDispatchUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['beforeDispatchUserTurn']>>(() => {});
const onUndispatchedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUndispatchedUserTurn']>>(() => {});
const onAcceptedQueuedMessage = vi.fn<NonNullable<AgentInputCoordinatorDeps['onAcceptedQueuedMessage']>>(() => {});
@@ -3534,6 +3534,238 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'second' });
});
+ it('reconciles a dead Claude turn when abort rejects after the vendor has stopped', async () => {
+ const h = createHarness();
+ const sid = 'stop-claude-abort-rejected';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'second');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ h.abortSession.mockRejectedValueOnce(new Error('Claude Code process aborted by user'));
+ h.reconcileTurnIdle.mockImplementationOnce(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+ h.coordinator.resume(sid);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ 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('releases a Codex abort lock when reconciliation proves the vendor has stopped', async () => {
+ const h = createHarness();
+ const sid = 'stop-codex-abort-rejected';
+ 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' },
+ });
+ h.setAgentKind('codex');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ h.abortSession.mockRejectedValueOnce(new Error('Codex process aborted by user'));
+ h.reconcileTurnIdle.mockImplementationOnce(() => {
+ h.setRunning(false);
+ return true;
+ });
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+ h.coordinator.resume(sid);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ 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.each([
+ { agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },
+ { agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },
+ ])('retries abort reconciliation after $agentKind abort settles before the live turn is idle', async ({
+ agentKind,
+ providerId,
+ model,
+ }) => {
+ vi.useFakeTimers();
+ const h = createHarness();
+ const sid = `stop-delayed-idle-${agentKind}`;
+ const first = makeItem('q-1', 'first', {
+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },
+ });
+ const second = makeItem('q-2', 'second', {
+ createOpts: { ...makeItem('tmp2', 'tmp2').createOpts, agentKind, providerId, model },
+ });
+ const abort = deferred<void>();
+ h.setAgentKind(agentKind);
+ h.abortSession.mockImplementationOnce(() => abort.promise);
+ h.reconcileTurnIdle
+ .mockReturnValueOnce(false)
+ .mockImplementationOnce(() => {
+ h.setRunning(false);
+ return true;
+ });
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+ h.coordinator.resume(sid);
+ abort.resolve();
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(1);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).pendingQueue).toEqual([second]);
+
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(2);
+ 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('retains an abort lock when owner switching hides the agent kind and live idle cannot be confirmed', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = createHarness();
+ const sid = 'stop-owner-boundary-agent-unknown';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'second');
+ h.setAgentKind(null);
+ h.reconcileTurnIdle
+ .mockReturnValueOnce(false)
+ .mockImplementationOnce(() => true);
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+ h.coordinator.resume(sid);
+ h.setRunning(false);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).queueAbortPending).toBe(true);
+
+ // The owner is available again before the delayed retry. The retry must
+ // keep the lock until the authoritative reconciliation proves idle.
+ h.setAgentKind('codex');
+ await vi.advanceTimersByTimeAsync(250);
+ await flush();
+
+ expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(latestProjection(h.projections).queueAbortPending).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('ignores an old abort completion after clearSession starts a new turn', async () => {
+ const h = createHarness();
+ const sid = 'stop-abort-clear-new-turn';
+ const first = makeItem('q-1', 'first', {
+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind: 'codex' },
+ });
+ const replacement = makeItem('q-new', 'replacement', {
+ createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind: 'codex' },
+ });
+ const abort = deferred<void>();
+ h.setAgentKind('codex');
+ h.abortSession.mockImplementationOnce(() => abort.promise);
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+
+ // The user explicitly resets the session while the old abort RPC is still
+ // pending, then starts a new turn in the replacement state.
+ h.coordinator.clearSession(sid);
+ h.setRunning(false);
+ h.coordinator.enqueue(sid, replacement);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ h.reconcileTurnIdle.mockReturnValueOnce(true);
+ abort.resolve();
+ await flush();
+
+ const state = (
+ h.coordinator as unknown as {
+ getState: (id: string) => { activeTurn: { item: AgentInputQueuedMessage | null } | null };
+ }
+ ).getState(sid);
+ expect(state.activeTurn?.item?.clientId).toBe('q-new');
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },
+ { agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },
+ ])('invalidates an old abort token when $agentKind starts a new turn after a non-preserving stop', async ({
+ agentKind,
+ providerId,
+ model,
+ }) => {
+ const h = createHarness();
+ const sid = `stop-abort-new-turn-${agentKind}`;
+ const first = makeItem('q-1', 'first', {
+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },
+ });
+ const replacement = makeItem('q-new', 'replacement', {
+ createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind, providerId, model },
+ });
+ const abort = deferred<void>();
+ const beforeDispatch = deferred<void>();
+ h.setAgentKind(agentKind);
+ h.abortSession.mockImplementationOnce(() => abort.promise);
+ h.beforeDispatchUserTurn.mockImplementationOnce(() => beforeDispatch.promise);
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.stop(sid, { keepQueue: false });
+ h.setRunning(false);
+ beforeDispatch.resolve();
+ await flush();
+
+ // A non-preserving stop does not hold queueAbortPending, so a replacement
+ // turn can start while the old vendor abort promise is still unresolved.
+ h.coordinator.enqueue(sid, replacement);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+
+ abort.resolve();
+ await flush();
+
+ const state = (
+ h.coordinator as unknown as {
+ getState: (id: string) => { activeTurn: { item: AgentInputQueuedMessage | null } | null };
+ }
+ ).getState(sid);
+ expect(state.activeTurn?.item?.clientId).toBe('q-new');
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ });
+
it('keeps Codex queue abort lock until a real turn boundary', async () => {
const h = createHarness();
const sid = 'stop-codex';
@@ -4288,6 +4520,7 @@ describe('AgentInputCoordinator steer transaction', () => {
// host 校准: 复核后清掉 stale busy tracker (镜像 register.ts 的接线行为)。
h.reconcileTurnIdle.mockImplementationOnce(() => {
h.setRunning(false);
+ return true;
});
const ok = await h.coordinator.steer(sid, second, { removeFromQueue: true });
@@ -4338,7 +4571,10 @@ describe('AgentInputCoordinator steer transaction', () => {
await flush();
h.coordinator.enqueue(sid, markerOnly);
h.steerToAgent.mockRejectedValueOnce(new Error('[NO_ACTIVE_TURN] Session has no active turn'));
- h.reconcileTurnIdle.mockImplementationOnce(() => h.setRunning(false));
+ h.reconcileTurnIdle.mockImplementationOnce(() => {
+ h.setRunning(false);
+ return true;
+ });
await expect(h.coordinator.steer(sid, incoming, { removeFromQueue: true })).resolves.toBe(true);
await flush();
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 17536dd625..b6ff094c63 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -130,12 +130,14 @@ export interface AgentInputCoordinatorDeps {
abortSession: (sessionId: string) => Promise<void>;
isTurnRunning: (sessionId: string) => boolean;
/**
- * steer 收到 maker-core 权威的 NO_ACTIVE_TURN 后回调 host 校准 busy 视图。
- * isTurnRunning 的事件驱动 tracker 可能 stale 为 true (turn 异常死亡没发
- * terminal event), 此时 fallback 转普通派发后 drain 会被假忙永久挡住,
- * 插话点击表现为"毫无反应"。host 实现应自行复核后再清 tracker。
+ * Reconcile the host's live session/tracker view after an abort or a
+ * maker-core NO_ACTIVE_TURN. The event-driven tracker can stay stale when a
+ * turn dies without a terminal event, leaving the queue behind a false busy
+ * boundary. Returns true only when it actually cleared that stale boundary;
+ * a normal status=closed cleanup returning false must not make Codex release
+ * its abort lock before the in-flight send outcome settles.
*/
- reconcileTurnIdle?: (sessionId: string) => void;
+ reconcileTurnIdle?: (sessionId: string) => boolean;
hasPendingInteraction: (sessionId: string) => boolean;
getAgentKind: (sessionId: string) => 'claude-code' | 'codex' | null;
getSdkSessionId: (sessionId: string) => Promise<string | undefined>;
@@ -366,6 +368,18 @@ interface SessionInputState {
/** Codex emits terminal error followed by done; queued work must not drain between the pair. */
pendingExternalTerminalDone: boolean;
pendingExternalTerminalDoneTimer: ReturnType<typeof setTimeout> | null;
+ /**
+ * Identity of the current user-stop abort boundary. An old abort promise may
+ * settle after clearSession/new turn; its cleanup must not release the newer
+ * turn's boundary or clear its activeTurn.
+ */
+ abortBoundaryToken: symbol | null;
+ /**
+ * Session.abort() may settle before maker-core publishes the idle state. Keep
+ * rechecking the same abort boundary until the live turn is idle or a newer
+ * state invalidates it.
+ */
+ abortReconcileRetryTimer: ReturnType<typeof setTimeout> | null;
sessionRunningRetryTimer: ReturnType<typeof setTimeout> | null;
sessionRunningRetryGeneration: number | null;
/**
@@ -406,6 +420,8 @@ function createInitialInputState(generation = 0): SessionInputState {
drainWakeupGeneration: 0,
pendingExternalTerminalDone: false,
pendingExternalTerminalDoneTimer: null,
+ abortBoundaryToken: null,
+ abortReconcileRetryTimer: null,
sessionRunningRetryTimer: null,
sessionRunningRetryGeneration: null,
credentialSwitchWait: null,
@@ -1009,6 +1025,7 @@ export class AgentInputCoordinator {
reason: string,
): Promise<AgentInputProjection> {
const state = this.getState(sessionId);
+ this.invalidateAbortBoundaryForNewTurn(state);
const active: ActiveTurn = {
item: null,
delivery: 'turn',
@@ -1327,6 +1344,7 @@ export class AgentInputCoordinator {
accepted.error = null;
accepted.stickyError = null;
accepted.recovery = null;
+ this.invalidateAbortBoundaryForNewTurn(accepted);
accepted.activeTurn = {
item,
delivery: 'steer',
@@ -1379,6 +1397,7 @@ export class AgentInputCoordinator {
const state = this.getState(sessionId);
const preserveQueue = opts?.keepQueue === true;
this.abortSteerTransactions(sessionId);
+ this.clearAbortReconcileRetry(state);
// Stop 是用户显式收手:凭证切换等待随之取消(保留队列时队首仍在,恢复后会重新进入等待)。
this.clearCredentialSwitchWait(state);
if (!preserveQueue) {
@@ -1415,6 +1434,9 @@ export class AgentInputCoordinator {
// Stop 出来的暂停是用户显式意图,不许后续新输入静默放行(区别于崩溃恢复暂停)。
state.queuePausedByRestore = false;
state.queueAbortPending = shouldPause && this.isDispatchBoundaryBusy(sessionId, state);
+ const abortBoundaryToken = Symbol('agent-input-abort-boundary');
+ const abortBoundaryGeneration = state.generation;
+ state.abortBoundaryToken = abortBoundaryToken;
state.steeringQueueClientIds = [];
state.queueExpanded = false;
this.emit(sessionId);
@@ -1424,8 +1446,32 @@ export class AgentInputCoordinator {
log.warn('abortSession failed', { sessionId, error: errorMessage(err) });
})
.finally(() => {
- if (this.deps.getAgentKind(sessionId) === 'codex') return;
- this.releaseAbortLockAndDrain(sessionId, 'abort-promise', { clearActiveTurn: true });
+ const current = this.states.get(sessionId);
+ if (
+ current !== state ||
+ current.generation !== abortBoundaryGeneration ||
+ current.abortBoundaryToken !== abortBoundaryToken
+ ) {
+ // clearSession, a newer Stop, or a terminal event has superseded this
+ // abort. Its late promise must not touch the current session state.
+ log.info('ignoring stale abort completion', {
+ sessionId,
+ abortBoundaryGeneration,
+ currentGeneration: current?.generation,
+ });
+ return;
+ }
+ // `Session.abort()` can settle before the vendor process has actually
+ // published its idle state. Keep this boundary alive and recheck it
+ // instead of relying on a terminal event that may be lost during an
+ // owner switch.
+ this.reconcileAbortBoundary(
+ sessionId,
+ state,
+ abortBoundaryGeneration,
+ abortBoundaryToken,
+ 'abort-promise',
+ );
});
return this.getProjection(sessionId);
@@ -1822,6 +1868,7 @@ export class AgentInputCoordinator {
clearSession(sessionId: string, clearedAt: string | number = Date.now()): AgentInputProjection {
this.deps.noteSessionClearBoundary?.(sessionId, clearedAt);
const prev = this.getState(sessionId);
+ this.clearAbortReconcileRetry(prev);
this.clearSessionRunningRetry(prev);
this.clearCredentialSwitchWait(prev);
this.clearPendingExternalTerminalDone(prev);
@@ -1851,7 +1898,9 @@ export class AgentInputCoordinator {
): void {
const state = this.getState(sessionId);
const active = state.activeTurn;
+ this.clearAbortReconcileRetry(state);
state.queueAbortPending = false;
+ state.abortBoundaryToken = null;
if (type === 'error') {
if (active?.persisted) {
state.activeTurn = null;
@@ -2009,6 +2058,7 @@ export class AgentInputCoordinator {
const state = this.getState(sessionId);
const releasedAbortLock = state.queueAbortPending;
this.cancelScheduledDrain(state);
+ this.clearAbortReconcileRetry(state);
this.clearSessionRunningRetry(state);
this.clearPendingExternalTerminalDone(state);
this.abortSteerTransactions(sessionId);
@@ -2020,12 +2070,14 @@ export class AgentInputCoordinator {
this.handleActiveTurnClosedBeforeDispatch(sessionId, state, active);
}
state.queueAbortPending = false;
+ state.abortBoundaryToken = null;
state.steeringQueueClientIds = [];
this.emit(sessionId);
return;
}
state.activeTurn = null;
state.queueAbortPending = false;
+ state.abortBoundaryToken = null;
state.steeringQueueClientIds = [];
this.emit(sessionId);
if (releasedAbortLock) this.scheduleDrain(sessionId, 'session-closed-abort-boundary');
@@ -2229,6 +2281,7 @@ export class AgentInputCoordinator {
state.error = null;
}
state.recovery = null;
+ this.invalidateAbortBoundaryForNewTurn(state);
const active: ActiveTurn = {
item: head,
delivery: 'turn',
@@ -2849,7 +2902,7 @@ export class AgentInputCoordinator {
private releaseAbortLockAndDrain(
sessionId: string,
reason: string,
- opts?: { clearActiveTurn?: boolean },
+ opts?: { clearActiveTurn?: boolean; preserveAbortBoundaryToken?: boolean },
): void {
const state = this.getState(sessionId);
if (opts?.clearActiveTurn) {
@@ -2860,10 +2913,145 @@ export class AgentInputCoordinator {
}
if (!state.queueAbortPending && !opts?.clearActiveTurn) return;
state.queueAbortPending = false;
+ if (!opts?.preserveAbortBoundaryToken) {
+ this.clearAbortReconcileRetry(state);
+ state.abortBoundaryToken = null;
+ }
this.emit(sessionId);
this.scheduleDrain(sessionId, reason);
}
+ /**
+ * A stop abort is scoped to the turn that existed when stop was requested.
+ * A non-preserving stop does not keep the abort lock, so a new enqueue may
+ * start another turn before the old vendor abort promise settles. Invalidate
+ * the old token at that new-turn boundary; otherwise the late abort callback
+ * would pass the state/generation check and clear the replacement turn.
+ */
+ private invalidateAbortBoundaryForNewTurn(state: SessionInputState): void {
+ this.clearAbortReconcileRetry(state);
+ state.abortBoundaryToken = null;
+ }
+
+ private reconcileAbortBoundary(
+ sessionId: string,
+ state: SessionInputState,
+ abortBoundaryGeneration: number,
+ abortBoundaryToken: symbol,
+ source: string,
+ ): void {
+ const current = this.states.get(sessionId);
+ if (
+ current !== state ||
+ current.generation !== abortBoundaryGeneration ||
+ current.abortBoundaryToken !== abortBoundaryToken
+ ) {
+ return;
+ }
+
+ let reconciledIdle = false;
+ try {
+ reconciledIdle = this.deps.reconcileTurnIdle?.(sessionId) === true;
+ } catch (err) {
+ // A best-effort reconciliation must never prevent the retry path from
+ // keeping the boundary fail-closed.
+ log.warn('reconcileTurnIdle after abort failed', {
+ sessionId,
+ source,
+ error: errorMessage(err),
+ });
+ }
+ if (reconciledIdle) {
+ this.releaseAbortLockAndDrain(sessionId, 'abort-idle-reconciled', { clearActiveTurn: true });
+ return;
+ }
+
+ let agentKind: 'claude-code' | 'codex' | null = null;
+ try {
+ agentKind = this.deps.getAgentKind(sessionId);
+ } catch (err) {
+ log.warn('agent kind lookup failed during abort reconciliation', {
+ sessionId,
+ source,
+ error: errorMessage(err),
+ });
+ }
+
+ let liveTurnRunning = true;
+ try {
+ liveTurnRunning = this.deps.isTurnRunning(sessionId);
+ } catch (err) {
+ log.warn('live turn-state lookup failed during abort reconciliation', {
+ sessionId,
+ source,
+ error: errorMessage(err),
+ });
+ }
+
+ // Claude can release its queue lock as soon as abort settles, but keep the
+ // boundary token while the live turn is still running so a delayed idle
+ // reconciliation can clear stale tracker state without touching a newer
+ // turn. Codex keeps queueAbortPending until idle is authoritative.
+ //
+ // During an owner-boundary replacement the agent kind can temporarily be
+ // unknown. That is not proof that the boundary is gone: keep retrying while
+ // the queue lock or live turn says work may still exist, but remain
+ // fail-closed until a later reconciliation proves the Session is idle.
+ const shouldRetry = current.queueAbortPending || liveTurnRunning;
+ if (agentKind === 'claude-code' && (current.queueAbortPending || current.activeTurn !== null)) {
+ this.releaseAbortLockAndDrain(sessionId, 'abort-promise', {
+ clearActiveTurn: true,
+ preserveAbortBoundaryToken: shouldRetry,
+ });
+ }
+ if (shouldRetry) {
+ this.scheduleAbortReconcileRetry(
+ sessionId,
+ current,
+ abortBoundaryGeneration,
+ abortBoundaryToken,
+ );
+ } else if (!current.queueAbortPending && current.activeTurn === null) {
+ // Nothing remains that this stop boundary can own. Do not leave a stale
+ // token behind after the one-shot Claude cleanup path has completed.
+ current.abortBoundaryToken = null;
+ }
+ }
+
+ private scheduleAbortReconcileRetry(
+ sessionId: string,
+ state: SessionInputState,
+ abortBoundaryGeneration: number,
+ abortBoundaryToken: symbol,
+ ): void {
+ if (state.abortReconcileRetryTimer) return;
+ state.abortReconcileRetryTimer = setTimeout(() => {
+ const current = this.states.get(sessionId);
+ if (current === state) current.abortReconcileRetryTimer = null;
+ if (
+ current !== state ||
+ current.generation !== abortBoundaryGeneration ||
+ current.abortBoundaryToken !== abortBoundaryToken
+ ) {
+ return;
+ }
+ this.reconcileAbortBoundary(
+ sessionId,
+ current,
+ abortBoundaryGeneration,
+ abortBoundaryToken,
+ 'abort-retry',
+ );
+ }, SESSION_RUNNING_RETRY_DELAY_MS);
+ }
+
+ private clearAbortReconcileRetry(state: SessionInputState): void {
+ if (state.abortReconcileRetryTimer) {
+ clearTimeout(state.abortReconcileRetryTimer);
+ }
+ state.abortReconcileRetryTimer = null;
+ }
+
private registerSteerAbortController(sessionId: string, clientId: string, controller: AbortController): void {
let byClientId = this.steerAbortControllers.get(sessionId);
if (!byClientId) {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 87ba6a52c4..d3aac69df5 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1726,6 +1726,45 @@ interface WiredSessionRegistration {
*/
const wiredSessionsById = new Map<string, WiredSessionRegistration>();
+/**
+ * Monotonic logical-turn generation used by direct abort reconciliation.
+ * Session ids survive owner-boundary replacement, so the Session object alone
+ * is not enough to reject a late retry for a newer turn on the same instance.
+ */
+const sessionTurnBoundaryGenerationById = new Map<string, number>();
+
+interface DirectAbortReconcileBoundary {
+ session: WiredSession;
+ generation: number;
+ turnId: string | null;
+ retryTimer: ReturnType<typeof setTimeout> | null;
+}
+
+/** One direct ABORT_SESSION retry chain per session; a newer abort supersedes the old one. */
+const directAbortReconcileBoundaries = new Map<string, DirectAbortReconcileBoundary>();
+const DIRECT_ABORT_RECONCILE_RETRY_DELAY_MS = 250;
+
+function currentSessionTurnBoundaryGeneration(sessionId: string): number {
+ return sessionTurnBoundaryGenerationById.get(sessionId) ?? 0;
+}
+
+function advanceSessionTurnBoundaryGeneration(sessionId: string): number {
+ const next = currentSessionTurnBoundaryGeneration(sessionId) + 1;
+ sessionTurnBoundaryGenerationById.set(sessionId, next);
+ return next;
+}
+
+function cancelDirectAbortReconciliation(
+ sessionId: string,
+ expected?: DirectAbortReconcileBoundary,
+): void {
+ const boundary = directAbortReconcileBoundaries.get(sessionId);
+ if (!boundary || (expected && boundary !== expected)) return;
+ if (boundary.retryTimer) clearTimeout(boundary.retryTimer);
+ boundary.retryTimer = null;
+ directAbortReconcileBoundaries.delete(sessionId);
+}
+
/**
* SDK result 事件的 total_cost_usd 是 session 累计 (不是 per-turn) ——
* 老 vendor/claude/usageExtractor.ts:72-74 也确认过。要算"这一 turn 花了多少"
@@ -1841,6 +1880,17 @@ const rewindInputSessions = new Set<string>();
const SESSION_REWIND_INPUT_LOCK_ID = 'session-rewind';
const SESSION_REWIND_STOP_TIMEOUT_MS = 15_000;
let pendingCredentialSwitchHolder: PendingCredentialSwitchService | null = null;
+function settlePendingCredentialSwitch(sessionId: string, source: string): void {
+ const pending = pendingCredentialSwitchHolder?.onTurnSettled(sessionId);
+ if (!pending) return;
+ void pending.catch((err) => {
+ log.warn('pending credential switch settle failed', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+}
// turn 收口时对远端 codex MCP 做一次 best-effort ensure 的钩子 (live turn
// 期间被推迟的 daemon bootstrap 在 idle 时点补刀)。真实现定义在
// registerMakerIpcs 闭包内 (依赖 maker / ensure 函数), 模块级 turn 收口
@@ -2518,7 +2568,7 @@ function settleSilentStopDone(sessionId: string, reason: 'exhausted' | 'skip' |
sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(sessionId);
noteClaudeSessionTurnState(sessionId, false);
agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');
- void pendingCredentialSwitchHolder?.onTurnSettled(sessionId);
+ settlePendingCredentialSwitch(sessionId, `silent-stop:${reason}`);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);
refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);
@@ -2649,9 +2699,13 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
return;
}
if (existing) {
+ // A runtime replacement invalidates any delayed direct-abort callback that
+ // still belongs to the old Session instance.
+ cancelDirectAbortReconciliation(session.id);
for (const dispose of existing.disposers) dispose();
existing.session.setInteractionListener(null);
}
+ advanceSessionTurnBoundaryGeneration(session.id);
const registration: WiredSessionRegistration = { session, disposers: [] };
wiredSessionsById.set(session.id, registration);
@@ -2756,6 +2810,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
interruptedTurnAutoResumeGuard.noteTurnStarted(session.id);
const wasInTurn = sessionTurnActivityTracker.isSessionInTurn(session.id);
sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning);
+ if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);
// 后台活动检测:turn 开始 → 该会话的 API 流量回归主线,后台横幅熄灭。
noteClaudeSessionTurnState(session.id, true);
if (!wasInTurn) {
@@ -2967,7 +3022,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 提前唤醒会让 apply/重试读到 isSessionInTurn=true 而空转,退化到 10s 兜底
// (review P2 2026-07-04)。apply 内部串行 + 幂等,fire-and-forget 安全;
// planned upgrade close 等场景多唤一次也只是 no-op。
- void pendingCredentialSwitchHolder?.onTurnSettled(session.id);
+ settlePendingCredentialSwitch(session.id, `event:${event.type}`);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
@@ -3544,38 +3599,80 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
}));
registration.disposers.push(session.onStatusChange((status) => {
if (wiredSessionsById.get(session.id)?.session !== session) return;
- broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });
+ // The local window broadcast is best-effort, but keep this guard here as
+ // well because status callbacks are a lifecycle boundary: a third-party
+ // bridge must not be able to skip session cleanup by throwing.
+ try {
+ broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });
+ } catch (err) {
+ log.warn('session status broadcast failed', {
+ sessionId: session.id,
+ status,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
if (status === 'closed') {
- cleanupPendingInteractionsForSession(session.id, 'session_closed');
- // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、
- // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录
- // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,
- // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。
- autoResumeBookkeeping.teardown(session.id);
- agentInputCoordinatorHolder?.onSessionClosed(session.id);
- // 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。
- pendingCredentialSwitchHolder?.onSessionClosed(session.id);
- deferredCodexRestartHolder?.onSessionSettled();
- agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
- refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
- gitSnapshotCoordinator?.onSessionClosed(session.id);
- wiredSessionsById.delete(session.id);
- for (const dispose of registration.disposers) dispose();
- session.setInteractionListener(null);
- clearOrcaMcpHydrated(session.id);
- knownNonOrcaSessionIds.delete(session.id);
- lastReportedCostUsdBySession.delete(session.id);
- lastReportedModelUsageBySession.delete(session.id);
- turnModelPromiseBySession.delete(session.id);
- sessionTurnActivityTracker.deleteSession(session.id);
- markSessionTurnEnded(session.id);
- // 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。
- clearClaudeSessionBackgroundActivity(session.id);
- clearSessionPersistState(session.id);
- // 进程关闭 ≠ 通知作废:临时会话调度(非 heartbeat / 非 persistentSession)在 run
- // 终态后立刻 closeSession,此刻完成卡片刚在灵动岛上弹出来。硬删条目会让它当场
- // 消失,所以这条路径保留仍在展示的卡片,由 dwell 到期或用户 ack 收掉。
- handleAgentIslandSessionClosedAfterCleanup(session.id, 'process-closed');
+ try {
+ cleanupPendingInteractionsForSession(session.id, 'session_closed');
+ // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、
+ // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录
+ // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,
+ // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。
+ autoResumeBookkeeping.teardown(session.id);
+ agentInputCoordinatorHolder?.onSessionClosed(session.id);
+ // 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。
+ pendingCredentialSwitchHolder?.onSessionClosed(session.id);
+ deferredCodexRestartHolder?.onSessionSettled();
+ agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
+ gitSnapshotCoordinator?.onSessionClosed(session.id);
+ clearOrcaMcpHydrated(session.id);
+ knownNonOrcaSessionIds.delete(session.id);
+ lastReportedCostUsdBySession.delete(session.id);
+ lastReportedModelUsageBySession.delete(session.id);
+ turnModelPromiseBySession.delete(session.id);
+ // 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。
+ clearClaudeSessionBackgroundActivity(session.id);
+ clearSessionPersistState(session.id);
+ // 进程关闭 ≠ 通知作废:临时会话调度(非 heartbeat / 非 persistentSession)在 run
+ // 终态后立刻 closeSession,此刻完成卡片刚在灵动岛上弹出来。硬删条目会让它当场
+ // 消失,所以这条路径保留仍在展示的卡片,由 dwell 到期或用户 ack 收掉。
+ handleAgentIslandSessionClosedAfterCleanup(session.id, 'process-closed');
+ } catch (err) {
+ log.warn('session close cleanup failed; forcing idle reconciliation', {
+ sessionId: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ // Wiring teardown is independent of the best-effort product cleanup
+ // above. A single disposer or listener error must not leave a closed
+ // session reachable from the in-memory routing map.
+ cancelDirectAbortReconciliation(session.id);
+ wiredSessionsById.delete(session.id);
+ for (const dispose of registration.disposers) {
+ try {
+ dispose();
+ } catch (err) {
+ log.warn('session disposer failed during close teardown', {
+ sessionId: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ try {
+ session.setInteractionListener(null);
+ } catch (err) {
+ log.warn('session interaction listener teardown failed', {
+ sessionId: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ // This must run even when an owner-boundary-sensitive cleanup above
+ // rejects. A closed Session cannot keep the desktop turn boundary busy.
+ sessionTurnActivityTracker.deleteSession(session.id);
+ sessionTurnBoundaryGenerationById.delete(session.id);
+ markSessionTurnEnded(session.id);
+ }
}
}));
@@ -7315,6 +7412,188 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
});
+ /**
+ * Reconcile the in-memory turn boundary after a vendor abort/close when the
+ * normal terminal event was lost. The vendor Session is authoritative for
+ * whether work is still running; the desktop tracker is only an event-driven
+ * view and can remain stale across owner-boundary teardown.
+ */
+ const getStableSessionForTurnBoundary = (sessionId: string): WiredSession | null => {
+ const wired = wiredSessionsById.get(sessionId)?.session;
+ if (wired) return wired;
+ try {
+ return maker.getSession(sessionId) ?? null;
+ } catch (err) {
+ // Dynamic Maker intentionally fails closed while an account owner is
+ // being replaced. A missing stable wiring snapshot means we cannot
+ // authoritatively reconcile this session yet; callers must retain their
+ // boundary and wait for the normal close/settle path.
+ log.warn('session lookup unavailable during turn-boundary reconciliation', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ };
+
+ const reconcileSessionTurnIdle = (sessionId: string, source: string): boolean => {
+ const sess = getStableSessionForTurnBoundary(sessionId);
+ if (!sess) return false;
+ let liveSessionIdle = false;
+ try {
+ liveSessionIdle = !sess.isTurnRunning();
+ } catch (err) {
+ log.warn('live session turn-state lookup failed during reconciliation', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return false;
+ }
+ if (!liveSessionIdle) return false;
+ const trackerStale = sessionTurnActivityTracker.isSessionInTurn(sessionId) ||
+ sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);
+ const hadZombieInteraction = hasPendingAgentInteractionForSession(sessionId);
+ if (trackerStale || hadZombieInteraction) {
+ log.warn('reconciling stale session turn boundary', {
+ sessionId,
+ source,
+ trackerStale,
+ hadZombieInteraction,
+ liveSessionIdle,
+ });
+ } else {
+ // The owner-boundary wiring guard can drop the isRunning=true event
+ // entirely. In that case the live Session being idle is still the
+ // authoritative proof that this abort boundary can be released.
+ log.info('confirmed live session idle during turn-boundary reconciliation', {
+ sessionId,
+ source,
+ });
+ }
+ sessionTurnActivityTracker.setSessionInTurn(sessionId, false);
+ try {
+ // The marker write is best-effort and ordered behind pending message
+ // persistence. It may retry/settle after an owner boundary is available.
+ markTurnEndedAfterPersistDrain(sessionId);
+ noteClaudeSessionTurnState(sessionId, false);
+ settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);
+ deferredCodexRestartHolder?.onSessionSettled();
+ agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);
+ } catch (err) {
+ log.warn('stale session turn side-effect cleanup failed', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ if (hadZombieInteraction) {
+ try {
+ cleanupPendingAgentInteractionsForSession(sessionId, 'turn_idle_reconcile');
+ } catch (err) {
+ log.warn('stale session interaction cleanup failed', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ return true;
+ };
+
+ const readDirectAbortTurnId = (session: WiredSession, sessionId: string): string | null => {
+ try {
+ return session.getCurrentTurnId?.() ?? null;
+ } catch (err) {
+ log.warn('direct abort turn-id lookup failed', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ };
+
+ const isDirectAbortBoundaryCurrent = (
+ sessionId: string,
+ boundary: DirectAbortReconcileBoundary,
+ ): boolean => {
+ if (directAbortReconcileBoundaries.get(sessionId) !== boundary) return false;
+ if (wiredSessionsById.get(sessionId)?.session !== boundary.session) return false;
+ if (currentSessionTurnBoundaryGeneration(sessionId) !== boundary.generation) return false;
+
+ // Codex exposes a provider turn id. Compare only when both sides have an
+ // id: after an abort the old id legitimately becomes null, while a new
+ // turn with a different non-null id must invalidate this retry chain.
+ const currentTurnId = readDirectAbortTurnId(boundary.session, sessionId);
+ return boundary.turnId === null || currentTurnId === null || boundary.turnId === currentTurnId;
+ };
+
+ const scheduleDirectAbortReconciliation = (
+ sessionId: string,
+ boundary: DirectAbortReconcileBoundary,
+ ): void => {
+ if (boundary.retryTimer) return;
+ boundary.retryTimer = setTimeout(() => {
+ boundary.retryTimer = null;
+ if (!isDirectAbortBoundaryCurrent(sessionId, boundary)) {
+ cancelDirectAbortReconciliation(sessionId, boundary);
+ return;
+ }
+ reconcileDirectAbortBoundary(sessionId, boundary, 'direct-abort-retry');
+ }, DIRECT_ABORT_RECONCILE_RETRY_DELAY_MS);
+ };
+
+ const reconcileDirectAbortBoundary = (
+ sessionId: string,
+ boundary: DirectAbortReconcileBoundary,
+ source: string,
+ ): void => {
+ if (!isDirectAbortBoundaryCurrent(sessionId, boundary)) {
+ cancelDirectAbortReconciliation(sessionId, boundary);
+ return;
+ }
+
+ let reconciledIdle = false;
+ try {
+ reconciledIdle = reconcileSessionTurnIdle(sessionId, source);
+ } catch (err) {
+ log.warn('direct abort idle reconciliation failed', {
+ sessionId,
+ source,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ if (reconciledIdle) {
+ cancelDirectAbortReconciliation(sessionId, boundary);
+ return;
+ }
+
+ // Keep the boundary fail-closed until the same Session instance and turn
+ // generation prove idle. Owner replacement, a new turn, or close cancels
+ // this chain through the identity/generation guards above.
+ if (isDirectAbortBoundaryCurrent(sessionId, boundary)) {
+ scheduleDirectAbortReconciliation(sessionId, boundary);
+ } else {
+ cancelDirectAbortReconciliation(sessionId, boundary);
+ }
+ };
+
+ const beginDirectAbortReconciliation = (
+ sessionId: string,
+ session: WiredSession,
+ ): DirectAbortReconcileBoundary => {
+ cancelDirectAbortReconciliation(sessionId);
+ const boundary: DirectAbortReconcileBoundary = {
+ session,
+ generation: currentSessionTurnBoundaryGeneration(sessionId),
+ turnId: readDirectAbortTurnId(session, sessionId),
+ retryTimer: null,
+ };
+ directAbortReconcileBoundaries.set(sessionId, boundary);
+ return boundary;
+ };
+
const inputCoordinator: AgentInputCoordinator = new AgentInputCoordinator({
sendToAgent: async (sessionId, message, createOpts, sendOpts) => {
try {
@@ -7419,42 +7698,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
steerToAgentAccepted(sessionId, message, sendOpts),
abortSession: async (sessionId) => {
markWorkerManualInterruptIfKnown(sessionId, 'input_stop');
- const sess = maker.getSession(sessionId);
+ const sess = getStableSessionForTurnBoundary(sessionId);
if (!sess) return;
handleAgentIslandSessionStopped(sess);
- await sess.abort();
- cleanupPendingInteractionsForSession(sessionId, 'session_aborted');
+ try {
+ await sess.abort();
+ } finally {
+ // The coordinator owns idle reconciliation after this promise settles,
+ // so its boolean result is not consumed twice. Interaction waiters are
+ // still always released even when the vendor abort rejects.
+ cleanupPendingInteractionsForSession(sessionId, 'session_aborted');
+ }
},
isTurnRunning: (sessionId) => {
- const sess = maker.getSession(sessionId);
+ const sess = getStableSessionForTurnBoundary(sessionId);
return isSessionTurnDispatchBoundaryBusy(sessionTurnActivityTracker, sessionId, sess);
},
reconcileTurnIdle: (sessionId) => {
- // steer 拿到 maker-core 权威 NO_ACTIVE_TURN 后校准本地 busy 视图。
- // tracker 只靠事件流维护, turn 异常死亡 (没发 done / terminal error) 时会
- // stale 为 in-turn, 让 coordinator 的 fallback drain 永久卡死 —— 插话点击
- // 表现为"毫无反应"。复核 live session 真没在跑后, 清 tracker + 清僵尸
- // interaction (两者都是 getDrainableHead 的 busy 门)。
- const sess = maker.getSession(sessionId);
- if (sess?.isTurnRunning()) return;
- const trackerStale = sessionTurnActivityTracker.isSessionInTurn(sessionId) ||
- sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);
- const hadZombieInteraction = hasPendingAgentInteractionForSession(sessionId);
- if (!trackerStale && !hadZombieInteraction) return;
- log.warn('reconcileTurnIdle: clearing stale busy state after authoritative NO_ACTIVE_TURN', {
- sessionId,
- trackerStale,
- hadZombieInteraction,
- });
- sessionTurnActivityTracker.setSessionInTurn(sessionId, false);
- markSessionTurnEnded(sessionId);
- noteClaudeSessionTurnState(sessionId, false);
- if (hadZombieInteraction) {
- cleanupPendingAgentInteractionsForSession(sessionId, 'turn_idle_reconcile');
- }
+ // steer 拿到 maker-core 权威 NO_ACTIVE_TURN、或 abort 已让 vendor 停止
+ // 但终态事件丢失时,都走同一条收口路径。
+ return reconcileSessionTurnIdle(sessionId, 'authoritative-idle');
},
hasPendingInteraction: hasPendingAgentInteractionForSession,
- getAgentKind: (sessionId) => maker.getSession(sessionId)?.agentKind ?? null,
+ getAgentKind: (sessionId) => getStableSessionForTurnBoundary(sessionId)?.agentKind ?? null,
getSdkSessionId: async (sessionId) => {
const meta = await maker.getSessionMeta(sessionId).catch(() => null);
return meta?.sdkSessionId;
@@ -8228,15 +8494,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
silentStopAutoResumeGuard.noteSessionReset(sessionId);
interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);
autoResumeBookkeeping.teardown(sessionId);
- const sess = maker.getSession(sessionId);
+ const sess = getStableSessionForTurnBoundary(sessionId);
if (!sess) return;
handleAgentIslandSessionStopped(sess);
// 用户 Stop 当前 turn → 若该会话有 active goal,先暂停目标(置 paused + 停续跑 + detach
// 监听),**再** abort。这样 abort 产生的终止事件到来时目标已暂停、监听已摘,不会被误判成
// 续跑(原本依赖 error 文案正则判 paused/blocked,不可靠)。null-safe;无 active goal 时 no-op。
await goalStopObserver?.(sessionId);
- await sess.abort();
- cleanupPendingInteractionsForSession(sessionId, 'session_aborted');
+ const directAbortBoundary = beginDirectAbortReconciliation(sessionId, sess);
+ try {
+ await sess.abort();
+ } finally {
+ // The stable lookup may still be inside an owner-boundary transition;
+ // reconciliation owns its own safe live-state lookup and must run even
+ // when the abort promise rejects or the Session reports a late idle.
+ try {
+ reconcileDirectAbortBoundary(sessionId, directAbortBoundary, 'direct-abort');
+ } finally {
+ cleanupPendingInteractionsForSession(sessionId, 'session_aborted');
+ }
+ }
});
ipcMain.handle(MAKER_INVOKE.CLOSE_SESSION, async (_e, sessionId: unknown, opts?: unknown) => {
@@ -9201,7 +9478,17 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {
function broadcastToAllWindows(channel: string, payload: unknown): void {
// device-link 被控端旁路:命中转发白名单且存在控制链路时,把事件转发给控制端
// (无 link 时 O(1) no-op,不进 maker-core 热路径成本)
- tapWindowBroadcast(channel, payload);
+ // 旁路永远不能反向阻断本机生命周期。owner boundary 切换期间远端链路
+ // 可能暂不可用;如果异常冒泡,Session 的 status/terminal listener 会在
+ // 清理前中止,最终留下 tracker busy + 死进程,所有后续消息永久排队。
+ try {
+ tapWindowBroadcast(channel, payload);
+ } catch (err) {
+ log.warn('device-link broadcast tap failed; keeping local broadcast alive', {
+ channel,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
try {