Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(scheduler): cancel pre-dispatch routine sends without aborting the session
马建彤0ded4535666d
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.tsindex 9b5f3e1000..205f5dd285 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts@@ -70,6 +70,7 @@ type SendImpl = (interface FakeSessionHarness {session: Session;+ cancelPendingSend: ReturnType<typeof vi.fn>;emit(event: AgentEvent): void;emitStatus(status: 'active' | 'aborting' | 'closed' | 'error'): void;setContinuationState(@@ -92,6 +93,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {number,'awaiting' | 'active' | 'cancelled'>();+ const cancelPendingSend = vi.fn(() => false);const session = {id: 'scheduler-session',agentKind: 'claude-code',@@ -126,11 +128,13 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {});},abort: vi.fn(async () => undefined),+ cancelPendingSend,close: vi.fn(async () => undefined),} as unknown as Session;return {session,+ cancelPendingSend,emit(event: AgentEvent) {for (const listener of [...listeners]) listener(event);},@@ -300,7 +304,6 @@ describe('MakerScheduleRunner background subagent task tracking', () => {const { runner, maker, notifier } = createRunnerHarness(h.session, {beforeDispatchUserTurn: async () => { valid = false; },});- vi.mocked(h.session.abort).mockImplementation(() => new Promise(() => undefined));vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', workDir: '/repo/project' } as never);mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'ask', planModeEnabled: true });const result = await runner.fire(baseSchedule({ source: 'bot', targetSessionId: 'bot-session' }), {@@ -308,10 +311,37 @@ describe('MakerScheduleRunner background subagent task tracking', () => {});expect(result).toMatchObject({ deferred: true });expect(vendor).not.toHaveBeenCalled();- expect(h.session.abort).toHaveBeenCalledOnce();+ expect(h.session.abort).not.toHaveBeenCalled();expect(notifier.notify).not.toHaveBeenCalled();});+ it('pause/delete during direct onAccepted cancels the pending send without aborting the session', async () => {+ const h = createSessionHarness(async (_message, opts) => {+ await opts?.onAccepted?.();+ return { accepted: true };+ });+ h.cancelPendingSend.mockReturnValue(true);+ Object.assign(h.session, { stablePermissionModeState: { mode: 'ask', generation: 0 } });+ const abortController = new AbortController();+ const ctx = { ...createFireContext(), signal: abortController.signal };+ const beforeDispatch = vi.fn(async () => { abortController.abort(); });+ const { runner, maker } = createRunnerHarness(h.session, {+ beforeDispatchUserTurn: beforeDispatch,+ });+ vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', workDir: '/repo/project' } as never);+ mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'ask', planModeEnabled: true });++ const fire = runner.fire(baseSchedule({ source: 'bot', targetSessionId: 'bot-session' }), {+ ...ctx,+ deferToCaller: true,+ }).catch((error: unknown) => error);++ await vi.waitFor(() => expect(beforeDispatch).toHaveBeenCalled());+ await vi.waitFor(() => expect(h.cancelPendingSend).toHaveBeenCalled());+ expect(h.session.abort).not.toHaveBeenCalled();+ expect(await fire).toBeInstanceOf(Error);+ });+it.each(['before create', 'before send'])('rechecks routine permission changes %s after async preparation', async (stage) => {const h = createSessionHarness(acceptingSend());Object.assign(h.session, { stablePermissionModeState: { mode: 'bypassPermissions', generation: 0 } });diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex e4694786e5..856a2cc9c2 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -176,6 +176,7 @@ interface FakeSessionHarness {setModel: ReturnType<typeof vi.fn>;setEffort: ReturnType<typeof vi.fn>;setVendorOptions: ReturnType<typeof vi.fn>;+ cancelPendingSend: ReturnType<typeof vi.fn>;vendorOptions: Record<string, unknown>;emit(event: AgentEvent): void;emitStatus(status: SessionStatus): void;@@ -195,6 +196,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {const setVendorOptions = vi.fn(async (patch: Record<string, unknown>) => {Object.assign(vendorOptions, patch);});+ const cancelPendingSend = vi.fn(() => true);const session = {id: SESSION_ID,agentKind: 'claude-code',@@ -221,6 +223,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {},stablePermissionModeState: { mode: 'ask', generation: 0 },stablePlanModeState: { enabled: false, generation: 0 },+ cancelPendingSend,abort: vi.fn(async () => undefined),close: vi.fn(async () => undefined),} as unknown as Session;@@ -231,6 +234,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {setModel,setEffort,setVendorOptions,+ cancelPendingSend,vendorOptions,emit(event: AgentEvent) {// 生产 Session 会给当前 schedule turn 的每个事件补 turnOrigin;fake 默认@@ -311,8 +315,11 @@ interface QueueHarness {enqueueCalls: Array<Parameters<SchedulerQueueDeps['enqueuePrompt']>[0]>;removeCalls: Array<{ sessionId: string; clientId: string }>;cancelAutoResumeCalls: Array<{ sessionId: string; runId: string }>;- /** 模拟 drain 派发:触发最近一次入队项的 onAccepted。 */+ /** 模拟 drain 派发:触发最近一次入队项的 onAccepted。取消异常按生产 coordinator 的+ * 回滚分支吞掉(见 acceptedCallbackRunner),让用例继续观察 run 结局。 */accept(permissions?: { permissionMode?: string; planMode?: boolean }): Promise<void>;+ /** 同上但不吞 AcceptedCallbackDispatchCancelled,供取消语义的回归用例断言。 */+ acceptRaw(permissions?: { permissionMode?: string; planMode?: boolean }): Promise<void>;/** 模拟排队项被丢弃(用户删除 / abort 撤项)。 */discard(): void;/** 模拟普通自动续跑最终仍失败。 */@@ -383,6 +390,13 @@ function createQueueHarness(opts: {},},async accept(permissions = { permissionMode: 'ask', planMode: false }) {+ try {+ await this.acceptRaw(permissions);+ } catch (error) {+ if (!(error instanceof AcceptedCallbackDispatchCancelled)) throw error;+ }+ },+ async acceptRaw(permissions = { permissionMode: 'ask', planMode: false }) {const request = enqueueCalls.at(-1);try { await request?.onPreparing?.(); }catch (error) { request?.onPreparationFailed?.(error); return; }@@ -777,15 +791,17 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {Object.assign(changed.session, selection, { agentDeviceId: nextDevice,setFastMode: vi.fn(async () => {}), setEffort: vi.fn(async () => {}) });replaceLiveSession(changed.session);- if (boundary === 'accepted') await request.onAccepted({ permissionMode: 'ask', planMode: false });- else await queue.accept();+ if (boundary === 'accepted') {+ await expect(request.onAccepted({ permissionMode: 'ask', planMode: false }))+ .rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ } else await queue.accept();// Let an incorrectly accepted send finish so the assertion reports success// vs failure instead of merely timing out on the pre-fix implementation.changed.emit({ type: 'done', data: {}, source: agentKind });expect(await result).toBeInstanceOf(Error);expect(String(await result)).toContain('Scheduled model route changed');expect(changed.setModel).not.toHaveBeenCalled();- if (boundary === 'accepted') expect(changed.session.abort).toHaveBeenCalledTimes(1);+ if (boundary === 'accepted') expect(changed.session.abort).not.toHaveBeenCalled();});it.each(['harness-changed', 'effort-failed', 'fast-failed'] as const)(@@ -828,8 +844,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await queue.accept();expect(await result).toBeInstanceOf(Error);expect(h.send).not.toHaveBeenCalled();- if (failure === 'harness-changed') expect(h.session.abort).not.toHaveBeenCalled();- else expect(h.session.abort).toHaveBeenCalled();+ expect(h.session.abort).not.toHaveBeenCalled();},);@@ -874,7 +889,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {}await queue.accept(queuedPermissions);expect(await fire).toMatchObject({ deferred: true });- expect(acceptedSession.session.abort).toHaveBeenCalledOnce();+ expect(acceptedSession.session.abort).not.toHaveBeenCalled();expect(ctx.onTurnActive).not.toHaveBeenCalled();expect(f.notifier.notify).not.toHaveBeenCalled();expect(acceptedSession.listenerCount()).toBe(0);@@ -910,14 +925,14 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const fire = runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), ctx);await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));vi.mocked(maker.getSession).mockReturnValue(undefined);- await expect(queue.accept()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);expect(await fire).toMatchObject({ deferred: true });expect(ctx.onTurnActive).not.toHaveBeenCalled();expect(notifier.notify).not.toHaveBeenCalled();expect(h.listenerCount()).toBe(0);});- it('cancels an edited routine revision at queued acceptance before marking the turn active', async () => {+ it('cancels an edited routine revision at queued acceptance without aborting the session', async () => {const h = createSessionHarness(async () => ({ accepted: true }));const queue = createQueueHarness({ busy: true });const f = createRunnerHarness(h.session, queue.deps);@@ -926,9 +941,9 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const fire = f.runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), ctx);await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));valid = false;- await queue.accept();+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);expect(await fire).toMatchObject({ deferred: true });- expect(h.session.abort).toHaveBeenCalledOnce();+ expect(h.session.abort).not.toHaveBeenCalled();expect(ctx.onTurnActive).not.toHaveBeenCalled();expect(f.notifier.notify).not.toHaveBeenCalled();});@@ -1456,6 +1471,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await Promise.resolve();original.emitStatus('closed');replaceLiveSession(replacement.session);+ replacement.cancelPendingSend.mockReturnValue(false);expect(replacement.listenerCount()).toBe(1);ctx.abortController.abort();@@ -1667,7 +1683,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await queue.accept();await fireRejected;- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.setModel).not.toHaveBeenCalled();expect(harness.setEffort).not.toHaveBeenCalled();expect(mocks.setSessionProvider).not.toHaveBeenCalled();@@ -1710,7 +1726,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {expect(requiresModelSwitchRebuild).toHaveBeenCalledWith('gpt-5.6-sol', {providerId: 'mygpt',});- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.setModel).not.toHaveBeenCalled();expect(harness.setEffort).not.toHaveBeenCalled();expect(mocks.setSessionProvider).not.toHaveBeenCalled();@@ -1759,7 +1775,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {providerId: 'mygpt',});expect(harness.setModel).toHaveBeenCalledWith('gpt-5.6-sol');- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.setEffort).not.toHaveBeenCalled();expect(mocks.setSessionProvider).not.toHaveBeenCalled();});@@ -1926,7 +1942,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await queue.accept();await rejected;- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.setModel).not.toHaveBeenCalled();expect(harness.send).not.toHaveBeenCalled();});@@ -2000,7 +2016,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));(maker.getSession as ReturnType<typeof vi.fn>).mockReturnValue(undefined);- await expect(queue.accept()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);await fireRejected;expect(harness.setModel).not.toHaveBeenCalled();expect(mocks.setSessionFastMode).not.toHaveBeenCalled();@@ -2125,10 +2141,10 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {expect(harness.send).not.toHaveBeenCalled();});- it('aborts the late-dispatched turn when accept lands after schedule pause/delete', async () => {- // abort 撞上"项已转 activeTurn、尚未 accept"的窗口:removeQueuedPrompt 是- // no-op,coordinator 仍会把 turn 发出去 —— accept 时刻必须补杀刚起步的 turn,- // 不让已暂停/删除的任务继续执行(review P2)。+ it('cancels the late accepted dispatch after schedule pause/delete without aborting the session', async () => {+ // pause/delete 撞上"项已转 activeTurn、尚未 accept"的窗口时,removeQueuedPrompt 是+ // no-op,coordinator 仍可能调用 onAccepted —— 此时抛取消信号,本轮在 vendor dispatch+ // 前收口,不需要也不应该用 Session.abort() 关闭用户会话(review P2 / #6931)。const harness = createSessionHarness(async () => ({ accepted: true }));const queue = createQueueHarness({ busy: true, removeTriggersDiscard: false });const { runner, maker } = createRunnerHarness(harness.session, queue.deps);@@ -2139,12 +2155,12 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {ctx.abortController.abort();await expect(firePromise).rejects.toThrow(/abort/i);- // coordinator 稍后仍完成了派发(accept 晚到)→ 刚起步的 turn 被立即中断。- await queue.accept();+ // coordinator 稍后仍调用了 onAccepted(晚到)→ 取消这次派发,但不 abort 会话。+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);expect((maker as unknown as { getSession: () => Session }).getSession).toBeDefined();expect((harness.session as unknown as { abort: ReturnType<typeof vi.fn> }).abort,- ).toHaveBeenCalled();+ ).not.toHaveBeenCalled();// 不再挂 turn 监听(run 已收口)。expect(harness.listenerCount()).toBe(0);expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);@@ -2640,7 +2656,7 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()// 被拒后必须补一次 reclaimSlot=false 复位记账,否则引擎侧永远算它「不占槽」expect(ends).toEqual([true, false]);// turn 在 vendor dispatch 之前就被掐掉- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();});it('排队超时后迟到的 onAccepted 被补杀,不产生未跟踪的执行', async () => {@@ -2661,7 +2677,7 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()// 超时之后 coordinator 才 drain 到它await queue.accept();- expect(harness.session.abort).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();// 迟到派发不得真的发出 promptexpect(harness.send).not.toHaveBeenCalled();} finally {@@ -2704,36 +2720,58 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()}});- it('abort 撞在 onAccepted 执行期间:等待门自己收口,run 不永久挂 running', async () => {- // onAccepted 第一行就把 dispatched 置 true。abort 若在此之后到达:- // - onAbort 走"中断 live turn"分支,不 failDispatch;- // - trackPoll 见 dispatched 直接早退,也不 failDispatch。- // 两边都不收口 → dispatchGate 永不 settle → run 一直挂 running 到卡死守卫兜底- // (review #944 第十七轮 P1)。取消分支必须自己 failDispatch。+ it('pause/delete during onAccepted cancels the pending send without aborting the session', async () => {+ // onAccepted 第一行就把 dispatched 置 true;pause/delete 若在之后的+ // bind/routing/权限快照 await 中到达,onAbort 必须只取消 send reservation,+ // 不能走整会话 abort。这里让第一次权限快照读取(onAccepted 内部)触发 abort,+ // 精确复刻该窗口,而不是在进入 fireHeartbeatViaQueue 之前就 abort。const harness = createSessionHarness(async () => ({ accepted: true }));const queue = createQueueHarness({ busy: true, removeTriggersDiscard: false });- const { runner, maker } = createRunnerHarness(harness.session, queue.deps);+ const { runner } = createRunnerHarness(harness.session, queue.deps);const ctx = createFireContext();- // getSession 在 dispatched=true 之后、ctx.signal.aborted 复核之前被调用 ——- // 借它精确复刻"abort 撞在回调执行期间"这个窗口。- (maker.getSession as ReturnType<typeof vi.fn>).mockImplementation(() => {- ctx.abortController.abort();- return harness.session;- });const firePromise = runner.fire(heartbeatSchedule(), ctx);- // 这条拒绝会在 queue.accept() 内同步触发。先登记消费方,避免测试自己把+ // 这条拒绝会在 queue.acceptRaw() 内同步触发。先登记消费方,避免测试自己把// 预期错误留到下一拍才观察,造成 PromiseRejectionHandledWarning。const fireRejected = expect(firePromise).rejects.toThrow(/abort/i);await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));- await queue.accept();++ let snapshotCalls = 0;+ mocks.getSessionFsSnapshot.mockImplementation(async () => {+ snapshotCalls += 1;+ if (snapshotCalls === 1) ctx.abortController.abort();+ return { permissionMode: 'ask', planModeEnabled: false };+ });++ await queue.acceptRaw();// 修复前这里永不 settle(fire 挂死);修复后以"用户中断"收口await fireRejected;- expect(harness.session.abort).toHaveBeenCalledTimes(1);+ expect(snapshotCalls).toBeGreaterThan(0);+ expect(harness.cancelPendingSend).toHaveBeenCalled();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.send).not.toHaveBeenCalled();});+ it('pause/delete after vendor dispatch still aborts the running turn', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ harness.cancelPendingSend.mockReturnValue(false);+ const queue = createQueueHarness({ busy: true });+ const { runner } = createRunnerHarness(harness.session, queue.deps);+ const ctx = createFireContext();++ const firePromise = runner.fire(heartbeatSchedule(), ctx);+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ const fireRejected = expect(firePromise).rejects.toThrow(/abort/i);+ await queue.accept();+ await vi.waitFor(() => expect(harness.listenerCount()).toBe(1));++ ctx.abortController.abort();+ await fireRejected;+ expect(harness.cancelPendingSend).toHaveBeenCalled();+ expect(harness.session.abort).toHaveBeenCalledOnce();+ });+it('排队期间系统挂起:睡着的时间不计入等待额度', async () => {// 排队上限用壁钟量"等了多久",而机器睡觉时定时器不跑、壁钟照走:睡够 30 分钟醒来// 第一拍就会撤掉一条完全健康的排队 prompt(review #944 第十六轮 P1)。@@ -2835,10 +2873,11 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()}});- it('排队超时后迟到的 accept:有 live 会话时取消这次派发(不抛错)', async () => {- // 阻断手段是 live.abort() 同步取消 Session.send 的 send reservation —— 这个回调正- // 运行在 Session.send 的 onAccepted 链里,返回后 send 会以 cancelled-before-dispatch- // 收场,coordinator 干净回滚。所以有 live 时不需要抛错(抛错那条路不置空 activeTurn)。+ it('排队超时后迟到的 accept:有 live 会话时取消这次派发且不 abort 会话', async () => {+ // 取消通道是 AcceptedCallbackDispatchCancelled:它运行在 Session.send 的 onAccepted+ // 链里,被 runAcceptedCallback 原样上抛,send 在 vendor dispatch 前收场,coordinator+ // 干净回滚。Session.abort() 会走用户 Stop 的整会话中断链,不能用来撤销单次派发+ // (#6931)。vi.useFakeTimers();try {const harness = createSessionHarness(async () => ({ accepted: true }));@@ -2853,9 +2892,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ());await settled;- // 迟到的 accept 不抛(coordinator 靠 reservation 取消回滚),但必须取消这次派发- await expect(queue.accept()).resolves.toBeUndefined();- expect(harness.session.abort).toHaveBeenCalled();+ // 迟到的 accept 通过取消信号回滚,但不得关闭用户会话+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ expect(harness.session.abort).not.toHaveBeenCalled();} finally {vi.useRealTimers();}@@ -2883,8 +2922,8 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()(maker.getSession as ReturnType<typeof vi.fn>).mockReturnValue(undefined);// 必须是 AcceptedCallbackDispatchCancelled:普通 Error 会被 runAcceptedCallback// 当成副作用失败吞掉,turn 照样发出去(review #944 第十一轮 P1)。- await expect(queue.accept()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);- await expect(queue.accept()).rejects.toThrow(/SEND_CANCELLED_BEFORE_DISPATCH/);+ await expect(queue.acceptRaw()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ await expect(queue.acceptRaw()).rejects.toThrow(/SEND_CANCELLED_BEFORE_DISPATCH/);} finally {vi.useRealTimers();}@@ -3084,7 +3123,7 @@ describe('queued heartbeat for a Bot Session task (persisted Auto)', () => {errorMsg: fourth.error?.message,});// 每次都在 vendor dispatch 前取消,从未真正执行。- expect(harness.session.abort).toHaveBeenCalledTimes(4);+ expect(harness.session.abort).not.toHaveBeenCalled();expect(harness.listenerCount()).toBe(0);expect(runtimeMode(runtime)).toBe('bypassPermissions');});@@ -3326,7 +3365,7 @@ describe('queued heartbeat for a Bot Session task (persisted Auto)', () => {await queue.accept(queuedFromRow);expect(await fire).toMatchObject({ sessionId: SESSION_ID, deferred: true });- expect(harness.session.abort).toHaveBeenCalledOnce();+ expect(harness.session.abort).not.toHaveBeenCalled();expect(ctx.onTurnActive).not.toHaveBeenCalled();expect(f.notifier.notify).not.toHaveBeenCalled();expect(harness.listenerCount()).toBe(0);diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex f5cbd1c054..ad093549e7 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -400,7 +400,14 @@ class QueuedDispatchTimeoutError extends Error {}*/class QueuedSlotUnavailableError extends Error {}-class RoutineDispatchDeferredError extends Error {}+/**+ * A routine occurrence that must not be dispatched. It is also an+ * AcceptedCallbackDispatchCancelled so the accepted-callback bridge rethrows it+ * instead of swallowing it as a side-effect failure, while the runner's existing+ * `instanceof RoutineDispatchDeferredError` branches keep the deferral/rewind+ * semantics.+ */+class RoutineDispatchDeferredError extends AcceptedCallbackDispatchCancelled {}/*** 落库权限 / Plan 与运行中的会话都可读且稳定,但两者不同。权限切换在途时会话读不到稳定@@ -1910,7 +1917,18 @@ export class MakerScheduleRunner implements ScheduleRunner {// 4.5.4 只有直发降级路径需要把取消映射到 session.abort()。生产队列路径由// coordinator 按「仍在排队 / 已派发」分别撤项或中断,不能让这个监听器误杀// 异步入队期间刚好开始的用户 turn。+ //+ // 发送尚未越过 vendor 边界时只取消这次 send reservation;只有 send 已开始且+ // 没有可取消的预约(已接受 / 正在中断)时才 abort 整个会话。否则 pause/delete+ // 落在 onAccepted 的 await 里会调用整会话 abort,触发 15s 恢复复核并可能关闭+ // 用户会话(#6931)。+ // Whether the vendor send call has started. A pause/delete that lands before+ // this point should only cancel the pending reservation (if any), never abort+ // the whole session.+ let sendStarted = false;const onAbort = (): void => {+ if (session.cancelPendingSend?.()) return;+ if (!sendStarted) return;this.deps.logger.info?.(`[runner] ctx.signal aborted, calling session.abort() for ${session.id}`,);@@ -2049,6 +2067,7 @@ export class MakerScheduleRunner implements ScheduleRunner {ctx.signal.removeEventListener('abort', onAbort);return this.deferFire(schedule, session.id, 'routine-dispatch-invalidated');}+ sendStarted = true;const sendResult = await session.send(outgoingMessage as never, {origin,...(isHeartbeat || schedule.source === 'bot' || agentDeviceId@@ -2145,11 +2164,14 @@ export class MakerScheduleRunner implements ScheduleRunner {baselineStarted = true;}if (ctx.canDispatch && !ctx.canDispatch()) {- // abort synchronously cancels the send reservation; do not wait for- // a potentially stalled provider interrupt before deferring the run.- void session.abort().catch((err) => {- this.deps.logger.warn?.('[runner] obsolete routine turn abort failed', err);- });+ // Throw before Session.send reaches its vendor-dispatch boundary. The+ // deferral error is itself an AcceptedCallbackDispatchCancelled, so the+ // direct Session.send path and any accepted-callback wrapper both cancel+ // instead of swallowing it. The runner's catch turns it into a deferral+ // and rewinds the persisted scheduler row below. Do not abort the Session+ // here: abort is user-Stop semantics for the whole conversation (it arms+ // the abort-recovery watchdog and sends a provider interrupt), not a way+ // to cancel this one pre-dispatch send.throw new RoutineDispatchDeferredError('Routine revision changed before dispatch');}// 保留 scheduler 的既有 userSendAt 写入;该入口同时推进列表 lastActivityAt。@@ -2521,31 +2543,28 @@ export class MakerScheduleRunner implements ScheduleRunner {/*** onAccepted 里"本轮绝不能真的跑起来"的统一阻断出口。*- * 阻断手段是 `live.abort()`,但它拦的**不是"已经在跑的 turn"** —— 此刻 vendor 还没- * 派发。这个回调运行在 `Session.send` 的 onAccepted 链里(register.ts 把- * persistUserMessage 装在那儿,coordinator 的 onPersisted 又挂在它下面),而- * `Session.abort()` 的第一件事就是同步 `cancelSendReservation`:回调返回后 send 立刻- * 复核 `reservation.cancelled`,以 cancelled-before-dispatch 收场,coordinator 走- * handleSendNotDispatched 干净回滚(activeTurn 置空)。所以它取消的是**这次派发本身**。+ * 这个回调运行在 `Session.send` 的 onAccepted 链里(register.ts 把+ * persistUserMessage 装在那儿,coordinator 的 onPersisted 又挂在它下面),此刻+ * vendor 还没派发。它需要的只是取消**这次派发本身**,不是中断整个会话。+ *+ * 取消通道必须是 `AcceptedCallbackDispatchCancelled`:accepted 回调的普通异常被+ * runAcceptedCallback 刻意吞掉(副作用失败不该毁掉已受理的 turn),普通 Error+ * 根本到不了 coordinator,turn 照样会发出去(review #944 第十一轮 P1)。这条通道+ * 会被原样上抛,coordinator 走 persisted 分支回滚 —— 对 scheduler 项会放掉+ * activeTurn 并唤醒队列(第十轮,见 agent-input-coordinator 的回归用例)。*- * 拿不到 live 时没有这个手段:正常返回就等于放行,coordinator 紧接着把 turn 交给- * vendor,产生一次没人跟踪、还可能与顺延重试重叠的执行(review #944 第八轮 P1)。- * 此时抛 AcceptedCallbackDispatchCancelled —— **必须是这个类**:accepted 回调的普通- * 异常被 runAcceptedCallback 刻意吞掉(副作用失败不该毁掉已受理的 turn),第八轮我抛- * 的普通 Error 因此根本没到 coordinator,turn 照样发了出去(review #944 第十一轮 P1)。- * 这条通道会被原样上抛,coordinator 走 persisted 分支回滚;那条分支对 scheduler 项- * 已经会放掉 activeTurn 并唤醒队列(第十轮)。+ * 不要在这里调用 `Session.abort()`。它是用户按 Stop 的整会话操作:会置+ * `aborting`、向 vendor 发 interrupt,并启动 MANUAL_ABORT_RECOVERY_GRACE_MS+ * (15s)的兜底复核。后台例行任务只需要撤销自己的发送预约;借用 abort 会把+ * 用户正在使用的会话拖进中断链,而 Pi 的 abort RPC 超时是 30s —— 15s 复核+ * 会先判"中断没生效"并关闭会话,用户随后发送即报 `Session <id> is closed`+ * (#6931)。抛错发生在 vendor dispatch 之前,Session.send 不会执行 handle.send,+ * 其 finally 会清掉 send reservation,因此不需要 abort 来取消预约。*/const blockAcceptedDispatch = (live: Session | undefined, why: string): void => {- if (live) {- void live.abort().catch((err) => {- this.deps.logger.warn?.(`[runner] ${why} turn abort failed`, err);- });- return;- }this.deps.logger.warn?.(- '[runner] no live session to cancel the accepted dispatch; signalling the coordinator to roll it back',- { scheduleId: schedule.id, runId: ctx.runId, sessionId, why },+ '[runner] cancelling accepted dispatch before vendor dispatch; signalling the coordinator to roll it back',+ { scheduleId: schedule.id, runId: ctx.runId, sessionId, why, liveSessionPresent: Boolean(live) },);throw new AcceptedCallbackDispatchCancelled(`[SEND_CANCELLED_BEFORE_DISPATCH] queued heartbeat dispatch cancelled before vendor dispatch (${why})`,@@ -2846,9 +2865,15 @@ export class MakerScheduleRunner implements ScheduleRunner {if (dispatched) {const live = this.deps.maker.getSession(sessionId);if (live) {- void live.abort().catch((err) => {- this.deps.logger.warn?.('[runner] session.abort failed', err);- });+ // pause/delete can land after onAccepted but before Session.send crosses+ // the vendor boundary. Cancel that pre-dispatch reservation without+ // turning the whole session into 'aborting'; abort only when no such+ // reservation is left (the turn already crossed the boundary).+ if (!live.cancelPendingSend?.()) {+ void live.abort().catch((err) => {+ this.deps.logger.warn?.('[runner] session.abort failed', err);+ });+ }}}};diff --git a/packages/maker-core/src/session-control.test.ts b/packages/maker-core/src/session-control.test.tsindex 7d54eb6e53..43b513ed7c 100644--- a/packages/maker-core/src/session-control.test.ts+++ b/packages/maker-core/src/session-control.test.ts@@ -133,6 +133,33 @@ describe('Session graceful-stop control state', () => {await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });expect(sendSpy).not.toHaveBeenCalled();});+ it('cancels a pre-dispatch send reservation without aborting the session', async () => {+ const stub = createHandle();+ const session = createSession(stub);+ const sendSpy = vi.spyOn(stub.handle, 'send');+ let acceptedStarted!: () => void;+ const accepted = new Promise<void>((resolve) => { acceptedStarted = resolve; });+ let releaseAcceptance!: () => void;+ const acceptanceGate = new Promise<void>((resolve) => { releaseAcceptance = resolve; });++ const send = session.send('hello', {+ onAccepted: async () => {+ acceptedStarted();+ await acceptanceGate;+ },+ });+ await accepted;++ expect(session.getStatus()).toBe('active');+ expect(session.cancelPendingSend()).toBe(true);+ releaseAcceptance();++ await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });+ expect(sendSpy).not.toHaveBeenCalled();+ expect(stub.abort).not.toHaveBeenCalled();+ expect(session.getStatus()).toBe('active');+ });+it('cancels and joins a pre-acceptance send reservation before reporting stop requested', async () => {const stub = createHandle();let running = false;diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 3e9fba9461..ed8dbeba14 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1261,6 +1261,24 @@ export class Session {}}+ /**+ * Cancel a send that is still in the pre-dispatch (`accepting`) phase without+ * turning the whole session into `aborting`. Hosts that withdraw one queued+ * routine send use this instead of abort(): abort is user-Stop semantics and+ * arms the manual-abort recovery watchdog.+ *+ * Returns true when a pre-dispatch reservation was cancelled. False means there+ * is no such reservation (the turn already crossed the vendor boundary, was+ * accepted, or no send is pending), so callers that need to stop a running turn+ * should use abort().+ */+ cancelPendingSend(): boolean {+ const reservation = this.sendReservation;+ if (!reservation || reservation.accepted || reservation.phase !== 'accepting') return false;+ this.cancelSendReservation(reservation);+ return true;+ }+async abort(): Promise<void> {if (this.status === 'closed') return;if (this.status === 'error') return;