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): 保留策略中断的错误提示 (#2436)

Dash4048aef9c293
diff --git a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
index 18bb1ee408..b35a827062 100644
--- a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
@@ -37,6 +37,12 @@ describe('mapServerMessages — persisted terminal error rows', () => {
);
});
+ it('maps host shell-command policy blocks to stable localized copy', () => {
+ expect(ERROR_REASON_I18N_KEYS['host-shell-command-blocked']).toBe(
+ 'logic.errors.hostShellCommandBlocked',
+ );
+ });
+
it('maps upstream overload to the same copy the tail banner uses', () => {
// 本表注释的一致性诉求: 同一条过载错误不能出现「尾部红条本地化、历史静态卡
// 英文原文」的分裂。复用 banner 那条 key(不新增文案), 且 codex 改措辞也不影响
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 67641d0e98..579e19e892 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -17,6 +17,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'silent-stop-exhausted': 'logic.errors.silentStopExhausted',
'permission-tighten-interrupt-failed': 'logic.errors.permissionTightenInterruptFailed',
'codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable',
+ 'host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',
upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
codex_reconnect_stalled: 'logic.errors.upstreamResponseIdleTimeout',
// 压缩风暴分两条:有切模型证据的才点名切模型。共用一条会让没切过模型(或已切回)
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fb08d6b8cf..43cfffcad7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8883,6 +8883,7 @@
"silentStopExhausted": "The model returned empty responses repeatedly; auto-resume is paused. Click \"Continue\" to resume the task.",
"permissionTightenInterruptFailed": "Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed.",
"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.",
"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 e3957d38c2..209a7af965 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8870,6 +8870,7 @@
"silentStopExhausted": "モデルが空の応答を繰り返し返したため、自動再開を一時停止しました。「続行」をクリックしてタスクを再開してください。",
"permissionTightenInterruptFailed": "権限を厳格化する際に実行中のタスクを停止できませんでした。タスクは終了まで確認なしで実行され続ける可能性があります。必要に応じて手動で停止してください。",
"codexAutoReviewUnavailable": "自動レビューは一時的に利用できません。現在の操作をブロックし、デフォルト権限に切り替えました。もう一度実行してください。必要な場合は確認します。",
+ "hostShellCommandBlocked": "Cindy は内蔵 iOS シミュレータを迂回するシェルコマンドをブロックしました。デバイスの操作、アプリの起動、画面操作、スクリーンショット、診断には iOS シミュレータツールを使用してください。",
"upstreamResponseIdleTimeout": "モデルから長時間応答がなかったため、無限待機を避けるためこのターンを自動中断しました。完了したツール呼び出しは保持されています。次のメッセージを送信して続行できます。",
"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 b046daa5ed..92b5cfbe86 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8870,6 +8870,7 @@
"silentStopExhausted": "모델이 빈 응답을 반복해서 반환하여 자동 재개가 일시 중지되었습니다. \"계속\"을 클릭하여 작업을 재개하세요.",
"permissionTightenInterruptFailed": "권한을 강화하는 동안 실행 중인 작업을 중지하지 못했습니다. 작업이 끝날 때까지 확인 없이 계속 실행될 수 있습니다. 필요하면 수동으로 중지하세요.",
"codexAutoReviewUnavailable": "자동 리뷰를 일시적으로 사용할 수 없습니다. 현재 작업을 차단하고 기본 권한으로 전환했습니다. 다시 시도하세요. 필요한 경우 확인을 요청합니다.",
+ "hostShellCommandBlocked": "Cindy가 내장 iOS 시뮬레이터를 우회하는 셸 명령을 차단했습니다. 기기 제어, 앱 실행, 화면 조작, 스크린샷, 진단에는 iOS 시뮬레이터 도구를 사용하세요.",
"upstreamResponseIdleTimeout": "모델이 오랫동안 응답하지 않아 무한 대기를 막기 위해 이번 턴을 자동으로 중단했습니다. 완료된 도구 호출은 유지되며, 다음 메시지를 보내 계속할 수 있습니다.",
"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 beda75b17a..ab9932cc5b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8866,6 +8866,7 @@
"silentStopExhausted": "模型连续多次返回空响应,自动续跑已暂停。点击「继续」恢复任务。",
"permissionTightenInterruptFailed": "收紧权限时未能停止正在运行的任务,它可能会继续免确认执行直到结束;如有需要请手动停止。",
"codexAutoReviewUnavailable": "自动审批暂时不可用,当前操作已阻止并切换为默认权限。请重试,需要时会询问你。",
+ "hostShellCommandBlocked": "Cindy 已阻止会绕过内嵌模拟器的 Shell 命令。请改用模拟器工具控制设备、启动应用、操作界面、截图和诊断。",
"upstreamResponseIdleTimeout": "模型长时间没有任何响应,本轮已自动中断以免无限等待。已完成的工具调用都保留,可以直接发下一条消息继续。",
"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 7f7354a5dc..29a11dea25 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8869,6 +8869,7 @@
"silentStopExhausted": "模型連續多次返回空響應,自動續跑已暫停。點選「繼續」恢復任務。",
"permissionTightenInterruptFailed": "收緊權限時未能停止正在執行的任務,它可能會繼續免確認執行直到結束;如有需要請手動停止。",
"codexAutoReviewUnavailable": "自動審批暫時不可用,當前操作已阻止並切換為預設權限。請重試,需要時會詢問你。",
+ "hostShellCommandBlocked": "Cindy 已阻止會繞過內嵌模擬器的 Shell 命令。請改用模擬器工具控制裝置、啟動 App、操作介面、截圖和診斷。",
"upstreamResponseIdleTimeout": "模型長時間沒有任何響應,本輪已自動中斷以免無限等待。已完成的工具呼叫都保留,可以直接發下一條訊息繼續。",
"codexCompactionNotConverging": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。壓不動的部分通常不在對話裡——system prompt 與工具定義佔掉的空間壓縮清不掉。新開一個任務可以繼續。",
"codexCompactionNotConvergingModelSwitch": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。本任務中途切換過模型,而 Codex 仍按切換前那個模型的上下文上限來判斷。切回原模型可以繼續,或者新開一個任務。",
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 35df0a7d93..9996f5f09c 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -282,16 +282,22 @@ function createNoopLogger(): Logger {
return logger;
}
-function createLoggerSpy(): { logger: Logger; warn: ReturnType<typeof vi.fn> } {
+function createLoggerSpy(): {
+ logger: Logger;
+ warn: ReturnType<typeof vi.fn>;
+ error: ReturnType<typeof vi.fn>;
+} {
const warn = vi.fn();
+ const error = vi.fn();
const logger: Logger = {
...createNoopLogger(),
warn,
+ error,
child() {
return logger;
},
};
- return { logger, warn };
+ return { logger, warn, error };
}
function createDeps(
@@ -13036,10 +13042,16 @@ describe('CodexAgent MCP thread context hooks', () => {
decision: 'deny' as const,
reason: 'use the embedded iOS Simulator',
}));
+ let acknowledgeInterrupt!: () => void;
+ const interruptAck = new Promise<unknown>((resolve) => {
+ acknowledgeInterrupt = () => resolve({});
+ });
const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy, logger }));
- const host = installFakeHost(agent, (method) =>
- method === Method.TurnInterrupt ? {} : undefined,
- );
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ if (method === Method.TurnInterrupt) return interruptAck;
+ return undefined;
+ });
const handle = await agent.startSession({
sessionId: 'session-command-item-host-policy',
model: 'gpt-5.4',
@@ -13047,7 +13059,15 @@ describe('CodexAgent MCP thread context hooks', () => {
permissionMode: 'bypassPermissions',
});
const handlers = host.getThreadHandlers();
- if (!handlers?.itemStarted) throw new Error('expected itemStarted handler');
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ await handle.send({ type: 'user', content: 'test host policy' });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { isRunning: true },
+ });
const command = 'API_TOKEN=super-secret /usr/bin/open -a Simulator';
handlers.itemStarted({
@@ -13075,6 +13095,454 @@ describe('CodexAgent MCP thread context hooks', () => {
reason: 'use the embedded iOS Simulator',
});
expect(JSON.stringify(warn.mock.calls)).not.toContain('super-secret');
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: {
+ message: 'use the embedded iOS Simulator',
+ isTerminal: false,
+ reason: 'host-shell-command-blocked',
+ },
+ });
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute',
+ type: 'commandExecution',
+ command,
+ cwd: '/repo',
+ },
+ });
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnInterrupt),
+ ).toHaveLength(1);
+
+ acknowledgeInterrupt();
+ await Promise.resolve();
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute-after-ack',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: false, reason: 'host-shell-command-blocked' },
+ });
+ await vi.waitFor(() => {
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnInterrupt),
+ ).toHaveLength(2);
+ });
+
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'interrupted' },
+ });
+
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: {
+ message: 'use the embedded iOS Simulator',
+ isTerminal: true,
+ reason: 'host-shell-command-blocked',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');
+ await handle.close();
+ });
+
+ it('keeps explicit user Stop attribution after a policy hit and late blocked item', async () => {
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ let resolvePolicyInterrupt!: () => void;
+ const policyInterruptAck = new Promise<unknown>((resolve) => {
+ resolvePolicyInterrupt = () => resolve({});
+ });
+ let interruptCount = 0;
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ if (method === Method.TurnInterrupt) {
+ interruptCount += 1;
+ return interruptCount === 1 ? policyInterruptAck : {};
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy-user-stop',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ await handle.send({ type: 'user', content: 'test user Stop after host policy' });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { isRunning: true },
+ });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-before-stop',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: false, reason: 'host-shell-command-blocked' },
+ });
+
+ await handle.abort();
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-after-stop',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnInterrupt),
+ ).toHaveLength(2);
+
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'interrupted' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'done',
+ data: { cancelled: true },
+ });
+
+ resolvePolicyInterrupt();
+ await Promise.resolve();
+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');
+ await handle.close();
+ });
+
+ it('ends an active plan cycle after a host-policy interruption', async () => {
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ let turnSeq = 0;
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: `turn-${++turnSeq}` } };
+ if (method === Method.TurnInterrupt) return {};
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy-plan-cycle',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ planMode: true,
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+
+ await handle.send({ type: 'user', content: 'make a plan' });
+ const turnStartRequests = () =>
+ host.request.mock.calls.filter(([method]) => method === Method.TurnStart);
+ const [, planParams] = turnStartRequests()[0] as [string, Record<string, unknown>];
+ expect(planParams.collaborationMode).toMatchObject({ mode: 'plan' });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-plan-bypass',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'interrupted' },
+ });
+
+ await handle.send({ type: 'user', content: 'continue normally' });
+ const [, normalParams] = turnStartRequests()[1] as [string, Record<string, unknown>];
+ expect(normalParams.collaborationMode).toMatchObject({ mode: 'default' });
+ await handle.close();
+ });
+
+ it.each(['interrupted', 'completed', 'failed'] as const)(
+ 'preserves an early %s turn completion while interrupt ACK is pending',
+ async (turnStatus) => {
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ let acknowledgeInterrupt!: () => void;
+ const interruptAck = new Promise<unknown>((resolve) => {
+ acknowledgeInterrupt = () => resolve({});
+ });
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ if (method === Method.TurnInterrupt) return interruptAck;
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy-completes-before-ack',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ await handle.send({ type: 'user', content: 'test early completion' });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { isRunning: true },
+ });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: false, reason: 'host-shell-command-blocked' },
+ });
+
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: turnStatus },
+ });
+ if (turnStatus === 'interrupted') {
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: true, reason: 'host-shell-command-blocked' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ } else if (turnStatus === 'failed') {
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: true, reason: 'turn-failed' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'done',
+ data: { cancelled: false, raw: { status: 'failed' } },
+ });
+ } else {
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'done',
+ data: { raw: { status: 'completed' } },
+ });
+ }
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ acknowledgeInterrupt();
+ await Promise.resolve();
+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');
+ await handle.close();
+ },
+ );
+
+ it('keeps the turn visible when a host-policy interrupt cannot be acknowledged', async () => {
+ const { logger, error } = createLoggerSpy();
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy, logger }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ if (method === Method.TurnInterrupt) throw new Error('transport closed');
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy-interrupt-failed',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ await handle.send({ type: 'user', content: 'test failed host-policy interrupt' });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { isRunning: true },
+ });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: {
+ message: 'use the embedded iOS Simulator',
+ isTerminal: false,
+ reason: 'host-shell-command-blocked',
+ },
+ });
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnInterrupt),
+ ).toHaveLength(2);
+ expect(handle.isTurnRunning?.()).toBe(true);
+ await vi.waitFor(() => {
+ expect(error).toHaveBeenCalledWith('host policy could not interrupt running command', {
+ turnId: 'turn-1',
+ });
+ });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute-2',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: false, reason: 'host-shell-command-blocked' },
+ });
+ await vi.waitFor(() => {
+ expect(
+ host.request.mock.calls.filter(([method]) => method === Method.TurnInterrupt),
+ ).toHaveLength(4);
+ });
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('preserves policy origin when interrupt ACKs are lost before an interrupted completion', async () => {
+ const { logger, error } = createLoggerSpy();
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy, logger }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ if (method === Method.TurnInterrupt) throw new Error('ACK lost');
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy-interrupt-ack-lost',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.turnCompleted) {
+ throw new Error('expected itemStarted and turnCompleted handlers');
+ }
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ await handle.send({ type: 'user', content: 'test lost interrupt ACK' });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { isRunning: true },
+ });
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute',
+ type: 'commandExecution',
+ command: '/usr/bin/open -a Simulator',
+ cwd: '/repo',
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: false, reason: 'host-shell-command-blocked' },
+ });
+ await vi.waitFor(() => {
+ expect(error).toHaveBeenCalledWith('host policy could not interrupt running command', {
+ turnId: 'turn-1',
+ });
+ });
+
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'interrupted' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: { isTerminal: true, reason: 'host-shell-command-blocked' },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');
await handle.close();
});
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 8fca82dc09..020a19342e 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -3020,6 +3020,21 @@ export class CodexAgent extends BaseAgent {
// turn id 在同一 thread 内唯一;墓碑随 session handle 释放,不跨 session 泄漏。
const completedTurnIds = new Set<string>();
const terminalErroredTurnIds = new Set<string>();
+ // Keep one authoritative interrupt origin per turn until turn/completed.
+ // A host-policy ACK proves only request acceptance, not that the command
+ // stopped; explicit user Stop overrides that provenance and cannot be
+ // reclassified by late blocked-item notifications. Failed policy ACKs stay
+ // provenance-only so output remains visible until completion decides.
+ const turnInterruptOrigins = new Map<
+ string,
+ | {
+ source: 'host-policy';
+ reason: string;
+ itemId: string;
+ acknowledgement: 'pending' | 'acknowledged' | 'failed';
+ }
+ | { source: 'user-stop' }
+ >();
// daemon 后端 retry-loop 的终局升级 (issue #677): 远端摸不到 Codex 后端时
// daemon 无限 willRetry, turn 永不收口。同 turn 重试超阈值 → 合成终态错误,
// 走与终态 error 完全相同的收口路径 (terminalErroredTurnIds + Done status)。
@@ -7680,6 +7695,45 @@ export class CodexAgent extends BaseAgent {
function handleTurnCompleted(params: TurnCompletedParams): void {
const turn = params.turn;
+ const interruptOrigin = turnInterruptOrigins.get(turn.id);
+ turnInterruptOrigins.delete(turn.id);
+ if (
+ interruptOrigin?.source === 'host-policy'
+ && !terminalErroredTurnIds.has(turn.id)
+ && !completedTurnIds.has(turn.id)
+ && turn.status === 'interrupted'
+ ) {
+ // The provider completion is the first proof that the denied command is
+ // actually finished. Close the turn with the policy error and Codex's
+ // required idle tail; the tombstone keeps interrupted from becoming a
+ // user-Stop done(cancelled:true). Completed/failed fall through to the
+ // provider-authoritative path regardless of interrupt ACK state.
+ // This path deliberately tombstones the provider completion, so the
+ // normal interrupted-turn branch below cannot end a plan cycle for us.
+ // Clear it here before the next send inherits stale Plan Mode state.
+ if (currentTurnPlanModeActive) {
+ proposedPlanText = null;
+ planCycleActive = false;
+ currentTurnPlanModeActive = false;
+ }
+ terminalErroredTurnIds.add(turn.id);
+ eventQueue.push({
+ type: 'error',
+ data: {
+ message: interruptOrigin.reason,
+ isTerminal: true,
+ reason: 'host-shell-command-blocked',
+ },
+ source: 'codex',
+ });
+ handleTurnCompleted(params);
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
+ source: 'codex',
+ });
+ 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
@@ -8967,18 +9021,67 @@ export class CodexAgent extends BaseAgent {
});
if (hostPolicy?.decision === 'deny') {
discardPendingSpawnLineageIds(reservedChildThreadIds);
+ const existingInterruptOrigin = turnInterruptOrigins.get(params.turnId);
+ // Explicit user Stop owns the terminal attribution until the
+ // authoritative completion. Late blocked items must not reclassify
+ // that cancellation as a policy interruption.
+ if (existingInterruptOrigin?.source === 'user-stop') return;
+ // Deduplicate only the same blocked item while its interrupt RPC is
+ // still in flight. A different blocked item is fresh proof that the
+ // turn is still executing and must issue another bounded interrupt,
+ // even if the previous request has not acknowledged yet.
+ if (
+ existingInterruptOrigin?.acknowledgement === 'pending' &&
+ existingInterruptOrigin.itemId === params.item.id
+ ) {
+ return;
+ }
log.warn('command execution interrupted by host policy', {
turnId: params.turnId,
reason: hostPolicy.reason,
});
- void host
- .request(Method.TurnInterrupt, { threadId, turnId: params.turnId })
- .catch(() => undefined);
+ const pendingInterrupt: {
+ source: 'host-policy';
+ reason: string;
+ itemId: string;
+ acknowledgement: 'pending' | 'acknowledged' | 'failed';
+ } = {
+ source: 'host-policy',
+ reason: hostPolicy.reason,
+ itemId: params.item.id,
+ acknowledgement: 'pending',
+ };
+ turnInterruptOrigins.set(params.turnId, pendingInterrupt);
+ // Keep the task visibly running until provider completion proves the
+ // command stopped. This non-terminal warning survives the ACK window
+ // without arming Session's terminal-error drain.
eventQueue.push({
type: 'error',
- data: { message: hostPolicy.reason, isTerminal: false },
+ data: {
+ message: pendingInterrupt.reason,
+ isTerminal: false,
+ reason: 'host-shell-command-blocked',
+ },
source: 'codex',
});
+ void (async () => {
+ const interrupted = await interruptTurnForPermissionTighten(params.turnId, {
+ suppressFailureEvent: true,
+ });
+ if (turnInterruptOrigins.get(params.turnId) !== pendingInterrupt) return;
+ if (interrupted) {
+ pendingInterrupt.acknowledgement = 'acknowledged';
+ return;
+ }
+ pendingInterrupt.acknowledgement = 'failed';
+ if (closed) return;
+ // The command may still be running. This provenance marker is not
+ // a tombstone, so later output remains visible; completion status
+ // decides whether the interrupt actually took effect.
+ log.error('host policy could not interrupt running command', {
+ turnId: params.turnId,
+ });
+ })();
return;
}
}
@@ -10456,6 +10559,12 @@ export class CodexAgent extends BaseAgent {
const hadPendingRetry = overloadRetryPending();
discardOverloadRetry('aborted');
if (closed) return;
+ if (currentTurnId) {
+ // User intent wins terminal attribution. Keep an explicit marker
+ // instead of merely deleting policy provenance so late blocked-item
+ // notifications cannot re-arm it before turn/completed arrives.
+ turnInterruptOrigins.set(currentTurnId, { source: 'user-stop' });
+ }
// 有挂起重投时的 Stop **必须**由这里显式收口逻辑 turn —— desktop 的
// SessionTurnActivityTracker 只在收到终态事件后才释放派发闩,Codex
// coordinator 也刻意等这个事件而不自己解锁,hook runner 同样等到一小时硬