Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge: sync latest main for Pi review fixes
Chris120071552bf9
diff --cc apps/desktop/src/main/maker-ipc/register.tsindex 8752b0cb5c,7117c4c217..ad3dd4a981--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -5422,13 -5335,16 +5512,16 @@@ export function registerMakerIpc(maker});co.agentKind = dbMakerKind;}- // 意图制切换下,renderer 的 createOpts 快照构建于 send 事务内 apply 之前- // (乐观翻转后 agentKind 可能已一致,但 model/resume/providerId 仍是旧值,+ // 意图制切换 / 凭证形态切换下,renderer 与排队项的 createOpts 快照构建于 send+ // 事务内 apply 之前。agentKind 可能已一致,但 model/resume/providerId/effort/fast+ // 仍是旧值;// 尤其 resumeSessionId 可能是**旧引擎**的原生会话 id——resume 会以错误引擎- // 解释它)。lazy-create 时刻 DB 行是唯一真源,三个字段无条件对齐。+ // 解释它)。lazy-create 时刻 DB 行是唯一真源,执行字段无条件对齐。co.model = row.model ?? undefined;co.resumeSessionId = row.sdkSessionId ?? undefined;- co.providerId = row.providerId ?? undefined;+ co.providerId = row.providerId;+ co.effort = (row.effort ?? undefined) as CreateOpts['effort'];+ co.fastMode = !!row.fastMode;} catch {// 校正读库失败按原 opts 继续(与切换功能上线前行为一致)。}diff --cc apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 47569eb209,fb0d021126..6e1e401664--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@@ -371,113 -380,224 +399,331 @@@ describe('MakerScheduleRunner queued diexpect(latestNotifiedRun(notifier)).toMatchObject({ status: 'success' });});+ it('ignores events from a user turn or a different scheduler run', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true });+ const { runner } = createRunnerHarness(harness.session, queue.deps);++ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();++ harness.emit({+ type: 'text',+ data: { text: 'manual compact output', isFinal: true },+ source: 'claude-code',+ turnOrigin: { kind: 'user' },+ });+ harness.emit({+ type: 'done',+ data: {},+ source: 'claude-code',+ turnOrigin: { kind: 'user' },+ });+ harness.emit({+ type: 'done',+ data: {},+ source: 'claude-code',+ turnOrigin: {+ kind: 'scheduler',+ scheduleId: 'schedule-hb',+ scheduleName: 'PR #971 心跳',+ runId: 'other-run',+ },+ });+ // Session 在上一 turn 终态后会清 origin;此时 standalone 用户/compact 事件+ // 不能被仍在等待的 schedule waiter 误收。+ harness.emit({+ type: 'text',+ data: { text: 'originless standalone output', isFinal: true },+ source: 'claude-code',+ turnOrigin: undefined,+ });+ harness.emit({+ type: 'done',+ data: {},+ source: 'claude-code',+ turnOrigin: undefined,+ });+ await Promise.resolve();+ expect(harness.listenerCount()).toBe(1);++ harness.emit({+ type: 'text',+ data: { text: 'owned result', isFinal: true },+ source: 'claude-code',+ });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });++ await expect(firePromise).resolves.toMatchObject({ resultText: 'owned result' });+ });++ it('keeps the same run open when ordinary auto-resume claims a capacity interruption', async () => {+ let autoResumePending = true;+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => autoResumePending });+ const { runner } = createRunnerHarness(harness.session, queue.deps);++ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();+ harness.emit({+ type: 'error',+ data: { message: 'Selected model is at capacity.', isTerminal: true },+ source: 'claude-code',+ });+ // 同一失败 turn 的配对 done 不能把 schedule run 提前收成成功。+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });+ await Promise.resolve();+ expect(harness.listenerCount()).toBe(1);++ autoResumePending = false;+ harness.emit({ type: 'text', data: { text: 'continued result', isFinal: true }, source: 'claude-code' });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });++ await expect(firePromise).resolves.toMatchObject({+ sessionId: SESSION_ID,+ resultText: 'continued result',+ });+ });++ it('ignores a delayed done while the same run still owns the auto-resume claim', async () => {+ vi.useFakeTimers();+ try {+ let autoResumePending = true;+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => autoResumePending });+ const { runner } = createRunnerHarness(harness.session, queue.deps);++ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();+ harness.emit({+ type: 'error',+ data: { message: 'Selected model is at capacity.', isTerminal: true },+ source: 'claude-code',+ });+ await Promise.resolve();++ // 配对 done 晚于优化窗口到达时,仍应以 run claim 为准,不得提前 finish。+ await vi.advanceTimersByTimeAsync(251);+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });+ expect(harness.listenerCount()).toBe(1);++ // 生产路径在恢复 turn 的 pre-vendor 边界清除旧 claim。+ autoResumePending = false;+ // terminal error 后 Session 已清 origin;旧 attempt 的配对 done 即使迟到到+ // pre-vendor 窗口,也不能被当成新续跑的完成事件。+ harness.emit({+ type: 'done',+ data: {},+ source: 'claude-code',+ turnOrigin: undefined,+ });+ expect(harness.listenerCount()).toBe(1);+ harness.emit({+ type: 'text',+ data: { text: 'delayed continuation result', isFinal: true },+ source: 'claude-code',+ });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });++ await expect(firePromise).resolves.toMatchObject({+ sessionId: SESSION_ID,+ resultText: 'delayed continuation result',+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('fails the same run when a claimed auto-resume cannot be dispatched', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => true });+ const { runner } = createRunnerHarness(harness.session, queue.deps);++ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();+ harness.emit({+ type: 'error',+ data: { message: 'Selected model is at capacity.', isTerminal: true },+ source: 'claude-code',+ });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });+ await Promise.resolve();+ queue.failAutoResume();++ await expect(firePromise).rejects.toThrow('scheduled task auto-resume failed');+ expect(harness.listenerCount()).toBe(0);+ });++ it('cancels a claimed auto-resume when the schedule is paused or deleted', async () => {+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => 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));+ await queue.accept();+ harness.emit({+ type: 'error',+ data: { message: 'Selected model is at capacity.', isTerminal: true },+ source: 'claude-code',+ });+ await Promise.resolve();++ // 退避中没有活动 vendor turn;abort 必须直接撤销接管并结束 waiter。+ ctx.abortController.abort();++ await expect(firePromise).rejects.toThrow(/abort/i);+ expect(queue.cancelAutoResumeCalls).toEqual([+ { sessionId: SESSION_ID, runId: 'run-q1' },+ ]);+ expect(harness.listenerCount()).toBe(0);+ });++ it('does not let the previous auto-resume claim hide a deterministic error from the resumed turn', async () => {+ let autoResumePending = true;+ const harness = createSessionHarness(async () => ({ accepted: true }));+ const queue = createQueueHarness({ busy: true, autoResumePending: () => autoResumePending });+ const { runner } = createRunnerHarness(harness.session, queue.deps);++ const firePromise = runner.fire(heartbeatSchedule(), createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));+ await queue.accept();++ harness.emit({+ type: 'error',+ data: { message: 'Selected model is at capacity.', isTerminal: true },+ source: 'claude-code',+ });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });+ await Promise.resolve();+ expect(harness.listenerCount()).toBe(1);++ // Production clears the previous claim at the resumed turn's pre-vendor+ // boundary. A synchronous deterministic error does not create a new claim.+ autoResumePending = false;+ harness.emit({+ type: 'error',+ data: { message: 'authentication failed', isTerminal: true },+ source: 'claude-code',+ });+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });++ await expect(firePromise).rejects.toThrow('authentication failed');+ expect(harness.listenerCount()).toBe(0);+ });++ 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 });diff --cc apps/desktop/src/main/scheduler-host/runner.tsindex c1ba285c93,34d73b373f..5146062bd5--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@@ -1389,12 -1354,8 +1440,13 @@@ export class MakerScheduleRunner implemctx: 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;+ },+ options?: { sessionAlreadyBound?: boolean; onAccepted?: () => void },): Promise<FireResult> {const headlessTurn = {closed: false,@@@ -1425,13 -1387,9 +1478,14 @@@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,+ options?: { sessionAlreadyBound?: boolean; onAccepted?: () => void },): Promise<FireResult> {const sq = this.deps.schedulerQueue;if (!sq) throw new Error('fireHeartbeatViaQueue requires schedulerQueue dep');@@@ -1619,25 -1567,30 +1675,31 @@@// 运行于 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);}- waiterSlot.current = this.createTurnCompletionWaiter(live, ctx.onProgress);+ if (live) {+ waiterSlot.current = this.createTurnCompletionWaiter(live, {+ onProgress: ctx.onProgress,+ origin,+ requireTurnOrigin: true,+ });+ }// 与直发路径 onAccepted 的簿记对齐(落库/基线钩子除外,见方法头注释)。ctx.onTurnActive?.(sessionId);noteSilentStopUserSend(sessionId);diff --cc apps/desktop/src/preload/preload.tsindex a262875b82,2d8fa98e4a..9617db8d1d--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@@ -4699,8 -4701,19 +4706,19 @@@ contextBridge.exposeInMainWorld('electrproviderId?: string | null,effort?: string,fastMode?: boolean,- ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean }> =>- ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }> =>++ ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }> =>ipcRenderer.invoke('maker:switch-session-agent', sessionId, targetAgentKind, model, providerId, effort, fastMode),+ // 读 main 权威的 pending 切换意图(内存态,不落库)。重开视图 / 远程会话重连后+ // 用它恢复乐观显示——否则用户登记的意图在 UI 上凭空消失,下一条消息却按意图切换。+ getSessionAgentSwitchIntent: (+ sessionId: string,+ ): Promise<{- targetAgentKind: 'claude-code' | 'codex';++ targetAgentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ providerId: string | null;+ effort?: string;+ fastMode?: boolean;+ } | null> => ipcRenderer.invoke('maker:get-session-agent-switch-intent', sessionId),// effort/mode 透传 string —— 合法值由 maker capabilities 在运行时校验,// preload 不重复枚举 (避免 capabilities 加新值时这里也要改)。setEffort: (sessionId: string, effort: string): Promise<void> =>diff --cc apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex fec4f208d6,b6e4ed3e05..bc305f2af3--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@@ -1209,14 -1242,82 +1245,89 @@@ export function ChatInput(// device-link 远程会话:能力(模型 / fast / effort)从被控端读;本地会话 deviceLinkDeviceId undefined → 本地。const ccCaps = useAgentCapabilities('claude-code', deviceLinkDeviceId);const codexCaps = useAgentCapabilities('codex', deviceLinkDeviceId);+ const piCaps = useAgentCapabilities('pi', deviceLinkDeviceId);+ const activeAgentCapabilities =+ agentKind === 'codex'+ ? codexCaps.capabilities+ : agentKind === 'pi'+ ? piCaps.capabilities+ : ccCaps.capabilities;+ // session-agent-switch 入口门控。device-link 远程会话读**被控端**的值;除了基础+ // supportsSessionAgentSwitch,还必须有 v2 CAS 能力。同引擎 no-op 的安全收尾依赖 host+ // 返回修订号,只有基础位的旧 host 无法把自己的 clear push 与外部 ABA 关联,不能开放+ // 一个会随机吞掉模型重选的入口。本机会话恒可用——main 与 renderer 同版本,不能因+ // capabilities 还没加载完而闪掉入口。+ // SSH 远程(remoteHostId)是另一套引擎生命周期,继续不支持,由调用点单独排除。+ // Orca 会话(lead / worker)同样排除:被控端 handler 对带 orcaRole 的会话一律拒+ // UNSUPPORTED_CAPABILITY。角色未加载(undefined)也 fail-closed,避免冷启动短暂露出入口。+ const ccSupportsSessionAgentSwitch =+ ccCaps.capabilities?.supportsSessionAgentSwitch === true &&+ ccCaps.capabilities.supportsSessionAgentSwitchCas === true;+ const codexSupportsSessionAgentSwitch =+ codexCaps.capabilities?.supportsSessionAgentSwitch === true &&+ codexCaps.capabilities.supportsSessionAgentSwitchCas === true;+ // 此能力与原子 model-selection payload 同版发布。旧被控端会忽略 SET_MODEL 第 5 参,+ // 因此缺能力位时保留原来的 SET_MODEL → SET_EFFORT → SET_FAST 兼容链;同引擎+ // reselect 入口本就要求 CAS=true,不会退回这条非原子路径。+ const remoteAtomicModelSelectionSupported =+ ccCaps.capabilities?.supportsSessionAgentSwitchCas === true ||+ codexCaps.capabilities?.supportsSessionAgentSwitchCas === true;+ const sessionAgentSwitchSupported =+ sessionOrcaRole === null &&+ (!deviceLinkDeviceId || ccSupportsSessionAgentSwitch || codexSupportsSessionAgentSwitch);++ // 切换写入的串行链与写序号都按 session 存在**模块级**协调层(agentSwitchCoordinator),+ // 不放组件 ref:用户切走再切回时旧组件已卸载但 invoke 仍在飞,新组件若另起空队列 /+ // 归零序号,两个请求会重新并发、旧 ack 会被误判成新鲜。理由与取舍见该模块头注释。+ // 链路重连代际:deviceId 在断链重连期间保持不变,只靠它当依赖的话读回永远不会重试。+ // 断链期间发出的读回会失败(catch 吞掉),断链期间被控端 / 另一控制端改的意图其+ // sessions:patched 推送也收不到 —— 恢复连接后必须重读一次,否则 composer 会一直+ // 停在过期引擎上。非 connected → connected 的每次跃迁 +1,驱动下方 effect 重跑。+ const remoteConnStatus = useRemoteSessionConnection(deviceLinkDeviceId);+ const [remoteReconnectEpoch, setRemoteReconnectEpoch] = useState(0);+ const remoteWasConnectedRef = useRef(false);+ useEffect(() => {+ const connected = remoteConnStatus === 'connected';+ if (connected && !remoteWasConnectedRef.current) setRemoteReconnectEpoch((n) => n + 1);+ remoteWasConnectedRef.current = connected;+ }, [remoteConnStatus]);++ // 会话打开时读回 main 的权威 pending 意图。意图是 main 的内存态、不落库,+ // renderer 换窗口 / 重开视图 / LRU 驱逐后本地镜像为空,不读回就会出现「UI 显示旧引擎、+ // 下一条消息却按意图切换」的错位。device-link 会话直连稳定 deviceId;本地会话走+ // 本机 maker。SSH 是另一套引擎生命周期,继续排除。+ useEffect(() => {+ if (!sessionId || remoteHostId) return;+ let cancelled = false;+ const writeSeq = getAgentSwitchWriteSeq(sessionId);+ const intentRev = makerChatStore.getAgentSwitchIntentRev(sessionId);+ const switchApi = deviceLinkDeviceId+ ? makerApiForDevice(deviceLinkDeviceId)+ : makerApiFor(sessionId);+ void switchApi+ .getSessionAgentSwitchIntent(sessionId)+ .then((authoritativeIntent) => {+ const fresh = isAgentSwitchResponseFresh({+ // 会话在往返期间被切走 → 这次响应不属于当前视图,丢弃。+ cancelled: cancelled || !isSessionScopeCurrent(sessionId, currentSessionIdRef.current),+ writeSeqAtStart: writeSeq,+ writeSeqNow: getAgentSwitchWriteSeq(sessionId),+ intentRevAtStart: intentRev,+ intentRevNow: makerChatStore.getAgentSwitchIntentRev(sessionId),+ });+ if (!fresh) return;+ makerChatStore.mirrorAgentSwitchIntent(sessionId, authoritativeIntent);+ })+ .catch(() => {+ // 老被控端未收录该 channel(CHANNEL_NOT_ALLOWED)、断链或本地读取失败:保留已有镜像,+ // 不擦用户已登记的选择(入口本身已按 capabilities 隐藏)。+ });+ return () => {+ cancelled = true;+ };+ }, [sessionId, deviceLinkDeviceId, remoteHostId, remoteReconnectEpoch]);+// cycle-permission-mode 快捷键 (默认 Shift+Tab) 的轮切候选 —— 与// PermissionSelector 用同一份 capabilities.permissionModes 列表, 键盘轮切// 与下拉菜单看到的顺序一致。vendorKey 未锁定时按 PermissionSelector 的@@@ -4063,14 -4215,10 +4236,14 @@@effort: newEffort,fastMode: targetFast,});- if (makerChatStore.getSnapshot(sessionId).agentStatus.isRunning) {+ if (makerChatStore.getSnapshot(sourceSessionId).agentStatus.isRunning) {toast.success(t('newChat.chatInput.agentSwitch.deferred', {- agent: targetAgentKind === 'codex' ? 'Codex' : 'Claude Code',+ agent: targetAgentKind === 'codex'+ ? 'Codex'+ : targetAgentKind === 'pi'+ ? 'Pi'+ : 'Claude Code',model: newModelId,}),{ duration: 4000 },diff --cc apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 18e9effa6a,8320d8d7e8..3a7154fed9--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@@ -561,8 -558,7 +561,7 @@@ function ModelSelectorContentView(agentSwitch?.currentVendor ?? vendorKey ?? 'cc',);const browseSwitchPendingRef = useRef(false);- const agentSwitchQueueRef = useRef<Promise<void>>(Promise.resolve());- const handleBrowseVendorChange = async (next: 'cc' | 'codex') => {+ const handleBrowseVendorChange = async (next: 'cc' | 'codex' | 'pi') => {if (interactionDisabled || next === browseVendor || browseSwitchPendingRef.current) return;// 返回当前引擎(含已有意图时浏览原引擎准备撤销)不需要确认;只有从// currentVendor 进入另一 Agent 浏览态才调用上层风险确认。确认前绝不翻分段。@@@ -592,20 -587,14 +591,15 @@@targetProviderId: string | null,) => {if (!agentSwitch) return;- const run = () => agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);- // 配置面板保持可连续操作,但切换事务必须按点击顺序执行:否则较早的请求可能- // 较晚完成并覆盖用户最后一次选择。失败也不能阻断后续已排队的意图。- agentSwitchQueueRef.current = agentSwitchQueueRef.current- .then(run, run)- .then(- () => undefined,- () => undefined,- );+ // 立即交给调用方同步登记目标 session 的 pending token。真正的顺序由+ // agentSwitchCoordinator 按 session 串行;组件级 Promise 队列会把不同 session+ // 错误地串在一起,并在回调尚未启动时留下可发送窗口。+ void agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);};- // 同时拉两个 agent —— vendorKey 不传时把两边模型一起展示。hooks 必须按固定顺序调用。+ // 同时拉三个 agent —— vendorKey 不传时把三边模型一起展示。hooks 必须按固定顺序调用。const cc = useAgentCapabilities('claude-code', deviceId);const codex = useAgentCapabilities('codex', deviceId);+ const pi = useAgentCapabilities('pi', deviceId);// 本机折扣 GPT 仍按本机 API key gate;device-link 必须只看被控端 provider 状态。// 旧被控端不支持 provider:list 时按远端 capabilities 退化,不得误用控制端 key。const { hasSavedKey } = useApiKey();diff --cc apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 613600abd1,01c49d612d..e633e8deeb--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@@ -3572,7 -3563,16 +3572,10 @@@ export function CCAgentSessionView(sessionId={sessionId}// session=null 是冷启动 / 直链 GET 尚未回流的合法首帧;显式传 null,// 让 ChatInput 暂不显示 Agent 身份,不能跟随 displayAgentKind 的 cc 回退。- runtimeAgentKind={- session- ? session.agentKind === 'codex'- ? 'codex'- : 'claude-code'- : null- }+ runtimeAgentKind={session ? dbToMakerAgentKind(session.agentKind) : null}+ // 协同会话不参与跨引擎切换;session 未加载时保留 undefined 未知态,+ // 仅在完整元数据确认非 Orca 后传 null 开放入口。+ sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}initialWorkingDir={session?.workingDir}remoteHostId={session?.remoteHostId ?? null}deviceLinkDeviceId={remoteDeviceId}diff --cc apps/desktop/src/renderer/lib/makerChatStore.tsindex 9c604adeb4,ce0100571a..bd5ec08eb3--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@@ -748,9 -748,16 +749,16 @@@ export interface SessionChatState* Codex reducer。ensureInitialMessages 从 DB sessions.agent_kind 读出来灌进。* 默认 'claude-code' 兼容老路径(老 session row 没有此字段时按 Claude 处理)。*/- agentKind: 'claude-code' | 'codex';+ agentKind: 'claude-code' | 'codex' | 'pi';/** 下一条消息发送时才由 main 应用的跨引擎切换意图。 */agentSwitchIntent: AgentSwitchIntentRecord | null;+ /**+ * 意图的单调修订号:**任何来源**(本端登记/撤销、被控端 push 回流、另一窗口)真正改变+ * 意图时 +1,只增不减。异步读回的新鲜度判定必须用它,不能比较意图值本身——外部把意图+ * 从 null 改成非空又清回 null 时,值与引用都会回到相等,过期响应会被误判为新鲜而复活+ * 已取消的意图(ABA)。+ */+ agentSwitchIntentRev: number;/*** Remote codex target (P2): SSH host alias from `@cindy/maker-remote-ssh`* pool。null/undefined = 本地 session。ensureInitialMessages 从 DB@@@ -9306,9 -9376,78 +9399,78 @@@ function getAgentSwitchIntent(sessionIdreturn sessions.get(sessionId)?.agentSwitchIntent ?? null;}+ /**+ * 意图的单调修订号(不存在的会话按 0)。异步读回的新鲜度判定读它——值比较会被 ABA+ * (null → 已登记 → null)骗过,修订号不会。+ */+ function getAgentSwitchIntentRev(sessionId: string): number {+ return sessions.get(sessionId)?.agentSwitchIntentRev ?? 0;+ }++ /**+ * main 的 pending 意图投影(PublicAgentSwitchIntent,字段名 targetAgentKind)收窄成+ * store 记录(target)。形状不合法 / 非意图 → null,按「无意图」处理。+ */+ function normalizeAgentSwitchIntent(value: unknown): AgentSwitchIntentRecord | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const item = value as Record<string, unknown>;+ if (item.targetAgentKind !== 'claude-code' && item.targetAgentKind !== 'codex') return null;+ if (typeof item.model !== 'string' || item.model.length === 0) return null;+ // providerId 缺失按 null(与 main projectPendingAgentSwitchIntent 的 `?? null` 对齐);+ // 只有出现非 string / 非空值的脏值才判非法,避免协议演进时静默丢掉合法意图。+ if (item.providerId != null && typeof item.providerId !== 'string') return null;+ if (item.effort !== undefined && typeof item.effort !== 'string') return null;+ if (item.fastMode !== undefined && typeof item.fastMode !== 'boolean') return null;+ return {+ target: item.targetAgentKind,+ model: item.model,+ providerId: typeof item.providerId === 'string' ? item.providerId : null,+ ...(typeof item.effort === 'string' && item.effort.length > 0 ? { effort: item.effort } : {}),+ ...(typeof item.fastMode === 'boolean' ? { fastMode: item.fastMode } : {}),+ };+ }++ function agentSwitchIntentEquals(+ a: AgentSwitchIntentRecord | null,+ b: AgentSwitchIntentRecord | null,+ ): boolean {+ if (a === b) return true;+ if (!a || !b) return false;+ return (+ a.target === b.target &&+ a.model === b.model &&+ a.providerId === b.providerId &&+ a.effort === b.effort &&+ a.fastMode === b.fastMode+ );+ }++ /**+ * 「意图的权威态在会话所在端」:被控端(或本机另一个窗口)登记 / 清除 pending 意图后,+ * main 经 sessions:patched 广播 agentSwitchIntent 字段;device-link 远程会话打开时+ * 控制端还会主动读回一次。两条 sink 都汇到这里。+ *+ * 幂等:值等价即 no-op —— 本端乐观登记后收到自己的回声不会重建对象、不触发多余重渲染,+ * 也不会与用户正在进行的选择打架。null / 非法值 = 无意图 → 清除。+ */+ function mirrorAgentSwitchIntent(sessionId: string, value: unknown): void {+ if (!sessionId) return;+ const next = normalizeAgentSwitchIntent(value);+ if (agentSwitchIntentEquals(sessions.get(sessionId)?.agentSwitchIntent ?? null, next)) return;+ if (!next) {+ clearAgentSwitchIntent(sessionId);+ return;+ }+ setState(sessionId, (s) => ({+ ...s,+ agentSwitchIntent: next,+ agentSwitchIntentRev: s.agentSwitchIntentRev + 1,+ }));+ }+function setSessionRuntime(sessionId: string,- opts: { agentKind?: 'claude-code' | 'codex'; fastMode?: boolean; planModeEnabled?: boolean },+ opts: { agentKind?: 'claude-code' | 'codex' | 'pi'; fastMode?: boolean; planModeEnabled?: boolean },): void {if (!sessionId) return;setState(sessionId, (s) => {diff --cc apps/desktop/src/renderer/vite-env.d.tsindex dacb67ce6b,59c21cd3ee..f1de441274--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@@ -4445,7 -4453,20 +4456,20 @@@ interface ElectronAPIproviderId?: string | null,effort?: string,fastMode?: boolean,- ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean }>;- ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }>;++ ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }>;+ /**+ * 读 main 权威的 pending 切换意图(内存态,不落库;无意图 → null)。+ * 重开视图 / device-link 远程会话重连后恢复乐观显示用。+ */+ getSessionAgentSwitchIntent: (+ sessionId: string,+ ) => Promise<{- targetAgentKind: 'claude-code' | 'codex';++ targetAgentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ providerId: string | null;+ effort?: string;+ fastMode?: boolean;+ } | null>;// effort/mode 透传 string —— 合法值由 maker capabilities 决定, vite-env 不重复枚举setEffort: (sessionId: string, effort: string) => Promise<void>;setPermissionMode: (sessionId: string, mode: string) => Promise<void>;