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): 避免延迟重启阻塞已空闲任务 (#5096)

Dashc61a4b4ee739
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
index 7300821990..d71ec2d958 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
@@ -27,6 +27,7 @@ describe('DeferredCodexRestartService', () => {
hasBusyLocalCodexSession?: () => boolean;
listLocalCodexSessionIds?: () => string[];
onApplied?: (sessionIds: string[]) => void;
+ onQueueGateReleased?: (sessionIds: string[]) => void;
}) {
const restart = overrides?.restart ?? vi.fn(async () => {});
const service = new DeferredCodexRestartService({
@@ -36,12 +37,50 @@ describe('DeferredCodexRestartService', () => {
hasBusyLocalCodexSession: overrides?.hasBusyLocalCodexSession ?? (() => false),
listLocalCodexSessionIds: overrides?.listLocalCodexSessionIds ?? (() => []),
onApplied: overrides?.onApplied,
+ onQueueGateReleased: overrides?.onQueueGateReleased,
retryDelayMs: 1_000,
logger,
});
return { service, restart };
}
+ it.each(['success', 'failure', 'owner-change'])(
+ 'releases only the captured restart scope after %s', async (outcome) => {
+ let finish!: () => void;
+ const held = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const onQueueGateReleased = vi.fn((ids: string[]) => {
+ for (const id of ids) expect(service.isSessionRestarting(id)).toBe(false);
+ });
+ const { service } = createService({
+ listLocalCodexSessionIds: () => ['local-codex'],
+ restart: async () => {
+ await held;
+ if (outcome === 'failure') throw new Error('restart failed');
+ },
+ onQueueGateReleased,
+ });
+ service.schedule('browser-change');
+ expect(service.isSessionRestarting('local-codex')).toBe(false);
+ const attempt = service.flushBeforeLocalCodexSessionStart();
+ expect(service.isSessionRestarting('local-codex')).toBe(true);
+ expect(service.isSessionRestarting('unrelated-session')).toBe(false);
+ if (outcome === 'owner-change') service.clear();
+ finish();
+ await attempt;
+
+ expect(service.isSessionRestarting('local-codex')).toBe(false);
+ if (outcome === 'owner-change') {
+ expect(onQueueGateReleased).not.toHaveBeenCalled();
+ } else {
+ expect(onQueueGateReleased).toHaveBeenCalledExactlyOnceWith(['local-codex']);
+ }
+ expect(service.isPending()).toBe(outcome === 'failure');
+ service.clear();
+ },
+ );
+
it('settle 边界兑现 pending 重启并收口', async () => {
const restart = vi.fn(async () => {});
const { service } = createService({ restart });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
index 79ebbc4acb..d1524345f6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
@@ -5,12 +5,11 @@
* Issue 形态:全局 Codex 凭证/运行时变更被延期,已有会话里的后续消息进入
* 持久化输入队列,但延期重启兑现、报告"唤醒 N 个会话"之后,消息既没落
* `messages` 也没产生第二次派发 —— 静默滞留。此前 service 与 coordinator
- * 只各自有单元测试,唤醒链路(register 的 onApplied → wakeSession 接线、
- * hasPendingCredentialSwitch 的 isPending 联动)从未被串起来测过;drain 被
+ * 只各自有单元测试,唤醒链路与队列门从未被串起来测过;drain 被
* gate 挡住时也零日志,断点无从定位。
*
* 本文件用**真实的两个模块**接线(mock 只到 deps 边界),覆盖:
- * 1. 基线端到端:pending 门挡住 → 重启兑现(关旧 Session)→ wake → 恰好
+ * 1. 等待全局空闲不挡输入;实际重启 → 关旧 Session → wake → 恰好
* 派发一次、恰好落一条 user message、退出 snapshot;
* 2. 竞态排列 a:wake 在 ensureQueueRestored 仍在读取期间到达;
* 3. 竞态排列 b:close cleanup 吞掉已排程的 wake-drain(register 接线的
@@ -28,7 +27,7 @@ import type {
import { DeferredCodexRestartService } from '../deferredCodexRestart.js';
import { CodexCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch.js';
import {
- createDeferredRestartAppliedWake,
+ createDeferredRestartSettledWake,
createDeferredRestartQueueGate,
} from '../deferredRestartQueueWiring.js';
import type {
@@ -153,6 +152,7 @@ function createRestartHarness() {
let running = false;
let live = true;
let busyOtherSession = false;
+ let pendingCredentialSwitch = false;
const projections: AgentInputProjection[] = [];
let loadQueueSnapshot: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null = null;
@@ -174,9 +174,9 @@ function createRestartHarness() {
if (!await applyRuntime()) return;
await restartImpl();
},
- hasBusyLocalCodexSession: () => busyOtherSession,
+ hasBusyLocalCodexSession: () => busyOtherSession || running,
listLocalCodexSessionIds: () => live ? [SID] : [],
- onApplied: createDeferredRestartAppliedWake({
+ onQueueGateReleased: createDeferredRestartSettledWake({
wakeSession: (sessionId, reason) => coordinator.wakeSession(sessionId, reason),
}),
retryDelayMs: 60_000,
@@ -202,9 +202,8 @@ function createRestartHarness() {
getSdkSessionId: vi.fn(async () => 'sdk-session'),
hasAssistantProgressAfter: () => Promise.resolve(false),
hasPendingCredentialSwitch: createDeferredRestartQueueGate({
- hasPendingCredentialSwitchEntry: () => false,
- isDeferredRestartPending: () => service.isPending(),
- listActiveSessions: () => live ? [{ id: SID, agentKind: 'codex', remoteHostId: null }] : [],
+ hasPendingCredentialSwitchEntry: () => pendingCredentialSwitch,
+ isSessionRestarting: (sessionId) => service.isSessionRestarting(sessionId),
}),
emitProjection: (projection) => {
projections.push(projection);
@@ -222,6 +221,24 @@ function createRestartHarness() {
sendToAgent,
persistQueueSnapshot,
projections,
+ beginRestart() {
+ const hold = deferred<void>();
+ const previousRestart = restartImpl;
+ restartImpl = async () => {
+ await hold.promise;
+ await previousRestart();
+ };
+ service.schedule('memory-change');
+ const attempt = service.flushBeforeLocalCodexSessionStart();
+ return async () => {
+ hold.resolve();
+ await attempt;
+ await flush();
+ };
+ },
+ setPendingCredentialSwitch(value: boolean) {
+ pendingCredentialSwitch = value;
+ },
setRunning(value: boolean) {
running = value;
},
@@ -267,14 +284,59 @@ beforeEach(() => {
});
describe('deferred Codex restart × input queue drain (#2506)', () => {
- it('端到端:pending 门挡住的后续消息在重启兑现后恰好派发一次并落库', async () => {
+ it.each(['Codex Browser capability routing changed', 'memory-change', 'subagent-spawn-config-change'])(
+ 'dispatches an idle session follow-up while another session delays %s', async (reason) => {
+ const h = createRestartHarness();
+ await h.coordinator.ensureQueueRestored(h.SID);
+ h.setBusyOtherSession(true);
+ h.service.schedule(reason);
+ await h.service.flushBeforeLocalCodexSessionStart();
+
+ expect(h.coordinator.shouldQueueNewTurn(h.SID)).toBe(false);
+ h.coordinator.enqueue(h.SID, makeItem('idle-follow-up', 'continue the completed task'));
+ await flush();
+
+ expect(h.service.isPending()).toBe(true);
+ expect(h.sendToAgent).toHaveBeenCalledOnce();
+ expect(mocks.createMessage).toHaveBeenCalledOnce();
+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);
+
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(h.SID, 'done');
+ h.service.onSessionSettled();
+ h.coordinator.enqueue(h.SID, makeItem('next-follow-up', 'keep going'));
+ await flush();
+ expect(h.service.isPending()).toBe(true);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(mocks.createMessage).toHaveBeenCalledTimes(2);
+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);
+ h.service.clear();
+ },
+ );
+
+ it('still waits for this session credential switch after a global restart settles', async () => {
+ const h = createRestartHarness();
+ await h.coordinator.ensureQueueRestored(h.SID);
+ h.setPendingCredentialSwitch(true);
+ const finishRestart = h.beginRestart();
+ h.coordinator.enqueue(h.SID, makeItem('credential-follow-up', 'use the selected account'));
+ await finishRestart();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual(['credential-follow-up']);
+
+ h.setPendingCredentialSwitch(false);
+ h.coordinator.wakeSession(h.SID, 'credential-switch-applied');
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledOnce();
+ expect(mocks.createMessage).toHaveBeenCalledOnce();
+ });
+
+ it('端到端:实际重启期间的后续消息在收口后恰好派发一次并落库', async () => {
const h = createRestartHarness();
await h.coordinator.ensureQueueRestored(h.SID);
mocks.logger.debug.mockClear();
- // 另一会话忙 → 重启延期挂起;本会话上一轮已完成(running=false)。
- h.setBusyOtherSession(true);
- h.service.schedule('memory-change');
+ const finishRestart = h.beginRestart();
expect(h.service.isPending()).toBe(true);
// 用户在已有会话发后续消息:进入队列 + 写入 snapshot,但不落 messages、不派发。
@@ -283,15 +345,12 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
expect(h.sendToAgent).not.toHaveBeenCalled();
expect(mocks.createMessage).not.toHaveBeenCalled();
expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual(['m-1']);
- // 诊断:被 pending 门挡住的 drain 必须留痕(此前零日志 → 静默滞留)。
+ // 诊断:实际重启期间的 drain 必须留痕。
expect(
drainBlockedLogs().some((meta) => meta.gate === 'credential-switch-gate'),
).toBe(true);
- // 挡路会话结束 → 延期重启兑现:关旧 Session → 清 pending 门 → onApplied 唤醒。
- h.setBusyOtherSession(false);
- h.service.onSessionSettled();
- await flush();
+ await finishRestart();
expect(h.service.isPending()).toBe(false);
expect(h.sendToAgent).toHaveBeenCalledTimes(1);
@@ -310,29 +369,38 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
const h = createRestartHarness();
await h.coordinator.ensureQueueRestored(h.SID);
h.service.schedule('memory-change');
- h.coordinator.enqueue(h.SID, makeItem('retry-message', 'resume after retry'));
- await flush();
- expect(h.sendToAgent).not.toHaveBeenCalled();
+ const hold = deferred<void>();
let first = true;
h.setRestartImpl(async () => {
h.coordinator.onSessionClosed(h.SID);
h.setLive(false);
if (!first) return;
first = false;
+ await hold.promise;
if (failure === 'busy') throw new CodexCredentialModeSwitchBusyError([]);
if (failure === 'bridge-failure') throw new Error('bridge preparation failed');
h.service.schedule(failure, failure === 'new-runtime' ? async () => {} : undefined);
});
- await h.service.flushBeforeLocalCodexSessionStart();
- expect(h.service.isPending()).toBe(true);
- expect(h.service.listGatedSessionIds()).toEqual([h.SID]);
+ const attempt = h.service.flushBeforeLocalCodexSessionStart();
+ await flush();
+ // The old session is gone, but its bridge is still being replaced.
+ h.coordinator.enqueue(h.SID, makeItem('retry-message', 'resume after retry'));
+ await flush();
+ expect(h.service.isSessionRestarting(h.SID)).toBe(true);
expect(h.sendToAgent).not.toHaveBeenCalled();
- await h.service.flushBeforeLocalCodexSessionStart();
+ hold.resolve();
+ await attempt;
await flush();
- expect(h.service.isPending()).toBe(false);
+ expect(h.service.isPending()).toBe(true);
+ expect(h.service.listGatedSessionIds()).toEqual([h.SID]);
+ expect(h.service.isSessionRestarting(h.SID)).toBe(false);
+ // A failed or superseded refresh must not hold input until another retry.
expect(h.sendToAgent).toHaveBeenCalledOnce();
expect(mocks.createMessage).toHaveBeenCalledOnce();
expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);
+ h.setRunning(false);
+ await h.service.flushBeforeLocalCodexSessionStart();
+ expect(h.service.isPending()).toBe(false);
},
);
@@ -387,22 +455,21 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
const h = createRestartHarness();
await h.coordinator.ensureQueueRestored(h.SID);
- h.setBusyOtherSession(true);
- h.service.schedule('memory-change');
+ const finishRestart = h.beginRestart();
h.coordinator.enqueue(h.SID, makeItem('m-1', 'queued before close race'));
await flush();
expect(h.sendToAgent).not.toHaveBeenCalled();
// 门已清除(重启已兑现),但 wake 的 microtask 尚未执行时 close cleanup 到达:
// cancelScheduledDrain 会作废这次 wake —— 单靠这一次 wake 消息就永久滞留。
- h.setBusyOtherSession(false);
h.service.clear();
+ await finishRestart();
h.coordinator.wakeSession(h.SID, 'deferred-codex-restart-applied');
h.coordinator.onSessionClosed(h.SID);
await flush();
expect(h.sendToAgent).not.toHaveBeenCalled();
- // register 接线的正确性前提正在于此:onApplied 严格发生在 restart(全部
+ // register 接线的正确性前提正在于此:队列唤醒严格发生在 restart(全部
// close)之后,wake 不会落进 close 窗口。补一次 close 之后的 wake 即派发。
h.coordinator.wakeSession(h.SID, 'deferred-codex-restart-applied');
await flush();
@@ -414,15 +481,12 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
const h = createRestartHarness();
await h.coordinator.ensureQueueRestored(h.SID);
- h.setBusyOtherSession(true);
- h.service.schedule('memory-change');
+ const finishRestart = h.beginRestart();
h.coordinator.enqueue(h.SID, makeItem('m-1', 'exactly once'));
await flush();
// 重启兑现 → wake;紧跟两次冗余 wake(如另一来源的 superseded 唤醒)。
- h.setBusyOtherSession(false);
- h.service.onSessionSettled();
- await flush();
+ await finishRestart();
h.coordinator.wakeSession(h.SID, 'deferred-codex-restart-superseded');
h.coordinator.wakeSession(h.SID, 'deferred-codex-restart-applied');
await flush();
@@ -432,7 +496,7 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
// 用户清空队列后才到达的迟到 wake:无派发、无落库、无崩溃。
const h2 = createRestartHarness();
await h2.coordinator.ensureQueueRestored(h2.SID);
- h2.service.schedule('memory-change');
+ const finishSecondRestart = h2.beginRestart();
h2.coordinator.enqueue(h2.SID, makeItem('m-2', 'cleared before wake'));
await flush();
h2.coordinator.remove(h2.SID, 'm-2');
@@ -440,6 +504,8 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
h2.coordinator.wakeSession(h2.SID, 'deferred-codex-restart-applied');
await flush();
expect(h2.sendToAgent).not.toHaveBeenCalled();
+ await finishSecondRestart();
+ expect(h2.sendToAgent).not.toHaveBeenCalled();
});
});
@@ -455,20 +521,19 @@ describe('register.ts 真实接线经由共享工厂(源码断言,#2506)', () =>
expect(registerSource).toMatch(
/hasPendingCredentialSwitch:\s*createDeferredRestartQueueGate\(\{/,
);
- // 三个 dep 都在同一接线块里:凭证切换登记表、重启 pending、活跃会话来源。
+ // 凭证切换登记与实际重启范围分别检查;不能改回全局 pending 门。
const gateBlock = registerSource.slice(
registerSource.indexOf('hasPendingCredentialSwitch: createDeferredRestartQueueGate'),
);
const gateHead = gateBlock.slice(0, 600);
expect(gateHead).toContain('pendingCredentialSwitchHolder?.has(sessionId) === true');
- expect(gateHead).toContain('deferredCodexRestartHolder?.isPending() === true');
- expect(gateHead).toContain('maker.listActiveSessions()');
+ expect(gateHead).toContain('deferredCodexRestartHolder?.isSessionRestarting(sessionId) === true');
});
- it('DeferredCodexRestartService 的 onApplied 经由 createDeferredRestartAppliedWake', () => {
- expect(registerSource).toMatch(/onApplied:\s*createDeferredRestartAppliedWake\(\{/);
+ it('DeferredCodexRestartService releases the queue after every settled attempt', () => {
+ expect(registerSource).toMatch(/onQueueGateReleased:\s*createDeferredRestartSettledWake\(\{/);
const wakeBlock = registerSource.slice(
- registerSource.indexOf('onApplied: createDeferredRestartAppliedWake'),
+ registerSource.indexOf('onQueueGateReleased: createDeferredRestartSettledWake'),
);
expect(wakeBlock.slice(0, 300)).toContain('inputCoordinator.wakeSession(sessionId, reason)');
});
diff --git a/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts b/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
index 5eef44457b..f4db2b3b7e 100644
--- a/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
+++ b/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
@@ -15,12 +15,11 @@ import { isCredentialModeSwitchBusyError } from '../maker-host/codex-credential-
* turn done/error / 会话关闭(register.ts 接线)→ onSessionSettled:
* 仍有本地 Codex 会话在 turn 内 → 静默保留 pending,等下一个边界;
* 全部空闲 → restart 先持有全部本地 host 的启动守卫并软关闭会话,再在
- * 守卫内执行 applyRuntime、替换 bridge,最后 onApplied 唤醒被 pending 门
- * 挡住的输入队列。
- * 排队门:pending 期间本地 Codex live 会话的输入队列被 coordinator 的
- * hasPendingCredentialSwitch 谓词(register.ts 扩展)挡住 —— 否则排队消息
- * 会在旧 host 上接续开新 turn,重启被无限顺延(review P1 2026-07-23)。
- * 未 spawn 的会话不挡:fresh spawn 本来就读新设置。
+ * 守卫内执行 applyRuntime、替换 bridge,最后释放队列门并唤醒输入队列。
+ * 排队门只覆盖实际重启中的会话,包括刚软关闭的会话。等待其它任务空闲
+ * 期间不挡消息,否则一个长任务会冻结所有已打开任务的后续输入。
+ * 持续有任务运行时设置可以延后生效;不以冻结任务来强迫出现全局空闲。
+ * 重启失败也释放队列门,保留 pending 交给既有空闲边界与定时器重试。
* 自愈兜底:stop/interrupt 可能只发 status idle 不发 done/error,事件路径
* 不触发 —— 周期定时器重试,杜绝「事件丢失 → 永不生效」。
*
@@ -45,11 +44,13 @@ export interface DeferredCodexRestartDeps {
hasBusyLocalCodexSession: () => boolean;
/**
* 兑现前采集当前本地 Codex live 会话 id —— restart 会把它们全部关闭,收口后
- * 通过 onApplied 逐个唤醒(它们的输入队列此前被 pending 门挡着,漏唤 = 冻结)。
+ * 通过 onQueueGateReleased 逐个唤醒,包括重启失败前已关闭的会话。
*/
listLocalCodexSessionIds: () => string[];
- /** 兑现成功后回调:唤醒被 pending 门挡住的会话输入队列。 */
+ /** 兑现成功后回调。 */
onApplied?: (sessionIds: string[]) => void;
+ /** 实际重启尝试结束后释放输入,不把失败后的等待重试变成全局输入锁。 */
+ onQueueGateReleased?: (sessionIds: string[]) => void;
/** 自愈兜底重试间隔覆写(测试用)。 */
retryDelayMs?: number;
logger?: {
@@ -81,6 +82,10 @@ export class DeferredCodexRestartService {
return this.pending;
}
+ isSessionRestarting(sessionId: string): boolean {
+ return this.pending && this.applying && this.pendingSessionIds.has(sessionId);
+ }
+
/**
* 登记一次延迟重启;已有 pending 时合并(重启是全局动作,一次兑现覆盖所有
* 登记),applyRuntime 覆盖为最新(设置本身 last-write-wins)。
@@ -154,7 +159,7 @@ export class DeferredCodexRestartService {
}
/**
- * 当前被 pending 门挡住及此前重试已关闭的本地 Codex 会话名单。立即路径覆盖 pending
+ * 本次重启涉及及此前重试已关闭的本地 Codex 会话名单。立即路径覆盖 pending
* 登记时,调用方在 prepare 关会话**前**采集,clear 后逐个补唤醒 —— 门谓词变
* false 不会自己触发 drain,漏唤 = 队列停到下一次无关唤醒(review P1
* 2026-07-23)。无 pending 时为空;facade 暂不可读时保留已采集名单,owner clear 会清空。
@@ -174,12 +179,14 @@ export class DeferredCodexRestartService {
private async tryApply(): Promise<void> {
if (!this.pending || this.applying) return;
const gen = this.generation;
+ let wakeSessionIds: string[] = [];
this.applying = true;
try {
// deps 走 dynamic Maker facade,owner 边界期间会抛 —— 整段兜住,
// 靠兜底定时器(或边界时的 clear())收口,不产生 unhandled rejection。
if (this.deps.hasBusyLocalCodexSession()) return;
for (const id of this.deps.listLocalCodexSessionIds()) this.pendingSessionIds.add(id);
+ wakeSessionIds = [...this.pendingSessionIds];
await this.deps.restart(async () => {
if (gen !== this.generation) return false;
// Claim inside the startup guard: a runtime callback can close the
@@ -237,6 +244,18 @@ export class DeferredCodexRestartService {
}
} finally {
this.applying = false;
+ // Close cleanup may cancel an already scheduled drain. Wake only after
+ // the complete attempt settles, even when it failed or a newer setting
+ // remains pending. Never wake queues belonging to a previous owner.
+ if (gen === this.generation && wakeSessionIds.length > 0) {
+ try {
+ this.deps.onQueueGateReleased?.(wakeSessionIds);
+ } catch (err) {
+ this.deps.logger?.warn('deferred codex restart: queue wake failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
}
}
diff --git a/apps/desktop/src/main/maker-ipc/deferredRestartQueueWiring.ts b/apps/desktop/src/main/maker-ipc/deferredRestartQueueWiring.ts
index 4f4ba77cf0..26d3254307 100644
--- a/apps/desktop/src/main/maker-ipc/deferredRestartQueueWiring.ts
+++ b/apps/desktop/src/main/maker-ipc/deferredRestartQueueWiring.ts
@@ -8,46 +8,31 @@
* 本工厂接线。
*/
-/** onApplied 唤醒的 wake reason,coordinator 日志与测试断言共用同一常量。 */
-export const DEFERRED_RESTART_WAKE_REASON = 'deferred-codex-restart-applied';
-
-interface GateSessionShape {
- id: string;
- agentKind: string;
- remoteHostId?: string | null;
-}
+/** 重启尝试收口后的 wake reason,包括失败后释放输入队列。 */
+export const DEFERRED_RESTART_WAKE_REASON = 'deferred-codex-restart-settled';
/**
* coordinator 的 hasPendingCredentialSwitch 谓词:
* 1. 延迟凭证切换登记表里有该会话 → 挡;
- * 2. 延迟 Codex 重启 pending 期间,本地 Codex live 会话 → 挡 —— 否则排队消息
- * 在旧 host 上接续开新 turn,重启被无限顺延(review P1 2026-07-23)。未
- * spawn / 已关闭的会话不挡:fresh spawn 本来就读新设置。
- * maker 是 dynamic facade,owner 边界窗口 listActiveSessions 会抛 → 按不挡
- * 处理(边界会清 pending)。
+ * 2. 实际重启中的本地 Codex 会话 → 暂停派发,包括重启刚关闭的会话。
+ * 等待全局空闲的 pending 不阻塞输入。重启范围由 service 的关闭前快照确定,
+ * 不能从 live 列表推断,否则关闭到 bridge 替换完成之间会过早放行。
*/
export function createDeferredRestartQueueGate(deps: {
hasPendingCredentialSwitchEntry: (sessionId: string) => boolean;
- isDeferredRestartPending: () => boolean;
- listActiveSessions: () => GateSessionShape[];
+ isSessionRestarting: (sessionId: string) => boolean;
}): (sessionId: string) => boolean {
return (sessionId) => {
if (deps.hasPendingCredentialSwitchEntry(sessionId)) return true;
- if (!deps.isDeferredRestartPending()) return false;
- try {
- const session = deps.listActiveSessions().find((s) => s.id === sessionId);
- return !!session && session.agentKind === 'codex' && !session.remoteHostId;
- } catch {
- return false;
- }
+ return deps.isSessionRestarting(sessionId);
};
}
/**
- * DeferredCodexRestartService.onApplied 的接线:重启兑现后逐会话唤醒输入队列,
+ * DeferredCodexRestartService.onQueueGateReleased 的接线:尝试收口后逐会话唤醒输入队列,
* wake reason 固定为 DEFERRED_RESTART_WAKE_REASON。
*/
-export function createDeferredRestartAppliedWake(deps: {
+export function createDeferredRestartSettledWake(deps: {
wakeSession: (sessionId: string, reason: string) => void;
}): (sessionIds: string[]) => void {
return (sessionIds) => {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 78d47c0673..59313589dc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1028,7 +1028,7 @@ import {
type MemoryChangeParts,
} from './deferredCodexRestart.js';
import {
- createDeferredRestartAppliedWake,
+ createDeferredRestartSettledWake,
createDeferredRestartQueueGate,
} from './deferredRestartQueueWiring.js';
import {
@@ -14246,8 +14246,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
hasPendingCredentialSwitch: createDeferredRestartQueueGate({
hasPendingCredentialSwitchEntry: (sessionId) =>
pendingCredentialSwitchHolder?.has(sessionId) === true,
- isDeferredRestartPending: () => deferredCodexRestartHolder?.isPending() === true,
- listActiveSessions: () => maker.listActiveSessions(),
+ isSessionRestarting: (sessionId) =>
+ deferredCodexRestartHolder?.isSessionRestarting(sessionId) === true,
}),
emitProjection: (projection) => {
broadcastToAllWindows(MAKER_PUSH.INPUT_PROJECTION, projection);
@@ -14544,9 +14544,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
// Memory 设置变更撞上 Codex busy 时的延迟软重启登记(见 deferredCodexRestart.ts)。
- // 与 pendingCredentialSwitchService 共用 turn 结束 / 会话关闭边界接线;pending
- // 期间本地 Codex live 会话的排队派发被上方 coordinator 的 hasPendingCredentialSwitch
- // 谓词挡住,兑现后由 onApplied 逐个唤醒。
+ // 与 pendingCredentialSwitchService 共用 turn 结束 / 会话关闭边界接线。
+ // 等待其它任务空闲时不阻塞输入;只在实际重启期间挡住相关会话的派发,
+ // 成功或失败收口后均唤醒,避免全局设置变化冻结无关任务。
const deferredCodexRestartService = new DeferredCodexRestartService({
restart: (applyRuntime) => restartCodexAfterAuthModeChange(async () => {
if (await applyRuntime() === false) return false;
@@ -14566,7 +14566,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.listActiveSessions()
.filter((session) => session.agentKind === 'codex' && !session.remoteHostId)
.map((session) => session.id),
- onApplied: createDeferredRestartAppliedWake({
+ onQueueGateReleased: createDeferredRestartSettledWake({
wakeSession: (sessionId, reason) => inputCoordinator.wakeSession(sessionId, reason),
}),
logger: log,