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(codex): 图片历史保底恢复后自动继续任务 (#4170)

Dashb3a957b98dd0
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index be3914f631..49d47c4ff1 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -541,15 +541,18 @@ describe('session runtime control wiring', () => {
it('projects rebuilt zero usage and the verified window after the runtime is closed', () => {
const commitRebuild = handlerBody(
registerSource,
- 'commitRebuild: async (sessionId, handoff, meta) => {',
+ 'commitRebuild: async (sessionId, handoff, meta, signal) => {',
'setPendingHandoff: (sessionId, handoff, expectedGeneration)',
);
const query = commitRebuild.indexOf('contextWindow: sessions.contextWindow,');
const commit = commitRebuild.indexOf('commitContextRebuild(sessionId, handoff, meta)');
+ const cancellation = commitRebuild.indexOf('signal?.throwIfAborted();');
const broadcast = commitRebuild.indexOf('broadcastSessionPatched(\n sessionId,');
expect(query).toBeGreaterThan(-1);
expect(commit).toBeGreaterThan(query);
+ expect(cancellation).toBeGreaterThan(query);
+ expect(commit).toBeGreaterThan(cancellation);
expect(broadcast).toBeGreaterThan(commit);
expect(commitRebuild).toContain('contextTokens: 0,');
expect(commitRebuild).toContain('{ contextWindow: projectionContextWindow }');
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 be217cb319..6cd6fa8764 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
@@ -3005,6 +3005,25 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.sendToAgent).toHaveBeenCalledTimes(1);
});
+ it('lets already queued input take over when oversized recovery clears the old error', async () => {
+ const h = createHarness();
+ const sid = 'oversized-recovery-queued-takeover';
+ h.coordinator.enqueue(sid, makeItem('q-old', 'old task'));
+ await flush();
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, makeItem('q-new', 'do not deploy; inspect only'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', 'oversized history', { reason: 'codex_history_oversized' });
+ expect(h.coordinator.hasPendingQueuedWork(sid)).toBe(true);
+ h.coordinator.clearError(sid);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'do not deploy; inspect only' });
+ expect(latestProjection(h.projections).recovery).toBeNull();
+ });
+
it('active-turn retry falls back to resending the original text when the turn produced nothing', async () => {
const h = createHarness();
const sid = 'retry-continue-no-progress';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
index d35639b501..f5c5ae5288 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ CODEX_HISTORY_CONTINUE_MESSAGE,
createContextOverflowRollover,
effectiveContextWindow,
effectivePiContextWindow,
@@ -284,6 +285,7 @@ describe('createContextOverflowRollover', () => {
getSessionRow: vi.fn(
async (): Promise<{
status: string;
+ source?: string;
agentKind: string;
remoteHostId: string | null;
clearedAt: number | null;
@@ -295,6 +297,7 @@ describe('createContextOverflowRollover', () => {
workingDir?: string | null;
}> => ({
status: 'active',
+ source: 'desktop',
agentKind: 'pi',
remoteHostId: null,
clearedAt: null,
@@ -822,6 +825,7 @@ describe('createContextOverflowRollover', () => {
]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -846,8 +850,9 @@ describe('createContextOverflowRollover', () => {
sourceUserClientId: 'u2',
sourceAgentKind: 'codex',
}),
+ expect.any(AbortSignal),
);
- expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', '再做 B');
+ expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', '再做 B', undefined, { signal: expect.any(AbortSignal) });
});
it('rebuilds once, injects handoff, and wire-replays the same user content', async () => {
@@ -874,11 +879,12 @@ describe('createContextOverflowRollover', () => {
sourceProviderId: 'xai',
expectedClearedAt: null,
}),
+ expect.any(AbortSignal),
);
expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', expect.any(String), 3);
expect(deps.setPendingHandoff.mock.calls[0]?.[1]).toContain('先做 A');
expect(deps.setPendingHandoff.mock.calls[0]?.[1]).not.toContain('再做 B');
- expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', '再做 B');
+ expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', '再做 B', undefined, { signal: expect.any(AbortSignal) });
expect(deps.onRebuilt).toHaveBeenCalledWith('s1');
expect(deps.replayUserMessage.mock.invocationCallOrder[0]).toBeLessThan(
deps.onRebuilt.mock.invocationCallOrder[0],
@@ -946,7 +952,7 @@ describe('createContextOverflowRollover', () => {
agentMeta: { origin: { kind: 'orca', senderLabel: 'Lead', displayText: '派给 worker' } },
},
]);
- const rollover = createContextOverflowRollover(deps);
+ const rollover = createContextOverflowRollover({ ...deps, hasExternalRecoveryOwner: () => true });
rollover.claim('s1');
await expect(
rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),
@@ -976,6 +982,7 @@ describe('createContextOverflowRollover', () => {
const deps = makeDeps([msg('user', '继续', 'u1'), msg('error', compactError, 'e1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1103,6 +1110,7 @@ describe('createContextOverflowRollover', () => {
const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1303,6 +1311,7 @@ describe('createContextOverflowRollover', () => {
const deps = makeDeps([msg('user', '继续', 'u1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1324,6 +1333,7 @@ describe('createContextOverflowRollover', () => {
const deps = makeDeps([msg('user', '继续', 'u1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: 'remote-1',
clearedAt: null,
@@ -1346,11 +1356,18 @@ describe('createContextOverflowRollover', () => {
it('strips oversized Codex history in place instead of forking a Cindy session', async () => {
const deps = makeDeps([
- msg('user', '继续', 'u1'),
+ { ...msg('user', '继续', 'u1'), agentMeta: { agentFacingWireContent: {
+ type: 'user', content: [
+ { type: 'text', text: 'Use $image-plugin to finish this image' },
+ { type: 'image', path: '/retained/image.png' },
+ ],
+ } } },
+ msg('assistant', 'Already changed files; still checking the result', 'a1'),
msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1380,12 +1397,145 @@ describe('createContextOverflowRollover', () => {
});
expect(deps.commitRebuild).not.toHaveBeenCalled();
expect(deps.onRebuilt).toHaveBeenCalledWith('s1');
+ expect(deps.replayUserMessage).toHaveBeenCalledWith(
+ 's1', CODEX_HISTORY_CONTINUE_MESSAGE, undefined,
+ { signal: expect.any(AbortSignal), resumeRetainedHistory: true, sourceUserContent: '继续', sourceUserClientId: 'u1',
+ sourceCapabilitySelectionText: 'Use $image-plugin to finish this image' },
+ );
+ rollover.claim('s1');
+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(false);
+ expect(deps.replayUserMessage).toHaveBeenCalledTimes(1);
});
+ it.each(['cancelled', 'dispatch-cancelled', 'rejected', 'external', 'before-send'] as const)(
+ 'does not claim automatic continuation succeeded when %s', async (scenario) => {
+ const user = msg('user', 'finish editing', 'u1');
+ if (scenario === 'external') user.agentMeta = { origin: { kind: 'scheduler' } };
+ const deps = makeDeps([user, msg('error', { reason: 'codex_history_oversized' }, 'e1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()), agentKind: 'codex', sdkSessionId: 'fat-thread',
+ });
+ const cancellation = new AbortController();
+ deps.replayUserMessage.mockResolvedValue({ accepted: false });
+ if (scenario === 'dispatch-cancelled') {
+ deps.replayUserMessage.mockImplementation(async () => {
+ cancellation.abort();
+ throw new Error('cancelled during admission');
+ });
+ }
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ getRecoveryAbortSignal: () => cancellation.signal,
+ tryStripOversizedCodexHistory: async () => {
+ if (scenario === 'cancelled') cancellation.abort();
+ return 'recovered';
+ },
+ });
+ if (scenario === 'before-send') {
+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);
+ } else {
+ rollover.claim('s1');
+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' }))
+ .resolves.toBe(scenario === 'cancelled' || scenario === 'dispatch-cancelled');
+ expect(deps.onRebuilt).not.toHaveBeenCalled();
+ }
+ expect(deps.replayUserMessage).toHaveBeenCalledTimes(
+ scenario === 'rejected' || scenario === 'dispatch-cancelled' ? 1 : 0,
+ );
+ },
+ );
+
+ it.each(['claimed', 'strip', 'dispatch'] as const)('new input cancels recovery during %s', async (phase) => {
+ const deps = makeDeps([msg('user', 'old task', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()), agentKind: 'codex', sdkSessionId: 'fat-thread',
+ });
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: async () => {
+ if (phase === 'strip') rollover.cancelRecovery('s1');
+ return 'recovered';
+ },
+ replayUserMessage: async (...args) => {
+ deps.replayUserMessage();
+ rollover.cancelRecovery('s1');
+ expect(args[3]?.signal?.aborted).toBe(true);
+ return { accepted: false };
+ },
+ });
+ rollover.claim('s1');
+ if (phase === 'claimed') rollover.cancelRecovery('s1');
+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(true);
+ expect(deps.replayUserMessage).toHaveBeenCalledTimes(phase === 'dispatch' ? 1 : 0);
+ expect(deps.onRebuilt).not.toHaveBeenCalled();
+ expect(rollover.claim('s1')).toBe('claimed');
+ });
+
+ it.each(['strip', 'plan', 'close', 'commit', 'replay'] as const)(
+ 'cancels failed-strip fallback during %s without advancing the old request', async (phase) => {
+ const deps = makeDeps([msg('user', 'old request', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()), agentKind: 'codex', sdkSessionId: 'fat-thread',
+ });
+ const cancelAt = (point: string) => {
+ if (phase === point) rollover.cancelRecovery('s1');
+ };
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: async () => { cancelAt('strip'); return 'failed'; },
+ findLatestRebuildMeta: async () => { cancelAt('plan'); return null; },
+ closeSession: async () => { await deps.closeSession(); cancelAt('close'); },
+ commitRebuild: async (...args) => {
+ expect(args[3]?.aborted).toBe(false);
+ await deps.commitRebuild();
+ cancelAt('commit');
+ },
+ replayUserMessage: async (...args) => {
+ await deps.replayUserMessage();
+ cancelAt('replay');
+ expect(args[3]?.signal?.aborted).toBe(true);
+ return { accepted: false };
+ },
+ });
+ rollover.claim('s1');
+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(true);
+ expect(deps.closeSession).toHaveBeenCalledTimes(['strip', 'plan'].includes(phase) ? 0 : 1);
+ expect(deps.commitRebuild).toHaveBeenCalledTimes(['commit', 'replay'].includes(phase) ? 1 : 0);
+ expect(deps.replayUserMessage).toHaveBeenCalledTimes(phase === 'replay' ? 1 : 0);
+ expect(deps.onRebuilt).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['slack-hook', 'telegram', undefined, 'bound', 'detached-active'])(
+ 'leaves oversized recovery to its external owner: %s', async (origin) => {
+ // Protected IM input may not be persisted: this row can be an older desktop input.
+ const deps = makeDeps([msg('user', 'old desktop request', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()), agentKind: 'codex', sdkSessionId: 'fat-thread',
+ source: origin === 'bound' || origin === 'detached-active' ? 'desktop' : origin,
+ });
+ let externalTurnActive = origin === 'bound' || origin === 'detached-active';
+ const strip = vi.fn(async () => 'recovered' as const);
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ hasExternalRecoveryOwner: () => externalTurnActive,
+ tryStripOversizedCodexHistory: strip,
+ });
+ rollover.claim('s1');
+ const recovery = rollover.tryRecover('s1', { reason: 'codex_history_oversized' });
+ externalTurnActive = false; // IM's later terminal subscriber releases its marker.
+ await expect(recovery).resolves.toBe(false);
+ expect(strip).not.toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ },
+ );
+
it('falls back to rollover when oversized strip fails', async () => {
const deps = makeDeps([msg('user', '继续', 'u1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1415,6 +1565,7 @@ describe('createContextOverflowRollover', () => {
]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1444,6 +1595,7 @@ describe('createContextOverflowRollover', () => {
]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
@@ -1472,6 +1624,7 @@ describe('createContextOverflowRollover', () => {
]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
+ source: 'desktop',
agentKind: 'codex',
remoteHostId: null,
clearedAt: null,
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 f40d547fca..d4e359cb5a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -2,6 +2,7 @@ import {
CodexResumePreparationBlockedError,
AUTO_REVIEW_SOURCE_CONTENT,
AUTO_REVIEW_USER_INTENT,
+ INHERITED_CAPABILITY_SELECTION,
appendAutoReviewUserIntent,
MAIN_OWNED_SEND_CONTEXT,
type AgentKind,
@@ -2150,6 +2151,20 @@ describe('session-agent-switch handoff injection', () => {
expect(intent).not.toContain('assistant handoff');
});
+ it.each(['Earlier authorization; do not deploy.', ''])('preserves restored intent for wire-only recovery: %s', async (intent) => {
+ const { deps, session } = createDeps();
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'Internal continuation', undefined, {
+ [AUTO_REVIEW_SOURCE_CONTENT]: 'Continue',
+ [AUTO_REVIEW_USER_INTENT]: intent,
+ [INHERITED_CAPABILITY_SELECTION]: '$image-plugin',
+ });
+ const opts = vi.mocked(session.send).mock.calls[0]![1]!;
+ expect(opts[AUTO_REVIEW_USER_INTENT]).toBe(intent);
+ expect(opts[AUTO_REVIEW_SOURCE_CONTENT]).toBe('Continue');
+ expect(opts[INHERITED_CAPABILITY_SELECTION]).toBe('$image-plugin');
+ expect(deps.createDbMessage).not.toHaveBeenCalled();
+ });
+
it.each([false, true])('invalidates old grants for oversized stamped input (deviceLink=%s)', async (deviceLink) => {
const raw = 'x'.repeat(1000) + 'DO NOT SEND' + 'x'.repeat(1000);
const queued = stampTrustedDesktopQueuedOrigin({ clientId: 'long', text: raw,
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 3f7d5dffc8..abaf390006 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -26,6 +26,10 @@ import { buildHandoffText, extractPlainText, type HandoffSourceMessage } from '.
const SYNTHETIC_TRIGGER_PREFIX = '[UI_ACTION_TRIGGER]';
+export const CODEX_HISTORY_CONTINUE_MESSAGE =
+ 'Continue the unfinished task from the retained history. Do not repeat completed actions. ' +
+ 'Some historical tool images were omitted during recovery; inspect them again only if needed.';
+
export interface OverflowSourceMessage extends HandoffSourceMessage {
clientId: string;
agentMeta?: Record<string, unknown> | null;
@@ -307,6 +311,7 @@ export function findLatestRebuildableError(
export interface ContextOverflowRolloverDeps {
getSessionRow(sessionId: string): Promise<{
status: string;
+ source?: string | null;
agentKind: string;
remoteHostId: string | null;
clearedAt: number | null;
@@ -359,6 +364,7 @@ export interface ContextOverflowRolloverDeps {
expectedClearedAt?: number | null;
replacementRoute?: NativeSessionRecoveryTarget & { expectedSdkSessionId: string };
},
+ signal?: AbortSignal,
): Promise<void>;
setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;
readPendingHandoffGeneration?(sessionId: string): number;
@@ -366,7 +372,17 @@ export interface ContextOverflowRolloverDeps {
sessionId: string,
content: unknown,
agentFacingWireContent?: unknown,
+ recovery?: { signal?: AbortSignal; resumeRetainedHistory?: false } | {
+ signal?: AbortSignal;
+ resumeRetainedHistory: true;
+ sourceUserContent: unknown;
+ sourceUserClientId: string;
+ sourceCapabilitySelectionText: string;
+ },
): Promise<{ accepted: boolean }>;
+ getRecoveryAbortSignal?(sessionId: string): AbortSignal;
+ /** Synchronous: external dispatch may release its turn marker on this same terminal event. */
+ hasExternalRecoveryOwner?(sessionId: string): boolean;
onRebuilt?(sessionId: string): void;
withSessionLock?<T>(sessionId: string, fn: () => Promise<T>): Promise<T>;
withCloseSuppressed<T>(sessionId: string, fn: () => Promise<T>): Promise<T>;
@@ -419,6 +435,7 @@ export function shouldRebuildForModelWindowSwitch(input: {
export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps): {
claim(sessionId: string): OverflowClaimResult;
+ cancelRecovery(sessionId: string): void;
tryRecover(sessionId: string, errorData: unknown): Promise<boolean>;
prepareUnhealthySession(sessionId: string): Promise<boolean>;
prepareNativeSessionRecovery(
@@ -438,7 +455,9 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
},
): Promise<ModelWindowSwitchPreparationResult>;
} {
- const inFlight = new Set<string>();
+ const inFlight = new Map<string, AbortController | undefined>();
+ // One automatic continuation per source input, not one per replacement thread.
+ const continuedInputs = new Map<string, string>();
const runStripRelink = async (
sessionId: string,
@@ -466,14 +485,21 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
});
};
- const runRecover = async (sessionId: string, errorData: unknown): Promise<boolean> => {
+ const runRecover = async (
+ sessionId: string,
+ errorData: unknown,
+ signal?: AbortSignal,
+ ): Promise<boolean> => {
+ if (signal?.aborted) return true;
const oversized = isOversizedHistoryErrorData(errorData);
if (!isContextOverflowErrorData(errorData) && !oversized) return false;
await deps.drainPersistQueue();
const sessionRow = await deps.getSessionRow(sessionId);
+ signal?.throwIfAborted();
if (!sessionRow || sessionRow.status === 'deleted') return false;
// SSH only. device-link 会话落在被控桌面本地库,没有 remoteHostId,必须继续换窗。
if (sessionRow.remoteHostId) return false;
+ if (oversized && sessionRow.source !== 'desktop') return false;
return deps.withCloseSuppressed(sessionId, async () => {
const live = deps.getLiveSession(sessionId);
@@ -490,16 +516,47 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
tokens,
});
if (action === 'strip') {
+ const source = await deps.listMessages(sessionId);
+ const sourceUser =
+ [...source].reverse().find((message) => message.role === 'user' && !isSyntheticUser(message)) ??
+ (await deps.findLatestUser?.(sessionId));
+ if (signal?.aborted) return true;
+ if (deps.hasExternalRecoveryOwner?.(sessionId)) return false;
+ if (sourceUser && continuedInputs.get(sessionId) === sourceUser.clientId) return false;
const strip = await runStripRelink(sessionId, sessionRow);
+ signal?.throwIfAborted();
const next = afterStripAttempt(strip, { local: true, tokens });
- if (next === 'done') {
+ if (next === 'done' || (strip === 'not-needed' && next === 'none')) {
+ // A repaired thread still needs a turn. Continue from retained history,
+ // never replay the original input after tools may already have run.
+ if (!sourceUser || isExternalDispatchOwner(sourceUser.agentMeta) ||
+ deps.hasExternalRecoveryOwner?.(sessionId)) return false;
+ const sourceWire = persistedUserContentToWireMessage(
+ sourceUser.agentMeta?.agentFacingWireContent ?? sourceUser.content,
+ );
+ const sourceText = typeof sourceWire === 'string' ? sourceWire : sourceWire.content;
+ continuedInputs.set(sessionId, sourceUser.clientId);
+ const continuation = await deps.replayUserMessage(
+ sessionId,
+ CODEX_HISTORY_CONTINUE_MESSAGE,
+ undefined,
+ {
+ signal,
+ resumeRetainedHistory: true,
+ sourceUserContent: sourceUser.content,
+ sourceUserClientId: sourceUser.clientId,
+ sourceCapabilitySelectionText: typeof sourceText === 'string'
+ ? sourceText : extractPlainText(sourceText),
+ },
+ );
+ if (signal?.aborted) return true;
+ if (!continuation.accepted) return false;
deps.onRebuilt?.(sessionId);
deps.log.info('codex oversized history strip settled', { sessionId, strip, next });
return true;
}
if (next === 'none') {
- if (strip === 'not-needed') deps.onRebuilt?.(sessionId);
- return strip === 'not-needed';
+ return false;
}
action = next;
deps.log.warn('codex oversized strip did not finish; rebuilding', { sessionId, strip });
@@ -510,6 +567,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
deps.listMessages(sessionId),
deps.findLatestRebuildMeta(sessionId),
]);
+ signal?.throwIfAborted();
const alreadyRolled =
rebuildMeta?.reason === 'context-overflow' ? rebuildMeta.sourceUserClientId : null;
const plan = planContextOverflowRollover(source, alreadyRolled);
@@ -522,6 +580,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
}
if (live) await deps.closeSession(sessionId);
+ signal?.throwIfAborted();
const label = engineLabelForOverflow(sessionRow.agentKind);
const handoff = buildHandoffText(plan.handoffMessages, {
fromLabel: label,
@@ -536,7 +595,8 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
sourceModel: sessionRow.model ?? null,
sourceProviderId: sessionRow.providerId ?? null,
expectedClearedAt: sessionRow.clearedAt,
- });
+ }, signal);
+ signal?.throwIfAborted();
deps.setPendingHandoff(sessionId, handoff, handoffGeneration);
if (plan.skipGenericReplay) {
deps.log.info('overflow rebuilt; external owner must retry send', {
@@ -545,14 +605,13 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
});
return true;
}
- const replay =
- plan.sourceUserAgentFacingWireContent !== undefined
- ? await deps.replayUserMessage(
- sessionId,
- plan.sourceUserContent,
- plan.sourceUserAgentFacingWireContent,
- )
- : await deps.replayUserMessage(sessionId, plan.sourceUserContent);
+ const replay = await deps.replayUserMessage(
+ sessionId,
+ plan.sourceUserContent,
+ plan.sourceUserAgentFacingWireContent,
+ { signal },
+ );
+ signal?.throwIfAborted();
if (!replay.accepted) {
deps.log.warn('context overflow rollover replay was not accepted', {
sessionId,
@@ -851,7 +910,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
return {
async prepareNativeSessionRecovery(sessionId, target, assertCanCommit) {
if (inFlight.has(sessionId)) throw new Error('Native session recovery is already in progress');
- inFlight.add(sessionId);
+ inFlight.set(sessionId, undefined);
try {
await deps.withCloseSuppressed(sessionId, async () => {
await deps.drainPersistQueue();
@@ -896,17 +955,32 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
claim(sessionId: string): OverflowClaimResult {
if (inFlight.has(sessionId)) return 'in-flight';
- inFlight.add(sessionId);
+ inFlight.set(sessionId, new AbortController());
return 'claimed';
},
+ cancelRecovery(sessionId: string): void {
+ // Keep the claim until its async work unwinds; only the hidden send is
+ // cancelled, never the newer input or the session's normal generation.
+ inFlight.get(sessionId)?.abort();
+ },
+
async tryRecover(sessionId: string, errorData: unknown): Promise<boolean> {
+ let signal: AbortSignal | undefined;
try {
+ // IM may not persist this input (protected content), and an attached IM
+ // turn can outlive its binding. Check live ownership before any await.
+ if (isOversizedHistoryErrorData(errorData) && deps.hasExternalRecoveryOwner?.(sessionId)) return false;
+ const claim = inFlight.get(sessionId) ?? new AbortController();
+ inFlight.set(sessionId, claim);
+ const inputSignal = deps.getRecoveryAbortSignal?.(sessionId);
+ signal = inputSignal ? AbortSignal.any([claim.signal, inputSignal]) : claim.signal;
if (deps.withSessionLock) {
- return await deps.withSessionLock(sessionId, () => runRecover(sessionId, errorData));
+ return await deps.withSessionLock(sessionId, () => runRecover(sessionId, errorData, signal));
}
- return await runRecover(sessionId, errorData);
+ return await runRecover(sessionId, errorData, signal);
} catch (error) {
+ if (signal?.aborted) return true;
deps.log.warn('context overflow rollover failed', {
sessionId,
error: error instanceof Error ? error.message : String(error),
@@ -919,7 +993,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
async prepareUnhealthySession(sessionId: string): Promise<boolean> {
if (inFlight.has(sessionId)) return false;
- inFlight.add(sessionId);
+ inFlight.set(sessionId, undefined);
try {
return await deps.withCloseSuppressed(sessionId, () => runPrepare(sessionId));
} catch (error) {
@@ -937,7 +1011,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
async prepareModelWindowSwitch(sessionId, target) {
if (inFlight.has(sessionId)) return 'in-flight';
- inFlight.add(sessionId);
+ inFlight.set(sessionId, undefined);
try {
return await deps.withCloseSuppressed(sessionId, () =>
runPrepareModelWindowSwitch(sessionId, target),
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 677c054f64..31a2786be4 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -2,6 +2,7 @@ import {
CodexResumePreparationBlockedError,
AUTO_REVIEW_SOURCE_CONTENT,
AUTO_REVIEW_USER_INTENT,
+ INHERITED_CAPABILITY_SELECTION,
MAIN_OWNED_SEND_CONTEXT,
type AgentKind,
type MainOwnedSendContext,
@@ -210,6 +211,9 @@ export function revokeTrustedDesktopQueuedOrigin(item: AgentInputQueuedMessage):
type MakerSendOptions = {
readonly [AUTO_REVIEW_SOURCE_CONTENT]?: UserMessage['content'];
+ /** Main-only continuation: a restored intent is not an authored user turn. */
+ readonly [AUTO_REVIEW_USER_INTENT]?: string;
+ readonly [INHERITED_CAPABILITY_SELECTION]?: string;
readonly [MAIN_OWNED_SEND_CONTEXT]?: MainOwnedSendContext;
messageUuid?: string;
userName?: string;
@@ -1186,8 +1190,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
: mainOwnedSendContext?.origin.kind === 'desktop' ? mainOwnedSendContext.rawChannelText : undefined;
const autoReviewSourceContent = so[AUTO_REVIEW_SOURCE_CONTENT]
?? (typeof normalized === 'string' ? normalized : normalized.content) as UserMessage['content'];
- let restoredAutoReviewIntent: string | undefined;
- if (isOrdinaryUserTurn && trustedUserText !== undefined
+ let restoredAutoReviewIntent = so[AUTO_REVIEW_USER_INTENT];
+ if (restoredAutoReviewIntent === undefined && isOrdinaryUserTurn && trustedUserText !== undefined
&& (!mainOwnedSendContext || mainOwnedSendContext.origin.kind === 'desktop')) {
let history: AutoReviewHistoryMessage[] = [];
try {
@@ -1294,6 +1298,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
: null;
const sendResult = await sess.send(outgoing as never, {
[AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent,
+ ...(so[INHERITED_CAPABILITY_SELECTION] !== undefined
+ ? { [INHERITED_CAPABILITY_SELECTION]: so[INHERITED_CAPABILITY_SELECTION] }
+ : {}),
...(restoredAutoReviewIntent !== undefined
? { [AUTO_REVIEW_USER_INTENT]: restoredAutoReviewIntent }
: {}),
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index fba39b283a..5bc906a9c9 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -33,8 +33,8 @@ import {
listPiSubagentRuns,
piSubagentRunRoot,
} from '@cindy/maker-core/pi-subagent-runs';
-import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';
-import { restoreAutoReviewSteerIntent } from './autoReviewUserIntent.js';
+import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, INHERITED_CAPABILITY_SELECTION, MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';
+import { readAutoReviewUserText, restoreAutoReviewSteerIntent, restoreAutoReviewUserIntent } from './autoReviewUserIntent.js';
import type {
AgentEvent,
AgentKind,
@@ -111,6 +111,8 @@ import {
type GhostGrantConfirmInteractionSnapshot,
} from '../cindy-brain/ghostGrantConfirmBridge.js';
import { createFeishuDesktopConfirmNotifier } from '../im/desktopConfirmNoticeWiring.js';
+import { bindingStore } from '../im/binding.js';
+import { isHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInteractionSurface.js';
import {
initGhostSetupInteractionBridge,
parseGhostSetupInteractionCommand,
@@ -11848,10 +11850,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
};
contextOverflowRolloverHolder = createContextOverflowRollover({
+ hasExternalRecoveryOwner: (sessionId) =>
+ isHeadlessGhostSetupTurn(sessionId) || !!bindingStore.findByTarget(sessionId),
getSessionRow: async (sessionId) => {
const [row] = await getDbClient()
.drizzle.select({
status: sessions.status,
+ source: sessions.source,
agentKind: sessions.agentKind,
remoteHostId: sessions.remoteHostId,
clearedAt: sessions.clearedAt,
@@ -11986,7 +11991,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
rehydrateColdPiRuntimeForWindowVerification,
closeSession: (sessionId) => maker.closeSession(sessionId),
drainPersistQueue,
- commitRebuild: async (sessionId, handoff, meta) => {
+ commitRebuild: async (sessionId, handoff, meta, signal) => {
// Read projection metadata before the transaction: after a successful
// context.rebuild there must be no fallible step before the zero-usage push.
const ownerScope = captureDataOwnerBroadcastScope();
@@ -12006,6 +12011,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
throw new Error('context rebuild owner changed before commit');
}
+ signal?.throwIfAborted();
const { updatedAt } = await commitContextRebuild(sessionId, handoff, meta);
if (
!isDataOwnerBroadcastScopeCurrent(ownerScope) ||
@@ -12079,13 +12085,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// recovery 和错误横幅。重放绕开 coordinator,随后的 done 会被 recovery 吃掉。
agentInputCoordinatorHolder?.clearError(sessionId);
},
- replayUserMessage: async (sessionId, content, agentFacingWireContent) => {
+ getRecoveryAbortSignal: (sessionId) => {
+ const coordinator = agentInputCoordinatorHolder!;
+ if (coordinator.hasPendingQueuedWork(sessionId)) {
+ // The terminal error may have installed recovery after this input was
+ // queued. Release that old error so the queued input can actually drain.
+ coordinator.clearError(sessionId);
+ return AbortSignal.abort();
+ }
+ return coordinator.getInputAbortSignal(sessionId);
+ },
+ replayUserMessage: async (sessionId, content, agentFacingWireContent, recovery) => {
const [row] = await getDbClient()
.drizzle.select()
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
if (!row?.workingDir) return { accepted: false };
+ if (recovery?.signal?.aborted) return { accepted: false };
const createOpts = buildCreateOptsWithStderr({
id: sessionId,
agentKind: dbToMakerAgentKind(row.agentKind),
@@ -12098,6 +12115,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
planMode: !!row.planModeEnabled,
title: row.title ?? undefined,
remoteHostId: row.remoteHostId ?? undefined,
+ ...(recovery?.resumeRetainedHistory ? { resumeSessionId: row.sdkSessionId ?? undefined } : {}),
});
if (createOpts.extraDirs === undefined) {
try {
@@ -12114,10 +12132,30 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const writableDirs = await readSessionWritableDirsFromDb(sessionId).catch(() => []);
if (writableDirs.length > 0) createOpts.writableDirs = writableDirs;
}
+ const recoveryIntent = recovery?.resumeRetainedHistory
+ ? restoreAutoReviewUserIntent(await readAutoReviewHistory(sessionId), {
+ clientId: recovery.sourceUserClientId,
+ content: recovery.sourceUserContent,
+ })
+ : undefined;
+ if (recovery?.resumeRetainedHistory &&
+ (row.source !== 'desktop' || isHeadlessGhostSetupTurn(sessionId) || bindingStore.findByTarget(sessionId))) {
+ return { accepted: false };
+ }
const result = await sendToAgentAcceptedUnlocked(
sessionId,
persistedUserContentToWireMessage(agentFacingWireContent ?? content),
createOpts,
+ recovery?.resumeRetainedHistory
+ ? {
+ signal: recovery.signal,
+ [INHERITED_CAPABILITY_SELECTION]: recovery.sourceCapabilitySelectionText,
+ // The internal continuation is not fresh user authorization. Restore
+ // intent from authored history, never attachment/quote projections.
+ [AUTO_REVIEW_SOURCE_CONTENT]: readAutoReviewUserText(recovery.sourceUserContent) ?? '',
+ [AUTO_REVIEW_USER_INTENT]: recoveryIntent,
+ }
+ : { signal: recovery?.signal },
);
return { accepted: result.accepted === true };
},
@@ -13221,6 +13259,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
autoResumeBookkeeping.bindSuppressedErrorToClient(sessionId, attemptToken, clientId);
}
if (source === 'manual') {
+ contextOverflowRolloverHolder?.cancelRecovery(sessionId);
// UI continuation can dispatch before the scheduler backoff callback.
// Retire that pending waiter first so it cannot consume the manual retry.
failPendingSchedulerAutoResume(sessionId);
@@ -13235,6 +13274,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 用 enqueue 入口而不是消息文本: 零产出重试重发的是原文, 文本上无从区分,
// 而它走 unshift 不经这里, 于是不会把自己的回流作废掉。
onUserEnqueue: (sessionId) => {
+ contextOverflowRolloverHolder?.cancelRecovery(sessionId);
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
@@ -13250,6 +13290,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
},
onAutomaticEnqueue: (sessionId) => {
+ contextOverflowRolloverHolder?.cancelRecovery(sessionId);
// Orca 等自动输入会推进同一会话,必须撤销旧 retry owner,避免它消费这轮事件;
// 但预算充值仍只发生在真人消息的持久化路径,自动输入不会重置 episode。
autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(sessionId);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7482e31f93..0a9441ade4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8768,7 +8768,7 @@
"contextRebuild": {
"labelOverflow": "Context reorganized, continuing",
"labelTimeout": "Last turn didn't respond; context reorganized to continue",
- "labelStrip": "Oversized images removed, continuing",
+ "labelStrip": "Historical images reorganized",
"toggleHint": "View handoff context",
"handoffTitle": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)",
"handoffTitleEnglishSource": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)"
@@ -11410,7 +11410,7 @@
"codexAutoReviewUnavailable": "Auto-review is temporarily unavailable. The current action was blocked and permissions switched to Default. Retry the request; Cindy will ask when needed.",
"hostShellCommandBlocked": "Cindy blocked a shell command that would bypass the embedded iOS Simulator. Use the iOS Simulator tool for device control, app launches, interaction, screenshots, and diagnostics.",
"upstreamResponseIdleTimeout": "The model stopped responding for a long time, so this turn was interrupted to avoid hanging forever. Completed tool calls are preserved — send the next message to continue.",
- "codexHistoryOversized": "This task’s history includes oversized images, so remote compaction cannot finish. Cindy will omit those images and continue in this task.",
+ "codexHistoryOversized": "Automatic image history recovery and continuation could not finish. Send “Continue” to resume this task.",
"codexHistoryOversizedRemote": "This task’s history includes oversized images, so remote compaction cannot finish. Open the task on the machine running Codex and send again; Cindy will omit those images there.",
"codexCompactionNotConverging": "Codex kept compacting the context without making progress, so this turn was interrupted to stop the loop. What's taking up the space usually isn't the conversation — the system prompt and tool definitions can't be compacted away. Start a new task to continue.",
"codexCompactionNotConvergingModelSwitch": "Codex kept compacting the context without making progress, so this turn was interrupted to stop the loop. This task switched model midway, and Codex still evaluates the context limit against the previous model. Switch back to that model to continue, or start a new task.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0a039f4dfc..747de68c7f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8762,7 +8762,7 @@
"contextRebuild": {
"labelOverflow": "コンテキストを整理して続行しました",
"labelTimeout": "直前の応答がなかったため、整理して続行しました",
- "labelStrip": "大きな画像を除いて続行しました",
+ "labelStrip": "履歴の画像を整理しました",
"toggleHint": "引き継ぎ内容を表示",
"handoffTitle": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",
"handoffTitleEnglishSource": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)"
@@ -11394,7 +11394,7 @@
"codexAutoReviewUnavailable": "自動レビューは一時的に利用できません。現在の操作をブロックし、デフォルト権限に切り替えました。もう一度実行してください。必要な場合は確認します。",
"hostShellCommandBlocked": "Cindy は内蔵 iOS シミュレータを迂回するシェルコマンドをブロックしました。デバイスの操作、アプリの起動、画面操作、スクリーンショット、診断には iOS シミュレータツールを使用してください。",
"upstreamResponseIdleTimeout": "モデルから長時間応答がなかったため、無限待機を避けるためこのターンを自動中断しました。完了したツール呼び出しは保持されています。次のメッセージを送信して続行できます。",
- "codexHistoryOversized": "履歴に過大な画像があり、リモート圧縮を完了できません。Cindy がそれらの画像を省略し、このタスクのまま続けます。",
+ "codexHistoryOversized": "画像履歴の自動復旧と続行が完了しませんでした。「続けて」と送信して、このタスクを再開してください。",
"codexHistoryOversizedRemote": "履歴に過大な画像があり、リモート圧縮を完了できません。Codex を実行している端末でこのタスクを開いて再送信してください。Cindy が画像を省略して続けます。",
"codexCompactionNotConverging": "Codex がコンテキストの圧縮を繰り返しても効果がないため、無限ループを避けるためこのターンを自動中断しました。容量を占めているのは会話ではなく、圧縮では削れないシステムプロンプトとツール定義であることがほとんどです。新しいセッションを開始してください。",
"codexCompactionNotConvergingModelSwitch": "Codex がコンテキストの圧縮を繰り返しても効果がないため、無限ループを避けるためこのターンを自動中断しました。このセッションは途中でモデルを切り替えており、Codex は切り替え前のモデルの上限でコンテキストを判定し続けています。元のモデルに戻すか、新しいセッションを開始してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 27ae82451a..d453c968aa 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8762,7 +8762,7 @@
"contextRebuild": {
"labelOverflow": "컨텍스트를 정리하고 계속합니다",
"labelTimeout": "직전 응답이 없어 정리한 뒤 계속합니다",
- "labelStrip": "큰 이미지를 빼고 계속합니다",
+ "labelStrip": "기록의 이미지를 정리했습니다",
"toggleHint": "인계 내용 보기",
"handoffTitle": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",
"handoffTitleEnglishSource": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)"
@@ -11394,7 +11394,7 @@
"codexAutoReviewUnavailable": "자동 리뷰를 일시적으로 사용할 수 없습니다. 현재 작업을 차단하고 기본 권한으로 전환했습니다. 다시 시도하세요. 필요한 경우 확인을 요청합니다.",
"hostShellCommandBlocked": "Cindy가 내장 iOS 시뮬레이터를 우회하는 셸 명령을 차단했습니다. 기기 제어, 앱 실행, 화면 조작, 스크린샷, 진단에는 iOS 시뮬레이터 도구를 사용하세요.",
"upstreamResponseIdleTimeout": "모델이 오랫동안 응답하지 않아 무한 대기를 막기 위해 이번 턴을 자동으로 중단했습니다. 완료된 도구 호출은 유지되며, 다음 메시지를 보내 계속할 수 있습니다.",
- "codexHistoryOversized": "기록에 과대한 이미지가 있어 원격 압축을 끝낼 수 없습니다. Cindy가 해당 이미지를 생략하고 이 작업에서 계속합니다.",
+ "codexHistoryOversized": "이미지 기록의 자동 복구 및 계속 진행을 완료하지 못했습니다. ‘계속’을 보내 이 작업을 재개하세요.",
"codexHistoryOversizedRemote": "기록에 과대한 이미지가 있어 원격 압축을 끝낼 수 없습니다. Codex를 실행 중인 기기에서 이 작업을 연 뒤 다시 보내세요. Cindy가 이미지를 생략하고 계속합니다.",
"codexCompactionNotConverging": "Codex가 컨텍스트를 반복해서 압축했지만 줄어들지 않아, 무한 루프를 막기 위해 이번 턴을 자동으로 중단했습니다. 공간을 차지하는 것은 대화가 아니라 압축으로 줄일 수 없는 시스템 프롬프트와 도구 정의인 경우가 대부분입니다. 새 세션을 시작하세요.",
"codexCompactionNotConvergingModelSwitch": "Codex가 컨텍스트를 반복해서 압축했지만 줄어들지 않아, 무한 루프를 막기 위해 이번 턴을 자동으로 중단했습니다. 이 세션은 도중에 모델을 변경했고, Codex는 변경 전 모델의 컨텍스트 한도로 계속 판단하고 있습니다. 원래 모델로 되돌리거나 새 세션을 시작하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 5849fcb6c0..3687b5c580 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8762,7 +8762,7 @@
"contextRebuild": {
"labelOverflow": "已整理上下文并继续",
"labelTimeout": "上一轮没有响应,已整理后继续",
- "labelStrip": "已去掉过大图片并继续",
+ "labelStrip": "已整理历史图片",
"toggleHint": "查看交接内容",
"handoffTitle": "交接内容——整理后发送给后续对话的上下文摘要(不计入对话记录,仅在此展示)",
"handoffTitleEnglishSource": "交接内容——整理后发送给后续对话的上下文摘要,原文为英文(不计入对话记录,仅在此展示)"
@@ -11394,7 +11394,7 @@
"codexAutoReviewUnavailable": "自动审批暂时不可用,当前操作已阻止并切换为默认权限。请重试,需要时会询问你。",
"hostShellCommandBlocked": "Cindy 已阻止会绕过内嵌模拟器的 Shell 命令。请改用模拟器工具控制设备、启动应用、操作界面、截图和诊断。",
"upstreamResponseIdleTimeout": "模型长时间没有任何响应,本轮已自动中断以免无限等待。已完成的工具调用都保留,可以直接发下一条消息继续。",
- "codexHistoryOversized": "这段历史里有过大的图片,远端压缩发不出去。Cindy 会自动略去这些图片,并在当前任务里继续。",
+ "codexHistoryOversized": "图片历史未能自动恢复并继续。请发送“继续”,接着完成当前任务。",
"codexHistoryOversizedRemote": "这段历史里有过大的图片,远端压缩发不出去。请在运行 Codex 的那台电脑上打开任务后再发送,Cindy 会自动略去这些图片并继续。",
"codexCompactionNotConverging": "Codex 反复压缩上下文却压不动,本轮已自动中断以免无限循环。压不动的部分通常不在对话里——system prompt 与工具定义占掉的空间压缩清不掉。新开一个任务可以继续。",
"codexCompactionNotConvergingModelSwitch": "Codex 反复压缩上下文却压不动,本轮已自动中断以免无限循环。本任务中途切换过模型,而 Codex 仍按切换前那个模型的上下文上限来判断。切回原模型可以继续,或者新开一个任务。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index f018d4eb9b..a07a259335 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8761,7 +8761,7 @@
"contextRebuild": {
"labelOverflow": "已整理上下文並繼續",
"labelTimeout": "上一輪沒有回應,已整理後繼續",
- "labelStrip": "已去掉過大圖片並繼續",
+ "labelStrip": "已整理歷史圖片",
"toggleHint": "檢視交接內容",
"handoffTitle": "交接內容——整理後傳送給後續對話的上下文摘要(不計入對話記錄,僅在此展示)",
"handoffTitleEnglishSource": "交接內容——整理後傳送給後續對話的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)"
@@ -11394,7 +11394,7 @@
"codexAutoReviewUnavailable": "自動審批暫時不可用,當前操作已阻止並切換為預設權限。請重試,需要時會詢問你。",
"hostShellCommandBlocked": "Cindy 已阻止會繞過內嵌模擬器的 Shell 命令。請改用模擬器工具控制裝置、啟動 App、操作介面、截圖和診斷。",
"upstreamResponseIdleTimeout": "模型長時間沒有任何響應,本輪已自動中斷以免無限等待。已完成的工具呼叫都保留,可以直接發下一條訊息繼續。",
- "codexHistoryOversized": "這段歷史裡有過大的圖片,遠端壓縮送不出去。Cindy 會自動略去這些圖片,並在目前任務裡繼續。",
+ "codexHistoryOversized": "圖片歷史未能自動恢復並繼續。請傳送「繼續」,接著完成目前任務。",
"codexHistoryOversizedRemote": "這段歷史裡有過大的圖片,遠端壓縮送不出去。請在執行 Codex 的那台電腦上打開任務後再傳送,Cindy 會自動略去這些圖片並繼續。",
"codexCompactionNotConverging": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。壓不動的部分通常不在對話裡——system prompt 與工具定義佔掉的空間壓縮清不掉。新開一個任務可以繼續。",
"codexCompactionNotConvergingModelSwitch": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。本任務中途切換過模型,而 Codex 仍按切換前那個模型的上下文上限來判斷。切回原模型可以繼續,或者新開一個任務。",
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index ce5d7b27bb..ab219d8ed4 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -48,7 +48,16 @@ Cindy 保底压缩是**一套**流程,不是剥图 / 换窗两套功能。装
决定函数见 `cindyContextCompression.ts`。字节预算目前只有 Codex 能测量。工具输出
不另开一档:官方 compact 会先清旧工具结果;官方失败后交接不带 tool_result 正文。
可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时
-由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援路径不得依赖额外模型调用。
+由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援摘要不得依赖额外模型调用。
+Codex 剥图保留原生历史后,普通用户任务可在同一任务内自动续接未完成工作,
+不重放原用户请求或已完成的工具操作;每条用户输入最多自动续接一次。
+停止/清空或新输入接管会取消待续接的恢复;已有排队输入时不抢先续接。
+取消也覆盖剥图失败后的重建、提交与发送边界。interrupt/unsubscribe 等待期间到达的
+权威成功结果优先于 oversized 错误;事件队列关闭前统一结算,不能再触发自动续接。
+续接沿用原输入的插件能力选择,不把隐藏续接提示或历史授权当作新选择。
+外部分发者仍拥有自己的重试;IM 原生任务、仍绑定 IM 的任务及尚未结束的外部分发 turn
+不进入 Desktop 图片历史自动恢复,不以缺失消息 origin 推定桌面授权。成功仅展示上下文整理分隔条,
+恢复或续接失败才显示错误与手动继续指引。发送前恢复不额外续接,避免与用户新输入重复。
切模型预检的数学仍在 `assessModelSwitchContext`。本机普通任务的用户选模只登记待应用意图,
不改当前 route 或原生线程;用户反复改选时覆盖意图,以实际发送时的最终选择为准。
沿用跨引擎的 pending registry 与发送入口,不能在 turn 结束或定时巡检时自动消费选模意图。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index cdec008434..cd18ea2d01 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1785,6 +1785,9 @@ export const AUTO_REVIEW_SOURCE_CONTENT = Symbol('cindy.auto-review-source-conte
/** Host-restored user authorization for this send; never accepted from wire options. */
export const AUTO_REVIEW_USER_INTENT = Symbol('cindy.auto-review-user-intent');
+/** Main-only selection from the original input for a retained-history continuation. */
+export const INHERITED_CAPABILITY_SELECTION = Symbol('cindy.inherited-capability-selection');
+
export interface MainOwnedSendContext {
readonly origin: TurnPermissionOrigin;
/** Main-authenticated user text before channel/persona/context decoration. */
@@ -1798,6 +1801,7 @@ export interface MainOwnedSendContext {
export interface SendOptions {
readonly [AUTO_REVIEW_SOURCE_CONTENT]?: UserMessage['content'];
readonly [AUTO_REVIEW_USER_INTENT]?: string;
+ readonly [INHERITED_CAPABILITY_SELECTION]?: string;
/** Host-authenticated metadata; never accept an equivalent string-keyed wire field. */
readonly [MAIN_OWNED_SEND_CONTEXT]?: MainOwnedSendContext;
/**
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 7f198a1fed..15207cc1d4 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -10,6 +10,7 @@ import { Method } from './app-server/protocol.js';
import type { ThreadEventHandlers } from './app-server/host.js';
import {
AUTO_REVIEW_SOURCE_CONTENT,
+ INHERITED_CAPABILITY_SELECTION,
MAIN_OWNED_SEND_CONTEXT,
CodexResumePreparationBlockedError,
AgentNotAuthenticatedError,
@@ -2065,7 +2066,8 @@ describe('CodexAgent capability routing', () => {
}
});
- it('binds explicit capability selection before a pending turn/start response', async () => {
+ it.each([undefined, '', '请用 $feishu-delegate:message-feishu-coworkers 查消息'])(
+ 'binds original capability selection before pending turn/start: %s', async (inheritedSelection) => {
const pendingTurnStart = deferred<{ turn: { id: string } }>();
const agent = new CodexAgent(
createDeps(
@@ -2091,7 +2093,10 @@ describe('CodexAgent capability routing', () => {
});
const sendPromise = handle.send({
type: 'user',
- content: '请用 $feishu-delegate:message-feishu-coworkers 查消息',
+ content: inheritedSelection === undefined
+ ? '请用 $feishu-delegate:message-feishu-coworkers 查消息' : 'Continue the retained task.',
+ }, inheritedSelection === undefined ? undefined : {
+ [INHERITED_CAPABILITY_SELECTION]: inheritedSelection,
});
await vi.waitFor(() => {
expect(
@@ -2141,7 +2146,7 @@ describe('CodexAgent capability routing', () => {
message: 'Allow tool call',
requestedSchema: {},
}),
- ).resolves.toEqual({ action: 'accept', content: null, _meta: null });
+ ).resolves.toEqual({ action: inheritedSelection === '' ? 'decline' : 'accept', content: null, _meta: null });
pendingTurnStart.resolve({ turn: { id: 'early-capability-turn' } });
await sendPromise;
@@ -29027,6 +29032,7 @@ describe('CodexAgent reconnect-stall watchdog', () => {
agent: CodexAgent,
sessionId: string,
interruptAck?: Promise<unknown>,
+ signal?: AbortSignal,
) {
const host = installReconnectHost(agent, false, interruptAck);
const handle = await agent.startSession({ sessionId, model: 'gpt-5.4', workingDir: '/repo' });
@@ -29034,7 +29040,7 @@ describe('CodexAgent reconnect-stall watchdog', () => {
void (async () => {
for await (const event of handle.events()) seen.push(event);
})();
- await handle.send({ type: 'user', content: 'go' });
+ await handle.send({ type: 'user', content: 'go' }, { signal });
const handlers = host.getThreadHandlers();
if (!handlers) throw new Error('expected thread handlers');
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
@@ -29084,7 +29090,17 @@ describe('CodexAgent reconnect-stall watchdog', () => {
}
});
- it('classifies reconnect stall as oversized only when live-tail images are strip-worthy', async () => {
+ it.each([
+ { cancelled: false, completion: undefined, rejectAck: false },
+ { cancelled: true, completion: undefined, rejectAck: false },
+ { cancelled: false, completion: undefined, rejectAck: true },
+ { cancelled: true, completion: undefined, rejectAck: true },
+ ...(['completed', 'failed', 'interrupted'] as const).flatMap((completion) =>
+ [false, true].map((rejectAck) => ({ cancelled: false, completion, rejectAck }))),
+ ].flatMap((scenario) => [
+ { ...scenario, releaseFailure: undefined as boolean | undefined },
+ ...(scenario.rejectAck ? [false, true].map((releaseFailure) => ({ ...scenario, releaseFailure })) : []),
+ ]))('settles oversized recovery: %j', async ({ cancelled, completion, rejectAck, releaseFailure }) => {
vi.useFakeTimers();
const agent = new CodexAgent(createDeps());
const proto = Object.getPrototypeOf(agent) as {
@@ -29103,19 +29119,70 @@ describe('CodexAgent reconnect-stall watchdog', () => {
scannedBytes: 20 * 1024 * 1024,
});
try {
- const { handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-oversized');
+ let acknowledge!: (value: unknown) => void;
+ let reject!: (reason: Error) => void;
+ const ack = new Promise((resolve, rejectPromise) => { acknowledge = resolve; reject = rejectPromise; });
+ const cancellation = new AbortController();
+ const retire = vi.spyOn(agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },
+ 'retireHostKey').mockResolvedValue(undefined);
+ const { host, handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-oversized', ack, cancellation.signal);
+ const releasing = deferred<void>();
+ const release = host.subscribeThread.mock.results[0]?.value.release;
+ if (releaseFailure !== undefined) release.mockImplementationOnce(() => releasing.promise);
+ handlers.itemCompleted?.({
+ threadId: 'start-thread-id', turnId: 'turn-1',
+ item: { id: 'answer-1', type: 'agentMessage', text: 'Work finished.', phase: 'final_answer' },
+ } as never);
emitReconnect(handlers, 1);
await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS + 1);
await Promise.resolve();
await Promise.resolve();
+ expect(handle.isTurnRunning?.()).toBe(true);
expect(seen).toContainEqual(expect.objectContaining({
- type: 'error',
- data: expect.objectContaining({
- reason: 'codex_history_oversized',
- isTerminal: true,
- }),
+ type: 'status', data: expect.objectContaining({ status: 'Compacting...', isRunning: true }),
}));
- expect(seen.filter((event) => event.type === 'error' && (event.data as { reason?: string }).reason === 'codex_history_oversized')).toHaveLength(1);
+ expect(seen.some((event) => event.type === 'error' &&
+ (event.data as { reason?: string }).reason === 'codex_history_oversized')).toBe(false);
+ if (releaseFailure !== undefined) {
+ reject(new Error('interrupt unavailable'));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(release).toHaveBeenCalledOnce();
+ expect(seen.some((event) => event.type === 'error' &&
+ (event.data as { reason?: string }).reason === 'codex_history_oversized')).toBe(false);
+ }
+ if (cancelled) cancellation.abort();
+ if (completion) {
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id', turn: { id: 'turn-1', status: completion },
+ } as never);
+ expect(handle.isTurnRunning?.()).toBe(true);
+ }
+ if (releaseFailure !== undefined) {
+ if (releaseFailure) releasing.reject(new Error('unsubscribe failed'));
+ else releasing.resolve();
+ } else if (rejectAck) reject(new Error('turn already ended'));
+ else acknowledge({});
+ await vi.advanceTimersByTimeAsync(1);
+ if (completion || !rejectAck) expect(handle.isTurnRunning?.()).toBe(false);
+ const oversizedIndex = seen.findIndex((event) => event.type === 'error' &&
+ (event.data as { reason?: string }).reason === 'codex_history_oversized');
+ if (cancelled || completion === 'completed') expect(oversizedIndex).toBe(-1);
+ else {
+ expect(oversizedIndex).toBeGreaterThanOrEqual(0);
+ if (completion || !rejectAck) expect(seen[oversizedIndex + 1]).toMatchObject({
+ type: 'status', data: { isRunning: false },
+ });
+ }
+ if (completion === 'completed') {
+ const done = seen.filter((event) => event.type === 'done');
+ expect(done).toHaveLength(1);
+ expect(done[0]).toMatchObject({ data: { result: 'Work finished.' } });
+ expect(retire).not.toHaveBeenCalled();
+ if (releaseFailure === undefined) {
+ await handle.send({ type: 'user', content: 'next task' });
+ expect(handle.isTurnRunning?.()).toBe(true);
+ }
+ }
await handle.close();
} finally {
localHome.mockRestore();
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index afa4538f3e..b417e9cb56 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -28,6 +28,7 @@ import { structuredPatch } from 'diff';
import {
BaseAgent,
+ INHERITED_CAPABILITY_SELECTION,
CodexResumePreparationBlockedError,
OneShotError,
AgentNotAuthenticatedError,
@@ -5515,6 +5516,7 @@ export class CodexAgent extends BaseAgent {
reason: string;
cleanup: () => Promise<void>;
retireHostOnFailure?: boolean;
+ closeHandleOnFailure?: boolean;
}): Promise<boolean> => {
try {
await params.cleanup();
@@ -5537,13 +5539,13 @@ export class CodexAgent extends BaseAgent {
});
}
}
- terminateHandleAfterThreadCleanupFailure(params.reason);
+ if (params.closeHandleOnFailure !== false) terminateHandleAfterThreadCleanupFailure(params.reason);
return false;
}
};
const releaseCurrentThreadSubscription = async (
reason: string,
- opts: { retireHostOnFailure?: boolean } = {},
+ opts: { retireHostOnFailure?: boolean; closeHandleOnFailure?: boolean } = {},
): Promise<boolean> => {
const currentSubscription = subscription;
if (!currentSubscription) return true;
@@ -5552,6 +5554,7 @@ export class CodexAgent extends BaseAgent {
reason,
cleanup: () => currentSubscription.release(),
retireHostOnFailure: opts.retireHostOnFailure ?? true,
+ closeHandleOnFailure: opts.closeHandleOnFailure,
});
if (subscription === currentSubscription) subscription = null;
return released;
@@ -7720,7 +7723,7 @@ export class CodexAgent extends BaseAgent {
// 先立终态墓碑:下面合成的本地收口据此走 suppressTerminalUi 分支(只清状态、
// 不再推一遍终态 UI),迟到的 item / error 也一并被 stale guard 拦住。
if (turnId) terminalErroredTurnIds.add(turnId);
- eventQueue.push({
+ const timeoutEvent: AgentEvent = {
type: 'error',
data: {
// reason 与 claude-code 侧共用同一稳定 key(renderer i18n 映射,规则 18);
@@ -7736,7 +7739,34 @@ export class CodexAgent extends BaseAgent {
msSinceLastEvent: msSinceLast,
},
source: 'codex',
- });
+ };
+ // Main can only relink an idle native thread. Publishing this error before
+ // interrupt ACK made its one-shot recovery see busy and abandon the task.
+ const deferOversizedError =
+ opts?.reason === CODEX_HISTORY_OVERSIZED_REASON && !pendingTurnId && !!turnId;
+ const interruptedSend = overloadRetry;
+ let timeoutEmitted = false;
+ const emitTimeout = (settled = false): void => {
+ if (timeoutEmitted || closed) return;
+ timeoutEmitted = true;
+ if (!deferOversizedError || !interruptedSend?.isCancelled()) eventQueue.push(timeoutEvent);
+ if (deferOversizedError && settled) {
+ // Session drains terminal errors with an idle tail. Do not leave its
+ // drain watchdog armed when Main cannot recover this thread.
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
+ source: 'codex',
+ });
+ }
+ };
+ if (deferOversizedError) {
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Compacting...', ...usageTracker.snapshot(), isRunning: true },
+ source: 'codex',
+ });
+ } else emitTimeout();
if (pendingTurnId) {
// 重连提示可能早于 turnStarted 到达。此时 turn/start 仍在飞,不能只清掉
// 看门狗:迟到的 response / turnStarted 必须被隔离,否则用户已经看到终态后
@@ -7804,17 +7834,26 @@ export class CodexAgent extends BaseAgent {
// 进入旧 transport。
const turnGenBeforeInterrupt = turnStartGeneration;
void (async () => {
+ // All ACK/release outcomes use the same authoritative-success decision.
+ const settleInterruptedTurn = (fallback?: TurnCompletedParams): boolean => {
+ const completedNormally = deferOversizedError &&
+ reconnectStallDeferredTurnCompletion?.turn.status === 'completed';
+ if (completedNormally) terminalErroredTurnIds.delete(turnId);
+ const settled = settleReconnectStallCleanup(turnId, fallback);
+ if (settled && deferOversizedError && !completedNormally) emitTimeout(true);
+ return settled;
+ };
const interrupted = await interruptTurnForPermissionTighten(turnId, {
suppressFailureEvent: true,
});
if (interrupted) {
- if (!settleReconnectStallCleanup(turnId, {
+ if (!settleInterruptedTurn({
threadId,
turn: { id: turnId, status: 'failed' },
} as TurnCompletedParams)) clearReconnectStallCleanup(turnId);
return;
}
- if (settleReconnectStallCleanup(turnId)) {
+ if (settleInterruptedTurn()) {
log.info('reconnect-stall turn completed while interrupt was settling; keeping shared host', {
threadId,
turnId,
@@ -7851,6 +7890,17 @@ export class CodexAgent extends BaseAgent {
'upstream-idle watchdog: turn interrupt not confirmed — closing this codex host so the next send rebuilds it',
{ threadId, turnId },
);
+ let completedDuringRelease = false;
+ if (deferOversizedError) {
+ // Keep the terminal stream open through unsubscribe, including a failed
+ // release. This caller closes the handle after publishing its one result.
+ await releaseCurrentThreadSubscription('reconnect-stall subscription release', {
+ retireHostOnFailure: false,
+ closeHandleOnFailure: false,
+ });
+ completedDuringRelease = settleInterruptedTurn();
+ if (!completedDuringRelease) emitTimeout();
+ }
try {
// thread/unsubscribe 失败本身不能先强退共享 host:同 turn 的权威
// completion 仍可能在 close 等待期间到达。先只终止当前 handle,等下方
@@ -7859,7 +7909,7 @@ export class CodexAgent extends BaseAgent {
} catch (e) {
log.warn('upstream-idle watchdog close threw', { error: String(e) });
}
- if (settleReconnectStallCleanup(turnId)) {
+ if (completedDuringRelease || settleInterruptedTurn()) {
log.info('reconnect-stall turn completed during handle close; keeping shared host', {
threadId,
turnId,
@@ -9693,6 +9743,16 @@ export class CodexAgent extends BaseAgent {
// including the paths that defer UI settlement or return early. Item
// history is only needed while approval attribution is still mutable.
observedModelItemIdsByTurn.delete(turn.id);
+ if (reconnectStallCleanupTurnId === turn.id) {
+ // Retain the authoritative terminal and its reply until the interrupt
+ // handshake settles; do not consume data needed by normal completion.
+ reconnectStallDeferredTurnCompletion ??= params;
+ log.debug('deferring reconnect-stall turn completion until interrupt settles', {
+ threadId,
+ turnId: turn.id,
+ });
+ return;
+ }
const assistantReply = assistantReplyByTurn.get(turn.id);
assistantReplyByTurn.delete(turn.id);
const finalAssistantText = assistantReply?.finalText ?? assistantReply?.lastText ?? '';
@@ -9735,19 +9795,6 @@ export class CodexAgent extends BaseAgent {
});
return;
}
- if (reconnectStallCleanupTurnId === turn.id) {
- // The watchdog already published the terminal error and is still
- // waiting for turn/interrupt. Keep the local busy guard until the
- // handshake settles, but retain this authoritative completion: it
- // proves the old turn ended and the host event path is alive, so a
- // double interrupt rejection must not retire healthy sibling sessions.
- reconnectStallDeferredTurnCompletion ??= params;
- log.debug('deferring reconnect-stall turn completion until interrupt settles', {
- threadId,
- turnId: turn.id,
- });
- return;
- }
if (reconnectStallTurnId === turn.id) clearReconnectStall();
let recoveryState = overloadRetry;
let pendingRecovery =
@@ -12080,7 +12127,7 @@ export class CodexAgent extends BaseAgent {
const capabilitySelectionText =
(sendOpts as CodexInternalSendOptions | undefined)?.[
CODEX_INHERITED_CAPABILITY_SELECTION
- ] ?? userMessageText(message.content);
+ ] ?? sendOpts?.[INHERITED_CAPABILITY_SELECTION] ?? userMessageText(message.content);
assertCurrentHost('turn/start');
resubscribeAfterTransportErrorIfNeeded();
// 新 turn 总是携带当前 (可能已收紧的) 策略, 上一轮残留的延迟中断标记