Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: address review — sync Pi scheduler route state
Chrise3dc6656285b
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex 4ccde37fcc..e18de83dc9 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@ -17,18 +17,8 @@*/import { describe, expect, it, vi, beforeEach } from 'vitest';-import type {- AgentEvent,- Maker,- Session,- SessionSendResult,-} from '@cindy/maker-core';-import type {- FireContext,- Logger,- Notifier,- Schedule,-} from '@cindy/maker-scheduler';+import type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';+import type { FireContext, Logger, Notifier, Schedule } from '@cindy/maker-scheduler';const mocks = vi.hoisted(() => ({createMessage: vi.fn(),@@ -40,6 +30,7 @@ const mocks = vi.hoisted(() => ({getSessionProvider: vi.fn(),setSessionProvider: vi.fn(),hydrateSessionProvider: vi.fn(),+ setSessionFastMode: vi.fn(),isSessionInTurn: vi.fn(),}));@@ -49,6 +40,10 @@ vi.mock('../../maker-host/session-provider-store.js', () => ({hydrateSessionProvider: mocks.hydrateSessionProvider,}));+vi.mock('../../maker-host/session-effort-store.js', () => ({+ setSessionFastMode: mocks.setSessionFastMode,+}));+vi.mock('../../localDb/ipc/messages.js', () => ({createMessage: mocks.createMessage,}));@@ -101,7 +96,9 @@ function createSessionHarness(): FakeSessionHarness {});// setModel 声明 string 入参(签名与真实 Session.setModel 一致),下面 mockImplementation 才能// 按 (m) 更新 session.model;测试可再用 mockRejectedValue / mockImplementation 覆盖。- const setModel = vi.fn(async (_m: string): Promise<void> => {});+ const setModel = vi.fn(+ async (_m: string, _opts?: { providerId?: string | null }): Promise<void> => {},+ );const setEffort = vi.fn(async () => undefined);const session = {id: 'scheduler-session',@@ -125,7 +122,7 @@ function createSessionHarness(): FakeSessionHarness {// session.model(而非 getSessionMeta 快照)确定复用会话实际在跑的模型,harness 必须同样更新。// 需要模拟"setModel 抛错"的用例用 mockRejectedValue 覆盖本实现(reject → 不更新 = Claude 语义);// 模拟 Codex"await 前先改 model 再抛"的用例用 mockImplementation 显式先改 model 再 throw。- setModel.mockImplementation(async (m: string) => {+ setModel.mockImplementation(async (m: string, _opts?: { providerId?: string | null }) => {(session as { model: string }).model = m;});@@ -185,11 +182,21 @@ interface RunnerHarness {function createRunnerHarness(h: FakeSessionHarness,- meta: { model?: string; effort?: string; workDir?: string; sdkSessionId?: string } | null = null,+ meta: {+ model?: string;+ effort?: string;+ fastMode?: boolean;+ workDir?: string;+ sdkSessionId?: string;+ } | null = null,opts: {sessionAlive?: boolean;activeSessions?: Session[];- availableModels?: Array<{ id: string; efforts?: readonly string[]; defaultEffort?: string | null }>;+ availableModels?: Array<{+ id: string;+ efforts?: readonly string[];+ defaultEffort?: string | null;+ }>;checkModelRoute?: ConstructorParameters<typeof MakerScheduleRunner>[0]['checkModelRoute'];resolveRouteCopyCapabilities?: ConstructorParameters<typeof MakerScheduleRunner@@ -246,6 +253,7 @@ describe('MakerScheduleRunner model selection', () => {mocks.backfillSessionMeta.mockResolvedValue(undefined);mocks.resolveWorkingDir.mockResolvedValue({ ok: true, path: '/work' });mocks.getSessionProvider.mockReturnValue(null);+ mocks.setSessionFastMode.mockReset();mocks.isSessionInTurn.mockReturnValue(false);mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active' });});@@ -254,7 +262,9 @@ describe('MakerScheduleRunner model selection', () => {it('超额档(gpt-5.5 只到 xhigh + effort=max)→ createSession 收到 clamp 后的 xhigh', async () => {const h = createSessionHarness();const harness = createRunnerHarness(h, null, {- availableModels: [{ id: 'gpt-5.5', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' }],+ availableModels: [+ { id: 'gpt-5.5', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ ],});const opts = await fireToCompletion(harness,@@ -277,10 +287,16 @@ describe('MakerScheduleRunner model selection', () => {const h = createSessionHarness();const harness = createRunnerHarness(h, null, {availableModels: [- { id: 'gpt-5.5', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },+ {+ id: 'gpt-5.5',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },],checkModelRoute: vi.fn(async (_a, _m, providerId) =>- providerId ? { kind: 'pass' as const } : { kind: 'reroute' as const, providerId: 'anthropic' },+ providerId+ ? { kind: 'pass' as const }+ : { kind: 'reroute' as const, providerId: 'anthropic' },),resolveRouteCopyCapabilities: vi.fn(async () => ({efforts: ['low', 'medium', 'high'],@@ -300,7 +316,11 @@ describe('MakerScheduleRunner model selection', () => {const h = createSessionHarness();const harness = createRunnerHarness(h, null, {availableModels: [- { id: 'gpt-5.6-sol', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'high' },+ {+ id: 'gpt-5.6-sol',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],+ defaultEffort: 'high',+ },],});const opts = await fireToCompletion(@@ -312,6 +332,54 @@ describe('MakerScheduleRunner model selection', () => {});});+ describe('Pi 派发前路由重裁决', () => {+ it('晚到 reroute 在 send 前同步 Pi 原生 provider-model,再更新 host store', async () => {+ const checkModelRoute = vi+ .fn()+ .mockResolvedValueOnce({ kind: 'pass' as const })+ .mockResolvedValueOnce({ kind: 'reroute' as const, providerId: 'byom-b' });+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'chatgpt/gpt-5.6-sol';+ const harness = createRunnerHarness(h, null, { checkModelRoute });++ await fireToCompletion(+ harness,+ h,+ baseSchedule({ agentKind: 'pi', model: 'chatgpt/gpt-5.6-sol' }),+ );++ expect(checkModelRoute).toHaveBeenCalledTimes(2);+ expect(h.setModel).toHaveBeenCalledWith('chatgpt/gpt-5.6-sol', { providerId: 'byom-b' });+ expect(h.setModel.mock.invocationCallOrder[0]).toBeLessThan(+ h.send.mock.invocationCallOrder[0],+ );+ expect(mocks.setSessionProvider).toHaveBeenCalledWith('scheduler-session', 'byom-b');+ });++ it('晚到 reroute 的 Pi 原生同步失败时不写 store,也不发送 prompt', async () => {+ const checkModelRoute = vi+ .fn()+ .mockResolvedValueOnce({ kind: 'pass' as const })+ .mockResolvedValueOnce({ kind: 'reroute' as const, providerId: 'byom-b' });+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'chatgpt/gpt-5.6-sol';+ h.setModel.mockRejectedValue(new Error('provider snapshot unavailable'));+ const harness = createRunnerHarness(h, null, { checkModelRoute });++ await expect(+ harness.runner.fire(+ baseSchedule({ agentKind: 'pi', model: 'chatgpt/gpt-5.6-sol' }),+ createFireContext(),+ ),+ ).rejects.toThrow('Session send failed before dispatch');+ expect(h.setModel).toHaveBeenCalledWith('chatgpt/gpt-5.6-sol', { providerId: 'byom-b' });+ expect(mocks.setSessionProvider).not.toHaveBeenCalled();+ expect(h.send).not.toHaveBeenCalled();+ });+ });+describe('non-heartbeat (每次新建 session)', () => {it('schedule.model 留空时 Claude 兜底 claude-sonnet-4-6(成本保守,与 UI 空值回退一致)', async () => {const h = createSessionHarness();@@ -350,11 +418,13 @@ describe('MakerScheduleRunner model selection', () => {);expect(resolveDefaultModelRoute).toHaveBeenCalledWith('pi', 'local-byom');- expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({- agentKind: 'pi',- model: 'byom/llama-4',- providerId: 'local-byom',- }));+ expect(harness.createSession).toHaveBeenCalledWith(+ expect.objectContaining({+ agentKind: 'pi',+ model: 'byom/llama-4',+ providerId: 'local-byom',+ }),+ );});it('Pi 空模型且没有已连接来源时在创建会话前明确失败', async () => {@@ -362,10 +432,12 @@ describe('MakerScheduleRunner model selection', () => {const resolveDefaultModelRoute = vi.fn(async () => null);const harness = createRunnerHarness(h, null, { resolveDefaultModelRoute });- await expect(harness.runner.fire(- baseSchedule({ agentKind: 'pi', model: undefined, providerId: undefined }),- createFireContext(),- )).rejects.toThrow('Pi has no connected model source');+ await expect(+ harness.runner.fire(+ baseSchedule({ agentKind: 'pi', model: undefined, providerId: undefined }),+ createFireContext(),+ ),+ ).rejects.toThrow('Pi has no connected model source');expect(harness.createSession).not.toHaveBeenCalled();expect(h.send).not.toHaveBeenCalled();});@@ -374,11 +446,7 @@ describe('MakerScheduleRunner model selection', () => {const h = createSessionHarness();const harness = createRunnerHarness(h);- const opts = await fireToCompletion(- harness,- h,- baseSchedule({ model: 'claude-sonnet-4-6' }),- );+ const opts = await fireToCompletion(harness, h, baseSchedule({ model: 'claude-sonnet-4-6' }));expect(opts.model).toBe('claude-sonnet-4-6');expect(h.setModel).not.toHaveBeenCalled();@@ -549,7 +617,11 @@ describe('MakerScheduleRunner model selection', () => {const harness = createRunnerHarness(h, HEARTBEAT_META, {sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -581,7 +653,11 @@ describe('MakerScheduleRunner model selection', () => {const harness = createRunnerHarness(h, HEARTBEAT_META, {sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -612,8 +688,16 @@ describe('MakerScheduleRunner model selection', () => {{sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'claude-opus-4-8', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-opus-4-8',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],},);@@ -621,7 +705,11 @@ describe('MakerScheduleRunner model selection', () => {await fireToCompletion(harness,h,- baseSchedule({ model: 'claude-opus-4-8', effort: 'max', targetSessionId: 'scheduler-session' }),+ baseSchedule({+ model: 'claude-opus-4-8',+ effort: 'max',+ targetSessionId: 'scheduler-session',+ }),);expect(h.setModel).toHaveBeenCalledWith('claude-opus-4-8'); // 尝试切换(被拒)@@ -648,8 +736,16 @@ describe('MakerScheduleRunner model selection', () => {{sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'claude-opus-4-8', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-opus-4-8',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],},);@@ -658,7 +754,11 @@ describe('MakerScheduleRunner model selection', () => {harness,h,// effort 显式留空 = follow;model 换到只到 xhigh 的新模型。- baseSchedule({ model: 'claude-opus-4-8', effort: undefined, targetSessionId: 'scheduler-session' }),+ baseSchedule({+ model: 'claude-opus-4-8',+ effort: undefined,+ targetSessionId: 'scheduler-session',+ }),);expect(h.setModel).toHaveBeenCalledWith('claude-opus-4-8'); // 切换成功@@ -686,8 +786,16 @@ describe('MakerScheduleRunner model selection', () => {{sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'claude-sonnet-4-6', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-sonnet-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],},);@@ -722,8 +830,16 @@ describe('MakerScheduleRunner model selection', () => {{sessionAlive: true,availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'claude-opus-4-8', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-opus-4-8',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],},);@@ -731,7 +847,11 @@ describe('MakerScheduleRunner model selection', () => {await fireToCompletion(harness,h,- baseSchedule({ model: 'claude-opus-4-8', effort: 'max', targetSessionId: 'scheduler-session' }),+ baseSchedule({+ model: 'claude-opus-4-8',+ effort: 'max',+ targetSessionId: 'scheduler-session',+ }),);expect(h.setModel).toHaveBeenCalledWith('claude-opus-4-8');@@ -752,8 +872,16 @@ describe('MakerScheduleRunner model selection', () => {{sessionAlive: false, // 冷 resume(非复用)availableModels: [- { id: 'claude-opus-4-7', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'claude-opus-4-8', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-7',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-opus-4-8',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],},);@@ -762,7 +890,11 @@ describe('MakerScheduleRunner model selection', () => {harness,h,// follow-effort(留空)+ 换到只到 xhigh 的模型。- baseSchedule({ model: 'claude-opus-4-8', effort: undefined, targetSessionId: 'scheduler-session' }),+ baseSchedule({+ model: 'claude-opus-4-8',+ effort: undefined,+ targetSessionId: 'scheduler-session',+ }),);// follow 的 max 按新模型 clamp 到 xhigh,经 setEffort 下发但失败。@@ -939,16 +1071,86 @@ describe('MakerScheduleRunner model selection', () => {);});+ it('heartbeat 复用 Pi 时即使模型不变也把 provider-model 原子同步到原生进程', async () => {+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'byom-a' });+ mocks.getSessionProvider.mockReturnValue('byom-a');+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'gpt-5.6-sol';+ const harness = createRunnerHarness(+ h,+ {+ model: 'gpt-5.6-sol',+ workDir: '/work',+ sdkSessionId: 'sdk-pi-1',+ },+ { sessionAlive: true },+ );++ await fireToCompletion(+ harness,+ h,+ baseSchedule({+ agentKind: 'pi',+ model: 'gpt-5.6-sol',+ providerId: 'byom-b',+ targetSessionId: 'scheduler-session',+ }),+ );++ expect(h.setModel).toHaveBeenCalledWith('gpt-5.6-sol', { providerId: 'byom-b' });+ expect(h.setModel.mock.invocationCallOrder[0]).toBeLessThan(+ h.send.mock.invocationCallOrder[0],+ );+ expect(mocks.setSessionProvider).toHaveBeenCalledWith('scheduler-session', 'byom-b');+ });++ it('heartbeat 复用 Pi 的原生路由同步失败时在 send 前 fail-closed', async () => {+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'byom-a' });+ mocks.getSessionProvider.mockReturnValue('byom-a');+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'gpt-5.6-sol';+ h.setModel.mockRejectedValue(new Error('set_model rejected'));+ const harness = createRunnerHarness(+ h,+ {+ model: 'gpt-5.6-sol',+ workDir: '/work',+ sdkSessionId: 'sdk-pi-1',+ },+ { sessionAlive: true },+ );++ await expect(+ harness.runner.fire(+ baseSchedule({+ agentKind: 'pi',+ model: 'gpt-5.6-sol',+ providerId: 'byom-b',+ targetSessionId: 'scheduler-session',+ }),+ createFireContext(),+ ),+ ).rejects.toThrow('schedule Pi route sync failed before dispatch');+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.setSessionProvider).not.toHaveBeenCalled();+ });+it('heartbeat 复用本地 Codex 且跨 credential family → 先关闭再按新来源重建', async () => {mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'xd' });const h = createSessionHarness();Object.defineProperty(h.session, 'agentKind', { value: 'codex' });Object.defineProperty(h.session, 'model', { value: 'codex/gpt-5.5' });- const harness = createRunnerHarness(h, {- model: 'codex/gpt-5.5',- workDir: '/work',- sdkSessionId: 'sdk-1',- }, { sessionAlive: true });+ const harness = createRunnerHarness(+ h,+ {+ model: 'codex/gpt-5.5',+ workDir: '/work',+ sdkSessionId: 'sdk-1',+ },+ { sessionAlive: true },+ );await fireToCompletion(harness,@@ -962,8 +1164,9 @@ describe('MakerScheduleRunner model selection', () => {);expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');- expect(harness.closeSession.mock.invocationCallOrder[0])- .toBeLessThan(harness.createSession.mock.invocationCallOrder[0]);+ expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(+ harness.createSession.mock.invocationCallOrder[0],+ );expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'openai', model: 'gpt-5.4' }),);@@ -987,11 +1190,15 @@ describe('MakerScheduleRunner model selection', () => {remoteHostId: null,isTurnRunning: () => true,} as unknown as Session;- const harness = createRunnerHarness(h, {- model: 'codex/gpt-5.5',- workDir: '/work',- sdkSessionId: 'sdk-1',- }, { sessionAlive: true, activeSessions: [h.session, busyCodexSession] });+ const harness = createRunnerHarness(+ h,+ {+ model: 'codex/gpt-5.5',+ workDir: '/work',+ sdkSessionId: 'sdk-1',+ },+ { sessionAlive: true, activeSessions: [h.session, busyCodexSession] },+ );const result = await harness.runner.fire(baseSchedule({@@ -1017,11 +1224,15 @@ describe('MakerScheduleRunner model selection', () => {mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'xd' });const h = createSessionHarness();Object.defineProperty(h.session, 'model', { value: 'claude-sonnet-4-6' });- const harness = createRunnerHarness(h, {- model: 'claude-sonnet-4-6',- workDir: '/work',- sdkSessionId: 'sdk-1',- }, { sessionAlive: true });+ const harness = createRunnerHarness(+ h,+ {+ model: 'claude-sonnet-4-6',+ workDir: '/work',+ sdkSessionId: 'sdk-1',+ },+ { sessionAlive: true },+ );await fireToCompletion(harness,@@ -1034,8 +1245,9 @@ describe('MakerScheduleRunner model selection', () => {);expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');- expect(harness.closeSession.mock.invocationCallOrder[0])- .toBeLessThan(harness.createSession.mock.invocationCallOrder[0]);+ expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(+ harness.createSession.mock.invocationCallOrder[0],+ );expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({ providerId: 'anthropic', model: 'claude-opus-4-8' }),);@@ -1053,11 +1265,15 @@ describe('MakerScheduleRunner model selection', () => {const h = createSessionHarness();Object.defineProperty(h.session, 'model', { value: 'claude-sonnet-4-6' });Object.defineProperty(h.session, 'isTurnRunning', { value: () => true });- const harness = createRunnerHarness(h, {- model: 'claude-sonnet-4-6',- workDir: '/work',- sdkSessionId: 'sdk-1',- }, { sessionAlive: true });+ const harness = createRunnerHarness(+ h,+ {+ model: 'claude-sonnet-4-6',+ workDir: '/work',+ sdkSessionId: 'sdk-1',+ },+ { sessionAlive: true },+ );const result = await harness.runner.fire(baseSchedule({@@ -1078,4 +1294,67 @@ describe('MakerScheduleRunner model selection', () => {expect(h.send).not.toHaveBeenCalled();});});++ describe('Pi Fast bridge 状态同步', () => {+ it('fresh Pi 首轮在 send 前写入 Fast=true', async () => {+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ const harness = createRunnerHarness(h);++ await fireToCompletion(+ harness,+ h,+ baseSchedule({ agentKind: 'pi', model: 'gpt-5.6-sol', fastMode: true }),+ );++ expect(mocks.setSessionFastMode).toHaveBeenCalledWith('scheduler-session', true);+ expect(mocks.setSessionFastMode.mock.invocationCallOrder[0]).toBeLessThan(+ h.send.mock.invocationCallOrder[0],+ );+ });++ it('复用 Pi 在 send 前写入 Fast=false,清掉旧 bridge 状态', async () => {+ const h = createSessionHarness();+ (h.session as { agentKind: string }).agentKind = 'pi';+ (h.session as { model: string }).model = 'gpt-5.6-sol';+ const harness = createRunnerHarness(+ h,+ {+ model: 'gpt-5.6-sol',+ fastMode: false,+ workDir: '/work',+ sdkSessionId: 'sdk-pi-1',+ },+ { sessionAlive: true },+ );++ await fireToCompletion(+ harness,+ h,+ baseSchedule({+ agentKind: 'pi',+ model: undefined,+ targetSessionId: 'scheduler-session',+ }),+ );++ expect(mocks.setSessionFastMode).toHaveBeenCalledWith('scheduler-session', false);+ expect(mocks.setSessionFastMode.mock.invocationCallOrder[0]).toBeLessThan(+ h.send.mock.invocationCallOrder[0],+ );+ });++ it('Claude/Codex 不写 Pi bridge Fast store', async () => {+ const h = createSessionHarness();+ const harness = createRunnerHarness(h);++ await fireToCompletion(+ harness,+ h,+ baseSchedule({ agentKind: 'codex', model: 'gpt-5.5', fastMode: true }),+ );++ expect(mocks.setSessionFastMode).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex c98d75d2cd..47569eb209 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -19,19 +19,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';import { AcceptedCallbackDispatchCancelled } from '../../maker-ipc/acceptedCallbackRunner.js';-import type {- AgentEvent,- Maker,- Session,- SessionSendResult,-} from '@cindy/maker-core';-import type {- FireContext,- Logger,- Notifier,- Schedule,- ScheduleRun,-} from '@cindy/maker-scheduler';+import type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';+import type { FireContext, Logger, Notifier, Schedule, ScheduleRun } from '@cindy/maker-scheduler';const mocks = vi.hoisted(() => ({createMessage: vi.fn(),@@ -40,6 +29,20 @@ const mocks = vi.hoisted(() => ({wireSessionToIpc: vi.fn(),resolveWorkingDir: vi.fn(),backfillSessionMeta: vi.fn(),+ getSessionProvider: vi.fn(),+ setSessionProvider: vi.fn(),+ hydrateSessionProvider: vi.fn(),+ setSessionFastMode: vi.fn(),+}));++vi.mock('../../maker-host/session-provider-store.js', () => ({+ getSessionProvider: mocks.getSessionProvider,+ setSessionProvider: mocks.setSessionProvider,+ hydrateSessionProvider: mocks.hydrateSessionProvider,+}));++vi.mock('../../maker-host/session-effort-store.js', () => ({+ setSessionFastMode: mocks.setSessionFastMode,}));vi.mock('../../localDb/ipc/messages.js', () => ({@@ -99,7 +102,9 @@ interface FakeSessionHarness {function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {const listeners: Array<(event: AgentEvent) => void> = [];const send = vi.fn<SendImpl>(sendImpl);- const setModel = vi.fn(async () => undefined);+ const setModel = vi.fn(+ async (_model: string, _opts?: { providerId?: string | null }) => undefined,+ );const setEffort = vi.fn(async () => undefined);const session = {id: SESSION_ID,@@ -256,9 +261,17 @@ function createRunnerHarness(session: Session,schedulerQueue: SchedulerQueueDeps,opts: {- availableModels?: Array<{ id: string; efforts?: readonly string[]; defaultEffort?: string | null }>;+ availableModels?: Array<{+ id: string;+ efforts?: readonly string[];+ defaultEffort?: string | null;+ }>;/** 绑定会话 meta 里的 effort(= 排队路径的 baseline.effort);默认 undefined。 */metaEffort?: string;+ /** 绑定会话 meta 里的 Fast 状态(= Pi bridge 派发前应同步的值)。 */+ metaFastMode?: boolean;+ /** 绑定会话 meta 里的 model;默认沿用 Claude fixture。 */+ metaModel?: string;/** 停用轴裁决桩(缺省 = 不裁决,与生产未接线时一致)。 */checkModelRoute?: MakerScheduleRunnerDeps['checkModelRoute'];} = {},@@ -274,8 +287,9 @@ function createRunnerHarness(id: SESSION_ID,agentKind: 'claude-code',workDir: '/tmp/bound',- model: 'claude-opus-4-6',+ model: opts.metaModel ?? 'claude-opus-4-6',effort: opts.metaEffort,+ fastMode: opts.metaFastMode,sdkSessionId: 'sdk-1',})),isSessionAlive: vi.fn(() => true),@@ -305,6 +319,7 @@ beforeEach(() => {userSendAt: null,providerId: null,});+ mocks.getSessionProvider.mockReturnValue(null);});describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {@@ -339,7 +354,11 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {await queue.accept();await vi.waitFor(() => expect(harness.listenerCount()).toBe(1));expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(true);- harness.emit({ type: 'text', data: { text: 'heartbeat summary', isFinal: true }, source: 'claude-code' });+ harness.emit({+ type: 'text',+ data: { text: 'heartbeat summary', isFinal: true },+ source: 'claude-code',+ });harness.emit({ type: 'done', data: {}, source: 'claude-code' });const result = await firePromise;@@ -352,6 +371,113 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {expect(latestNotifiedRun(notifier)).toMatchObject({ status: 'success' });});+ it('排队 Pi 即使模型不变也同步原生 provider-model,并在派发前写 Fast', async () => {+ mocks.getSessionRowSnapshot.mockResolvedValue({+ status: 'active',+ userSendAt: null,+ providerId: 'byom-a',+ });+ mocks.getSessionProvider.mockReturnValue('byom-a');+ const harness = createSessionHarness(async () => ({ accepted: true }));+ (harness.session as { agentKind: string }).agentKind = 'pi';+ (harness.session as { model: string }).model = 'gpt-5.6-sol';+ const queue = createQueueHarness({ busy: true });+ const { runner } = createRunnerHarness(harness.session, queue.deps, {+ metaModel: 'gpt-5.6-sol',+ metaFastMode: true,+ });++ const firePromise = runner.fire(+ heartbeatSchedule({+ agentKind: 'pi',+ model: 'gpt-5.6-sol',+ providerId: 'byom-b',+ }),+ createFireContext(),+ );+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();++ expect(harness.setModel).toHaveBeenCalledWith('gpt-5.6-sol', { providerId: 'byom-b' });+ expect(mocks.setSessionProvider).toHaveBeenCalledWith(SESSION_ID, 'byom-b');+ expect(mocks.setSessionFastMode).toHaveBeenCalledWith(SESSION_ID, true);+ harness.emit({ type: 'done', data: {}, source: 'pi' });+ await expect(firePromise).resolves.toMatchObject({ sessionId: SESSION_ID });+ });++ it('排队 Pi 的原生路由同步失败时在 vendor dispatch 前 fail-closed', async () => {+ mocks.getSessionRowSnapshot.mockResolvedValue({+ status: 'active',+ userSendAt: null,+ providerId: 'byom-a',+ });+ mocks.getSessionProvider.mockReturnValue('byom-a');+ const harness = createSessionHarness(async () => ({ accepted: true }));+ (harness.session as { agentKind: string }).agentKind = 'pi';+ (harness.session as { model: string }).model = 'gpt-5.6-sol';+ harness.setModel.mockRejectedValue(new Error('set_model rejected'));+ const queue = createQueueHarness({ busy: true });+ const { runner } = createRunnerHarness(harness.session, queue.deps, {+ metaModel: 'gpt-5.6-sol',+ });++ const firePromise = runner.fire(+ heartbeatSchedule({+ agentKind: 'pi',+ model: 'gpt-5.6-sol',+ providerId: 'byom-b',+ }),+ createFireContext(),+ );+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();++ await expect(firePromise).rejects.toThrow(+ 'schedule Pi route sync failed before queued dispatch',+ );+ expect(harness.session.abort).toHaveBeenCalled();+ expect(mocks.setSessionProvider).not.toHaveBeenCalled();+ });++ it('排队 Pi 每次派发都写 Fast=false,清掉复用会话的旧 bridge 状态', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ (harness.session as { agentKind: string }).agentKind = 'pi';+ (harness.session as { model: string }).model = 'gpt-5.6-sol';+ const queue = createQueueHarness({ busy: true });+ const { runner } = createRunnerHarness(harness.session, queue.deps, {+ metaModel: 'gpt-5.6-sol',+ metaFastMode: false,+ });++ const firePromise = runner.fire(+ heartbeatSchedule({ agentKind: 'pi', model: undefined, providerId: undefined }),+ createFireContext(),+ );+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();++ expect(mocks.setSessionFastMode).toHaveBeenCalledWith(SESSION_ID, false);+ harness.emit({ type: 'done', data: {}, source: 'pi' });+ await expect(firePromise).resolves.toMatchObject({ sessionId: SESSION_ID });+ });++ it('正常排队项 accept 时 live session 已消失 → 在路由/Fast 同步前阻止 vendor dispatch', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true });+ const { runner, maker } = createRunnerHarness(harness.session, queue.deps);+ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ const fireRejected = expect(firePromise).rejects.toThrow(+ 'queued heartbeat live session unavailable before route sync and vendor dispatch',+ );+ 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 fireRejected;+ expect(harness.setModel).not.toHaveBeenCalled();+ expect(mocks.setSessionFastMode).not.toHaveBeenCalled();+ });+it('defers (no duplicate enqueue) when the schedule already has a queued prompt', async () => {const harness = createSessionHarness(async () => ({ accepted: true }));const queue = createQueueHarness({ busy: true, hasQueued: true });@@ -471,7 +597,9 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {// coordinator 稍后仍完成了派发(accept 晚到)→ 刚起步的 turn 被立即中断。await queue.accept();expect((maker as unknown as { getSession: () => Session }).getSession).toBeDefined();- expect((harness.session as unknown as { abort: ReturnType<typeof vi.fn> }).abort).toHaveBeenCalled();+ expect(+ (harness.session as unknown as { abort: ReturnType<typeof vi.fn> }).abort,+ ).toHaveBeenCalled();// 不再挂 turn 监听(run 已收口)。expect(harness.listenerCount()).toBe(0);expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);@@ -564,7 +692,11 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const queue = createQueueHarness({ busy: true });const { runner } = createRunnerHarness(harness.session, queue.deps, {availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -594,7 +726,11 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const queue = createQueueHarness({ busy: true });const { runner } = createRunnerHarness(harness.session, queue.deps, {availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -620,8 +756,16 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const queue = createQueueHarness({ busy: true });const { runner } = createRunnerHarness(harness.session, queue.deps, {availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'capped-xhigh-model', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'capped-xhigh-model',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -684,8 +828,16 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const queue = createQueueHarness({ busy: true });const { runner } = createRunnerHarness(harness.session, queue.deps, {availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'capped-xhigh-model', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'capped-xhigh-model',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -714,8 +866,16 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const { runner } = createRunnerHarness(harness.session, queue.deps, {metaEffort: 'max', // enqueue 时刻 baseline.effort = max(陈旧)availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'capped-xhigh-model', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'capped-xhigh-model',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -744,8 +904,16 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {const { runner } = createRunnerHarness(harness.session, queue.deps, {metaEffort: 'xhigh', // baseline.effort = 上次 fire backfill 的 clamp 值availableModels: [- { id: 'claude-opus-4-6', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high' },- { id: 'capped-xhigh-model', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high' },+ {+ id: 'claude-opus-4-6',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ defaultEffort: 'high',+ },+ {+ id: 'capped-xhigh-model',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ defaultEffort: 'high',+ },],});@@ -792,7 +960,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const ctx = createFireContext();let started = 0;const ends: boolean[] = [];- (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => { started += 1; };+ (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => {+ started += 1;+ };(ctx as { endQueueWait?: (r: boolean) => boolean }).endQueueWait = (r) => {ends.push(r);return true; // 有空槽@@ -844,7 +1014,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const firePromise = runner.fire(heartbeatSchedule(), createFireContext());await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await expect(firePromise).resolves.toMatchObject({ deferred: true });// 超时之后 coordinator 才 drain 到它@@ -866,7 +1038,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const ctx = createFireContext();let started = 0;const ends: boolean[] = [];- (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => { started += 1; };+ (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => {+ started += 1;+ };(ctx as { endQueueWait?: (r: boolean) => boolean }).endQueueWait = (r) => {ends.push(r);return true;@@ -875,7 +1049,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const firePromise = runner.fire(heartbeatSchedule(), ctx);await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));// 走到上限:轮询在下一拍发现超时 → 撤项 + 顺延- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await expect(firePromise).resolves.toMatchObject({ deferred: true });expect(queue.removeCalls).toEqual([{ sessionId: SESSION_ID, clientId: 'client-1' }]);@@ -955,7 +1131,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));// 一路清醒:每拍的真实间隔都等于轮询间隔,额度正常累加- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await settled;expect(queue.removeCalls).toEqual([{ sessionId: SESSION_ID, clientId: 'client-1' }]);} finally {@@ -970,15 +1148,14 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const queue = createQueueHarness({ busy: true });const { runner, notifier } = createRunnerHarness(harness.session, queue.deps);- const firePromise = runner.fire(- heartbeatSchedule({ recurring: false }),- createFireContext(),- );+ const firePromise = runner.fire(heartbeatSchedule({ recurring: false }), createFireContext());// 先挂上 rejection handler 再推进假时钟:fire 会在 advance 期间同步 reject,// 此时若还没有 handler,Node 会报 unhandled rejection 污染整个测试文件。const rejection = expect(firePromise).rejects.toThrow();await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await rejection;expect(queue.removeCalls).toEqual([{ sessionId: SESSION_ID, clientId: 'client-1' }]);@@ -998,7 +1175,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const firePromise = runner.fire(heartbeatSchedule(), createFireContext());await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));// 快到上限时派发被接受- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS - QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS - QUEUED_DISPATCH_TRACK_POLL_MS,+ );await queue.accept();// 再跨过上限:已 dispatched,轮询早退,不得撤项await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS);@@ -1024,7 +1203,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const firePromise = runner.fire(heartbeatSchedule(), createFireContext());const settled = expect(firePromise).resolves.toMatchObject({ deferred: true });await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await settled;// 迟到的 accept 不抛(coordinator 靠 reservation 取消回滚),但必须取消这次派发@@ -1048,7 +1229,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const firePromise = runner.fire(heartbeatSchedule(), createFireContext());const settled = expect(firePromise).resolves.toMatchObject({ deferred: true });await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));- await vi.advanceTimersByTimeAsync(QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS);+ await vi.advanceTimersByTimeAsync(+ QUEUED_DISPATCH_MAX_WAIT_MS + QUEUED_DISPATCH_TRACK_POLL_MS,+ );await settled;// 会话此刻已不在内存里(ephemeral 关闭 / 进程重建)@@ -1072,7 +1255,9 @@ describe('MakerScheduleRunner queued dispatch: slot accounting and wait cap', ()const ctx = createFireContext();let startCalls = 0;const ends: boolean[] = [];- (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => { startCalls += 1; };+ (ctx as { onQueueWaitStart?: () => void }).onQueueWaitStart = () => {+ startCalls += 1;+ };(ctx as { endQueueWait?: (r: boolean) => boolean }).endQueueWait = (r) => {ends.push(r);return true;diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex db962533c3..331d7a49f7 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -32,7 +32,14 @@import { randomUUID } from 'node:crypto';import { isTerminalAgentErrorEvent } from '@cindy/maker-core';-import type { Maker, AgentEvent, AgentKind, Effort, PermissionMode, Session } from '@cindy/maker-core';+import type {+ Maker,+ AgentEvent,+ AgentKind,+ Effort,+ PermissionMode,+ Session,+} from '@cindy/maker-core';import { clampEffortToSupported } from '@cindy/model-providers';import type {Schedule,@@ -52,6 +59,7 @@ import {setSessionProvider,hydrateSessionProvider,} from '../maker-host/session-provider-store.js';+import { setSessionFastMode } from '../maker-host/session-effort-store.js';import {CredentialModeSwitchBusyError,prepareLocalCodexCredentialModeSwitch,@@ -60,7 +68,12 @@ import {} from '../maker-host/codex-credential-switch.js';import { ensureDialogueWorkspaceDir } from '../localDb/dialogueWorkspace';import { AcceptedCallbackDispatchCancelled } from '../maker-ipc/acceptedCallbackRunner.js';-import { wireSessionToIpc, isSessionInTurn, noteSilentStopUserSend, onSilentStopSettled } from '../maker-ipc/register.js';+import {+ wireSessionToIpc,+ isSessionInTurn,+ noteSilentStopUserSend,+ onSilentStopSettled,+} from '../maker-ipc/register.js';import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton.js';import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff.js';import {@@ -223,9 +236,7 @@ export interface MakerScheduleRunnerDeps {model: string,providerId: string | null,) => Promise<- | { kind: 'pass' }- | { kind: 'reroute'; providerId: string }- | { kind: 'reject'; reason: string }+ { kind: 'pass' } | { kind: 'reroute'; providerId: string } | { kind: 'reject'; reason: string }>;/*** 某 (来源, 模型, agent) 拷贝的能力(efforts / Fast)。effort 与 Fast 支持都是@@ -257,6 +268,9 @@ export interface MakerScheduleRunnerDeps {*/class QueuedRouteDisabledError extends Error {}+/** Pi 原生路由热切失败;继续派发会把任务发给旧 provider,必须在 vendor 前站下。 */+class QueuedPiRouteSyncError extends Error {}+/*** 排队等派发超过 QUEUED_DISPATCH_MAX_WAIT_MS。用独立类型让 dispatchGate 的 catch* 能把它和真正的失败区分开:超时不是"这轮跑失败了",而是"这轮没轮到",按顺延收口。@@ -520,8 +534,7 @@ export class MakerScheduleRunner implements ScheduleRunner {this.deps.maker.getSessionMeta(sessionId).catch(() => null),getSessionRowSnapshot(sessionId),]);- const archived =- !row || row.status === 'archived' || row.status === 'deleted';+ const archived = !row || row.status === 'archived' || row.status === 'deleted';if (archived) {holder.releaseAgentSwitchLock?.();holder.releaseAgentSwitchLock = undefined;@@ -589,6 +602,7 @@ export class MakerScheduleRunner implements ScheduleRunner {return await this.fireHeartbeatViaQueue(schedule, ctx, sessionId, {model: meta?.model,effort: meta?.effort,+ fastMode: meta?.fastMode,providerId: row?.providerId ?? null,});}@@ -667,12 +681,16 @@ export class MakerScheduleRunner implements ScheduleRunner {: undefined;const explicitProviderId = schedule.providerId?.trim() ? schedule.providerId.trim() : null;const defaultRouteProviderId = explicitProviderId ?? (isHeartbeat ? heartbeatProviderId : null);- const dynamicDefaultRoute = !rawModel?.trim() && effectiveAgentKind === 'pi'- ? await this.deps.resolveDefaultModelRoute?.(effectiveAgentKind, defaultRouteProviderId) ?? null- : null;+ const dynamicDefaultRoute =+ !rawModel?.trim() && effectiveAgentKind === 'pi'+ ? ((await this.deps.resolveDefaultModelRoute?.(+ effectiveAgentKind,+ defaultRouteProviderId,+ )) ?? null)+ : null;const model = rawModel?.trim()? rawModel- : dynamicDefaultRoute?.model ?? defaultModelFor(effectiveAgentKind);+ : (dynamicDefaultRoute?.model ?? defaultModelFor(effectiveAgentKind));if (!model) {throw new Error('schedule route unavailable: Pi has no connected model source');}@@ -685,10 +703,11 @@ export class MakerScheduleRunner implements ScheduleRunner {? heartbeatFastMode: schedule.fastMode: undefined;- let createProviderId = explicitProviderId- ?? (isHeartbeat ? heartbeatProviderId : null)- ?? dynamicDefaultRoute?.providerId- ?? null;+ let createProviderId =+ explicitProviderId ??+ (isHeartbeat ? heartbeatProviderId : null) ??+ dynamicDefaultRoute?.providerId ??+ null;// 停用轴准入(PR #744 review):每次 fire 都是新的付费调用,不属于「运行中的会话// 不打断」豁免 —— 保存过的路由被用户停用后,本次 run 必须以明确错误失败(run 历史// 可见),不能继续经停用路由扣费;隐式默认落点被停用而有启用替代拷贝时改路由过去。@@ -848,12 +867,35 @@ export class MakerScheduleRunner implements ScheduleRunner {// 失败时运行时仍是旧值, 必须跳过对应字段落库 —— 否则 meta 与运行时不一致,// 且下次 fire 读到 meta == schedule 会判定"无变化"不再重试, 错误被永久固化。const heartbeatModelChanged = isHeartbeat && model !== heartbeatModel;+ // Pi 的 BYOM 来源存在原生进程内,不经过 compat proxy。maker.createSession 复用+ // active session 时会忽略 opts.providerId,所以即使 model id 没变,也必须把+ // (provider, model) 作为一个原子路由重新下发;否则 DB/UI 已显示新来源,prompt+ // 却仍会直连旧来源。未显式覆盖时沿用 live store 的最新来源。+ const reusedPiRouteProviderId =+ explicitProviderId ??+ reroutedProviderId ??+ getSessionProvider(session.id) ??+ heartbeatProviderId ??+ null;+ const mustSyncReusedPiRoute = reusedLiveSession && effectiveAgentKind === 'pi';let modelSwitchApplied = true;- if (heartbeatModelChanged) {+ if (heartbeatModelChanged || mustSyncReusedPiRoute) {try {- await session.setModel(model);+ if (mustSyncReusedPiRoute) {+ await session.setModel(model, { providerId: reusedPiRouteProviderId });+ } else {+ await session.setModel(model);+ }} catch (err) {if (reusedLiveSession) modelSwitchApplied = false;+ if (mustSyncReusedPiRoute) {+ // 对 Pi 而言失败后来源未知;继续 send 可能把内容发给旧 BYOM endpoint,+ // 不能沿用 Claude/Codex 的 non-fatal 模型切换降级。+ throw new Error(+ `schedule Pi route sync failed before dispatch (model "${model}", provider "${reusedPiRouteProviderId ?? 'cindy'}")`,+ { cause: err },+ );+ }this.deps.logger.warn?.('[runner] heartbeat setModel failed (non-fatal)', err);}}@@ -877,7 +919,12 @@ export class MakerScheduleRunner implements ScheduleRunner {const runtimeReconciledEffort =runtimeModel === model && desiredEffort === schedule.effort? reconciledEffort- : this.reconcileEffortForModel(effectiveAgentKind, runtimeModel, desiredEffort, schedule.id);+ : this.reconcileEffortForModel(+ effectiveAgentKind,+ runtimeModel,+ desiredEffort,+ schedule.id,+ );// heartbeatEffort 为对比基线:仅当 clamp 结果与会话当前档不同才 setEffort(follow-effort 且模型// 支持当前档 → 相等 → 不动;换到 capped 模型 → clamp 出更低档 → 触发同步)。const heartbeatEffortChanged =@@ -895,7 +942,8 @@ export class MakerScheduleRunner implements ScheduleRunner {// 这两种情况失败 = 没生效,必须跳过落库让下次 fire 重试;否则 DB 记了没生效的档、下次判定// "已同步"不再重试(PR #479 review「Skip persisting followed effort when fresh sync fails」)。// 仅当 fresh 且要落的档 == createSession 已应用的档时,setEffort 只是幂等兜底,失败可照常落库。- if (reusedLiveSession || runtimeReconciledEffort !== reconciledEffort) effortSwitchApplied = false;+ if (reusedLiveSession || runtimeReconciledEffort !== reconciledEffort)+ effortSwitchApplied = false;this.deps.logger.warn?.('[runner] heartbeat setEffort failed (non-fatal)', err);}}@@ -921,6 +969,13 @@ export class MakerScheduleRunner implements ScheduleRunner {hydrateSessionProvider(session.id, heartbeatProviderId);}+ // Pi 的 ChatGPT Fast 由 compat bridge 的 per-session store 读取,Pi handle 本身+ // 不消费 createSession.fastMode。每次派发前都写 true/false:fresh session 才能+ // 首轮命中 Fast,复用 session 也不会残留上一次的值。+ if (effectiveAgentKind === 'pi') {+ setSessionFastMode(session.id, fastMode === true);+ }+// 4.5 wire 到 IPC 转发链路 —— 让 session 的事件 / 状态 / interaction 请求广播到// renderer。renderer 的 makerChatStore 全局 listen 'maker:event',会把 user prompt /// assistant text / tool_use / tool_result 等落库到 messages 表。@@ -977,7 +1032,9 @@ export class MakerScheduleRunner implements ScheduleRunner {// 回退分配了对话工作区的会话按 'dialogue' 落库 —— 侧边栏才会归入// "对话"分组(覆盖存量 workspaceKind='project' 但无目录的旧任务)。workspaceKind: !isHeartbeat- ? (isDialogueTarget ? 'dialogue' : schedule.workspaceKind)+ ? isDialogueTarget+ ? 'dialogue'+ : schedule.workspaceKind: undefined,source: !isHeartbeat ? 'scheduler' : undefined,},@@ -1098,6 +1155,16 @@ export class MakerScheduleRunner implements ScheduleRunner {`schedule route rerouted across credential modes after session creation; failing this run so the next fire rebuilds the session (model "${runtimeModel}" → provider "${verdict.providerId}")`,);}+ if (effectiveAgentKind === 'pi') {+ try {+ await session.setModel(runtimeModel, { providerId: verdict.providerId });+ } catch (err) {+ throw new Error(+ `schedule Pi route sync failed after pre-dispatch reroute (model "${runtimeModel}", provider "${verdict.providerId}")`,+ { cause: err },+ );+ }+ }setSessionProvider(session.id, verdict.providerId);}}@@ -1298,8 +1365,7 @@ export class MakerScheduleRunner implements ScheduleRunner {.getCapabilities(agentKind).availableModels.find((m) => m.id === model);reconciled = (clampEffortToSupported(effort, descriptor?.efforts) ?? undefined) as- | Effort- | undefined;+ Effort | undefined;if (effort && reconciled !== effort) {this.deps.logger.info?.('[runner] effort reconciled to model capability', {scheduleId,@@ -1320,7 +1386,12 @@ export class MakerScheduleRunner implements ScheduleRunner {ctx: FireContext,sessionId: string,/** 绑定会话的当前路由基线(meta.model / meta.effort / sessions.provider_id)。 */- routingBaseline: { model?: string; effort?: string; providerId: string | null },+ routingBaseline: {+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId: string | null;+ },): Promise<FireResult> {const headlessTurn = {closed: false,@@ -1351,7 +1422,12 @@ export class MakerScheduleRunner implements ScheduleRunner {schedule: Schedule,ctx: FireContext,sessionId: string,- routingBaseline: { model?: string; effort?: string; providerId: string | null },+ routingBaseline: {+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId: string | null;+ },markHeadlessTurnDispatched: () => void,): Promise<FireResult> {const sq = this.deps.schedulerQueue;@@ -1502,11 +1578,14 @@ export class MakerScheduleRunner implements ScheduleRunner {// activeTurn 的项是 no-op,coordinator 仍会把 turn 发出去 —— 这里补杀,// 免得产生一次没人跟踪、可能与顺延重试重叠的执行。if (dispatchCancelled) {- this.deps.logger.warn?.('[runner] late accept after queued dispatch was cancelled; killing turn', {- scheduleId: schedule.id,- runId: ctx.runId,- sessionId,- });+ this.deps.logger.warn?.(+ '[runner] late accept after queued dispatch was cancelled; killing turn',+ {+ scheduleId: schedule.id,+ runId: ctx.runId,+ sessionId,+ },+ );endQueueWait(false);blockAcceptedDispatch(live, 'queued dispatch cancelled');return;@@ -1524,28 +1603,38 @@ export class MakerScheduleRunner implements ScheduleRunner {blockAcceptedDispatch(live, 'slot unavailable');return;}+ if (!live) {+ const unavailable = new Error(+ 'queued heartbeat live session unavailable before route sync and vendor dispatch',+ );+ failAfterAccept(unavailable);+ failDispatch(unavailable);+ blockAcceptedDispatch(undefined, 'session unavailable for queued route sync');+ return;+ }// 任务编辑器里选的 model/effort/来源在排队派发时刻热同步到会话(此回调// 运行于 vendor dispatch 之前,setModel 对本 turn 生效)—— 对齐直发路径// 的 4.4.1/4.4.2 语义,不让"任务改了模型且每轮都撞忙"的用户被静默忽略// (PR #972 review P2)。凭证形态需要切换的场景无法热切,跳过并留日志。- if (live) {- try {- await this.applyQueuedHeartbeatRouting(schedule, live, routingBaseline);- } catch (err) {- if (err instanceof QueuedRouteDisabledError) {- // 停用轴准入拒绝(PR #744 review 第六轮):这次排队心跳是新的付费调用,- // 目标路由已被停用时不能"保持 live 路由继续派发"。此刻仍在 vendor- // dispatch 之前 —— 取消这次派发(同 late-dispatch 路径),run 以明确错误- // 失败收口(不含 abort 字样 ⇒ 引擎按 failed 记录)。- failAfterAccept(err);- failDispatch(err);- blockAcceptedDispatch(live, 'route disabled');- return;- }- this.deps.logger.warn?.('[runner] queued heartbeat routing sync failed (non-fatal)', err);+ try {+ await this.applyQueuedHeartbeatRouting(schedule, live, routingBaseline);+ } catch (err) {+ if (err instanceof QueuedRouteDisabledError || err instanceof QueuedPiRouteSyncError) {+ // 停用轴准入拒绝(PR #744 review 第六轮):这次排队心跳是新的付费调用,+ // 目标路由已被停用时不能"保持 live 路由继续派发"。此刻仍在 vendor+ // dispatch 之前 —— 取消这次派发(同 late-dispatch 路径),run 以明确错误+ // 失败收口(不含 abort 字样 ⇒ 引擎按 failed 记录)。+ failAfterAccept(err);+ failDispatch(err);+ blockAcceptedDispatch(+ live,+ err instanceof QueuedPiRouteSyncError ? 'Pi route sync failed' : 'route disabled',+ );+ return;}+ this.deps.logger.warn?.('[runner] queued heartbeat routing sync failed (non-fatal)', err);}- if (live) waiterSlot.current = this.createTurnCompletionWaiter(live, ctx.onProgress);+ waiterSlot.current = this.createTurnCompletionWaiter(live, ctx.onProgress);// 与直发路径 onAccepted 的簿记对齐(落库/基线钩子除外,见方法头注释)。ctx.onTurnActive?.(sessionId);noteSilentStopUserSend(sessionId);@@ -1662,7 +1751,9 @@ export class MakerScheduleRunner implements ScheduleRunner {if (dispatched) return;if (!sq.isPromptTracked(sessionId, clientId)) {failDispatch(- new Error('queued heartbeat prompt was dropped before dispatch (queue cleared or recovery abandoned)'),+ new Error(+ 'queued heartbeat prompt was dropped before dispatch (queue cleared or recovery abandoned)',+ ),);return;}@@ -1751,13 +1842,18 @@ export class MakerScheduleRunner implements ScheduleRunner {private async applyQueuedHeartbeatRouting(schedule: Schedule,live: NonNullable<ReturnType<Maker['getSession']>>,- baseline: { model?: string; effort?: string; providerId: string | null },+ baseline: {+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId: string | null;+ },): Promise<void> {const explicitModel = schedule.model?.trim() ? schedule.model : undefined;const targetModel =- explicitModel- ?? (baseline.model?.trim() ? baseline.model : undefined)- ?? (live.model?.trim() ? live.model : defaultModelFor(schedule.agentKind));+ explicitModel ??+ (baseline.model?.trim() ? baseline.model : undefined) ??+ (live.model?.trim() ? live.model : defaultModelFor(schedule.agentKind));const explicitProviderId = schedule.providerId?.trim() ? schedule.providerId.trim() : null;const currentProviderId = getSessionProvider(live.id) ?? baseline.providerId;// 停用轴准入(PR #744 review 第五、六轮):排队分支在 fire 主路径的准入点之前@@ -1776,11 +1872,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 误按隐式默认裁决放行,随后照旧沿停用来源派发(PR #744 review 第八轮)。// 两者都缺才是真正的隐式默认(reroute 才有意义)。const routeProviderId = explicitProviderId ?? currentProviderId;- const verdict = await this.deps.checkModelRoute(- live.agentKind,- targetModel,- routeProviderId,- );+ const verdict = await this.deps.checkModelRoute(live.agentKind, targetModel, routeProviderId);if (verdict.kind === 'reject') {throw new QueuedRouteDisabledError(`schedule route unavailable: model "${targetModel}" is disabled in settings (${verdict.reason})`,@@ -1819,7 +1911,12 @@ export class MakerScheduleRunner implements ScheduleRunner {}this.deps.logger.info?.('[runner] queued heartbeat routing needs credential mode switch; keeping session routing this round',- { scheduleId: schedule.id, sessionId: live.id, fromModel: live.model, toModel: targetModel },+ {+ scheduleId: schedule.id,+ sessionId: live.id,+ fromModel: live.model,+ toModel: targetModel,+ },);return;}@@ -1828,12 +1925,27 @@ export class MakerScheduleRunner implements ScheduleRunner {// 真实运行值为基准判断是否需要覆盖(review P2)。effort 无 live getter,// 仍以 baseline 判断(setEffort 幂等,误判多调一次无害)。const modelChanged = explicitModel !== undefined && targetModel !== live.model;+ // 与直发路径一致:Pi 的 provider 是原生进程态。schedule 显式 model/source+ // 或停用轴改道时,需要把 provider-model 一起重申;只写 provider store 对+ // Pi BYOM 无效,即使 model 字符串没变也不能跳过。+ const mustSyncPiNativeRoute =+ live.agentKind === 'pi' && (explicitModel !== undefined || applyProviderId !== null);let modelApplied = true;- if (modelChanged) {+ if (modelChanged || mustSyncPiNativeRoute) {try {- await live.setModel(targetModel);+ if (mustSyncPiNativeRoute) {+ await live.setModel(targetModel, { providerId: nextProviderId });+ } else {+ await live.setModel(targetModel);+ }} catch (err) {modelApplied = false;+ if (mustSyncPiNativeRoute) {+ throw new QueuedPiRouteSyncError(+ `schedule Pi route sync failed before queued dispatch (model "${targetModel}", provider "${nextProviderId ?? 'cindy'}")`,+ { cause: err },+ );+ }this.deps.logger.warn?.('[runner] queued heartbeat setModel failed (non-fatal)', err);}}@@ -1895,6 +2007,9 @@ export class MakerScheduleRunner implements ScheduleRunner {if (applyProviderId) {setSessionProvider(live.id, applyProviderId);}+ if (live.agentKind === 'pi') {+ setSessionFastMode(live.id, baseline.fastMode === true);+ }if ((modelChanged && modelApplied) || (effortChanged && effortApplied) || applyProviderId) {await backfillSessionMeta(this.deps.getDb(),@@ -1935,8 +2050,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// scheduler.isRunSilenced 会变回 false,这里照常通知。// success 时跳过桌面/飞书通知(引擎落库会同时置 readAt,小红点也不亮)。// 失败不豁免 —— 异常必须可见,通知照发(fail-safe)。- const silenced =- finalRun.status === 'success' && !!this.scheduler?.isRunSilenced(ctx.runId);+ const silenced = finalRun.status === 'success' && !!this.scheduler?.isRunSilenced(ctx.runId);// 已被卡死守卫强制收口的 run:引擎早就把这一轮记成 failed 并按配置投过通知了。// 迟到 settle 的我们再投一条,用户会为同一轮收到两条(review #944 第十四轮 P1)。// 常见顺序恰好是"引擎先投、runner 几分钟后才 settle",所以只靠引擎侧挡不住。@@ -2295,10 +2409,7 @@ function normalizeSchedulerSendError(err: unknown): {};}-function isSessionRunningSendError(- err: unknown,- error: SanitizedSendOutcomeError,-): boolean {+function isSessionRunningSendError(err: unknown, error: SanitizedSendOutcomeError): boolean {if (error.errorCode === 'SESSION_RUNNING') return true;return err instanceof Error && err.message.startsWith('SESSION_RUNNING:');}diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex b464e4054c..1441d7c23c 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -203,12 +203,12 @@"viewUsageDetail": "查看任务用量详情","linkCopied": "链接已复制","sessionInfo": "任务信息",- "branches": "会话分支",+ "branches": "任务分支","branchCurrent": "当前",- "branchEmpty": "当前会话还没有可切换的分支。",+ "branchEmpty": "当前任务还没有可切换的分支。","branchEmptyEntry": "空节点",- "branchLoadFailed": "读取会话分支失败。",- "branchSwitchFailed": "切换会话分支失败。",+ "branchLoadFailed": "读取任务分支失败。",+ "branchSwitchFailed": "切换任务分支失败。","branchRunningBlocked": "任务运行中,结束后才能切换分支。","branchRole": {"user": "用户",