Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 冷 Pi 切模不再为窗口核实冷启动运行时 (#4835)
Yunjin Zhangc7186a37ac7c
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsindex 48ffecf251..7df1f30ea4 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@ -998,6 +998,50 @@ describe('session runtime control wiring', () => {expect(setModel).toContain('Pi current runtime could not be verified');});+ it('skips the cold Pi window rehydration when the live usage leaves the target headroom', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ // 冷启动核实(2~3s)必须经预检:目标窗口对**已知占用**有余量时不再拉起运行时,+ // 路由照常落定、下一次发送按目标窗口懒重建;danger/overflow 仍走原核实路径。+ const pressurePreflight = setModel.indexOf('shouldSkipColdPiWindowRehydration({');+ const rehydrate = setModel.indexOf(+ 'await rehydrateColdPiRuntimeForWindowVerification(sessionId)',+ );+ expect(pressurePreflight).toBeGreaterThan(-1);+ expect(pressurePreflight).toBeLessThan(rehydrate);+ // 占用只能取 runtime 关闭时固化的 live 读数:sessions.context_tokens 可能因+ // 中断 / 崩溃低报,拿它判「有余量」会绕过缩窗交接(Greptile P1)。+ const liveUsageRead = setModel.indexOf('getSessionLastLiveUsage(sessionId)');+ expect(liveUsageRead).toBeGreaterThan(-1);+ expect(liveUsageRead).toBeLessThan(pressurePreflight);+ expect(setModel).toContain('set-model: skipped cold Pi window verification');+ expect(setModel).toContain('coldPiRouteWithoutLiveWindowCheck = true;');+ // 终态活进程核验必须同步跳过,否则只是换成 'Pi target runtime could not be verified'。+ const finalBlockStart = setModel.indexOf('const piSessionAfterRouteChange =');+ const finalVerification = setModel.indexOf(+ 'Pi target runtime could not be verified',+ finalBlockStart,+ );+ expect(finalBlockStart).toBeGreaterThan(-1);+ expect(finalVerification).toBeGreaterThan(finalBlockStart);+ expect(setModel.slice(finalBlockStart, finalVerification)).toContain(+ '!coldPiRouteWithoutLiveWindowCheck',+ );+ // 固化点:每个会话关闭时先记 live 用量,再走关闭清理。+ const closeCaptureLine = 'rememberSessionLastLiveUsage(session.id, session.getUsageSnapshot?.());';+ const closeCapture = registerSource.indexOf(closeCaptureLine);+ const closeHook = registerSource.indexOf(+ 'finalizeClosedSession: (session: WiredSession, context) => {',+ );+ expect(closeCapture).toBeGreaterThan(-1);+ expect(closeHook).toBeGreaterThan(-1);+ expect(closeCapture).toBeGreaterThan(closeHook);+ expect(closeCapture - closeHook).toBeLessThan(600);+ });+it('closes a cold Pi runtime when route persistence fails after rehydrate', () => {const setModel = handlerBody(registerSource,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionLastLiveUsage.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionLastLiveUsage.test.tsnew file mode 100644index 0000000000..205a4fa59c--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionLastLiveUsage.test.ts@@ -0,0 +1,42 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ _resetSessionLastLiveUsageForTests,+ forgetSessionLastLiveUsage,+ getSessionLastLiveUsage,+ rememberSessionLastLiveUsage,+} from '../sessionLastLiveUsage';++afterEach(() => {+ _resetSessionLastLiveUsageForTests();+});++describe('sessionLastLiveUsage', () => {+ it('remembers the live usage captured when the runtime closes', () => {+ rememberSessionLastLiveUsage('session-1', { contextTokens: 26_921, contextWindow: 1_000_000 });+ expect(getSessionLastLiveUsage('session-1')).toMatchObject({+ contextTokens: 26_921,+ contextWindow: 1_000_000,+ });+ expect(getSessionLastLiveUsage('session-1')!.capturedAtMs).toBeGreaterThan(0);+ });++ it('keeps the earlier trustworthy value when the close snapshot is missing or malformed', () => {+ rememberSessionLastLiveUsage('session-1', { contextTokens: 26_921, contextWindow: 1_000_000 });+ rememberSessionLastLiveUsage('session-1', undefined);+ rememberSessionLastLiveUsage('session-1', { contextTokens: Number.NaN, contextWindow: 1 });+ rememberSessionLastLiveUsage('session-1', { contextTokens: -1, contextWindow: 1 });+ rememberSessionLastLiveUsage('session-1', { contextTokens: 1, contextWindow: Number.NaN });+ expect(getSessionLastLiveUsage('session-1')?.contextTokens).toBe(26_921);+ });++ it('forgets a session entry', () => {+ rememberSessionLastLiveUsage('session-1', { contextTokens: 1, contextWindow: 2 });+ forgetSessionLastLiveUsage('session-1');+ expect(getSessionLastLiveUsage('session-1')).toBeUndefined();+ });++ it('treats a never-closed session as unknown (conservative cold-start fallback)', () => {+ expect(getSessionLastLiveUsage('session-unknown')).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 13f970a3ee..6e14fc960c 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -119,6 +119,7 @@ import {buildDeferredRuntimeSelectionProfile,nextDeferredModelWindowRetry,planUserRuntimeModelSwitch,+ shouldSkipColdPiWindowRehydration,} from '../../shared/runtimeModelSwitchGate.js';import type { DesktopCommandContext } from '../commands/index.js';import { getDesktopCommandRegistry } from '../commands/index.js';@@ -815,6 +816,10 @@ import {} from '../maker-host/codex-local-sessions.js';import { hydrateQueuedAgentReferences } from './agentInputReferences.js';import { agentHandoffPending } from './agentHandoffPendingSingleton.js';+import {+ getSessionLastLiveUsage,+ rememberSessionLastLiveUsage,+} from './sessionLastLiveUsage.js';import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';import { buildCompletedPlanGuardNote, buildPlanReconcileNote } from './planReconcile.js';import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';@@ -4436,6 +4441,9 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSessiondeferredProductTurnFailureGate.clearSession(session.id, session);},finalizeClosedSession: (session: WiredSession, context) => {+ // 关闭前固化 live 用量(见 sessionLastLiveUsage.ts):冷 Pi 切模的窗口核实+ // 预检用它代替可能低报的 DB 快照(Greptile P1)。+ rememberSessionLastLiveUsage(session.id, session.getUsageSnapshot?.());finalizeSessionClose(context.closedDirectAbortBoundary !== null, {clearTurnState: () => {sessionTurnActivityTracker.deleteSession(session.id);@@ -16104,6 +16112,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};let liveSessionBeforeRouteChange = maker.getSession(sessionId);let rehydratedColdPiRuntime: typeof liveSessionBeforeRouteChange = undefined;+ // 冷 Pi 但没做活进程窗口核验(本轮新增:目标窗口对已知占用有余量、压力预检证明+ // 核实不可能改变结论,于是跳过了冷启动核实):目标 route 照常落定,由下一次发送+ // 按目标窗口懒创建;apply 之后的终态活进程核验必须同步跳过,否则只会换成+ // 'Pi target runtime could not be verified'。+ let coldPiRouteWithoutLiveWindowCheck = false;const targetProviderId =effectiveProviderId === undefined? (previousRuntime.pendingCredentialSwitch?.providerId ?? currentProviderId)@@ -16170,25 +16183,64 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));}if (!liveSessionBeforeRouteChange) {- try {- await rehydrateColdPiRuntimeForWindowVerification(sessionId);- } catch {- throwIpcError(- localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),- 'Pi current runtime could not be verified; runtime selection was not changed',- );- }- liveSessionBeforeRouteChange = maker.getSession(sessionId);- if (!liveSessionBeforeRouteChange) {- throwIpcError(- localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),- 'Pi current runtime could not be verified; runtime selection was not changed',- );+ // 冷启动核实(2~3s)只在它可能改变决策时才做:目标窗口对**已知占用**已到+ // danger/overflow 才可能需要缩窗交接 / 二次确认;有余量时任何「当前窗口」+ // 读数都不会触发交接(见 assessRuntimeModelSwitchGate 的 fail-open 矩阵),+ // 让用户白等一次 Pi 冷启动就是纯卡顿(2026-09-21 实报)。+ // 占用取 runtime **关闭时固化的 live 读数**(sessionLastLiveUsage),+ // 不读 sessions.context_tokens:后者只在 turn 正常收尾时落库,中断 / 崩溃+ // 后可能低报真实占用,拿它证明「目标还有余量」会绕过缩窗交接+ // (Greptile P1,2026-09-21);进程重启 / 硬杀后没有缓存时自动回退到核实。+ // 无原生会话的冷 Pi 也不在本预检范围内(维持既有 fail-closed 语义)。+ const coldPiLastLiveUsage = getSessionLastLiveUsage(sessionId);+ const coldPiTargetContextWindow = lookupVerifiedContextWindow(+ (_agentKind, modelId, pid) =>+ resolveConfiguredContextWindow(getActiveCatalog(), 'pi', pid, modelId),+ model,+ targetRouteProviderId,+ 'pi',+ );+ const skipColdPiWindowVerification =+ !!runtimeStatus.sdkSessionId &&+ shouldSkipColdPiWindowRehydration({+ contextTokens: coldPiLastLiveUsage?.contextTokens ?? null,+ targetContextWindow: coldPiTargetContextWindow,+ });+ if (skipColdPiWindowVerification) {+ coldPiRouteWithoutLiveWindowCheck = true;+ log.info('set-model: skipped cold Pi window verification', {+ sessionId,+ reason: 'target-window-has-headroom',+ contextTokens: coldPiLastLiveUsage?.contextTokens ?? null,+ contextWindow: coldPiLastLiveUsage?.contextWindow ?? null,+ capturedAtMs: coldPiLastLiveUsage?.capturedAtMs ?? null,+ targetContextWindow: coldPiTargetContextWindow,+ fromModel: currentRuntimeModel ?? null,+ toModel: model,+ currentProviderId,+ nextProviderId: targetRouteProviderId,+ });+ } else {+ try {+ await rehydrateColdPiRuntimeForWindowVerification(sessionId);+ } catch {+ throwIpcError(+ localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),+ 'Pi current runtime could not be verified; runtime selection was not changed',+ );+ }+ liveSessionBeforeRouteChange = maker.getSession(sessionId);+ if (!liveSessionBeforeRouteChange) {+ throwIpcError(+ localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),+ 'Pi current runtime could not be verified; runtime selection was not changed',+ );+ }+ rehydratedColdPiRuntime = liveSessionBeforeRouteChange;+ currentRuntimeModel = liveSessionBeforeRouteChange.model;+ runtimeRouteChanged =+ currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId;}- rehydratedColdPiRuntime = liveSessionBeforeRouteChange;- currentRuntimeModel = liveSessionBeforeRouteChange.model;- runtimeRouteChanged =- currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId;}}let targetContextWindow: number | undefined;@@ -16577,7 +16629,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)runtimeAgentKind === 'pi' &&runtimeRouteChanged &&result.status !== 'deferred' &&- !modelWindowRebuilt+ !modelWindowRebuilt &&+ !coldPiRouteWithoutLiveWindowCheck) {if (!piSessionAfterRouteChange) {restoreControlStores();diff --git a/apps/desktop/src/main/maker-ipc/sessionLastLiveUsage.ts b/apps/desktop/src/main/maker-ipc/sessionLastLiveUsage.tsnew file mode 100644index 0000000000..acd975ac91--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/sessionLastLiveUsage.ts@@ -0,0 +1,57 @@+import type { UsageSnapshot } from '@cindy/maker-core';++/**+ * 会话最近一次 **live runtime** 的用量快照(进程内,不落库)。+ *+ * 冷 Pi 的窗口核实预检需要「当前占用」来判断目标窗口还有没有余量,但+ * `sessions.context_tokens` 只在 turn 正常收尾(`status: isRunning=false + Done`)时+ * 落库:turn 被中断 / 进程被杀 / 退出时在飞都可能留下低报的旧值,拿它证明「目标有余量」+ * 会绕过缩窗交接(Greptile P1,2026-09-21)。+ *+ * 这里改在 runtime **关闭的那一刻**直接读 live 快照(会话对象自己的用量记账,是当前+ * 唯一权威来源),并且只在**同一次进程生命周期内**可用:+ * - 进程重启后没有缓存 → 预检自动回退到冷启动核实(保守,代价是一次 2~3s);+ * - 没走到 close 的硬杀同样没有缓存 → 回退核实。+ *+ * 因此只要读得到缓存,就一定是「这次变冷之前最后一次 live 读数」,不存在低报窗口。+ * 条目按会话保留(进程内生命周期,数量与本次运行关闭过的会话数同阶)。+ */+export interface SessionLastLiveUsage {+ contextTokens: number;+ contextWindow: number;+ capturedAtMs: number;+}++const lastLiveUsageBySession = new Map<string, SessionLastLiveUsage>();++function positiveOrZero(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;+}++/** 关闭 runtime 时固化 live 用量;快照缺失或字段非法时不动缓存(保留更早的可信值)。 */+export function rememberSessionLastLiveUsage(+ sessionId: string,+ usage: Pick<UsageSnapshot, 'contextTokens' | 'contextWindow'> | undefined | null,+): void {+ if (!sessionId || !usage) return;+ const contextTokens = positiveOrZero(usage.contextTokens);+ const contextWindow = positiveOrZero(usage.contextWindow);+ if (contextTokens === null || contextWindow === null) return;+ lastLiveUsageBySession.set(sessionId, {+ contextTokens,+ contextWindow,+ capturedAtMs: Date.now(),+ });+}++export function getSessionLastLiveUsage(sessionId: string): SessionLastLiveUsage | undefined {+ return lastLiveUsageBySession.get(sessionId);+}++export function forgetSessionLastLiveUsage(sessionId: string): void {+ lastLiveUsageBySession.delete(sessionId);+}++export function _resetSessionLastLiveUsageForTests(): void {+ lastLiveUsageBySession.clear();+}diff --git a/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts b/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.tsindex 9c99cd4ce5..2a1669a21a 100644--- a/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts+++ b/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts@@ -5,6 +5,7 @@ import {applyWithVerifiedModelWindow,buildDeferredRuntimeSelectionProfile,nextDeferredModelWindowRetry,+ shouldSkipColdPiWindowRehydration,} from '../runtimeModelSwitchGate';const million = 1_000_000;@@ -213,6 +214,53 @@ describe('assessRuntimeModelSwitchGate', () => {});});+describe('shouldSkipColdPiWindowRehydration', () => {+ it.each([+ {+ name: 'live usage far below the target window → skip the 2~3s cold start',+ input: { contextTokens: 26_921, targetContextWindow: million },+ want: true,+ },+ {+ name: 'empty context → nothing to protect, skip',+ input: { contextTokens: 0, targetContextWindow: twoHundredK },+ want: true,+ },+ {+ name: 'warn band still hot-applies (no rebuild) → skip',+ input: { contextTokens: 150_000, targetContextWindow: twoHundredK },+ want: true,+ },+ {+ name: 'danger band can need the shrink handoff → verify',+ input: { contextTokens: 185_000, targetContextWindow: twoHundredK },+ want: false,+ },+ {+ name: 'overflow can need confirmation → verify',+ input: { contextTokens: 240_000, targetContextWindow: twoHundredK },+ want: false,+ },+ {+ name: 'missing live usage must not skip verification',+ input: { contextTokens: null, targetContextWindow: twoHundredK },+ want: false,+ },+ {+ name: 'unknown target window must not skip verification',+ input: { contextTokens: 26_921, targetContextWindow: null },+ want: false,+ },+ {+ name: 'non-positive target window is not a verified ceiling',+ input: { contextTokens: 26_921, targetContextWindow: 0 },+ want: false,+ },+ ])('$name', ({ input, want }) => {+ expect(shouldSkipColdPiWindowRehydration(input)).toBe(want);+ });+});+describe('buildDeferredRuntimeSelectionProfile', () => {it('keeps the clicked high + Fast on the pending profile', () => {expect(diff --git a/apps/desktop/src/shared/runtimeModelSwitchGate.ts b/apps/desktop/src/shared/runtimeModelSwitchGate.tsindex 24e5eec78f..6efc6d782a 100644--- a/apps/desktop/src/shared/runtimeModelSwitchGate.ts+++ b/apps/desktop/src/shared/runtimeModelSwitchGate.ts@@ -11,6 +11,7 @@ import { composeAtomicModelSelection } from '@cindy/model-providers';import {assessModelSwitchContext,MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,+ shouldHandoffAfterContextAssessment,} from './modelSwitchAssessment.js';export type RuntimeModelSwitchGate = {@@ -97,6 +98,44 @@ export function assessRuntimeModelSwitchGate(return { skipRebuild: false, defer: false };}+/**+ * 冷 Pi 的窗口核实要**冷启动一个完整运行时**(实测 2~3s:asset-prep → `pi list` →+ * Pi boot),是「点一次切模型等一次」的卡顿来源。但核实读到的**当前窗口 / 占用**+ * 只服务于一个判定:缩窗交接(见 `assessRuntimeModelSwitchGate`:`skipRebuild=false`+ * 要求 `target < current` 且占用已到 danger/overflow)。因此当**已知占用**相对+ * **目标窗口**还没到 danger/overflow 时,核实结果不可能改变结论 —— 矩阵里压根不会+ * 走换窗重建,冷启动是纯等待。+ *+ * `contextTokens` 必须来自 **live runtime 的最后一次读数**(关闭时固化,见+ * `maker-ipc/sessionLastLiveUsage.ts`),不能直接用 `sessions.context_tokens`:+ * 后者只在 turn 正常收尾时落库,中断 / 崩溃后可能低报真实占用,拿它证明「目标还有+ * 余量」会绕过缩窗交接(Greptile P1,2026-09-21)。+ *+ * 缺占用(null / 非法)或缺目标窗口时返回 false(保守):没有可信占用就证明不了目标+ * 有余量,维持原核实路径,不省这次冷启动。+ */+export function shouldSkipColdPiWindowRehydration(input: {+ contextTokens: number | null | undefined;+ targetContextWindow: number | null | undefined;+}): boolean {+ const { contextTokens, targetContextWindow } = input;+ if (+ typeof contextTokens !== 'number' ||+ !Number.isFinite(contextTokens) ||+ contextTokens < 0+ ) {+ return false;+ }+ if (!isPositiveWindow(targetContextWindow)) return false;+ return !shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({+ contextTokens,+ targetContextWindow,+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,+ }),+ );+}+/** 回合中登记 pending 时写入的运行时快照:必须带上点选时的 effort / Fast,不能等结算再猜。 */export function buildDeferredRuntimeSelectionProfile<TAgent extends string,