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(scheduler): 重启后先恢复排队快照再判断会话是否忙碌

liugaoweib6c5c9fd228f
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 1b2d749226..925dba7651 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -16418,6 +16418,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
isSessionTurnDispatchBoundaryBusy(sessionTurnActivityTracker, sessionId, sess)
);
},
+ ensureQueueRestored: async (sessionId) => {
+ await inputCoordinator.ensureQueueRestored(sessionId).catch(() => undefined);
+ return inputCoordinator.isQueueRestored(sessionId);
+ },
hasQueuedPrompt: (sessionId, scheduleId) =>
inputCoordinator.hasQueuedItemWhere(
sessionId,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index 99a3aa04e7..d69a00c539 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -1506,6 +1506,97 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(mocks.setSessionProvider).not.toHaveBeenCalled();
});
+ it('指定模型时先恢复排队快照,重启后的假忙不再空转顺延', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const setFastMode = vi.fn(async () => {});
+ Object.assign(h.session, { agentKind: 'codex', model: 'shared-model', setFastMode });
+ mocks.getSessionProvider.mockReturnValue('selected');
+ let restored = false;
+ const queue = createQueueHarness({ busy: true });
+ queue.deps.isSessionBusy = () => !restored;
+ queue.deps.ensureQueueRestored = vi.fn(async () => {
+ restored = true;
+ return true;
+ });
+ const { runner } = createRunnerHarness(h.session, queue.deps, {
+ metaModel: 'shared-model',
+ acquirePendingAgentSwitch: async () => ({
+ release: vi.fn(),
+ selection: {
+ agentKind: 'codex',
+ model: 'shared-model',
+ providerId: 'selected',
+ effort: 'high',
+ fastMode: false,
+ },
+ }),
+ });
+
+ const fire = runner.fire(
+ heartbeatSchedule({
+ agentKind: 'codex',
+ modelAgentKind: 'codex',
+ model: 'shared-model',
+ }),
+ createFireContext(),
+ );
+
+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
+ expect(queue.deps.ensureQueueRestored).toHaveBeenCalledWith(SESSION_ID);
+ await queue.accept();
+ await vi.waitFor(() => expect(h.listenerCount()).toBe(1));
+ h.emit({ type: 'done', data: {}, source: 'pi' });
+ await expect(fire).resolves.toMatchObject({ sessionId: SESSION_ID });
+ });
+
+ it('排队快照恢复失败时顺延,不把未恢复误记成会话正忙后空转', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ queue.deps.ensureQueueRestored = vi.fn(async () => false);
+ const { runner, notifier } = createRunnerHarness(h.session, queue.deps, {
+ acquirePendingAgentSwitch: async () => {
+ throw new Error('should not switch before restore');
+ },
+ });
+
+ const result = await runner.fire(
+ heartbeatSchedule({
+ agentKind: 'codex',
+ modelAgentKind: 'codex',
+ model: 'shared-model',
+ }),
+ createFireContext(),
+ );
+
+ expect(result).toMatchObject({ sessionId: SESSION_ID, deferred: true });
+ expect(queue.enqueueCalls).toHaveLength(0);
+ expect(notifier.notify).not.toHaveBeenCalled();
+ expect(queue.deps.ensureQueueRestored).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('恢复后会话仍在跑时,指定模型的心跳继续顺延且不入队', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ queue.deps.ensureQueueRestored = vi.fn(async () => true);
+ const { runner } = createRunnerHarness(h.session, queue.deps, {
+ acquirePendingAgentSwitch: async () => {
+ throw new Error('should not switch while the session is still busy');
+ },
+ });
+
+ const result = await runner.fire(
+ heartbeatSchedule({
+ agentKind: 'codex',
+ modelAgentKind: 'codex',
+ model: 'shared-model',
+ }),
+ createFireContext(),
+ );
+
+ expect(result).toMatchObject({ sessionId: SESSION_ID, deferred: true });
+ expect(queue.enqueueCalls).toHaveLength(0);
+ });
+
it('busy 心跳跨 dynamic identity 时不入旧 thread 队列,而是顺延到安全重建点', async () => {
const [routeA, routeB] = queuedImageGenerationRoutes;
setCodexAppliedCustomProviderRoutes(queuedImageGenerationRoutes);
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 6b12732f5e..411370b5df 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -221,6 +221,12 @@ function defaultPermissionModeForSchedule(): PermissionMode {
export interface SchedulerQueueDeps {
/** 目标会话当前是否忙(turn 运行中 / 队列有积压 / 凭证切换等待中)。 */
isSessionBusy(sessionId: string): boolean;
+ /**
+ * 重启后内存还没有读回排队快照时,shouldQueueNewTurn 会把它当成忙。
+ * 指定模型的任务会因此直接顺延,永远走不到入队时的恢复。
+ * 返回 false 表示这次没恢复成功,调用方按 queue-restore-pending 顺延。
+ */
+ ensureQueueRestored?(sessionId: string): Promise<boolean>;
/** 该 schedule 是否已有排队中(或正在派发)的心跳消息 —— 防重复入队。 */
hasQueuedPrompt(sessionId: string, scheduleId: string): boolean;
enqueuePrompt(req: {
@@ -553,6 +559,43 @@ export class MakerScheduleRunner implements ScheduleRunner {
return routinePermissionSnapshot(live ?? this.deps.maker.getSession(sessionId), stored);
}
+ /**
+ * 绑定会话在判断忙闲前先恢复排队快照。未恢复会被 shouldQueueNewTurn
+ * 当成忙;指定了模型的任务又会在入队前直接顺延,于是重启后永远空转。
+ * 恢复失败返回顺延结果;没有桥或已恢复则返回 undefined,继续原路径。
+ */
+ private async restoreBoundQueue(
+ schedule: Schedule,
+ ctx: FireContext,
+ sessionId: string,
+ ): Promise<FireResult | undefined> {
+ const restore = this.deps.schedulerQueue?.ensureQueueRestored;
+ if (!restore) return undefined;
+ throwIfFireAborted(ctx.signal, 'queue snapshot restore');
+ let restored = false;
+ try {
+ restored = await restore(sessionId);
+ } catch (err) {
+ this.deps.logger.warn?.('[runner] queue snapshot restore failed', {
+ scheduleId: schedule.id,
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ restored = false;
+ }
+ throwIfFireAborted(ctx.signal, 'queue snapshot restore');
+ if (restored) return undefined;
+ if (this.canDefer(schedule, ctx)) {
+ return this.deferFire(schedule, sessionId, 'queue-restore-pending');
+ }
+ const errMsg = formatSchedulerSendError(
+ buildSchedulerSendContext(schedule, ctx, sessionId),
+ 'QUEUE_RESTORE_PENDING',
+ );
+ await this.notifyFailureSilent(schedule, ctx, errMsg);
+ throw new Error(errMsg);
+ }
+
private async failOrDeferSessionRunning(
schedule: Schedule,
ctx: FireContext,
@@ -780,6 +823,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 直发路径不经过 makerSendTransaction。先落实 pending switch,再读取 meta/row,
// 才能让本轮 createSession 与 send 都指向切换后的 live engine。
throwIfFireAborted(ctx.signal, 'credential switch setup');
+ const restorePending = await this.restoreBoundQueue(schedule, ctx, sessionId);
+ if (restorePending) return restorePending;
const selection: ScheduledModelSelection | undefined =
schedule.modelAgentKind && schedule.model?.trim()
? {