Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): preserve native sessions across model and catalog changes (#5274)

Chris Zhangb7cb47b56ca0
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 8c8130209f..b23c686aa5 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -404,7 +404,7 @@ describe('session runtime control wiring', () => {
);
const resolveAxes = persistRoute.indexOf('const axes = resolveSessionRuntimeAxes({');
const persist = persistRoute.indexOf(
- 'await getDbClient().drizzle.update(sessions).set(patch)',
+ 'await pendingDb.drizzle.update(sessions).set(patch)',
resolveAxes,
);
const commitEffort = persistRoute.indexOf('setSessionEffort(sessionId, finalEffort);', persist);
@@ -414,7 +414,8 @@ describe('session runtime control wiring', () => {
);
const broadcast = persistRoute.indexOf('broadcastSessionPatched(sessionId, patch);', persist);
- expect(persistRoute).toContain('const [desiredRow] = await getDbClient()');
+ expect(persistRoute).toContain('const [desiredRow] = await pendingDb');
+ expect(persistRoute).toContain('assertPendingOwner();');
expect(persistRoute).toContain('const restoringPreviousRoute =');
expect(persistRoute).toContain('let finalEffort = restoringPreviousRoute && route.effort');
expect(persistRoute).toContain(
@@ -444,7 +445,7 @@ describe('session runtime control wiring', () => {
patchFast,
);
const normalWakeGuard = setModel.indexOf(
- 'if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred)',
+ 'if (!internalOptions.applyingPiCredentialPending && (rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection ||',
persistSelection,
);
const wakeQueue = setModel.indexOf(
@@ -485,7 +486,7 @@ describe('session runtime control wiring', () => {
const apply = setModel.indexOf('applyRuntimeSetModelChange({');
expect(verifiedWindowOnly).toBeGreaterThan(-1);
expect(setModel).toContain('contextWindow: sessions.contextWindow,');
- expect(setModel).toContain('effectiveContextWindow(');
+ expect(setModel).toContain('verifiedCurrentWindow =');
expect(setModel).toContain('hasModelWindowContextToProtect(');
expect(setModel).toContain("'MODEL_CONTEXT_USAGE_UNKNOWN'");
expect(setModel).toContain("'MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'");
@@ -500,7 +501,7 @@ describe('session runtime control wiring', () => {
expect(registerSource).toContain("return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;");
expect(setModel).toContain('await maker.getSessionMeta(sessionId)');
expect(setModel).toContain(
- 'liveSessionBeforeRouteChange?.model ?? persistedSessionMeta?.model',
+ 'internalOptions.previousPiRoute?.model ?? persistedSessionMeta?.model',
);
expect(setModel).not.toContain(
'if (liveSessionBeforeRouteChange && runtimeAgentKind && runtimeRouteChanged)',
@@ -528,7 +529,7 @@ describe('session runtime control wiring', () => {
expect(setModel).toContain('sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)');
expect(setModel).toContain('modelWindowRebuilt ||');
expect(setModel).toContain('patch.contextWindow = targetContextWindow;');
- expect(setModel).toContain('(rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection)');
+ expect(setModel).toContain('(rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection ||');
expect(setModel).toContain('wakeSessionInputAfterCredentialSwitch(sessionId);');
});
@@ -549,7 +550,7 @@ describe('session runtime control wiring', () => {
const requested = setModel.indexOf('const requestedProviderId = normalizeSessionProviderId(');
const restore = setModel.indexOf('if (!hasSessionProvider(sessionId)) {');
const hydrate = setModel.indexOf('hydrateSessionProvider(sessionId, persistedProviderId);');
- const current = setModel.indexOf('const currentProviderId = resolveCurrentSetModelProviderId(');
+ const current = setModel.indexOf('const currentProviderId = internalOptions.previousPiRoute');
const catalogCurrent = setModel.indexOf('const catalogCurrentWindow =');
expect(requested).toBeGreaterThan(-1);
expect(restore).toBeGreaterThan(requested);
@@ -1141,10 +1142,13 @@ describe('session runtime control wiring', () => {
expect(setModel.indexOf('cold remote Pi runtime cannot verify the target window')).toBeLessThan(
apply,
);
- expect(setModel).toContain("runtimeAgentKind === 'pi' && runtimeRouteChanged");
+ expect(setModel).toContain("runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh)");
expect(setModel).not.toContain('busy Pi task cannot change runtime selection');
expect(setModel).toContain('finalPiWindow < verifiedCurrentWindow!');
expect(setModel).not.toContain('finalPiWindow < targetContextWindow');
+ expect(setModel).toContain('internalOptions.previousPiRoute.providerId');
+ expect(setModel).toContain('setSessionProvider(sessionId, internalOptions.previousPiRoute.providerId)');
+ expect(setModel).toContain('coldPiRouteWithoutLiveWindowCheck = true');
});
it('switches and verifies Pi before deciding whether the actual window needs rebuild', () => {
@@ -1164,12 +1168,8 @@ describe('session runtime control wiring', () => {
'preparation = await contextOverflowRolloverHolder.prepareModelWindowSwitch(',
);
- const piPreflightGuard = setModel.lastIndexOf(
- "runtimeAgentKind !== 'pi'",
- preflightPreparation,
- );
- expect(piPreflightGuard).toBeGreaterThan(-1);
- expect(preflightPreparation - piPreflightGuard).toBeLessThan(700);
+ expect(preflightPreparation).toBeGreaterThan(-1);
+ expect(preflightPreparation).toBeLessThan(apply);
expect(closeRecovery).toBeGreaterThan(-1);
expect(closeRecovery).toBeLessThan(finalWindow);
expect(finalWindow).toBeGreaterThan(apply);
@@ -1191,7 +1191,7 @@ describe('session runtime control wiring', () => {
expect(setModel).toContain('contextWindowConfirmationRequired: finalPiWindow');
expect(setModel).toContain('contextTokensForConfirmation: finalPressureContextTokens');
expect(setModel).toContain('finalPressureContextTokens = contextTokens');
- expect(setModel).toContain('runtimeRouteChanged || confirmedContextWindow !== undefined');
+ expect(setModel).toContain('runtimeRouteChanged || piConfigurationRefresh || confirmedContextWindow !== undefined');
expect(setModel).toContain('targetContextWindow = finalPiWindow');
expect(setModel).toContain("if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi') {");
expect(setModel).toContain('planUserRuntimeModelSwitch({');
@@ -1302,7 +1302,7 @@ describe('session runtime control wiring', () => {
expect(setModel).toContain('deferSessionRuntimeAxisMutation({');
expect(setModel).toContain('pendingPatch: pendingAxisPatch');
expect(registerSource).toContain('routeExplicit: isPendingSessionRuntimeRouteExplicit(');
- expect(setModel).toContain('const result = routeExplicit');
+ expect(setModel).toMatch(/const result(?::[^;\n]+)? = routeExplicit\s*\? await applyRuntimeSetModelChange\(/);
expect(setModel).toContain('acceptSessionRuntimeAxisMutation({');
expect(setModel).toContain("runtimeAgentKind !== 'pi' &&");
expect(setModel).toContain('(routeExplicit || internalOptions.effortExplicit === true)');
@@ -1332,7 +1332,7 @@ describe('session runtime control wiring', () => {
expect(setModel).toContain('forceSessionRebuild:');
expect(setModel).toContain('rebuildLiveOrcaWorker ||');
expect(setModel).toContain(
- 'if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred)',
+ 'if (!internalOptions.applyingPiCredentialPending && (rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection ||',
);
});
});
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionAskMulti.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionAskMulti.test.ts
index 4c1ed17237..0b1b1040b8 100644
--- a/apps/desktop/src/main/im/shared/__tests__/cardActionAskMulti.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionAskMulti.test.ts
@@ -64,6 +64,7 @@ vi.mock('../../../maker-ipc/runtimeSetModel', () => ({
applyRuntimeSetModelChange: vi.fn(),
}));
vi.mock('../../../maker-ipc/register', () => ({
+ applyPiImModelSelectionUnderLock: vi.fn(async () => ({ status: 'applied' })),
cancelPendingAgentSwitchForSession: vi.fn(),
isSessionInTurn: vi.fn(() => false),
registerPendingCredentialSwitchForSession: vi.fn(),
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionGroupLaneGuard.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionGroupLaneGuard.test.ts
index bdff1ab8d1..a306905847 100644
--- a/apps/desktop/src/main/im/shared/__tests__/cardActionGroupLaneGuard.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionGroupLaneGuard.test.ts
@@ -37,6 +37,7 @@ vi.mock('electron', () => ({
},
BrowserWindow: { getAllWindows: () => [] },
}));
+vi.mock('electron-store', () => ({ default: class ElectronStore {} }));
vi.mock('../../../logger', () => ({ createLogger: () => mocks.logger }));
vi.mock('../../../maker-host', () => ({ getMaker: mocks.getMaker }));
vi.mock('../../../maker-host/model-route-guard-live', () => ({
@@ -78,6 +79,7 @@ vi.mock('../../../maker-ipc/runtimeSetModel', () => ({
applyRuntimeSetModelChange: vi.fn(async () => ({ status: 'applied' })),
}));
vi.mock('../../../maker-ipc/register', () => ({
+ applyPiImModelSelectionUnderLock: vi.fn(async () => ({ status: 'applied' })),
cancelPendingAgentSwitchForSession: vi.fn(),
isSessionInTurn: vi.fn(() => false),
registerPendingCredentialSwitchForSession: vi.fn(),
@@ -86,6 +88,9 @@ vi.mock('../../../maker-ipc/register', () => ({
getPendingCredentialSwitchTarget: vi.fn(() => undefined),
withSendToSessionLock: vi.fn(async (_sessionId: string, task: () => Promise<unknown>) => task()),
}));
+vi.mock('../../../maker-ipc/sessionRuntimeControl', () => ({
+ cancelPendingSessionRuntimeMutation: vi.fn(() => true),
+}));
vi.mock('../pendingInteractions', () => ({
resolvePending: vi.fn(() => false),
lookupPending: vi.fn(() => null),
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
index 2260f6a46b..bbeed81f2e 100644
--- a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
@@ -23,6 +23,10 @@ const mocks = vi.hoisted(() => ({
resolveLenientSessionRoute: vi.fn(),
applyRuntimeSetModelChange:
vi.fn<(input: unknown) => Promise<{ status: 'applied' | 'deferred' }>>(),
+ applyPiImModelSelectionUnderLock: vi.fn(async (): Promise<{
+ status: 'applied' | 'deferred'; generation?: number; effectiveProviderId?: string | null;
+ }> => ({ status: 'applied' })),
+ cancelPendingSessionRuntimeMutation: vi.fn(() => true),
actualApplyRuntimeSetModelChange: null as null | ((input: never) => Promise<unknown>),
registerPendingCredentialSwitchForSession: vi.fn(),
clearPendingCredentialSwitchForSession: vi.fn(),
@@ -100,6 +104,7 @@ vi.mock('../../../maker-ipc/runtimeSetModel', async (importOriginal) => {
return { applyRuntimeSetModelChange: mocks.applyRuntimeSetModelChange };
});
vi.mock('../../../maker-ipc/register', () => ({
+ applyPiImModelSelectionUnderLock: mocks.applyPiImModelSelectionUnderLock,
cancelPendingAgentSwitchForSession: mocks.cancelPendingAgentSwitchForSession,
isSessionInTurn: mocks.isSessionInTurn,
registerPendingCredentialSwitchForSession: mocks.registerPendingCredentialSwitchForSession,
@@ -108,6 +113,9 @@ vi.mock('../../../maker-ipc/register', () => ({
getPendingCredentialSwitchTarget: mocks.getPendingCredentialSwitchTarget,
withSendToSessionLock: mocks.withSendToSessionLock,
}));
+vi.mock('../../../maker-ipc/sessionRuntimeControl', () => ({
+ cancelPendingSessionRuntimeMutation: mocks.cancelPendingSessionRuntimeMutation,
+}));
vi.mock('../pendingInteractions', () => ({
resolvePending: vi.fn(() => false),
lookupPending: vi.fn(() => null),
@@ -224,6 +232,7 @@ beforeEach(() => {
mocks.readPermissionMode.mockResolvedValue('auto');
mocks.updatePermissionMode.mockResolvedValue(undefined);
mocks.applyRuntimeSetModelChange.mockResolvedValue({ status: 'applied' });
+ mocks.applyPiImModelSelectionUnderLock.mockResolvedValue({ status: 'applied' });
mocks.getMaker.mockReturnValue({
createSession: vi.fn(async () => ({ id: 'sess-new' })),
closeSession: mocks.closeSession,
@@ -632,6 +641,60 @@ describe('model:pick 持久化失败', () => {
expect(mocks.cancelPendingAgentSwitchForSession).toHaveBeenCalledWith('sess-target');
});
+ it('routes a live Pi model card through the window-safe host selection under the existing lock', async () => {
+ const live = { agentKind: 'pi', model: 'old-model', setEffort: vi.fn(async () => {}) };
+ (turnRunner.getMakerSessionById as ReturnType<typeof vi.fn>).mockReturnValue(live);
+ mocks.readModelRouteSnapshot.mockResolvedValue({ model: 'old-model', effort: 'medium', providerId: 'old-source' });
+ const im = makeIm();
+ await pressModelPick(im, 'new-source');
+ expect(mocks.updateModelEffort).toHaveBeenCalled();
+ expect(mocks.applyRuntimeSetModelChange).not.toHaveBeenCalled();
+ expect(mocks.applyPiImModelSelectionUnderLock).toHaveBeenCalledExactlyOnceWith(
+ 'sess-target', 'claude-opus-4-7', 'new-source', expect.objectContaining({ model: 'old-model', providerId: 'old-source' }),
+ );
+ expect(mocks.applyRuntimeSetModelChange).not.toHaveBeenCalled();
+ expect(mocks.withSendToSessionLock).toHaveBeenCalledWith('sess-target', expect.any(Function));
+ expect(live.setEffort).toHaveBeenCalledWith('high');
+ });
+
+ it('routes a cold Pi model card through the same host selection with its persisted source route', async () => {
+ const maker = mocks.getMaker();
+ mocks.getMaker.mockReturnValue({ ...maker, getSessionMeta: vi.fn(async () => ({ agentKind: 'pi' })) });
+ mocks.readModelRouteSnapshot.mockResolvedValue({ model: 'old-model', effort: 'medium', providerId: 'old-source' });
+ const im = makeIm();
+ await pressModelPick(im, 'new-source');
+ expect(mocks.updateModelEffort).toHaveBeenCalled();
+ expect(mocks.applyPiImModelSelectionUnderLock).toHaveBeenCalledExactlyOnceWith(
+ 'sess-target', 'claude-opus-4-7', 'new-source', expect.objectContaining({ model: 'old-model', providerId: 'old-source' }),
+ );
+ expect(mocks.applyRuntimeSetModelChange).not.toHaveBeenCalled();
+ });
+
+ it('persists the Pi host-selected source when a card target was rerouted', async () => {
+ (turnRunner.getMakerSessionById as ReturnType<typeof vi.fn>).mockReturnValue({ agentKind: 'pi', model: 'old-model' });
+ mocks.readModelRouteSnapshot.mockResolvedValue({ model: 'old-model', effort: 'medium', providerId: 'old-source' });
+ mocks.applyPiImModelSelectionUnderLock.mockResolvedValueOnce({
+ status: 'applied', effectiveProviderId: 'enabled-source',
+ });
+ await pressModelPick(makeIm(), 'disabled-source');
+ expect(mocks.updateModelEffort).toHaveBeenCalledWith(
+ 'sess-target', 'claude-opus-4-7', 'high', 'enabled-source',
+ );
+ });
+
+ it('cancels the exact deferred Pi choice if the IM card cannot persist it', async () => {
+ (turnRunner.getMakerSessionById as ReturnType<typeof vi.fn>).mockReturnValue({ agentKind: 'pi', model: 'old-model' });
+ mocks.readModelRouteSnapshot.mockResolvedValue({ model: 'old-model', effort: 'medium', providerId: 'old-source' });
+ mocks.applyPiImModelSelectionUnderLock.mockResolvedValueOnce({
+ status: 'deferred', generation: 7, effectiveProviderId: 'enabled-source',
+ });
+ mocks.updateModelEffort.mockRejectedValueOnce(new Error('write failed'));
+ await pressModelPick(makeIm(), 'disabled-source');
+ expect(mocks.cancelPendingSessionRuntimeMutation).toHaveBeenCalledWith('sess-target', 7);
+ expect(mocks.applyPiImModelSelectionUnderLock).toHaveBeenCalledTimes(1);
+ expect(mocks.markManualOverride).not.toHaveBeenCalled();
+ });
+
it('在持久化和运行态切换前统一归一化 providerId', async () => {
const im = makeIm();
diff --git a/apps/desktop/src/main/im/shared/cardActionHandler.ts b/apps/desktop/src/main/im/shared/cardActionHandler.ts
index 1f618a13e0..d64a3509a0 100644
--- a/apps/desktop/src/main/im/shared/cardActionHandler.ts
+++ b/apps/desktop/src/main/im/shared/cardActionHandler.ts
@@ -34,6 +34,7 @@ import {
setSessionProvider,
} from '../../maker-host/session-provider-store';
import {
+ applyPiImModelSelectionUnderLock,
cancelPendingAgentSwitchForSession,
clearPendingCredentialSwitchForSession,
getPendingCredentialSwitchTarget,
@@ -43,6 +44,7 @@ import {
wakeSessionInputAfterCredentialSwitch,
} from '../../maker-ipc/register';
import { applyRuntimeSetModelChange } from '../../maker-ipc/runtimeSetModel';
+import { cancelPendingSessionRuntimeMutation } from '../../maker-ipc/sessionRuntimeControl';
import { getDesktopCcPrefs, type DesktopCcPrefs } from '../index';
import {
captureImAccountGeneration,
@@ -342,6 +344,10 @@ export function createCardActionHandler(
const previousProviderId = previousRoute
? previousRoute.providerId
: getSessionProvider(sessionId);
+ const liveBeforePick = turnRunner.getMakerSessionById(sessionId);
+ const sessionAgentKind = liveBeforePick?.agentKind ??
+ (await getMaker().getSessionMeta?.(sessionId))?.agentKind;
+ const isPiSession = sessionAgentKind === 'pi';
const restorePersistentRoute = async (reason: string): Promise<void> => {
if (!previousRoute) return;
try {
@@ -359,12 +365,17 @@ export function createCardActionHandler(
const rollbackRuntimeChange = async (reason: string): Promise<void> => {
setSessionProvider(sessionId, previousProviderId);
const liveForRollback = turnRunner.getMakerSessionById(sessionId);
- if (!liveForRollback || !previousRoute) return;
+ if (!previousRoute) return;
try {
- await liveForRollback.setModel(previousRoute.model, {
- providerId: previousRoute.providerId,
- });
- if (effort) {
+ if (isPiSession) {
+ await applyPiImModelSelectionUnderLock(sessionId, previousRoute.model,
+ previousRoute.providerId, { model: modelId, providerId: providerId ?? previousProviderId });
+ } else if (liveForRollback) {
+ await liveForRollback.setModel(previousRoute.model, {
+ providerId: previousRoute.providerId,
+ });
+ }
+ if (liveForRollback && effort) {
await liveForRollback.setEffort(previousRoute.effort);
}
} catch (rollbackErr) {
@@ -375,16 +386,28 @@ export function createCardActionHandler(
};
// 持久化与运行态切换必须和 send / agent switch 共用 session 锁,保证后选覆盖先选。
- try {
- await updateModelEffort(sessionId, modelId, effort ?? 'high', providerId);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.error(`model:pick DB update failed: ${msg}`);
- return msg;
+ if (!isPiSession) {
+ try {
+ await updateModelEffort(sessionId, modelId, effort ?? 'high', providerId);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.error(`model:pick DB update failed: ${msg}`);
+ return msg;
+ }
}
+ let piDeferredGeneration: number | undefined;
+ const rollbackPiSelection = async (reason: string): Promise<void> => {
+ if (piDeferredGeneration !== undefined) {
+ cancelPendingSessionRuntimeMutation(sessionId, piDeferredGeneration);
+ return;
+ }
+ await rollbackRuntimeChange(reason);
+ };
try {
- const runtimeChange = await applyRuntimeSetModelChange({
+ const runtimeChange = isPiSession
+ ? await applyPiImModelSelectionUnderLock(sessionId, modelId, providerId, previousRoute)
+ : await applyRuntimeSetModelChange({
maker: getMaker(),
sessionId,
model: modelId,
@@ -395,7 +418,25 @@ export function createCardActionHandler(
wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,
getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
logger: log,
- });
+ });
+ if (isPiSession && runtimeChange.status === 'deferred' && 'generation' in runtimeChange) {
+ piDeferredGeneration = runtimeChange.generation;
+ }
+
+ if (isPiSession) {
+ try {
+ // The Pi host transaction reads the old DB route to protect native
+ // history and register a correct rollback snapshot while busy.
+ await updateModelEffort(sessionId, modelId, effort ?? 'high',
+ 'effectiveProviderId' in runtimeChange ? runtimeChange.effectiveProviderId : providerId);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.error(`model:pick DB update failed after Pi selection: ${msg}`);
+ await restorePersistentRoute('Pi DB update');
+ await rollbackPiSelection('Pi DB update');
+ return msg;
+ }
+ }
const liveAfterModel = turnRunner.getMakerSessionById(sessionId);
if (runtimeChange.status !== 'deferred' && liveAfterModel && effort) {
@@ -405,7 +446,7 @@ export function createCardActionHandler(
const msg = err instanceof Error ? err.message : String(err);
log.warn(`model:pick live setEffort failed: ${msg}`);
await restorePersistentRoute('setEffort');
- await rollbackRuntimeChange('setEffort');
+ await rollbackPiSelection('setEffort');
return msg;
}
}
@@ -433,7 +474,8 @@ export function createCardActionHandler(
// (PR #5155 review P2)。
clearPendingCredentialSwitchForSession(sessionId);
await restorePersistentRoute('manual override marker');
- await rollbackRuntimeChange('manual override marker');
+ if (isPiSession) await rollbackPiSelection('manual override marker');
+ else await rollbackRuntimeChange('manual override marker');
return msg;
}
// 这次 IM 选择晚于 renderer 登记的跨引擎 intent;只有整条 route 更新成功后
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
index eb43dba565..f3561ff79d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
@@ -1,12 +1,22 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { BUNDLED_CATALOG, buildUserProvider } from '@cindy/model-providers';
+vi.mock('electron', () => ({ app: { getPath: () => '/tmp/cindy-credential-switch-test' } }));
+vi.mock('original-fs', async () => {
+ const fs = await import('node:fs');
+ return { ...fs, default: fs };
+});
+vi.mock('electron-store', () => ({ default: class {
+ get(): unknown { return undefined; }
+ set(): void {}
+ delete(): void {}
+} }));
+
const nativeLogin = vi.hoisted(() => ({ connected: false }));
vi.mock('../claude-native-auth.js', () => ({ hasClaudeNativeLogin: () => nativeLogin.connected }));
import {
isCodexThreadModelProviderIdentityMismatch,
- piProxyProviderIdentity,
prepareLocalSessionCredentialModeSwitch,
prepareLocalCodexCredentialModeSwitch,
shouldCloseSessionForCredentialSwitch,
@@ -384,56 +394,39 @@ describe('shouldCloseSessionForCredentialSwitch codex mode', () => {
});
});
-describe('piProxyProviderIdentity', () => {
- it('collapses Cindy gateway aliases to the headerless proxy identity', () => {
- expect(piProxyProviderIdentity(null)).toBeNull();
- expect(piProxyProviderIdentity(undefined)).toBeNull();
- expect(piProxyProviderIdentity('xd')).toBeNull();
- expect(piProxyProviderIdentity('cindy')).toBeNull();
- expect(piProxyProviderIdentity(' xd ')).toBeNull();
- });
-
- it('pins native subscription and BYOM sources', () => {
- expect(piProxyProviderIdentity('xai')).toBe('xai');
- expect(piProxyProviderIdentity('openai')).toBe('openai');
- expect(piProxyProviderIdentity('anthropic')).toBe('anthropic');
- expect(piProxyProviderIdentity('litellm-custom')).toBe('litellm-custom');
- });
-});
-
-describe('shouldCloseSessionForCredentialSwitch pi proxy identity', () => {
- it('closes idle Pi when crossing xAI and OpenAI even though both are provider-oauth', () => {
+describe('shouldCloseSessionForCredentialSwitch Pi routing', () => {
+ it('leaves cross-provider viability to the Pi runtime', () => {
expect(shouldCloseSessionForCredentialSwitch({
agentKind: 'pi',
currentProviderId: 'xai',
nextProviderId: 'openai',
currentModel: 'grok-4.6',
nextModel: 'gpt-5.6-sol',
- })).toBe(true);
+ })).toBe(false);
expect(shouldCloseSessionForCredentialSwitch({
agentKind: 'pi',
currentProviderId: 'openai',
nextProviderId: 'xai',
currentModel: 'gpt-5.6-sol',
nextModel: 'grok-4.6',
- })).toBe(true);
+ })).toBe(false);
});
- it('closes idle Pi when crossing native xAI and Cindy AI gateway', () => {
+ it('does not infer a restart from native and gateway identities', () => {
expect(shouldCloseSessionForCredentialSwitch({
agentKind: 'pi',
currentProviderId: 'xai',
nextProviderId: 'xd',
currentModel: 'grok-4.6',
nextModel: 'gpt-5.6-sol',
- })).toBe(true);
+ })).toBe(false);
expect(shouldCloseSessionForCredentialSwitch({
agentKind: 'pi',
currentProviderId: 'xd',
nextProviderId: 'xai',
currentModel: 'gpt-5.6-sol',
nextModel: 'grok-4.6',
- })).toBe(true);
+ })).toBe(false);
});
it('keeps a live Pi process for same-family model changes', () => {
diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
index 28ab8bf81d..1f76884288 100644
--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts
+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
@@ -1,4 +1,4 @@
-import { isOpenAiSubscriptionProvider, providerCatalogId, sourceProviderForPreset } from '@cindy/model-providers';
+import { providerCatalogId, sourceProviderForPreset } from '@cindy/model-providers';
import {
canReuseCodexHostForCredentialMode,
canReuseHostForCredentialMode,
@@ -283,54 +283,23 @@ function throwIfCredentialSwitchAborted(signal: AbortSignal | undefined): void {
}
}
-/**
- * Pi loopback proxy identity that must agree across request header
- * `x-cindy-pi-provider-id`, `registerPiProxySession`, and `sessions.provider_id`.
- *
- * Cindy gateway (`xd` / `cindy` / unset) sends no provider header. Native
- * subscription and BYOM sources pin that id. Pi `set_model` does not reread
- * spawn-time `models.json`, so crossing this identity on a live process leaves
- * a stale header and the proxy returns 403 `pi_provider_mismatch`.
- */
-export function piProxyProviderIdentity(
- providerId: string | null | undefined,
-): string | null {
- const normalized = normalizeProviderId(providerId);
- if (!normalized || normalized === 'xd' || normalized === 'cindy') return null;
- return normalized;
-}
-
/**
* 判断运行中的本地会话是否必须关闭后重建。
*
* provider route 可以在空闲时或 turn 边界热切,但 agent 子进程的凭证形态是 spawn-time 状态;
* 只要旧/新来源解析出的 credential family 不同,就不能继续复用当前进程。
- * Pi 还要额外对齐 proxy 供应商身份:Grok/xAI 与 GPT/OpenAI 同属
- * `provider-oauth`,但活进程仍会带旧 `x-cindy-pi-provider-id`。
+ * Pi 的实际启动输入和目录刷新能力由该会话的 previewModelSwitch 判定,
+ * 不能用来源身份或凭证家族代替原生运行时的判断。
*/
export function shouldCloseSessionForCredentialSwitch(
input: ShouldCloseSessionForCredentialSwitchInput,
): boolean {
if (input.remoteHostId) return false;
+ if (input.agentKind === 'pi') return false;
+
const currentProviderId = normalizeProviderId(input.currentProviderId);
const nextProviderId = normalizeProviderId(input.nextProviderId);
- if (
- input.agentKind === 'pi'
- && piProxyProviderIdentity(currentProviderId) !== piProxyProviderIdentity(nextProviderId)
- ) {
- // Native ChatGPT accounts have independent startup provider blocks and placeholder
- // credentials. Pi's verified set_model switches the live proxy/subagent identity;
- // no account token is frozen in the process. Missing startup routes still fail
- // before RPC inside Pi, preserving the old route and pending message.
- const providers = getActiveCatalog().providers;
- const current = providers.find(provider => provider.id === currentProviderId);
- const next = providers.find(provider => provider.id === nextProviderId);
- if (current && next && isOpenAiSubscriptionProvider(current) && isOpenAiSubscriptionProvider(next)) {
- return false;
- }
- return true;
- }
const currentMode = resolveAgentCredentialMode({
agentKind: input.agentKind,
providerId: currentProviderId,
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index f6687ce928..7880f51755 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -2266,6 +2266,7 @@ export function getMaker(): Maker {
capabilityAdditions: {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
},
+ resolvePiRuntimeModels: () => deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
resolvePiRuntimeModelDescriptor: (providerId, modelId) =>
resolvePiRuntimeModelDescriptor(getDesktopSelectableCatalog(), providerId, modelId, {
localOverrides: getLocalCatalogOverridesSnapshot(),
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index d7a19d6139..ecc4ec1223 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -398,6 +398,7 @@ async function readPiCatalogProbeEnv(binaryPath: string): Promise<Record<string,
export async function readPiBundledModels(
binaryPath: string,
+ options: { cachedOnly?: boolean } = {},
): Promise<PiBundledModelCatalog | null> {
const cached = piBundledModelsByBinary.get(binaryPath);
if (cached) {
@@ -406,6 +407,9 @@ export async function readPiBundledModels(
if (catalog === null) piBundledModelsByBinary.delete(binaryPath);
return catalog;
}
+ // A model-switch preview may inspect a live task without launching another Pi
+ // process. Its startup already attempted this exact binary's offline probe.
+ if (options.cachedOnly) return null;
const pending = (async () => {
let configDir: string | undefined;
try {
@@ -899,6 +903,7 @@ export interface BuildPiAgentOpts {
onPiManagedPackageMutationCommitted?: () => Promise<void>;
onPiManagedPackageMutationSettled?: AgentDeps['onPiManagedPackageMutationSettled'];
resolvePiRuntimeModelDescriptor?: AgentDeps['resolvePiRuntimeModelDescriptor'];
+ resolvePiRuntimeModels?: AgentDeps['resolvePiRuntimeModels'];
resolvePiGatewayModelDescriptor?: AgentDeps['resolvePiGatewayModelDescriptor'];
getGhostRosterPrompt?: AgentDeps['getGhostRosterPrompt'];
/** Trusted project-approval authority; omitted until the host has one, which fails closed. */
@@ -1709,8 +1714,9 @@ export async function resolvePiNativeProviders(ctx: {
providerId?: string | null;
model: string;
resumeSessionId?: string;
+ purpose?: 'startup' | 'preview' | 'live-refresh';
}): Promise<PiNativeProvidersResult> {
- if (!ctx.remoteHostId) {
+ if (!ctx.remoteHostId && (ctx.purpose === undefined || ctx.purpose === 'startup')) {
// Pi scans the local ~/.agents/skills root when it starts. This hook is awaited by every
// Desktop Pi startSession caller, so refresh Codex-only projections added after app startup
// before the process snapshots its global skills. Remote Pi has a different HOME/root.
@@ -1730,7 +1736,7 @@ export async function resolvePiNativeProviders(ctx: {
const piBinaryPath = resolvePiBinaryPath();
// Never treat the Desktop executable as the catalog of a different remote Pi binary.
const bundledModels = !ctx.remoteHostId && piBinaryPath
- ? await readPiBundledModels(piBinaryPath)
+ ? await readPiBundledModels(piBinaryPath, { cachedOnly: ctx.purpose === 'preview' })
: null;
let subscriptions: PiNativeProvidersResult = { providers: [], env: {} };
if (!ctx?.remoteHostId && compatProxyReady) {
@@ -1761,7 +1767,7 @@ export async function resolvePiNativeProviders(ctx: {
);
}
const isRemote = Boolean(ctx.remoteHostId);
- if (!isRemote && ctx.providerId === MANAGED_OLLAMA_PROVIDER_ID) {
+ if (!isRemote && ctx.providerId === MANAGED_OLLAMA_PROVIDER_ID && ctx.purpose !== 'preview') {
await ensureManagedOllamaReadyForSession({
providerId: ctx.providerId,
remoteHostId: ctx.remoteHostId ?? null,
@@ -2005,6 +2011,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
registerPiProxySession,
resolvePiNativeProviders: (ctx) => resolvePiNativeProviders(ctx),
resolvePiRuntimeModelDescriptor: opts.resolvePiRuntimeModelDescriptor,
+ resolvePiRuntimeModels: opts.resolvePiRuntimeModels,
resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor,
// `cindy` is the gateway fallback block even when the session starts on a subscription or
// BYOM provider. Its explicit protocol comes from the exact XD model; the local Pi table only
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 4552f8b746..6ebe428217 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -1,6 +1,7 @@
import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, appendAutoReviewUserIntent } from '@cindy/maker-core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentInputCoordinator } from '../agent-input-coordinator.js';
+import { runSchedulerQueuedPreparation } from '../schedulerQueuedPreparation.js';
import {
createPiTranslateContext, disposePiTranslateContext, translatePiEvent,
} from '../../../../../../packages/maker-core/src/agents/pi/translator.js';
@@ -4147,6 +4148,42 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'next' });
});
+ it('discards a scheduled prompt after preparation fails and lets the next message run', async () => {
+ const h = createHarness();
+ const sid = 'scheduler-preparation-failed';
+ const error = new Error('target window cannot be prepared');
+ const onPreparationFailed = vi.fn();
+ const onPreparing = vi.fn(async () => { throw error; });
+ const preparations = new Map([['scheduled', { onPreparing, onPreparationFailed }]]);
+ const dispatched: string[] = [];
+ h.sendToAgent.mockImplementation(async (sessionId, _message, _create, opts) => {
+ const clientId = opts.persistUserMessage?.clientId;
+ await runSchedulerQueuedPreparation(clientId, preparations, () => {});
+ await persistQueuedUserMessage(sessionId, opts);
+ dispatched.push(clientId!);
+ return sendSuccess();
+ });
+ h.coordinator.enqueue(sid, makeItem('scheduled', 'scheduled work', {
+ origin: { kind: 'scheduler', scheduleId: 'sch-1', scheduleName: 'Check' },
+ }));
+ h.coordinator.enqueue(sid, makeItem('following', 'user message'));
+ await vi.waitFor(() => expect(dispatched).toEqual(['following']));
+
+ expect(onPreparationFailed).toHaveBeenCalledExactlyOnceWith(error);
+ expect(onPreparing).toHaveBeenCalledOnce();
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledExactlyOnceWith(
+ sid, expect.objectContaining({ clientId: 'scheduled' }),
+ );
+ expect(h.coordinator.hasQueuedItemWhere(sid, item => item.clientId === 'scheduled',
+ { includeRecovery: true })).toBe(false);
+ expect(latestProjection(h.projections).recovery).toBeNull();
+ expect(dispatched).toEqual(['following']);
+ expect(mocks.createMessage).toHaveBeenCalledTimes(1);
+ h.coordinator.retryLastError(sid);
+ await flush();
+ expect(dispatched).toEqual(['following']);
+ });
+
it('rolls back every pre-accept send failure to the queue head and retries by typed recovery', async () => {
const h = createHarness();
const sid = 'send-rollback';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts
index 9e2b96f885..bc68379f7a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts
@@ -34,11 +34,14 @@ interface HarnessSession {
function createHarness(
sessions: HarnessSession[],
- opts?: { retryDelayMs?: number; resolveRoute?: PendingCredentialSwitchDeps['resolveRoute'] },
+ opts?: { retryDelayMs?: number; resolveRoute?: PendingCredentialSwitchDeps['resolveRoute'];
+ applyPiPending?: PendingCredentialSwitchDeps['applyPiPending'];
+ isPiOwnerCurrent?: PendingCredentialSwitchDeps['isPiOwnerCurrent'] },
) {
const closeSession = vi.fn(async (_sessionId: string) => {});
const broadcastApplied = vi.fn<NonNullable<PendingCredentialSwitchDeps['broadcastApplied']>>();
const onApplied = vi.fn<NonNullable<PendingCredentialSwitchDeps['onApplied']>>();
+ const broadcastFailed = vi.fn<NonNullable<PendingCredentialSwitchDeps['broadcastFailed']>>();
const persistRoute = vi.fn<NonNullable<PendingCredentialSwitchDeps['persistRoute']>>(
async () => {},
);
@@ -48,15 +51,132 @@ function createHarness(
closeSession,
},
broadcastApplied,
+ broadcastFailed,
onApplied,
+ ...(opts?.applyPiPending ? { applyPiPending: opts.applyPiPending } : {}),
+ ...(opts?.isPiOwnerCurrent ? { isPiOwnerCurrent: opts.isPiOwnerCurrent } : {}),
persistRoute,
...(opts?.resolveRoute ? { resolveRoute: opts.resolveRoute } : {}),
...(opts?.retryDelayMs !== undefined ? { retryDelayMs: opts.retryDelayMs } : {}),
});
- return { service, closeSession, broadcastApplied, onApplied, persistRoute, sessions };
+ return { service, closeSession, broadcastApplied, broadcastFailed, onApplied, persistRoute, sessions };
}
describe('PendingCredentialSwitchService', () => {
+ it('applies a busy Pi selection through the model-window transaction before waking the queue', async () => {
+ const sessionId = rememberSession('pi-pending-hot-switch');
+ setSessionProvider(sessionId, 'old-source');
+ let running = true;
+ const events: string[] = [];
+ const applyPiPending = vi.fn<NonNullable<PendingCredentialSwitchDeps['applyPiPending']>>(async (_id, target, resolved) => {
+ events.push('apply');
+ expect(target.selectionSource).toBe('agent');
+ expect(resolved).toEqual({ model: 'next-model', providerId: 'new-source' });
+ return 'applied';
+ });
+ const h = createHarness([{ id: sessionId, agentKind: 'pi', isTurnRunning: () => running }], { applyPiPending });
+ h.service.register(sessionId, { model: 'next-model', providerId: 'new-source', selectionSource: 'agent' });
+ await h.service.onTurnSettled(sessionId);
+ expect(applyPiPending).not.toHaveBeenCalled();
+ running = false;
+ h.onApplied.mockImplementation(() => { events.push('wake'); });
+ h.broadcastApplied.mockImplementation(() => { events.push('broadcast'); });
+ await h.service.onTurnSettled(sessionId);
+ expect(events).toEqual(['apply', 'wake', 'broadcast']);
+ expect(h.closeSession).not.toHaveBeenCalled();
+ expect(h.service.has(sessionId)).toBe(false);
+ expect(getSessionProvider(sessionId)).toBe('old-source');
+ });
+
+ it('rolls back a failed Pi selection once and reports the failure', async () => {
+ const sessionId = rememberSession('pi-pending-rollback');
+ setSessionProvider(sessionId, 'old-source');
+ const applyPiPending = vi.fn<NonNullable<PendingCredentialSwitchDeps['applyPiPending']>>(async () => {
+ throw new Error('native model refresh unsupported');
+ });
+ const h = createHarness([{ id: sessionId, agentKind: 'pi', isTurnRunning: () => false }], { applyPiPending });
+ h.service.register(sessionId, { model: 'new-model', providerId: 'new-source',
+ previousRoute: { model: 'old-model', providerId: 'old-source' } });
+ await h.service.onTurnSettled(sessionId);
+ expect(h.persistRoute).toHaveBeenCalledExactlyOnceWith(sessionId,
+ { model: 'old-model', providerId: 'old-source' });
+ expect(h.service.has(sessionId)).toBe(false);
+ expect(h.broadcastFailed).toHaveBeenCalledExactlyOnceWith({
+ sessionId, reason: 'apply-failed',
+ });
+ expect(h.broadcastApplied).not.toHaveBeenCalled();
+ expect(h.closeSession).not.toHaveBeenCalled();
+ await h.service.onTurnSettled(sessionId);
+ expect(applyPiPending).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs a cold Pi pending choice through the same window-aware host callback after its runtime exits', async () => {
+ const sessionId = rememberSession('pi-pending-cold');
+ const applyPiPending = vi.fn<NonNullable<PendingCredentialSwitchDeps['applyPiPending']>>(async () => 'applied');
+ const h = createHarness([], { applyPiPending });
+ h.service.register(sessionId, { agentKind: 'pi', model: 'small-model', providerId: 'new-source',
+ previousRoute: { model: 'large-model', providerId: 'old-source' } });
+ h.service.onSessionClosed(sessionId);
+ await vi.waitFor(() => expect(applyPiPending).toHaveBeenCalledExactlyOnceWith(
+ sessionId, expect.objectContaining({ model: 'small-model' }),
+ { model: 'small-model', providerId: 'new-source' }, expect.any(Function),
+ ));
+ expect(h.closeSession).not.toHaveBeenCalled();
+ expect(h.broadcastApplied).toHaveBeenCalledTimes(1);
+ expect(h.service.has(sessionId)).toBe(false);
+ });
+
+ it('leaves a newer Pi choice intact while the earlier native apply completes', async () => {
+ const sessionId = rememberSession('pi-pending-latest-wins');
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const h = createHarness([{ id: sessionId, agentKind: 'pi', isTurnRunning: () => false }], {
+ applyPiPending: async () => { await gate; return 'applied'; },
+ });
+ h.service.register(sessionId, { model: 'first', providerId: 'one' });
+ const applying = h.service.onTurnSettled(sessionId);
+ h.service.register(sessionId, { model: 'second', providerId: 'two' });
+ release();
+ await applying;
+ expect(h.service.get(sessionId)?.model).toBe('second');
+ expect(h.onApplied).not.toHaveBeenCalled();
+ expect(h.broadcastApplied).not.toHaveBeenCalled();
+ });
+
+ it('does not write or broadcast a stale Pi choice after the account changes', async () => {
+ const sessionId = rememberSession('pi-pending-owner-change');
+ let ownerCurrent = true;
+ const h = createHarness([{ id: sessionId, agentKind: 'pi', isTurnRunning: () => false }], {
+ isPiOwnerCurrent: () => ownerCurrent,
+ applyPiPending: async () => {
+ ownerCurrent = false;
+ throw new Error('old account');
+ },
+ });
+ h.service.register(sessionId, { model: 'new-model', providerId: 'new-source', ownerEpoch: 'old-owner',
+ previousRoute: { model: 'old-model', providerId: 'old-source' } });
+ await h.service.onTurnSettled(sessionId);
+ expect(h.persistRoute).not.toHaveBeenCalled();
+ expect(h.broadcastFailed).not.toHaveBeenCalled();
+ expect(h.onApplied).not.toHaveBeenCalled();
+ expect(h.service.has(sessionId)).toBe(false);
+ });
+
+ it('reports failed Pi rollback without claiming the previous route was restored or retrying', async () => {
+ const sessionId = rememberSession('pi-pending-rollback-failure');
+ const h = createHarness([{ id: sessionId, agentKind: 'pi', isTurnRunning: () => false }], {
+ applyPiPending: async () => { throw new Error('native switch failed'); },
+ });
+ h.persistRoute.mockRejectedValueOnce(new Error('disk unavailable'));
+ h.service.register(sessionId, { model: 'new-model', providerId: 'new-source',
+ previousRoute: { model: 'old-model', providerId: 'old-source' } });
+ await h.service.onTurnSettled(sessionId);
+ expect(h.service.has(sessionId)).toBe(true);
+ expect(h.onApplied).not.toHaveBeenCalled();
+ expect(h.broadcastFailed).toHaveBeenCalledWith({ sessionId, reason: 'rollback-failed' });
+ await h.service.onTurnSettled(sessionId);
+ expect(h.persistRoute).toHaveBeenCalledTimes(1);
+ });
it.each(['claude-code', 'codex', 'pi'] as const)('retains a failed remote %s context reload until it succeeds', async (agentKind) => {
const sessionId = rememberSession(`remote-context-${agentKind}`);
const h = createHarness([{ id: sessionId, agentKind, remoteHostId: 'remote-test', isTurnRunning: () => false }]);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
index e90d54ff95..a68b755e07 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
@@ -2,6 +2,17 @@ import { rehydrateCloseSuppression } from '../../maker-host/rehydrateCloseSuppre
import { BUNDLED_CATALOG } from '@cindy/model-providers';
import { setCustomProviders } from '../../maker-host/active-catalog.js';
import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// The route helper reaches worktree preferences transitively. Keep this unit
+// test in Node without loading electron-store's native Electron entrypoint.
+vi.mock('electron-store', () => ({
+ default: class {
+ private readonly values = new Map<string, unknown>();
+ get(key: string): unknown { return this.values.get(key); }
+ set(key: string, value: unknown): void { this.values.set(key, value); }
+ delete(key: string): void { this.values.delete(key); }
+ },
+}));
import { acceptSessionRuntimeMutation, getPendingSessionRuntimeMutation, clearSessionRuntimeControlState } from '../sessionRuntimeControl.js';
import { createPendingAgentSwitchRegistry } from '../sessionAgentSwitchHandler.js';
import { PendingCredentialSwitchService } from '../pendingCredentialSwitch.js';
@@ -402,6 +413,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: 'local-model',
setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })),
}),
listActiveSessions: () => [],
closeSession: vi.fn(async () => {}),
@@ -715,7 +728,7 @@ describe('applyRuntimeSetModelChange', () => {
codexAuthInjection: 'oauth-bearer',
});
- expect(result).toEqual({ status: 'applied' });
+ expect(result).toEqual({ status: 'applied', retiredRuntime: true });
expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();
expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');
expect(setModel).not.toHaveBeenCalled();
@@ -752,7 +765,7 @@ describe('applyRuntimeSetModelChange', () => {
providerId: 'deepseek',
});
- expect(result).toEqual({ status: 'applied' });
+ expect(result).toEqual({ status: 'applied', retiredRuntime: true });
expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');
expect(setModel).not.toHaveBeenCalled();
expect(getSessionProvider(sessionId)).toBe('deepseek');
@@ -958,7 +971,7 @@ describe('applyRuntimeSetModelChange', () => {
registerPendingCredentialSwitch: vi.fn(),
});
- expect(result).toEqual({ status: 'applied' });
+ expect(result).toEqual({ status: 'applied', retiredRuntime: true });
expect(closeSession).toHaveBeenCalledTimes(1);
expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');
expect(getSessionProvider(sessionId)).toBe('xd');
@@ -1143,14 +1156,14 @@ describe('applyRuntimeSetModelChange', () => {
wakeSessionInputQueue,
});
- expect(result).toEqual({ status: 'applied' });
+ expect(result).toEqual({ status: 'applied', retiredRuntime: true });
// clear 必须不带唤醒(否则 drain 趁 close 窗口把队首派发到旧会话),
// 唤醒在 close + 写路由完成之后。
expect(order).toEqual(['clear-no-wake', 'close', 'wake']);
expect(getSessionProvider(sessionId)).toBe('xd');
});
- it('closes a stopped Pi runtime before publishing the new route and waking its queued first send', async () => {
+ it('retires only a Pi runtime whose preview proves a rebuild is required', async () => {
const sessionId = rememberSession('runtime-set-model-pi-stop-switch');
setSessionProvider(sessionId, 'openai');
const order: string[] = [];
@@ -1171,6 +1184,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: 'chatgpt/gpt-5.5',
setModel: vi.fn(async () => {}),
+ previewModelSwitch: vi.fn(async () => ({ action: 'rebuild' as const,
+ targetContextWindow: 100_000, windowVerified: false, reason: 'missing spawn input' })),
}),
listActiveSessions: () => [
{ id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
@@ -1187,7 +1202,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(opts).toEqual({ wake: false });
}),
wakeSessionInputQueue,
- })).resolves.toEqual({ status: 'applied' });
+ })).resolves.toEqual({ status: 'applied', retiredRuntime: true });
expect(order).toEqual(['close', 'route', 'wake']);
expect(closeSession).toHaveBeenCalledOnce();
@@ -1206,6 +1221,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: 'chatgpt/gpt-5.5',
setModel: vi.fn(async () => {}),
+ previewModelSwitch: vi.fn(async () => ({ action: 'rebuild' as const,
+ targetContextWindow: 100_000, windowVerified: false, reason: 'missing spawn input' })),
}),
listActiveSessions: () => [
{ id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
@@ -1235,7 +1252,7 @@ describe('applyRuntimeSetModelChange', () => {
{ fromProvider: 'xai', fromModel: 'grok-4.6', toProvider: 'xd', toModel: 'gpt-5.6-sol' },
{ fromProvider: 'xd', fromModel: 'gpt-5.6-sol', toProvider: 'xai', toModel: 'grok-4.6' },
] as const)(
- 'closes idle Pi before $fromProvider → $toProvider so the next send lazy-creates',
+ 'hot-switches idle Pi from $fromProvider to $toProvider when the native preview allows it',
async ({ fromProvider, fromModel, toProvider, toModel }) => {
const sessionId = rememberSession(`runtime-set-model-pi-${fromProvider}-to-${toProvider}`);
setSessionProvider(sessionId, fromProvider);
@@ -1249,6 +1266,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: fromModel,
setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })),
}),
listActiveSessions: () => [
{ id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
@@ -1265,8 +1284,8 @@ describe('applyRuntimeSetModelChange', () => {
wakeSessionInputQueue: vi.fn(),
})).resolves.toEqual({ status: 'applied' });
- expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');
- expect(setModel).not.toHaveBeenCalled();
+ expect(closeSession).not.toHaveBeenCalled();
+ expect(setModel).toHaveBeenCalledWith(toModel, { providerId: toProvider });
expect(getSessionProvider(sessionId)).toBe(toProvider);
},
);
@@ -1282,6 +1301,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: 'grok-4.6',
setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })),
}),
listActiveSessions: () => [
{ id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
@@ -1313,6 +1334,8 @@ describe('applyRuntimeSetModelChange', () => {
remoteHostId: null,
model: 'grok-4.6',
setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })),
}),
listActiveSessions: () => [
{ id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => true },
@@ -1331,7 +1354,6 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'gpt-5.6-sol',
providerId: 'openai',
- forceSessionRebuild: true,
});
expect(closeSession).not.toHaveBeenCalled();
expect(setModel).not.toHaveBeenCalled();
@@ -1359,7 +1381,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(closeSession).not.toHaveBeenCalled();
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, { model: 'same-model', providerId: 'xd', forceSessionRebuild: true });
busy = false;
- await expect(applyRuntimeSetModelChange(input)).resolves.toEqual({ status: 'applied' });
+ await expect(applyRuntimeSetModelChange(input)).resolves.toEqual({ status: 'applied', retiredRuntime: true });
expect(closeSession).toHaveBeenCalledExactlyOnceWith(sessionId, 'runtime-refresh');
expect(setModel).not.toHaveBeenCalled();
expect(getSessionProvider(sessionId)).toBe('xd');
@@ -1393,7 +1415,7 @@ describe('applyRuntimeSetModelChange', () => {
providerId: 'xd',
forceSessionRebuild: true,
clearPendingCredentialSwitch: vi.fn(),
- })).resolves.toEqual({ status: 'applied' });
+ })).resolves.toEqual({ status: 'applied', retiredRuntime: true });
expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');
expect(setModel).not.toHaveBeenCalled();
@@ -1425,7 +1447,7 @@ describe('applyRuntimeSetModelChange', () => {
model: 'gpt-5.6-sol',
providerId: 'mygpt',
clearPendingCredentialSwitch: vi.fn(),
- })).resolves.toEqual({ status: 'applied' });
+ })).resolves.toEqual({ status: 'applied', retiredRuntime: true });
expect(requiresModelSwitchRebuild).toHaveBeenCalledWith('gpt-5.6-sol', {
providerId: 'mygpt',
@@ -1466,7 +1488,7 @@ describe('applyRuntimeSetModelChange', () => {
providerId: 'mygpt',
requiresCodexThreadRelink: true,
relinkCodexThread,
- })).resolves.toEqual({ status: 'applied', persistedRoute: true });
+ })).resolves.toEqual({ status: 'applied', persistedRoute: true, retiredRuntime: true });
expect(order).toEqual(['close', 'relink']);
expect(requiresModelSwitchRebuild).not.toHaveBeenCalled();
@@ -1573,6 +1595,20 @@ describe('applyRuntimeSetModelChange', () => {
});
describe('context configuration refresh across live routes', () => {
+ it('rejects a Pi catalog refresh without the host window transaction', async () => {
+ const id = rememberSession('pi-refresh-no-window-host');
+ const session = { id, agentKind: 'pi' as const, model: 'model',
+ setModel: vi.fn(), requiresModelSwitchRebuild: vi.fn(() => true),
+ previewModelSwitch: vi.fn(async () => ({ action: 'refresh' as const, targetContextWindow: 32_000, windowVerified: false })) };
+ const closeSession = vi.fn();
+ await expect(refreshActiveModelContextSettings({
+ runtime: { maker: { getSession: () => session, listActiveSessions: () => [session], closeSession } },
+ inferProviderId: () => 'xd', assertCurrent: () => {}, hasPendingSelection: () => false,
+ withSessionLock: withSendToSessionLock,
+ })).rejects.toThrow('model-window host transaction');
+ expect(session.setModel).not.toHaveBeenCalled();
+ expect(closeSession).not.toHaveBeenCalled();
+ });
it.each([false, true])('refreshes an ambiguous implicit source only when its actual runtime budget changed (%s)', async (changed) => {
const id = rememberSession('implicit-context-refresh');
const closeSession = vi.fn();
@@ -1626,11 +1662,32 @@ describe('context configuration refresh across live routes', () => {
runtime: { maker: { getSession: () => session, listActiveSessions: () => [session], closeSession }, registerPendingCredentialSwitch },
inferProviderId: () => 'xd', assertCurrent: () => {}, hasPendingSelection: () => pending,
withSessionLock: withSendToSessionLock,
+ applyPiRefresh: vi.fn(),
});
expect(closeSession).not.toHaveBeenCalled();
expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();
});
+ it('marks a busy Pi catalog refresh as automatic before its pending boundary', async () => {
+ const id = rememberSession('pi-busy-catalog-refresh');
+ const session = { id, agentKind: 'pi' as const, model: 'same-model',
+ setModel: vi.fn(),
+ isTurnRunning: () => true,
+ requiresModelSwitchRebuild: vi.fn(async () => true),
+ previewModelSwitch: vi.fn(async () => ({ action: 'refresh' as const, targetContextWindow: 32_000, windowVerified: false })),
+ };
+ const registerPendingCredentialSwitch = vi.fn();
+ await refreshActiveModelContextSettings({
+ runtime: { maker: { getSession: () => session, listActiveSessions: () => [session], closeSession: vi.fn() },
+ isSessionInTurn: () => true, registerPendingCredentialSwitch },
+ inferProviderId: () => 'xd', assertCurrent: () => {}, hasPendingSelection: () => false,
+ withSessionLock: withSendToSessionLock, applyPiRefresh: vi.fn(),
+ });
+ expect(registerPendingCredentialSwitch).toHaveBeenCalledExactlyOnceWith(id, {
+ model: 'same-model', providerId: null, selectionSource: 'agent',
+ });
+ });
+
it.each(['explicit', 'default'] as const)('refreshes all three engines for a %s edit while preserving other routes and pending choices', async (kind) => {
const ids = ['claude-code', 'codex', 'pi', 'other-route', 'pending'] as const;
const sessions = ids.map((id) => {
@@ -1638,21 +1695,25 @@ describe('context configuration refresh across live routes', () => {
setSessionProvider(id, id === 'other-route' ? 'other' : 'xd');
return { id, agentKind: id === 'other-route' || id === 'pending' ? 'pi' as const : id,
model: 'shared-model', setModel: vi.fn(async () => {}),
+ previewModelSwitch: vi.fn(async () => ({ action: (id === 'other-route' ? 'hot' : 'refresh') as 'hot' | 'refresh', targetContextWindow: 64_000, windowVerified: false })),
requiresModelSwitchRebuild: vi.fn(() => id !== 'other-route'), isTurnRunning: () => false };
});
const closeSession = vi.fn(async (_sessionId: string) => {});
+ const applyPiRefresh = vi.fn(async () => {});
await refreshActiveModelContextSettings({
runtime: { maker: { getSession: (id) => sessions.find((s) => s.id === id), listActiveSessions: () => sessions, closeSession },
getPendingCredentialSwitch: (id) => id === 'pending' ? { model: 'next-model', providerId: 'xd' } : undefined },
...(kind === 'explicit' ? { targets: sessions.slice(0, 3).map((s) => ({ agent: s.agentKind, providerId: 'xd', modelId: s.model })) } : {}),
hasPendingSelection: () => false, withSessionLock: async (_id, run) => run(),
+ applyPiRefresh,
inferProviderId: () => null, assertCurrent: () => {},
});
- expect(closeSession.mock.calls.map(([id]) => id)).toEqual(['claude-code', 'codex', 'pi']);
+ expect(closeSession.mock.calls.map(([id]) => id)).toEqual(['claude-code', 'codex']);
+ expect(applyPiRefresh).toHaveBeenCalledExactlyOnceWith('pi', 'shared-model', 'xd');
expect(sessions[4]!.requiresModelSwitchRebuild).not.toHaveBeenCalled();
});
- it.each(['claude-code', 'codex', 'pi'] as const)('retains a failed %s catalog reload and continues later tasks', async (agentKind) => {
+ it.each(['claude-code', 'codex'] as const)('retains a failed %s catalog reload and continues later tasks', async (agentKind) => {
const sessions = ['failed', 'later'].map(suffix => ({
id: rememberSession(`catalog-${agentKind}-${suffix}`), agentKind, remoteHostId: 'ssh-host',
model: 'model', setModel: vi.fn(), requiresModelSwitchRebuild: () => true,
@@ -1671,15 +1732,36 @@ describe('context configuration refresh across live routes', () => {
});
});
+ it('reports a failed Pi refresh and continues to the next task without retiring either runtime', async () => {
+ const sessions = ['failed', 'later'].map(suffix => ({
+ id: rememberSession(`catalog-pi-${suffix}`), agentKind: 'pi' as const,
+ model: 'model', setModel: vi.fn(), requiresModelSwitchRebuild: () => true,
+ previewModelSwitch: vi.fn(async () => ({ action: 'refresh' as const, targetContextWindow: 64_000, windowVerified: false })),
+ }));
+ const closeSession = vi.fn();
+ const applyPiRefresh = vi.fn(async (id: string) => {
+ if (id === sessions[0]!.id) throw new Error('native refresh failed');
+ });
+ await refreshActiveModelContextSettings({
+ runtime: { maker: { listActiveSessions: () => sessions, getSession: id => sessions.find(s => s.id === id), closeSession } },
+ applyPiRefresh, hasPendingSelection: () => false, withSessionLock: withSendToSessionLock,
+ inferProviderId: () => 'xd', assertCurrent: () => {},
+ });
+ expect(closeSession).not.toHaveBeenCalled();
+ expect(applyPiRefresh).toHaveBeenCalledTimes(2);
+ });
+
it.each(['selection', 'account'] as const)('preserves a newer %s change while a catalog close fails', async (change) => {
const id = rememberSession(`catalog-close-${change}`);
let changed = false;
const session = { id, agentKind: 'pi' as const, remoteHostId: 'ssh-host', model: 'model',
- setModel: vi.fn(), requiresModelSwitchRebuild: () => true };
+ setModel: vi.fn(), requiresModelSwitchRebuild: () => true,
+ previewModelSwitch: vi.fn(async () => ({ action: 'refresh' as const, targetContextWindow: 64_000, windowVerified: false })) };
const registerPendingCredentialSwitch = vi.fn();
const run = refreshActiveModelContextSettings({
runtime: { maker: { listActiveSessions: () => [session], getSession: () => session,
closeSession: async () => { changed = true; throw new Error('close failed'); } }, registerPendingCredentialSwitch },
+ applyPiRefresh: async () => { changed = true; throw new Error('native refresh failed'); },
hasPendingSelection: () => changed && change === 'selection', withSessionLock: withSendToSessionLock,
inferProviderId: () => 'xd', assertCurrent: () => { if (changed && change === 'account') throw new Error('owner changed'); },
});
@@ -1784,7 +1866,9 @@ describe('Pi native OpenAI account switching', () => {
const setModel = vi.fn(async () => {});
const closeSession = vi.fn(async () => {});
const maker: RuntimeSetModelMaker = {
- getSession: () => ({ agentKind: 'pi', remoteHostId: null, model: 'chatgpt/gpt-5.6-luna', setModel }),
+ getSession: () => ({ agentKind: 'pi', remoteHostId: null, model: 'chatgpt/gpt-5.6-luna', setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })) }),
listActiveSessions: () => [{ id: sessionId, agentKind: 'pi', isTurnRunning: () => false }], closeSession,
};
await applyRuntimeSetModelChange({ maker, sessionId, model: 'chatgpt/gpt-5.6-luna', providerId: to,
@@ -1807,7 +1891,9 @@ describe('Pi native OpenAI account switching', () => {
const registerPendingCredentialSwitch = vi.fn();
const result = await applyRuntimeSetModelChange({
sessionId, model: 'chatgpt/gpt-5.6-luna', providerId: 'account-b', registerPendingCredentialSwitch,
- maker: { getSession: () => ({ agentKind: 'pi', model: 'chatgpt/gpt-5.6-luna', setModel }),
+ maker: { getSession: () => ({ agentKind: 'pi', model: 'chatgpt/gpt-5.6-luna', setModel,
+ previewModelSwitch: vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 100_000, windowVerified: true })) }),
listActiveSessions: () => [{ id: sessionId, agentKind: 'pi', isTurnRunning: () => true }], closeSession },
});
expect(result.status).toBe('deferred');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts
index 1f656f4001..f21641c8e4 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts
@@ -76,7 +76,9 @@ describe('Codex writer decision freshness', () => {
expect(restore).toHaveBeenCalledWith(sessionId, pending);
expect(getSessionProvider(sessionId)).toBe('cprov-source');
} else {
- await expect(result).resolves.toEqual(state === 'moved' ? { status: 'applied', persistedRoute: true } : { status: 'applied' });
+ await expect(result).resolves.toEqual(state === 'moved'
+ ? { status: 'applied', persistedRoute: true, retiredRuntime: true }
+ : { status: 'applied', retiredRuntime: true });
}
expect(relink).toHaveBeenCalledTimes(state === 'moved' ? 1 : 0);
});
@@ -102,7 +104,7 @@ describe('Codex writer decision freshness', () => {
expect(relink).not.toHaveBeenCalled();
expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();
} else {
- await expect(switching).resolves.toEqual({ status: 'applied', persistedRoute: true });
+ await expect(switching).resolves.toEqual({ status: 'applied', persistedRoute: true, retiredRuntime: true });
expect(closeSession).toHaveBeenCalledOnce();
expect(relink).toHaveBeenCalledOnce();
}
@@ -151,7 +153,7 @@ describe.each(routeCases)('Codex route: $sourceModel → $targetModel', (route)
clearPendingCredentialSwitch: vi.fn(),
wakeSessionInputQueue,
}),
- ).resolves.toEqual({ status: 'applied', persistedRoute: true });
+ ).resolves.toEqual({ status: 'applied', persistedRoute: true, retiredRuntime: true });
expect(order).toEqual(['close', 'relink', 'route', 'wake']);
expect(getSessionProvider(sessionId)).toBe(targetProvider);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/schedulerQueuedPreparation.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/schedulerQueuedPreparation.test.ts
new file mode 100644
index 0000000000..557c55d084
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/schedulerQueuedPreparation.test.ts
@@ -0,0 +1,39 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+import { runSchedulerQueuedPreparation } from '../schedulerQueuedPreparation';
+
+describe('queued scheduler pre-send preparation', () => {
+ it('finishes once before the queued send captures its runtime', async () => {
+ const events: string[] = [];
+ const preparations = new Map([['queued-1', { onPreparing: async () => { events.push('prepare'); } }]]);
+ const send = async () => {
+ await runSchedulerQueuedPreparation('queued-1', preparations, () => {});
+ events.push('capture-session');
+ };
+ await send();
+ await send();
+ expect(events).toEqual(['prepare', 'capture-session', 'capture-session']);
+ const source = readFileSync(resolve(__dirname, '../register.ts'), 'utf8');
+ const lockBody = source.slice(source.indexOf('const sendToAgentAccepted: typeof'),
+ source.indexOf('contextOverflowRolloverHolder =', source.indexOf('const sendToAgentAccepted: typeof')));
+ expect(lockBody.indexOf('runSchedulerQueuedPreparation(')).toBeGreaterThan(lockBody.indexOf('withSendToSessionLock('));
+ expect(lockBody.indexOf('runSchedulerQueuedPreparation(')).toBeLessThan(lockBody.lastIndexOf('sendToAgentAcceptedUnlocked(...args));'));
+ });
+
+ it('rejects the queued send on preparation failure and reports it once', async () => {
+ const error = new Error('target window cannot be prepared');
+ const onPreparationFailed = vi.fn();
+ const onFailure = vi.fn();
+ const preparations = new Map([['queued-2', {
+ onPreparing: async () => { throw error; }, onPreparationFailed,
+ }]]);
+ await expect(runSchedulerQueuedPreparation('queued-2', preparations, onFailure)).rejects.toMatchObject({
+ name: 'SchedulerQueuedPreparationError', cause: error,
+ });
+ expect(onPreparationFailed).toHaveBeenCalledExactlyOnceWith(error);
+ expect(onFailure).toHaveBeenCalledOnce();
+ expect(preparations.size).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e18869c9c7..dab85b422c 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -1,6 +1,7 @@
import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT } from '@cindy/maker-core';
import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
import { assertSharedTaskQueueMutation } from './sharedTaskInput.js';
+import { SchedulerQueuedPreparationError } from './schedulerQueuedPreparation.js';
/**
* AgentInputCoordinator — main 侧排队输入事务协调器。
*
@@ -4712,6 +4713,18 @@ export class AgentInputCoordinator {
return;
}
if (!active.persisted) {
+ if (head.origin?.kind === 'scheduler' && err instanceof SchedulerQueuedPreparationError) {
+ // The scheduler already settled this run as failed. Do not restore its
+ // prompt without the one-shot route/window preparation it required.
+ latest.activeTurn = null;
+ this.clearCredentialSwitchWait(latest);
+ this.notifyRejectedUserTurn(sessionId, head);
+ this.deps.onDiscardedQueuedMessage?.(sessionId, head);
+ this.emit(sessionId);
+ this.scheduleDrain(sessionId, 'scheduler-preparation-failed');
+ this.deps.onQueueEmptied?.(sessionId);
+ return;
+ }
if (isSessionRunningError(err)) {
this.deferQueueHeadAfterSessionRunning(
sessionId,
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 5ef3f3eef3..218ae84a20 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -918,6 +918,8 @@ export const MAKER_PUSH = {
* 会话内轻提示。
*/
SESSION_CREDENTIAL_SWITCH_APPLIED: 'maker:session-credential-switch-applied',
+ /** A deferred Pi model switch failed; the previous route remains authoritative. */
+ SESSION_CREDENTIAL_SWITCH_FAILED: 'maker:session-credential-switch-failed',
/** cc 默认路由会话的生效计费路由变化 (payload: { sessionId, route })。 */
CLAUDE_SESSION_ROUTE_CHANGED: 'maker:claude-session-route-changed',
/**
diff --git a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts
index 3839269fac..ce52ff89cd 100644
--- a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts
+++ b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts
@@ -11,19 +11,16 @@ import { setSessionProvider } from '../maker-host/session-provider-store.js';
/**
* PendingCredentialSwitchService —— 会话凭证形态切换的「延迟生效」登记表。
*
- * 背景:切换模型来源本质只影响**下一次** spawn 用哪把钥匙。旧行为在会话自己
- * 跑任务时直接拒绝整个切换(CREDENTIAL_SWITCH_BUSY toast),用户的选择被丢弃
- * 且极易误以为已生效(2026-07-04 实报:06:35 切换被拒未察觉,11:07 发消息才
- * 撞出真相)。新语义:busy 时把目标 (model, providerId) 登记为 pending,当前
- * turn 结束后自动关会话,下一次发送按新来源重建 —— 切换永远"成功",只是生效
- * 时机不同。
+ * Busy 时登记目标 (model, providerId),在 turn 结束或会话关闭时再应用。
+ * Pi 走原生模型切换和既有窗口容量事务;其它 harness 维持关闭后重建。
+ * 应用失败会回滚旧路由并广播失败,输入队列只有在结果确定后才解冻。
*
* 生效路径(代码保证确定性,不依赖任何 LLM 行为):
* turn done/error(register.ts 接线)→ onTurnSettled:
* 仍在跑(steer 接续等)→ 保留 pending,等下一个 turn 边界;
- * 已空闲 → 关闭本会话(rehydrate suppressed)→ 写 provider store → 广播。
- * 会话被其它路径关闭 → onSessionClosed:直接写 route + 广播(下一次加载
- * hydrate 也会从 DB 读到新值,双保险)。
+ * 已空闲 → Pi 复用 host 切换事务;其它 harness 关闭并重建。
+ * 会话被其它路径关闭 → onSessionClosed:Pi 仍经过冷会话窗口事务;
+ * 其它 harness 直接持久化目标供下次加载。
* 自愈兜底:turn 可能只发 status idle、不发 done/error(stop/interrupt/SDK
* crash),此时上面两条事件路径都不触发,而 pending 存在期间输入队列被
* coordinator 的 hasPendingCredentialSwitch 门冻结 —— register 起周期定时器
@@ -41,6 +38,8 @@ export interface PendingCredentialSwitch {
providerId: string | null;
/** Configuration must be reloaded even when the provider/model stay the same. */
forceSessionRebuild?: boolean;
+ /** Catalog/budget refresh is not a user's confirmation of a smaller window. */
+ selectionSource?: 'agent';
/** 目标会话的 agent(register 时由调用方捕获,收口前的停用重裁决用;可缺席 = 不裁决)。 */
agentKind?: AgentKind;
/**
@@ -51,6 +50,8 @@ export interface PendingCredentialSwitch {
*/
previousRoute?: { model: string; providerId: string | null; effort?: string; fastMode?: boolean };
requestedAt: number;
+ /** Account owner captured when this delayed choice was accepted. */
+ ownerEpoch?: string;
}
interface PendingSwitchSession {
@@ -74,6 +75,17 @@ export interface PendingCredentialSwitchDeps {
}) => void;
/** 生效后唤醒该会话的输入队列(排队消息此前被 pending 门挡住)。 */
onApplied?: (sessionId: string) => void;
+ /** Pi keeps its native session and applies through the host model-window transaction. */
+ applyPiPending?: (
+ sessionId: string,
+ target: PendingCredentialSwitch,
+ resolved: { model: string; providerId: string | null },
+ isCurrent: () => boolean,
+ ) => Promise<'applied' | 'deferred'>;
+ broadcastFailed?: (payload: { sessionId: string; reason: 'apply-failed' | 'rollback-failed' }) => void;
+ isPiOwnerCurrent?: (ownerEpoch: string) => boolean;
+ /** Serialize Pi rollback with all user route selections and queued sends. */
+ withPiSessionLock?: (sessionId: string, run: () => Promise<void>) => Promise<void>;
/**
* 停用轴裁决(生产 = model-route-guard-live 的 resolveLenientSessionRoute)。
* SET_MODEL 请求时刻已裁决过,但 deferred 切换的**生效**可能在数分钟后 —— 期间
@@ -120,6 +132,7 @@ export class PendingCredentialSwitchService {
private readonly applying = new Set<string>();
/** 自愈兜底定时器(per session,pending 收口即清)。 */
private readonly retryTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ private readonly failedPiTargets = new WeakSet<PendingCredentialSwitch>();
constructor(private readonly deps: PendingCredentialSwitchDeps) {}
@@ -129,17 +142,21 @@ export class PendingCredentialSwitchService {
model: string;
providerId: string | null;
forceSessionRebuild?: boolean;
+ selectionSource?: 'agent';
agentKind?: AgentKind;
previousRoute?: { model: string; providerId: string | null; effort?: string; fastMode?: boolean };
+ ownerEpoch?: string;
},
): void {
this.pending.set(sessionId, {
model: target.model,
providerId: target.providerId,
...(target.forceSessionRebuild ? { forceSessionRebuild: true } : {}),
+ ...(target.selectionSource ? { selectionSource: target.selectionSource } : {}),
...(target.agentKind ? { agentKind: target.agentKind } : {}),
...(target.previousRoute ? { previousRoute: target.previousRoute } : {}),
requestedAt: Date.now(),
+ ...(target.ownerEpoch ? { ownerEpoch: target.ownerEpoch } : {}),
});
this.scheduleRetry(sessionId);
this.deps.logger?.info('pending credential switch registered', {
@@ -170,6 +187,13 @@ export class PendingCredentialSwitchService {
async onTurnSettled(sessionId: string): Promise<void> {
const target = this.pending.get(sessionId);
if (!target) return;
+ if (this.failedPiTargets.has(target)) return;
+ if (target.agentKind === 'pi' && target.ownerEpoch &&
+ this.deps.isPiOwnerCurrent?.(target.ownerEpoch) === false) {
+ this.pending.delete(sessionId);
+ this.clearRetry(sessionId);
+ return;
+ }
if (this.applying.has(sessionId)) return;
const session = this.deps.maker
.listActiveSessions()
@@ -178,6 +202,40 @@ export class PendingCredentialSwitchService {
this.applying.add(sessionId);
try {
+ if ((session?.agentKind ?? target.agentKind) === 'pi' && this.deps.applyPiPending) {
+ const resolved = await this.resolveApplyRoute(target);
+ if (this.pending.get(sessionId) !== target) return;
+ if (!resolved.apply) {
+ await this.failPiPending(sessionId, target, new Error('Pi model route could not be revalidated'));
+ return;
+ }
+ try {
+ const outcome = await this.deps.applyPiPending(sessionId, target, {
+ model: resolved.model ?? target.model,
+ providerId: resolved.providerId,
+ }, () => this.pending.get(sessionId) === target && this.piOwnerCurrent(target));
+ if (outcome === 'deferred' || this.pending.get(sessionId) !== target || !this.piOwnerCurrent(target)) return;
+ this.pending.delete(sessionId);
+ this.clearRetry(sessionId);
+ try { this.deps.onApplied?.(sessionId); } catch (error) {
+ this.deps.logger?.warn('pending Pi switch queue wake failed', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ try {
+ this.deps.broadcastApplied?.({
+ sessionId, model: resolved.model ?? target.model, providerId: resolved.providerId,
+ });
+ } catch (error) {
+ this.deps.logger?.warn('pending Pi switch applied broadcast failed', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ } catch (error) {
+ await this.failPiPending(sessionId, target, error);
+ }
+ return;
+ }
if (session) {
try {
if (session.remoteHostId && target.forceSessionRebuild) {
@@ -218,6 +276,62 @@ export class PendingCredentialSwitchService {
}
}
+ private async failPiPending(sessionId: string, target: PendingCredentialSwitch, error: unknown): Promise<void> {
+ if (this.pending.get(sessionId) !== target) return;
+ if (!this.piOwnerCurrent(target)) {
+ this.pending.delete(sessionId);
+ this.clearRetry(sessionId);
+ return;
+ }
+ const message = error instanceof Error ? error.message : String(error);
+ this.failedPiTargets.add(target);
+ this.clearRetry(sessionId);
+ this.deps.logger?.error?.('pending Pi model switch failed', { sessionId, error: message });
+ let rollbackFailed = false;
+ let restored = false;
+ try {
+ const rollback = async () => {
+ if (this.pending.get(sessionId) !== target || !this.piOwnerCurrent(target)) return;
+ if (target.previousRoute && this.deps.persistRoute) {
+ await this.deps.persistRoute(sessionId, target.previousRoute);
+ }
+ if (this.pending.get(sessionId) !== target || !this.piOwnerCurrent(target)) return;
+ if (target.previousRoute) setSessionProvider(sessionId, target.previousRoute.providerId);
+ this.pending.delete(sessionId);
+ restored = true;
+ };
+ if (this.deps.withPiSessionLock) await this.deps.withPiSessionLock(sessionId, rollback);
+ else await rollback();
+ } catch (rollbackError) {
+ rollbackFailed = true;
+ this.deps.logger?.error?.('pending Pi model switch rollback failed; queue remains gated', {
+ sessionId, error: rollbackError instanceof Error ? rollbackError.message : String(rollbackError),
+ });
+ }
+ if ((!restored && !rollbackFailed) ||
+ (this.pending.has(sessionId) && this.pending.get(sessionId) !== target)) return;
+ if (this.piOwnerCurrent(target)) {
+ if (restored) {
+ try { this.deps.onApplied?.(sessionId); } catch (wakeError) {
+ this.deps.logger?.warn('pending Pi rollback queue wake failed', {
+ sessionId, error: wakeError instanceof Error ? wakeError.message : String(wakeError),
+ });
+ }
+ }
+ try {
+ this.deps.broadcastFailed?.({ sessionId, reason: rollbackFailed ? 'rollback-failed' : 'apply-failed' });
+ } catch (broadcastError) {
+ this.deps.logger?.warn('pending Pi failure broadcast failed', {
+ sessionId, error: broadcastError instanceof Error ? broadcastError.message : String(broadcastError),
+ });
+ }
+ }
+ }
+
+ private piOwnerCurrent(target: PendingCredentialSwitch): boolean {
+ return !target.ownerEpoch || this.deps.isPiOwnerCurrent?.(target.ownerEpoch) !== false;
+ }
+
/**
* 会话被其它路径关闭(stop 后手动关 / 升级重建等)。会话已不在,直接写 route
* 并收口 pending;下一次加载 hydrate 从 DB 读到的也是新值(renderer 已落盘)。
@@ -229,6 +343,13 @@ export class PendingCredentialSwitchService {
if (this.applying.has(sessionId)) return;
const target = this.pending.get(sessionId);
if (!target) return;
+ if (this.failedPiTargets.has(target)) return;
+ if (target.agentKind === 'pi' && this.deps.applyPiPending) {
+ // A crashed or externally closed Pi turn still has native history in the
+ // persisted task. Re-enter the same cold model-window transaction.
+ void this.onTurnSettled(sessionId);
+ return;
+ }
this.applying.add(sessionId);
void this.finalizeApplyChecked(sessionId, target, 'session close').finally(() => {
this.applying.delete(sessionId);
@@ -455,7 +576,8 @@ export class PendingCredentialSwitchService {
if (!this.pending.has(sessionId)) return;
void this.onTurnSettled(sessionId).finally(() => {
// 仍未收口(还在跑 / busy 竞态)→ 继续兜底。收口路径已 clearRetry。
- if (this.pending.has(sessionId) && !this.retryTimers.has(sessionId)) {
+ const target = this.pending.get(sessionId);
+ if (target && !this.failedPiTargets.has(target) && !this.retryTimers.has(sessionId)) {
this.scheduleRetry(sessionId);
}
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index fbe610dce5..819520b2fe 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -845,7 +845,6 @@ import {
} from './agentHandoff.js';
import {
createContextOverflowRollover,
- effectiveContextWindow,
hasModelWindowContextToProtect,
isContextOverflowErrorData,
isOversizedHistoryErrorData,
@@ -1016,6 +1015,7 @@ import {
isSupportedRuntimeEffort,
resolveRetainedRuntimeEffort,
} from './runtimeSelectionAxes.js';
+import { runSchedulerQueuedPreparation } from './schedulerQueuedPreparation.js';
import {
acceptSessionRuntimeAxisMutation,
acceptSessionRuntimeMutation,
@@ -1046,7 +1046,7 @@ import {
} from './sessionRuntimeControl.js';
import { applyRuntimeEffortWithRecovery } from './runtimeSetEffort.js';
import { normalizeDeviceLinkSetModelWireArgs } from './setModelWireArgs.js';
-import { PendingCredentialSwitchService } from './pendingCredentialSwitch.js';
+import { PendingCredentialSwitchService, type PendingCredentialSwitchDeps } from './pendingCredentialSwitch.js';
import {
DeferredCodexRestartService,
runMemoryChangeWithCodexRestart,
@@ -3721,7 +3721,7 @@ export function registerSwitchedSessionVendorOptionsResolver(
*/
export async function registerPendingCredentialSwitchForSession(
sessionId: string,
- target: { model: string; providerId: string | null; forceSessionRebuild?: boolean },
+ target: { model: string; providerId: string | null; forceSessionRebuild?: boolean; selectionSource?: 'agent' },
): Promise<void> {
const service = pendingCredentialSwitchHolder;
if (!service) {
@@ -3761,7 +3761,8 @@ export async function registerPendingCredentialSwitchForSession(
const prevModel = live?.model ?? prevRow?.model ?? null;
service.register(sessionId, {
...target,
- ...(dbAgentKind ? { agentKind: dbToMakerAgentKind(dbAgentKind) } : {}),
+ ownerEpoch: captureSessionRuntimeControlOwnerEpoch(),
+ ...(dbAgentKind ? { agentKind: dbToMakerAgentKind(dbAgentKind) } : live?.agentKind ? { agentKind: live.agentKind } : {}),
...(prevModel
? {
previousRoute: {
@@ -3791,12 +3792,29 @@ export function wakeSessionInputAfterCredentialSwitch(sessionId: string): void {
agentInputCoordinatorHolder?.wakeSession(sessionId, 'credential-switch-applied-inline');
}
+let applyPiImModelSelectionHolder: ((
+ sessionId: string, model: string, providerId: string | null | undefined,
+ previousRoute: { model: string; providerId: string | null } | null,
+ options?: { refreshPiConfiguration?: boolean; source?: 'user' | 'agent' },
+) => Promise<{ status: 'applied' | 'deferred'; generation?: number; effectiveProviderId?: string | null }>) | null = null;
+
+/** IM model cards already own the send lock; reuse Desktop's window-safe Pi transaction. */
+export async function applyPiImModelSelectionUnderLock(
+ sessionId: string, model: string, providerId: string | null | undefined,
+ previousRoute: { model: string; providerId: string | null } | null,
+ options?: { refreshPiConfiguration?: boolean; source?: 'user' | 'agent' },
+): Promise<{ status: 'applied' | 'deferred'; generation?: number; effectiveProviderId?: string | null }> {
+ if (!applyPiImModelSelectionHolder) throw new Error('Pi model selection is not ready');
+ return applyPiImModelSelectionHolder(sessionId, model, providerId, previousRoute, options);
+}
+
export function getPendingCredentialSwitchTarget(
sessionId: string,
-): { model: string; providerId: string | null; forceSessionRebuild?: boolean } | undefined {
+): { model: string; providerId: string | null; forceSessionRebuild?: boolean; selectionSource?: 'agent' } | undefined {
const pending = pendingCredentialSwitchHolder?.get(sessionId);
return pending ? { model: pending.model, providerId: pending.providerId,
- ...(pending.forceSessionRebuild ? { forceSessionRebuild: true } : {}) } : undefined;
+ ...(pending.forceSessionRebuild ? { forceSessionRebuild: true } : {}),
+ ...(pending.selectionSource ? { selectionSource: pending.selectionSource } : {}) } : undefined;
}
// ── Scheduler 撞忙排队桥(scheduler-host runner 消费)────────────────────────
@@ -3817,6 +3835,10 @@ export interface SchedulerQueuedPromptRequest {
/** 落库与队列气泡展示的用户原始 prompt(不含隐藏协议)。 */
persistedContent: string;
origin: { kind: 'scheduler'; scheduleId: string; scheduleName: string; runId?: string };
+ /** Runs under the send lock before the live session is captured or a user row is written. */
+ onPreparing?: () => Promise<void>;
+ /** Reject the queued run if preparation fails before dispatch. */
+ onPreparationFailed?: (error: unknown) => void;
/** 排队项被 drain 派发、turn 已被会话接受时回调(等价直发路径的 send onAccepted)。 */
onAccepted: (queuedPermissions?: { permissionMode?: string; planMode?: boolean }) => void | Promise<void>;
/** 派发已 accept 但最终未成为运行 turn(取消/回滚)时回调。 */
@@ -3844,6 +3866,10 @@ interface SchedulerQueueBridge {
let schedulerQueueBridgeHolder: SchedulerQueueBridge | null = null;
/** 排队心跳的 discard 监听(clientId → 通知 runner 收尾)。派发/丢弃后清条目。 */
const schedulerQueuedPromptDiscardWatchers = new Map<string, () => void>();
+const schedulerQueuedPromptPreparations = new Map<string, {
+ onPreparing: () => Promise<void>;
+ onPreparationFailed?: (error: unknown) => void;
+}>();
export function isSchedulerTargetSessionBusy(sessionId: string): boolean {
return schedulerQueueBridgeHolder?.isSessionBusy(sessionId) ?? false;
@@ -5052,11 +5078,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
// Catalog updates and explicit budget edits share one serial refresh boundary.
let contextRefresh = Promise.resolve();
+ let applyPiModelSettingsRefresh: (sessionId: string, model: string, providerId: string | null) => Promise<void> =
+ async () => { throw new Error('Pi model settings refresh is not ready'); };
+ let applyPiPendingSelection: NonNullable<PendingCredentialSwitchDeps['applyPiPending']> =
+ async () => { throw new Error('Pi pending model switch is not ready'); };
const refreshContextSettings = (targets?: readonly { agent: AgentKind; providerId: string; modelId: string }[]) => {
const owner = getActiveAppSession();
const next = contextRefresh.then(() => refreshActiveModelContextSettings({
targets, inferProviderId: (model, agent) => resolveDesktopModelContextProviderId(getActiveCatalog(), agent, null, model),
withSessionLock: withSendToSessionLock,
+ applyPiRefresh: applyPiModelSettingsRefresh,
hasPendingSelection: (sessionId) => {
const pending = getPendingSessionRuntimeMutation(sessionId);
return !!agentSwitchPending.get(sessionId) ||
@@ -11637,6 +11668,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
/** Internal calls from the send / switch transaction already own the route lock. */
sessionLockHeld?: boolean;
applyingUserSelectionOnSend?: boolean;
+ /** Reassess the current Pi route after its catalog descriptor or budget changed. */
+ refreshPiConfiguration?: boolean;
+ /** The pending service owns removal and queue release after this apply commits. */
+ applyingPiCredentialPending?: boolean;
+ /** Renderer may have staged the target in DB while the old Pi runtime went cold. */
+ previousPiRoute?: { model: string; providerId: string | null };
expectedGeneration?: number;
deferWhileRunning?: boolean;
applyingPendingGeneration?: number;
@@ -13208,6 +13245,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (inputCoordinator.isExecutionPaused(sessionId)) {
throwIpcError('PRECONDITION_FAILED', 'Task is paused; resume it before continuing');
}
+ const queuedClientId = (args[3] as { persistUserMessage?: { clientId?: string } } | undefined)
+ ?.persistUserMessage?.clientId;
+ await runSchedulerQueuedPreparation(queuedClientId, schedulerQueuedPromptPreparations,
+ () => { if (queuedClientId) schedulerQueuedPromptDiscardWatchers.delete(queuedClientId); });
return botInput?.remoteHostId ? sendToAgentAcceptedUnlocked(...args)
: withCindyMakeProjectUse(app.getPath('userData'), botInput?.workingDir, () => sendToAgentAcceptedUnlocked(...args));
});
@@ -14524,6 +14565,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
onAcceptedQueuedMessage: async (sessionId, item, restoredFromSnapshot): Promise<void> => {
// 已派发 → 该项不会再走 discard,释放 scheduler 的 discard 监听防泄漏。
schedulerQueuedPromptDiscardWatchers.delete(item.clientId);
+ schedulerQueuedPromptPreparations.delete(item.clientId);
// 返回 promise 让 coordinator 在 onPersisted 链路里 await —— worker 运行态与
// pending auto-bridge 副作用必须先于 turn 启动完成;失败仍吞错落日志,不拦派发。
await orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);
@@ -14694,6 +14736,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!autoResume) settleUndispatchedInterruptedAutoResume(sessionId, item);
// 排队心跳被丢弃 → 通知 runner 按 aborted 收尾对应 run,不让 fire 永久挂起。
const watcher = schedulerQueuedPromptDiscardWatchers.get(item.clientId);
+ schedulerQueuedPromptPreparations.delete(item.clientId);
if (watcher) {
schedulerQueuedPromptDiscardWatchers.delete(item.clientId);
try {
@@ -14813,6 +14856,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// registerAll 可能因切账号重跑:先清旧账号残留的 discard 监听(对应队列快照
// 已随账号切换失效,runner 侧 run 也已被 sweep 收尾)。
schedulerQueuedPromptDiscardWatchers.clear();
+ schedulerQueuedPromptPreparations.clear();
schedulerQueueBridgeHolder = {
isSessionBusy: (sessionId) => {
// 两个视角取并集:coordinator 队列/锁/凭证切换视角(shouldQueueNewTurn,
@@ -14871,6 +14915,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (req.onDiscarded) {
schedulerQueuedPromptDiscardWatchers.set(clientId, req.onDiscarded);
}
+ if (req.onPreparing) {
+ schedulerQueuedPromptPreparations.set(clientId, {
+ onPreparing: req.onPreparing,
+ onPreparationFailed: req.onPreparationFailed,
+ });
+ }
try {
await enqueueSendToSessionMessage({
targetSessionId: req.sessionId,
@@ -14886,6 +14936,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
} catch (err) {
schedulerQueuedPromptDiscardWatchers.delete(clientId);
+ schedulerQueuedPromptPreparations.delete(clientId);
throw err;
}
return { clientId };
@@ -14907,6 +14958,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const pendingCredentialSwitchService = new PendingCredentialSwitchService({
maker,
isSessionInTurn,
+ isPiOwnerCurrent: sessionRuntimeControlOwnerEpochMatches,
+ withPiSessionLock: withSendToSessionLock,
+ applyPiPending: (sessionId, target, resolved, isCurrent) =>
+ applyPiPendingSelection(sessionId, target, resolved, isCurrent),
+ broadcastFailed: (payload) => {
+ broadcastToAllWindows(MAKER_PUSH.SESSION_CREDENTIAL_SWITCH_FAILED, payload);
+ },
broadcastApplied: (payload) => {
broadcastToAllWindows(MAKER_PUSH.SESSION_CREDENTIAL_SWITCH_APPLIED, payload);
},
@@ -14921,8 +14979,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// deferred 接受时已按请求值落盘,不纠正则下一次懒 resume 按停用路由重建
// (PR #744 review 第十、十四轮)。
persistRoute: async (sessionId, route) => {
+ const ownerEpoch = pendingCredentialSwitchHolder?.get(sessionId)?.ownerEpoch;
+ const assertPendingOwner = () => {
+ if (ownerEpoch && !sessionRuntimeControlOwnerEpochMatches(ownerEpoch)) {
+ throw new Error('pending model switch account changed');
+ }
+ };
+ assertPendingOwner();
+ const pendingDb = getDbClient();
const agentKind = getSessionDbAgentKind(sessionId);
- const [desiredRow] = await getDbClient()
+ const [desiredRow] = await pendingDb
.drizzle.select({
model: sessions.model,
effort: sessions.effort,
@@ -14931,6 +14997,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
+ assertPendingOwner();
const finalModel = route.model ?? desiredRow?.model ?? null;
const previousRoute = pendingCredentialSwitchHolder?.get(sessionId)?.previousRoute;
const restoringPreviousRoute =
@@ -15000,7 +15067,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
if (verifiedWindow) patch.contextWindow = verifiedWindow;
}
- await getDbClient().drizzle.update(sessions).set(patch).where(eq(sessions.id, sessionId));
+ assertPendingOwner();
+ await pendingDb.drizzle.update(sessions).set(patch).where(eq(sessions.id, sessionId));
+ assertPendingOwner();
setSessionEffort(sessionId, finalEffort);
setSessionFastMode(sessionId, finalFastMode);
broadcastSessionPatched(sessionId, patch);
@@ -16562,7 +16631,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
expectedAgentSwitchRevision: unknown,
selection: unknown,
internalOptions: InternalRuntimeSelectionOptions,
- ) => {
+ ): ReturnType<typeof applySessionRuntimeSelection> => {
if (typeof sessionId !== 'string' || typeof model !== 'string') {
throwIpcError('INVALID_PARAMS', 'sessionId + model required');
}
@@ -16741,11 +16810,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
}
}
- const currentProviderId = resolveCurrentSetModelProviderId(
- hasSessionProvider(sessionId),
- getSessionProvider(sessionId),
- persistedProviderId,
- );
+ const currentProviderId = internalOptions.previousPiRoute
+ ? internalOptions.previousPiRoute.providerId
+ : resolveCurrentSetModelProviderId(
+ hasSessionProvider(sessionId),
+ getSessionProvider(sessionId),
+ persistedProviderId,
+ );
const guardProviderId = resolveSetModelGuardProviderId(
requestedProviderId,
currentProviderId,
@@ -16936,7 +17007,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
deferred: true,
superseded: false,
generation,
- effectiveProviderId: normalizeSessionProviderId(effectiveProviderId) ?? null,
+ effectiveProviderId: effectiveProviderId === undefined
+ ? currentProviderId : normalizeSessionProviderId(effectiveProviderId) ?? null,
};
};
// 远端回合中不能 live 改 turn:登记选择,回合结束后再生效,不再 PRECONDITION 丢掉。
@@ -16946,6 +17018,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (internalOptions.deferWhileRunning && isSessionInTurn(sessionId)) {
return deferLockedSelection();
}
+ if (internalOptions.previousPiRoute && !maker.getSession(sessionId)) {
+ // Renderer may have persisted the deferred target before a Pi turn exited.
+ // Restore the captured source identity for the cold window transaction.
+ setSessionProvider(sessionId, internalOptions.previousPiRoute.providerId);
+ }
const previousRuntime = {
hadProviderRoute: hasSessionProvider(sessionId),
providerId: getSessionProvider(sessionId),
@@ -17012,21 +17089,41 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
? dbToMakerAgentKind(getSessionDbAgentKind(sessionId))
: persistedSessionMeta?.agentKind);
const targetRouteProviderId = targetProviderId;
- let currentRuntimeModel = liveSessionBeforeRouteChange?.model ?? persistedSessionMeta?.model;
+ let currentRuntimeModel = liveSessionBeforeRouteChange?.model ??
+ internalOptions.previousPiRoute?.model ?? persistedSessionMeta?.model;
let runtimeRouteChanged =
currentRuntimeModel !== undefined &&
(currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId);
- if (runtimeAgentKind === 'pi' && runtimeRouteChanged) {
+ const piConfigurationRefresh = runtimeAgentKind === 'pi' && internalOptions.refreshPiConfiguration === true;
+ const piPreview = runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh) && liveSessionBeforeRouteChange
+ ? await liveSessionBeforeRouteChange.previewModelSwitch?.(model, {
+ providerId: targetRouteProviderId,
+ })
+ : undefined;
+ if (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh) && liveSessionBeforeRouteChange) {
+ if (!piPreview || piPreview.action === 'unavailable') {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ piPreview?.reason ?? 'Pi target route cannot be previewed; runtime selection was not changed',
+ );
+ }
+ }
+ if (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh)) {
if (isSessionInTurn(sessionId)) {
return deferLockedSelection();
}
- if (!liveSessionBeforeRouteChange && runtimeStatus.remoteHostId) {
+ if (!liveSessionBeforeRouteChange && !runtimeStatus.sdkSessionId) {
+ // There is no native history to inspect or retire. The next send will
+ // create Pi directly with the target route and an empty context.
+ coldPiRouteWithoutLiveWindowCheck = true;
+ }
+ if (!liveSessionBeforeRouteChange && runtimeStatus.remoteHostId && runtimeStatus.sdkSessionId) {
throwIpcError(
localModelWindowSwitchErrorCode('MODEL_WINDOW_TARGET_CONTEXT_UNKNOWN'),
'cold remote Pi runtime cannot verify the target window; runtime selection was not changed',
);
}
- if (!liveSessionBeforeRouteChange) {
+ if (!liveSessionBeforeRouteChange && runtimeStatus.sdkSessionId) {
assertRuntimeOwnerCurrent();
assertSharedTaskCurrent.admit();
// 冷启动核实(2~3s)只在它可能改变决策时才做:目标窗口对**已知占用**已到
@@ -17090,21 +17187,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
let targetContextWindow: number | undefined;
- let currentContextWindow: number | undefined;
let verifiedCurrentWindow: number | undefined;
let modelWindowContextNeedsProtection = false;
let modelWindowRebuilt = false;
- if (runtimeAgentKind && (runtimeRouteChanged || confirmedContextWindow !== undefined)) {
+ if (runtimeAgentKind && (runtimeRouteChanged || piConfigurationRefresh || confirmedContextWindow !== undefined)) {
const resolveRouteWindow = (_agentKind: string, modelId: string, pid: string | null) =>
sshCodexProviders
? resolveVerifiedContextWindow({ providers: sshCodexProviders }, runtimeAgentKind, pid ?? 'openai', modelId)
: resolveConfiguredContextWindow(getActiveCatalog(), runtimeAgentKind, pid, modelId);
- const verifiedTargetWindow = lookupVerifiedContextWindow(
+ const catalogTargetWindow = lookupVerifiedContextWindow(
resolveRouteWindow,
model,
targetRouteProviderId,
runtimeAgentKind,
);
+ const verifiedTargetWindow =
+ runtimeAgentKind === 'pi' && piPreview?.windowVerified === true &&
+ typeof piPreview.targetContextWindow === 'number' && piPreview.targetContextWindow > 0
+ ? catalogTargetWindow === null
+ ? piPreview.targetContextWindow
+ : Math.min(piPreview.targetContextWindow, catalogTargetWindow)
+ : catalogTargetWindow;
const catalogCurrentWindow =
lookupVerifiedContextWindow(
resolveRouteWindow,
@@ -17113,32 +17216,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
runtimeAgentKind,
) ?? undefined;
const liveCurrentWindow = liveSessionBeforeRouteChange?.getUsageSnapshot?.().contextWindow;
- const reportedCurrentWindow =
- typeof liveCurrentWindow === 'number' &&
- Number.isFinite(liveCurrentWindow) &&
- liveCurrentWindow > 0
- ? liveCurrentWindow
- : typeof runtimeStatus.contextWindow === 'number' &&
- Number.isFinite(runtimeStatus.contextWindow) &&
- runtimeStatus.contextWindow > 0
- ? runtimeStatus.contextWindow
- : 0;
- // Current-session usage has already been route-capped by the harness when a verified
- // catalog ceiling exists. If the current route has no verified catalog entry, its live
- // (or last persisted) effective window is still the best fact about the running context.
- // Pi remains live-only because its provider/model reload can change the effective window.
- currentContextWindow =
- runtimeAgentKind === 'pi'
- ? typeof liveCurrentWindow === 'number' &&
- Number.isFinite(liveCurrentWindow) &&
- liveCurrentWindow > 0
- ? liveCurrentWindow
- : undefined
- : effectiveContextWindow(
- currentRuntimeModel,
- reportedCurrentWindow,
- catalogCurrentWindow,
- ) || undefined;
// Pi 的有效窗口只能相信运行时上报值;其它引擎的缩窗闸门只接受目录核实值。
verifiedCurrentWindow =
runtimeAgentKind === 'pi'
@@ -17203,7 +17280,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
isRemote: !!runtimeStatus.remoteHostId ||
(!internalOptions.applyingUserSelectionOnSend && isDeviceLinkInvoke()),
agentKind: runtimeAgentKind,
- runtimeRouteChanged,
+ runtimeRouteChanged: runtimeRouteChanged || piConfigurationRefresh,
verifiedTargetWindow,
verifiedCurrentWindow,
contextTokensKnown,
@@ -17222,7 +17299,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
if (
!modelSwitchPlan.skipRebuild &&
- runtimeAgentKind !== 'pi' &&
typeof targetContextWindow === 'number' &&
targetContextWindow > 0 &&
!targetDoesNotShrink
@@ -17241,15 +17317,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: targetContextWindow!,
recheckTargetPressure: true,
confirmedTargetPressure:
- internalOptions.applyingUserSelectionOnSend === true ||
+ (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true) ||
(!isDeviceLinkInvoke() && confirmedContextWindow === targetContextWindow),
onConfirmationRequired: (contextTokens) => {
confirmationContextTokens = contextTokens;
},
assertCanCommit: () => { assertRuntimeOwnerCurrent(); assertSharedTaskCurrent.admit(); },
beforeClose: () => {
- clearPendingCredentialSwitchForSession(sessionId, { wake: false });
- pendingClearedForWindowRebuild = true;
+ if (!internalOptions.applyingPiCredentialPending) {
+ clearPendingCredentialSwitchForSession(sessionId, { wake: false });
+ pendingClearedForWindowRebuild = true;
+ }
},
});
} catch (error) {
@@ -17390,7 +17468,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
setSessionEffort(sessionId, retainedProfile.effort);
setSessionFastMode(sessionId, retainedProfile.fastMode);
- pendingCredentialSwitchHolder?.clear(sessionId);
+ if (!internalOptions.applyingPiCredentialPending) pendingCredentialSwitchHolder?.clear(sessionId);
if (internalOptions.source === 'user') {
recordRecoveredSessionRuntimeMutation(sessionId, retainedProfile);
} else if (!routeExplicit) {
@@ -17517,13 +17595,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
};
assertRuntimeOwnerCurrent();
- const result = routeExplicit
+ const result: Awaited<ReturnType<typeof applyRuntimeSetModelChange>> = routeExplicit
? await applyRuntimeSetModelChange({
maker,
admit: () => { assertRuntimeOwnerCurrent(); assertSharedTaskCurrent.admit(); },
sessionId,
model,
providerId: effectiveProviderId,
+ ...(piConfigurationRefresh ? { refreshPiConfiguration: true } : {}),
...(canTransferThread ? {
requiresCodexThreadRelink: () => maker.requiresCodexThreadHostTransfer({
...transferTarget, threadId: transferStatus.sdkSessionId!,
@@ -17539,25 +17618,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
forceSessionRebuild:
rebuildLiveOrcaWorker ||
(atomicSelection?.effort === null && runtimeAgentKind !== 'pi'),
- ...(runtimeAgentKind === 'pi' && runtimeRouteChanged
- ? {
- assertSessionCloseSupported: () => {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Pi target route requires an unsupported runtime replacement; runtime selection was not changed',
- );
- },
- }
- : {}),
isSessionInTurn,
registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,
- clearPendingCredentialSwitch: atomicSelection
+ clearPendingCredentialSwitch: internalOptions.applyingPiCredentialPending
+ ? () => {}
+ : atomicSelection ||
+ (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh))
? (pendingSessionId) =>
clearPendingCredentialSwitchForSession(pendingSessionId, { wake: false })
: clearPendingCredentialSwitchForSession,
// Worker rebuild must publish the accepted runtime profile before queued input
// can lazy-create the replacement execution unit.
- ...(!rebuildLiveOrcaWorker && !atomicSelection
+ ...(!rebuildLiveOrcaWorker && !atomicSelection &&
+ !(runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh))
? { wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch }
: {}),
getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
@@ -17566,7 +17639,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
codexAuthInjection: getCodexProxyAuthInjectionState(),
logger: log,
})
- : { status: 'applied' as const };
+ : { status: 'applied' };
// deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示
// "任务结束后生效"而不是当成已即时切换。
const response = {
@@ -17582,8 +17655,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const piSessionAfterRouteChange = maker.getSession(sessionId);
if (
runtimeAgentKind === 'pi' &&
- runtimeRouteChanged &&
+ (runtimeRouteChanged || piConfigurationRefresh) &&
result.status !== 'deferred' &&
+ result.retiredRuntime !== true &&
!modelWindowRebuilt &&
!coldPiRouteWithoutLiveWindowCheck
) {
@@ -17631,7 +17705,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: finalPiWindow,
recheckTargetPressure: true,
confirmedTargetPressure:
- internalOptions.applyingUserSelectionOnSend === true ||
+ (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true) ||
(!isDeviceLinkInvoke() && confirmedContextWindow === finalPiWindow),
onConfirmationRequired: (contextTokens) => {
finalPressureContextTokens = contextTokens;
@@ -17720,6 +17794,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (
result.persistedRoute !== true &&
(modelWindowRebuilt ||
+ (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh)) ||
(internalOptions.source === 'user' && (isDeviceLinkInvoke() || atomicSelection)))
) {
// device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;
@@ -17755,7 +17830,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// harness can switch atomically. If SQLite rejects, unwind every
// in-memory side effect while generation/effectiveOverride still
// describe the old profile.
- pendingCredentialSwitchHolder?.clear(sessionId);
+ if (!internalOptions.applyingPiCredentialPending) pendingCredentialSwitchHolder?.clear(sessionId);
restoreControlStores();
let recoveryError: unknown;
const shouldCloseRuntimeAfterPersistenceFailure =
@@ -17776,7 +17851,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId,
previousRuntime.pendingCredentialSwitch,
);
- } else if (!recoveryError) {
+ } else if (!recoveryError && !internalOptions.applyingPiCredentialPending) {
wakeSessionInputAfterCredentialSwitch(sessionId);
}
if (recoveryError) {
@@ -17860,7 +17935,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
});
}
- if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred) {
+ if (!internalOptions.applyingPiCredentialPending && (rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection ||
+ (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh))) && !response.deferred) {
wakeSessionInputAfterCredentialSwitch(sessionId);
}
if (!response.deferred) {
@@ -17938,7 +18014,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// to dispatch and cannot be followed by a stale lock-free route write.
return Object.assign(response, {
generation,
- effectiveProviderId: normalizeSessionProviderId(effectiveProviderId) ?? null,
+ effectiveProviderId: effectiveProviderId === undefined
+ ? currentProviderId : normalizeSessionProviderId(effectiveProviderId) ?? null,
});
} catch (err) {
// Atomic calls suppress applyRuntimeSetModelChange's early wake. If a later step
@@ -17957,6 +18034,53 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
return internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked);
};
+ applyPiModelSettingsRefresh = async (sessionId, model, providerId) => {
+ const generation = getSessionRuntimeControlSnapshot(sessionId).generation;
+ const result = await handleSetModel(sessionId, model, providerId, undefined, undefined, {
+ source: 'agent', sessionLockHeld: true, applyingUserSelectionOnSend: true,
+ expectedGeneration: generation, refreshPiConfiguration: true,
+ });
+ if (result.contextWindowConfirmationRequired) {
+ throw new Error('Pi model settings need a smaller context window; confirm the switch before continuing');
+ }
+ };
+ applyPiPendingSelection = async (sessionId, target, resolved, isCurrent) => {
+ const assertPendingCurrent = () => {
+ if (!isCurrent() || !target.ownerEpoch ||
+ !sessionRuntimeControlOwnerEpochMatches(target.ownerEpoch)) {
+ throw new Error('Pi pending model switch was superseded or its account changed');
+ }
+ };
+ assertPendingCurrent();
+ const result = await handleSetModel(sessionId, resolved.model, resolved.providerId,
+ undefined, undefined, {
+ source: target.selectionSource ?? 'user', applyingUserSelectionOnSend: true,
+ applyingPiCredentialPending: true, refreshPiConfiguration: true,
+ ...(target.previousRoute ? { previousPiRoute: target.previousRoute } : {}),
+ assertSelectionCurrent: assertPendingCurrent,
+ });
+ if (result.superseded) throw new Error('Pi pending model switch was superseded');
+ if (result.contextWindowConfirmationRequired) {
+ throw new Error('Pi model switch needs confirmation for its smaller context window');
+ }
+ return result.deferred ? 'deferred' : 'applied';
+ };
+ applyPiImModelSelectionHolder = async (sessionId, model, providerId, previousRoute, options) => {
+ const result = await handleSetModel(sessionId, model, providerId, undefined, undefined, {
+ source: options?.source ?? 'user', sessionLockHeld: true, applyingUserSelectionOnSend: true,
+ ...(previousRoute ? { previousPiRoute: previousRoute } : {}),
+ ...(options?.refreshPiConfiguration ? { refreshPiConfiguration: true } : {}),
+ });
+ if (result.superseded) throw new Error('Pi model selection was superseded');
+ if (result.contextWindowConfirmationRequired) {
+ throw new Error('Pi model selection needs confirmation for its smaller context window');
+ }
+ return {
+ status: result.deferred ? 'deferred' : 'applied',
+ generation: result.generation,
+ effectiveProviderId: result.effectiveProviderId,
+ };
+ };
applySessionRuntimeSelection = (sessionId, model, providerId, selection, options) =>
handleSetModel(sessionId, model, providerId, undefined, selection, options);
registerSessionSetModelHandler(makerSessionRegistry, {
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index 19909ff729..77119bc69a 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -32,6 +32,15 @@ interface RuntimeSetModelSession {
model: string,
opts?: { providerId?: string | null },
) => boolean | Promise<boolean>;
+ previewModelSwitch?: (
+ model: string,
+ opts?: { providerId?: string | null },
+ ) => Promise<{
+ action: 'hot' | 'refresh' | 'rebuild' | 'unavailable';
+ targetContextWindow: number | null;
+ windowVerified: boolean;
+ reason?: string;
+ } | undefined>;
}
interface RuntimeSetModelActiveSession {
@@ -63,6 +72,8 @@ export interface ApplyRuntimeSetModelChangeInput {
* 形态相同,也必须沿用 credential-switch 的 idle close / busy defer 边界。
*/
forceSessionRebuild?: boolean;
+ /** Re-evaluate the current Pi descriptor, including immutable spawn inputs. */
+ refreshPiConfiguration?: boolean;
/** Fail closed before an otherwise-required runtime replacement mutates route state. */
assertSessionCloseSupported?: () => void;
/** Called after async preflight, immediately before the first setting side effect. */
@@ -74,7 +85,7 @@ export interface ApplyRuntimeSetModelChangeInput {
*/
registerPendingCredentialSwitch?: (
sessionId: string,
- target: { model: string; providerId: string | null; forceSessionRebuild?: boolean },
+ target: { model: string; providerId: string | null; forceSessionRebuild?: boolean; selectionSource?: 'agent' },
) => void | Promise<void>;
/**
* 「无需切换」分支清掉旧 pending(后选覆盖先选)。典型场景:deferred 登记后
@@ -97,7 +108,7 @@ export interface ApplyRuntimeSetModelChangeInput {
*/
getPendingCredentialSwitch?: (
sessionId: string,
- ) => { model: string; providerId: string | null; forceSessionRebuild?: boolean } | undefined;
+ ) => { model: string; providerId: string | null; forceSessionRebuild?: boolean; selectionSource?: 'agent' } | undefined;
/**
* 当前本地 Codex spawn 的鉴权注入形态(getCodexProxyAuthInjectionState())。
* shouldCloseSessionForCredentialSwitch 用它解析隐式来源的凭证家族,精确判定
@@ -116,7 +127,7 @@ export interface ApplyRuntimeSetModelChangeInput {
export type ApplyRuntimeSetModelChangeResult =
/** 直接生效(热切 route / 或已关会话待下次发送重建)。 */
- | { status: 'applied'; persistedRoute?: true }
+ | { status: 'applied'; persistedRoute?: true; retiredRuntime?: true }
/** 凭证形态要换但会话自己在跑:已登记 pending,turn 结束后自动生效。 */
| { status: 'deferred'; persistedRoute?: never };
@@ -193,10 +204,25 @@ export async function applyRuntimeSetModelChange(
codexAuthInjection: input.codexAuthInjection,
})
: false;
+ // Pi owns the decision about its live model directory, proxy bridge and
+ // spawn-time inputs. A provider id or credential family alone cannot prove
+ // that its native session needs replacement.
+ const piRouteChanged = sess?.agentKind === 'pi' &&
+ (sess.model !== model || currentProviderId !== nextProviderId);
+ const piPreview = piRouteChanged || (sess?.agentKind === 'pi' && input.refreshPiConfiguration === true)
+ ? await sess.previewModelSwitch?.(model, { providerId: nextProviderId })
+ : undefined;
+ if ((piRouteChanged || (sess?.agentKind === 'pi' && input.refreshPiConfiguration === true)) && !piPreview) {
+ throw new Error('Pi model switch preview is unavailable; runtime selection was not changed');
+ }
+ if (piPreview?.action === 'unavailable') {
+ throw new Error(piPreview.reason ?? 'Pi target model is unavailable; runtime selection was not changed');
+ }
let requiresCodexThreadRelink = typeof input.requiresCodexThreadRelink === 'function'
? await input.requiresCodexThreadRelink() : input.requiresCodexThreadRelink === true;
const modelSwitchRequiresRebuild =
sess &&
+ sess.agentKind !== 'pi' &&
input.forceSessionRebuild !== true &&
!credentialModeRequiresRebuild &&
!requiresCodexThreadRelink
@@ -205,7 +231,8 @@ export async function applyRuntimeSetModelChange(
const shouldCloseSession = Boolean(sess) && (
input.forceSessionRebuild === true ||
modelSwitchRequiresRebuild ||
- credentialModeRequiresRebuild
+ credentialModeRequiresRebuild ||
+ piPreview?.action === 'rebuild'
);
if (shouldCloseSession && typeof input.requiresCodexThreadRelink === 'function') {
requiresCodexThreadRelink = await input.requiresCodexThreadRelink();
@@ -378,8 +405,8 @@ export async function applyRuntimeSetModelChange(
toModel: model,
});
return relinkAfterClose && input.relinkCodexThread
- ? { status: 'applied', persistedRoute: true }
- : { status: 'applied' };
+ ? { status: 'applied', persistedRoute: true, retiredRuntime: true }
+ : { status: 'applied', retiredRuntime: true };
}
input.admit?.();
@@ -436,6 +463,8 @@ export async function refreshActiveModelContextSettings(input: {
assertCurrent: () => void;
hasPendingSelection: (sessionId: string) => boolean;
withSessionLock: (sessionId: string, run: () => Promise<void>) => Promise<void>;
+ /** Called under the caller's session lock; Pi shares the full model-window transaction. */
+ applyPiRefresh?: (sessionId: string, model: string, providerId: string | null) => Promise<void>;
}): Promise<void> {
const { runtime, targets, inferProviderId, assertCurrent } = input;
for (const active of runtime.maker.listActiveSessions()) {
@@ -449,6 +478,46 @@ export async function refreshActiveModelContextSettings(input: {
// The pending route is a later user choice; its rebuild reads current settings.
const hasPending = () => input.hasPendingSelection(active.id) || !!runtime.getPendingCredentialSwitch?.(active.id);
if (hasPending()) return;
+ if (session.agentKind === 'pi') {
+ if (!input.applyPiRefresh) {
+ throw new Error('Pi model settings refresh requires the model-window host transaction');
+ }
+ const budgetChanged = await session.requiresModelSwitchRebuild?.(
+ session.model, { providerId: source },
+ ) ?? false;
+ const preview = await session.previewModelSwitch?.(session.model, { providerId: source });
+ assertCurrent();
+ if (hasPending() || runtime.maker.getSession(active.id) !== session) return;
+ if (!preview || preview.action === 'unavailable') {
+ runtime.logger?.info('Pi catalog refresh requires explicit runtime action', {
+ sessionId: active.id,
+ reason: preview?.reason ?? 'model switch preview unavailable',
+ });
+ return;
+ }
+ if (!targets && !budgetChanged && preview.action === 'hot') return;
+ if (isLocalSessionBusy(active, runtime.isSessionInTurn)) {
+ // Catalog updates must wait for the turn boundary. A later user
+ // selection takes priority through the existing pending registry.
+ await runtime.registerPendingCredentialSwitch?.(active.id, {
+ model: session.model,
+ providerId: getSessionProvider(active.id),
+ selectionSource: 'agent',
+ });
+ return;
+ }
+ try {
+ await input.applyPiRefresh(active.id, session.model, getSessionProvider(active.id));
+ } catch (error) {
+ assertCurrent();
+ runtime.logger?.info('Pi catalog refresh failed', {
+ sessionId: active.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ if (targets) throw error;
+ }
+ return;
+ }
if ((!targets || source === null) && !await session.requiresModelSwitchRebuild?.(session.model, { providerId: source })) return;
assertCurrent();
if (hasPending() || runtime.maker.getSession(active.id) !== session) return;
diff --git a/apps/desktop/src/main/maker-ipc/schedulerQueuedPreparation.ts b/apps/desktop/src/main/maker-ipc/schedulerQueuedPreparation.ts
new file mode 100644
index 0000000000..31962d489e
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/schedulerQueuedPreparation.ts
@@ -0,0 +1,30 @@
+/** One-shot pre-send preparation for queued scheduler prompts. */
+export interface SchedulerQueuedPreparation {
+ onPreparing: () => Promise<void>;
+ onPreparationFailed?: (error: unknown) => void;
+}
+
+/** This scheduled run has already failed; its unpersisted prompt must not retry. */
+export class SchedulerQueuedPreparationError extends Error {
+ constructor(cause: unknown) {
+ super('Scheduled prompt preparation failed', { cause });
+ this.name = 'SchedulerQueuedPreparationError';
+ }
+}
+
+export async function runSchedulerQueuedPreparation(
+ clientId: string | undefined,
+ preparations: Map<string, SchedulerQueuedPreparation>,
+ onFailure: () => void,
+): Promise<void> {
+ const preparation = clientId ? preparations.get(clientId) : undefined;
+ if (!preparation) return;
+ preparations.delete(clientId!);
+ try {
+ await preparation.onPreparing();
+ } catch (error) {
+ onFailure();
+ try { preparation.onPreparationFailed?.(error); } catch { /* Preserve the preparation error. */ }
+ throw new SchedulerQueuedPreparationError(error);
+ }
+}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
index e7fe1e2195..52f3ce6d72 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
@@ -17,6 +17,17 @@
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
+vi.mock('electron', () => ({ app: { getPath: () => '/tmp/cindy-scheduler-test' } }));
+vi.mock('electron-store', () => ({ default: class {
+ get(): unknown { return undefined; }
+ set(): void {}
+ delete(): void {}
+} }));
+vi.mock('original-fs', async () => {
+ const fs = await import('node:fs');
+ return { ...fs, default: fs };
+});
+
import type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';
import type { FireContext, Logger, Notifier, Schedule } from '@cindy/maker-scheduler';
import {
@@ -235,6 +246,7 @@ function createRunnerHarness(
opts: {
sessionAlive?: boolean;
acquirePendingAgentSwitch?: ConstructorParameters<typeof MakerScheduleRunner>[0]['acquirePendingAgentSwitch'];
+ applyPiModelSelectionUnderLock?: ConstructorParameters<typeof MakerScheduleRunner>[0]['applyPiModelSelectionUnderLock'];
resolveModelSelection?: ConstructorParameters<typeof MakerScheduleRunner>[0]['resolveModelSelection'];
activeSessions?: Session[];
availableModels?: Array<{
@@ -249,13 +261,14 @@ function createRunnerHarness(
resolveDefaultModelRoute?: ConstructorParameters<
typeof MakerScheduleRunner
>[0]['resolveDefaultModelRoute'];
+ getSessionMeta?: () => Promise<typeof meta>;
} = {},
): RunnerHarness {
const createSession = vi.fn(async () => h.session);
const closeSession = vi.fn(async () => undefined);
const maker = {
createSession,
- getSessionMeta: vi.fn(async () => meta),
+ getSessionMeta: vi.fn(opts.getSessionMeta ?? (async () => meta)),
getSession: vi.fn(() => h.session),
listActiveSessions: vi.fn(() => opts.activeSessions ?? [h.session]),
closeSession,
@@ -273,6 +286,10 @@ function createRunnerHarness(
logger: createLogger(),
checkModelRoute: opts.checkModelRoute,
acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,
+ applyPiModelSelectionUnderLock: opts.applyPiModelSelectionUnderLock ?? (async (_id, targetModel, providerId) => {
+ await h.session.setModel(targetModel, { providerId });
+ return { status: 'applied' as const };
+ }),
resolveModelSelection: opts.resolveModelSelection,
resolveRouteCopyCapabilities: opts.resolveRouteCopyCapabilities,
resolveDefaultModelRoute: opts.resolveDefaultModelRoute,
@@ -481,10 +498,11 @@ describe('MakerScheduleRunner model selection', () => {
});
describe('Pi 派发前路由重裁决', () => {
- it('晚到 reroute 跨 Pi proxy 身份时本轮失败,留给下次 fire 关进程重建', async () => {
+ it('Pi 完成准备后来源再变化时拒绝本次发送,保留当前会话', async () => {
const checkModelRoute = vi
.fn()
.mockResolvedValueOnce({ kind: 'pass' as const })
+ .mockResolvedValueOnce({ kind: 'pass' as const })
.mockResolvedValueOnce({ kind: 'reroute' as const, providerId: 'byom-b' });
const h = createSessionHarness();
(h.session as { agentKind: string }).agentKind = 'pi';
@@ -497,13 +515,34 @@ describe('MakerScheduleRunner model selection', () => {
createFireContext(),
),
).rejects.toThrow(/Session send failed before dispatch/);
- expect(checkModelRoute).toHaveBeenCalledTimes(2);
+ expect(checkModelRoute).toHaveBeenCalledTimes(3);
expect(h.setModel).not.toHaveBeenCalled();
expect(mocks.setSessionProvider).not.toHaveBeenCalled();
expect(h.send).not.toHaveBeenCalled();
});
});
+ it('prepares a late Pi reroute before binding the result listener or sending', async () => {
+ const h = createSessionHarness();
+ (h.session as { agentKind: string }).agentKind = 'pi';
+ (h.session as { model: string }).model = 'chatgpt/gpt-5.6-sol';
+ const listener = vi.spyOn(h.session, 'onEvent');
+ const transaction = vi.fn(async () => ({ status: 'applied' as const }));
+ const checkModelRoute = vi.fn()
+ .mockResolvedValueOnce({ kind: 'pass' as const })
+ .mockResolvedValueOnce({ kind: 'reroute' as const, providerId: 'byom-b' })
+ .mockResolvedValue({ kind: 'pass' as const });
+ const harness = createRunnerHarness(h, null, {
+ checkModelRoute, applyPiModelSelectionUnderLock: transaction,
+ });
+ await fireToCompletion(harness, h, baseSchedule({ agentKind: 'pi', model: h.session.model }));
+ expect(transaction).toHaveBeenCalledWith('scheduler-session', h.session.model, 'byom-b',
+ { model: h.session.model, providerId: null }, { refreshPiConfiguration: true, source: 'agent' });
+ expect(transaction.mock.invocationCallOrder[0]).toBeLessThan(listener.mock.invocationCallOrder[0]);
+ expect(transaction.mock.invocationCallOrder[0]).toBeLessThan(h.send.mock.invocationCallOrder[0]);
+ expect(harness.closeSession).not.toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');
+ });
+
describe('non-heartbeat (每次新建 session)', () => {
it('schedule.model 留空时 Claude 兜底 claude-sonnet-4-6(成本保守,与 UI 空值回退一致)', async () => {
const h = createSessionHarness();
@@ -1212,6 +1251,38 @@ describe('MakerScheduleRunner model selection', () => {
// - 留空 + heartbeat → hydrate 绑定会话的 provider_id(只在内存无条目时写,不覆盖)。
// - 显式设置 → setSessionProvider 覆盖 + backfill 落 sessions.provider_id。
describe('provider (来源) 注入', () => {
+ it('cold Pi heartbeat verifies the target window before resuming native history', async () => {
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'byom-a' });
+ mocks.getSessionProvider.mockReturnValue('byom-a');
+ const h = createSessionHarness();
+ (h.session as { agentKind: string }).agentKind = 'pi';
+ const transaction = vi.fn(async () => ({ status: 'applied' as const }));
+ const previous = {
+ agentKind: 'pi' as const, model: 'old-model', effort: 'high', workDir: '/work',
+ sdkSessionId: 'old-native-history',
+ };
+ const harness = createRunnerHarness(h, previous, {
+ sessionAlive: false,
+ applyPiModelSelectionUnderLock: transaction,
+ getSessionMeta: vi.fn()
+ .mockResolvedValueOnce(previous)
+ .mockResolvedValue({ ...previous, sdkSessionId: 'prepared-native-history' }),
+ });
+
+ await fireToCompletion(harness, h, baseSchedule({
+ agentKind: 'pi', model: 'new-model', providerId: 'byom-b',
+ targetSessionId: 'scheduler-session',
+ }));
+ expect(transaction).toHaveBeenCalledWith('scheduler-session', 'new-model', 'byom-b',
+ { model: 'old-model', providerId: 'byom-a' },
+ { refreshPiConfiguration: true, source: 'agent' });
+ expect(transaction.mock.invocationCallOrder[0]).toBeLessThan(
+ harness.createSession.mock.invocationCallOrder[0]);
+ expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ model: 'new-model', providerId: 'byom-b', resumeSessionId: 'prepared-native-history',
+ }));
+ expect(h.setModel).not.toHaveBeenCalled();
+ });
it('非 heartbeat Claude + 留空 providerId → 物化当前 Claude 订阅来源并落库', async () => {
const h = createSessionHarness();
const resolveDefaultModelRoute = vi.fn(async () => ({
@@ -1343,7 +1414,7 @@ describe('MakerScheduleRunner model selection', () => {
);
});
- it('heartbeat 复用 Pi 跨 proxy 身份时先关闭再按新来源重建', async () => {
+ it('heartbeat 复用 Pi 跨 proxy 身份时在同一会话上热切来源', async () => {
mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', providerId: 'byom-a' });
mocks.getSessionProvider.mockReturnValue('byom-a');
const h = createSessionHarness();
@@ -1370,14 +1441,9 @@ describe('MakerScheduleRunner model selection', () => {
}),
);
- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');
- expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(
- harness.createSession.mock.invocationCallOrder[0],
- );
- expect(h.setModel).not.toHaveBeenCalled();
- expect(harness.createSession).toHaveBeenCalledWith(
- expect.objectContaining({ providerId: 'byom-b', model: 'gpt-5.6-sol' }),
- );
+ expect(harness.closeSession).not.toHaveBeenCalled();
+ expect(h.setModel).toHaveBeenCalledWith('gpt-5.6-sol', { providerId: 'byom-b' });
+ expect(harness.createSession).toHaveBeenCalledTimes(1);
});
it('heartbeat 复用 Pi 同身份时即使模型不变也把 provider-model 原子同步到原生进程', async () => {
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index e9a0b04c6e..29f55ae7fd 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -18,6 +18,17 @@
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
+vi.mock('electron', () => ({ app: { getPath: () => '/tmp/cindy-scheduler-test' } }));
+vi.mock('electron-store', () => ({ default: class {
+ get(): unknown { return undefined; }
+ set(): void {}
+ delete(): void {}
+} }));
+vi.mock('original-fs', async () => {
+ const fs = await import('node:fs');
+ return { ...fs, default: fs };
+});
+
import { AcceptedCallbackDispatchCancelled } from '../../maker-ipc/acceptedCallbackRunner.js';
import type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';
@@ -325,8 +336,11 @@ function createQueueHarness(opts: {
if (opts.enqueueRetry) return { retry: true as const };
if (opts.enqueueDuplicate) return { duplicate: true as const };
enqueueCalls.push(req);
- if (opts.acceptBeforeEnqueueResolves)
+ if (opts.acceptBeforeEnqueueResolves) {
+ try { await req.onPreparing?.(); }
+ catch (error) { req.onPreparationFailed?.(error); throw error; }
await req.onAccepted({ permissionMode: 'ask', planMode: false });
+ }
return { clientId: `client-${enqueueCalls.length}` };
}),
removeQueuedPrompt: (sessionId, clientId) => {
@@ -348,6 +362,9 @@ function createQueueHarness(opts: {
},
},
async accept(permissions = { permissionMode: 'ask', planMode: false }) {
+ const request = enqueueCalls.at(-1);
+ try { await request?.onPreparing?.(); }
+ catch (error) { request?.onPreparationFailed?.(error); return; }
await enqueueCalls.at(-1)?.onAccepted(permissions);
},
discard() {
@@ -378,6 +395,7 @@ function createRunnerHarness(
checkModelRoute?: MakerScheduleRunnerDeps['checkModelRoute'];
acquirePendingAgentSwitch?: MakerScheduleRunnerDeps['acquirePendingAgentSwitch'];
resolveModelSelection?: MakerScheduleRunnerDeps['resolveModelSelection'];
+ applyPiModelSelectionUnderLock?: MakerScheduleRunnerDeps['applyPiModelSelectionUnderLock'];
} = {},
) {
const logger = createLogger();
@@ -415,6 +433,11 @@ function createRunnerHarness(
schedulerQueue,
checkModelRoute: opts.checkModelRoute,
acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,
+ applyPiModelSelectionUnderLock: opts.applyPiModelSelectionUnderLock ?? (async (_id, model, providerId) => {
+ await liveSession.setModel(model, { providerId });
+ mocks.getSessionProvider.mockReturnValue(providerId);
+ return { status: 'applied' as const };
+ }),
resolveModelSelection: opts.resolveModelSelection,
});
return {
@@ -648,7 +671,8 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
await queue.accept();
expect(await result).toBeInstanceOf(Error);
expect(h.send).not.toHaveBeenCalled();
- expect(h.session.abort).toHaveBeenCalled();
+ if (failure === 'harness-changed') expect(h.session.abort).not.toHaveBeenCalled();
+ else expect(h.session.abort).toHaveBeenCalled();
},
);
@@ -1220,7 +1244,33 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(harness.listenerCount()).toBe(0);
});
- it('排队 Pi 跨 proxy 身份时本轮沿用当前路由,不热切 setModel', async () => {
+ it('prepares a queued Pi that went cold using its persisted route before acceptance', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ (h.session as { agentKind: string }).agentKind = 'pi';
+ (h.session as { model: string }).model = 'old-model';
+ mocks.getSessionProvider.mockReturnValue('byom-a');
+ const queue = createQueueHarness({ busy: true });
+ const transaction = vi.fn(async () => {
+ (h.session as { model: string }).model = 'new-model';
+ mocks.getSessionProvider.mockReturnValue('byom-b');
+ return { status: 'applied' as const };
+ });
+ const { runner, maker } = createRunnerHarness(h.session, queue.deps, {
+ metaModel: 'old-model', applyPiModelSelectionUnderLock: transaction,
+ });
+ const fire = runner.fire(heartbeatSchedule({
+ agentKind: 'pi', model: 'new-model', providerId: 'byom-b',
+ }), createFireContext());
+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));
+ vi.mocked(maker.getSession).mockReturnValueOnce(undefined);
+ await queue.accept();
+ expect(transaction).toHaveBeenCalledWith(SESSION_ID, 'new-model', 'byom-b',
+ { model: 'old-model', providerId: 'byom-a' }, { refreshPiConfiguration: true, source: 'agent' });
+ h.emit({ type: 'done', data: {}, source: 'pi' });
+ await expect(fire).resolves.toMatchObject({ sessionId: SESSION_ID });
+ });
+
+ it('排队 Pi 跨 proxy 身份时在发送前热切到目标来源', async () => {
mocks.getSessionRowSnapshot.mockResolvedValue({
status: 'active',
userSendAt: null,
@@ -1247,8 +1297,8 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));
await queue.accept();
- expect(harness.setModel).not.toHaveBeenCalled();
- expect(mocks.setSessionProvider).not.toHaveBeenCalled();
+ expect(harness.setModel).toHaveBeenCalledWith('gpt-5.6-sol', { providerId: 'byom-b' });
+ expect(mocks.setSessionProvider).toHaveBeenCalledWith(SESSION_ID, 'byom-b');
harness.emit({ type: 'done', data: {}, source: 'pi' });
await expect(firePromise).resolves.toMatchObject({ sessionId: SESSION_ID });
});
@@ -1315,9 +1365,11 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
await queue.accept();
await expect(firePromise).rejects.toThrow(
- 'schedule Pi route sync failed before queued dispatch',
+ 'set_model rejected',
);
- expect(harness.session.abort).toHaveBeenCalled();
+ // Preparation failed before a send reservation existed; do not abort another turn.
+ expect(harness.session.abort).not.toHaveBeenCalled();
+ expect(harness.send).not.toHaveBeenCalled();
expect(mocks.setSessionProvider).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index ae1c619ad9..3b68186ff2 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -36,6 +36,7 @@ import {
import { getAgentIslandService } from '../agent-island/service.js';
import { getDesktopNotificationsEnabled } from '../notificationService.js';
import {
+ applyPiImModelSelectionUnderLock,
acquirePendingAgentSwitchForDirectSend,
broadcastSessionCreated,
cancelSchedulerAutoResume,
@@ -123,6 +124,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul
},
onUndispatchedUserTurn: deps.onUndispatchedUserTurn,
acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,
+ applyPiModelSelectionUnderLock: applyPiImModelSelectionUnderLock,
resolveModelSelection: resolveScheduledModelSelectionLive,
onSessionCreated: broadcastSessionCreated,
// 停用轴裁决:每次 fire 前判保存路由是否已被用户停用(见 runner deps 注释)。
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 4ed3cf6b81..37aa39fb00 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -228,6 +228,9 @@ export interface SchedulerQueueDeps {
persistedContent: string;
inheritTargetPlanMode?: boolean;
origin: { kind: 'scheduler'; scheduleId: string; scheduleName: string; runId: string };
+ /** Runs under the send lock before the queued Session is captured. */
+ onPreparing?: () => Promise<void>;
+ onPreparationFailed?: (error: unknown) => void;
onAccepted: (queuedPermissions?: {
permissionMode?: string;
planMode?: boolean;
@@ -269,6 +272,14 @@ export interface MakerScheduleRunnerDeps {
) => Promise<(() => void) | ScheduledModelSelectionLease>;
/** Resolve the same provider-specific snapshot for fresh explicit choices. */
resolveModelSelection?: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;
+ /** Apply Pi's route and context-window transaction while the send lock is held. */
+ applyPiModelSelectionUnderLock?: (
+ sessionId: string,
+ model: string,
+ providerId: string | null,
+ previousRoute: { model: string; providerId: string | null },
+ options?: { refreshPiConfiguration?: boolean; source?: 'user' | 'agent' },
+ ) => Promise<{ status: 'applied' | 'deferred' }>;
/** 新建可见会话落库后通知本机窗口与 device-link 列表订阅者。 */
onSessionCreated?: (sessionId: string) => void;
/** 可选:撞忙排队桥。未注入时心跳撞忙回退为顺延(deferFire)旧行为。 */
@@ -885,6 +896,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
holder.releaseAgentSwitchLock?.();
holder.releaseAgentSwitchLock = undefined;
return await this.fireHeartbeatViaQueue(schedule, ctx, sessionId, holder, {
+ agentKind: meta?.agentKind,
model: meta?.model,
effort: meta?.effort,
fastMode: meta?.fastMode,
@@ -1155,6 +1167,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (
liveSession &&
credentialSwitchInput &&
+ liveSession.agentKind !== 'pi' &&
shouldCloseSessionForCredentialSwitch(credentialSwitchInput)
) {
// provider store 可能已先于 runtime 被覆盖。若 live thread 连「当前已登记路由」
@@ -1214,6 +1227,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (
reusedLiveSession &&
liveSession &&
+ liveSession.agentKind !== 'pi' &&
(await liveSession.requiresModelSwitchRebuild?.(model, { providerId: nextProviderId })) ===
true
) {
@@ -1245,6 +1259,18 @@ export class MakerScheduleRunner implements ScheduleRunner {
});
}
}
+ if (isHeartbeat && effectiveAgentKind === 'pi' && !reusedLiveSession && resumeSessionId) {
+ if (!this.deps.applyPiModelSelectionUnderLock) {
+ throw new Error('Scheduled Pi model selection is not available');
+ }
+ const applied = await this.deps.applyPiModelSelectionUnderLock(
+ sessionId, model, createProviderId,
+ { model: heartbeatModel ?? model, providerId: heartbeatProviderId },
+ { refreshPiConfiguration: true, source: 'agent' },
+ );
+ if (applied.status !== 'applied') throw new Error('Scheduled Pi model selection was deferred');
+ resumeSessionId = (await this.deps.maker.getSessionMeta(sessionId))?.sdkSessionId ?? undefined;
+ }
// The worktree path can also await filesystem work, so cancellation may
// have arrived after the preceding guard. Never create a late session.
throwIfFireAborted(ctx.signal, 'session creation');
@@ -1254,30 +1280,29 @@ export class MakerScheduleRunner implements ScheduleRunner {
return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
throwIfFireAborted(ctx.signal, 'session creation');
}
+ const createSessionOpts = {
+ id: sessionId,
+ agentKind: effectiveAgentKind,
+ workingDir,
+ model,
+ effort: reconciledEffort,
+ fastMode,
+ permissionMode:
+ routinePermissions?.permissionMode ??
+ heartbeatPermissions?.permissionMode ??
+ defaultPermissionModeForSchedule(),
+ ...((routinePermissions ?? heartbeatPermissions)
+ ? { planMode: (routinePermissions ?? heartbeatPermissions)!.planMode }
+ : {}),
+ title: isHeartbeat ? undefined : `[Schedule] ${schedule.name}`,
+ resumeSessionId,
+ // Explicit null means Cindy's default route for Pi.
+ providerId: createProviderId,
+ vendorOptions: { source: 'scheduler' as const },
+ };
let session: Awaited<ReturnType<Maker['createSession']>>;
try {
- session = await this.deps.maker.createSession({
- id: sessionId,
- agentKind: effectiveAgentKind,
- workingDir,
- model,
- effort: reconciledEffort,
- fastMode,
- permissionMode:
- routinePermissions?.permissionMode ??
- heartbeatPermissions?.permissionMode ??
- defaultPermissionModeForSchedule(),
- ...((routinePermissions ?? heartbeatPermissions)
- ? { planMode: (routinePermissions ?? heartbeatPermissions)!.planMode }
- : {}),
- title: isHeartbeat ? undefined : `[Schedule] ${schedule.name}`,
- resumeSessionId,
- // Pi distinguishes an explicit null (Cindy default route) from undefined
- // (legacy model-based native-provider fallback). Preserve the scheduler's
- // default-route null when spawning a fresh Pi session.
- providerId: createProviderId,
- vendorOptions: { source: 'scheduler' },
- });
+ session = await this.deps.maker.createSession(createSessionOpts);
} catch (err) {
if (err instanceof CredentialModeSwitchBusyError) {
// fresh Codex 也共用本地 credential mode,撞上其它本地 Codex turn 时按撞忙处理。
@@ -1314,10 +1339,29 @@ export class MakerScheduleRunner implements ScheduleRunner {
null;
const mustSyncReusedPiRoute = reusedLiveSession && effectiveAgentKind === 'pi';
let modelSwitchApplied = true;
- if (heartbeatModelChanged || mustSyncReusedPiRoute) {
+ if ((heartbeatModelChanged && effectiveAgentKind !== 'pi') || mustSyncReusedPiRoute) {
try {
if (mustSyncReusedPiRoute) {
- await session.setModel(model, { providerId: reusedPiRouteProviderId });
+ if (!this.deps.applyPiModelSelectionUnderLock) {
+ throw new Error('Scheduled Pi model selection is not available');
+ }
+ const applied = await this.deps.applyPiModelSelectionUnderLock(
+ session.id, model, reusedPiRouteProviderId,
+ { model: session.model, providerId: getSessionProvider(session.id) ?? heartbeatProviderId },
+ { refreshPiConfiguration: true, source: 'agent' },
+ );
+ if (applied.status !== 'applied') throw new Error('Scheduled Pi model selection was deferred');
+ // A protected window handoff can retire the old Pi handle. Resume from
+ // the transaction's persisted native checkpoint before this fire sends.
+ if (this.deps.maker.getSession(session.id) !== session) {
+ const latest = await this.deps.maker.getSessionMeta(session.id);
+ session = await this.deps.maker.createSession({
+ ...createSessionOpts,
+ model,
+ providerId: reusedPiRouteProviderId,
+ resumeSessionId: latest?.sdkSessionId ?? undefined,
+ });
+ }
} else {
await session.setModel(model);
}
@@ -1520,6 +1564,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
session.id,
holder,
{
+ agentKind: session.agentKind,
model: session.model ?? model,
effort: runtimeReconciledEffort,
fastMode,
@@ -1544,6 +1589,37 @@ export class MakerScheduleRunner implements ScheduleRunner {
);
}
+ // Resolve Pi's last provider change before listener, abort and handoff
+ // state bind to the Session instance. The transaction may retire it.
+ if (effectiveAgentKind === 'pi' && this.deps.checkModelRoute) {
+ const currentProviderId = getSessionProvider(session.id);
+ const verdict = await this.deps.checkModelRoute('pi', runtimeModel, currentProviderId);
+ if (verdict.kind === 'reject') {
+ throw new Error(`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, runtimeModel, currentProviderId)} (${verdict.reason})`);
+ }
+ if (verdict.kind === 'reroute' && shouldApplyExclusiveProviderRerouteLive(currentProviderId)) {
+ if (!this.deps.applyPiModelSelectionUnderLock) {
+ throw new Error('Scheduled Pi model selection is not available');
+ }
+ const applied = await this.deps.applyPiModelSelectionUnderLock(
+ session.id, runtimeModel, verdict.providerId,
+ { model: session.model, providerId: currentProviderId },
+ { refreshPiConfiguration: true, source: 'agent' },
+ );
+ if (applied.status !== 'applied') throw new Error('Scheduled Pi model selection was deferred');
+ if (this.deps.maker.getSession(session.id) !== session) {
+ const latest = await this.deps.maker.getSessionMeta(session.id);
+ session = await this.deps.maker.createSession({
+ ...createSessionOpts,
+ model: runtimeModel,
+ providerId: verdict.providerId,
+ resumeSessionId: latest?.sdkSessionId ?? undefined,
+ });
+ }
+ setSessionProvider(session.id, verdict.providerId);
+ }
+ }
+
// 4.5.4 只有直发降级路径需要把取消映射到 session.abort()。生产队列路径由
// coordinator 按「仍在排队 / 已派发」分别撤项或中断,不能让这个监听器误杀
// 异步入队期间刚好开始的用户 turn。
@@ -1643,6 +1719,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// fire 在入口改道(reroutedProviderId)并经凭证切换重建正确收敛;同凭证
// 形态的改道热换即可生效(PR #744 review 第二十七轮)。
if (
+ effectiveAgentKind !== 'pi' &&
shouldCloseSessionForCredentialSwitch({
agentKind: session.agentKind,
remoteHostId: session.remoteHostId,
@@ -1661,14 +1738,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
);
}
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}"): ${err instanceof Error ? err.message : String(err)}`,
- { cause: err },
- );
- }
+ throw new Error('schedule Pi route changed after pre-dispatch preparation');
}
setSessionProvider(session.id, verdict.providerId);
}
@@ -2004,6 +2074,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
/** 绑定会话的当前路由基线(meta.model / meta.effort / sessions.provider_id)。 */
routingBaseline: {
model?: string;
+ agentKind?: AgentKind;
effort?: string;
fastMode?: boolean;
resolvedSelection?: ScheduledModelSelection;
@@ -2045,6 +2116,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
holder: EphemeralSessionHolder,
routingBaseline: {
model?: string;
+ agentKind?: AgentKind;
effort?: string;
fastMode?: boolean;
resolvedSelection?: ScheduledModelSelection;
@@ -2062,6 +2134,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
scheduleName: schedule.name,
runId: ctx.runId,
} as const;
+ let preparedPiRoute: { model: string; providerId: string | null } | null = null;
// "Open session" 尽早可用(sessionId 已知,无需等派发)。
if (!options?.sessionAlreadyBound) {
@@ -2182,6 +2255,16 @@ export class MakerScheduleRunner implements ScheduleRunner {
? `${UI_ACTION_TRIGGER_PREFIX}${schedule.prompt}`
: schedule.prompt,
origin,
+ onPreparing: async () => {
+ const preparingLive = this.deps.maker.getSession(sessionId);
+ if ((preparingLive?.agentKind ?? routingBaseline.agentKind ?? schedule.agentKind) !== 'pi') return;
+ preparedPiRoute = await this.prepareQueuedPiRouting(
+ schedule, sessionId, preparingLive, routingBaseline,
+ );
+ },
+ onPreparationFailed: (error) => {
+ failDispatch(error instanceof Error ? error : new Error(String(error)));
+ },
onAccepted: async (queuedPermissions) => {
dispatched = true;
// Queue admission happens while another (possibly user-driven)
@@ -2257,7 +2340,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// (PR #972 review P2)。凭证形态需要切换的场景无法热切;当前路由仍一致时
// 跳过并留日志,thread/store 已错配时 fail-closed。
try {
- await this.applyQueuedHeartbeatRouting(schedule, live, routingBaseline);
+ await this.applyQueuedHeartbeatRouting(schedule, live, routingBaseline, preparedPiRoute);
} catch (err) {
if (
err instanceof QueuedRouteDisabledError ||
@@ -2577,6 +2660,52 @@ export class MakerScheduleRunner implements ScheduleRunner {
* setModel / setEffort 成功才落库 meta,失败保留旧值让下轮重试(与直发路径的
* 复用会话语义一致)。
*/
+ private async prepareQueuedPiRouting(
+ schedule: Schedule,
+ sessionId: string,
+ live: ReturnType<Maker['getSession']>,
+ baseline: {
+ model?: string;
+ resolvedSelection?: ScheduledModelSelection;
+ providerId: string | null;
+ },
+ ): Promise<{ model: string; providerId: string | null }> {
+ const model = schedule.model?.trim() || baseline.model?.trim() || live?.model ||
+ defaultModelFor('pi');
+ const currentProviderId = getSessionProvider(sessionId) ?? baseline.providerId;
+ const explicitProviderId = schedule.providerId?.trim() || null;
+ const routeProviderId = explicitProviderId ?? currentProviderId;
+ let providerId = routeProviderId;
+ if (this.deps.checkModelRoute) {
+ const verdict = await this.deps.checkModelRoute('pi', model, routeProviderId);
+ if (verdict.kind === 'reject') {
+ throw new QueuedRouteDisabledError(
+ `schedule route unavailable: ${describeModelRouteRejection(verdict.reason, model, routeProviderId)} (${verdict.reason})`,
+ );
+ }
+ if (verdict.kind === 'reroute' && shouldApplyExclusiveProviderRerouteLive(routeProviderId)) {
+ providerId = verdict.providerId;
+ }
+ }
+ const resolved = baseline.resolvedSelection;
+ if (resolved && (resolved.agentKind !== 'pi' || resolved.model !== model ||
+ resolved.providerId !== providerId)) {
+ throw new QueuedRouteDisabledError('Scheduled model route changed before queued dispatch');
+ }
+ if (!this.deps.applyPiModelSelectionUnderLock) {
+ throw new QueuedPiRouteSyncError('Scheduled Pi model selection is not available');
+ }
+ const applied = await this.deps.applyPiModelSelectionUnderLock(
+ sessionId, model, providerId,
+ { model: live?.model ?? baseline.model ?? model, providerId: currentProviderId },
+ { refreshPiConfiguration: true, source: 'agent' },
+ );
+ if (applied.status !== 'applied') {
+ throw new QueuedPiRouteSyncError('Scheduled Pi model selection was deferred');
+ }
+ return { model, providerId };
+ }
+
private async applyQueuedHeartbeatRouting(
schedule: Schedule,
live: NonNullable<ReturnType<Maker['getSession']>>,
@@ -2587,6 +2716,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
resolvedSelection?: ScheduledModelSelection;
providerId: string | null;
},
+ preparedPiRoute: { model: string; providerId: string | null } | null = null,
): Promise<void> {
const explicitModel = schedule.model?.trim() ? schedule.model : undefined;
const targetModel =
@@ -2663,6 +2793,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
);
}
if (
+ live.agentKind !== 'pi' &&
shouldCloseSessionForCredentialSwitch({
agentKind: live.agentKind,
remoteHostId: live.remoteHostId,
@@ -2707,6 +2838,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
return;
}
if (
+ live.agentKind !== 'pi' &&
(await live.requiresModelSwitchRebuild?.(targetModel, { providerId: nextProviderId })) ===
true
) {
@@ -2726,8 +2858,17 @@ export class MakerScheduleRunner implements ScheduleRunner {
// Pi BYOM 无效,即使 model 字符串没变也不能跳过。
const mustSyncPiNativeRoute =
live.agentKind === 'pi' && (explicitModel !== undefined || applyProviderId !== null);
+ if (live.agentKind === 'pi') {
+ // The full window transaction already ran before the send captured this
+ // Session. A later route drift must fail before vendor dispatch.
+ if (!preparedPiRoute || live.model !== preparedPiRoute.model ||
+ getSessionProvider(live.id) !== preparedPiRoute.providerId ||
+ targetModel !== preparedPiRoute.model || nextProviderId !== preparedPiRoute.providerId) {
+ throw new QueuedPiRouteSyncError('Scheduled Pi route changed after preparation');
+ }
+ }
let modelApplied = true;
- if (modelChanged || mustSyncPiNativeRoute) {
+ if (live.agentKind !== 'pi' && (modelChanged || mustSyncPiNativeRoute)) {
try {
if (mustSyncPiNativeRoute) {
await live.setModel(targetModel, { providerId: nextProviderId });
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 6e1d431080..73fc9b78ec 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -789,6 +789,9 @@ const fanOutMakerCodexRuntimeRouteChanged = createIpcFanOut('maker:codex-runtime
const fanOutMakerSessionCredentialSwitchApplied = createIpcFanOut(
'maker:session-credential-switch-applied',
);
+const fanOutMakerSessionCredentialSwitchFailed = createIpcFanOut(
+ 'maker:session-credential-switch-failed',
+);
const fanOutMakerClaudeSessionRouteChanged = createIpcFanOut('maker:claude-session-route-changed');
const fanOutIOSSimulatorFocusRequest = createIpcFanOut('maker:ios-simulator:focus-request');
const fanOutIOSSimulatorH264Frame = createIpcFanOut('maker:ios-simulator:h264-frame');
@@ -7233,6 +7236,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onCodexRuntimeRouteChanged: fanOutMakerCodexRuntimeRouteChanged,
// 延迟凭证切换兑现(见 setModel deferred):清"任务结束后生效"标记 / 会话内轻提示。
onSessionCredentialSwitchApplied: fanOutMakerSessionCredentialSwitchApplied,
+ onSessionCredentialSwitchFailed: fanOutMakerSessionCredentialSwitchFailed,
// cc 默认路由会话的生效计费路由(proxy 按请求观察): 'gateway' | 'subscription' |
// null(会话尚未发过请求)。用量 chip 优先用它显示订阅/网关形态。
diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
index fd932cdb77..9d9b77173d 100644
--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
@@ -66,6 +66,31 @@ function stubElectron() {
const sess = (id: string): Session => ({ id }) as unknown as Session;
describe('makerApiFor 路由(完整对等会话级操作)', () => {
+ it('accepts deferred switch outcomes only from the owning remote device and session', async () => {
+ stubElectron();
+ let listener: ((push: { deviceId: string; channel: string; payload: unknown }, stamp?: unknown) => void) | undefined;
+ const off = vi.fn();
+ window.electronAPI.deviceLink.onRemotePush = vi.fn((callback) => {
+ listener = callback as typeof listener;
+ return off;
+ });
+ const { setDataOwnerGeneration } = await import('@/contexts/dataOwnerGeneration');
+ setDataOwnerGeneration('owner-a', 1);
+ const { subscribeRemoteCredentialSwitchOutcome } = await import('@/lib/makerTransport');
+ const outcomes: unknown[] = [];
+ const dispose = subscribeRemoteCredentialSwitchOutcome('session-a', 'device-a', (value) => outcomes.push(value));
+ listener?.({ deviceId: 'device-b', channel: 'maker:session-credential-switch-failed', payload: { sessionId: 'session-a', reason: 'apply-failed' } });
+ listener?.({ deviceId: 'device-a', channel: 'maker:session-credential-switch-failed', payload: { sessionId: 'session-b', reason: 'apply-failed' } });
+ listener?.({ deviceId: 'device-a', channel: 'maker:session-credential-switch-failed', payload: { sessionId: 'session-a', reason: 'unexpected' } });
+ listener?.({ deviceId: 'device-a', channel: 'maker:session-credential-switch-failed', payload: { sessionId: 'session-a', reason: 'apply-failed', error: 'never show secret' } });
+ listener?.({ deviceId: 'device-a', channel: 'maker:session-credential-switch-applied', payload: { sessionId: 'session-a', model: 'next', providerId: null } });
+ expect(outcomes).toEqual([
+ { kind: 'failed', sessionId: 'session-a', reason: 'apply-failed' },
+ { kind: 'applied', sessionId: 'session-a' },
+ ]);
+ dispose();
+ expect(off).toHaveBeenCalledOnce();
+ });
it('routes connection input only through the dedicated local Main bridge', async () => {
const {makerSpies, invoke} = stubElectron();
const {submitRemotePluginConnection} = await import('@/lib/makerTransport');
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 5576c8e402..eb1c6eaa32 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -399,7 +399,7 @@ import { createWorkLouderCodexVoiceGesture } from '@/lib/workLouderCodexVoiceGes
import { appendMentionChip } from './mentionChipInsertion';
// device-link 远程会话:设置变更不落本地 DB(会 404),改写远程内存层 + 运行时隧道。
import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
-import { makerApiFor, makerApiForDevice, makerApiForSticky } from '@/lib/makerTransport';
+import { makerApiFor, makerApiForDevice, makerApiForSticky, subscribeRemoteCredentialSwitchOutcome } from '@/lib/makerTransport';
import { SESSION_LINK_DROP_MIME } from '@/lib/sessionLinkDrop';
const log = createLogger('ChatInput');
@@ -1287,9 +1287,28 @@ export function ChatInput({
if (!sessionId) return;
return window.electronAPI.maker.onSessionCredentialSwitchApplied((payload) => {
if (payload.sessionId !== sessionId) return;
+ if (deviceLinkDeviceId || getSessionDeviceId(sessionId)) return;
toast.success(t('newChat.chatInput.credentialSwitchApplied'), { duration: 3000 });
});
- }, [sessionId, t]);
+ }, [deviceLinkDeviceId, sessionId, t]);
+ useEffect(() => {
+ if (!sessionId) return;
+ return window.electronAPI.maker.onSessionCredentialSwitchFailed((payload) => {
+ if (payload.sessionId !== sessionId) return;
+ if (deviceLinkDeviceId || getSessionDeviceId(sessionId)) return;
+ toast.error(t('newChat.chatInput.credentialSwitchFailed'), { duration: 6000 });
+ });
+ }, [deviceLinkDeviceId, sessionId, t]);
+ useEffect(() => {
+ if (!sessionId) return;
+ return subscribeRemoteCredentialSwitchOutcome(sessionId, deviceLinkDeviceId ?? undefined, (outcome) => {
+ if (outcome.kind === 'applied') {
+ toast.success(t('newChat.chatInput.credentialSwitchApplied'), { duration: 3000 });
+ } else {
+ toast.error(t('newChat.chatInput.credentialSwitchFailed'), { duration: 6000 });
+ }
+ });
+ }, [deviceLinkDeviceId, sessionId, t]);
// F-QUEUE-1 — preserve prior semantics
const showStopButton = isAgentBusy ?? isStreaming;
const { confirm: confirmDialog } = useConfirmDialog();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7e5e9ff2e1..be22e0411f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9041,6 +9041,7 @@
"credentialSwitchDeferred": "Model provider switched — it takes effect after the current task finishes.",
"effortRuntimeDirty": "Reasoning effort is still updating. Wait a moment, then send again.",
"credentialSwitchApplied": "Model provider switch is now in effect.",
+ "credentialSwitchFailed": "Model provider switch failed. Choose the model again.",
"modelSwitchContextGuard": {
"title": "This model can't fit the current conversation",
"warnToast": "This conversation already uses {{used}} — about {{pct}}% of the new model's {{total}} capacity",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6ecee5d9cc..c52f1633f1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9039,6 +9039,7 @@
"credentialSwitchDeferred": "モデルプロバイダーを切り替えました。現在のタスク終了後に有効になります。",
"effortRuntimeDirty": "推論強度を更新しています。少し待ってからもう一度送信してください。",
"credentialSwitchApplied": "モデルプロバイダーの切り替えが有効になりました。",
+ "credentialSwitchFailed": "モデルプロバイダーの切り替えに失敗しました。モデルを選び直してください。",
"modelSwitchContextGuard": {
"title": "このモデルには今の会話が収まりません",
"warnToast": "この会話はすでに {{used}} 使っています。切替後は新しいモデルの容量({{total}})の約 {{pct}}% になります",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2e03258188..56cd8a3618 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9039,6 +9039,7 @@
"credentialSwitchDeferred": "모델 제공자를 전환했습니다. 현재 작업이 끝난 후 적용됩니다.",
"effortRuntimeDirty": "추론 강도를 업데이트하고 있습니다. 잠시 후 다시 전송해 주세요.",
"credentialSwitchApplied": "모델 제공자 전환이 적용되었습니다.",
+ "credentialSwitchFailed": "모델 제공자 전환에 실패했습니다. 모델을 다시 선택해 주세요.",
"modelSwitchContextGuard": {
"title": "이 모델에는 지금 대화를 다 넣을 수 없습니다",
"warnToast": "이 대화는 이미 {{used}}를 사용 중입니다. 바꾸면 새 모델 용량({{total}})의 약 {{pct}}%가 됩니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 6c4db5ab90..2cd121d5af 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9039,6 +9039,7 @@
"credentialSwitchDeferred": "模型来源已切换,将在当前任务结束后生效。",
"effortRuntimeDirty": "推理强度还在更新,稍等一下再发送",
"credentialSwitchApplied": "模型来源切换已生效。",
+ "credentialSwitchFailed": "模型来源切换失败,请重新选择。",
"modelSwitchContextGuard": {
"title": "这个模型装不下当前对话",
"warnToast": "这段对话已经用了 {{used}},换过去大约会占新模型容量({{total}})的 {{pct}}%",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c2c0da3b3a..a88accd5a5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9039,6 +9039,7 @@
"credentialSwitchDeferred": "模型來源已切換,將在當前任務結束後生效。",
"effortRuntimeDirty": "推理強度還在更新,稍等一下再傳送",
"credentialSwitchApplied": "模型來源切換已生效。",
+ "credentialSwitchFailed": "模型來源切換失敗,請重新選擇。",
"modelSwitchContextGuard": {
"title": "這個模型裝不下目前的對話",
"warnToast": "這段對話已經用了 {{used}},換過去大約會佔新模型容量({{total}})的 {{pct}}%",
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index 6925d100e6..4fb83b5727 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -37,6 +37,33 @@ import type { LocalPluginOauthRequest, LocalPluginSecretRequest, LocalPluginConn
type FullMaker = typeof window.electronAPI.maker;
+export type RemoteCredentialSwitchOutcome =
+ | { kind: 'applied'; sessionId: string }
+ | { kind: 'failed'; sessionId: string; reason: 'apply-failed' | 'rollback-failed' };
+
+/** A deferred model choice settles on its owning device after the invoke has returned. */
+export function subscribeRemoteCredentialSwitchOutcome(
+ sessionId: string,
+ deviceId: string | undefined,
+ callback: (outcome: RemoteCredentialSwitchOutcome) => void,
+): () => void {
+ if (!sessionId) return () => {};
+ return window.electronAPI.deviceLink.onRemotePush((push, ownerStamp) => {
+ const sourceDeviceId = deviceId ?? getStickySessionDeviceId(sessionId);
+ if (!sourceDeviceId || push.deviceId !== sourceDeviceId || !isDeviceLinkRemotePushCurrent(push, ownerStamp)) return;
+ const payload = push.payload;
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return;
+ const value = payload as Record<string, unknown>;
+ if (value.sessionId !== sessionId) return;
+ if (push.channel === 'maker:session-credential-switch-applied') {
+ callback({ kind: 'applied', sessionId });
+ } else if (push.channel === 'maker:session-credential-switch-failed' &&
+ (value.reason === 'apply-failed' || value.reason === 'rollback-failed')) {
+ callback({ kind: 'failed', sessionId, reason: value.reason });
+ }
+ });
+}
+
/** The dedicated local Main API owns the browser and encrypted callback; Renderer sees status only. */
export function assistRemotePluginOauth(
sessionId: string,
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6d76ad25c9..f94a378189 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6498,6 +6498,9 @@ interface ElectronAPI {
onSessionCredentialSwitchApplied: (
cb: (payload: { sessionId: string; model: string; providerId: string | null }) => void,
) => () => void;
+ onSessionCredentialSwitchFailed: (
+ cb: (payload: { sessionId: string; reason: 'apply-failed' | 'rollback-failed' }) => void,
+ ) => () => void;
/** cc 默认路由会话的生效计费路由(proxy 按请求观察);null = 会话尚未发过请求 */
claudeSessionRouteGet: (sessionId: string) => Promise<'gateway' | 'subscription' | null>;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 35173c569e..6ea50560d8 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -114,6 +114,7 @@ import { hasSessionEntryPreviewMismatch } from '@/session/sessionEntrySyncIndica
import { resolveEffectiveConnectionError } from '@/components/connectionBannerVisibility';
import { PaperPlaneIcon } from '@/components/PaperPlaneIcon';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { subscribeCredentialSwitchOutcome } from '@/session/credentialSwitchOutcome';
import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
import { useSharedTaskAccess } from '@/device-link/useSharedTaskAccess';
import { useLeaveSharedTask } from '@/device-link/useLeaveSharedTask';
@@ -992,6 +993,10 @@ export default function SessionScreen() {
const visualOpenSearch = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualOpenSearch) === '1';
const visualSearchQuery = MOBILE_VISUAL_MOCK_ENABLED ? readRouteParam(params.visualSearchQuery) : null;
const navigation = useNavigation<SessionRouteParamsNavigation & { isFocused(): boolean }>();
+ useEffect(() => subscribeCredentialSwitchOutcome((outcome) => {
+ if (outcome.deviceId !== deviceId || outcome.sessionId !== sessionId || !navigation.isFocused()) return;
+ Alert.alert(t(outcome.kind === 'applied' ? 'models.switchOutcome.applied' : 'models.switchOutcome.failed'));
+ }), [deviceId, navigation, sessionId, t]);
const router = useRouter();
// 完整消息读取权限按「会话 + 单调代际」登记。focus 与 AppState 正交:后台时
// 导航仍可能保持 focused,必须立即撤权;重新聚焦/回前台会生成新代际,使旧
diff --git a/apps/mobile/src/__tests__/credentialSwitchOutcome.test.ts b/apps/mobile/src/__tests__/credentialSwitchOutcome.test.ts
new file mode 100644
index 0000000000..99dfce4157
--- /dev/null
+++ b/apps/mobile/src/__tests__/credentialSwitchOutcome.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+import {
+ dispatchCredentialSwitchOutcome,
+ subscribeCredentialSwitchOutcome,
+} from '@/session/credentialSwitchOutcome';
+
+describe('credential switch outcome pushes', () => {
+ it('delivers only typed outcomes with the owning device and session', () => {
+ const received: unknown[] = [];
+ const off = subscribeCredentialSwitchOutcome((outcome) => received.push(outcome));
+ try {
+ dispatchCredentialSwitchOutcome('device-a', 'maker:session-credential-switch-failed', {
+ sessionId: 'session-a', reason: 'apply-failed', error: 'internal secret must not surface',
+ });
+ dispatchCredentialSwitchOutcome('device-b', 'maker:session-credential-switch-applied', {
+ sessionId: 'session-b', model: 'model', providerId: null,
+ });
+ dispatchCredentialSwitchOutcome('device-a', 'maker:session-credential-switch-failed', {
+ sessionId: 'session-a', reason: 'unknown',
+ });
+ dispatchCredentialSwitchOutcome('device-a', 'maker:session-credential-switch-applied', { sessionId: '' });
+ expect(received).toEqual([
+ { deviceId: 'device-a', sessionId: 'session-a', kind: 'failed', reason: 'apply-failed' },
+ { deviceId: 'device-b', sessionId: 'session-b', kind: 'applied' },
+ ]);
+ } finally {
+ off();
+ }
+ dispatchCredentialSwitchOutcome('device-a', 'maker:session-credential-switch-applied', { sessionId: 'session-a' });
+ expect(received).toHaveLength(2);
+ });
+});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 840f377def..b4f13578d5 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -8,6 +8,7 @@ import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase }
import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';
import { AppState, Platform } from 'react-native';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
+import { dispatchCredentialSwitchOutcome } from '@/session/credentialSwitchOutcome';
import { mobileRuntimeIdentity } from '@/debug/mobileRuntimeIdentity';
import {
DeviceLinkClient,
@@ -1631,6 +1632,7 @@ export function routeFrame(env: Envelope, handlers: {
if (peerLinkClosed) return;
if (env.kind !== 'push' || !env.src) return;
const push = env.payload as PushPayload;
+ dispatchCredentialSwitchOutcome(env.src, push.channel, push.payload);
if (push.channel === 'local-db:task-tags:changed') {
writeTaskTagCatalog(
handlers.currentDataOwnerId,
diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.json
index 618451c401..593087f552 100644
--- a/apps/mobile/src/i18n/locales/en/models.json
+++ b/apps/mobile/src/i18n/locales/en/models.json
@@ -47,6 +47,10 @@
"cancel": "Keep this model",
"confirm": "Switch and continue"
},
+ "switchOutcome": {
+ "applied": "Model provider switch is now in effect.",
+ "failed": "Model provider switch failed. Choose the model again."
+ },
"agentSwitch": {
"browseAccessibility": "Browse {{agent}} models",
"confirmTitle": "Switch to {{agent}}?",
diff --git a/apps/mobile/src/i18n/locales/ja/models.json b/apps/mobile/src/i18n/locales/ja/models.json
index 9441a43b06..79db508984 100644
--- a/apps/mobile/src/i18n/locales/ja/models.json
+++ b/apps/mobile/src/i18n/locales/ja/models.json
@@ -47,6 +47,10 @@
"cancel": "現在のモデルを維持",
"confirm": "切り替えて続行"
},
+ "switchOutcome": {
+ "applied": "モデルプロバイダーの切り替えが有効になりました。",
+ "failed": "モデルプロバイダーの切り替えに失敗しました。モデルを選び直してください。"
+ },
"agentSwitch": {
"browseAccessibility": "{{agent}} のモデルを表示",
"confirmTitle": "{{agent}} に切り替えますか?",
diff --git a/apps/mobile/src/i18n/locales/ko/models.json b/apps/mobile/src/i18n/locales/ko/models.json
index 6adbe9f631..ec357c9f7a 100644
--- a/apps/mobile/src/i18n/locales/ko/models.json
+++ b/apps/mobile/src/i18n/locales/ko/models.json
@@ -47,6 +47,10 @@
"cancel": "현재 모델 유지",
"confirm": "전환하고 계속"
},
+ "switchOutcome": {
+ "applied": "모델 제공자 전환이 적용되었습니다.",
+ "failed": "모델 제공자 전환에 실패했습니다. 모델을 다시 선택해 주세요."
+ },
"agentSwitch": {
"browseAccessibility": "{{agent}} 모델 보기",
"confirmTitle": "{{agent}}(으)로 전환할까요?",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/models.json b/apps/mobile/src/i18n/locales/zh-CN/models.json
index 1303524033..54f8789263 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/models.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json
@@ -47,6 +47,10 @@
"cancel": "保留当前模型",
"confirm": "切换并继续"
},
+ "switchOutcome": {
+ "applied": "模型来源切换已生效。",
+ "failed": "模型来源切换失败,请重新选择。"
+ },
"agentSwitch": {
"browseAccessibility": "浏览 {{agent}} 模型",
"confirmTitle": "切换到 {{agent}}?",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/models.json b/apps/mobile/src/i18n/locales/zh-TW/models.json
index 23685ae0fc..30d526d8a8 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/models.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/models.json
@@ -47,6 +47,10 @@
"cancel": "保留目前模型",
"confirm": "切換並繼續"
},
+ "switchOutcome": {
+ "applied": "模型來源切換已生效。",
+ "failed": "模型來源切換失敗,請重新選擇。"
+ },
"agentSwitch": {
"browseAccessibility": "瀏覽 {{agent}} 模型",
"confirmTitle": "切換到 {{agent}}?",
diff --git a/apps/mobile/src/session/credentialSwitchOutcome.ts b/apps/mobile/src/session/credentialSwitchOutcome.ts
new file mode 100644
index 0000000000..0dd4d1ac36
--- /dev/null
+++ b/apps/mobile/src/session/credentialSwitchOutcome.ts
@@ -0,0 +1,28 @@
+export type CredentialSwitchOutcome =
+ | { deviceId: string; sessionId: string; kind: 'applied' }
+ | { deviceId: string; sessionId: string; kind: 'failed'; reason: 'apply-failed' | 'rollback-failed' };
+
+const listeners = new Set<(outcome: CredentialSwitchOutcome) => void>();
+
+/** Live outcome notifications accompany the durable sessions:patched route projection. */
+export function subscribeCredentialSwitchOutcome(listener: (outcome: CredentialSwitchOutcome) => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
+
+export function dispatchCredentialSwitchOutcome(deviceId: string, channel: string, payload: unknown): void {
+ if (!deviceId || !payload || typeof payload !== 'object' || Array.isArray(payload)) return;
+ const value = payload as Record<string, unknown>;
+ const sessionId = value.sessionId;
+ if (typeof sessionId !== 'string' || !sessionId) return;
+ let outcome: CredentialSwitchOutcome;
+ if (channel === 'maker:session-credential-switch-applied') {
+ outcome = { deviceId, sessionId, kind: 'applied' };
+ } else if (channel === 'maker:session-credential-switch-failed' &&
+ (value.reason === 'apply-failed' || value.reason === 'rollback-failed')) {
+ outcome = { deviceId, sessionId, kind: 'failed', reason: value.reason };
+ } else {
+ return;
+ }
+ for (const listener of listeners) listener(outcome);
+}
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 20352bc903..1e04f717c1 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -94,10 +94,14 @@ Pi 任务时冻结,并写入该任务 `settings.json` 的 `compaction.reserveT
模型容量用于 Pi 原生请求长度裁剪,不能随小预算缩到 1K;工作预算只调整原生压缩阈值,
并作为已应用预算进入 Cindy 的用量快照。
大窗切小窗先由 Desktop 的统一目标窗口事务按目标窗口 90% 固定压力线评估(独立于 Pi
-日常自动压缩百分比),命中时换干净原生窗口;未命中时 Pi 重写 settings 后调用
-`switch_session`,必须重新 `set_model` 并用 `get_state` 校验
-provider/model/contextWindow,因为 Pi 会用进程初始 CLI route 重建 runtime。校验完成前
-子代理 route 保持 pending,失败则终止该 live 任务。Claude Code 仍用独立百分比。env:`CINDY_PI_API_KEY`、
+日常自动压缩百分比),命中时复用既有上下文接续事务;未命中时保留当前原生会话,使用
+`set_compaction_reserve_tokens` 原地更新压缩保留量,再用原生 `set_model` 与 `get_state`
+确认 provider/model/contextWindow。同 ID 模型的目录资料或工作预算改变也属于这条路径。
+普通切模不得用 `switch_session` 或扩展 `/reload` 重读压缩配置:两者会重建会话或扩展状态,
+不能当成无损配置刷新。忙时选择必须在回合结束后走同一切换与容量事务,不能由延后服务
+直接关闭 Pi。原生校验完成前,子代理 route 保持 pending;确认并持久化目标路由后才放行
+排队消息。
+Claude Code 仍用独立百分比。env:`CINDY_PI_API_KEY`、
`CINDY_PI_SESSION_ID`、`PI_CODING_AGENT_DIR`、`CINDY_PI_PERMISSION_FILE`、`CINDY_PI_MCP_BRIDGE`、
外部 MCP 专用动态 env、`PI_OFFLINE=1`(关启动期联网)、`NO_PROXY` 兜底 loopback(防全局代理
打穿本地 proxy 与 MCP bridge)。
@@ -123,6 +127,26 @@ SSH 不套用本机限核值。沿用现有默认值与 override 存储,不新
未配置 Pi 百分比且未缩小工作预算时不写 `reserveTokens`,沿用 Pi 默认 16384;
显式小预算仍以默认 90% 计算触发阈值。
+### 运行中的模型目录与凭据更新
+
+模型目录更新沿用 Cindy 的统一目录和 Pi 的原生 provider 配置,不能另建一份模型权威表。
+先预览目标资料和容量,再在现有串行切换边界应用配置;Pi 的 `refresh_models` 只刷新目录,
+即使 provider/model ID 未变也须通过 `set_model` 应用新 descriptor。刷新响应中的
+`aborted` 或 provider errors 表示未完整成功,不能仅凭 RPC `success: true` 继续。
+
+新增原生适配器使用 Pi 公开的 `unregisterProvider`/`registerProvider` 与模型目录刷新,
+不重建用户扩展。模型凭据仅通过宿主发起、绑定本次运行实例和随机 nonce 的私有交接进入
+Pi 内存,不进入 prompt、聊天历史、日志或明文配置文件。交接同时维护 bash 凭据剥离名单、
+后续子代理的启动配置和来源专用授权;已运行子代理仍保留其独立身份。私有命令的 prompt
+响应不等于配置成功,必须收到对应 nonce 的完成回执。来源一致性检查不可因热切而删除。
+
+`refresh_models` 与 `set_compaction_reserve_tokens` 需要配套 Pi 原生 RPC 支持;当前
+`tools/pi/latest.json` 的版本 pin 不代表这两项接口已经发布。旧 Pi 缺少本次操作所需接口时,
+在改变当前模型前明确反馈,不自动降级为会话重载。开发、单测或本地补丁通过不等于托管
+runtime 已升级;发布须分别核验 Pi 接口、Cindy 接入与实际 runtime 版本。
+接口补丁、重启边界和隔离验证见
+[`../research/pi-native-model-refresh.md`](../research/pi-native-model-refresh.md)。
+
Skill 停用适配同时保存物理身份与管理页已扫描的词法发现入口;启动前只采用仍指向该
物理身份的入口,直接加入 Pi 排除配置,不依赖重新遍历宽目录。旧偏好没有发现入口时
diff --git a/docs/research/pi-native-model-refresh.md b/docs/research/pi-native-model-refresh.md
new file mode 100644
index 0000000000..3b801a7f4a
--- /dev/null
+++ b/docs/research/pi-native-model-refresh.md
@@ -0,0 +1,88 @@
+# Pi 原生模型刷新与会话连续性
+
+## 问题与采用的方向
+
+已有任务跨来源选模型被拒绝,源于 Cindy 外层将来源变化一律判成进程替换,
+而窗口检查又禁止这类替换。只删除拒绝条件会恢复换模型,但仍会丢掉 Pi 进程内状态。
+此外,过去通过 `switch_session` 重读压缩配置,即使不退出进程,也会重建会话和扩展。
+
+本次沿用 Pi 原生模型选择、provider 注册和压缩机制:普通切模保留当前会话,
+目录下发与凭据变化先进入 Pi,再选择目标模型;容量不足走 Cindy 已有的目标窗口
+保护和上下文接续。不能把重新打开 Pi 会话当作普通配置刷新。
+
+对应报告:[跨来源选择被拒绝](https://github.com/makecindy/cindy/issues/4486)。
+其建议中的关闭后懒创建不是本次采用的默认方案。
+
+## Pi 配套改动与发布依赖
+
+[配套补丁](pi-native-model-refresh.patch) 基于 Pi
+`1b347794e2a630e4359f2584f4eea388145d0ddf`,新增两个小范围原生 RPC:
+
+- `refresh_models`:离线重读模型配置,不替换当前模型描述、扩展实例或排队输入。
+ 返回的 `aborted` 和 provider `errors` 必须同时检查;成功后显式 `set_model`
+ 才应用目标描述,包括 provider/model ID 没变的情况。
+- `set_compaction_reserve_tokens`:调整当前会话的压缩保留量,所有既有压缩入口
+ 读取同一有效值;`null` 恢复配置值。不会落盘或触发会话重载。
+
+该补丁是供评审与上游提交使用的源码制品,**不被 Cindy 构建自动应用**。
+`tools/pi/latest.json` 仍为 v0.85.1,没有改 pin、下载或替换托管 runtime。
+因此本分支不代表现有安装版本已具备新增接口,也不能单独作为完整修复发布。
+配套 Pi 版本发布、托管 runtime 更新和实际平台验收须分别完成。
+
+旧 Pi 可以直接完成的选择继续使用原生 `set_model`;需要新接口时,先探测其支持,
+在改变目录、凭据或模型前报错,保留原会话。不能用 `switch_session`、`/reload`
+或自动关闭来掩盖接口缺失。
+
+2026-09-30 查询时,上游贡献规则要求维护者先给予 `lgtm`,当前提交账号未在批准
+名册中;配套改动已本地实现并验证,尚未向上游提交 PR。规则见
+[Pi CONTRIBUTING.md](https://github.com/earendil-works/pi/blob/1b347794e2a630e4359f2584f4eea388145d0ddf/CONTRIBUTING.md)。
+
+## 哪些动作需要替换状态
+
+| 情况 | 本次处理 | 是否重开 Pi |
+| --- | --- | --- |
+| 已加载的模型或供应商之间切换 | 原生选择,核实实际模型与窗口 | 否 |
+| Cindy 新增模型、同名模型资料变化 | 刷新当前目录,重新应用目标模型 | 否,需配套接口 |
+| 新增供应商或凭据更新 | 私有交接,更新 Cindy 管理的 provider 注册 | 否,需配套接口 |
+| 压缩预算变化 | 修改当前会话保留量 | 否,需配套接口 |
+| 内容已接近目标小窗口上限 | Cindy 既有目标窗口保护与有交接内容的接续 | 可能;这是容量接续,不是选来源的固定步骤 |
+| 回合正在执行 | 等既有安全边界,再运行同一选择事务 | 不为选择中断回合 |
+| Pi 已退出、可执行版本或不可热更的启动条件变化 | 按既有生命周期恢复或显式更新 | 需要新进程;不属于普通模型切换 |
+| 发生部分应用且无法确认实际路由 | 明确失败并停止不确定的运行实例,禁止错误来源继续接收内容 | 故障处理,不能假报无损切换 |
+
+同一任务保存的聊天记录、Pi 原生会话及扩展内存是不同层次。保留聊天记录不等于
+重开 Pi 没有损失。本机 Gateway 代理每次请求读取当前 key;启动占位 key 不是
+必须重启的理由。SSH 则需另外维护远端凭据和按需代理转发。
+
+## 实现边界
+
+模型权威仍为 Cindy 统一目录。运行中的 Pi 使用最新可选清单枚举新增 ID,再按来源
+取得具体描述;不能只更新选择器,或从启动时模型数组推断实时可用模型。
+私有模型文件与设置文件需要回滚时,恢复原字节,不用已经变化的新目录重新生成旧状态。
+
+凭据不放进 prompt、历史或日志。宿主仅对当前实例及本次随机 nonce 返回受限的
+凭据快照,收到对应完成回执才继续。只替换 Cindy 自己管理的原生适配器;用户其它扩展
+不被卸载。新启动子任务同步已应用的目录、能力与独立来源授权;已运行子任务保持自身身份。
+
+桌面本机、device-link 远控、手机、IM 和定时任务的选择必须走同一宿主容量事务。定时任务
+在捕获运行实例、等待结果和拼接交接内容前完成容量准备;排队派发也经过同一发送锁。
+延后选择在
+回合结束后仍经过该事务;旧选择的迟到回执不能覆盖新选择或新账号。失败通知独立于成功
+通知,使用固定原因码,不把原始错误或凭据传给控制端。
+
+## 验证证据与限制
+
+Pi 补丁的 3 个定向测试文件共 22 个用例通过,覆盖真实 JSONL RPC handler、
+RPC client、运行中的压缩触发阈值、参数校验、同 ID 模型重新选择及队列/扩展保留。
+定向类型检查与改动文件格式检查通过。没有运行 Pi 整仓构建或全量测试。
+
+另将 Cindy 实际生成的原生适配器和私有命令载入真实 Pi 测试 harness,用隔离临时目录、
+假模型和假凭据验证新增供应商、同 ID 更新、nonce 回执及扩展实例/排队内容保留,1 个整合
+用例通过。没有调用付费模型或读取个人授权。这不是正在运行的 Cindy 产品验收。
+
+Cindy 核心模型路由与压缩预算的两个定向文件共 144 个用例通过,新增私有桥接的
+3 个用例通过。宿主与既有容量事务的 6 个文件 323 例通过,收尾后相关 4 个文件
+156 例通过(两组有重叠,不相加);调度直发/排队的 2 个文件 156 例通过,包含冷 Pi
+历史恢复、跨来源热切、准备失败停止发送及结果监听顺序。各消费入口的定向验证见本 PR 的验证记录。未启动 Desktop DEV、模拟器或现有
+Pi 任务;未完成 Windows、SSH 主机或桌面/手机双设备实机验收。源码与隔离验证通过,
+不能替代配套 runtime 发布后各端的实际选择与容量接续验收。
diff --git a/docs/research/pi-native-model-refresh.patch b/docs/research/pi-native-model-refresh.patch
new file mode 100644
index 0000000000..15aadf8724
--- /dev/null
+++ b/docs/research/pi-native-model-refresh.patch
@@ -0,0 +1,542 @@
+diff --git a/packages/coding-agent/docs/rpc-commands.md b/packages/coding-agent/docs/rpc-commands.md
+index 24f6032..894f2fc 100644
+--- a/packages/coding-agent/docs/rpc-commands.md
++++ b/packages/coding-agent/docs/rpc-commands.md
+@@ -269,6 +269,20 @@ Response contains an array of full [Model](#model-object) objects:
+ }
+ ```
+
++### refresh_models
++
++Reload `models.json` without replacing the session. This command does not perform network model discovery. It preserves the current model selection, extension instances, and queued messages. Use `set_model` after a successful refresh to apply a changed descriptor, even when the provider and model ID are unchanged.
++
++```json
++{"type": "refresh_models"}
++```
++
++Response data contains `models` (the available model snapshot), `aborted`, and `errors` (provider IDs mapped to error messages). Treat `aborted: true` or nonempty `errors` as an incomplete refresh; `success: true` only means the refresh command ran. A malformed model configuration returns a failed response.
++
++```json
++{"type": "response", "command": "refresh_models", "success": true, "data": {"models": [], "aborted": false, "errors": {}}}
++```
++
+ ## Thinking
+
+ ### set_thinking_level
+@@ -416,6 +430,18 @@ Response:
+ {"type": "response", "command": "set_auto_compaction", "success": true}
+ ```
+
++### set_compaction_reserve_tokens
++
++Set a non-negative safe integer reserve for the live session. `null` clears the runtime override and restores the configured value for the current model. The override applies to manual and automatic compaction without reloading extensions or changing queued messages. It is not saved to `settings.json` or carried into another session.
++
++```json
++{"type": "set_compaction_reserve_tokens", "reserveTokens": 32000}
++```
++
++```json
++{"type": "response", "command": "set_compaction_reserve_tokens", "success": true, "data": {"reserveTokens": 32000}}
++```
++
+ ## Retry
+
+ ### set_auto_retry
+diff --git a/packages/coding-agent/docs/rpc.md b/packages/coding-agent/docs/rpc.md
+index a39cc8d..e48d34f 100644
+--- a/packages/coding-agent/docs/rpc.md
++++ b/packages/coding-agent/docs/rpc.md
+@@ -156,6 +156,7 @@ The detailed references formerly on this page now have dedicated pages. These an
+ <a id="set_model"></a>
+ <a id="cycle_model"></a>
+ <a id="get_available_models"></a>
++<a id="refresh_models"></a>
+ <a id="set_thinking_level"></a>
+ <a id="cycle_thinking_level"></a>
+ <a id="get_available_thinking_levels"></a>
+@@ -163,6 +164,7 @@ The detailed references formerly on this page now have dedicated pages. These an
+ <a id="set_follow_up_mode"></a>
+ <a id="compact"></a>
+ <a id="set_auto_compaction"></a>
++<a id="set_compaction_reserve_tokens"></a>
+ <a id="set_auto_retry"></a>
+ <a id="abort_retry"></a>
+ <a id="bash"></a>
+diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
+index 4aaf3c2..7d22670 100644
+--- a/packages/coding-agent/src/core/agent-session.ts
++++ b/packages/coding-agent/src/core/agent-session.ts
+@@ -31,6 +31,7 @@ import {
+ runToolCall,
+ type ThinkingLevel,
+ } from "@earendil-works/pi-agent-core";
++import type { ModelsRefreshResult } from "@earendil-works/pi-ai";
+ import { contentText, getCurrentSystemMessage, retryDelayMs } from "@earendil-works/pi-ai";
+ import type {
+ AssistantMessage,
+@@ -382,6 +383,23 @@ export class AgentSession {
+ private _compactionAbortController: AbortController | undefined = undefined;
+ private _autoCompactionAbortController: AbortController | undefined = undefined;
+ private _overflowRecoveryAttempted = false;
++ private _runtimeCompactionReserveTokens: number | undefined;
++
++ /** Override the reserve for this live session without reloading its extensions or queues. */
++ setRuntimeCompactionReserveTokens(value: number | null): number {
++ if (value !== null && (!Number.isSafeInteger(value) || value < 0)) {
++ throw new Error("Compaction reserve tokens must be a non-negative safe integer or null.");
++ }
++ this._runtimeCompactionReserveTokens = value === null ? undefined : value;
++ return this.getEffectiveCompactionSettings(this.model).reserveTokens;
++ }
++
++ private getEffectiveCompactionSettings(model?: Model<any>): ReturnType<SettingsManager["getCompactionSettings"]> {
++ const settings = this.settingsManager.getCompactionSettings(model);
++ return this._runtimeCompactionReserveTokens === undefined
++ ? settings
++ : { ...settings, reserveTokens: this._runtimeCompactionReserveTokens };
++ }
+
+ // Branch summarization state
+ private _branchSummaryAbortController: AbortController | undefined = undefined;
+@@ -488,6 +506,11 @@ export class AgentSession {
+ return this._modelRuntime;
+ }
+
++ /** Reload the local model catalogue while retaining this session and its extensions. */
++ async refreshModels(): Promise<ModelsRefreshResult> {
++ return this._modelRuntime.refresh({ allowNetwork: false });
++ }
++
+ private async _getRequiredRequestAuth(
+ model: Model<any>,
+ signal?: AbortSignal,
+@@ -728,7 +751,7 @@ export class AgentSession {
+ return shouldCompact(
+ estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens,
+ model.contextWindow,
+- this.settingsManager.getCompactionSettings(this.model),
++ this.getEffectiveCompactionSettings(this.model),
+ );
+ }
+
+@@ -2689,7 +2712,7 @@ export class AgentSession {
+ throw new Error(formatNoModelSelectedMessage());
+ }
+
+- const settings = this.settingsManager.getCompactionSettings(model);
++ const settings = this.getEffectiveCompactionSettings(model);
+ const pathEntries = this.sessionManager.getBranch();
+
+ const preparation = prepareCompaction(pathEntries, settings);
+@@ -2864,7 +2887,7 @@ export class AgentSession {
+ skipAbortedCheck = true,
+ toolResults: AgentMessage[] = [],
+ ): Promise<boolean> {
+- const settings = this.settingsManager.getCompactionSettings(this.model);
++ const settings = this.getEffectiveCompactionSettings(this.model);
+ if (!settings.enabled) return false;
+
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
+@@ -3011,7 +3034,7 @@ export class AgentSession {
+ */
+ private async _runAutoCompaction(reason: "overflow" | "threshold", willRetry: boolean): Promise<boolean> {
+ const model = this.model;
+- const settings = this.settingsManager.getCompactionSettings(model);
++ const settings = this.getEffectiveCompactionSettings(model);
+ let abortController: AbortController | undefined;
+ let started = false;
+ let fromExtension = false;
+diff --git a/packages/coding-agent/src/modes/rpc/rpc-client.ts b/packages/coding-agent/src/modes/rpc/rpc-client.ts
+index 94ee29f..66e6c29 100644
+--- a/packages/coding-agent/src/modes/rpc/rpc-client.ts
++++ b/packages/coding-agent/src/modes/rpc/rpc-client.ts
+@@ -281,6 +281,12 @@ export class RpcClient {
+ return this.getData<{ models: ModelInfo[] }>(response).models;
+ }
+
++ /** Reload models.json without replacing the current session. Never probes the network. */
++ async refreshModels(): Promise<{ models: ModelInfo[]; aborted: boolean; errors: Record<string, string> }> {
++ const response = await this.send({ type: "refresh_models" });
++ return this.getData(response);
++ }
++
+ /**
+ * Set thinking level.
+ */
+@@ -333,6 +339,12 @@ export class RpcClient {
+ await this.send({ type: "set_auto_compaction", enabled });
+ }
+
++ /** Override the live session's compaction reserve; null restores configured settings. */
++ async setCompactionReserveTokens(reserveTokens: number | null): Promise<number> {
++ const response = await this.send({ type: "set_compaction_reserve_tokens", reserveTokens });
++ return this.getData<{ reserveTokens: number }>(response).reserveTokens;
++ }
++
+ /**
+ * Set auto-retry enabled/disabled.
+ */
+diff --git a/packages/coding-agent/src/modes/rpc/rpc-mode.ts b/packages/coding-agent/src/modes/rpc/rpc-mode.ts
+index 1c0995d..88f52e7 100644
+--- a/packages/coding-agent/src/modes/rpc/rpc-mode.ts
++++ b/packages/coding-agent/src/modes/rpc/rpc-mode.ts
+@@ -490,6 +490,15 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
+ return success(id, "get_available_models", { models });
+ }
+
++ case "refresh_models": {
++ const result = await session.refreshModels();
++ return success(id, "refresh_models", {
++ models: session.modelRuntime.getAvailableSnapshot(),
++ aborted: result.aborted,
++ errors: Object.fromEntries([...result.errors].map(([provider, cause]) => [provider, cause.message])),
++ });
++ }
++
+ // =================================================================
+ // Thinking
+ // =================================================================
+@@ -540,6 +549,11 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
+ return success(id, "set_auto_compaction");
+ }
+
++ case "set_compaction_reserve_tokens": {
++ const reserveTokens = session.setRuntimeCompactionReserveTokens(command.reserveTokens);
++ return success(id, "set_compaction_reserve_tokens", { reserveTokens });
++ }
++
+ // =================================================================
+ // Retry
+ // =================================================================
+diff --git a/packages/coding-agent/src/modes/rpc/rpc-types.ts b/packages/coding-agent/src/modes/rpc/rpc-types.ts
+index 7fc7151..cea41e5 100644
+--- a/packages/coding-agent/src/modes/rpc/rpc-types.ts
++++ b/packages/coding-agent/src/modes/rpc/rpc-types.ts
+@@ -33,6 +33,7 @@ export type RpcCommand =
+ | { id?: string; type: "set_model"; provider: string; modelId: string }
+ | { id?: string; type: "cycle_model" }
+ | { id?: string; type: "get_available_models" }
++ | { id?: string; type: "refresh_models" }
+
+ // Thinking
+ | { id?: string; type: "set_thinking_level"; level: ThinkingLevel }
+@@ -46,6 +47,7 @@ export type RpcCommand =
+ // Compaction
+ | { id?: string; type: "compact"; customInstructions?: string }
+ | { id?: string; type: "set_auto_compaction"; enabled: boolean }
++ | { id?: string; type: "set_compaction_reserve_tokens"; reserveTokens: number | null }
+
+ // Retry
+ | { id?: string; type: "set_auto_retry"; enabled: boolean }
+@@ -159,6 +161,13 @@ export type RpcResponse =
+ success: true;
+ data: { models: Model<any>[] };
+ }
++ | {
++ id?: string;
++ type: "response";
++ command: "refresh_models";
++ success: true;
++ data: { models: Model<any>[]; aborted: boolean; errors: Record<string, string> };
++ }
+
+ // Thinking
+ | { id?: string; type: "response"; command: "set_thinking_level"; success: true }
+@@ -184,6 +193,13 @@ export type RpcResponse =
+ // Compaction
+ | { id?: string; type: "response"; command: "compact"; success: true; data: CompactionResult }
+ | { id?: string; type: "response"; command: "set_auto_compaction"; success: true }
++ | {
++ id?: string;
++ type: "response";
++ command: "set_compaction_reserve_tokens";
++ success: true;
++ data: { reserveTokens: number };
++ }
+
+ // Retry
+ | { id?: string; type: "response"; command: "set_auto_retry"; success: true }
+diff --git a/packages/coding-agent/test/rpc-prompt-response-semantics.test.ts b/packages/coding-agent/test/rpc-prompt-response-semantics.test.ts
+index 98325b1..fa5df38 100644
+--- a/packages/coding-agent/test/rpc-prompt-response-semantics.test.ts
++++ b/packages/coding-agent/test/rpc-prompt-response-semantics.test.ts
+@@ -1,4 +1,4 @@
+-import { existsSync, mkdirSync, rmSync } from "node:fs";
++import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+ import { tmpdir } from "node:os";
+ import { join } from "node:path";
+ import { Agent } from "@earendil-works/pi-agent-core";
+@@ -17,7 +17,7 @@ import type { LoadExtensionsResult } from "../src/core/extensions/index.ts";
+ import { SessionManager } from "../src/core/session-manager.ts";
+ import { SettingsManager } from "../src/core/settings-manager.ts";
+ import { runRpcMode } from "../src/modes/rpc/rpc-mode.ts";
+-import { createInMemoryModelRegistry, getModelRuntime } from "./model-runtime-test-utils.ts";
++import { createModelRegistry, getModelRuntime } from "./model-runtime-test-utils.ts";
+ import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.ts";
+
+ const rpcIo = vi.hoisted(() => ({
+@@ -103,6 +103,7 @@ async function createRuntimeHost(options: {
+ extensionsResult?: LoadExtensionsResult;
+ }): Promise<{
+ runtimeHost: AgentSessionRuntime;
++ modelsPath: string;
+ cleanup: () => Promise<void>;
+ }> {
+ const tempDir = join(tmpdir(), `pi-rpc-prompt-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+@@ -135,7 +136,8 @@ async function createRuntimeHost(options: {
+ const sessionManager = SessionManager.inMemory();
+ const settingsManager = SettingsManager.create(tempDir, tempDir);
+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+- const modelRegistry = await createInMemoryModelRegistry(authStorage);
++ const modelsPath = join(tempDir, "models.json");
++ const modelRegistry = await createModelRegistry(authStorage, modelsPath);
+ if (options.withAuth) {
+ await authStorage.modify("anthropic", async () => ({ type: "api_key", key: "test-key" }));
+ }
+@@ -160,6 +162,7 @@ async function createRuntimeHost(options: {
+
+ return {
+ runtimeHost,
++ modelsPath,
+ cleanup: async () => {
+ try {
+ await session.abort();
+@@ -176,16 +179,18 @@ async function createRuntimeHost(options: {
+
+ async function startRpcMode(options: Parameters<typeof createRuntimeHost>[0]): Promise<{
+ lineHandler: (line: string) => void;
++ session: AgentSession;
++ modelsPath: string;
+ cleanup: () => Promise<void>;
+ }> {
+ rpcIo.outputLines = [];
+ rpcIo.lineHandler = undefined;
+
+- const { runtimeHost, cleanup } = await createRuntimeHost(options);
++ const { runtimeHost, modelsPath, cleanup } = await createRuntimeHost(options);
+ void runRpcMode(runtimeHost);
+ await vi.waitFor(() => expect(rpcIo.lineHandler).toBeDefined());
+
+- return { lineHandler: rpcIo.lineHandler!, cleanup };
++ return { lineHandler: rpcIo.lineHandler!, session: runtimeHost.session, modelsPath, cleanup };
+ }
+
+ describe("RPC prompt response semantics", () => {
+@@ -194,6 +199,76 @@ describe("RPC prompt response semantics", () => {
+ rpcIo.lineHandler = undefined;
+ });
+
++ it("refreshes model metadata and compaction reserve without replacing session state", async () => {
++ const { lineHandler, session, modelsPath, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 0 });
++ try {
++ const current = session.model!;
++ const runner = session.extensionRunner;
++ await session.followUp("keep queued");
++ writeFileSync(
++ modelsPath,
++ JSON.stringify({
++ providers: {
++ [current.provider]: {
++ modelOverrides: { [current.id]: { contextWindow: current.contextWindow + 1000 } },
++ },
++ },
++ }),
++ );
++ lineHandler(JSON.stringify({ id: "refresh", type: "refresh_models" }));
++ await vi.waitFor(() =>
++ expect(parseOutputLines(rpcIo.outputLines)).toContainEqual(
++ expect.objectContaining({
++ id: "refresh",
++ success: true,
++ command: "refresh_models",
++ data: expect.objectContaining({ aborted: false, errors: {} }),
++ }),
++ ),
++ );
++ expect(session.model).toBe(current);
++ lineHandler(
++ JSON.stringify({ id: "same-id", type: "set_model", provider: current.provider, modelId: current.id }),
++ );
++ await vi.waitFor(() =>
++ expect(parseOutputLines(rpcIo.outputLines)).toContainEqual(
++ expect.objectContaining({
++ id: "same-id",
++ success: true,
++ command: "set_model",
++ data: expect.objectContaining({ contextWindow: current.contextWindow + 1000 }),
++ }),
++ ),
++ );
++ lineHandler(JSON.stringify({ id: "reserve", type: "set_compaction_reserve_tokens", reserveTokens: 32000 }));
++ await vi.waitFor(() =>
++ expect(parseOutputLines(rpcIo.outputLines)).toContainEqual(
++ expect.objectContaining({
++ id: "reserve",
++ success: true,
++ command: "set_compaction_reserve_tokens",
++ data: { reserveTokens: 32000 },
++ }),
++ ),
++ );
++ lineHandler(JSON.stringify({ id: "invalid", type: "set_compaction_reserve_tokens", reserveTokens: -1 }));
++ await vi.waitFor(() =>
++ expect(parseOutputLines(rpcIo.outputLines)).toContainEqual(
++ expect.objectContaining({
++ id: "invalid",
++ success: false,
++ command: "set_compaction_reserve_tokens",
++ }),
++ ),
++ );
++ expect(session.extensionRunner).toBe(runner);
++ expect(session.pendingMessageCount).toBe(1);
++ expect(session.model?.contextWindow).toBe(current.contextWindow + 1000);
++ } finally {
++ await cleanup();
++ }
++ });
++
+ it("emits one failure response when prompt preflight rejects", async () => {
+ const { lineHandler, cleanup } = await startRpcMode({
+ withAuth: false,
+diff --git a/packages/coding-agent/test/suite/agent-session-compaction-model-overrides.test.ts b/packages/coding-agent/test/suite/agent-session-compaction-model-overrides.test.ts
+index c606bca..3887337 100644
+--- a/packages/coding-agent/test/suite/agent-session-compaction-model-overrides.test.ts
++++ b/packages/coding-agent/test/suite/agent-session-compaction-model-overrides.test.ts
+@@ -33,6 +33,99 @@ describe("AgentSession compaction model overrides", () => {
+ while (harnesses.length) harnesses.pop()?.cleanup();
+ });
+
++ it("changes the live compaction reserve without replacing extensions or queued input", async () => {
++ const observed: number[] = [];
++ let extensionLoads = 0;
++ const harness = await createHarness({
++ models: [{ id: "faux-1", contextWindow: 4000 }],
++ tools: [],
++ settings: { compaction: { reserveTokens: 10, keepRecentTokens: 150 } },
++ extensionFactories: [
++ (pi) => {
++ extensionLoads++;
++ pi.on("session_before_compact", (event) => {
++ observed.push(event.preparation.settings.reserveTokens);
++ return {
++ compaction: {
++ summary: "runtime reserve summary",
++ firstKeptEntryId: event.preparation.firstKeptEntryId,
++ tokensBefore: event.preparation.tokensBefore,
++ },
++ };
++ });
++ },
++ ],
++ });
++ harnesses.push(harness);
++ seedHistory(harness);
++ await harness.session.followUp("queued follow-up");
++ const sessionFile = harness.session.sessionFile;
++ const extensionRunner = harness.session.extensionRunner;
++ expect(harness.session.setRuntimeCompactionReserveTokens(2000)).toBe(2000);
++ expect(() => harness.session.setRuntimeCompactionReserveTokens(-1)).toThrow();
++ expect(() => harness.session.setRuntimeCompactionReserveTokens(Number.MAX_SAFE_INTEGER + 1)).toThrow();
++ expect(harness.session.pendingMessageCount).toBe(1);
++ await harness.session.compact();
++ expect(observed).toEqual([2000]);
++ expect(harness.session.extensionRunner).toBe(extensionRunner);
++ expect(harness.session.sessionFile).toBe(sessionFile);
++ expect(harness.session.pendingMessageCount).toBe(1);
++ expect(extensionLoads).toBe(1);
++ expect(harness.session.setRuntimeCompactionReserveTokens(null)).toBe(10);
++ expect(harness.settingsManager.getCompactionReserveTokens()).toBe(10);
++ });
++
++ it("reports incomplete model refresh without changing the selected model", async () => {
++ const harness = await createHarness({ models: [{ id: "faux-1" }], tools: [] });
++ harnesses.push(harness);
++ const selected = harness.session.model;
++ const failure = new Error("provider unavailable");
++ const refresh = vi.spyOn(harness.session.modelRuntime, "refresh").mockResolvedValue({
++ aborted: false,
++ errors: new Map([["faux", failure]]),
++ });
++
++ expect(await harness.session.refreshModels()).toEqual({
++ aborted: false,
++ errors: new Map([["faux", failure]]),
++ });
++ expect(refresh).toHaveBeenCalledWith({ allowNetwork: false });
++ expect(harness.session.model).toBe(selected);
++ });
++
++ it("applies the runtime reserve to the next pre-prompt compaction threshold", async () => {
++ const preparations: number[] = [];
++ const harness = await createHarness({
++ models: [{ id: "faux-1", contextWindow: 4000 }],
++ tools: [],
++ settings: { compaction: { enabled: true, reserveTokens: 10, keepRecentTokens: 150 } },
++ extensionFactories: [
++ (pi) => {
++ pi.on("session_before_compact", (event) => {
++ preparations.push(event.preparation.settings.reserveTokens);
++ return {
++ compaction: {
++ summary: "runtime threshold summary",
++ firstKeptEntryId: event.preparation.firstKeptEntryId,
++ tokensBefore: event.preparation.tokensBefore,
++ },
++ };
++ });
++ },
++ ],
++ });
++ harnesses.push(harness);
++ seedHistory(harness, 2500);
++ harness.setResponses([fauxAssistantMessage("first"), fauxAssistantMessage("second")]);
++ await harness.session.prompt("before reserve update");
++ expect(preparations).toEqual([]);
++ seedHistory(harness, 2500);
++ harness.session.setRuntimeCompactionReserveTokens(2000);
++ await harness.session.prompt("after reserve update");
++ expect(preparations).toEqual([2000]);
++ expect(harness.eventsOfType("compaction_end")).toHaveLength(1);
++ });
++
+ it.each(["manual", "pre-prompt", "post-run", "overflow"] as const)(
+ "uses model token settings for %s compaction and extension preparation",
+ async (path) => {
+diff --git a/packages/coding-agent/test/rpc-client-runtime-refresh.test.ts b/packages/coding-agent/test/rpc-client-runtime-refresh.test.ts
+new file mode 100644
+index 0000000..5437df1
+--- /dev/null
++++ b/packages/coding-agent/test/rpc-client-runtime-refresh.test.ts
+@@ -0,0 +1,31 @@
++import { describe, expect, it, vi } from "vitest";
++import { RpcClient } from "../src/modes/rpc/rpc-client.ts";
++
++type ClientTransport = {
++ send: (command: { type: string; reserveTokens?: number | null }) => Promise<unknown>;
++ getData: <T>(response: unknown) => T;
++};
++
++describe("RpcClient runtime refresh", () => {
++ it("uses the public refresh and live compaction commands", async () => {
++ const client = new RpcClient();
++ const transport = client as unknown as ClientTransport;
++ const send = vi.fn(async (command: { type: string; reserveTokens?: number | null }) => ({
++ data:
++ command.type === "refresh_models"
++ ? { models: [], aborted: false, errors: {} }
++ : { reserveTokens: command.reserveTokens === null ? 16384 : command.reserveTokens },
++ }));
++ transport.send = send;
++ transport.getData = <T>(response: unknown): T => (response as { data: T }).data;
++
++ expect(await client.refreshModels()).toEqual({ models: [], aborted: false, errors: {} });
++ expect(await client.setCompactionReserveTokens(32000)).toBe(32000);
++ expect(await client.setCompactionReserveTokens(null)).toBe(16384);
++ expect(send.mock.calls.map(([command]) => command)).toEqual([
++ { type: "refresh_models" },
++ { type: "set_compaction_reserve_tokens", reserveTokens: 32000 },
++ { type: "set_compaction_reserve_tokens", reserveTokens: null },
++ ]);
++ });
++});
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index 5389f2c42d..c6763fda45 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -396,6 +396,8 @@ describe('PUSH_FORWARD_ALLOWLIST', () => {
'maker:interaction-request',
'maker:interaction-dismissed',
'maker:auto-permission:fallback',
+ 'maker:session-credential-switch-applied',
+ 'maker:session-credential-switch-failed',
'maker:provider:changed',
'maker:agents:changed',
'maker:schedule:event',
diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.ts
index 27ac85bcea..b65455db2d 100644
--- a/packages/device-link/src/__tests__/topics.test.ts
+++ b/packages/device-link/src/__tests__/topics.test.ts
@@ -19,6 +19,15 @@ describe('topicForPush', () => {
expect(topicForPush('maker:turn-change-set:updated', { sessionId: 's1' })).toBe('session:s1');
expect(topicForPush('maker:turn-change-set:updated', {})).toBeNull();
});
+ it('routes delayed model-provider outcomes to the owning task', () => {
+ expect(topicForPush('maker:session-credential-switch-applied', {
+ sessionId: 's1', model: 'model', providerId: 'xd',
+ })).toBe('session:s1');
+ expect(topicForPush('maker:session-credential-switch-failed', {
+ sessionId: 's1', reason: 'apply-failed',
+ })).toBe('session:s1');
+ expect(topicForPush('maker:session-credential-switch-failed', { reason: 'apply-failed' })).toBeNull();
+ });
it('delivers companion task state to the parent and private-thread changes to the account topic', () => {
expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: 'parent', childSessionId: 'child' })).toBe('session:parent');
expect(topicForPush('maker:bot-delegation:changed', { parentSessionId: null })).toBeNull();
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index fa9539dbb1..e341ddb6a7 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -644,6 +644,10 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
'maker:interaction-dismissed',
// Claude Auto classifier 故障后降级到 ask;payload 带 sessionId,控制端显示同款提示。
'maker:auto-permission:fallback',
+ // Deferred model-provider outcome. Both payloads contain only task identity
+ // and selected route or a bounded failure code; no native error text.
+ 'maker:session-credential-switch-applied',
+ 'maker:session-credential-switch-failed',
// 被控端 active-catalog revision 变化:控制端按 deviceId 驱逐并重拉 provider 目录。
'maker:provider:changed',
// 注:maker:auth:state-changed 曾在此 —— 但发射点不 tap、控制端也不消费(被控端 agent 鉴权
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 8b8c6c4228..829cb60f84 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -869,6 +869,8 @@ export interface AgentDeps {
model: string;
/** Present only when restoring an existing Pi session; permits private compatibility ids. */
resumeSessionId?: string;
+ /** Preview must not prepare global skills or start a local model service. */
+ purpose?: 'startup' | 'preview' | 'live-refresh';
},
) => Promise<PiNativeProvidersResult | null>;
@@ -881,6 +883,8 @@ export interface AgentDeps {
providerId: string | null | undefined,
modelId: string,
) => ModelDescriptor | null;
+ /** Current Pi-selectable catalog projection for live registry refreshes. */
+ resolvePiRuntimeModels?: () => ModelDescriptor[];
/**
* Pi-only:为 `cindy` gateway 的 models.json 块按会话实际来源解析 provider-aware 描述符。
@@ -2176,6 +2180,17 @@ export interface CodexContextWindowInfo {
* 一个已启动的 agent 会话句柄。
* 上层 Session 类持有此句柄并对外暴露 UI 友好的 API。
*/
+export interface PiModelSwitchPreview {
+ /** Existing Pi model snapshot can serve the target without a catalog mutation. */
+ action: 'hot' | 'refresh' | 'rebuild' | 'unavailable';
+ /** Target configuration's context capacity; null when not established. */
+ targetContextWindow: number | null;
+ /** Only true when the live Pi runtime has confirmed this exact target window. */
+ windowVerified: boolean;
+ /** Non-secret reason suitable for a host error; never include env values. */
+ reason?: string;
+}
+
export interface AgentSessionHandle {
/** Canonical physical Skill identities frozen at native runtime startup. */
readonly disabledSkillPaths?: readonly string[];
@@ -2323,6 +2338,12 @@ export interface AgentSessionHandle {
/** 运行时切换模型 —— 不支持时抛 NotSupportedError */
setModel?(model: string, opts?: { providerId?: string | null; effort?: Effort }): Promise<void>;
+ /** Read-only Pi preflight before the host changes its persisted route or context. */
+ previewModelSwitch?(
+ model: string,
+ opts?: { providerId?: string | null },
+ ): Promise<PiModelSwitchPreview>;
+
/**
* 当前 provider handle 是否必须先关闭、再由同一业务任务 cold resume 才能应用目标模型。
* 缺省 false;用于 Codex 这类把部分模型配置冻结在 app-server spawn / thread resume
diff --git a/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterRefresh.test.ts b/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterRefresh.test.ts
new file mode 100644
index 0000000000..79bb917db2
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/nativeProviderAdapterRefresh.test.ts
@@ -0,0 +1,127 @@
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
+import { PI_NATIVE_PROVIDER_ADAPTER_SOURCE } from '../native-provider-adapter-source.js';
+
+type Alias = { id: string; name: string; provider: string; keyEnv?: string };
+
+function loadAdapter(initialAliases: Alias[] = []) {
+ const env: Record<string, string> = {
+ CINDY_PI_NATIVE_PROVIDER_ADAPTERS: JSON.stringify(initialAliases),
+ CINDY_PI_KEY_OLD: 'old-secret',
+ CINDY_PI_OPENAI_PROXY_KEY: 'old-proxy-secret',
+ };
+ const handlers = new Map<string, (event: unknown, ctx: unknown) => void>();
+ const providers = new Map<string, unknown>();
+ const actions: string[] = [];
+ const pi = {
+ on(name: string, handler: (event: unknown, ctx: unknown) => void) { handlers.set(name, handler); },
+ registerProvider(provider: { id: string }) { actions.push(`register:${provider.id}`); providers.set(provider.id, provider); },
+ unregisterProvider(id: string) { actions.push(`unregister:${id}`); providers.delete(id); },
+ };
+ let models: Array<{ provider: string; id: string }> = initialAliases.map((alias) => ({ provider: alias.id, id: 'old' }));
+ let nextModels = models;
+ const ctx = {
+ modelRegistry: {
+ getAll: () => models,
+ async refresh(options: { allowNetwork?: boolean }) {
+ expect(options).toEqual({ allowNetwork: false });
+ actions.push('refresh');
+ models = nextModels;
+ return { aborted: false, errors: new Map() };
+ },
+ },
+ };
+ const source = PI_NATIVE_PROVIDER_ADAPTER_SOURCE.replaceAll('import(', '__loadPiAi(');
+ const compiled = ts.transpileModule(source + '\n(globalThis as any).adapter = { parseCindyProviderRefreshSnapshot, registerCindyNativeProviderAdapters };', {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
+ }).outputText;
+ const sandbox: Record<string, unknown> = {
+ process: { env },
+ __loadPiAi: async (name: string) => name.endsWith('/compat')
+ ? { getApiProvider: () => undefined }
+ : { lazyStream: () => undefined, envApiKeyAuth: () => undefined },
+ };
+ runInNewContext(compiled, sandbox);
+ const adapter = sandbox.adapter as {
+ parseCindyProviderRefreshSnapshot: (raw: unknown, nonce: string) => {
+ nonce: string; env: Record<string, string>; aliases: Alias[];
+ } | undefined;
+ registerCindyNativeProviderAdapters: (pi: unknown) => Promise<{
+ refresh: (snapshot: { nonce: string; env: Record<string, string>; aliases: Alias[] }, ctx: unknown, secrets: Set<string>) => Promise<void>;
+ }>;
+ };
+ return { adapter, env, pi, ctx, handlers, providers, actions, setModels: (value: typeof models) => { nextModels = value; } };
+}
+
+describe('Cindy native provider refresh bridge', () => {
+ it('validates the entire nonce-bound snapshot before any env or provider mutation', () => {
+ const { adapter } = loadAdapter();
+ const nonce = 'abcdefghijklmnop';
+ const valid = { nonce, env: { CINDY_PI_KEY_NEW: 'secret', CINDY_PI_SESSION_TOKEN: 'token' }, aliases: [
+ { id: 'custom:xai', name: 'xAI', provider: 'xai', keyEnv: 'CINDY_PI_KEY_NEW' },
+ ] };
+ expect(adapter.parseCindyProviderRefreshSnapshot(JSON.stringify(valid), nonce)?.aliases).toEqual(valid.aliases);
+ expect(adapter.parseCindyProviderRefreshSnapshot(JSON.stringify({ ...valid, nonce: 'other' }), nonce)).toBeUndefined();
+ expect(adapter.parseCindyProviderRefreshSnapshot(JSON.stringify({ ...valid, env: { OPENAI_API_KEY: 'secret' } }), nonce)).toBeUndefined();
+ expect(adapter.parseCindyProviderRefreshSnapshot(JSON.stringify({ ...valid, aliases: [
+ { ...valid.aliases[0], keyEnv: 'OPENAI_API_KEY' },
+ ] }), nonce)).toBeUndefined();
+ expect(adapter.parseCindyProviderRefreshSnapshot(JSON.stringify({ ...valid, aliases: [
+ { ...valid.aliases[0], keyEnv: 'CINDY_PI_OPENAI_PROXY_KEY' },
+ ] }), nonce)).toBeUndefined();
+ });
+
+ it('replaces only adapters it registered and refreshes models without clearing extension state', async () => {
+ const old = { id: 'old', name: 'Old', provider: 'anthropic', keyEnv: 'CINDY_PI_KEY_OLD' };
+ const next = { id: 'next', name: 'Next', provider: 'openai', keyEnv: 'CINDY_PI_KEY_NEXT' };
+ const h = loadAdapter([old]);
+ const controller = await h.adapter.registerCindyNativeProviderAdapters(h.pi);
+ h.handlers.get('session_start')?.({}, h.ctx);
+ h.providers.set('package-owned', { id: 'package-owned' });
+ h.setModels([{ provider: 'next', id: 'new-model' }]);
+ const secrets = new Set(['CINDY_PI_KEY_OLD']);
+ await controller.refresh({ nonce: 'abcdefghijklmnop', env: { CINDY_PI_KEY_NEXT: 'next-secret' }, aliases: [next] }, h.ctx, secrets);
+ expect(h.actions).toEqual(['register:old', 'unregister:old', 'refresh', 'register:next', 'refresh']);
+ expect([...h.providers.keys()]).toEqual(['package-owned', 'next']);
+ expect(h.env.CINDY_PI_KEY_OLD).toBeUndefined();
+ expect(h.env.CINDY_PI_KEY_NEXT).toBe('next-secret');
+ expect([...secrets]).toEqual(['CINDY_PI_KEY_NEXT']);
+ expect(h.handlers.size).toBe(1);
+ });
+
+ it('acknowledges success only after applying a valid staged snapshot', async () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const start = source.indexOf("pi.registerCommand('cindy-native-provider-refresh'");
+ const end = source.indexOf('if (!currentPermissionState().reviewOnly)', start);
+ expect(start).toBeGreaterThan(0);
+ expect(end).toBeGreaterThan(start);
+ const code = ts.transpileModule(
+ `async function setup(pi: any, nativeProviderAdapters: any, parseCindyProviderRefreshSnapshot: any) {\nconst SECRET_ENV_NAMES = new Set<string>();\n${source.slice(start, end)}\n}\n(globalThis as any).setup = setup;`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const sandbox: Record<string, unknown> = {};
+ runInNewContext(code, sandbox);
+ const setup = sandbox.setup as (
+ pi: unknown, controller: unknown, parse: (raw: unknown, nonce: string) => unknown,
+ ) => Promise<void>;
+ let handler: ((args: string, ctx: unknown) => Promise<void>) | undefined;
+ const applied: unknown[] = [];
+ await setup({ registerCommand: (_name: string, command: { handler: typeof handler }) => { handler = command.handler; } },
+ { refresh: async (snapshot: unknown) => { applied.push(snapshot); } },
+ (raw, nonce) => raw === 'valid' ? { nonce, env: {}, aliases: [] } : undefined);
+ const calls: Array<{ title: string; payload: unknown }> = [];
+ const ctx = { ui: { input: async (title: string, raw: string) => {
+ const payload = JSON.parse(raw) as unknown;
+ calls.push({ title, payload });
+ return title === 'cindy:provider-refresh' ? 'valid' : undefined;
+ } } };
+ await handler?.('abcdefghijklmnop', ctx);
+ expect(applied).toHaveLength(1);
+ expect(calls).toEqual([
+ { title: 'cindy:provider-refresh', payload: { nonce: 'abcdefghijklmnop' } },
+ { title: 'cindy:provider-refresh-ack', payload: { nonce: 'abcdefghijklmnop', ok: true } },
+ ]);
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index d9c03a30d7..35664507c5 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -289,7 +289,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
function buildDeps(
reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'],
- includeNextModel = false,
+ includeNextModel: boolean | readonly string[] = false,
mcp?: McpSetup,
): AgentDeps {
return {
@@ -345,10 +345,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
maxOutputTokens: 64_000,
},
...(includeNextModel
- ? [
- {
- id: 'm-next',
- displayName: 'M Next',
+ ? (includeNextModel === true ? ['m-next'] : includeNextModel).map((id) => ({
+ id,
+ displayName: id,
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
@@ -359,8 +358,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
cacheWrite: 3.75,
},
maxOutputTokens: 64_000,
- },
- ]
+ }))
: []),
],
},
@@ -424,7 +422,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
async function start(
permissionMode?: string,
reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'],
- includeNextModel = false,
+ includeNextModel: boolean | readonly string[] = false,
mcp?: McpSetup,
directories?: {
extraDirs?: string[];
@@ -3282,7 +3280,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// 撤销是**无效的**:该标志只在构造 spawnEnv 时读一次(spawn 之前),进程起来后改它既收不回
// 已注入的 env、也不能让扩展停止读那个文件。于是"写失败 + 删除也失败"(只读挂载/磁盘满)时,
// 父会话已切到新 provider,子代理仍按上一个有效快照跑 —— 委派发往旧 endpoint(review)。
- const handle = await start();
+ const handle = await start(undefined, undefined, true);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
expect(snapshot).toBeTruthy();
@@ -3294,7 +3292,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
mkdirSync(snapshotPath);
captured.requests = [];
- await expect(handle.setModel('m')).rejects.toThrow(/子代理路由快照/);
+ await expect(handle.setModel('m-next')).rejects.toThrow(/子代理路由快照/);
// 关键:pi 侧的 set_model **根本没发出去** —— 父子路由不会出现"父已切、子没切"的中间态。
expect(captured.requests.map((r) => r.type)).not.toContain('set_model');
@@ -3309,7 +3307,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// 快照指向**被拒绝的** provider/model,而父会话仍在旧路由 —— 下一次委派就打到用户并未启用
// 的端点。此时 subagentRoutingEnabled 是空操作(只在 spawn 前读),删文件也已失败,唯一
// 可证明有效的手段是让这个 pi 进程不再有下一次派发:终止会话(review 连点两轮)。
- const handle = await start();
+ const handle = await start(undefined, undefined, true);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
const snapshotPath = path.join(runtimeDir, snapshot as string);
@@ -3323,7 +3321,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
mkdirSync(snapshotPath);
};
- await expect(handle.setModel('m')).rejects.toThrow(/已终止本会话/);
+ await expect(handle.setModel('m-next')).rejects.toThrow(/已终止本会话/);
// 会话必须真的被关掉,而不是只置一个拦不住任何东西的标志。
expect(captured.closed).toBe(true);
@@ -3334,7 +3332,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// reject / 超时与 `success:false` 有本质区别:后者我们**知道**没生效、可以回滚;前者我们
// **不知道** pi 侧切没切。两条路都不安全 —— 回滚可能与真实状态相反,放行也可能相反,任一
// 方向都是父子路由分叉(下一次委派打到用户并未启用的端点)。所以 fail-closed:终止会话。
- const handle = await start();
+ const handle = await start(undefined, undefined, true);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
const snapshotPath = path.join(runtimeDir, snapshot as string);
@@ -3346,7 +3344,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(before.provider).toBeTruthy();
captured.rejectSetModel = true;
- await expect(handle.setModel('m')).rejects.toThrow(/未收到确认/);
+ await expect(handle.setModel('m-next')).rejects.toThrow(/未收到确认/);
// 会话必须真的被关掉:进程还活着就意味着"下一次委派"仍可能发生。
expect(captured.closed).toBe(true);
// 快照**刻意**停在 pending:它既不是已确认的新路由、也不是旧路由,扩展一律拒绝派发。
@@ -3356,7 +3354,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
model?: string;
};
expect(stuck.pending).toBe(true);
- expect(stuck.model).toBe('m');
+ expect(stuck.model).toBe('m-next');
});
it('isolates the routing snapshot per runtime instance (dev + packaged sharing one userData)', async () => {
@@ -3371,12 +3369,12 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// bypassPermissions,本实例的破坏性工具不再确认(跨实例权限提升)。同一把 nonce 一起收口。
const permsOf = () => readdirSync(runtimeDir).filter((f) => f.startsWith('perm-s1-'));
- const first = await start();
+ const first = await start(undefined, undefined, true);
const firstFiles = snapshotsOf();
expect(firstFiles).toHaveLength(1);
expect(permsOf()).toHaveLength(1);
// 第二个实例:同一个 sessionId、同一个 agentHome —— 就是 dev + 打包版共库双开的形状。
- const second = await start();
+ const second = await start(undefined, undefined, true);
const bothFiles = snapshotsOf();
expect(bothFiles).toHaveLength(2);
// 权限档也必须是两份独立文件,否则一个实例切档会改掉另一个实例 bridge 现读的那份。
@@ -3386,10 +3384,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(firstPath).not.toBe(secondPath);
const secondBefore = readFileSync(secondPath, 'utf8');
- await first.setModel('m-only-in-first');
+ await first.setModel('m-next');
// 切换只落在自己那份快照上;另一个活着的实例一个字节都没被动过。
- expect((JSON.parse(readFileSync(firstPath, 'utf8')) as { model?: string }).model).toBe('m-only-in-first');
+ expect((JSON.parse(readFileSync(firstPath, 'utf8')) as { model?: string }).model).toBe('m-next');
expect(readFileSync(secondPath, 'utf8')).toBe(secondBefore);
// 会话结束要回收:带 nonce 之后文件不再按 sessionId 复用,不回收就随每次 startSession 堆积。
@@ -3405,7 +3403,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// review P1:原来在 RPC 回包**之前**就把新路由写成"已确认"形状,于是等待窗口里模型发起的
// 派发会现读快照、按未确认的 provider 起子进程;RPC 随后失败时回滚文件撤不回已起的子进程。
// 修法:窗口内快照带 `pending: true`,扩展见到就拒绝派发(拒绝的真实性由集成用例验证)。
- const handle = await start();
+ const handle = await start(undefined, undefined, true);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
const snapshotPath = path.join(runtimeDir, snapshot as string);
@@ -3444,7 +3442,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
// 并发/连点切换(本地 + 远程控制端同时切)若交错:A 写 pending、B 写 pending、A 落定 B 的
// 内容 —— 盘上就会出现没人确认过的 model/provider 组合,而 `previousSnapshot` 也不再是真正
// 可回滚的那一份。串行闸保证第二次切换在第一次落定之后才开始。
- const handle = await start();
+ const handle = await start(undefined, undefined, ['m-first', 'm-second']);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
const snapshotPath = path.join(runtimeDir, snapshot as string);
@@ -3471,10 +3469,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
release();
await Promise.all([first, second]);
- // 两次切换按调用序抵达 Pi;每次 settings reload 都重放同一路由后才确认终态。
+ // 两次切换按调用序抵达 Pi;不重载会话,也不重复发送 set_model。
const setModelCalls = captured.requests.filter((r) => r.type === 'set_model');
expect(setModelCalls.map((r) => r.modelId)).toEqual([
- 'm-first', 'm-first', 'm-second', 'm-second',
+ 'm-first', 'm-second',
]);
const after = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;
expect(after.model).toBe('m-second');
@@ -3486,7 +3484,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
it('rolls back to the user-selected provider when set_model cleanly reports failure', async () => {
// 与上一条对照:success:false 是**确定**没生效 → 回滚,快照必须回到用户原本选定的
// provider/model,下一次委派才会继续直连那个 Pi 原生 provider(BYOM 约束)。
- const handle = await start();
+ const handle = await start(undefined, undefined, true);
const runtimeDir = path.join(agentHome, 'runtime');
const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));
const snapshotPath = path.join(runtimeDir, snapshot as string);
@@ -3496,7 +3494,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
};
captured.failSetModel = true;
- await expect(handle.setModel('m')).rejects.toThrow(/set_model failed/);
+ await expect(handle.setModel('m-next')).rejects.toThrow(/set_model failed/);
// 会话不该因为一次干净的失败被终止(那是 reject/超时才有的代价)。
expect(captured.closed).toBe(false);
// 快照已回滚到切换前的值 —— 父进程路由与下一次委派一致。
@@ -3617,7 +3615,11 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
resumeSessionId: resumeFile,
});
- expect(deps.resolvePiGatewayModelDescriptor).toHaveBeenCalledWith('openai', 'chatgpt/gpt-missing');
+ expect(deps.resolvePiRuntimeModelDescriptor).toHaveBeenCalledWith('openai', 'chatgpt/gpt-missing');
+ expect(deps.resolvePiGatewayModelDescriptor).toHaveBeenCalledWith('openai', 'm');
+ const config = JSON.parse(readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'));
+ expect(config.providers.cindy.models.map((model: { id: string }) => model.id))
+ .not.toContain('chatgpt/gpt-missing');
await handle.close();
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
index d180aefec8..7a6214ada9 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
@@ -13,6 +13,8 @@ const knobs = vi.hoisted(() => ({
compactHold: null as null | Promise<void>,
rpcCalls: [] as Array<Record<string, unknown>>,
switchSessionSuccess: true,
+ reserveSuccess: true,
+ reserveUnknown: false,
autoCompactionSuccess: true,
runtimeProvider: "cindy",
runtimeModel: "m",
@@ -87,6 +89,12 @@ vi.mock("../rpc-client.js", () => ({
? { success: true, data: {} }
: { success: false, error: "runtime rejected" };
}
+ if (cmd.type === "set_compaction_reserve_tokens") {
+ if (knobs.reserveUnknown) return { success: false, error: "Unknown command: set_compaction_reserve_tokens" };
+ return knobs.reserveSuccess
+ ? { success: true, data: { reserveTokens: cmd.reserveTokens ?? 16_384 } }
+ : { success: false, error: "reserve rejected" };
+ }
if (cmd.type === "set_model") {
knobs.runtimeProvider = String(cmd.provider);
knobs.runtimeModel = String(cmd.modelId);
@@ -174,6 +182,8 @@ describe("PiAgent native auto-compaction ownership", () => {
knobs.compactHold = null;
knobs.rpcCalls = [];
knobs.switchSessionSuccess = true;
+ knobs.reserveSuccess = true;
+ knobs.reserveUnknown = false;
knobs.autoCompactionSuccess = true;
knobs.runtimeProvider = "cindy";
knobs.runtimeModel = "m";
@@ -215,6 +225,44 @@ describe("PiAgent native auto-compaction ownership", () => {
} finally { await handle.close(); }
});
+ it('clears a startup narrow budget with the effective native default reserve', async () => {
+ let budget: number | null = 1_000;
+ const deps = buildDeps();
+ deps.runtimeConfig = { ...deps.runtimeConfig, piAutoCompactThresholdPct: undefined };
+ deps.resolveModelContextLimit = () => budget;
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'clear-budget', workingDir: cwd, model: 'm', providerId: 'xd',
+ });
+ budget = null;
+ knobs.rpcCalls = [];
+ await handle.setModel!('m', { providerId: 'xd' });
+ expect(knobs.rpcCalls).toContainEqual({
+ type: 'set_compaction_reserve_tokens', reserveTokens: 16_384,
+ });
+ expect(readLatestPiSettings().compaction).toBeUndefined();
+ await handle.close();
+ });
+
+ it('applies a new narrow budget when the previous route had no budget', async () => {
+ let budget: number | null = null;
+ const deps = buildDeps();
+ deps.runtimeConfig = { ...deps.runtimeConfig, piAutoCompactThresholdPct: undefined };
+ deps.resolveModelContextLimit = () => budget;
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'add-budget', workingDir: cwd, model: 'm', providerId: 'xd',
+ });
+ expect(readLatestPiSettings().compaction).toBeUndefined();
+ budget = 1_000;
+ knobs.rpcCalls = [];
+ await handle.setModel!('m', { providerId: 'xd' });
+ expect(knobs.rpcCalls).toContainEqual({
+ type: 'set_compaction_reserve_tokens', reserveTokens: 199_100,
+ });
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(199_100);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(1_000);
+ await handle.close();
+ });
+
it.each([null, 'xd', 'cindy'] as const)('refreshes gateway aliases from a %s source without changing routes', async (providerId) => {
let window = 200_000;
const deps = buildDeps();
@@ -495,10 +543,10 @@ describe("PiAgent native auto-compaction ownership", () => {
.map((call, index) => (call.type === "set_model" ? index : -1))
.filter((index) => index >= 0);
const verifyIndex = knobs.rpcCalls.findLastIndex((call) => call.type === "get_state");
- expect(setModelIndexes).toHaveLength(2);
- expect(setModelIndexes[0]).toBeLessThan(switchIndex);
- expect(setModelIndexes[1]).toBeGreaterThan(switchIndex);
- expect(verifyIndex).toBeGreaterThan(setModelIndexes[1]!);
+ expect(setModelIndexes).toHaveLength(1);
+ expect(switchIndex).toBe(-1);
+ expect(verifyIndex).toBeGreaterThan(setModelIndexes[0]!);
+ expect(knobs.rpcCalls.some((call) => call.type === "set_compaction_reserve_tokens")).toBe(true);
expect(knobs.runtimeProvider).toBe("cindy");
expect(knobs.runtimeModel).toBe("n");
expect(handle.getUsageSnapshot().contextWindow).toBe(100_000);
@@ -525,9 +573,9 @@ describe("PiAgent native auto-compaction ownership", () => {
await handle.setModel!("n");
expect(readLatestPiSettings().compaction?.reserveTokens).toBe(100_000);
- expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(2);
- expect(knobs.rpcCalls.filter((call) => call.type === "set_model")).toHaveLength(3);
- expect(knobs.rpcCalls.filter((call) => call.type === "get_state")).toHaveLength(2);
+ expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(0);
+ expect(knobs.rpcCalls.filter((call) => call.type === "set_model")).toHaveLength(1);
+ expect(knobs.rpcCalls.filter((call) => call.type === "get_state")).toHaveLength(1);
expect(handle.getUsageSnapshot().contextWindow).toBe(1_000_000);
await handle.close();
});
@@ -556,28 +604,29 @@ describe("PiAgent native auto-compaction ownership", () => {
await handle.setModel!("n");
expect(readLatestPiSettings().compaction?.reserveTokens).toBe(10_000);
- expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(2);
- expect(knobs.rpcCalls.filter((call) => call.type === "set_model")).toHaveLength(3);
- expect(knobs.rpcCalls.filter((call) => call.type === "get_state")).toHaveLength(2);
+ expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(0);
+ expect(knobs.rpcCalls.filter((call) => call.type === "set_model")).toHaveLength(1);
+ expect(knobs.rpcCalls.filter((call) => call.type === "get_state")).toHaveLength(1);
expect(handle.getUsageSnapshot().contextWindow).toBe(100_000);
await handle.close();
});
- it("terminates when the runtime window changes again during settings verification", async () => {
+ it("uses the confirmed runtime window for native reserve", async () => {
const handle = await start();
knobs.targetRuntimeContextWindow = 1_000_000;
knobs.setModelReportsContextWindow = false;
- knobs.verifiedContextWindows = [1_000_000, 500_000];
+ knobs.verifiedContextWindows = [1_000_000];
- await expect(handle.setModel!("n")).rejects.toThrow(/未能重载压缩阈值/);
- expect(knobs.closeCalls).toBe(1);
+ await handle.setModel!("n");
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(250_000);
+ expect(knobs.closeCalls).toBe(0);
await handle.close();
});
- it("terminates the session when the reloaded runtime does not confirm the target model", async () => {
+ it("terminates the session when native Pi does not confirm the target model", async () => {
const handle = await start();
knobs.stateModelOverride = "m";
- await expect(handle.setModel!("n")).rejects.toThrow(/未能重载压缩阈值/);
+ await expect(handle.setModel!("n")).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
await handle.close();
});
@@ -672,7 +721,7 @@ describe("PiAgent native auto-compaction ownership", () => {
knobs.rpcCalls = [];
await handle.setModel!("n");
const rewritten = readLatestPiSettings();
- expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(2);
+ expect(knobs.rpcCalls.filter((call) => call.type === "switch_session")).toHaveLength(0);
expect(rewritten.packages?.[0]?.source).toBe(cwd);
expect(rewritten.skills ?? []).not.toContain(`-${b}`);
expect(rewritten.packages?.[0]?.skills ?? []).not.toContain("-b");
@@ -682,10 +731,33 @@ describe("PiAgent native auto-compaction ownership", () => {
} finally { await handle.close(); }
});
- it("terminates the session when compaction settings reload fails after a window change", async () => {
+ it("rejects before switching when the native reserve setter fails", async () => {
const handle = await start();
- knobs.switchSessionSuccess = false;
- await expect(handle.setModel!("n")).rejects.toThrow(/未能重载压缩阈值/);
+ knobs.reserveSuccess = false;
+ await expect(handle.setModel!("n")).rejects.toThrow(/did not confirm the current compaction reserve/);
+ expect(knobs.rpcCalls.filter((call) => call.type === "set_model")).toHaveLength(0);
+ expect(knobs.closeCalls).toBe(0);
+ await handle.close();
+ });
+
+ it("keeps the old Pi route untouched when a catalog refresh also needs an unsupported reserve setter", async () => {
+ let addNative = false;
+ const deps = buildDeps();
+ deps.resolvePiNativeProviders = async () => ({
+ providers: addNative ? [{ id: "native-added", name: "Added", baseUrl: "http://a.test",
+ api: "openai-completions", models: [{ id: "native-model" }] }] : [],
+ env: {},
+ });
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: "old-pi-no-partial-refresh", workingDir: cwd, model: "m", providerId: "xd",
+ });
+ addNative = true;
+ knobs.reserveUnknown = true;
+ knobs.rpcCalls = [];
+ await expect(handle.setModel!("n", { providerId: "xd" })).rejects.toThrow(/does not support live compaction/);
+ expect(knobs.rpcCalls.map((call) => call.type)).toEqual(["set_compaction_reserve_tokens"]);
+ expect(knobs.closeCalls).toBe(0);
+ expect(handle.model).toBe("m");
await handle.close();
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index cb10581b29..1749adbcb3 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -42,6 +42,9 @@ const captured = vi.hoisted(() => ({
initialModel: undefined as string | undefined,
runtimeProvider: undefined as string | undefined,
runtimeModel: undefined as string | undefined,
+ remoteModels: new Map<string, string>(),
+ refreshAckMode: 'ok' as 'ok' | 'invalid',
+ hasRefreshCommand: true,
requestHandler: undefined as
| undefined
| ((command: Record<string, unknown>) => Promise<{
@@ -128,6 +131,37 @@ vi.mock("../rpc-client.js", () => {
},
}
: { success: true, data: {} };
+ if (response.success && command.type === "prompt" &&
+ typeof command.message === "string" && command.message.startsWith("/cindy-native-provider-refresh ")) {
+ const nonce = command.message.split(" ")[1];
+ captured.onEvent?.({ type: "extension_ui_request", method: "input",
+ title: "cindy:provider-refresh", id: "refresh-input", placeholder: JSON.stringify({ nonce }) });
+ captured.onEvent?.({ type: "extension_ui_request", method: "input",
+ title: "cindy:provider-refresh-ack", id: "refresh-ack",
+ placeholder: JSON.stringify(captured.refreshAckMode === 'invalid'
+ ? { nonce, ok: false, code: 'INVALID_PAYLOAD' } : { nonce, ok: true }) });
+ }
+ if (response.success && command.type === "refresh_models" &&
+ !Array.isArray((response.data as { models?: unknown } | undefined)?.models)) {
+ const modelFile = path.join(String(captured.env.PI_CODING_AGENT_DIR), "models.json");
+ const remoteModelContent = captured.remoteModels.get(modelFile)
+ ?? [...captured.remoteModels].find(([file]) => file.endsWith("/models.json"))?.[1];
+ const configured = JSON.parse(remoteModelContent
+ ?? readFileSync(modelFile, "utf8")) as {
+ providers: Record<string, { models?: Array<{ id: string }> }>;
+ };
+ return { success: true, data: { aborted: false, errors: {}, models:
+ Object.entries(configured.providers).flatMap(([provider, spec]) =>
+ (spec.models ?? []).map((model) => ({ provider, id: model.id }))) } };
+ }
+ if (response.success && command.type === "set_compaction_reserve_tokens") {
+ return { success: true, data: { reserveTokens: command.reserveTokens ?? 16_384 } };
+ }
+ if (response.success && command.type === "get_commands" &&
+ !Array.isArray((response.data as { commands?: unknown } | undefined)?.commands)) {
+ return { success: true, data: { commands: captured.hasRefreshCommand
+ ? [{ name: 'cindy-native-provider-refresh', source: 'extension' }] : [] } };
+ }
if (response.success && command.type === "set_model") {
captured.runtimeProvider = String(command.provider);
captured.runtimeModel = String(command.modelId);
@@ -169,6 +203,7 @@ import { PiRpcRequestTimeoutError } from "../rpc-client.js";
import {
PiNativeProviderProxyNotReadyError,
type AgentDeps,
+ type PiNativeProvidersResult,
} from "../../base-agent.js";
import type { ModelDescriptor } from "../../../types/capabilities.js";
import type { Logger } from "../../../interfaces/logger.js";
@@ -231,6 +266,9 @@ describe("Pi provider-aware model routing", () => {
captured.initialModel = undefined;
captured.runtimeProvider = undefined;
captured.runtimeModel = undefined;
+ captured.remoteModels.clear();
+ captured.refreshAckMode = 'ok';
+ captured.hasRefreshCommand = true;
captured.requestHandler = undefined;
agentHome = mkdtempSync(path.join(tmpdir(), "pi-provider-home-"));
cwd = mkdtempSync(path.join(tmpdir(), "pi-provider-cwd-"));
@@ -431,8 +469,8 @@ describe("Pi provider-aware model routing", () => {
await expect(
handle.setModel!("shared-model", { providerId: "xd" }),
- ).rejects.toThrow(/restart the Pi session to change provider API/);
- expect(captured.requests).not.toContainEqual({
+ ).resolves.toBeUndefined();
+ expect(captured.requests).toContainEqual({
type: "set_model",
provider: "cindy",
modelId: "shared-model",
@@ -1558,14 +1596,12 @@ describe("Pi provider-aware model routing", () => {
captured.requests.length = 0;
await expect(
handle.setModel!("shared-model", { providerId: "xd" }),
- ).rejects.toThrow(/restart the Pi session to change provider API/);
- expect(
- captured.requests.filter((request) => request.type === "set_model"),
- ).toEqual([]);
+ ).resolves.toBeUndefined();
+ expect(captured.requests.some((request) => request.type === "refresh_models")).toBe(true);
await handle.close();
});
- it("reloads models.json via switch_session when SuperGrok appears after session start", async () => {
+ it("refreshes models.json natively when SuperGrok appears after session start", async () => {
const xaiProvider = {
id: "xai",
sourceProviderId: "xai" as const,
@@ -1649,10 +1685,8 @@ describe("Pi provider-aware model routing", () => {
});
includeXai = true;
await handle.setModel!("xai/grok-4.6", { providerId: "xai" });
- expect(captured.requests).toContainEqual({
- type: "switch_session",
- sessionPath: "/mock/s.jsonl",
- });
+ expect(captured.requests.some((request) => request.type === "refresh_models")).toBe(true);
+ expect(captured.requests.some((request) => request.type === "switch_session")).toBe(false);
expect(captured.requests).toContainEqual({
type: "set_model",
provider: "xai",
@@ -1795,7 +1829,7 @@ describe("Pi provider-aware model routing", () => {
await handle.close();
});
- it("rolls models.json back when switch_session fails after an xAI catalog refresh", async () => {
+ it("retires Pi when a native catalog refresh fails after publishing models", async () => {
const xaiProvider = {
id: "xai",
sourceProviderId: "xai" as const,
@@ -1813,6 +1847,7 @@ describe("Pi provider-aware model routing", () => {
},
],
};
+ let refreshCalls = 0;
captured.requestHandler = async (command) => {
if (command.type === "get_state") {
return {
@@ -1823,8 +1858,8 @@ describe("Pi provider-aware model routing", () => {
},
};
}
- if (command.type === "switch_session") {
- return { success: false, error: "reload failed" };
+ if (command.type === "refresh_models" && ++refreshCalls === 2) {
+ return { success: false, error: "refresh failed" };
}
return { success: true, data: {} };
};
@@ -1890,20 +1925,22 @@ describe("Pi provider-aware model routing", () => {
includeXai = true;
await expect(
handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
- ).rejects.toThrow(/reload models/);
+ ).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
const models = JSON.parse(
readFileSync(
path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
"utf8",
),
) as { providers: Record<string, unknown> };
- expect(models.providers.xai).toBeUndefined();
+ expect(models.providers.xai).toBeDefined();
+ expect(captured.closes).toBeGreaterThan(0);
await handle.close();
});
- it("terminates the session when catalog rollback cannot be written after switch_session fails", async () => {
+ it("retires Pi when a rejected private bridge command cannot restore models.json", async () => {
const xaiProvider = {
id: "xai",
+ adapterProvider: "openai",
sourceProviderId: "xai" as const,
name: "xAI",
baseUrl: "http://127.0.0.1:9/v1",
@@ -1929,14 +1966,14 @@ describe("Pi provider-aware model routing", () => {
},
};
}
- if (command.type === "switch_session") {
+ if (command.type === "prompt") {
const modelsPath = path.join(
captured.env.PI_CODING_AGENT_DIR as string,
"models.json",
);
unlinkSync(modelsPath);
mkdirSync(modelsPath);
- return { success: false, error: "reload failed" };
+ return { success: false, error: "Unknown command: prompt" };
}
return { success: true, data: {} };
};
@@ -2006,9 +2043,10 @@ describe("Pi provider-aware model routing", () => {
expect(captured.closes).toBeGreaterThan(0);
});
- it("terminates the session when switch_session neither confirms nor rejects after an xAI catalog refresh", async () => {
+ it("terminates the session when the private bridge command neither confirms nor rejects", async () => {
const xaiProvider = {
id: "xai",
+ adapterProvider: "openai",
sourceProviderId: "xai" as const,
name: "xAI",
baseUrl: "http://127.0.0.1:9/v1",
@@ -2034,8 +2072,8 @@ describe("Pi provider-aware model routing", () => {
},
};
}
- if (command.type === "switch_session") {
- throw new Error("pi rpc timeout after 30000ms: switch_session");
+ if (command.type === "prompt") {
+ throw new Error("pi rpc timeout after 30000ms: prompt");
}
return { success: true, data: {} };
};
@@ -2105,7 +2143,7 @@ describe("Pi provider-aware model routing", () => {
expect(captured.closes).toBeGreaterThan(0);
});
- it("refuses a live xAI refresh when the provider endpoint would change", async () => {
+ it("refreshes a live xAI provider when its configured endpoint changes", async () => {
let call = 0;
const agent = new PiAgent({
auth: {
@@ -2190,10 +2228,9 @@ describe("Pi provider-aware model routing", () => {
});
await expect(
handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
- ).rejects.toThrow(/cannot serve model/);
- expect(captured.requests).not.toContainEqual(
- expect.objectContaining({ type: "switch_session" }),
- );
+ ).resolves.toBeUndefined();
+ expect(captured.requests).toContainEqual({ type: "set_model", provider: "xai", modelId: "grok-4.6" });
+ expect(captured.requests.some((request) => request.type === "switch_session")).toBe(false);
await handle.close();
});
@@ -2283,7 +2320,7 @@ describe("Pi provider-aware model routing", () => {
expect(resolves).toBe(1);
captured.requests.length = 0;
await handle.setModel!("xai/grok-4.5", { providerId: "xai" });
- expect(resolves).toBe(1);
+ expect(resolves).toBe(2);
expect(captured.requests).toContainEqual({
type: "set_model",
provider: "xai",
@@ -2291,7 +2328,7 @@ describe("Pi provider-aware model routing", () => {
});
expect(
captured.requests.filter((request) => request.type === "switch_session"),
- ).toHaveLength(1);
+ ).toHaveLength(0);
await handle.close();
});
@@ -2369,7 +2406,7 @@ describe("Pi provider-aware model routing", () => {
expect(resolves).toBe(1);
captured.requests.length = 0;
await handle.setModel!("xai/grok-4.6", { providerId: null });
- expect(resolves).toBe(1);
+ expect(resolves).toBe(2);
expect(captured.requests).toContainEqual({
type: "set_model",
provider: "cindy",
@@ -2377,11 +2414,11 @@ describe("Pi provider-aware model routing", () => {
});
expect(
captured.requests.filter((request) => request.type === "switch_session"),
- ).toHaveLength(1);
+ ).toHaveLength(0);
await handle.close();
});
- it("refuses to add a remote xAI proxy that was not provisioned at startup", async () => {
+ it("adds a remote xAI proxy to a running gateway task without a new Pi process", async () => {
let resolves = 0;
const agent = new PiAgent({
auth: {
@@ -2423,12 +2460,19 @@ describe("Pi provider-aware model routing", () => {
resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiFileOps: () => ({
mkdirp: async () => {},
- writeFile: async () => {},
+ writeFile: async (file: string, content: string) => {
+ captured.remoteModels.set(file, content);
+ },
stat: async () => ({ isFile: true }),
rm: async () => {},
listDir: async () => [],
- readFile: async () => { throw new Error("Unexpected remote file read in empty directory fixture"); },
- sha256File: async () => { throw new Error("Unexpected remote file hash in empty directory fixture"); },
+ readFile: async (file: string) => {
+ const value = captured.remoteModels.get(file);
+ if (value === undefined) throw new Error("Unexpected remote file read in empty directory fixture");
+ return value;
+ },
+ sha256File: async (file: string) => createHash("sha256")
+ .update(captured.remoteModels.get(file) ?? "").digest("hex"),
}),
getRemotePiTransport: async () => ({
writeLine: async () => {},
@@ -2489,7 +2533,8 @@ describe("Pi provider-aware model routing", () => {
});
await expect(
handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
- ).rejects.toThrow(/cannot serve model/);
+ ).resolves.toBeUndefined();
+ expect(captured.requests).toContainEqual({ type: "set_model", provider: "xai", modelId: "grok-4.6" });
expect(captured.requests).not.toContainEqual(
expect.objectContaining({ type: "switch_session" }),
);
@@ -3517,7 +3562,7 @@ describe("Pi provider-aware model routing", () => {
// provider 保存后 renderer 目录可能已出现 xhigh,但这个活动 Pi 进程仍读旧 models.json。
await expect(handle.setEffort!("xhigh")).rejects.toThrow(
- /startup model snapshot.*restart the Pi session/,
+ /applied model catalog/,
);
expect(
captured.requests.filter(
@@ -3596,7 +3641,7 @@ describe("Pi provider-aware model routing", () => {
providerId: "native-a",
effort: "high",
}),
- ).rejects.toThrow(/startup model snapshot/);
+ ).rejects.toThrow(/applied model catalog/);
expect(captured.requests.slice(beforeSwitch)).not.toContainEqual({
type: "set_model",
provider: "native-a",
@@ -3630,7 +3675,7 @@ describe("Pi provider-aware model routing", () => {
});
await expect(handle.setEffort!("xhigh")).rejects.toThrow(
- /startup model snapshot/,
+ /applied model catalog/,
);
expect(
captured.requests.some(
@@ -3742,6 +3787,230 @@ describe("Pi provider-aware model routing", () => {
resolvePiNativeProviders,
});
+ it('refreshes a managed adapter when the same model ID gets a new descriptor', async () => {
+ let window = 100_000;
+ const deps = byomDeps(async () => ({ providers: [{
+ id: 'native-a', name: 'Native A', adapterProvider: 'openai',
+ baseUrl: 'http://a.test', api: 'openai-completions',
+ models: [{ id: 'local-model', contextWindow: window }],
+ }], env: {} }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'adapter-descriptor-refresh', workingDir: cwd,
+ model: 'local-model', providerId: 'native-a',
+ });
+ window = 200_000;
+ captured.requests.length = 0;
+ expect(await handle.previewModelSwitch?.('local-model', { providerId: 'native-a' }))
+ .toMatchObject({ action: 'refresh', targetContextWindow: 200_000 });
+ await handle.setModel!('local-model', { providerId: 'native-a' });
+ expect(captured.requests).toContainEqual(expect.objectContaining({
+ type: 'prompt', message: expect.stringMatching(/^\/cindy-native-provider-refresh /),
+ }));
+ expect(captured.requests.filter((request) => request.type === 'refresh_models')).toHaveLength(2);
+ expect(captured.requests.some((request) => request.type === 'switch_session')).toBe(false);
+ await handle.close();
+ });
+
+ it.each(['provider', 'model'] as const)('retains only the running credential when its %s disappears during catalog refresh', async (removed) => {
+ let updated = false;
+ const running = {
+ id: 'native-a', name: 'Native A', adapterProvider: 'openai',
+ baseUrl: 'http://old.test', api: 'openai-completions' as const,
+ apiKeyEnvVar: 'CINDY_PI_KEY_ACTIVE',
+ models: [{ id: 'local-model', contextWindow: 200_000 }],
+ };
+ const deps = byomDeps(async (): Promise<PiNativeProvidersResult> => ({
+ providers: [
+ ...(!updated ? [running] : removed === 'model' ? [{ ...running,
+ baseUrl: 'http://new.test', models: [{ id: 'replacement', contextWindow: 200_000 }],
+ }] : []),
+ { id: 'native-b', name: updated ? 'Updated B' : 'B', adapterProvider: 'openai',
+ baseUrl: 'http://b.test', api: 'openai-completions' as const,
+ models: [{ id: 'other-model', contextWindow: 200_000 }] },
+ ],
+ env: updated
+ ? (removed === 'model' ? { CINDY_PI_KEY_ACTIVE: 'new-endpoint-key' } : {})
+ : { CINDY_PI_KEY_ACTIVE: 'running-endpoint-key', CINDY_PI_KEY_UNUSED: 'unused-key' },
+ }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'retained-native-credential', workingDir: cwd,
+ model: 'local-model', providerId: 'native-a',
+ });
+ updated = true;
+ expect(await handle.previewModelSwitch?.('local-model', { providerId: 'native-a' }))
+ .toMatchObject({ action: 'refresh' });
+ await handle.setModel!('local-model', { providerId: 'native-a' });
+ const snapshot = JSON.parse(String(captured.responses.find(response => response.id === 'refresh-input')?.value));
+ expect(snapshot.env.CINDY_PI_KEY_ACTIVE).toBe('running-endpoint-key');
+ expect(snapshot.env).not.toHaveProperty('CINDY_PI_KEY_UNUSED');
+ for (const alias of snapshot.aliases) {
+ if (alias.keyEnv) expect(snapshot.env).toHaveProperty(alias.keyEnv);
+ }
+ const config = JSON.parse(readFileSync(path.join(String(captured.env.PI_CODING_AGENT_DIR), 'models.json'), 'utf8'));
+ expect(config.providers['native-a'].baseUrl).toBe('http://old.test');
+ expect(await handle.previewModelSwitch?.('local-model', { providerId: 'native-a' }))
+ .toMatchObject({ action: 'hot' });
+ expect(captured.closes).toBe(0);
+ await handle.close();
+ });
+
+ it('retries the active model after a catalog refresh whose first set_model is rejected', async () => {
+ let name = 'First';
+ let rejectNextModel = false;
+ captured.requestHandler = async (command) => {
+ if (command.type === 'get_state') return { success: true, data: {
+ sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 },
+ } };
+ if (command.type === 'set_model' && rejectNextModel) {
+ rejectNextModel = false;
+ return { success: false, error: 'temporary rejection' };
+ }
+ return { success: true, data: {} };
+ };
+ const deps = byomDeps(async () => ({ providers: [{
+ id: 'native-a', name: 'Native A', baseUrl: 'http://a.test',
+ api: 'openai-completions', models: [{ id: 'local-model', name, contextWindow: 200_000 }],
+ }], env: {} }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'same-id-retry', workingDir: cwd, model: 'local-model', providerId: 'native-a',
+ });
+ name = 'Second';
+ rejectNextModel = true;
+ captured.requests.length = 0;
+ await expect(handle.setModel!('local-model', { providerId: 'native-a' }))
+ .rejects.toThrow(/temporary rejection/);
+ expect(captured.closes).toBe(0);
+ await handle.setModel!('local-model', { providerId: 'native-a' });
+ expect(captured.requests.filter((request) => request.type === 'set_model')).toHaveLength(2);
+ expect(captured.requests.filter((request) => request.type === 'refresh_models')).toHaveLength(2);
+ await handle.close();
+ });
+
+ it('reapplies the current model after another target is rejected following a full catalog refresh', async () => {
+ let updated = false;
+ let rejectB = true;
+ const descriptor = (id: string): ModelDescriptor => ({
+ id, displayName: id === 'model-a' && updated ? 'A updated' : id,
+ contextWindow: 200_000, efforts: [], defaultEffort: null,
+ });
+ captured.requestHandler = async (command) => {
+ if (command.type === 'get_state') return { success: true, data: {
+ sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 },
+ } };
+ if (command.type === 'set_model' && command.modelId === 'model-b' && rejectB) {
+ rejectB = false;
+ return { success: false, error: 'B rejected' };
+ }
+ return { success: true, data: {} };
+ };
+ const deps = byomDeps(async () => ({ providers: [], env: {} }),
+ [descriptor('model-a'), descriptor('model-b')]);
+ deps.resolvePiRuntimeModels = () => [descriptor('model-a'), descriptor('model-b')];
+ deps.resolvePiRuntimeModelDescriptor = (_provider, id) => descriptor(id);
+ deps.resolvePiGatewayModelDescriptor = (_provider, id) => descriptor(id);
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'current-after-other-rejected', workingDir: cwd,
+ model: 'model-a', providerId: 'xd',
+ });
+ updated = true;
+ await expect(handle.setModel!('model-b', { providerId: 'xd' })).rejects.toThrow(/B rejected/);
+ expect(captured.closes).toBe(0);
+ captured.requests.length = 0;
+ await handle.setModel!('model-a', { providerId: 'xd' });
+ expect(captured.requests).toContainEqual({ type: 'set_model', provider: 'cindy', modelId: 'model-a' });
+ expect(captured.requests.some((request) => request.type === 'switch_session')).toBe(false);
+ await handle.close();
+ });
+
+ it('restores exact private catalog bytes when the adapter rejects before mutation', async () => {
+ let name = 'Before';
+ const deps = byomDeps(async () => ({ providers: [{
+ id: 'native-a', name: 'Native A', adapterProvider: 'openai',
+ baseUrl: 'http://a.test', api: 'openai-completions',
+ models: [{ id: 'local-model', name, contextWindow: 200_000 }],
+ }], env: {} }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'invalid-refresh-rollback', workingDir: cwd,
+ model: 'local-model', providerId: 'native-a',
+ });
+ const configHome = captured.env.PI_CODING_AGENT_DIR!;
+ const modelsPath = path.join(configHome, 'models.json');
+ const settingsPath = path.join(configHome, 'settings.json');
+ const beforeModels = readFileSync(modelsPath, 'utf8');
+ const beforeSettings = readFileSync(settingsPath, 'utf8');
+ name = 'After';
+ captured.refreshAckMode = 'invalid';
+ captured.requests.length = 0;
+ await expect(handle.setModel!('local-model', { providerId: 'native-a' }))
+ .rejects.toThrow(/rejected the native provider refresh payload/);
+ expect(readFileSync(modelsPath, 'utf8')).toBe(beforeModels);
+ expect(readFileSync(settingsPath, 'utf8')).toBe(beforeSettings);
+ expect(captured.requests.some((request) => request.type === 'set_model')).toBe(false);
+ expect(captured.closes).toBe(0);
+ await handle.close();
+ });
+
+ it('does not prompt, write, or close when the private refresh command is absent', async () => {
+ let name = 'Before';
+ const deps = byomDeps(async () => ({ providers: [{
+ id: 'native-a', name: 'Native A', adapterProvider: 'openai',
+ baseUrl: 'http://a.test', api: 'openai-completions',
+ models: [{ id: 'local-model', name, contextWindow: 200_000 }],
+ }], env: {} }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'missing-refresh-command', workingDir: cwd,
+ model: 'local-model', providerId: 'native-a',
+ });
+ const configHome = captured.env.PI_CODING_AGENT_DIR!;
+ const modelsPath = path.join(configHome, 'models.json');
+ const settingsPath = path.join(configHome, 'settings.json');
+ const beforeModels = readFileSync(modelsPath, 'utf8');
+ const beforeSettings = readFileSync(settingsPath, 'utf8');
+ name = 'After';
+ captured.hasRefreshCommand = false;
+ captured.requests.length = 0;
+ await expect(handle.setModel!('local-model', { providerId: 'native-a' }))
+ .rejects.toThrow(/refresh extension is unavailable/);
+ expect(captured.requests.map((request) => request.type)).toEqual(['get_commands']);
+ expect(readFileSync(modelsPath, 'utf8')).toBe(beforeModels);
+ expect(readFileSync(settingsPath, 'utf8')).toBe(beforeSettings);
+ expect(captured.closes).toBe(0);
+ await handle.close();
+ });
+
+ it('adds all live Gateway rows to child routes and admits newly applied efforts', async () => {
+ let addModel = false;
+ let expandEffort = false;
+ const descriptor = (id: string): ModelDescriptor => ({
+ id, displayName: id, contextWindow: 200_000,
+ efforts: id === 'gateway-m' && expandEffort ? ['low', 'high'] : ['low'],
+ defaultEffort: 'low',
+ });
+ const deps = byomDeps(async () => ({ providers: [], env: {} }), [descriptor('gateway-m')]);
+ deps.resolvePiRuntimeModels = () => addModel
+ ? [descriptor('gateway-m'), descriptor('gateway-n')] : [descriptor('gateway-m')];
+ deps.resolvePiRuntimeModelDescriptor = (_provider, id) =>
+ id === 'gateway-n' && !addModel ? null : descriptor(id);
+ deps.resolvePiGatewayModelDescriptor = (_provider, id) =>
+ id === 'gateway-n' && !addModel ? null : descriptor(id);
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'gateway-live-child-routes', workingDir: cwd,
+ model: 'gateway-m', providerId: 'xd',
+ });
+ addModel = true;
+ expandEffort = true;
+ await handle.setModel!('gateway-m', { providerId: 'xd', effort: 'high' });
+ const snapshot = JSON.parse(readFileSync(runtimeFileOf('subagent', 'gateway-live-child-routes'), 'utf8')) as {
+ modelRoutes: Record<string, Array<{ provider: string; model: string }>>;
+ };
+ expect(snapshot.modelRoutes['gateway-n']).toContainEqual(expect.objectContaining({
+ provider: 'cindy', model: 'gateway-n',
+ }));
+ await expect(handle.setEffort?.('high')).resolves.toBeUndefined();
+ expect(captured.requests.some((request) => request.type === 'switch_session')).toBe(false);
+ await handle.close();
+ });
+
it("reads back the Pi route even when set_model reports the catalog-sized window", async () => {
captured.requestHandler = async (command) => {
if (command.type === "get_state") {
@@ -3801,8 +4070,6 @@ describe("Pi provider-aware model routing", () => {
captured.requests.length = 0;
await handle.setModel!("model-b", { providerId: "native-a" });
expect(captured.requests.map((request) => request.type)).toEqual([
- "set_model",
- "switch_session",
"set_model",
"get_state",
]);
@@ -3993,7 +4260,7 @@ describe("Pi provider-aware model routing", () => {
});
await expect(
handle.setModel!("local-model", { providerId: "added-later" }),
- ).rejects.toThrow(/cannot serve model 'local-model'|restart the session/);
+ ).rejects.toThrow(/not available in the current catalog/);
// 已在快照里的 provider 仍可正常切换。
await expect(
handle.setModel!("local-model", { providerId: "native-a" }),
@@ -4025,7 +4292,7 @@ describe("Pi provider-aware model routing", () => {
});
await expect(
handle.setModel!("ghost-model", { providerId: "native-a" }),
- ).rejects.toThrow(/cannot serve model 'ghost-model'/);
+ ).rejects.toThrow(/does not offer model 'ghost-model'/);
await handle.close();
});
@@ -4298,9 +4565,7 @@ describe("Pi provider-aware model routing", () => {
}
gatewayModels[0]!.supportsImageInput = true;
await handle.setModel!("gateway-text", { providerId: null });
- await expect(handle.send(imageMessage)).rejects.toMatchObject({
- code: "PI_IMAGE_INPUT_UNSUPPORTED",
- });
+ await expect(handle.send(imageMessage)).resolves.toBeUndefined();
// 明确支持图片的网关模型保留全部图片块,多图不被剥离或改写。
await handle.setModel!("gateway-vision", { providerId: null });
@@ -4327,7 +4592,7 @@ describe("Pi provider-aware model routing", () => {
}),
).rejects.toThrow(/failed to read image attachment/);
// 未发送任何 prompt(失败在 dispatch 前)
- expect(captured.requests).toHaveLength(0);
+ expect(captured.requests.some((request) => request.type === "prompt")).toBe(false);
await handle.close();
});
@@ -4728,11 +4993,7 @@ describe("Pi provider-aware model routing", () => {
// setModel 传 null 同样固定走网关(不落到 native-a)。
captured.requests.length = 0;
await handle.setModel!("local-model", { providerId: null });
- expect(captured.requests).toContainEqual({
- type: "set_model",
- provider: "cindy",
- modelId: "local-model",
- });
+ expect(captured.runtimeProvider).toBe("cindy");
await handle.close();
});
@@ -5661,8 +5922,6 @@ describe("Pi provider-aware model routing", () => {
expect(forwardEvents).toEqual([
"forward:http://127.0.0.1:18765:47989",
"set_model",
- // switch_session rebuilds from the original CLI route; target is re-applied.
- "set_model",
]);
await handle.close();
});
@@ -6113,7 +6372,7 @@ describe("Pi provider-aware model routing", () => {
expect(snapshot.pending).not.toBe(true);
}
const requestsBefore = captured.requests.length;
- await expect(handle.setModel!(model, { providerId: "not-in-startup" })).rejects.toThrow(/cannot serve/);
+ await expect(handle.setModel!(model, { providerId: "not-in-startup" })).rejects.toThrow(/not available in the current catalog/);
expect(captured.requests.length).toBe(requestsBefore);
expect(resolveParent?.()).toBe("openai");
await handle.close();
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 9c42b1d486..92fd0ba60d 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -135,6 +135,12 @@ try {
function withoutPiSecrets(env: Record<string, string | undefined>): Record<string, string | undefined> {
const clean = { ...env };
for (const name of SECRET_ENV_NAMES) delete clean[name];
+ // A provider added after session start was absent from the original host-generated list.
+ for (const name of Object.keys(clean)) {
+ if (/^CINDY_PI_KEY_[A-Z0-9_]+$/.test(name)
+ || name === 'CINDY_PI_SESSION_TOKEN' || name === 'CINDY_PI_API_KEY'
+ || name === 'CINDY_PI_OPENAI_PROXY_KEY' || name === 'CINDY_PI_XAI_PROXY_API_KEY') delete clean[name];
+ }
return clean;
}
@@ -3670,7 +3676,35 @@ ${PI_NATIVE_PROVIDER_ADAPTER_SOURCE}
export default async function cindyBridge(pi: any) {
installTextOnlyTurnPolicy(pi);
- await registerCindyNativeProviderAdapters(pi);
+ const nativeProviderAdapters = await registerCindyNativeProviderAdapters(pi);
+ pi.registerCommand('cindy-native-provider-refresh', {
+ description: 'Cindy internal native provider refresh',
+ handler: async (args: string, ctx: any) => {
+ const nonce = args.trim();
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(nonce)) return;
+ let code: 'INVALID_PAYLOAD' | 'APPLY_FAILED' | undefined;
+ let mutationStarted = false;
+ try {
+ const raw = await ctx.ui.input('cindy:provider-refresh', JSON.stringify({ nonce }));
+ const snapshot = parseCindyProviderRefreshSnapshot(raw, nonce);
+ if (!snapshot) {
+ code = 'INVALID_PAYLOAD';
+ } else {
+ mutationStarted = true;
+ await nativeProviderAdapters.refresh(snapshot, ctx, SECRET_ENV_NAMES);
+ }
+ } catch {
+ code = mutationStarted ? 'APPLY_FAILED' : 'INVALID_PAYLOAD';
+ }
+ // RPC prompt swallows extension command exceptions. The host must see an
+ // explicit, nonce-bound receipt before accepting a refreshed catalog.
+ try {
+ await ctx.ui.input('cindy:provider-refresh-ack', JSON.stringify(
+ code ? { nonce, ok: false, code } : { nonce, ok: true },
+ ));
+ } catch { /* A missing receipt forces the host to retire this process. */ }
+ },
+ });
if (!currentPermissionState().reviewOnly) registerCindyQuestionTool(pi);
pi.on('before_provider_request', async (event, ctx) => {
const payload = astraResponsesPayload(event.payload, ctx.model) ?? event.payload;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index de95231659..1fe7d0094f 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -86,6 +86,7 @@ import {
type PiNativeModelSpec,
type PiNativePackageEntry,
type PiNativeProviderSpec,
+ type PiModelSwitchPreview,
type PiSubagentRunnerLaunchRequest,
type PiSubagentRunnerProcess,
type SendOptions,
@@ -2195,6 +2196,8 @@ export class PiAgent extends BaseAgent {
gatewayApiByModel: Map<string, PiGatewayApi>;
/** models.json + settings.json 内容 sha256 —— 远端 daemon 启动身份的一部分。 */
modelsJsonHash: string;
+ /** Models alone, excluding the independently mutable compaction settings. */
+ modelConfigHash: string;
}> {
// 远端:baseUrl 用 host 注入的 upstream endpoint(remoteEndpoint,gateway key 同源),
// 不用本地 loopback compat proxy(远端够不到)。订阅 OAuth 的 loopback 分流远端不可达,
@@ -2214,7 +2217,7 @@ export class PiAgent extends BaseAgent {
}
this.deps.logger.warn('pi: runtimeConfig.endpoint missing — models.json will have no usable provider');
}
- const publicModels = this.capabilities.availableModels;
+ const publicModels = this.deps.resolvePiRuntimeModels?.() ?? this.capabilities.availableModels;
const runtimeModels =
retainedRuntimeModel && !publicModels.some((m) => m.id === retainedRuntimeModel.id)
? [...publicModels, retainedRuntimeModel]
@@ -2392,6 +2395,7 @@ export class PiAgent extends BaseAgent {
.update('\n')
.update(settingsJsonContent)
.digest('hex');
+ const modelConfigHash = createHash('sha256').update(modelsJsonContent).digest('hex');
if (!opts.preview) {
// 诊断(排查 LAZY_CREATE_FAILED):远端写前留痕 —— 确认 writeModelsJson 是否
// 执行、endpoint 是否有值、路径形态。
@@ -2424,6 +2428,7 @@ export class PiAgent extends BaseAgent {
// 远端 daemon 启动身份:models.json + settings.json。BYOM/gateway 或 retry
// 策略变更都必须杀旧进程,不能纯 attach 沿用内存里的旧快照。
modelsJsonHash,
+ modelConfigHash,
};
}
@@ -2667,12 +2672,9 @@ export class PiAgent extends BaseAgent {
// hostProxyForward 的 provider(当前为 xAI)仍通过 Desktop compat proxy:
// SSH 只解决可达性,session token 继续提供逐会话鉴权,不能把 loopback 端口
// 当作信任边界。
- const remoteUsesHostProxy = remote && nativeProviders.some((provider) => provider.hostProxyForward);
- const proxySessionToken = remoteUsesHostProxy
+ const proxySessionToken = remote
? stableRemoteProxySessionToken(opts.sessionId, this.deps.derivePiProxySessionToken)
- : !remote
- ? randomBytes(32).toString('base64url')
- : undefined;
+ : randomBytes(32).toString('base64url');
// A child may deliberately use a different provider from its parent (for
// example a ChatGPT parent delegating to Grok). Freeze every model route
@@ -2816,7 +2818,7 @@ export class PiAgent extends BaseAgent {
Boolean(gatewaySubagentProxyToken),
);
}
- const subagentModelRoutes = Object.fromEntries(
+ let subagentModelRoutes = Object.fromEntries(
[...subagentModelRouteCandidates].map(([id, candidates]) => [id, [...candidates.values()]]),
);
const startupEffort = reconcilePiStartupEffort(opts.effort, selectedRuntimeModel);
@@ -2829,32 +2831,34 @@ export class PiAgent extends BaseAgent {
});
}
- // Pi 子进程只读取本次启动生成的 models.json。renderer 目录热更新后,不能把新出现的
- // effort 直接发送给仍在运行的旧进程;否则 Pi 会把 thinkingLevelMap 中的 null 当作
- // 关闭 reasoning。这里冻结每个可路由模型在该启动快照中的能力,setModel 成功后只
- // 切换到同一快照里已有的目标模型能力。
- const resolveStartupEffortSnapshot = (providerId: string, modelId: string): readonly Effort[] | undefined => {
+ // Gateway effort admission follows only descriptors actually applied to
+ // Pi's registry, never the renderer's newer catalog ahead of refresh ACK.
+ const appliedGatewayEfforts = new Map<string, readonly Effort[]>();
+ for (const model of this.deps.resolvePiRuntimeModels?.() ?? this.capabilities.availableModels) {
+ const gateway = this.deps.resolvePiGatewayModelDescriptor
+ ? this.deps.resolvePiGatewayModelDescriptor(authProviderId, model.id)
+ : model;
+ if (gateway) appliedGatewayEfforts.set(model.id, gateway.efforts);
+ }
+ if (initialProvider === PI_PROVIDER_ID && selectedRuntimeModel) {
+ appliedGatewayEfforts.set(selectedRuntimeModel.id, selectedRuntimeModel.efforts);
+ }
+ const resolveAppliedEffortSnapshot = (providerId: string, modelId: string): readonly Effort[] | undefined => {
if (providerId !== PI_PROVIDER_ID) {
return startupEffortsOfNativeModel(
nativeProviderById.get(providerId)?.models.find((model) => model.id === resolveNativeModelId(providerId, modelId)),
);
}
- const gatewayModel =
- modelId === opts.model && selectedRuntimeModel
- ? selectedRuntimeModel
- : (this.deps.resolvePiGatewayModelDescriptor?.(authProviderId, modelId) ??
- this.capabilities.availableModels.find((model) => model.id === modelId));
- return gatewayModel?.efforts;
+ return appliedGatewayEfforts.get(modelId);
};
- const initialEffortSnapshot = resolveStartupEffortSnapshot(initialProvider, opts.model);
+ const initialEffortSnapshot = resolveAppliedEffortSnapshot(initialProvider, opts.model);
const assertStartupEffortAllowed = (snapshot: readonly Effort[] | undefined, effort: Effort): void => {
// efforts:[] 仍可能收到 resolveEffort 的 UI 占位值 low;它代表“不支持切换”,
// 只需跳过 RPC。其它档位必须拒绝,避免热刷目录后的新 effort 绕过启动快照。
if (!snapshot || (snapshot.length === 0 && effort === 'low')) return;
if (snapshot.includes(effort)) return;
throw new Error(
- `pi set_thinking_level refused: effort '${effort}' is not available in this session's ` +
- 'startup model snapshot; restart the Pi session after changing provider capabilities.',
+ `pi set_thinking_level refused: effort '${effort}' is not in Pi's applied model catalog.`,
);
};
@@ -2872,7 +2876,7 @@ export class PiAgent extends BaseAgent {
'pi',
`pi not authenticated: ${authState.errorReason ?? 'no_key'}`);
}
- const authEnv = await this.deps.auth.getAuthEnv({
+ let authEnv = await this.deps.auth.getAuthEnv({
credentialMode,
providerId: authProviderId,
});
@@ -3061,7 +3065,7 @@ export class PiAgent extends BaseAgent {
`${stableSessionPathSegment(opts.sessionId)}-${preview.modelsJsonHash.slice(0, 16)}${globalContextHash ? `-${globalContextHash}` : ''}`,
);
}
- const { gatewayImageInputByModel, gatewayApiByModel, modelsJsonHash } = await this.writeModelsJson(
+ const { gatewayImageInputByModel, gatewayApiByModel, modelsJsonHash, modelConfigHash } = await this.writeModelsJson(
configHome,
nativeProviders,
retainedRuntimeModel,
@@ -3812,6 +3816,15 @@ export class PiAgent extends BaseAgent {
// follow-up send)同口径。清空只认 turn 终态,由 send 预检覆盖为最新值。
let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;
let mutableModel = opts.model;
+ let appliedModelConfigHash = modelConfigHash;
+ let pendingCurrentDescriptorRefresh = false;
+ let retainedLiveGatewayModel = initialProvider === PI_PROVIDER_ID ? selectedRuntimeModel : undefined;
+ let providerRefreshStage: {
+ nonce: string;
+ env: Record<string, string>;
+ aliases: ReturnType<typeof nativeProviderAdapterAliases>;
+ acknowledge: (ok: boolean, code?: string) => void;
+ } | null = null;
let mutableWireModel = initialWireModel;
// Pi RPC 实际选中的 provider。与用于宿主鉴权/审阅元数据的 mutableProviderId 分开:
// null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。
@@ -5266,6 +5279,26 @@ export class PiAgent extends BaseAgent {
}
}
if (event.type === 'extension_ui_request') {
+ if (event.method === 'input' &&
+ (event.title === 'cindy:provider-refresh' || event.title === 'cindy:provider-refresh-ack')) {
+ const requestId = typeof event.id === 'string' ? event.id : '';
+ let payload: { nonce?: unknown; ok?: unknown; code?: unknown } = {};
+ try { payload = JSON.parse(typeof event.placeholder === 'string' ? event.placeholder : '{}'); }
+ catch { /* Invalid private command payload is rejected below. */ }
+ const stage = providerRefreshStage;
+ const valid = Boolean(requestId && stage && payload.nonce === stage.nonce &&
+ !closed && !piProcessExited && !proc.isClosed && !accountBoundaryTeardown);
+ if (event.title === 'cindy:provider-refresh') {
+ proc.send(valid
+ ? { type: 'extension_ui_response', id: requestId,
+ value: JSON.stringify({ nonce: stage!.nonce, env: stage!.env, aliases: stage!.aliases }) }
+ : { type: 'extension_ui_response', id: requestId, cancelled: true });
+ } else {
+ if (valid) stage!.acknowledge(payload.ok === true, typeof payload.code === 'string' ? payload.code : undefined);
+ proc.send({ type: 'extension_ui_response', id: requestId, cancelled: true });
+ }
+ return;
+ }
this.handleExtensionUiRequest(event, proc, () => ({
resolver: interactionResolver,
permissionMode,
@@ -6027,25 +6060,6 @@ export class PiAgent extends BaseAgent {
* setModel 的临界区正文。经 `setModelChain` 串行化后调用 —— 不要直接调它,
* 并发进入会让 pending / 落定两次写交错。
*/
- const nativeOffersModel = (providerId: string, modelId: string): boolean => {
- const native = nativeProviderById.get(providerId);
- if (!native) return false;
- const nativeModel = resolveNativeModelId(providerId, modelId);
- // inheritModels 里没有 api/catalogAddition 的行是 Pi 自带目录,不是缺失模型。
- return native.models.some((candidate) => candidate.id === nativeModel);
- };
- const sameRecord = (
- left?: Record<string, string>,
- right?: Record<string, string>,
- ): boolean => {
- const a = left ?? {};
- const b = right ?? {};
- const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
- for (const key of keys) {
- if (a[key] !== b[key]) return false;
- }
- return true;
- };
const terminateUnconfirmedCatalogReload = async (cause?: unknown): Promise<never> => {
this.deps.logger.error(
'pi: catalog state unconfirmed; terminating session',
@@ -6063,119 +6077,401 @@ export class PiAgent extends BaseAgent {
'[PI_CATALOG_RELOAD_UNCONFIRMED] 模型目录重载未确认,已终止本任务。请重新打开任务后再切换模型。',
);
};
- const restoreNativeCatalog = async (
- previousProviders: PiNativeProviderSpec[],
- ): Promise<void> => {
- // 先写盘再改内存:写失败时磁盘仍是新目录,内存也保持新目录,避免分叉后再抛。
- const written = await this.writeModelsJson(
- configHome,
- previousProviders,
- retainedRuntimeModel,
- authProviderId,
- {
- remote,
- fileOps,
- contextWindow: ctx.contextWindow || startupContextWindow,
- workingContextWindow: ctx.workingContextWindow,
+ const previewPiModelSwitch = async (
+ model: string,
+ target?: { providerId?: string | null },
+ ): Promise<PiModelSwitchPreview> => {
+ const requestedProviderId = target && Object.hasOwn(target, 'providerId')
+ ? target.providerId
+ : mutableProviderId;
+ const sameRoute = model === mutableModel && requestedProviderId === mutableProviderId;
+ let latestProviders = nativeProviders;
+ let latestEnv = nativeEnv;
+ if (this.deps.resolvePiNativeProviders) {
+ try {
+ const resolved = await this.deps.resolvePiNativeProviders({
+ workingDir: opts.workingDir,
+ remoteHostId: opts.remoteHostId,
+ providerId: requestedProviderId,
+ model,
+ resumeSessionId: sdkSessionId || opts.resumeSessionId,
+ purpose: 'preview',
+ });
+ if (resolved) {
+ latestProviders = resolved.providers;
+ latestEnv = resolved.env;
+ }
+ } catch (error) {
+ return {
+ action: 'unavailable', targetContextWindow: null, windowVerified: false,
+ reason: 'Pi provider catalog could not be read',
+ };
+ }
+ }
+ const sourceId = requestedProviderId === undefined
+ ? (model.startsWith('xai/') ? 'xai' : model.startsWith('chatgpt/') ? 'openai' : null)
+ : requestedProviderId;
+ const gateway = !sourceId || sourceId === 'xd' || sourceId === PI_PROVIDER_ID;
+ let nativeModel: PiNativeModelSpec | undefined;
+ if (!gateway) {
+ let native = latestProviders.find((entry) => (entry.sourceProviderId ?? entry.id) === sourceId);
+ if (sameRoute) {
+ const running = nativeProviderForSource(sourceId);
+ const nextNativeId = native?.modelIdAliases?.[model] ?? model;
+ // A removed/retired model stays available to its current task. Never
+ // rewrite that task's active provider to a different endpoint merely
+ // because a new public catalog no longer advertises it.
+ if (running && (!native || !native.models.some((candidate) => candidate.id === nextNativeId))) {
+ latestProviders = [...latestProviders.filter((entry) =>
+ (entry.sourceProviderId ?? entry.id) !== sourceId), running];
+ // Keep the credential paired with the retained endpoint, without
+ // retaining credentials for other providers removed from the catalog.
+ if (running.apiKeyEnvVar && nativeEnv[running.apiKeyEnvVar] !== undefined) {
+ latestEnv = { ...latestEnv, [running.apiKeyEnvVar]: nativeEnv[running.apiKeyEnvVar] };
+ }
+ native = running;
+ }
+ }
+ if (!native) {
+ return { action: 'unavailable', targetContextWindow: null, windowVerified: false,
+ reason: `Pi provider '${sourceId}' is not available in the current catalog` };
+ }
+ const nativeId = native.modelIdAliases?.[model] ?? model;
+ nativeModel = native.models.find((candidate) => candidate.id === nativeId);
+ if (!nativeModel && sameRoute) {
+ const retained = nativeProviderForSource(sourceId);
+ nativeModel = retained?.models.find((candidate) =>
+ candidate.id === (retained.modelIdAliases?.[model] ?? model));
+ }
+ if (!nativeModel) {
+ return { action: 'unavailable', targetContextWindow: null, windowVerified: false,
+ reason: `Pi provider '${sourceId}' does not offer model '${model}'` };
+ }
+ }
+ const gatewaySpec = gateway
+ ? this.deps.resolvePiGatewayModelSpec?.(sourceId, model, { remote })
+ : undefined;
+ if (gateway && gatewaySpec === null) {
+ return { action: 'unavailable', targetContextWindow: null, windowVerified: false,
+ reason: `No supported Gateway Pi API is available for model '${model}'` };
+ }
+ const knownDescriptor = this.deps.resolvePiRuntimeModelDescriptor
+ ? this.deps.resolvePiRuntimeModelDescriptor(sourceId, model)
+ : this.capabilities.availableModels.find((candidate) => candidate.id === model);
+ const targetContextWindow = nativeModel?.contextWindow
+ ?? knownDescriptor?.contextWindow
+ ?? (sameRoute && gateway ? retainedLiveGatewayModel?.contextWindow : undefined) ?? null;
+ // A refresh may change any provider block, so all credentials it references
+ // must be synchronised with the running Pi process before it is published.
+ // The private refresh bridge owns this update; this preview never handles a key.
+ const projected = await this.writeModelsJson(
+ configHome, latestProviders,
+ gateway ? (knownDescriptor ?? (sameRoute ? retainedLiveGatewayModel : undefined)
+ ?? retainedRuntimeModel) : retainedLiveGatewayModel,
+ gateway ? requestedProviderId : authProviderId,
+ { remote, fileOps, preview: true,
+ contextWindow: targetContextWindow ?? ctx.contextWindow ?? startupContextWindow,
+ workingContextWindow: this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
piCompactionPct: sessionPiAutoCompactPct,
- packages: nativePackagePaths,
- disabledSkills: disabledSkillLaunch,
- },
+ packages: nativePackagePaths, disabledSkills: disabledSkillLaunch },
);
- nativeProviders = previousProviders;
- nativeProviderById.clear();
- nativeProviderBySourceId.clear();
- for (const spec of previousProviders) {
- if (spec.id === PI_PROVIDER_ID) continue;
- nativeProviderById.set(spec.id, spec);
- nativeProviderBySourceId.set(spec.sourceProviderId ?? spec.id, spec);
+ if (gateway && !projected.gatewayApiByModel.has(model)) {
+ return { action: 'unavailable', targetContextWindow, windowVerified: false,
+ reason: `Gateway Pi model '${model}' has no runnable protocol` };
}
- gatewayApiByModel.clear();
- for (const [key, value] of written.gatewayApiByModel) gatewayApiByModel.set(key, value);
- gatewayImageInputByModel.clear();
- for (const [key, value] of written.gatewayImageInputByModel) {
- gatewayImageInputByModel.set(key, value);
+ const configChanged = projected.modelConfigHash !== appliedModelConfigHash;
+ const envChanged = Object.keys({ ...nativeEnv, ...latestEnv }).some(
+ (key) => nativeEnv[key] !== latestEnv[key],
+ );
+ const adaptersChanged = JSON.stringify(nativeProviderAdapterAliases(nativeProviders))
+ !== JSON.stringify(nativeProviderAdapterAliases(latestProviders));
+ let gatewayCredentialChanged = false;
+ if (remote && gateway) {
+ try {
+ const latestAuth = await this.deps.auth.getAuthEnv({
+ credentialMode: 'gateway-key', providerId: requestedProviderId,
+ });
+ gatewayCredentialChanged = latestAuth[PI_API_KEY_ENV] !== authEnv[PI_API_KEY_ENV];
+ } catch {
+ return { action: 'unavailable', targetContextWindow, windowVerified: false,
+ reason: 'The current Gateway credential could not be read' };
+ }
}
+ const needsRefresh = configChanged || envChanged || adaptersChanged || gatewayCredentialChanged;
+ return {
+ action: needsRefresh ? 'refresh' : 'hot',
+ targetContextWindow,
+ windowVerified: sameRoute && !needsRefresh && targetContextWindow === ctx.contextWindow,
+ };
};
- const restoreNativeCatalogOrTerminate = async (
- previousProviders: PiNativeProviderSpec[],
+ const refreshLiveCatalog = async (
+ model: string,
+ requestedProviderId: string | null | undefined,
): Promise<void> => {
- try {
- await restoreNativeCatalog(previousProviders);
- } catch (err) {
- await terminateUnconfirmedCatalogReload(err);
+ const live = await this.deps.resolvePiNativeProviders?.({
+ workingDir: opts.workingDir,
+ remoteHostId: opts.remoteHostId,
+ providerId: requestedProviderId,
+ model,
+ resumeSessionId: sdkSessionId || opts.resumeSessionId,
+ purpose: 'live-refresh',
+ });
+ let nextProviders = live?.providers ?? nativeProviders;
+ let nextEnv = live?.env ?? nativeEnv;
+ const sameRoute = model === mutableModel && requestedProviderId === mutableProviderId;
+ const sourceId = requestedProviderId === undefined
+ ? (model.startsWith('xai/') ? 'xai' : model.startsWith('chatgpt/') ? 'openai' : null)
+ : requestedProviderId;
+ if (sameRoute && sourceId && sourceId !== 'xd' && sourceId !== PI_PROVIDER_ID) {
+ const next = nextProviders.find((entry) => (entry.sourceProviderId ?? entry.id) === sourceId);
+ const running = nativeProviderForSource(sourceId);
+ if (running && (!next || !next.models.some((candidate) =>
+ candidate.id === (next.modelIdAliases?.[model] ?? model)))) {
+ nextProviders = [...nextProviders.filter((entry) =>
+ (entry.sourceProviderId ?? entry.id) !== sourceId), running];
+ if (running.apiKeyEnvVar && nativeEnv[running.apiKeyEnvVar] !== undefined) {
+ nextEnv = { ...nextEnv, [running.apiKeyEnvVar]: nativeEnv[running.apiKeyEnvVar] };
+ }
+ }
}
- };
- const refreshLiveXaiCatalog = async (
- modelId: string,
- providerId?: string | null,
- ): Promise<boolean> => {
- if (!this.deps.resolvePiNativeProviders) return false;
+ const nextDescriptor = this.deps.resolvePiRuntimeModelDescriptor
+ ? this.deps.resolvePiRuntimeModelDescriptor(sourceId, model)
+ : this.capabilities.availableModels.find((candidate) => candidate.id === model);
+ const nextGateway = !sourceId || sourceId === 'xd' || sourceId === PI_PROVIDER_ID;
+ const gatewayAuthEnv = remote && nextGateway
+ ? await this.deps.auth.getAuthEnv({ credentialMode: 'gateway-key', providerId: requestedProviderId })
+ : authEnv;
+ const nextAliases = nativeProviderAdapterAliases(nextProviders);
+ const currentAliases = nativeProviderAdapterAliases(nativeProviders);
+ const mutableEnv = (value: Record<string, string>) => Object.fromEntries(
+ Object.entries(value).filter(([key]) => /^CINDY_PI_KEY_[A-Z0-9_]+$/.test(key)
+ || key === PI_API_KEY_ENV || key === PI_SESSION_TOKEN_ENV
+ || key === 'CINDY_PI_OPENAI_PROXY_KEY' || key === 'CINDY_PI_XAI_PROXY_API_KEY'));
+ const desiredEnv = mutableEnv({ ...nextEnv,
+ ...(gatewayAuthEnv[PI_API_KEY_ENV] ? { [PI_API_KEY_ENV]: gatewayAuthEnv[PI_API_KEY_ENV] } : {}),
+ ...(proxySessionToken ? { [PI_SESSION_TOKEN_ENV]: proxySessionToken } : {}),
+ });
+ const oldEnv = mutableEnv({ ...nativeEnv, ...authEnv,
+ ...(proxySessionToken ? { [PI_SESSION_TOKEN_ENV]: proxySessionToken } : {}),
+ });
+ let bridgeChanged = JSON.stringify(desiredEnv) !== JSON.stringify(oldEnv)
+ || JSON.stringify(nextAliases) !== JSON.stringify(currentAliases);
+ const projected = await this.writeModelsJson(
+ configHome, nextProviders,
+ nextGateway ? (nextDescriptor ?? retainedLiveGatewayModel ?? retainedRuntimeModel) : retainedLiveGatewayModel,
+ nextGateway ? requestedProviderId : authProviderId,
+ { remote, fileOps, preview: true, contextWindow: nextDescriptor?.contextWindow ?? ctx.contextWindow,
+ workingContextWindow: this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
+ piCompactionPct: sessionPiAutoCompactPct, packages: nativePackagePaths,
+ disabledSkills: disabledSkillLaunch },
+ );
+ bridgeChanged ||= projected.modelConfigHash !== appliedModelConfigHash && nextAliases.length > 0;
+ if (bridgeChanged) {
+ // Unknown slash commands are ordinary prompts in Pi. Confirm that our
+ // private extension owns this name before ever sending a nonce/secret
+ // refresh command or touching the on-disk catalog.
+ const commands = await proc.request({ type: 'get_commands' });
+ const loaded = (commands.data as { commands?: Array<{ name?: unknown; source?: unknown }> }
+ | undefined)?.commands;
+ if (!commands.success || !loaded?.some((entry) =>
+ entry.name === 'cindy-native-provider-refresh' && entry.source === 'extension')) {
+ throw new Error('Pi native provider refresh extension is unavailable; update the bundled Pi runtime and retry.');
+ }
+ }
+ // First probe the installed Pi's native RPC against the still-current private
+ // catalog. Unknown-command here leaves the active route untouched.
+ const probe = await proc.request({ type: 'refresh_models' });
+ if (!probe.success && /^Unknown command:/.test(probe.error ?? '')) {
+ throw new Error('Pi runtime does not support live model refresh; update the bundled Pi runtime and retry.');
+ }
+ const probeData = probe.data as { aborted?: boolean; errors?: Record<string, string> } | undefined;
+ if (!probe.success || probeData?.aborted || Object.keys(probeData?.errors ?? {}).length > 0) {
+ throw new Error(`pi: current catalog refresh failed: ${probe.error ?? 'aborted'}`);
+ }
+ const previousGatewayModel = retainedLiveGatewayModel;
+ const modelsPath = joinRemotePosixPath(configHome, 'models.json');
+ const settingsPath = joinRemotePosixPath(configHome, 'settings.json');
+ // Capture exact private bytes. Rebuilding from a live catalog would not be
+ // a rollback if the catalog changed after the session started.
+ const [oldModelsContent, oldSettingsContent] = await Promise.all([
+ fileOps ? fileOps.readFile(modelsPath, 8_000_000) : fs.readFile(modelsPath, 'utf8'),
+ fileOps ? fileOps.readFile(settingsPath, 1_000_000) : fs.readFile(settingsPath, 'utf8'),
+ ]);
+ if (fileOps) {
+ const [modelsHash, settingsHash] = await Promise.all([
+ fileOps.sha256File(modelsPath), fileOps.sha256File(settingsPath),
+ ]);
+ if (modelsHash !== createHash('sha256').update(oldModelsContent).digest('hex') ||
+ settingsHash !== createHash('sha256').update(oldSettingsContent).digest('hex')) {
+ throw new Error('Pi remote catalog backup was incomplete; live refresh was not started');
+ }
+ }
+ const restoreFilesOrTerminate = async (): Promise<void> => {
+ try {
+ if (fileOps) {
+ await fileOps.writeFile(modelsPath, oldModelsContent);
+ await fileOps.writeFile(settingsPath, oldSettingsContent);
+ } else {
+ await fs.writeFile(modelsPath, oldModelsContent, { mode: 0o600 });
+ await fs.writeFile(settingsPath, oldSettingsContent, { mode: 0o600 });
+ }
+ } catch (error) {
+ await terminateUnconfirmedCatalogReload(error);
+ }
+ };
+ let written: Awaited<ReturnType<PiAgent['writeModelsJson']>>;
try {
- const live = await this.deps.resolvePiNativeProviders({
- workingDir: opts.workingDir,
- remoteHostId: opts.remoteHostId,
- providerId,
- model: modelId,
- resumeSessionId: sdkSessionId || opts.resumeSessionId,
- });
- const sourceProviderId = providerId ?? 'xai';
- const liveXai = live?.providers.find(
- (provider) => (provider.sourceProviderId ?? provider.id) === sourceProviderId,
+ written = await this.writeModelsJson(
+ configHome, nextProviders,
+ nextGateway ? (nextDescriptor ?? retainedLiveGatewayModel ?? retainedRuntimeModel) : retainedLiveGatewayModel,
+ nextGateway ? requestedProviderId : authProviderId,
+ { remote, fileOps, contextWindow: nextDescriptor?.contextWindow ?? ctx.contextWindow,
+ workingContextWindow: this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
+ piCompactionPct: sessionPiAutoCompactPct, packages: nativePackagePaths,
+ disabledSkills: disabledSkillLaunch },
);
- if (!live || !liveXai) return false;
- // 远端 hostProxyForward 依赖启动时注入的 session token / 代理登记。
- // 登录后才出现的 xAI 块带上隧道,请求会因没有 CINDY_PI_SESSION_TOKEN 失败。
- if (liveXai.hostProxyForward && !proxySessionToken) return false;
- const currentXai = nativeProviderForSource(sourceProviderId);
- if (currentXai) {
- if (currentXai.baseUrl !== liveXai.baseUrl) return false;
- if (!sameRecord(currentXai.headers, liveXai.headers)) return false;
- if (liveXai.hostProxyForward && !currentXai.hostProxyForward) return false;
+ } catch (error) {
+ await restoreFilesOrTerminate();
+ throw error;
+ }
+ if (bridgeChanged) {
+ const nonce = randomBytes(24).toString('base64url');
+ let acknowledge!: (ok: boolean, code?: string) => void;
+ const ack = new Promise<{ ok: boolean; code?: string }>((resolve) => {
+ acknowledge = (ok, code) => resolve({ ok, code });
+ });
+ providerRefreshStage = { nonce, env: desiredEnv, aliases: nextAliases, acknowledge };
+ try {
+ const command = await proc.request({ type: 'prompt', message: `/cindy-native-provider-refresh ${nonce}` });
+ const receipt = await Promise.race([
+ ack,
+ new Promise<{ ok: boolean; code: string }>((resolve) =>
+ setTimeout(() => resolve({ ok: false, code: 'ACK_TIMEOUT' }), 10_000)),
+ ]);
+ if (!command.success || !receipt.ok) {
+ if (receipt.code === 'INVALID_PAYLOAD') {
+ await restoreFilesOrTerminate();
+ throw new Error('Pi rejected the native provider refresh payload; the original route is unchanged.');
+ }
+ return await terminateUnconfirmedCatalogReload(receipt.code ?? command.error);
+ }
+ } catch (error) {
+ if (providerRefreshStage && !proc.isClosed) {
+ // A rejected or timed-out prompt could have changed the extension's
+ // registry before the RPC transport failed. Never guess its state.
+ if (!(error instanceof Error && /extension is unavailable|rejected the native provider/.test(error.message))) {
+ return await terminateUnconfirmedCatalogReload(error);
+ }
+ }
+ throw error;
+ } finally {
+ providerRefreshStage = null;
}
- const envKey = liveXai.apiKeyEnvVar;
- if (envKey) {
- if (!(envKey in nativeEnv)) return false;
- if (live.env[envKey] !== undefined && live.env[envKey] !== nativeEnv[envKey]) {
- return false;
+ }
+ try {
+ const refreshed = await proc.request({ type: 'refresh_models' });
+ const result = refreshed.data as { models?: Array<{ provider?: string; id?: string }>;
+ aborted?: boolean; errors?: Record<string, string> } | undefined;
+ if (!refreshed.success || result?.aborted || Object.keys(result?.errors ?? {}).length > 0) {
+ throw new Error('Pi did not complete the model catalog refresh');
+ }
+ const desiredProvider = nextGateway ? PI_PROVIDER_ID : nextProviders.find(
+ (entry) => (entry.sourceProviderId ?? entry.id) === sourceId)?.id;
+ const desiredNative = nextProviders.find((entry) => entry.id === desiredProvider);
+ const desiredId = desiredNative?.models.find((candidate) =>
+ candidate.id === (desiredNative.modelIdAliases?.[model] ?? model))?.wireId
+ ?? desiredNative?.modelIdAliases?.[model] ?? model;
+ if (!desiredProvider || !result?.models?.some((candidate) =>
+ candidate.provider === desiredProvider && candidate.id === desiredId)) {
+ throw new Error('Pi refreshed the catalog but did not expose the selected provider/model');
+ }
+ } catch (error) {
+ // Pi may have partially replaced registry entries even on a negative
+ // response. A confirmed rollback would require another refresh+ACK;
+ // retiring is the only safe outcome for the live process.
+ await terminateUnconfirmedCatalogReload(error);
+ }
+ nativeProviders = nextProviders;
+ nativeEnv = nextEnv;
+ if (remote && nextGateway) authEnv = gatewayAuthEnv;
+ // Child processes are spawned by the Desktop host after this point. Their
+ // immutable startup env must match the parent Pi registry we just verified.
+ for (const key of Object.keys(durableSpawnEnv)) {
+ if (/^CINDY_PI_KEY_[A-Z0-9_]+$/.test(key)
+ || key === 'CINDY_PI_OPENAI_PROXY_KEY'
+ || key === 'CINDY_PI_XAI_PROXY_API_KEY'
+ || key === PI_API_KEY_ENV || key === PI_SESSION_TOKEN_ENV) {
+ delete durableSpawnEnv[key];
+ }
+ }
+ Object.assign(durableSpawnEnv, desiredEnv);
+ durableSpawnEnv.CINDY_PI_NATIVE_PROVIDER_ADAPTERS = JSON.stringify(nextAliases);
+ const currentSecretNames = JSON.parse(
+ durableSpawnEnv[PI_SECRET_ENV_NAMES_ENV] ?? '[]') as string[];
+ durableSpawnEnv[PI_SECRET_ENV_NAMES_ENV] = JSON.stringify(
+ [...new Set([...currentSecretNames, ...Object.keys(desiredEnv)])]);
+ if (subagentRoutingEnabled) {
+ for (const [id, candidates] of subagentModelRouteCandidates) {
+ for (const [routeKey, route] of candidates) {
+ if (route.provider !== PI_PROVIDER_ID || !written.gatewayApiByModel.has(id)) {
+ candidates.delete(routeKey);
+ }
}
+ if (candidates.size === 0) subagentModelRouteCandidates.delete(id);
}
- nativeProviderById.set(liveXai.id, liveXai);
- nativeProviderBySourceId.set(liveXai.sourceProviderId ?? liveXai.id, liveXai);
- nativeProviders = [
- ...nativeProviders.filter(
- (provider) => (provider.sourceProviderId ?? provider.id) !== sourceProviderId,
- ),
- liveXai,
- ];
- const written = await this.writeModelsJson(
- configHome,
- nativeProviders,
- retainedRuntimeModel,
- authProviderId,
- {
- remote,
- fileOps,
- contextWindow: ctx.contextWindow || startupContextWindow,
- workingContextWindow: ctx.workingContextWindow,
- piCompactionPct: sessionPiAutoCompactPct,
- packages: nativePackagePaths,
- disabledSkills: disabledSkillLaunch,
- },
- );
- gatewayApiByModel.clear();
- for (const [key, value] of written.gatewayApiByModel) gatewayApiByModel.set(key, value);
- gatewayImageInputByModel.clear();
- for (const [key, value] of written.gatewayImageInputByModel) {
- gatewayImageInputByModel.set(key, value);
+ for (const gatewayModelId of written.gatewayApiByModel.keys()) {
+ addSubagentModelRoute(gatewayModelId, PI_PROVIDER_ID, gatewayModelId,
+ gatewaySubagentProxyToken ? gatewaySubagentRouteKey : undefined,
+ Boolean(gatewaySubagentProxyToken));
}
- return nativeOffersModel(liveXai.id, modelId);
- } catch (err) {
- this.deps.logger.warn('pi live xAI catalog refresh failed', {
- message: err instanceof Error ? err.message : String(err),
- });
- return false;
+ for (const spec of nextProviders) {
+ if (spec.id === PI_PROVIDER_ID) continue;
+ const source = spec.sourceProviderId ?? spec.id;
+ const wasRegistered = subagentProxyTokens.has(source);
+ const token = proxyTokenForSubagentProvider(spec, source);
+ if (token && !wasRegistered && opts.sessionId && this.deps.registerPiProxySession) {
+ appendProxyDisposer(this.deps.registerPiProxySession(
+ opts.sessionId, token, () => source, { scope: 'subagent-route' }));
+ }
+ for (const candidate of spec.models) {
+ const wire = candidate.wireId ?? candidate.id;
+ addSubagentModelRoute(candidate.id, spec.id, wire, source, Boolean(token));
+ for (const [alias, mapped] of Object.entries(spec.modelIdAliases ?? {})) {
+ if (mapped === candidate.id) addSubagentModelRoute(alias, spec.id, wire, source, Boolean(token));
+ }
+ if (!candidate.id.includes('/')) {
+ const canonical = source === 'xai' ? `xai/${candidate.id}`
+ : source === 'openai' || candidate.api === 'openai-codex-responses'
+ ? `chatgpt/${candidate.id}` : undefined;
+ addSubagentModelRoute(canonical, spec.id, wire, source, Boolean(token));
+ }
+ }
+ }
+ subagentModelRoutes = Object.fromEntries([...subagentModelRouteCandidates]
+ .map(([id, candidates]) => [id, [...candidates.values()]]));
}
+ nativeProviderById.clear();
+ nativeProviderBySourceId.clear();
+ for (const spec of nextProviders) {
+ if (spec.id === PI_PROVIDER_ID) continue;
+ nativeProviderById.set(spec.id, spec);
+ nativeProviderBySourceId.set(spec.sourceProviderId ?? spec.id, spec);
+ }
+ gatewayApiByModel.clear();
+ for (const [key, value] of written.gatewayApiByModel) gatewayApiByModel.set(key, value);
+ for (const gatewayModelId of written.gatewayApiByModel.keys()) {
+ const descriptor = this.deps.resolvePiGatewayModelDescriptor?.(requestedProviderId, gatewayModelId)
+ ?? this.deps.resolvePiRuntimeModels?.().find((candidate) => candidate.id === gatewayModelId)
+ ?? this.capabilities.availableModels.find((candidate) => candidate.id === gatewayModelId);
+ if (descriptor) appliedGatewayEfforts.set(gatewayModelId, descriptor.efforts);
+ }
+ gatewayImageInputByModel.clear();
+ for (const [key, value] of written.gatewayImageInputByModel) gatewayImageInputByModel.set(key, value);
+ appliedModelConfigHash = written.modelConfigHash;
+ // A full registry refresh can update the still-active A while a proposed
+ // switch to B later fails. Keep A pending until a confirmed set_model.
+ pendingCurrentDescriptorRefresh = true;
+ if (nextGateway) retainedLiveGatewayModel = nextDescriptor ?? previousGatewayModel;
};
const switchModel = async (
model: string,
@@ -6185,143 +6481,55 @@ export class PiAgent extends BaseAgent {
? setOpts.providerId
: undefined;
assertRemotePiContextProfileAvailable(opts.remoteHostId, model, requestedProviderId);
- // 心跳复用活进程会把当前 (provider, model) 再下发一次。
- // spawn 能靠 custom model id 跑在 Pi 自带目录没有的 SuperGrok
- // 路由上(grok-4.6);重复 set_model 反而 fail-closed。
- // 只对显式非 null 来源做 no-op:model-only 与 providerId=null
- // (钉回网关)仍走 RPC。
- const assertGatewayProtocolForModel = (
- nextModel: string,
- nextRequestedProviderId: string | null | undefined,
- ): void => {
- const nextProvider = resolveProviderForModel(nextModel, nextRequestedProviderId);
- if (nextProvider !== PI_PROVIDER_ID) return;
- const routeProviderId = nextRequestedProviderId !== undefined
- ? nextRequestedProviderId
- : mutableProviderId;
- const resolverContext = { remote };
- const resolvedSpec = this.deps.resolvePiGatewayModelSpec?.(
- routeProviderId,
- nextModel,
- resolverContext,
- );
- const resolvedApi = resolvedSpec?.api ?? this.deps.resolvePiGatewayModelApi?.(
- routeProviderId,
- nextModel,
- resolverContext,
- );
- if (
- resolvedSpec === null ||
- resolvedApi === null ||
- (resolvedApi !== undefined && !isPiGatewayApi(resolvedApi))
- ) {
- throw new Error(
- `No supported Gateway Pi API is available for model: ${nextModel}`,
- );
- }
- if (resolvedApi === undefined) {
- throw new Error(`Pi API is not configured for model: ${nextModel}`);
- }
- const desiredApi = resolvedApi;
- const configuredApi = gatewayApiByModel.get(nextModel);
- if (configuredApi && configuredApi !== desiredApi) {
- throw new Error(
- `pi: provider switch for model '${nextModel}' requires API '${desiredApi}', but this session ` +
- `started with '${configuredApi}'; restart the Pi session to change provider API.`,
- );
- }
+ const effectiveProviderId = requestedProviderId === undefined ? mutableProviderId : requestedProviderId;
+ const preview = await previewPiModelSwitch(model, { providerId: effectiveProviderId });
+ if (preview.action === 'unavailable') throw new Error(preview.reason ?? 'Pi model route is unavailable');
+ if (preview.action === 'rebuild') {
+ throw new Error(preview.reason ?? 'Pi model route needs a new process startup input');
+ }
+ // If the target window changes the reserve, check the optional Pi RPC
+ // while the old catalog and route are still intact. An older runtime must
+ // not receive a bridge/catalog mutation before we learn it cannot finish.
+ const projectedReserve = (window: number, workingWindow?: number): number => {
+ const settings = JSON.parse(buildPiSettingsJsonContent(
+ window, sessionPiAutoCompactPct, [], workingWindow,
+ )) as { compaction?: { reserveTokens?: number } };
+ // Pi's null setter clears the runtime override back to its in-memory
+ // SettingsManager value, which may still be the old per-task reserve.
+ return settings.compaction?.reserveTokens ?? 16_384;
};
- if (
- model === mutableModel &&
- requestedProviderId !== undefined &&
- requestedProviderId !== null &&
- Object.is(requestedProviderId, mutableProviderId)
- ) {
- if (setOpts?.effort) {
- assertStartupEffortAllowed(activeEffortSnapshot, setOpts.effort);
- }
- assertGatewayProtocolForModel(model, requestedProviderId);
- // 同路由不打 set_model,但仍要重试子代理快照:初始写失败或确认写失败
- // 留下 pending 时,心跳复用活进程必须能把文件重建/清 pending,
- // 否则扩展会一直 fail-closed。不带 pending,路由已确认。
- const sameRouteProvider = resolveProviderForModel(model, requestedProviderId);
- const sameRouteWire = resolveWireModel(sameRouteProvider, model);
- if (!(await writeSubagentRuntimeFile({ model: sameRouteWire, provider: sameRouteProvider }))) {
- deps.logger.warn('pi: same-route setModel could not refresh subagent snapshot', {
- model,
- provider: sameRouteProvider,
- });
- }
- deps.logger.debug('pi: setModel no-op; already on requested route', {
- model,
- providerId: requestedProviderId,
+ const currentReserve = projectedReserve(ctx.contextWindow, ctx.workingContextWindow);
+ const nextProjectedReserve = projectedReserve(
+ preview.targetContextWindow ?? ctx.contextWindow,
+ this.deps.resolveModelContextLimit?.(effectiveProviderId, model) ?? undefined);
+ if (currentReserve !== nextProjectedReserve) {
+ const reserveProbe = await proc.request({
+ type: 'set_compaction_reserve_tokens', reserveTokens: currentReserve,
});
- return;
- }
- // null = 钉回网关,绝不按模型名推断 xAI。只有 undefined(旧会话未持久化来源)
- // 才允许 xai/ 前缀回退。`??` 会把 null 也吃掉,误进 live catalog 刷新。
- const sourceHint = requestedProviderId === undefined
- ? (model.startsWith('xai/') ? 'xai' : undefined)
- : (requestedProviderId ?? undefined);
- const liveProviderHint = sourceHint ? nativeProviderForSource(sourceHint) : undefined;
- const needsXaiCatalogReload = (sourceHint === 'xai' || Boolean(liveProviderHint?.hostProxyForward))
- && (!liveProviderHint || !nativeOffersModel(liveProviderHint.id, model));
- if (needsXaiCatalogReload) {
- const previousProviders = nativeProviders.slice();
- const refreshed = await refreshLiveXaiCatalog(model, requestedProviderId);
- if (refreshed && sdkSessionId) {
- // Claude 热切先 applyFlagSettings 扩白名单;Pi 的 set_model 不重读 models.json,
- // 但 switch_session 会 createRuntime → ModelConfig.load,等于无重启扩名单。
- // success:false = 确定没重载,回滚安全。reject/超时 = 不知道 Pi 侧有没有吃到新
- // models.json,回滚和放行都可能分叉,按未确认 set_model 一样终止会话。
- let reloaded;
- try {
- reloaded = await proc.request({
- type: 'switch_session',
- sessionPath: sdkSessionId,
- });
- } catch (err) {
- return await terminateUnconfirmedCatalogReload(err);
- }
- if (!reloaded.success) {
- await restoreNativeCatalogOrTerminate(previousProviders);
- throw new Error(
- `pi: failed to reload models after catalog update: ${reloaded.error ?? 'unknown'}`,
- );
- }
- } else if (!refreshed) {
- await restoreNativeCatalogOrTerminate(previousProviders);
+ if (!reserveProbe.success ||
+ (reserveProbe.data as { reserveTokens?: unknown } | undefined)?.reserveTokens !== currentReserve) {
+ throw new Error(/^Unknown command:/.test(reserveProbe.error ?? '')
+ ? 'Pi runtime does not support live compaction reserve updates; update the bundled Pi runtime and retry.'
+ : 'Pi did not confirm the current compaction reserve; model switch was not started.');
}
}
- // 显式选一个启动快照 nativeProviderById 里“无法服务该 model”的 BYOM provider 时 fail
- // closed:要么该 provider 是会话启动后才新增的(不在快照),要么它虽在、但用户编辑
- // 配置后从中删/改了这个 model。两种都会让 resolveProviderForModel 静默回落 cindy 网关;
- // 若该 model id 也在网关目录里则 set_model “成功”、后续 prompt 发往网关而非用户选的
- // 本地/自定义端点(codex review P1)。提示重启会话以刷新启动快照,而不是静默换目的地。
- if (explicitByomUnresolvable(requestedProviderId, model)) {
- throw new Error(
- `pi: BYOM provider '${requestedProviderId}' cannot serve model '${model}' in this session's ` +
- 'startup provider set (provider not present, or it no longer offers this model); restart the ' +
- 'session to use it (refusing to fall back to the Cindy gateway).',
- );
+ if (preview.action === 'refresh') await refreshLiveCatalog(model, effectiveProviderId);
+ // Never let a requested native source silently fall through to Cindy's
+ // gateway when a provider disappeared or a model was removed.
+ if (explicitByomUnresolvable(effectiveProviderId, model)) {
+ throw new Error(`pi: provider '${effectiveProviderId}' cannot serve model '${model}'`);
}
- const provider = resolveProviderForModel(model, requestedProviderId);
+ const provider = resolveProviderForModel(model, effectiveProviderId);
const wireModel = resolveWireModel(provider, model);
- if (
- requestedProviderId
- && requestedProviderId !== PI_PROVIDER_ID
- && requestedProviderId !== 'xd'
- && provider === PI_PROVIDER_ID
- ) {
- throw new Error(
- `pi: provider '${requestedProviderId}' cannot serve model '${model}' even after reloading the live catalog; ` +
- 'restart the Pi session if the provider was added after this task started.',
- );
+ if (effectiveProviderId && effectiveProviderId !== PI_PROVIDER_ID &&
+ effectiveProviderId !== 'xd' && provider === PI_PROVIDER_ID) {
+ throw new Error(`pi: provider '${effectiveProviderId}' cannot serve model '${model}'`);
}
- assertGatewayProtocolForModel(model, requestedProviderId);
+ const routeUnchanged = model === mutableModel && provider === mutablePiProviderId &&
+ wireModel === mutableWireModel;
// effort 能力校验必须排在写路由快照**之前**:它会抛错中止本次切换,而快照一旦落盘就
// 指向了新 provider —— 那正是父子路由分叉的形状(upstream #1451 与本 PR 的合并点)。
- const nextEffortSnapshot = resolveStartupEffortSnapshot(provider, model);
+ const nextEffortSnapshot = resolveAppliedEffortSnapshot(provider, model);
if (setOpts?.effort) {
assertStartupEffortAllowed(nextEffortSnapshot, setOpts.effort);
}
@@ -6360,6 +6568,49 @@ export class PiAgent extends BaseAgent {
// 所以这一步落的是**带 pending 标记的**新路由:内容已经就位(证明可写、内容可回滚),但
// 扩展见到 `pending: true` 就拒绝派发。等待窗口里一个子进程都起不来,既不会用未确认的新
// 路由、也不会用与父不一致的旧路由;确认后再清掉标记放行。
+ const reserveForWindow = (window: number, source: string | null | undefined,
+ modelId: string, workingWindow?: number): number => {
+ const settings = JSON.parse(buildPiSettingsJsonContent(
+ window, sessionPiAutoCompactPct, [],
+ workingWindow ?? this.deps.resolveModelContextLimit?.(source, modelId) ?? undefined,
+ )) as { compaction?: { reserveTokens?: number } };
+ return settings.compaction?.reserveTokens ?? 16_384;
+ };
+ const oldReserve = currentReserve;
+ const targetReserve = nextProjectedReserve;
+ if (routeUnchanged && preview.action === 'hot' && oldReserve === targetReserve
+ && !pendingCurrentDescriptorRefresh) {
+ if (!(await writeSubagentRuntimeFile({ model: wireModel, provider }))) {
+ deps.logger.warn('pi: same-route setModel could not refresh subagent snapshot', { model, provider });
+ }
+ return;
+ }
+ let reserveApplied = false;
+ if (targetReserve !== oldReserve) {
+ const setReserve = await proc.request({
+ type: 'set_compaction_reserve_tokens', reserveTokens: targetReserve,
+ });
+ if (!setReserve.success) {
+ throw new Error(/^Unknown command:/.test(setReserve.error ?? '')
+ ? 'Pi runtime does not support live compaction reserve updates; update the bundled Pi runtime and retry.'
+ : `pi: compaction reserve update failed: ${setReserve.error ?? 'unknown'}`);
+ }
+ if ((setReserve.data as { reserveTokens?: unknown } | undefined)?.reserveTokens !== targetReserve) {
+ await terminateUnconfirmedCatalogReload('Pi reserve update was not acknowledged');
+ }
+ reserveApplied = true;
+ }
+ const restoreReserveOrTerminate = async (): Promise<void> => {
+ if (!reserveApplied) return;
+ try {
+ const restored = await proc.request({
+ type: 'set_compaction_reserve_tokens', reserveTokens: oldReserve,
+ });
+ if (restored.success &&
+ (restored.data as { reserveTokens?: unknown } | undefined)?.reserveTokens === oldReserve) return;
+ } catch { /* An unconfirmed reserve rollback requires retirement. */ }
+ await terminateUnconfirmedCatalogReload('compaction reserve rollback failed');
+ };
const previousSnapshot = {
model: mutableWireModel,
provider: mutablePiProviderId,
@@ -6368,6 +6619,7 @@ export class PiAgent extends BaseAgent {
subagentRoutingEnabled
&& !(await writeSubagentRuntimeFile({ model: wireModel, provider, pending: true }))
) {
+ await restoreReserveOrTerminate();
throw new Error(
'pi: 无法持久化子代理路由快照,已取消本次模型切换(避免父会话切到新 provider 而子代理仍按旧路由派发)。' +
'请检查运行目录是否可写后重试。',
@@ -6442,155 +6694,51 @@ export class PiAgent extends BaseAgent {
'pi: 模型切换失败且子代理路由快照无法回滚,已终止本会话以避免委派请求发往未启用的端点。' + '请检查运行目录是否可写后重开会话。',
);
}
+ await restoreReserveOrTerminate();
throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);
}
- // Keep the subagent snapshot pending until any settings reload has rebuilt and
- // re-verified the Pi runtime. switch_session recreates AgentSession from the
- // original CLI options, so clearing pending here would briefly allow children
- // to use the target route while the parent may have fallen back to the old one.
+ // Confirm the materialized route and real window before releasing children.
+ try {
+ const verified = await proc.request({ type: 'get_state' });
+ const verifiedModel = (verified.data as {
+ model?: { provider?: unknown; id?: unknown; contextWindow?: unknown } | null;
+ } | undefined)?.model;
+ if (!verified.success || verifiedModel?.provider !== provider || verifiedModel.id !== wireModel ||
+ typeof verifiedModel.contextWindow !== 'number' ||
+ !Number.isSafeInteger(verifiedModel.contextWindow) || verifiedModel.contextWindow <= 0) {
+ throw new Error('Pi did not confirm the requested model and context window');
+ }
+ const verifiedWindow = verifiedModel.contextWindow;
+ const verifiedReserve = reserveForWindow(verifiedWindow, effectiveProviderId, model);
+ if (verifiedReserve !== targetReserve) {
+ const corrected = await proc.request({
+ type: 'set_compaction_reserve_tokens', reserveTokens: verifiedReserve,
+ });
+ if (!corrected.success) throw new Error('Pi did not confirm the actual-window reserve');
+ if ((corrected.data as { reserveTokens?: unknown } | undefined)?.reserveTokens !== verifiedReserve) {
+ throw new Error('Pi did not acknowledge the actual-window reserve');
+ }
+ }
+ await this.writePiRuntimeSettings(configHome, {
+ fileOps, contextWindow: verifiedWindow,
+ workingContextWindow: this.deps.resolveModelContextLimit?.(effectiveProviderId, model) ?? undefined,
+ piCompactionPct: sessionPiAutoCompactPct, packages: nativePackagePaths,
+ disabledSkills: disabledSkillLaunch,
+ });
+ ctx.contextWindow = verifiedWindow;
+ ctx.workingContextWindow = this.deps.resolveModelContextLimit?.(effectiveProviderId, model) ?? undefined;
+ } catch (error) {
+ await terminateUnconfirmedCatalogReload(error);
+ }
mutableModel = model;
+ pendingCurrentDescriptorRefresh = false;
mutableWireModel = wireModel;
mutablePiProviderId = provider;
activeEffortSnapshot = nextEffortSnapshot;
- if (setOpts && Object.hasOwn(setOpts, 'providerId')) {
- mutableProviderId = setOpts.providerId;
- } else if (provider !== PI_PROVIDER_ID) {
- // 轮 40-w4-t13 MEDIUM:providerless 切模时实际路由变了 —— 宿主鉴权/审查
- // 元数据必须跟随实际路由, 否则 reviewAutoAction 用旧 provider 做决策
- // (AutoReviewRequest.providerId + 缓存键都错)。null/订阅来源已归一为
- // cindy(PI_PROVIDER_ID), 不在此分支。
- mutableProviderId = resolveSourceProvider(provider);
- }
+ mutableProviderId = effectiveProviderId;
autoReviewDecisionCache.clear();
- // 换模型 / 换路由可能正好修掉了审阅器不可用的原因;换完又不可用值得再提醒一次。
autoReviewUnavailableNotice.reset();
autoReviewConfirmUndeliveredNotice.reset();
- const data = (resp.data ?? {}) as { contextWindow?: number };
- const setModelReportedWindow =
- typeof data.contextWindow === 'number' && data.contextWindow > 0
- ? data.contextWindow
- : null;
- const nextWindow =
- setModelReportedWindow ??
- this.deps.resolvePiRuntimeModelDescriptor?.(mutableProviderId ?? null, model)
- ?.contextWindow ??
- this.capabilities.availableModels.find((candidate) => candidate.id === model)
- ?.contextWindow ??
- ctx.contextWindow;
- if (nextWindow > 0) ctx.contextWindow = nextWindow;
- ctx.workingContextWindow = this.deps.resolveModelContextLimit?.(mutableProviderId, model) ?? undefined;
- // Always reload and read get_state after set_model. The catalog and even the
- // set_model response can disagree with the materialized runtime window; callers
- // must not decide whether to destroy native context until this verification ends.
- {
- try {
- if (!Number.isFinite(nextWindow) || nextWindow <= 0) {
- throw new Error('pi: model switch returned no verifiable context window');
- }
- await this.writePiRuntimeSettings(configHome, {
- fileOps,
- contextWindow: nextWindow,
- workingContextWindow: ctx.workingContextWindow,
- piCompactionPct: sessionPiAutoCompactPct,
- packages: nativePackagePaths,
- disabledSkills: disabledSkillLaunch,
- });
- if (!sdkSessionId) {
- throw new Error('pi: missing session path after model switch; cannot reload compaction settings');
- }
- const reloaded = await proc.request({
- type: 'switch_session',
- sessionPath: sdkSessionId,
- });
- if (!reloaded.success) {
- throw new Error(
- `pi: failed to reload settings after context window change: ${reloaded.error ?? 'unknown'}`,
- );
- }
- // Pi rebuilds switch_session from the process' original --provider/--model
- // options. Re-apply the requested route, then read it back before exposing
- // the parent or its subagents as switched.
- const reapplied = await proc.request({
- type: 'set_model',
- provider,
- modelId: wireModel,
- });
- if (!reapplied.success) {
- throw new Error(
- `pi: failed to re-apply model after settings reload: ${reapplied.error ?? 'unknown'}`,
- );
- }
- const verified = await proc.request({ type: 'get_state' });
- if (!verified.success) {
- throw new Error(
- `pi: failed to verify model after settings reload: ${verified.error ?? 'unknown'}`,
- );
- }
- const verifiedModel = (verified.data as {
- model?: { provider?: unknown; id?: unknown; contextWindow?: unknown } | null;
- } | undefined)?.model;
- if (verifiedModel?.provider !== provider || verifiedModel.id !== wireModel) {
- throw new Error(
- `pi: settings reload restored an unexpected model (expected ${provider}/${wireModel}, ` +
- `got ${String(verifiedModel?.provider)}/${String(verifiedModel?.id)})`,
- );
- }
- const verifiedWindow = verifiedModel.contextWindow;
- if (
- typeof verifiedWindow !== 'number' ||
- !Number.isFinite(verifiedWindow) ||
- verifiedWindow <= 0
- ) {
- throw new Error('pi: settings reload returned an invalid context window');
- }
- if (verifiedWindow !== nextWindow) {
- await this.writePiRuntimeSettings(configHome, {
- fileOps,
- contextWindow: verifiedWindow,
- workingContextWindow: ctx.workingContextWindow,
- piCompactionPct: sessionPiAutoCompactPct,
- packages: nativePackagePaths,
- disabledSkills: disabledSkillLaunch,
- });
- const recalibrated = await proc.request({ type: 'switch_session', sessionPath: sdkSessionId });
- if (!recalibrated.success) {
- throw new Error(`pi: failed to reload recalibrated settings: ${recalibrated.error ?? 'unknown'}`);
- }
- const recalibratedModel = await proc.request({ type: 'set_model', provider, modelId: wireModel });
- if (!recalibratedModel.success) {
- throw new Error(`pi: failed to re-apply model after settings recalibration: ${recalibratedModel.error ?? 'unknown'}`);
- }
- const reverified = await proc.request({ type: 'get_state' });
- const reverifiedModel = (reverified.data as {
- model?: { provider?: unknown; id?: unknown; contextWindow?: unknown } | null;
- } | undefined)?.model;
- if (
- !reverified.success ||
- reverifiedModel?.provider !== provider ||
- reverifiedModel.id !== wireModel ||
- reverifiedModel.contextWindow !== verifiedWindow
- ) {
- throw new Error('pi: recalibrated settings did not match the verified runtime window');
- }
- }
- ctx.contextWindow = verifiedWindow;
- } catch (err) {
- this.deps.logger.error('pi: compaction settings reload unconfirmed after model switch', {
- message: err instanceof Error ? err.message : String(err),
- });
- try {
- await proc.close();
- } catch (closeErr) {
- this.deps.logger.warn(
- 'pi: session termination after compaction settings reload failure also failed',
- { message: closeErr instanceof Error ? closeErr.message : String(closeErr) },
- );
- }
- throw new Error(
- 'pi: 模型切换后未能重载压缩阈值,已终止本任务以免继续按旧 reserveTokens 压缩。请重新打开任务。',
- );
- }
- }
// The parent route and target-window settings are now confirmed. Clear the
// pending marker last; failure keeps subagent delegation disabled but does
// not misreport the parent switch itself.
@@ -7220,6 +7368,10 @@ export class PiAgent extends BaseAgent {
piSubagentApprovalDeferred.clear();
},
+ previewModelSwitch(model, target) {
+ return previewPiModelSwitch(model, target);
+ },
+
requiresModelSwitchRebuild(model, target) {
// Same-route configuration changes need models.json to be reloaded too.
// Ordinary route changes continue through Pi's existing switch_model path.
diff --git a/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts b/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts
index 15332822b0..f445adf961 100644
--- a/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts
+++ b/packages/maker-core/src/agents/pi/native-provider-adapter-source.ts
@@ -15,18 +15,80 @@ export function nativeProviderAdapterAliases(
}
export const PI_NATIVE_PROVIDER_ADAPTER_SOURCE = String.raw`
+type CindyAdapterAlias = { id: string; name: string; provider: string; keyEnv?: string };
+type CindyProviderRefreshSnapshot = {
+ nonce: string;
+ env: Record<string, string>;
+ aliases: CindyAdapterAlias[];
+};
+
+const CINDY_DYNAMIC_KEY_ENV_PATTERN = /^CINDY_PI_KEY_[A-Z0-9_]+$/;
+function cindyRefreshEnvAllowed(name: string): boolean {
+ return CINDY_DYNAMIC_KEY_ENV_PATTERN.test(name)
+ || name === 'CINDY_PI_SESSION_TOKEN'
+ || name === 'CINDY_PI_API_KEY'
+ || CINDY_FIXED_ADAPTER_KEYS.has(name);
+}
+const CINDY_FIXED_ADAPTER_KEYS = new Set([
+ 'CINDY_PI_OPENAI_PROXY_KEY',
+ 'CINDY_PI_XAI_PROXY_API_KEY',
+]);
+
+function parseCindyProviderRefreshSnapshot(raw: unknown, nonce: string): CindyProviderRefreshSnapshot | undefined {
+ if (typeof raw !== 'string') return undefined;
+ let payload: any;
+ try { payload = JSON.parse(raw); } catch { return undefined; }
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload) || payload.nonce !== nonce) return undefined;
+ if (!payload.env || typeof payload.env !== 'object' || Array.isArray(payload.env)) return undefined;
+ if (!Array.isArray(payload.aliases)) return undefined;
+ const env: Record<string, string> = Object.create(null);
+ for (const [name, value] of Object.entries(payload.env)) {
+ if (!cindyRefreshEnvAllowed(name) || typeof value !== 'string') return undefined;
+ env[name] = value;
+ }
+ const aliases: CindyAdapterAlias[] = [];
+ const seen = new Set<string>();
+ for (const alias of payload.aliases) {
+ if (!alias || typeof alias !== 'object' || Array.isArray(alias)) return undefined;
+ if (typeof alias.id !== 'string' || !alias.id || seen.has(alias.id)) return undefined;
+ if (typeof alias.name !== 'string') return undefined;
+ if (typeof alias.provider !== 'string' || !alias.provider) return undefined;
+ if (alias.keyEnv !== undefined && (
+ typeof alias.keyEnv !== 'string'
+ || !cindyRefreshEnvAllowed(alias.keyEnv)
+ || !Object.hasOwn(env, alias.keyEnv)
+ )) return undefined;
+ seen.add(alias.id);
+ aliases.push({ id: alias.id, name: alias.name, provider: alias.provider,
+ ...(alias.keyEnv ? { keyEnv: alias.keyEnv } : {}) });
+ }
+ return { nonce, env, aliases };
+}
+
async function registerCindyNativeProviderAdapters(pi: any) {
- const raw = process.env.CINDY_PI_NATIVE_PROVIDER_ADAPTERS;
- if (!raw) return;
- const aliases = JSON.parse(raw);
- if (!Array.isArray(aliases) || aliases.length === 0) return;
- const { lazyStream, envApiKeyAuth } = await import('@earendil-works/pi-ai');
- const { getApiProvider } = await import('@earendil-works/pi-ai/compat');
- pi.on('session_start', (_event: any, ctx: any) => {
- for (const alias of aliases) {
- if (typeof alias.id !== 'string' || typeof alias.provider !== 'string') continue;
- const models = ctx.modelRegistry.getAll().filter((model: any) => model.provider === alias.id);
- if (models.length === 0) continue;
+ let aliases: CindyAdapterAlias[] = [];
+ try {
+ const initial = JSON.parse(process.env.CINDY_PI_NATIVE_PROVIDER_ADAPTERS ?? '[]');
+ if (Array.isArray(initial)) aliases = initial;
+ } catch { /* A malformed startup hint cannot affect other Pi extensions. */ }
+ const registered = new Set<string>();
+ let apis: { lazyStream: any; envApiKeyAuth: any; getApiProvider: any } | undefined;
+ async function loadApis() {
+ if (!apis) {
+ const [{ lazyStream, envApiKeyAuth }, { getApiProvider }] = await Promise.all([
+ import('@earendil-works/pi-ai'),
+ import('@earendil-works/pi-ai/compat'),
+ ]);
+ apis = { lazyStream, envApiKeyAuth, getApiProvider };
+ }
+ return apis;
+ }
+ function registerAliases(models: any[], currentAliases: CindyAdapterAlias[]) {
+ if (!apis) throw new Error('Native provider adapter is unavailable');
+ const { lazyStream, envApiKeyAuth, getApiProvider } = apis;
+ for (const alias of currentAliases) {
+ const providerModels = models.filter((model: any) => model.provider === alias.id);
+ if (providerModels.length === 0) continue;
const stream = (model: any, context: any, options: any, simple: boolean) => lazyStream(model, async () => {
const api = getApiProvider(model.api);
if (!api) throw new Error('The selected native provider API is unavailable');
@@ -52,13 +114,45 @@ async function registerCindyNativeProviderAdapters(pi: any) {
};
})();
});
- pi.registerProvider({ id: alias.id, name: alias.name ?? alias.id,
- ...(typeof alias.keyEnv === 'string' ? { auth: { apiKey: envApiKeyAuth('API key', [alias.keyEnv]) } } : {}),
- getModels: () => models,
+ pi.registerProvider({ id: alias.id, name: alias.name,
+ ...(alias.keyEnv ? { auth: { apiKey: envApiKeyAuth('API key', [alias.keyEnv]) } } : {}),
+ getModels: () => providerModels,
stream: (model: any, context: any, options: any) => stream(model, context, options, false),
streamSimple: (model: any, context: any, options: any) => stream(model, context, options, true),
});
+ registered.add(alias.id);
}
+ }
+ if (aliases.length) await loadApis();
+ pi.on('session_start', (_event: any, ctx: any) => {
+ if (aliases.length) registerAliases(ctx.modelRegistry.getAll(), aliases);
});
+ return {
+ async refresh(snapshot: CindyProviderRefreshSnapshot, ctx: any, secretEnvNames: Set<string>) {
+ if (snapshot.aliases.length) await loadApis();
+ // The host supplies the entire current dynamic-key snapshot, so deleted
+ // provider/header keys disappear from both Pi and future bash children.
+ for (const name of Object.keys(process.env)) {
+ if (cindyRefreshEnvAllowed(name) && !Object.hasOwn(snapshot.env, name)) {
+ delete process.env[name];
+ secretEnvNames.delete(name);
+ }
+ }
+ for (const [name, value] of Object.entries(snapshot.env)) {
+ process.env[name] = value;
+ secretEnvNames.add(name);
+ }
+ for (const id of registered) pi.unregisterProvider(id);
+ registered.clear();
+ const result = await ctx.modelRegistry.refresh({ allowNetwork: false });
+ if (result?.aborted || result?.errors?.size) throw new Error('Native provider catalog refresh failed');
+ aliases = snapshot.aliases;
+ if (aliases.length) registerAliases(ctx.modelRegistry.getAll(), aliases);
+ // Registering providers schedules an internal refresh in Pi. Await one
+ // public refresh so the receipt reflects the final provider snapshot.
+ const final = await ctx.modelRegistry.refresh({ allowNetwork: false });
+ if (final?.aborted || final?.errors?.size) throw new Error('Native provider adapter refresh failed');
+ },
+ };
}
`;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index aa5c1bf377..8b1ed52d7a 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -52,6 +52,7 @@ import type { ContextUsageData } from './types/context-usage.js';
import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';
import type {
AgentSessionHandle,
+ PiModelSwitchPreview,
AgentSessionTeardownOptions,
BackgroundTaskSnapshot,
SendOptions,
@@ -1722,6 +1723,13 @@ export class Session {
await this.handle.setModel(model, opts);
}
+ async previewModelSwitch(
+ model: string,
+ opts?: { providerId?: string | null },
+ ): Promise<PiModelSwitchPreview | undefined> {
+ return this.handle.previewModelSwitch?.(model, opts);
+ }
+
async requiresModelSwitchRebuild(
model: string,
opts?: { providerId?: string | null },