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(desktop): guard switches into smaller model windows (#3601)

Chris Zhang1fbcdeac55a4
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 384b066b87..1285bb7fbd 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -2586,6 +2586,43 @@ describe('远程 set-* 持久化回流', () => {
expect(persist).toHaveBeenCalledWith('sess-1', { model: 'claude-x' });
});
+ it('set-model 最终窗口待确认时不提前持久化 model/provider', async () => {
+ const persist = vi.fn();
+ setRemoteSettingsPersist(persist);
+ const confirmation = {
+ deferred: false,
+ superseded: false,
+ contextWindowConfirmationRequired: 272_000,
+ contextTokensForConfirmation: 244_800,
+ };
+ registry.register('maker:set-model', () => confirmation);
+
+ const r = await runInvoke('ctrl-a', {
+ channel: 'maker:set-model',
+ args: ['sess-1', 'small-pi-model', 'pi-provider'],
+ });
+
+ expect(r).toEqual({ ok: true, result: confirmation });
+ expect(persist).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [{ contextTokensForConfirmation: 244_800 }],
+ [{ contextWindowConfirmationRequired: '272000' }],
+ ])('set-model 最终窗口确认字段不完整时也不得提前持久化 %#', async (confirmation) => {
+ const persist = vi.fn();
+ setRemoteSettingsPersist(persist);
+ registry.register('maker:set-model', () => confirmation);
+
+ const r = await runInvoke('ctrl-a', {
+ channel: 'maker:set-model',
+ args: ['sess-1', 'small-pi-model', 'pi-provider'],
+ });
+
+ expect(r).toEqual({ ok: true, result: confirmation });
+ expect(persist).not.toHaveBeenCalled();
+ });
+
it('set-model 持久化 trim 后的 providerId', async () => {
const persist = vi.fn();
setRemoteSettingsPersist(persist);
@@ -2620,8 +2657,12 @@ describe('远程 set-* 持久化回流', () => {
it('set-model handler 已在 session 锁内持久化时 dispatch 不重复回流', async () => {
const persist = vi.fn();
setRemoteSettingsPersist(persist);
- const handlerResult = { deferred: false, superseded: false };
- markRemoteSettingPersistedInsideHandler(handlerResult);
+ const response = { deferred: false, superseded: false };
+ markRemoteSettingPersistedInsideHandler(response);
+ const handlerResult = Object.assign(response, {
+ generation: 2,
+ effectiveProviderId: 'anthropic',
+ });
registry.register('maker:set-model', () => handlerResult);
const r = await runInvoke('ctrl-a', {
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index dcd9c9f808..f205d140c1 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -360,6 +360,28 @@ describe('sendToSession ordering', () => {
expect(resumedBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session resumed');");
});
+ it('routes a retained Pi error handle through bounded close retry before sending', () => {
+ const block = extractSendToSessionSource();
+ const loadLive = block.indexOf('let live = maker.getSession(targetSessionId);');
+ const retainedErrorGuard = block.indexOf(
+ "if (live?.agentKind === 'pi' && live.getStatus() === 'error') {",
+ );
+ const liveDispatch = block.indexOf('if (live) {', retainedErrorGuard);
+ const lazyResume = block.indexOf(
+ 'const { session } = await bootstrapSession(createOpts);',
+ liveDispatch,
+ );
+
+ expect(loadLive).toBeGreaterThan(-1);
+ expect(retainedErrorGuard).toBeGreaterThan(loadLive);
+ expect(liveDispatch).toBeGreaterThan(retainedErrorGuard);
+ expect(lazyResume).toBeGreaterThan(liveDispatch);
+ expect(block.slice(retainedErrorGuard, liveDispatch)).toContain('live = undefined;');
+ expect(source).toContain(
+ 'whose Maker.createSession call performs the existing bounded close retry',
+ );
+ });
+
it('awaits Git baseline capture after send_to_session user row persistence and before dispatch', () => {
const changeSetBlock = extractBetween(
source,
@@ -523,6 +545,8 @@ describe('sendToSession ordering', () => {
expect(setModelBlock).toContain('patch.fastMode = atomicSelection.fastMode;');
expect(setModelBlock).toContain('await persistSessionFields(sessionId, patch);');
expect(setModelBlock).toContain('markRemoteSettingPersistedInsideHandler(response);');
+ expect(setModelBlock).toContain('return Object.assign(response, {');
+ expect(setModelBlock).not.toContain('return {\n ...response,');
expectOrder(
setModelBlock,
'applyRuntimeSetModelChange({',
@@ -751,7 +775,7 @@ describe('sendToSession ordering', () => {
expect(terminalBlock).toContain('await orcaTeamServiceForEvents?.handleWorkerTerminalTurn({');
expect(terminalBlock).toContain('sessionId: session.id,');
expect(terminalBlock).toContain("status: isTerminalTurnErrorEvent(event) ? 'error' : 'done',");
- expect(terminalBlock).toContain('finalText,');
+ expect(terminalBlock).toContain('finalText: workerTerminalFinalText,');
expect(terminalBlock).not.toContain('getWorkerLink');
expect(terminalBlock).not.toContain('listWorkersByLead');
expect(terminalBlock).not.toContain('dispatchInterAgentMessage');
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index c472e8c15e..9d9f0fc48e 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -11,6 +11,10 @@ const registerSource = readFileSync(resolve(mainRoot, 'maker-ipc/register.ts'),
/\r\n?/g,
'\n',
);
+const deviceLinkHostSource = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8').replace(
+ /\r\n?/g,
+ '\n',
+);
const makerSendSource = readFileSync(
resolve(mainRoot, 'maker-ipc/makerSendTransaction.ts'),
'utf8',
@@ -25,6 +29,15 @@ function handlerBody(source: string, channel: string, nextChannel: string): stri
}
describe('session runtime control wiring', () => {
+ it('advertises host-side model-window protection to remote controllers', () => {
+ const capabilities = handlerBody(
+ registerSource,
+ 'ipcMain.handle(MAKER_INVOKE.GET_CAPABILITIES',
+ 'ipcMain.handle(MAKER_INVOKE.GET_NEW_MAKER_DEFAULTS',
+ );
+ expect(capabilities).toContain('supportsModelWindowSwitchGuard: true');
+ });
+
it('authenticates Desktop package-command entry points before minting Main context', () => {
const legacySend = handlerBody(
registerSource,
@@ -44,7 +57,9 @@ describe('session runtime control wiring', () => {
);
expect(steerDispatch).toContain('[MAIN_OWNED_SEND_CONTEXT]: so[MAIN_OWNED_SEND_CONTEXT]');
expect(registerSource).toContain('trustedDesktopSteerText.run(queued.text, runSteer)');
- expect(registerSource).toContain('attachTrustedDesktopSendContext(message, sendOpts, expectedText)');
+ expect(registerSource).toContain(
+ 'attachTrustedDesktopSendContext(message, sendOpts, expectedText)',
+ );
for (const [channel, nextChannel] of [
['MAKER_INVOKE.INPUT_ENQUEUE,', 'MAKER_INVOKE.INPUT_COMPACT,'],
@@ -245,9 +260,7 @@ describe('session runtime control wiring', () => {
expect(setModel.indexOf('assertTrustedAppRendererEvent(')).toBeLessThan(
setModel.indexOf("typeof sessionId !== 'string'"),
);
- expect(setModel).toContain(
- '!isSupportedRuntimeEffort((selection as { effort?: unknown }).effort)',
- );
+ expect(setModel).toContain('!isSupportedRuntimeEffort(selectionEffort)');
expect(setModel).toContain("internalOptions.source !== 'user'");
expect(registerSource).toMatch(
/handleSetModel\(\s*undefined,\s*sessionId,\s*model,\s*providerId,\s*undefined,\s*selection,\s*options,?\s*\)/,
@@ -256,6 +269,32 @@ describe('session runtime control wiring', () => {
expect(setModel).not.toContain('ipcMain.handle(MAKER_INVOKE.SET_MODEL, handleSetModel)');
});
+ it('accepts null effort for fixed-effort local retries and device-link atomic selections', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const confirmation = setModel.indexOf('const confirmedContextWindow =');
+ const selectionValidation = setModel.indexOf('!isSupportedRuntimeEffort(selectionEffort)');
+ const fixedEffortValidation = setModel.indexOf('atomicSelection.effort === null');
+ const prepare = setModel.indexOf('prepareModelWindowSwitch(');
+ const apply = setModel.indexOf('applyRuntimeSetModelChange({');
+
+ expect(confirmation).toBeGreaterThan(-1);
+ expect(confirmation).toBeLessThan(selectionValidation);
+ expect(setModel).toContain(
+ "selectionEffort === null &&\n (internalOptions.source !== 'user' ||\n isDeviceLinkInvoke() ||\n confirmedContextWindow !== undefined)",
+ );
+ expect(setModel).toContain('catalogModel.efforts.length > 0');
+ expect(fixedEffortValidation).toBeGreaterThan(selectionValidation);
+ expect(fixedEffortValidation).toBeLessThan(prepare);
+ expect(prepare).toBeLessThan(apply);
+ expect(setModel).toContain(
+ '!isDeviceLinkInvoke() && confirmedContextWindow === targetContextWindow',
+ );
+ });
+
it('validates atomic user axes against the selected catalog model before side effects', () => {
const setModel = handlerBody(
registerSource,
@@ -280,6 +319,163 @@ describe('session runtime control wiring', () => {
expect(axisValidation).toBeLessThan(setModel.indexOf('persistSessionFields(sessionId'));
});
+ it('reconciles deferred route axes before the pending gate can wake input', () => {
+ const persistRoute = handlerBody(
+ registerSource,
+ 'persistRoute: async (sessionId, route) => {',
+ 'logger: log,',
+ );
+ const resolveAxes = persistRoute.indexOf('const axes = resolveSessionRuntimeAxes({');
+ const persist = persistRoute.indexOf(
+ 'await getDbClient().drizzle.update(sessions).set(patch)',
+ resolveAxes,
+ );
+ const commitEffort = persistRoute.indexOf('setSessionEffort(sessionId, finalEffort);', persist);
+ const commitFast = persistRoute.indexOf('setSessionFastMode(sessionId, finalFastMode);', persist);
+ const broadcast = persistRoute.indexOf('broadcastSessionPatched(sessionId, patch);', persist);
+
+ expect(persistRoute).toContain('const [desiredRow] = await getDbClient()');
+ expect(persistRoute).toContain('const restoringPreviousRoute =');
+ expect(persistRoute).toContain(
+ 'let finalEffort = restoringPreviousRoute && route.effort',
+ );
+ expect(persistRoute).toContain(
+ 'let finalFastMode = restoringPreviousRoute && route.fastMode !== undefined',
+ );
+ expect(persistRoute).toContain('effortExplicit: false');
+ expect(persistRoute).toContain('fastExplicit: false');
+ expect(resolveAxes).toBeGreaterThan(-1);
+ expect(persist).toBeGreaterThan(resolveAxes);
+ expect(commitEffort).toBeGreaterThan(persist);
+ expect(commitFast).toBeGreaterThan(commitEffort);
+ expect(broadcast).toBeGreaterThan(commitFast);
+ });
+
+ it('commits device-link atomic axes before a rebuilt queue can wake', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const selectionStart = setModel.indexOf('const selectionToCommit = atomicSelection;');
+ const applyAxes = setModel.indexOf('await applyRuntimeSelectionAxesWithRecovery({');
+ const patchEffort = setModel.indexOf('patch.effort = atomicSelection.effort;', applyAxes);
+ const patchFast = setModel.indexOf('patch.fastMode = atomicSelection.fastMode;', patchEffort);
+ const persistSelection = setModel.indexOf(
+ 'await persistSessionFields(sessionId, patch);',
+ patchFast,
+ );
+ const normalWakeGuard = setModel.indexOf(
+ 'if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred)',
+ persistSelection,
+ );
+ const wakeQueue = setModel.indexOf(
+ 'wakeSessionInputAfterCredentialSwitch(sessionId);',
+ normalWakeGuard,
+ );
+
+ expect(setModel).toContain('selectionEffort === null &&');
+ expect(setModel).toContain('isDeviceLinkInvoke() ||');
+ expect(setModel).toContain(
+ "(atomicSelection?.effort === null && runtimeAgentKind !== 'pi')",
+ );
+ expect(setModel).toContain('!rebuildLiveOrcaWorker && !atomicSelection');
+ expect(setModel).toContain('{ wake: false }');
+ expect(setModel).toContain("runtimeAgentKind !== 'pi' &&");
+ expect(selectionStart).toBeGreaterThan(-1);
+ expect(setModel.slice(selectionStart, applyAxes)).toContain(
+ 'setSessionFastMode(sessionId, selectionToCommit.fastMode);',
+ );
+ expect(applyAxes).toBeGreaterThan(selectionStart);
+ expect(patchEffort).toBeGreaterThan(applyAxes);
+ expect(patchFast).toBeGreaterThan(patchEffort);
+ expect(persistSelection).toBeGreaterThan(patchFast);
+ expect(normalWakeGuard).toBeGreaterThan(persistSelection);
+ expect(wakeQueue).toBeGreaterThan(normalWakeGuard);
+ });
+
+ it('requires a verified target window before preparing any destructive model rebuild', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const verifiedWindowOnly = setModel.indexOf(
+ 'targetContextWindow = verifiedTargetWindow ?? undefined;',
+ );
+ const unknownWindowGuard = setModel.indexOf(
+ 'target model context window is unknown; runtime selection was not changed',
+ );
+ const prepare = setModel.indexOf('prepareModelWindowSwitch(');
+ const apply = setModel.indexOf('applyRuntimeSetModelChange({');
+ expect(verifiedWindowOnly).toBeGreaterThan(-1);
+ expect(setModel).toContain('await maker.getSessionMeta(sessionId)');
+ expect(setModel).toContain(
+ 'liveSessionBeforeRouteChange?.model ?? persistedSessionMeta?.model',
+ );
+ expect(setModel).not.toContain(
+ 'if (liveSessionBeforeRouteChange && runtimeAgentKind && runtimeRouteChanged)',
+ );
+ expect(setModel).not.toContain('verifiedTargetWindow ?? targetCatalogModel?.contextWindow');
+ expect(verifiedWindowOnly).toBeLessThan(unknownWindowGuard);
+ expect(unknownWindowGuard).toBeLessThan(prepare);
+ expect(prepare).toBeGreaterThan(-1);
+ expect(prepare).toBeLessThan(apply);
+ expect(setModel).not.toContain('getAutoCompactThresholdPct');
+ expect(setModel).toContain("preparation === 'busy'");
+ expect(setModel).toContain("preparation === 'remote-unsupported'");
+ expect(setModel).toContain('beforeClose: () => {');
+ expect(setModel).toContain('clearPendingCredentialSwitchForSession(sessionId, { wake: false })');
+ expect(setModel).toContain('sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)');
+ expect(setModel).toContain('modelWindowRebuilt ||');
+ expect(setModel).toContain('patch.contextWindow = targetContextWindow;');
+ expect(setModel).toContain(
+ '(rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection)',
+ );
+ expect(setModel).toContain('wakeSessionInputAfterCredentialSwitch(sessionId);');
+ });
+
+ it('projects rebuilt zero usage and the verified window after the runtime is closed', () => {
+ const commitRebuild = handlerBody(
+ registerSource,
+ 'commitRebuild: async (sessionId, handoff, meta) => {',
+ 'setPendingHandoff: (sessionId, handoff, expectedGeneration)',
+ );
+ const query = commitRebuild.indexOf('contextWindow: sessions.contextWindow,');
+ const commit = commitRebuild.indexOf('commitContextRebuild(sessionId, handoff, meta)');
+ const broadcast = commitRebuild.indexOf('broadcastSessionPatched(\n sessionId,');
+
+ expect(query).toBeGreaterThan(-1);
+ expect(commit).toBeGreaterThan(query);
+ expect(broadcast).toBeGreaterThan(commit);
+ expect(commitRebuild).toContain('contextTokens: 0,');
+ expect(commitRebuild).toContain('{ contextWindow: projectionContextWindow }');
+ expect(commitRebuild).toContain('const ownerScope = captureDataOwnerBroadcastScope();');
+ expect(commitRebuild).toContain('getCurrentDbClientSnapshot()?.clientEpoch');
+ expect(commitRebuild).toContain('ownerScope,\n );');
+ expect(commitRebuild).toContain("log.warn('context rebuild card creation failed after commit'");
+ expect(commitRebuild).toContain('try {\n await createDbMessage(\n sessionId,');
+
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ expect(setModel).toContain("typeof runtimeStatus.contextTokens === 'number'");
+ expect(setModel).toContain('runtimeStatus.contextTokens >= 0');
+ const persistFinalRoute = setModel.indexOf('await persistSessionFields(sessionId, patch);');
+ const projectFinalWindow = setModel.indexOf(
+ '// commitRebuild first projects zero usage against the still-authoritative',
+ );
+ expect(persistFinalRoute).toBeGreaterThan(-1);
+ expect(projectFinalWindow).toBeGreaterThan(persistFinalRoute);
+ expect(setModel.slice(projectFinalWindow)).toContain('contextTokens: 0,');
+ expect(setModel.slice(projectFinalWindow)).toContain('contextWindow: targetContextWindow,');
+ expect(setModel).toContain(
+ 'const routeProjectionOwnerScope = captureDataOwnerBroadcastScope();',
+ );
+ });
+
it('omits effort from the DB patch for fixed-effort models (sessions.effort NOT NULL)', () => {
const setModel = handlerBody(
registerSource,
@@ -353,6 +549,13 @@ describe('session runtime control wiring', () => {
expect(catchBlock.indexOf('cancelPendingSessionRuntimeMutation')).toBeLessThan(
catchBlock.indexOf('broadcastSessionRuntimeProjection'),
);
+ expect(catchBlock).toContain("const failureReason = 'runtime-selection-cancelled'");
+ expect(catchBlock).toContain('onTurnErrorEvent(sessionId, { message: failureMessage');
+ expect(catchBlock).toContain('broadcastToAllWindows(MAKER_PUSH.EVENT');
+ expect(catchBlock).toContain('The previous model remains active.');
+ expect(catchBlock.indexOf('broadcastSessionRuntimeProjection')).toBeLessThan(
+ catchBlock.indexOf('broadcastToAllWindows(MAKER_PUSH.EVENT'),
+ );
});
it('drops in-flight effort and Fast mutations after an owner boundary', () => {
@@ -437,6 +640,34 @@ describe('session runtime control wiring', () => {
expect(targetRoute).not.toContain('requiresCodexThreadRelink && atomicSelection');
});
+ it('skips stale Codex thread relink after rebuild and still commits the target route', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const rebuilt = setModel.indexOf("modelWindowRebuilt = preparation === 'rebuilt'");
+ const relinkGate = setModel.indexOf(
+ 'const shouldRelinkCodexThread = requiresCodexThreadRelink && !modelWindowRebuilt;',
+ );
+ const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
+ const persist = setModel.indexOf('await persistSessionFields(sessionId, patch);');
+
+ expect(rebuilt).toBeGreaterThan(-1);
+ expect(relinkGate).toBeGreaterThan(rebuilt);
+ expect(relinkGate).toBeLessThan(apply);
+ expect(setModel.slice(apply, persist)).toContain(
+ 'requiresCodexThreadRelink: shouldRelinkCodexThread',
+ );
+ expect(setModel.slice(apply, persist)).toContain(
+ 'shouldRelinkCodexThread && relinkCodexThread',
+ );
+ expect(setModel.slice(apply, persist)).toContain(
+ 'result.persistedRoute !== true &&\n (modelWindowRebuilt ||',
+ );
+ expect(persist).toBeGreaterThan(apply);
+ });
+
it('omits null runtime effort from the Codex relink SQLite commit', () => {
const setModel = handlerBody(
registerSource,
@@ -545,6 +776,48 @@ describe('session runtime control wiring', () => {
expect(registerSource).toContain('result = await applyCandidate();');
});
+ it('fails closed when non-UI runtime selection requires model-window confirmation', () => {
+ const setRuntime = handlerBody(
+ registerSource,
+ 'setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {',
+ 'assertExternalInputAllowed: assertReviewExternalInputAllowed,',
+ );
+ const setRuntimeGuard = setRuntime.indexOf(
+ 'if (runtimeSelectionRequiresModelWindowConfirmation(response))',
+ );
+ const setRuntimeSuccess = setRuntime.indexOf(
+ 'const control = getSessionRuntimeControlSnapshot(targetSessionId);',
+ );
+ expect(setRuntimeGuard).toBeGreaterThan(-1);
+ expect(setRuntimeGuard).toBeLessThan(setRuntimeSuccess);
+ expect(setRuntime.slice(setRuntimeGuard, setRuntimeSuccess)).toContain('ok: false');
+ expect(setRuntime.slice(setRuntimeGuard, setRuntimeSuccess)).toContain(
+ "errorCode: 'ROUTE_UNAVAILABLE'",
+ );
+ expect(setRuntime.slice(setRuntimeGuard, setRuntimeSuccess)).toContain(
+ 'runtime selection was not changed',
+ );
+
+ const fallback = handlerBody(
+ registerSource,
+ 'const maybeApplySessionRuntimeFallback = async (',
+ 'const sessionControlService = createSessionControlService({',
+ );
+ const fallbackGuard = fallback.indexOf(
+ 'if (runtimeSelectionRequiresModelWindowConfirmation(result))',
+ );
+ const fallbackSuccess = fallback.indexOf(
+ "log.info('automatic session runtime fallback evaluated'",
+ );
+ expect(fallbackGuard).toBeGreaterThan(-1);
+ expect(fallbackGuard).toBeLessThan(fallbackSuccess);
+ expect(fallback).toContain('blockAutoResumeForModelWindowConfirmation = true;');
+ expect(fallback).toContain('if (blockAutoResumeForModelWindowConfirmation) {');
+ expect(fallback).toContain(
+ 'pendingSessionRuntimeFallbackRebuilds.delete(runtimeSession);\n throw error;',
+ );
+ });
+
it('fences atomic model axis settlement after an owner boundary', () => {
const setModel = handlerBody(
registerSource,
@@ -598,6 +871,21 @@ describe('session runtime control wiring', () => {
expect(registerSource).toContain("effort: effective.effort ?? '',");
});
+ it('persists Pi runtime-verified windows without catalog replacement', () => {
+ const snapshotStart = registerSource.indexOf('if (pendingContextSnapshot) {');
+ const snapshotEnd = registerSource.indexOf(
+ 'if (pendingCodexAccountUsageSnapshot)',
+ snapshotStart,
+ );
+ const snapshot = registerSource.slice(snapshotStart, snapshotEnd);
+
+ expect(snapshot).toContain("session.agentKind === 'pi'");
+ expect(snapshot).toContain('piRuntimeWindow ?? verifiedWindow');
+ expect(snapshot.indexOf('pendingContextSnapshot.contextWindow')).toBeLessThan(
+ snapshot.indexOf('lookupVerifiedContextWindow('),
+ );
+ });
+
it('counts fallback eligibility across the whole interrupted-turn episode', () => {
expect(registerSource).toContain(
'decision.episodeAttempt,\n decision.attemptToken,',
@@ -622,6 +910,231 @@ describe('session runtime control wiring', () => {
expect(fallback).toContain('profiles.control.generation,');
});
+ it('rehydrates a cold Pi runtime before model-window assessment', () => {
+ const rehydrate = handlerBody(
+ registerSource,
+ 'async function rehydrateColdPiRuntimeForWindowVerification(',
+ 'const agentSwitchDeps:',
+ );
+ const rolloverWiring = handlerBody(
+ registerSource,
+ 'contextOverflowRolloverHolder = createContextOverflowRollover({',
+ 'const pendingCredentialSwitchService = new PendingCredentialSwitchService({',
+ );
+
+ expect(rehydrate).toContain("row.agentKind !== 'pi'");
+ expect(rehydrate).toContain('resumeSessionId: row.sdkSessionId');
+ expect(rehydrate).toContain('await bootstrapSession(createOpts)');
+ expect(rehydrate).not.toContain('.send(');
+ expect(rolloverWiring).toContain('rehydrateColdPiRuntimeForWindowVerification,');
+
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const rehydrateCall = setModel.indexOf(
+ 'await rehydrateColdPiRuntimeForWindowVerification(sessionId)',
+ );
+ const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
+ expect(rehydrateCall).toBeGreaterThan(-1);
+ expect(rehydrateCall).toBeLessThan(apply);
+ expect(setModel).toContain('Pi current runtime could not be verified');
+ });
+
+ it('closes a cold Pi runtime when route persistence fails after rehydrate', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const rehydrate = setModel.indexOf(
+ 'await rehydrateColdPiRuntimeForWindowVerification(sessionId)',
+ );
+ const captureRuntime = setModel.indexOf(
+ 'rehydratedColdPiRuntime = liveSessionBeforeRouteChange;',
+ rehydrate,
+ );
+ const persist = setModel.indexOf('await persistSessionFields(sessionId, patch);');
+ const persistenceFailure = setModel.indexOf('catch (persistenceError)', persist);
+ const persistenceRethrow = setModel.indexOf('throw persistenceError;', persistenceFailure);
+ const rollback = setModel.slice(
+ persistenceFailure,
+ persistenceRethrow + 'throw persistenceError;'.length,
+ );
+ const restoreControlStores = setModel.slice(
+ setModel.indexOf('const restoreControlStores ='),
+ setModel.indexOf('const closeRejectedPiRuntime ='),
+ );
+ const restoreStores = rollback.indexOf('restoreControlStores();');
+ const closeRuntime = rollback.indexOf(
+ 'await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));',
+ );
+
+ expect(rehydrate).toBeGreaterThan(-1);
+ expect(captureRuntime).toBeGreaterThan(rehydrate);
+ expect(captureRuntime).toBeLessThan(persist);
+ expect(rollback).toContain(
+ "(result.status !== 'deferred' && previousRuntime.hadLiveSession) ||",
+ );
+ expect(rollback).toContain('rehydratedColdPiRuntime !== undefined;');
+ expect(restoreStores).toBeGreaterThan(-1);
+ expect(closeRuntime).toBeGreaterThan(restoreStores);
+ expect(restoreControlStores).toContain(
+ 'setSessionProvider(sessionId, previousRuntime.providerId);',
+ );
+ expect(restoreControlStores).toContain('setSessionEffort(sessionId, previousRuntime.effort);');
+ expect(restoreControlStores).toContain('setSessionFastMode(sessionId, previousRuntime.fastMode);');
+ expect(rollback).not.toContain('.send(');
+ expect(rollback).toContain('throw persistenceError;');
+ });
+
+ it('rejects only remote rebuild pressure before applying the runtime model', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+
+ expect(setModel).not.toContain('CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1');
+ expect(deviceLinkHostSource).not.toContain(
+ 'CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1',
+ );
+ const remoteAssessment = setModel.indexOf('const remoteTargetAssessment');
+ const remoteGuard = setModel.indexOf('const remoteRouteCannotRebuild', remoteAssessment);
+ const remotePressureRejection = setModel.indexOf(
+ 'remote model-window rebuild is unsupported; runtime selection was not changed',
+ remoteGuard,
+ );
+ const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
+ expect(remoteGuard).toBeGreaterThan(remoteAssessment);
+ const remoteGuardBody = setModel.slice(remoteGuard, remotePressureRejection);
+ expect(remoteGuardBody).toContain('!!runtimeStatus.remoteHostId');
+ expect(remoteGuardBody).toContain('remoteRouteCannotRebuild && targetRequiresRebuild');
+ expect(remoteGuardBody).not.toContain("runtimeAgentKind === 'pi'");
+ // Protected Hosts may apply same-window, expansion, and low-pressure Pi routes,
+ // then use final get_state below to reject only an actual unsafe shrink.
+ expect(remotePressureRejection).toBeGreaterThan(remoteGuard);
+ expect(remotePressureRejection).toBeLessThan(apply);
+ expect(setModel).toContain("remoteTargetAssessment.level === 'danger'");
+ expect(setModel).toContain("remoteTargetAssessment.level === 'overflow'");
+ expect(setModel).toContain(
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ );
+ expect(setModel).toContain('!isDeviceLinkInvoke() && confirmedContextWindow ===');
+ expect(setModel).toContain(
+ "runtimeAgentKind !== 'pi' &&\n confirmedContextWindow !== targetContextWindow",
+ );
+ expect(setModel).not.toContain('confirmedContextWindow > targetContextWindow');
+ });
+
+ it('fails closed before switching a busy or unverifiable cold remote Pi runtime', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
+
+ expect(setModel.indexOf('busy Pi task cannot change runtime selection')).toBeLessThan(apply);
+ expect(
+ setModel.indexOf('cold remote Pi runtime cannot verify the target window'),
+ ).toBeLessThan(apply);
+ expect(setModel).toContain('model window switch context is unknown; runtime selection was not changed');
+ expect(setModel).toContain('finalPiWindow < verifiedCurrentWindow!');
+ expect(setModel).not.toContain('finalPiWindow < targetContextWindow');
+ });
+
+ it('switches and verifies Pi before deciding whether the actual window needs rebuild', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
+ const closeRecovery = setModel.indexOf('const closeRejectedPiRuntime =');
+ const finalWindow = setModel.indexOf('const finalPiWindow =');
+ const finalWindowEnd = setModel.indexOf('if (atomicSelection) {', finalWindow);
+ const runtimeCommit = setModel.indexOf('let generation: number;');
+ const finalPreparation = setModel.indexOf('let finalPreparation:');
+ const smallerFinalWindow = setModel.indexOf('finalPiWindow < verifiedCurrentWindow!');
+ const preflightPreparation = setModel.indexOf(
+ 'preparation = await contextOverflowRolloverHolder.prepareModelWindowSwitch(',
+ );
+
+ const piPreflightGuard = setModel.lastIndexOf(
+ "runtimeAgentKind !== 'pi'",
+ preflightPreparation,
+ );
+ expect(piPreflightGuard).toBeGreaterThan(-1);
+ expect(preflightPreparation - piPreflightGuard).toBeLessThan(700);
+ expect(closeRecovery).toBeGreaterThan(-1);
+ expect(closeRecovery).toBeLessThan(finalWindow);
+ expect(finalWindow).toBeGreaterThan(apply);
+ expect(finalWindow).toBeLessThan(runtimeCommit);
+ expect(setModel.match(/await closeRejectedPiRuntime\(/g)).toHaveLength(5);
+ expect(finalWindowEnd).toBeGreaterThan(finalWindow);
+ expect(setModel.slice(finalWindow, finalWindowEnd)).not.toContain(
+ 'await withRehydrateCloseSuppressed',
+ );
+ expect(setModel).toContain('restoreControlStores,');
+ expect(setModel).toContain('failed to close Pi after rejected final-window selection');
+ expect(setModel).toContain('assertRuntimeClosed: () => {');
+ expect(setModel).toContain('if (maker.getSession(sessionId)) {');
+ expect(setModel).toContain(
+ 'rejected Pi runtime could not be closed; runtime selection was not changed',
+ );
+ expect(setModel).toContain('recheckTargetPressure: true');
+ expect(setModel).toContain("finalPreparation === 'confirmation-required'");
+ expect(setModel).toContain('contextWindowConfirmationRequired: finalPiWindow');
+ expect(setModel).toContain('contextTokensForConfirmation: finalPressureContextTokens');
+ expect(setModel).toContain('finalPressureContextTokens = contextTokens');
+ expect(setModel).toContain('runtimeRouteChanged || confirmedContextWindow !== undefined');
+ expect(setModel).toContain('targetContextWindow = finalPiWindow');
+ expect(setModel).toContain("if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi') {");
+ expect(setModel).toContain("runtimeAgentKind !== 'pi' || !!runtimeStatus.remoteHostId");
+ expect(setModel).not.toContain(
+ "runtimeAgentKind !== 'pi' || isDeviceLinkInvoke() || !!runtimeStatus.remoteHostId",
+ );
+ const finalRemotePressureRejection = setModel.indexOf(
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ finalWindow,
+ );
+ expect(finalRemotePressureRejection).toBeGreaterThan(finalWindow);
+ expect(setModel).toContain('targetContextWindow = confirmedContextWindow ?? targetContextWindow');
+ expect(setModel).toContain('confirmedContextWindow === targetContextWindow');
+ expect(setModel).toContain('confirmedContextWindow === finalPiWindow');
+ expect(finalPreparation).toBeGreaterThan(smallerFinalWindow);
+ expect(setModel).toContain("finalPreparation === 'rebuilt'");
+ expect(setModel).toContain("finalPreparation === 'remote-unsupported'");
+ expect(setModel).toContain(
+ "? 'remote model-window rebuild is unsupported; runtime selection was not changed'",
+ );
+ expect(setModel).toContain('`Pi final-window context preparation failed: ${finalPreparation}`');
+ });
+
+ it('refreshes model-only context snapshots against the retained target provider route', () => {
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const refreshStart = setModel.indexOf(
+ "if (!response.deferred) {\n try {\n const currentAgentKind =",
+ );
+ const refreshEnd = setModel.indexOf('const projectionMeta =', refreshStart);
+ const refresh = setModel.slice(refreshStart, refreshEnd);
+
+ expect(setModel).toContain(
+ "effectiveProviderId === undefined\n ? (previousRuntime.pendingCredentialSwitch?.providerId ?? currentProviderId)",
+ );
+ expect(refresh).toContain('model,\n targetRouteProviderId,');
+ expect(refresh).not.toContain(
+ "typeof effectiveProviderId === 'string' ? effectiveProviderId : null",
+ );
+ expect(refresh).toContain('await recordSessionContextSnapshot(');
+ });
+
it('commits runtime control before best-effort context bookkeeping', () => {
const setModel = handlerBody(
registerSource,
@@ -643,9 +1156,27 @@ describe('session runtime control wiring', () => {
);
expect(setModel.slice(runtimeCommit, contextSnapshot)).toContain('if (!response.deferred) {');
expect(setModel.slice(runtimeCommit, contextSnapshot)).toContain('try {');
+ expect(setModel).toContain("currentAgentKind === 'pi'");
+ expect(setModel).toContain('getUsageSnapshot?.().contextWindow');
+ expect(setModel).toContain(': verifiedWindow;');
expect(setModel).toContain('runtime model context snapshot refresh failed');
});
+ it('cancels deferred selection when final-window pressure would need confirmation', () => {
+ const settle = handlerBody(
+ registerSource,
+ 'const settlePendingSessionRuntimeControl =',
+ 'settlePendingSessionRuntimeControlHolder = settlePendingSessionRuntimeControl;',
+ );
+
+ expect(settle).toContain('if (!pending) return;');
+ expect(settle).toContain('deferred model-window selection requires unsupported confirmation');
+ expect(settle).toContain('cancelPendingSessionRuntimeMutation(sessionId, pending.generation)');
+ expect(settle).toContain('await broadcastSessionRuntimeProjection(sessionId)');
+ expect(settle).not.toContain('markPendingSessionRuntimeConfirmationRequired(');
+ expect(settle).not.toContain('confirmedContextWindow: pending.confirmedContextWindow');
+ });
+
it('composes later partial runtime changes on the accepted pending profile', () => {
expect(registerSource).toContain(
'const routeExplicit = patch.model !== undefined || patch.providerId !== undefined;',
@@ -669,7 +1200,8 @@ describe('session runtime control wiring', () => {
expect(registerSource).toContain('routeExplicit: isPendingSessionRuntimeRouteExplicit(');
expect(setModel).toContain('const result = routeExplicit');
expect(setModel).toContain('acceptSessionRuntimeAxisMutation({');
- expect(setModel).toContain('applyEffort: routeExplicit || internalOptions.effortExplicit === true');
+ expect(setModel).toContain("runtimeAgentKind !== 'pi' &&");
+ expect(setModel).toContain('(routeExplicit || internalOptions.effortExplicit === true)');
expect(setModel).toContain('applyFastMode: routeExplicit || internalOptions.fastExplicit === true');
});
@@ -680,7 +1212,10 @@ describe('session runtime control wiring', () => {
'const recoverRemoteRuntimeAxisPersistence',
);
expect(setModel).toContain("runtimeStatus.orcaRole === 'worker'");
- expect(setModel).toContain('forceSessionRebuild: rebuildLiveOrcaWorker');
- expect(setModel).toContain('if (rebuildLiveOrcaWorker && !response.deferred)');
+ expect(setModel).toContain('forceSessionRebuild:');
+ expect(setModel).toContain('rebuildLiveOrcaWorker ||');
+ expect(setModel).toContain(
+ 'if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred)',
+ );
});
});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 47ede771b5..a3d0cd6e71 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -314,6 +314,17 @@ async function persistRemoteSetting(channel: string, args: unknown[], result: un
// (G2)。与被控端 handler 同语义:args[2]===undefined(老 2 参调用)不动 provider_id;string→写;
// null/''→清除(回落默认路由)。写进 DB 后 mapper 自动带进 sessions:patched → 回流控制端镜像。
if (channel === 'maker:set-model') {
+ // 最终 Pi 窗口首次触发压力时,handler 返回结构化确认请求而非接受选择。
+ // 此时 runtime 已回滚;通用回流也不得抢先把请求参数写进 DB。
+ if (
+ result !== null &&
+ typeof result === 'object' &&
+ !Array.isArray(result) &&
+ ('contextWindowConfirmationRequired' in result ||
+ 'contextTokensForConfirmation' in result)
+ ) {
+ return;
+ }
// 同引擎重选的第二段带 host revision CAS。handler 返回 superseded 表示
// 另一控制端已在两段之间更新过意图:runtime 未应用,DB 也必须同样不落
// 这次请求参数,否则 sessions:patched 会把过期选择反向盖回控制端。
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 0ace3791ee..02e54f331d 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -496,7 +496,7 @@ function contextRebuild(readyDb, args) {
: expectNumber(payload.expectedClearedAt, 'expectedClearedAt');
return readyDb.transaction(() => {
const sessionResult = readyDb.prepare(
- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',
+ 'UPDATE sessions SET sdk_session_id = NULL, context_tokens = 0, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',
).run(updatedAt, sessionId, expectedClearedAt);
if (sessionResult.changes !== 1) {
throw Object.assign(new Error('Session missing or clear-boundary changed: ' + sessionId), {
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 2b9a4c391b..3c71d2760b 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -1897,9 +1897,9 @@ describe('db worker tx handlers', () => {
});
});
- it('context.rebuild appends markers instead of deleting earlier rebuild boundaries', async () => {
+ it.each([false, true])('context.rebuild resets usage and appends markers (inline=%s)', async (useInlineWorker) => {
await withClient(async (client) => {
- await seedSession(client, 's1');
+ await seedSession(client, 's1', { contextTokens: 245_000, contextWindow: 500_000 });
await client.exec(
'UPDATE sessions SET sdk_session_id = ?, list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',
['native-a', 'keep me', 'user', 9, 's1'],
@@ -1940,16 +1940,18 @@ describe('db worker tx handlers', () => {
]);
await expect(
client.queryOne(
- 'SELECT sdk_session_id, updated_at, list_preview, list_message_count FROM sessions WHERE id = ?',
+ 'SELECT sdk_session_id, context_tokens, context_window, updated_at, list_preview, list_message_count FROM sessions WHERE id = ?',
['s1'],
),
).resolves.toEqual({
sdk_session_id: null,
+ context_tokens: 0,
+ context_window: 500_000,
updated_at: 2000,
list_preview: 'keep me',
list_message_count: null,
});
- });
+ }, { useInlineWorker });
});
it('session.agentSwitchFallback missing boundary rolls back sdk id clear', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index 30ce72419b..bd580e33b4 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -32,6 +32,10 @@ const h = vi.hoisted(() => ({
})),
closeSession: vi.fn(async (_sessionId: string) => undefined),
tapWindowBroadcast: vi.fn(),
+ windows: [] as Array<{
+ isDestroyed: ReturnType<typeof vi.fn>;
+ webContents: { send: ReturnType<typeof vi.fn> };
+ }>,
summarizeSession: vi.fn(async () => undefined),
stopAndRemovePiSubagentRuns: vi.fn(async (_root: string) => true),
writePiSubagentDeletedTombstone: vi.fn(async (_agentHome: string, _sessionId: string) => undefined),
@@ -60,7 +64,7 @@ vi.mock('electron', () => ({
h.handlers.set(channel, handler);
}),
},
- BrowserWindow: { getAllWindows: () => [] },
+ BrowserWindow: { getAllWindows: () => h.windows },
// status 写路径(removeHookAttachmentDir / removeTurnChangeSetsForSession)会调
// app.getPath('userData') 并对真实文件系统做 fire-and-forget fs.rm。这里返回每次
// 测试用 mkdtemp 生成的独立目录,避免并发 worktree 共享同一字面量路径互相删 fixture,
@@ -123,6 +127,7 @@ vi.mock('../../../cindy-brain/index.js', () => ({
}));
import {
+ broadcastSessionPatched,
patchSessionMetaInDb,
persistSessionFields,
registerSessionIpc,
@@ -238,6 +243,7 @@ beforeEach(() => {
h.closeSession.mockClear();
h.routeLock.mockImplementation(async (_sessionId, task) => task());
h.handlers.clear();
+ h.windows = [];
h.stopAndRemovePiSubagentRuns.mockClear();
h.stopAndRemovePiSubagentRuns.mockImplementation(async () => true);
h.writePiSubagentDeletedTombstone.mockClear();
@@ -271,6 +277,32 @@ afterEach(async () => {
});
describe('local-db:sessions:update handler wiring', () => {
+ it('isolates device-link and renderer failures while broadcasting a session patch', () => {
+ const failedWindowSend = vi.fn(() => {
+ throw new Error('window closed');
+ });
+ const healthyWindowSend = vi.fn();
+ h.tapWindowBroadcast.mockImplementationOnce(() => {
+ throw new Error('tap unavailable');
+ });
+ h.windows = [
+ { isDestroyed: vi.fn(() => false), webContents: { send: failedWindowSend } },
+ { isDestroyed: vi.fn(() => false), webContents: { send: healthyWindowSend } },
+ ];
+
+ expect(() =>
+ broadcastSessionPatched('s-projection', {
+ contextTokens: 0,
+ contextWindow: 272_000,
+ }),
+ ).not.toThrow();
+ expect(failedWindowSend).toHaveBeenCalledOnce();
+ expect(healthyWindowSend).toHaveBeenCalledWith('local-db:sessions:patched', {
+ sessionId: 's-projection',
+ patch: { contextTokens: 0, contextWindow: 272_000 },
+ });
+ });
+
it('rejects new SSH writable roots because the picker is not on the remote filesystem', async () => {
await expect(invokeCreate({
id: 'ssh-forged',
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 48ad3a7592..6b76a1362d 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -1003,7 +1003,7 @@ export async function commitContextRebuild(
sessionId: string,
handoff: string,
meta: {
- reason: 'context-overflow' | 'pi-prompt-timeout';
+ reason: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout';
sourceUserClientId: string | null;
sourceAgentKind?: 'cc' | 'codex' | 'pi';
sourceModel?: string | null;
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 3c5cd656e6..9b1245ed7c 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -231,15 +231,32 @@ export function broadcastSessionPatched(
if (ownerScope !== undefined && !isOwnerScopeCurrent(ownerScope)) return;
const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;
const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : getSafeOwnerPushStamp();
- if (hasCapturedScope) {
- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
- } else if (ownerStamp === undefined) {
- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });
- } else {
- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
+ try {
+ if (hasCapturedScope) {
+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
+ } else if (ownerStamp === undefined) {
+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });
+ } else {
+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
+ }
+ } catch (error) {
+ log.warn('session patch device-link broadcast failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
}
- for (const w of BrowserWindow.getAllWindows()) {
- if (!w.isDestroyed()) {
+ let windows: ReturnType<typeof BrowserWindow.getAllWindows> = [];
+ try {
+ windows = BrowserWindow.getAllWindows();
+ } catch (error) {
+ log.warn('session patch window enumeration failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ for (const w of windows) {
+ try {
+ if (w.isDestroyed()) continue;
if (hasCapturedScope) {
w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
} else if (ownerStamp === undefined) {
@@ -247,6 +264,11 @@ export function broadcastSessionPatched(
} else {
w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);
}
+ } catch (error) {
+ log.warn('session patch window broadcast failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 7431c58394..b9229e598b 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -230,7 +230,7 @@ function sessionAgentSwitchFallback(db: Database.Database, args: unknown): void
transaction();
}
-/** 同一任务换干净原生会话:清 sdk_session_id + 追加隐藏 context_rebuild,不改可见消息。 */
+/** 同一任务换干净原生会话:清 SDK/旧用量 + 追加隐藏 context_rebuild,不改可见消息。 */
function contextRebuild(db: Database.Database, args: unknown): void {
const payload = asRecord(args, 'context.rebuild args');
const sessionId = expectString(payload.sessionId, 'sessionId');
@@ -246,7 +246,7 @@ function contextRebuild(db: Database.Database, args: unknown): void {
const transaction = db.transaction(() => {
const sessionResult = db
.prepare(
- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',
+ 'UPDATE sessions SET sdk_session_id = NULL, context_tokens = 0, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',
)
.run(updatedAt, sessionId, expectedClearedAt);
if (sessionResult.changes !== 1) {
diff --git a/apps/desktop/src/main/maker-host/__tests__/compaction-settings-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/compaction-settings-store.test.ts
index 5dfff5839d..7c709da9b0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/compaction-settings-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/compaction-settings-store.test.ts
@@ -56,8 +56,11 @@ describe('compaction settings store', () => {
});
it('does not migrate Pi when Claude still follows the default', () => {
- expect(readCompactionState().isCustomized).toBe(false);
- expect(readPiCompactionPct()).toBe(75);
+ expect(readCompactionState()).toMatchObject({
+ isCustomized: false,
+ value: { claudeCodeAutoCompactPct: 90 },
+ });
+ expect(readPiCompactionPct()).toBe(90);
expect(readPiCompactionState().isCustomized).toBe(false);
expect(fs.existsSync(path.join(tempRoot, 'pi-compaction-settings.json'))).toBe(false);
});
@@ -99,9 +102,9 @@ describe('compaction settings store', () => {
writeCompactionPct(80);
__testing.resetStores();
expect(readPiCompactionPct()).toBe(80);
- expect(resetPiCompactionPct()).toBe(75);
+ expect(resetPiCompactionPct()).toBe(90);
__testing.resetStores();
- expect(readPiCompactionPct()).toBe(75);
+ expect(readPiCompactionPct()).toBe(90);
expect(readPiCompactionState().isCustomized).toBe(false);
expect(fs.existsSync(path.join(tempRoot, 'pi-compaction-settings.json'))).toBe(false);
expect(fs.existsSync(path.join(tempRoot, 'pi-compaction-migrated.json'))).toBe(true);
diff --git a/apps/desktop/src/main/maker-host/compaction-settings-store.ts b/apps/desktop/src/main/maker-host/compaction-settings-store.ts
index 4dc3b66ec6..7b6359197e 100644
--- a/apps/desktop/src/main/maker-host/compaction-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/compaction-settings-store.ts
@@ -2,13 +2,13 @@
* compaction-settings-store —— Claude Code 与 Pi 的自动上下文压缩阈值。
*
* 文件:
- * <userData>/compaction-settings.json { "claudeCodeAutoCompactPct": 75 }
- * <userData>/pi-compaction-settings.json { "piAutoCompactPct": 75 }
+ * <userData>/compaction-settings.json { "claudeCodeAutoCompactPct": 90 }
+ * <userData>/pi-compaction-settings.json { "piAutoCompactPct": 90 }
*
* 两个 agent 使用独立 override 文件,恢复其中一个默认值不会覆盖另一个设置;Codex
* 不读这两份设置。
*
- * 默认 75 —— 对齐历史自动压缩默认阈值。范围固定 50–95,写入和读取都 clamp + round。
+ * 默认 90 —— Claude Code 与 Pi 对齐 Codex 的 90% 口径。范围固定 50–95,写入和读取都 clamp + round。
* 同步 R/W —— 文件极小,Electron main 已是 background,不会卡 renderer 主线程。
*/
@@ -27,7 +27,7 @@ const log = desktopMakerLogger.child('compaction-settings-store');
const MIN_PCT = 50;
const MAX_PCT = 95;
-const DEFAULT_PCT = 75;
+const DEFAULT_PCT = 90;
interface CompactionSettings {
claudeCodeAutoCompactPct: number;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index 026472b154..d354be82c5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -775,6 +775,21 @@ describe('buildHandoffText 超限收缩保住首尾', () => {
);
});
+ it('model-window-switch 说明主动换小窗,不谎报已经溢出', () => {
+ const text = buildHandoffText([msg('user', '继续改'), msg('assistant', '好')], {
+ fromLabel: 'Pi',
+ toLabel: 'Pi',
+ sessionId: 'sess-smaller-window',
+ reason: 'model-window-switch',
+ });
+ expect(text).toContain('switching to a model with a smaller context window');
+ expect(text).not.toContain("exceeded the model's context window");
+ expect(text).toContain('[Session context rebuild · internal context]');
+ expect(text.trimEnd().endsWith("== End of rebuild note; the user's new message follows ==")).toBe(
+ true,
+ );
+ });
+
it('单轮 100 条 tool_use 折叠中部,且硬上限/检索段/结束标记全部存活', () => {
const messages: HandoffSourceMessage[] = [msg('user', '执行大量工具')];
for (let i = 0; i < 100; i++) {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
index 614d5ca352..e34056b2c2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -11,6 +11,7 @@ import {
persistedUserContentToWireMessage,
planContextOverflowRollover,
shouldRebuildForContextPressure,
+ shouldRebuildForModelWindowSwitch,
shouldRebuildPiNativeSession,
type OverflowSourceMessage,
} from '../contextOverflowRollover';
@@ -187,6 +188,47 @@ describe('planContextOverflowRollover', () => {
});
});
+describe('shouldRebuildForModelWindowSwitch', () => {
+ it.each([
+ [244_799, 272_000, false],
+ [244_800, 272_000, true],
+ [271_999, 272_000, true],
+ [272_000, 272_000, true],
+ [449_999, 272_000, true],
+ [450_000, 272_000, true],
+ [179_999, 200_000, false],
+ [180_000, 200_000, true],
+ ] as const)(
+ 'assesses 500K → %i at the unified 90%% target boundary (%i tokens)',
+ (contextTokens, targetContextWindow, expected) => {
+ expect(
+ shouldRebuildForModelWindowSwitch({
+ contextTokens,
+ currentContextWindow: 500_000,
+ targetContextWindow,
+ }),
+ ).toBe(expected);
+ },
+ );
+
+ it('does not rebuild for equal or larger target windows', () => {
+ expect(
+ shouldRebuildForModelWindowSwitch({
+ contextTokens: 450_000,
+ currentContextWindow: 500_000,
+ targetContextWindow: 500_000,
+ }),
+ ).toBe(false);
+ expect(
+ shouldRebuildForModelWindowSwitch({
+ contextTokens: 450_000,
+ currentContextWindow: 500_000,
+ targetContextWindow: 1_000_000,
+ }),
+ ).toBe(false);
+ });
+});
+
describe('createContextOverflowRollover', () => {
function makeDeps(source: OverflowSourceMessage[]) {
return {
@@ -225,10 +267,12 @@ describe('createContextOverflowRollover', () => {
contextWindow: number;
needsRollover?: boolean;
};
- } => ({ isTurnRunning: () => false }),
+ } | undefined => ({ isTurnRunning: () => false }),
),
+ rehydrateColdPiRuntimeForWindowVerification: vi.fn(async () => undefined),
closeSession: vi.fn(async () => undefined),
getAutoCompactThresholdPct: undefined as (() => number | undefined) | undefined,
+ resolveVerifiedWindow: vi.fn((): number | null => null),
drainPersistQueue: vi.fn(async () => undefined),
commitRebuild: vi.fn(async () => undefined),
setPendingHandoff: vi.fn(),
@@ -240,6 +284,442 @@ describe('createContextOverflowRollover', () => {
};
}
+ it.each(['cc', 'codex', 'pi'] as const)(
+ 'rebuilds %s native context before a pressured 500K → 272K model switch',
+ async (agentKind) => {
+ const deps = makeDeps([
+ msg('user', '先做 A', 'u1', 1),
+ msg('assistant', '做完 A', 'a1', 2),
+ ]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind,
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: '/tmp/live-session',
+ contextTokens: 244_800,
+ contextWindow: 500_000,
+ model: 'wide-model',
+ providerId: 'xd',
+ });
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ }),
+ ).resolves.toBe('rebuilt');
+
+ expect(deps.closeSession).toHaveBeenCalledWith('s1');
+ expect(deps.closeSession.mock.invocationCallOrder[0]!).toBeLessThan(
+ deps.commitRebuild.mock.invocationCallOrder[0]!,
+ );
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({
+ reason: 'model-window-switch',
+ sourceAgentKind: agentKind,
+ sourceModel: 'wide-model',
+ }),
+ );
+ const commitCalls = deps.commitRebuild.mock.calls as unknown as Array<[string, string]>;
+ const handoff = String(commitCalls[0]?.[1] ?? '');
+ expect(handoff).toContain('switching to a model with a smaller context window');
+ expect(handoff).not.toContain("exceeded the model's context window");
+ expect(deps.setPendingHandoff).toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ },
+ );
+
+ it('prefers the verified live Pi runtime window over a stale directory window', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ contextTokens: 300_000,
+ contextWindow: 200_000,
+ model: 'runtime-wide-model',
+ providerId: 'xd',
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens: 300_000, contextWindow: 1_000_000 }),
+ });
+ deps.resolveVerifiedWindow.mockReturnValue(200_000);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.resolveVerifiedWindow).toHaveBeenCalledWith(
+ 'pi',
+ 'runtime-wide-model',
+ 'xd',
+ );
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({ reason: 'model-window-switch' }),
+ );
+ });
+
+ it.each([244_800, 300_000])(
+ 'requires confirmation at %i tokens before rebuilding pressure revealed by Pi final-window verification',
+ async (contextTokens) => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ contextTokens,
+ contextWindow: 500_000,
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens, contextWindow: 272_000 }),
+ });
+ const rollover = createContextOverflowRollover(deps);
+ const onConfirmationRequired = vi.fn();
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ recheckTargetPressure: true,
+ onConfirmationRequired,
+ }),
+ ).resolves.toBe('confirmation-required');
+ expect(onConfirmationRequired).toHaveBeenCalledWith(contextTokens);
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ recheckTargetPressure: true,
+ confirmedTargetPressure: true,
+ }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({ reason: 'model-window-switch' }),
+ );
+ },
+ );
+
+ it('requires an exact confirmation before rebuilding a 1M Claude task for a 200K subscription route', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'cc',
+ contextTokens: 180_000,
+ contextWindow: 1_000_000,
+ model: 'claude-opus',
+ providerId: 'xd',
+ });
+ deps.resolveVerifiedWindow.mockReturnValue(1_000_000);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 200_000,
+ recheckTargetPressure: true,
+ }),
+ ).resolves.toBe('confirmation-required');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 200_000,
+ recheckTargetPressure: true,
+ confirmedTargetPressure: true,
+ }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.commitRebuild).toHaveBeenCalledTimes(1);
+ const commitCalls = deps.commitRebuild.mock.calls as unknown as Array<[string, string]>;
+ expect(String(commitCalls[0]?.[1] ?? '')).toContain(
+ 'switching to a model with a smaller context window',
+ );
+ expect(deps.setPendingHandoff).toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ });
+
+ it('does not rebuild after Pi final-window verification below the pressure line', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ contextTokens: 200_000,
+ contextWindow: 500_000,
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens: 200_000, contextWindow: 272_000 }),
+ });
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ recheckTargetPressure: true,
+ }),
+ ).resolves.toBe('not-needed');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ });
+
+ it('rehydrates cold Pi before using its runtime-verified window', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ sdkSessionId: '/tmp/cold-pi-session.jsonl',
+ contextTokens: 300_000,
+ contextWindow: 200_000,
+ model: 'runtime-wide-model',
+ providerId: 'xd',
+ });
+ deps.getLiveSession.mockReturnValueOnce(undefined).mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens: 0, contextWindow: 1_000_000 }),
+ });
+ deps.resolveVerifiedWindow.mockReturnValue(200_000);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.rehydrateColdPiRuntimeForWindowVerification).toHaveBeenCalledWith('s1');
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({ reason: 'model-window-switch' }),
+ );
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ });
+
+ it('keeps a provenance-less persisted Pi window fail-closed', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ contextTokens: 300_000,
+ contextWindow: 200_000,
+ model: 'unknown-model',
+ });
+ deps.getLiveSession.mockReturnValue(undefined);
+ deps.resolveVerifiedWindow.mockReturnValue(200_000);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('unknown-context');
+ expect(deps.rehydrateColdPiRuntimeForWindowVerification).toHaveBeenCalledWith('s1');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ });
+
+ it('rebuilds a pressured cold local session before its persisted SDK session can resume', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'cc',
+ sdkSessionId: '/tmp/cold-session.jsonl',
+ contextTokens: 300_000,
+ contextWindow: 500_000,
+ model: 'wide-model',
+ });
+ deps.getLiveSession.mockReturnValue(undefined);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({ reason: 'model-window-switch' }),
+ );
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ });
+
+ it('fails closed for a pressured cold SSH session without closing or rebuilding it', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ remoteHostId: 'remote-1',
+ sdkSessionId: '/tmp/remote-cold-session.jsonl',
+ contextTokens: 300_000,
+ contextWindow: 500_000,
+ model: 'wide-model',
+ });
+ deps.getLiveSession.mockReturnValue(undefined);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('remote-unsupported');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [500_000, 0, 'not-needed'],
+ [600_000, 0, 'not-needed'],
+ [272_000, 244_799, 'not-needed'],
+ [272_000, 244_800, 'remote-unsupported'],
+ ] as const)(
+ 'uses persisted cold SSH Pi facts for target %i at usage %i before deciding remote rebuild support',
+ async (targetContextWindow, contextTokens, expected) => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ agentKind: 'pi',
+ remoteHostId: 'remote-1',
+ sdkSessionId: '/tmp/remote-cold-pi-session.jsonl',
+ contextTokens,
+ contextWindow: 500_000,
+ model: 'wide-model',
+ });
+ deps.getLiveSession.mockReturnValue(undefined);
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: targetContextWindow }),
+ ).resolves.toBe(expected);
+ expect(deps.rehydrateColdPiRuntimeForWindowVerification).not.toHaveBeenCalled();
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ },
+ );
+
+ it('falls back to persisted usage when a lazy live snapshot still reports placeholder zero', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ contextTokens: 300_000,
+ contextWindow: 500_000,
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens: 0, contextWindow: 500_000 }),
+ });
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('rebuilt');
+ expect(deps.closeSession).toHaveBeenCalledWith('s1');
+ expect(deps.commitRebuild).toHaveBeenCalledWith(
+ 's1',
+ expect.any(String),
+ expect.objectContaining({ reason: 'model-window-switch' }),
+ );
+ });
+
+ it('keeps a persisted and live zero as authoritative empty usage', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ contextTokens: 0,
+ contextWindow: 500_000,
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens: 0, contextWindow: 500_000 }),
+ });
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe('not-needed');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [244_799, 'not-needed', false],
+ [244_800, 'rebuilt', true],
+ ] as const)(
+ 'uses authoritative positive live usage %i at the 90%% boundary',
+ async (contextTokens, expected, rebuilt) => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ contextTokens: 300_000,
+ contextWindow: 500_000,
+ });
+ deps.getLiveSession.mockReturnValue({
+ isTurnRunning: () => false,
+ getUsageSnapshot: () => ({ contextTokens, contextWindow: 500_000 }),
+ });
+ const rollover = createContextOverflowRollover(deps);
+
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 }),
+ ).resolves.toBe(expected);
+ expect(deps.closeSession).toHaveBeenCalledTimes(rebuilt ? 1 : 0);
+ expect(deps.commitRebuild).toHaveBeenCalledTimes(rebuilt ? 1 : 0);
+ },
+ );
+
+ it('does not retire the native session below the target pressure line', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ ...(await deps.getSessionRow()),
+ contextTokens: 244_799,
+ contextWindow: 500_000,
+ });
+ const beforeClose = vi.fn();
+ const rollover = createContextOverflowRollover(deps);
+ await expect(
+ rollover.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ beforeClose,
+ }),
+ ).resolves.toBe('not-needed');
+ expect(beforeClose).not.toHaveBeenCalled();
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ });
+
+ it('fails closed without mutating a busy or remote pressured session', async () => {
+ const busyDeps = makeDeps([msg('user', '继续', 'u1')]);
+ busyDeps.getSessionRow.mockResolvedValue({
+ ...(await busyDeps.getSessionRow()),
+ contextTokens: 244_800,
+ contextWindow: 500_000,
+ });
+ busyDeps.getLiveSession.mockReturnValue({ isTurnRunning: () => true });
+ const busy = createContextOverflowRollover(busyDeps);
+ await expect(
+ busy.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ }),
+ ).resolves.toBe('busy');
+ expect(busyDeps.closeSession).not.toHaveBeenCalled();
+
+ const remoteDeps = makeDeps([msg('user', '继续', 'u1')]);
+ remoteDeps.getSessionRow.mockResolvedValue({
+ ...(await remoteDeps.getSessionRow()),
+ remoteHostId: 'remote-1',
+ contextTokens: 244_800,
+ contextWindow: 500_000,
+ });
+ const remote = createContextOverflowRollover(remoteDeps);
+ await expect(
+ remote.prepareModelWindowSwitch('s1', {
+ contextWindow: 272_000,
+ }),
+ ).resolves.toBe('remote-unsupported');
+ expect(remoteDeps.closeSession).not.toHaveBeenCalled();
+ });
+
it('rebuilds once, injects handoff, and wire-replays the same user content', async () => {
const deps = makeDeps([
msg('user', '先做 A', 'u1', 1),
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 85dcca9faa..fb90b6efd7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
@@ -7,6 +7,7 @@ import {
} from '../../maker-host/session-provider-store.js';
import {
applyRuntimeSetModelChange,
+ closeRejectedRuntimeAndRestoreControlStores,
isRemoteModelSwitchRouteChangeError,
type RuntimeSetModelMaker,
} from '../runtimeSetModel.js';
@@ -59,6 +60,61 @@ describe('isRemoteModelSwitchRouteChangeError', () => {
});
});
+describe('closeRejectedRuntimeAndRestoreControlStores', () => {
+ it('restores the old control route and rejects when runtime close leaves the handle alive', async () => {
+ const closeError = new Error('close transport rejected');
+ const retainedRuntimeError = new Error('rejected runtime is still live');
+ const closeRuntime = vi.fn(async () => {
+ throw closeError;
+ });
+ const controlStores = {
+ providerId: 'target-provider',
+ effort: 'max',
+ fastMode: true,
+ };
+ const persistedRoute = {
+ model: 'old-model',
+ providerId: 'old-provider',
+ effort: 'low',
+ fastMode: false,
+ } as const;
+ const restoreControlStores = vi.fn(() => {
+ controlStores.providerId = persistedRoute.providerId;
+ controlStores.effort = persistedRoute.effort;
+ controlStores.fastMode = persistedRoute.fastMode;
+ });
+ const reportCloseError = vi.fn();
+ const assertRuntimeClosed = vi.fn(() => {
+ expect(controlStores).toEqual({
+ providerId: persistedRoute.providerId,
+ effort: persistedRoute.effort,
+ fastMode: persistedRoute.fastMode,
+ });
+ throw retainedRuntimeError;
+ });
+
+ await expect(
+ closeRejectedRuntimeAndRestoreControlStores({
+ closeRuntime,
+ restoreControlStores,
+ reportCloseError,
+ assertRuntimeClosed,
+ }),
+ ).rejects.toBe(retainedRuntimeError);
+
+ expect(closeRuntime).toHaveBeenCalledOnce();
+ expect(reportCloseError).toHaveBeenCalledWith(closeError);
+ expect(restoreControlStores).toHaveBeenCalledOnce();
+ expect(assertRuntimeClosed).toHaveBeenCalledOnce();
+ expect(controlStores).toEqual({
+ providerId: persistedRoute.providerId,
+ effort: persistedRoute.effort,
+ fastMode: persistedRoute.fastMode,
+ });
+ expect(persistedRoute.model).toBe('old-model');
+ });
+});
+
describe('applyRuntimeSetModelChange', () => {
it('rolls back provider route when live setModel rejects', async () => {
const sessionId = rememberSession('runtime-set-model-rollback');
@@ -891,6 +947,41 @@ describe('applyRuntimeSetModelChange', () => {
expect(wakeSessionInputQueue).toHaveBeenCalledOnce();
});
+ it('lets the Pi guard reject an incompatible runtime replacement before route side effects', async () => {
+ const sessionId = rememberSession('runtime-set-model-pi-replacement-guard');
+ setSessionProvider(sessionId, 'openai');
+ const closeSession = vi.fn(async () => {});
+ const clearPendingCredentialSwitch = vi.fn();
+ const wakeSessionInputQueue = vi.fn();
+ const maker: RuntimeSetModelMaker = {
+ getSession: () => ({
+ agentKind: 'pi',
+ remoteHostId: null,
+ model: 'chatgpt/gpt-5.5',
+ setModel: vi.fn(async () => {}),
+ }),
+ listActiveSessions: () => [
+ { id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
+ ],
+ closeSession,
+ };
+
+ await expect(applyRuntimeSetModelChange({
+ maker,
+ sessionId,
+ model: 'gpt-5.5',
+ providerId: 'xd',
+ assertSessionCloseSupported: () => { throw new Error('replacement unsupported'); },
+ clearPendingCredentialSwitch,
+ wakeSessionInputQueue,
+ })).rejects.toThrow('replacement unsupported');
+
+ expect(closeSession).not.toHaveBeenCalled();
+ expect(clearPendingCredentialSwitch).not.toHaveBeenCalled();
+ expect(wakeSessionInputQueue).not.toHaveBeenCalled();
+ expect(getSessionProvider(sessionId)).toBe('openai');
+ });
+
it.each([
{ fromProvider: 'xai', fromModel: 'grok-4.6', toProvider: 'openai', toModel: 'gpt-5.6-sol' },
{ fromProvider: 'openai', fromModel: 'gpt-5.6-sol', toProvider: 'xai', toModel: 'grok-4.6' },
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index dd84eb76b2..497dbaa98c 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -53,9 +53,15 @@ export interface BuildHandoffOptions {
/**
* 交接触发原因。message-deletion 表示同一引擎因本地消息被删除而重建原生
* 上下文;context-overflow 表示同一引擎因窗口超限而换干净原生会话;
- * pi-prompt-timeout 表示原生会话对 prompt 无响应后用户重试换窗。
+ * model-window-switch 表示切到更小模型前主动换窗;pi-prompt-timeout 表示原生会话
+ * 对 prompt 无响应后用户重试换窗。
*/
- reason?: 'agent-switch' | 'message-deletion' | 'context-overflow' | 'pi-prompt-timeout';
+ reason?:
+ | 'agent-switch'
+ | 'message-deletion'
+ | 'context-overflow'
+ | 'model-window-switch'
+ | 'pi-prompt-timeout';
}
/** 最近多少个用户轮次进入逐字区(其余进单行提要区)。 */
@@ -414,6 +420,7 @@ const FORK_TERMINATOR = "== End of fork note; the user's new message follows =="
function handoffTerminator(opts: BuildHandoffOptions): string {
return opts.reason === 'message-deletion' ||
opts.reason === 'context-overflow' ||
+ opts.reason === 'model-window-switch' ||
opts.reason === 'pi-prompt-timeout'
? REBUILD_TERMINATOR
: HANDOFF_TERMINATOR;
@@ -500,6 +507,7 @@ function assembleHandoffText(
if (
opts.reason === 'message-deletion' ||
opts.reason === 'context-overflow' ||
+ opts.reason === 'model-window-switch' ||
opts.reason === 'pi-prompt-timeout'
) {
const rebuildCause =
@@ -507,6 +515,10 @@ function assembleHandoffText(
? `The previous native agent session exceeded the model's context window, so Cindy started a fresh native session in the same task. ` +
`Below is the valid conversation history before the overflowing turn; treat only these records as the prior conversation, ` +
`and do not try to recover, cite, or infer messages that are not listed. `
+ : opts.reason === 'model-window-switch'
+ ? `The task is switching to a model with a smaller context window, so Cindy started a fresh native session before applying that model. ` +
+ `Below is the valid conversation history carried into the smaller window; treat only these records as the prior conversation, ` +
+ `and use the history retrieval tools when an earlier detail is needed. `
: opts.reason === 'pi-prompt-timeout'
? `The previous native agent session stopped responding to prompts, so Cindy started a fresh native session in the same task. ` +
`Below is the valid conversation history before the unresponsive turn; treat only these records as the prior conversation, ` +
diff --git a/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts b/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts
index c0be814aaa..0af575a8ee 100644
--- a/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts
+++ b/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts
@@ -13,8 +13,8 @@
* 交接正文本来就不带 tool_result。纯文本把字节顶破时 token 一定早已破。
* 混合型大尾巴(可剥图不足一半)有意不救,等证据再动比例阈值,不加新档。
*
- * 切模型预检的数学仍在 assessModelSwitchContext。确认切小窗后,动作端
- * 应以 tokens='violated' 调用本决定走 rebuild,不再走独立 handoff(本版尚未并入)。
+ * 切模型预检的数学仍在 assessModelSwitchContext。确认切小窗后,main 的统一
+ * set-model 事务在目标压力线先走 context_rebuild,再落目标 route;不另造 handoff。
*/
export type CompressionBudgetState = 'ok' | 'violated' | 'unknown';
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 98d508fc76..6d39708d66 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -15,6 +15,11 @@ import {
readAgentInputReferences,
} from '@cindy/maker-shared/agent-input-projection';
+import {
+ assessModelSwitchContext,
+ MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ shouldHandoffAfterContextAssessment,
+} from '../../shared/modelSwitchAssessment.js';
import { afterStripAttempt, decideCindyCompression } from './cindyContextCompression.js';
import { buildHandoffText, extractPlainText, type HandoffSourceMessage } from './agentHandoff.js';
@@ -329,13 +334,14 @@ export interface ContextOverflowRolloverDeps {
isTurnRunning(): boolean;
getUsageSnapshot?(): { contextTokens: number; contextWindow: number; needsRollover?: boolean };
} | null | undefined;
+ rehydrateColdPiRuntimeForWindowVerification?(sessionId: string): Promise<void>;
closeSession(sessionId: string): Promise<void>;
drainPersistQueue(): Promise<void>;
commitRebuild(
sessionId: string,
handoff: string,
meta: {
- reason: 'context-overflow' | 'pi-prompt-timeout';
+ reason: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout';
sourceUserClientId: string | null;
sourceAgentKind?: 'cc' | 'codex' | 'pi';
sourceModel?: string | null;
@@ -361,10 +367,53 @@ export interface ContextOverflowRolloverDeps {
export type OverflowClaimResult = 'claimed' | 'in-flight' | 'idle';
+export type ModelWindowSwitchPreparationResult =
+ | 'not-needed'
+ | 'confirmation-required'
+ | 'rebuilt'
+ | 'busy'
+ | 'remote-unsupported'
+ | 'unknown-context'
+ | 'in-flight';
+
+export function shouldRebuildForModelWindowSwitch(input: {
+ contextTokens: number;
+ currentContextWindow: number;
+ targetContextWindow: number;
+}): boolean {
+ if (
+ !Number.isFinite(input.currentContextWindow) ||
+ input.currentContextWindow <= 0 ||
+ !Number.isFinite(input.targetContextWindow) ||
+ input.targetContextWindow <= 0 ||
+ input.targetContextWindow >= input.currentContextWindow
+ ) {
+ return false;
+ }
+ return shouldHandoffAfterContextAssessment(
+ assessModelSwitchContext({
+ contextTokens: input.contextTokens,
+ targetContextWindow: input.targetContextWindow,
+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ }),
+ );
+}
+
export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps): {
claim(sessionId: string): OverflowClaimResult;
tryRecover(sessionId: string, errorData: unknown): Promise<boolean>;
prepareUnhealthySession(sessionId: string): Promise<boolean>;
+ prepareModelWindowSwitch(
+ sessionId: string,
+ target: {
+ contextWindow: number;
+ recheckTargetPressure?: boolean;
+ confirmedTargetPressure?: boolean;
+ onConfirmationRequired?: (contextTokens: number) => void;
+ assertCanCommit?: () => void;
+ beforeClose?: () => void;
+ },
+ ): Promise<ModelWindowSwitchPreparationResult>;
} {
const inFlight = new Set<string>();
@@ -498,6 +547,163 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
});
};
+ const runPrepareModelWindowSwitch = async (
+ sessionId: string,
+ target: {
+ contextWindow: number;
+ recheckTargetPressure?: boolean;
+ confirmedTargetPressure?: boolean;
+ onConfirmationRequired?: (contextTokens: number) => void;
+ assertCanCommit?: () => void;
+ beforeClose?: () => void;
+ },
+ ): Promise<ModelWindowSwitchPreparationResult> => {
+ await deps.drainPersistQueue();
+ const sessionRow = await deps.getSessionRow(sessionId);
+ if (!sessionRow || sessionRow.status === 'deleted' || !sessionRow.sdkSessionId) {
+ return 'not-needed';
+ }
+ const persistedContextTokens =
+ typeof sessionRow.contextTokens === 'number' &&
+ Number.isFinite(sessionRow.contextTokens) &&
+ sessionRow.contextTokens >= 0
+ ? sessionRow.contextTokens
+ : 0;
+ let live = deps.getLiveSession(sessionId);
+ let rehydratedColdPi = false;
+ if (sessionRow.agentKind === 'pi' && !live) {
+ if (sessionRow.remoteHostId) {
+ // A cold SSH runtime cannot be rehydrated locally. Persisted usage is still
+ // sufficient to allow an empty/low-pressure switch or reject a required rebuild.
+ const requiresRemoteRebuild = shouldHandoffAfterContextAssessment(
+ assessModelSwitchContext({
+ contextTokens: persistedContextTokens,
+ targetContextWindow: target.contextWindow,
+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ }),
+ );
+ return requiresRemoteRebuild ? 'remote-unsupported' : 'not-needed';
+ }
+ if (!deps.rehydrateColdPiRuntimeForWindowVerification) return 'unknown-context';
+ try {
+ await deps.rehydrateColdPiRuntimeForWindowVerification(sessionId);
+ } catch (error) {
+ deps.log.warn('cold Pi runtime window verification failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return 'unknown-context';
+ }
+ live = deps.getLiveSession(sessionId);
+ rehydratedColdPi = true;
+ }
+ const liveUsage = live?.getUsageSnapshot?.();
+ if (
+ rehydratedColdPi &&
+ (!liveUsage || !Number.isFinite(liveUsage.contextWindow) || liveUsage.contextWindow <= 0)
+ ) {
+ return 'unknown-context';
+ }
+ const liveContextTokens =
+ liveUsage && Number.isFinite(liveUsage.contextTokens) && liveUsage.contextTokens >= 0
+ ? liveUsage.contextTokens
+ : null;
+ // A freshly/lazily attached runtime reports the placeholder 0 before any usage.
+ // Only persisted 0 confirms that zero is authoritative; a positive live value is authoritative itself.
+ const contextTokens =
+ liveContextTokens !== null && (liveContextTokens > 0 || persistedContextTokens === 0)
+ ? liveContextTokens
+ : persistedContextTokens;
+ const reportedCurrentWindow =
+ liveUsage && Number.isFinite(liveUsage.contextWindow) && liveUsage.contextWindow > 0
+ ? liveUsage.contextWindow
+ : (sessionRow.contextWindow ?? 0);
+ const verifiedCurrentWindow = lookupVerifiedContextWindow(
+ deps.resolveVerifiedWindow,
+ sessionRow.model,
+ sessionRow.providerId,
+ sessionRow.agentKind,
+ );
+ // Cold Pi rows may contain either a catalog value or a runtime-verified value in
+ // the same legacy column. Rehydration above makes get_state the cold-path source.
+ const piRuntimeWindow =
+ liveUsage && Number.isFinite(liveUsage.contextWindow) && liveUsage.contextWindow > 0
+ ? liveUsage.contextWindow
+ : (sessionRow.contextWindow ?? 0);
+ const currentContextWindow =
+ sessionRow.agentKind === 'pi'
+ ? piRuntimeWindow
+ : effectiveContextWindow(
+ sessionRow.model,
+ reportedCurrentWindow,
+ verifiedCurrentWindow,
+ );
+ if (contextTokens > 0 && currentContextWindow <= 0) return 'unknown-context';
+ const targetPressureRequiresRebuild =
+ target.recheckTargetPressure === true &&
+ shouldHandoffAfterContextAssessment(
+ assessModelSwitchContext({
+ contextTokens,
+ targetContextWindow: target.contextWindow,
+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ }),
+ );
+ if (
+ !targetPressureRequiresRebuild &&
+ !shouldRebuildForModelWindowSwitch({
+ contextTokens,
+ currentContextWindow,
+ targetContextWindow: target.contextWindow,
+ })
+ ) {
+ return 'not-needed';
+ }
+ if (sessionRow.remoteHostId) return 'remote-unsupported';
+ if (live?.isTurnRunning()) return 'busy';
+ if (targetPressureRequiresRebuild && target.confirmedTargetPressure !== true) {
+ target.onConfirmationRequired?.(contextTokens);
+ return 'confirmation-required';
+ }
+
+ const source = (await deps.listMessages(sessionId)).filter(
+ (message) => message.role !== 'error',
+ );
+ const latestUser =
+ [...source].reverse().find((message) => message.role === 'user' && !isSyntheticUser(message)) ??
+ (await deps.findLatestUser?.(sessionId)) ??
+ null;
+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);
+ target.assertCanCommit?.();
+ target.beforeClose?.();
+ if (live) await deps.closeSession(sessionId);
+ target.assertCanCommit?.();
+ const label = engineLabelForOverflow(sessionRow.agentKind);
+ const handoff = buildHandoffText(source, {
+ fromLabel: label,
+ toLabel: label,
+ sessionId,
+ reason: 'model-window-switch',
+ });
+ await deps.commitRebuild(sessionId, handoff, {
+ reason: 'model-window-switch',
+ sourceUserClientId: latestUser?.clientId ?? null,
+ sourceAgentKind: normalizeOverflowDbAgentKind(sessionRow.agentKind),
+ sourceModel: sessionRow.model ?? null,
+ sourceProviderId: sessionRow.providerId ?? null,
+ expectedClearedAt: sessionRow.clearedAt,
+ });
+ deps.setPendingHandoff(sessionId, handoff, handoffGeneration);
+ deps.onRebuilt?.(sessionId);
+ deps.log.info('model window shrink rebuilt native context before runtime switch', {
+ sessionId,
+ agentKind: sessionRow.agentKind,
+ contextTokens,
+ currentContextWindow,
+ targetContextWindow: target.contextWindow,
+ });
+ return 'rebuilt';
+ };
+
const runPrepare = async (sessionId: string): Promise<boolean> => {
await deps.drainPersistQueue();
const sessionRow = await deps.getSessionRow(sessionId);
@@ -660,5 +866,24 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
inFlight.delete(sessionId);
}
},
+
+ async prepareModelWindowSwitch(sessionId, target) {
+ if (inFlight.has(sessionId)) return 'in-flight';
+ inFlight.add(sessionId);
+ try {
+ return await deps.withCloseSuppressed(sessionId, () =>
+ runPrepareModelWindowSwitch(sessionId, target),
+ );
+ } catch (error) {
+ deps.log.warn('model window switch preparation failed', {
+ sessionId,
+ targetContextWindow: target.contextWindow,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ } finally {
+ inFlight.delete(sessionId);
+ }
+ },
};
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 598f6b9a06..7b2491c521 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -84,6 +84,10 @@ import {
import { getManagedWorktreeBasePath } from '../../shared/managedWorktreePaths.js';
import { normalizeWorkingDirForProjectSettings } from '../../shared/workingDir.js';
import { buildTurnUsageDetails } from '../../shared/turnUsageDetails.js';
+import {
+ assessModelSwitchContext,
+ MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+} from '../../shared/modelSwitchAssessment.js';
import type { DesktopCommandContext } from '../commands/index.js';
import { getDesktopCommandRegistry } from '../commands/index.js';
import {
@@ -624,10 +628,7 @@ import { runAcceptedCallback } from './acceptedCallbackRunner.js';
import { createElectronIpcHandlerRegistry } from './electronIpcRegistry.js';
import { refreshCodexMcpEnvironment } from './codexMcpRefresh.js';
import { broadcastSchedulerChanged } from './schedule.js';
-import {
- excludeDirectoryGrantConflicts,
- validateExtraDirs,
-} from './extraDirsValidator.js';
+import { excludeDirectoryGrantConflicts, validateExtraDirs } from './extraDirsValidator.js';
import {
applyRemoteDirectoryGrantUpdate,
isPersistedDirectoryGrantSubset,
@@ -776,6 +777,7 @@ import {
isPiPromptRpcTimeoutError,
lookupVerifiedContextWindow,
persistedUserContentToWireMessage,
+ type ModelWindowSwitchPreparationResult,
shouldRebuildPiNativeSession,
} from './contextOverflowRollover.js';
import {
@@ -917,6 +919,7 @@ import {
} from '../maker-host/codex-credential-switch.js';
import {
applyRuntimeSetModelChange,
+ closeRejectedRuntimeAndRestoreControlStores,
isRemoteModelSwitchRouteChangeError,
} from './runtimeSetModel.js';
import {
@@ -4547,8 +4550,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
!session.remoteHostId &&
event.type === 'error' &&
isTerminalTurnErrorEvent(event) &&
- (isContextOverflowErrorData(event.data) ||
- isOversizedHistoryErrorData(event.data));
+ (isContextOverflowErrorData(event.data) || isOversizedHistoryErrorData(event.data));
if (
event.type === 'error' &&
isTerminalTurnErrorEvent(event) &&
@@ -4758,12 +4760,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
});
handleAgentIslandEventAfterBroadcast(session, stashed.event);
}
- onTurnErrorEvent(
- session.id,
- overflowErrorPayload,
- eventAgentMeta,
- overflowPersistId,
- );
+ onTurnErrorEvent(session.id, overflowErrorPayload, eventAgentMeta, overflowPersistId);
};
void contextOverflowRolloverHolder
?.tryRecover(session.id, overflowErrorData)
@@ -4910,12 +4907,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// render 换自绘卡)。同步守卫 hasEnabledGhostAssistantHook 保证无此类意识时
// 不 schedule —— 与今天行为逐字节一致,零额外开销(规则 10 不碰热路径)。
if (
- event.type === 'done'
- && !isContinuationBoundary
- && !isPairedFailedTurnDone
- && !isTerminalTurnErrorEvent(event)
- && isSuccessfulAssistantReplyDoneData(event.data)
- && turnAssistantPersistId
+ event.type === 'done' &&
+ !isContinuationBoundary &&
+ !isPairedFailedTurnDone &&
+ !isTerminalTurnErrorEvent(event) &&
+ isSuccessfulAssistantReplyDoneData(event.data) &&
+ turnAssistantPersistId
) {
const doneResult = (event.data as { result?: unknown } | null)?.result;
const replyText = typeof doneResult === 'string' ? doneResult : '';
@@ -4971,6 +4968,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
}
}
if (pendingContextSnapshot) {
+ const piRuntimeWindow =
+ session.agentKind === 'pi' &&
+ Number.isFinite(pendingContextSnapshot.contextWindow) &&
+ pendingContextSnapshot.contextWindow > 0
+ ? pendingContextSnapshot.contextWindow
+ : null;
const verifiedWindow = lookupVerifiedContextWindow(
(agentKind, modelId, providerId) =>
resolveVerifiedContextWindow(
@@ -4986,7 +4989,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
recordSessionContextSnapshot(
session.id,
pendingContextSnapshot.contextTokens,
- verifiedWindow ?? pendingContextSnapshot.contextWindow,
+ piRuntimeWindow ?? verifiedWindow ?? pendingContextSnapshot.contextWindow,
);
}
if (pendingCodexAccountUsageSnapshot) {
@@ -6610,6 +6613,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// host 级 optional 能力;旧 desktop 缺省为 false。两个 agent 查询都带回,
// 手机读取当前 agent 快照即可决定是否展示切换入口。
supportsSessionAgentSwitch: true,
+ // host 在 SET_MODEL 的 session lock 内执行 90% 模型窗口保护;旧 host 缺省 false,
+ // Mobile 据此对已知受压缩窗降级为 fail closed。
+ supportsModelWindowSwitchGuard: true,
// v2 因果能力:同引擎 no-op 返回 revision,后续 SET_MODEL 在 session 锁内 CAS。
// 新 desktop 控制端据此与只有基础切换能力的旧 host 做安全兼容门控。
supportsSessionAgentSwitchCas: true,
@@ -8997,6 +9003,51 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
+ async function rehydrateColdPiRuntimeForWindowVerification(sessionId: string): Promise<void> {
+ if (maker.getSession(sessionId)) return;
+ const [row] = await getDbClient()
+ .drizzle.select()
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (
+ !row ||
+ row.agentKind !== 'pi' ||
+ row.remoteHostId ||
+ !row.sdkSessionId ||
+ !row.workingDir
+ ) {
+ throw new Error(`session ${sessionId} cannot rehydrate a local Pi runtime for verification`);
+ }
+ const createOpts = buildCreateOptsWithStderr({
+ id: sessionId,
+ agentKind: 'pi',
+ workingDir: row.workingDir,
+ model: row.model,
+ providerId: row.providerId,
+ effort: (row.effort ?? undefined) as CreateOpts['effort'],
+ fastMode: !!row.fastMode,
+ permissionMode: (row.permissionMode ?? 'ask') as CreateOpts['permissionMode'],
+ planMode: !!row.planModeEnabled,
+ title: row.title ?? undefined,
+ resumeSessionId: row.sdkSessionId,
+ orcaRole: row.orcaRole ?? undefined,
+ });
+ const workDirExists = await checkWorkDirExists(
+ sessionId,
+ createOpts.workingDir,
+ createOpts.agentKind,
+ createOpts.remoteHostId,
+ );
+ if (!workDirExists) {
+ throw new Error(`working directory is missing for session ${sessionId}`);
+ }
+ await synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);
+ const extraDirs = await readSessionExtraDirsFromDb(sessionId);
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ await bootstrapSession(createOpts);
+ }
+
const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {
withSessionLock: withSendToSessionLock,
// 停用轴边界裁决:目标路由被停用 → 抛错;隐式默认落点被停用 → 返回启用替代来源。
@@ -9728,6 +9779,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await contextOverflowRolloverHolder?.prepareUnhealthySession(targetSessionId);
let live = maker.getSession(targetSessionId);
+ if (live?.agentKind === 'pi' && live.getStatus() === 'error') {
+ // A failed Pi close deliberately remains in Maker.activeSessions so the
+ // next create can retry teardown without spawning a second process.
+ // Never send through that unusable handle: fall through to lazy resume,
+ // whose Maker.createSession call performs the existing bounded close retry.
+ live = undefined;
+ }
if (live) {
if (live.isTurnRunning?.()) {
await enqueueSendToSessionMessage({
@@ -11267,9 +11325,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
superseded: boolean;
generation?: number;
effectiveProviderId?: string | null;
+ contextWindowConfirmationRequired?: number;
+ contextTokensForConfirmation?: number;
}> = async () => {
throw new Error('session runtime selection is not ready');
};
+ const runtimeSelectionRequiresModelWindowConfirmation = (result: {
+ contextWindowConfirmationRequired?: number;
+ contextTokensForConfirmation?: number;
+ }): boolean =>
+ result.contextWindowConfirmationRequired !== undefined ||
+ result.contextTokensForConfirmation !== undefined;
const settlingSessionRuntimeControls = new Set<string>();
const settlePendingSessionRuntimeControl = (sessionId: string, reason: string): void => {
if (settlingSessionRuntimeControls.has(sessionId)) return;
@@ -11295,6 +11361,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
routeExplicit: isPendingSessionRuntimeRouteExplicit(sessionId, pending.generation),
},
);
+ if (runtimeSelectionRequiresModelWindowConfirmation(result)) {
+ throw new Error('deferred model-window selection requires unsupported confirmation');
+ }
log.info('pending session runtime settled', {
sessionId,
reason,
@@ -11317,6 +11386,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
broadcastError instanceof Error ? broadcastError.message : String(broadcastError),
});
});
+ const failureMessage =
+ error instanceof Error && error.message.includes('unsupported')
+ ? 'Deferred model switch was cancelled because safe context rebuild is unsupported. The previous model remains active.'
+ : 'Deferred model switch was cancelled because it could not be applied safely. The previous model remains active.';
+ const failureReason = 'runtime-selection-cancelled';
+ onTurnErrorEvent(sessionId, { message: failureMessage, reason: failureReason }, null);
+ const dbAgentKind = getSessionDbAgentKind(sessionId);
+ const agentSource = dbAgentKind ? dbToMakerAgentKind(dbAgentKind) : undefined;
+ broadcastToAllWindows(MAKER_PUSH.EVENT, {
+ sessionId,
+ event: {
+ type: 'error',
+ data: { message: failureMessage, reason: failureReason, isTerminal: true },
+ ...(agentSource ? { source: agentSource } : {}),
+ } satisfies AgentEvent,
+ });
}
} finally {
settlingSessionRuntimeControls.delete(sessionId);
@@ -11429,6 +11514,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!readSessionRuntimeFallbackSettings().enabled || episodeAttempt < 2) return null;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
let runtimeSession: Session | null = null;
+ let blockAutoResumeForModelWindowConfirmation = false;
try {
const profiles = await readSessionRuntimeProfiles(sessionId);
if (!profiles) return null;
@@ -11534,6 +11620,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throw retryError;
}
}
+ if (runtimeSelectionRequiresModelWindowConfirmation(result)) {
+ blockAutoResumeForModelWindowConfirmation = true;
+ throw new Error(
+ 'automatic model-window confirmation is unsupported; runtime selection was not changed',
+ );
+ }
log.info('automatic session runtime fallback evaluated', {
sessionId,
episodeAttempt,
@@ -11552,6 +11644,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
attemptToken,
error: error instanceof Error ? error.message : String(error),
});
+ if (blockAutoResumeForModelWindowConfirmation) {
+ // Ordinary fallback failures may retry the unchanged runtime. A required
+ // confirmation must instead abort auto-resume before it sends again.
+ if (runtimeSession) pendingSessionRuntimeFallbackRebuilds.delete(runtimeSession);
+ throw error;
+ }
return runtimeSession;
}
};
@@ -11632,6 +11730,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
message: `session runtime generation changed; read it again before retrying`,
};
}
+ if (runtimeSelectionRequiresModelWindowConfirmation(response)) {
+ return {
+ ok: false,
+ errorCode: 'ROUTE_UNAVAILABLE',
+ message: 'model-window confirmation is required; runtime selection was not changed',
+ };
+ }
const control = getSessionRuntimeControlSnapshot(targetSessionId);
return {
ok: true,
@@ -12330,32 +12435,87 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
findLatestUser: findLatestUserMessageForRebuild,
findLatestRebuildMeta: findLatestContextRebuildMeta,
getLiveSession: (sessionId) => maker.getSession(sessionId),
+ rehydrateColdPiRuntimeForWindowVerification,
closeSession: (sessionId) => maker.closeSession(sessionId),
drainPersistQueue,
commitRebuild: async (sessionId, handoff, meta) => {
- const { updatedAt } = await commitContextRebuild(sessionId, handoff, meta);
- const [sessionKindRow] = await getDbClient()
- .drizzle.select({ agentKind: sessions.agentKind })
+ // Read projection metadata before the transaction: after a successful
+ // context.rebuild there must be no fallible step before the zero-usage push.
+ const ownerScope = captureDataOwnerBroadcastScope();
+ const dbSnapshot = getCurrentDbClientSnapshot();
+ if (!dbSnapshot) throw new Error('context rebuild requires an active Profile database');
+ const [sessionKindRow] = await dbSnapshot.client.drizzle
+ .select({
+ agentKind: sessions.agentKind,
+ contextWindow: sessions.contextWindow,
+ })
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
+ if (
+ !isDataOwnerBroadcastScopeCurrent(ownerScope) ||
+ getCurrentDbClientSnapshot()?.clientEpoch !== dbSnapshot.clientEpoch
+ ) {
+ throw new Error('context rebuild owner changed before commit');
+ }
+ const { updatedAt } = await commitContextRebuild(sessionId, handoff, meta);
+ if (
+ !isDataOwnerBroadcastScopeCurrent(ownerScope) ||
+ getCurrentDbClientSnapshot()?.clientEpoch !== dbSnapshot.clientEpoch
+ ) {
+ throw new Error('context rebuild owner changed after commit');
+ }
+ const projectionContextWindow =
+ typeof sessionKindRow?.contextWindow === 'number' &&
+ Number.isFinite(sessionKindRow.contextWindow) &&
+ sessionKindRow.contextWindow > 0
+ ? sessionKindRow.contextWindow
+ : undefined;
const cardAgentKind =
sessionKindRow?.agentKind === 'codex'
? 'codex'
: sessionKindRow?.agentKind === 'pi'
? 'pi'
: 'cc';
- broadcastSessionPatched(sessionId, {
- sdkSessionId: null,
- updatedAt: new Date(updatedAt).toISOString(),
- });
- await createDbMessage(sessionId, {
- clientId: `context-rebuild-card:${createId()}`,
- role: 'assistant',
- content: '',
- agentKind: cardAgentKind,
- agentMeta: { contextRebuild: { reason: meta.reason, handoff } } as AgentMeta,
- });
+ broadcastSessionPatched(
+ sessionId,
+ {
+ sdkSessionId: null,
+ contextTokens: 0,
+ ...(projectionContextWindow === undefined
+ ? {}
+ : { contextWindow: projectionContextWindow }),
+ updatedAt: new Date(updatedAt).toISOString(),
+ },
+ ownerScope,
+ );
+ try {
+ await createDbMessage(
+ sessionId,
+ {
+ clientId: `context-rebuild-card:${createId()}`,
+ role: 'assistant',
+ content: '',
+ agentKind: cardAgentKind,
+ agentMeta: { contextRebuild: { reason: meta.reason, handoff } } as AgentMeta,
+ },
+ {
+ broadcastOwnerScope: ownerScope,
+ shouldBroadcast: () =>
+ isDataOwnerBroadcastScopeCurrent(ownerScope) &&
+ getCurrentDbClientSnapshot()?.clientEpoch === dbSnapshot.clientEpoch,
+ },
+ );
+ } catch (error) {
+ // The hidden marker and zero-usage session state are already committed.
+ // A derived visual card must not turn that successful rebuild into a
+ // failed switch or strand control projections on the source route.
+ log.warn('context rebuild card creation failed after commit', {
+ sessionId,
+ reason: meta.reason,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
},
setPendingHandoff: (sessionId, handoff, expectedGeneration) =>
agentHandoffPending.set(sessionId, handoff, expectedGeneration),
@@ -13757,11 +13917,70 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// deferred 接受时已按请求值落盘,不纠正则下一次懒 resume 按停用路由重建
// (PR #744 review 第十、十四轮)。
persistRoute: async (sessionId, route) => {
- const patch: Record<string, unknown> = { providerId: route.providerId };
- if (route.model) patch.model = route.model;
- if (route.effort) patch.effort = route.effort;
- if (route.fastMode !== undefined) patch.fastMode = route.fastMode;
const agentKind = getSessionDbAgentKind(sessionId);
+ const [desiredRow] = await getDbClient()
+ .drizzle.select({
+ model: sessions.model,
+ effort: sessions.effort,
+ fastMode: sessions.fastMode,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const finalModel = route.model ?? desiredRow?.model ?? null;
+ const previousRoute = pendingCredentialSwitchHolder?.get(sessionId)?.previousRoute;
+ const restoringPreviousRoute =
+ !!route.model &&
+ route.model === previousRoute?.model &&
+ route.providerId === previousRoute.providerId;
+ let finalEffort = restoringPreviousRoute && route.effort && isSupportedRuntimeEffort(route.effort)
+ ? route.effort
+ : isSupportedRuntimeEffort(desiredRow?.effort)
+ ? desiredRow.effort
+ : !desiredRow && route.effort && isSupportedRuntimeEffort(route.effort)
+ ? route.effort
+ : null;
+ let finalFastMode = restoringPreviousRoute && route.fastMode !== undefined
+ ? route.fastMode
+ : desiredRow
+ ? desiredRow.fastMode === true
+ : route.fastMode === true;
+ if (agentKind && finalModel) {
+ const runtimeAgentKind = dbToMakerAgentKind(agentKind);
+ const providers = await getDesktopProviderService().listProviders({
+ allowSideEffects: false,
+ catalog: getActiveCatalog(),
+ });
+ const finalProviderId = route.providerId ?? effectiveSourceIdForModel(
+ providers,
+ null,
+ finalModel,
+ runtimeAgentKind,
+ );
+ const finalProvider = providers.find((provider) => provider.id === finalProviderId);
+ const catalogModel = findCatalogModel(finalProvider, finalModel, runtimeAgentKind, {
+ exact: true,
+ });
+ if (catalogModel) {
+ const axes = resolveSessionRuntimeAxes({
+ model: catalogModel,
+ effort: finalEffort,
+ fastMode: finalFastMode,
+ effortExplicit: false,
+ fastExplicit: false,
+ });
+ if (axes.ok) {
+ finalEffort = axes.effort;
+ finalFastMode = axes.fastMode;
+ }
+ }
+ }
+ const patch: Record<string, unknown> = {
+ providerId: route.providerId,
+ effort: finalEffort,
+ fastMode: finalFastMode,
+ };
+ if (route.model) patch.model = route.model;
if (route.model && agentKind) {
const verifiedWindow = lookupVerifiedContextWindow(
(resolvedAgentKind, modelId, pid) =>
@@ -13778,6 +13997,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (verifiedWindow) patch.contextWindow = verifiedWindow;
}
await getDbClient().drizzle.update(sessions).set(patch).where(eq(sessions.id, sessionId));
+ setSessionEffort(sessionId, finalEffort);
+ setSessionFastMode(sessionId, finalFastMode);
broadcastSessionPatched(sessionId, patch);
},
logger: log,
@@ -15217,19 +15438,39 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
throwIpcError('INVALID_PARAMS', 'expectedAgentSwitchRevision must be a non-negative integer');
}
+ const confirmedContextWindow = (selection as { confirmedContextWindow?: unknown } | undefined)
+ ?.confirmedContextWindow;
+ const selectionEffort = (selection as { effort?: unknown } | undefined)?.effort;
if (
selection !== undefined &&
(selection === null ||
typeof selection !== 'object' ||
Array.isArray(selection) ||
- (!isSupportedRuntimeEffort((selection as { effort?: unknown }).effort) &&
+ (!isSupportedRuntimeEffort(selectionEffort) &&
!(
- internalOptions.source !== 'user' && (selection as { effort?: unknown }).effort === null
+ selectionEffort === null &&
+ (internalOptions.source !== 'user' ||
+ isDeviceLinkInvoke() ||
+ confirmedContextWindow !== undefined)
)) ||
typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean')
) {
throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');
}
+ if (
+ confirmedContextWindow !== undefined &&
+ (typeof confirmedContextWindow !== 'number' ||
+ !Number.isSafeInteger(confirmedContextWindow) ||
+ confirmedContextWindow <= 0)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'confirmedContextWindow must be a positive integer');
+ }
+ if (isDeviceLinkInvoke() && confirmedContextWindow !== undefined) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ );
+ }
let atomicSelection = selection as
{ effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
@@ -15271,6 +15512,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: sessions.effort,
fastMode: sessions.fastMode,
workingDir: sessions.workingDir,
+ contextTokens: sessions.contextTokens,
})
.from(sessions)
.where(eq(sessions.id, sessionId))
@@ -15389,6 +15631,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
`model "${model}" is unavailable from provider "${actualProviderId ?? 'default'}"`,
);
}
+ if (
+ internalOptions.source === 'user' &&
+ atomicSelection.effort === null &&
+ catalogModel.efforts.length > 0
+ ) {
+ throwIpcError('INVALID_PARAMS', `effort "null" is unavailable for model "${model}"`);
+ }
const axes = resolveSessionRuntimeAxes({
model: catalogModel,
effort: atomicSelection.effort,
@@ -15423,6 +15672,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const pendingAxisPatch = routeExplicit
? axisPatch
: await resolvePendingRuntimeAxisPatch(sessionId, axisPatch);
+ if (runtimeStatus.remoteHostId && isSessionInTurn(sessionId)) {
+ throwIpcError('PRECONDITION_FAILED', 'busy remote task cannot change runtime selection');
+ }
if (internalOptions.deferWhileRunning && isSessionInTurn(sessionId)) {
const meta = await maker.getSessionMeta(sessionId);
if (!meta) return { deferred: false, superseded: true };
@@ -15479,10 +15731,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
pendingCredentialSwitch: pendingCredentialSwitchHolder?.get(sessionId),
hadLiveSession: maker.getSession(sessionId) !== undefined,
};
- const liveSessionBeforeRouteChange = maker.getSession(sessionId);
+ let liveSessionBeforeRouteChange = maker.getSession(sessionId);
+ let rehydratedColdPiRuntime: typeof liveSessionBeforeRouteChange = undefined;
const targetProviderId =
effectiveProviderId === undefined
- ? currentProviderId
+ ? (previousRuntime.pendingCredentialSwitch?.providerId ?? currentProviderId)
: (normalizeSessionProviderId(effectiveProviderId) ?? null);
const hasPersistedLocalCodexThread =
internalOptions.source === 'user' &&
@@ -15655,6 +15908,283 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
setSessionEffort(sessionId, previousRuntime.effort);
setSessionFastMode(sessionId, previousRuntime.fastMode);
};
+ const closeRejectedPiRuntime = (reason: string): Promise<void> =>
+ closeRejectedRuntimeAndRestoreControlStores({
+ closeRuntime: () =>
+ withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId)),
+ restoreControlStores,
+ reportCloseError: (error) => {
+ log.warn('failed to close Pi after rejected final-window selection', {
+ sessionId,
+ reason,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+ assertRuntimeClosed: () => {
+ if (maker.getSession(sessionId)) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'rejected Pi runtime could not be closed; runtime selection was not changed',
+ );
+ }
+ },
+ });
+ const persistedSessionMeta = liveSessionBeforeRouteChange
+ ? null
+ : await maker.getSessionMeta(sessionId);
+ const runtimeAgentKind =
+ liveSessionBeforeRouteChange?.agentKind ??
+ (getSessionDbAgentKind(sessionId)
+ ? dbToMakerAgentKind(getSessionDbAgentKind(sessionId))
+ : persistedSessionMeta?.agentKind);
+ const targetRouteProviderId = targetProviderId;
+ let currentRuntimeModel = liveSessionBeforeRouteChange?.model ?? persistedSessionMeta?.model;
+ let runtimeRouteChanged =
+ currentRuntimeModel !== undefined &&
+ (currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId);
+ if (runtimeAgentKind === 'pi' && runtimeRouteChanged) {
+ if (isSessionInTurn(sessionId)) {
+ throwIpcError('PRECONDITION_FAILED', 'busy Pi task cannot change runtime selection');
+ }
+ if (!liveSessionBeforeRouteChange && runtimeStatus.remoteHostId) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'cold remote Pi runtime cannot verify the target window; runtime selection was not changed',
+ );
+ }
+ if (!liveSessionBeforeRouteChange) {
+ try {
+ await rehydrateColdPiRuntimeForWindowVerification(sessionId);
+ } catch {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Pi current runtime could not be verified; runtime selection was not changed',
+ );
+ }
+ liveSessionBeforeRouteChange = maker.getSession(sessionId);
+ if (!liveSessionBeforeRouteChange) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Pi current runtime could not be verified; runtime selection was not changed',
+ );
+ }
+ rehydratedColdPiRuntime = liveSessionBeforeRouteChange;
+ currentRuntimeModel = liveSessionBeforeRouteChange.model;
+ runtimeRouteChanged =
+ currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId;
+ }
+ }
+ let targetContextWindow: number | undefined;
+ let verifiedCurrentWindow: number | undefined;
+ let modelWindowRebuilt = false;
+ if (runtimeAgentKind && (runtimeRouteChanged || confirmedContextWindow !== undefined)) {
+ const resolveRouteWindow = (_agentKind: string, modelId: string, pid: string | null) =>
+ resolveVerifiedContextWindow(getActiveCatalog(), runtimeAgentKind, pid, modelId);
+ const verifiedTargetWindow = lookupVerifiedContextWindow(
+ resolveRouteWindow,
+ model,
+ targetRouteProviderId,
+ runtimeAgentKind,
+ );
+ const catalogCurrentWindow =
+ lookupVerifiedContextWindow(
+ resolveRouteWindow,
+ currentRuntimeModel,
+ currentProviderId,
+ runtimeAgentKind,
+ ) ?? undefined;
+ const liveCurrentWindow = liveSessionBeforeRouteChange?.getUsageSnapshot?.().contextWindow;
+ // Pi's effective window is a runtime route fact; catalog/persisted values may be larger.
+ verifiedCurrentWindow =
+ runtimeAgentKind === 'pi'
+ ? typeof liveCurrentWindow === 'number' &&
+ Number.isFinite(liveCurrentWindow) &&
+ liveCurrentWindow > 0
+ ? liveCurrentWindow
+ : undefined
+ : catalogCurrentWindow;
+ const targetDoesNotShrink =
+ typeof verifiedCurrentWindow === 'number' &&
+ typeof verifiedTargetWindow === 'number' &&
+ verifiedTargetWindow >= verifiedCurrentWindow;
+ // Materialized/user-provider catalog windows can be display-only fallbacks.
+ // A destructive native-context rebuild may use only a route-verified window.
+ targetContextWindow = verifiedTargetWindow ?? undefined;
+ if (
+ confirmedContextWindow !== undefined &&
+ runtimeAgentKind !== 'pi' &&
+ confirmedContextWindow !== targetContextWindow
+ ) {
+ throwIpcError(
+ isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : 'INVALID_PARAMS',
+ 'confirmedContextWindow does not match the verified target window',
+ );
+ }
+ // A remote Pi confirmation may name the smaller window verified by the
+ // previous final get_state. Re-run the catalog-window preflight first;
+ // only the next final Pi verification may consume that confirmation.
+ if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi') {
+ targetContextWindow = confirmedContextWindow ?? targetContextWindow;
+ }
+ if (
+ (!targetContextWindow || targetContextWindow <= 0) &&
+ (runtimeAgentKind !== 'pi' || !!runtimeStatus.remoteHostId)
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'target model context window is unknown; runtime selection was not changed',
+ );
+ }
+ const persistedContextTokens =
+ typeof runtimeStatus.contextTokens === 'number' &&
+ Number.isFinite(runtimeStatus.contextTokens) &&
+ runtimeStatus.contextTokens >= 0
+ ? runtimeStatus.contextTokens
+ : null;
+ const liveContextTokens = liveSessionBeforeRouteChange?.getUsageSnapshot?.().contextTokens;
+ const verifiedLiveContextTokens =
+ typeof liveContextTokens === 'number' && Number.isFinite(liveContextTokens)
+ ? liveContextTokens
+ : null;
+ const liveUsageIsAuthoritative =
+ verifiedLiveContextTokens !== null &&
+ (verifiedLiveContextTokens > 0 || persistedContextTokens === 0);
+ const contextTokensKnown = liveUsageIsAuthoritative || persistedContextTokens !== null;
+ const contextTokens = liveUsageIsAuthoritative
+ ? verifiedLiveContextTokens
+ : (persistedContextTokens ?? 0);
+ if (!contextTokensKnown || !verifiedCurrentWindow) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'model window switch context is unknown; runtime selection was not changed',
+ );
+ }
+ const remoteTargetAssessment = assessModelSwitchContext({
+ contextTokens,
+ targetContextWindow: verifiedTargetWindow ?? undefined,
+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ });
+ const remoteRouteCannotRebuild = isDeviceLinkInvoke() || !!runtimeStatus.remoteHostId;
+ const targetRequiresRebuild =
+ !targetDoesNotShrink &&
+ (remoteTargetAssessment.level === 'danger' || remoteTargetAssessment.level === 'overflow');
+ if (remoteRouteCannotRebuild && targetRequiresRebuild) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote model-window rebuild is unsupported; runtime selection was not changed',
+ );
+ }
+ if (
+ runtimeAgentKind !== 'pi' &&
+ typeof targetContextWindow === 'number' &&
+ targetContextWindow > 0 &&
+ !targetDoesNotShrink
+ ) {
+ if (!contextOverflowRolloverHolder) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'model window switch protection is unavailable; runtime selection was not changed',
+ );
+ }
+ let pendingClearedForWindowRebuild = false;
+ let confirmationContextTokens: number | undefined;
+ let preparation: ModelWindowSwitchPreparationResult;
+ try {
+ preparation = await contextOverflowRolloverHolder.prepareModelWindowSwitch(sessionId, {
+ contextWindow: targetContextWindow!,
+ recheckTargetPressure: true,
+ confirmedTargetPressure:
+ !isDeviceLinkInvoke() && confirmedContextWindow === targetContextWindow,
+ onConfirmationRequired: (contextTokens) => {
+ confirmationContextTokens = contextTokens;
+ },
+ assertCanCommit: assertRuntimeOwnerCurrent,
+ beforeClose: () => {
+ clearPendingCredentialSwitchForSession(sessionId, { wake: false });
+ pendingClearedForWindowRebuild = true;
+ },
+ });
+ } catch (error) {
+ if (
+ pendingClearedForWindowRebuild &&
+ sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)
+ ) {
+ if (previousRuntime.pendingCredentialSwitch) {
+ pendingCredentialSwitchHolder?.register(
+ sessionId,
+ previousRuntime.pendingCredentialSwitch,
+ );
+ } else {
+ wakeSessionInputAfterCredentialSwitch(sessionId);
+ }
+ }
+ throw error;
+ }
+ if (preparation === 'confirmation-required') {
+ if (!previousRuntime.hadLiveSession && maker.getSession(sessionId)) {
+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));
+ }
+ restoreControlStores();
+ if (isDeviceLinkInvoke()) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ );
+ }
+ if (!confirmationContextTokens || confirmationContextTokens <= 0) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'verified model-window confirmation usage is unavailable',
+ );
+ }
+ return {
+ deferred: false,
+ superseded: false,
+ contextWindowConfirmationRequired: targetContextWindow,
+ contextTokensForConfirmation: confirmationContextTokens,
+ };
+ }
+ if (preparation === 'busy') {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'wait for the current turn to finish before switching to a smaller context window',
+ );
+ }
+ if (preparation === 'remote-unsupported') {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'this remote task cannot safely rebuild context for the smaller model window',
+ );
+ }
+ if (preparation === 'unknown-context') {
+ if (!previousRuntime.hadLiveSession && maker.getSession(sessionId)) {
+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));
+ }
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'current context window is unknown; runtime selection was not changed',
+ );
+ }
+ if (preparation === 'in-flight') {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'context preparation is already running; retry the model switch after it finishes',
+ );
+ }
+ assertRuntimeOwnerCurrent();
+ modelWindowRebuilt = preparation === 'rebuilt';
+ if (
+ modelWindowRebuilt &&
+ effectiveProviderId === undefined &&
+ previousRuntime.pendingCredentialSwitch
+ ) {
+ // beforeClose deliberately cleared the stale pending record so it
+ // cannot finalize against the retiring native session. Preserve its
+ // provider intent as an explicit route for this accepted switch.
+ effectiveProviderId = targetRouteProviderId;
+ }
+ }
+ }
const reconcileRetainedLiveProfile = async (): Promise<void> => {
const retainedSession = maker.getSession(sessionId);
if (!retainedSession || !sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {
@@ -15742,6 +16272,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
});
};
+ // context.rebuild clears sdk_session_id, so the preflight Codex thread can no longer
+ // be forked. Persist the accepted target route and let the next send create a new thread.
+ const shouldRelinkCodexThread = requiresCodexThreadRelink && !modelWindowRebuilt;
try {
const result = routeExplicit
? await applyRuntimeSetModelChange({
@@ -15755,21 +16288,36 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
}
: {}),
- forceSessionRebuild: rebuildLiveOrcaWorker,
+ 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: clearPendingCredentialSwitchForSession,
+ clearPendingCredentialSwitch: atomicSelection
+ ? (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
+ ...(!rebuildLiveOrcaWorker && !atomicSelection
? { wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch }
: {}),
getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
// 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见
// shouldCloseSessionForCredentialSwitch.codexAuthInjection)。
codexAuthInjection: getCodexProxyAuthInjectionState(),
- requiresCodexThreadRelink,
- ...(relinkCodexThread ? { relinkCodexThread } : {}),
+ requiresCodexThreadRelink: shouldRelinkCodexThread,
+ ...(shouldRelinkCodexThread && relinkCodexThread ? { relinkCodexThread } : {}),
logger: log,
})
: { status: 'applied' as const };
@@ -15782,6 +16330,86 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (supersededByOwnerBoundary()) {
return { deferred: false, superseded: true };
}
+ const piSessionAfterRouteChange = maker.getSession(sessionId);
+ if (
+ runtimeAgentKind === 'pi' &&
+ runtimeRouteChanged &&
+ result.status !== 'deferred' &&
+ !modelWindowRebuilt
+ ) {
+ if (!piSessionAfterRouteChange) {
+ restoreControlStores();
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Pi target runtime could not be verified; runtime selection was not accepted',
+ );
+ }
+ const finalPiWindow = piSessionAfterRouteChange.getUsageSnapshot?.().contextWindow;
+ if (typeof finalPiWindow !== 'number' || finalPiWindow <= 0) {
+ await closeRejectedPiRuntime('final context window was not verified');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Pi did not expose its verified final context window; runtime selection was not accepted',
+ );
+ }
+ targetContextWindow = finalPiWindow;
+ if (finalPiWindow < verifiedCurrentWindow!) {
+ if (!contextOverflowRolloverHolder) {
+ await closeRejectedPiRuntime('model-window protection was unavailable');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'model window switch protection is unavailable; runtime selection was not changed',
+ );
+ }
+ let finalPressureContextTokens: number | undefined;
+ let finalPreparation: ModelWindowSwitchPreparationResult;
+ try {
+ finalPreparation = await contextOverflowRolloverHolder.prepareModelWindowSwitch(
+ sessionId,
+ {
+ contextWindow: finalPiWindow,
+ recheckTargetPressure: true,
+ confirmedTargetPressure:
+ !isDeviceLinkInvoke() && confirmedContextWindow === finalPiWindow,
+ onConfirmationRequired: (contextTokens) => {
+ finalPressureContextTokens = contextTokens;
+ },
+ assertCanCommit: assertRuntimeOwnerCurrent,
+ },
+ );
+ } catch (error) {
+ await closeRejectedPiRuntime('final-window preparation threw');
+ throw error;
+ }
+ if (finalPreparation === 'confirmation-required') {
+ assertRuntimeOwnerCurrent();
+ await closeRejectedPiRuntime('final-window confirmation was required');
+ if (isDeviceLinkInvoke()) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ );
+ }
+ return {
+ ...response,
+ contextWindowConfirmationRequired: finalPiWindow,
+ contextTokensForConfirmation: finalPressureContextTokens,
+ };
+ }
+ if (finalPreparation === 'rebuilt') {
+ modelWindowRebuilt = true;
+ targetContextWindow = finalPiWindow;
+ } else if (finalPreparation !== 'not-needed') {
+ await closeRejectedPiRuntime(`final-window preparation returned ${finalPreparation}`);
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ finalPreparation === 'remote-unsupported'
+ ? 'remote model-window rebuild is unsupported; runtime selection was not changed'
+ : `Pi final-window context preparation failed: ${finalPreparation}`,
+ );
+ }
+ }
+ }
if (atomicSelection) {
const selectionToCommit = atomicSelection;
// model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。
@@ -15802,7 +16430,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
session: sess,
effort: selectionToCommit.effort,
fastMode: selectionToCommit.fastMode,
- applyEffort: routeExplicit || internalOptions.effortExplicit === true,
+ applyEffort:
+ runtimeAgentKind !== 'pi' &&
+ (routeExplicit || internalOptions.effortExplicit === true),
applyFastMode: routeExplicit || internalOptions.fastExplicit === true,
assertCanCommit: assertRuntimeOwnerCurrent,
commitControlStores,
@@ -15816,9 +16446,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
if (
- internalOptions.source === 'user' &&
- (isDeviceLinkInvoke() || atomicSelection) &&
- result.persistedRoute !== true
+ result.persistedRoute !== true &&
+ (modelWindowRebuilt ||
+ (internalOptions.source === 'user' && (isDeviceLinkInvoke() || atomicSelection)))
) {
// device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;
// 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的
@@ -15840,6 +16470,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
patch.fastMode = atomicSelection.fastMode;
}
+ if (modelWindowRebuilt && targetContextWindow) {
+ patch.contextWindow = targetContextWindow;
+ }
+ const routeProjectionOwnerScope = captureDataOwnerBroadcastScope();
try {
await persistSessionFields(sessionId, patch);
} catch (persistenceError) {
@@ -15850,9 +16484,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
pendingCredentialSwitchHolder?.clear(sessionId);
restoreControlStores();
let recoveryError: unknown;
+ const shouldCloseRuntimeAfterPersistenceFailure =
+ (result.status !== 'deferred' && previousRuntime.hadLiveSession) ||
+ rehydratedColdPiRuntime !== undefined;
if (
- result.status !== 'deferred' &&
- previousRuntime.hadLiveSession &&
+ shouldCloseRuntimeAfterPersistenceFailure &&
maker.getSession(sessionId)
) {
try {
@@ -15878,6 +16514,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
throw persistenceError;
}
+ if (modelWindowRebuilt && targetContextWindow) {
+ // commitRebuild first projects zero usage against the still-authoritative
+ // source route. Publish the accepted final window only after its route
+ // persistence succeeds, keeping rollback projections on the source window.
+ broadcastSessionPatched(
+ sessionId,
+ {
+ contextTokens: 0,
+ contextWindow: targetContextWindow,
+ },
+ routeProjectionOwnerScope,
+ );
+ }
if (isDeviceLinkInvoke()) {
// dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。
markRemoteSettingPersistedInsideHandler(response);
@@ -15935,7 +16584,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
});
}
- if (rebuildLiveOrcaWorker && !response.deferred) {
+ if ((rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection) && !response.deferred) {
wakeSessionInputAfterCredentialSwitch(sessionId);
}
if (!response.deferred) {
@@ -15952,10 +16601,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
modelId,
),
model,
- typeof effectiveProviderId === 'string' ? effectiveProviderId : null,
+ targetRouteProviderId,
currentAgentKind,
);
- if (verifiedWindow) {
+ const piRuntimeWindow = maker.getSession(sessionId)?.getUsageSnapshot?.().contextWindow;
+ const snapshotWindow =
+ currentAgentKind === 'pi'
+ ? typeof piRuntimeWindow === 'number' && piRuntimeWindow > 0
+ ? piRuntimeWindow
+ : null
+ : verifiedWindow;
+ if (snapshotWindow) {
const [usage] = await getDbClient()
.drizzle.select({ contextTokens: sessions.contextTokens })
.from(sessions)
@@ -15964,7 +16620,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await recordSessionContextSnapshot(
sessionId,
usage?.contextTokens ?? 0,
- verifiedWindow,
+ snapshotWindow,
);
}
} catch (error) {
@@ -16002,12 +16658,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
error: error instanceof Error ? error.message : String(error),
});
});
- return {
- ...response,
+ // Preserve object identity so a device-link in-lock persistence mark remains visible
+ // to dispatch and cannot be followed by a stale lock-free route write.
+ return Object.assign(response, {
generation,
effectiveProviderId: normalizeSessionProviderId(effectiveProviderId) ?? null,
- };
+ });
} catch (err) {
+ // Atomic calls suppress applyRuntimeSetModelChange's early wake. If a later step
+ // rejects after clearing an older pending switch, release the queue on the still-
+ // authoritative profile; a restored/new pending gate will conservatively block it.
+ if (atomicSelection) {
+ wakeSessionInputAfterCredentialSwitch(sessionId);
+ }
if (err instanceof CredentialModeSwitchBusyError) {
// 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,
// renderer toast 走 ipcError.CREDENTIAL_SWITCH_BUSY 专属文案。
@@ -16646,78 +17309,80 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId: string,
requestedDirs: string[],
options: { remote: boolean; senderId?: number },
- ) => withSendToSessionLock(sessionId, async () => {
- await assertReviewSettingsUnlocked(sessionId);
- const sess = maker.getSession(sessionId);
- const supported = axis === 'extraDirs'
- ? sess?.capabilities.extraDirs.supported
- : sess?.capabilities.writableDirs?.supported;
- const label = axis === 'extraDirs' ? 'set-extra-dirs' : 'set-writable-dirs';
- if (!sess || !supported) {
- log.debug(`${label}: ${sess ? 'agent capability=false' : 'session not found'}, no-op`, {
- sessionId,
- ...(sess ? { agentKind: sess.agentKind } : {}),
- });
- return;
- }
- const result = await applyRemoteDirectoryGrantUpdate(axis, requestedDirs, sess, {
- validate: (requested) => validateExtraDirs(requested, sess.workDir || undefined),
- readExtraDirs: () => readSessionExtraDirsFromDb(sessionId),
- readWritableDirs: () => readSessionWritableDirsFromDb(sessionId),
- excludeConflicts: async (candidates, blocked) => {
- const accepted = await excludeDirectoryGrantConflicts(candidates, blocked);
- if (axis === 'writableDirs') {
- const previousDirs = await readSessionWritableDirsFromDb(sessionId);
- const [route] = await getDbClient()
- .drizzle.select({ remoteHostId: sessions.remoteHostId })
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
- if (options.remote || route?.remoteHostId) {
- // The picker lives on the controller filesystem, so device-link and SSH may only
- // retain/revoke roots that were already persisted on the execution side.
- if (!isPersistedDirectoryGrantSubset(accepted, previousDirs)) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'remote writable directories can only retain or revoke existing grants',
- );
- }
- return accepted;
- } else {
- if (options.senderId === undefined) {
- throwIpcError('PRECONDITION_FAILED', 'Writable directory picker owner unavailable');
- }
- try {
- await consumeWritableDirectoryPickerGrants({
- scopeId: sessionId,
- senderId: options.senderId,
- requestedDirs: accepted,
- previousDirs,
- });
- } catch (error) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- error instanceof Error
- ? error.message
- : 'Writable directory authorization failed',
- );
+ ) =>
+ withSendToSessionLock(sessionId, async () => {
+ await assertReviewSettingsUnlocked(sessionId);
+ const sess = maker.getSession(sessionId);
+ const supported =
+ axis === 'extraDirs'
+ ? sess?.capabilities.extraDirs.supported
+ : sess?.capabilities.writableDirs?.supported;
+ const label = axis === 'extraDirs' ? 'set-extra-dirs' : 'set-writable-dirs';
+ if (!sess || !supported) {
+ log.debug(`${label}: ${sess ? 'agent capability=false' : 'session not found'}, no-op`, {
+ sessionId,
+ ...(sess ? { agentKind: sess.agentKind } : {}),
+ });
+ return;
+ }
+ const result = await applyRemoteDirectoryGrantUpdate(axis, requestedDirs, sess, {
+ validate: (requested) => validateExtraDirs(requested, sess.workDir || undefined),
+ readExtraDirs: () => readSessionExtraDirsFromDb(sessionId),
+ readWritableDirs: () => readSessionWritableDirsFromDb(sessionId),
+ excludeConflicts: async (candidates, blocked) => {
+ const accepted = await excludeDirectoryGrantConflicts(candidates, blocked);
+ if (axis === 'writableDirs') {
+ const previousDirs = await readSessionWritableDirsFromDb(sessionId);
+ const [route] = await getDbClient()
+ .drizzle.select({ remoteHostId: sessions.remoteHostId })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (options.remote || route?.remoteHostId) {
+ // The picker lives on the controller filesystem, so device-link and SSH may only
+ // retain/revoke roots that were already persisted on the execution side.
+ if (!isPersistedDirectoryGrantSubset(accepted, previousDirs)) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote writable directories can only retain or revoke existing grants',
+ );
+ }
+ return accepted;
+ } else {
+ if (options.senderId === undefined) {
+ throwIpcError('PRECONDITION_FAILED', 'Writable directory picker owner unavailable');
+ }
+ try {
+ await consumeWritableDirectoryPickerGrants({
+ scopeId: sessionId,
+ senderId: options.senderId,
+ requestedDirs: accepted,
+ previousDirs,
+ });
+ } catch (error) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ error instanceof Error
+ ? error.message
+ : 'Writable directory authorization failed',
+ );
+ }
}
}
- }
- return accepted;
- },
- persist: (patch) => persistSessionFields(sessionId, patch),
- terminate: () => maker.closeSession(sessionId),
- });
- log.info(label, {
- sessionId,
- requested: requestedDirs.length,
- kept: result.dirs.length,
- rejected: result.rejectedCount,
+ return accepted;
+ },
+ persist: (patch) => persistSessionFields(sessionId, patch),
+ terminate: () => maker.closeSession(sessionId),
+ });
+ log.info(label, {
+ sessionId,
+ requested: requestedDirs.length,
+ kept: result.dirs.length,
+ rejected: result.rejectedCount,
+ });
+ if (options.remote) markRemoteSettingPersistedInsideHandler(result.dirs);
+ return result.dirs;
});
- if (options.remote) markRemoteSettingPersistedInsideHandler(result.dirs);
- return result.dirs;
- });
// 两类目录授权均在同一 session 锁内完成校验、运行时应用与持久化。
// session 不在 / capability 不支持都 no-op, 不抛错 — 跟 setModel 容错语义一致。
@@ -16736,18 +17401,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
});
- ipcMain.handle(MAKER_INVOKE.SET_WRITABLE_DIRS, async (event, sessionId: unknown, dirs: unknown) => {
- const deviceLinkInvoke = isDeviceLinkInvoke();
- if (!deviceLinkInvoke) {
- assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
- }
- if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');
- if (!Array.isArray(dirs)) throwIpcError('INVALID_PARAMS', 'dirs must be string[]');
- return applyDirectoryGrants('writableDirs', sessionId, dirs as string[], {
- remote: deviceLinkInvoke,
- ...(!deviceLinkInvoke ? { senderId: event.sender.id } : {}),
- });
- });
+ ipcMain.handle(
+ MAKER_INVOKE.SET_WRITABLE_DIRS,
+ async (event, sessionId: unknown, dirs: unknown) => {
+ const deviceLinkInvoke = isDeviceLinkInvoke();
+ if (!deviceLinkInvoke) {
+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
+ }
+ if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');
+ if (!Array.isArray(dirs)) throwIpcError('INVALID_PARAMS', 'dirs must be string[]');
+ return applyDirectoryGrants('writableDirs', sessionId, dirs as string[], {
+ remote: deviceLinkInvoke,
+ ...(!deviceLinkInvoke ? { senderId: event.sender.id } : {}),
+ });
+ },
+ );
// ── Memory 控制 ────────────────────────────────────────────────────────
// 透传到 maker.{getAgentMemoryStatus, setAgentMemory, resetAgentMemory},
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index da9ad729c2..8596b50ccb 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -23,7 +23,10 @@ interface RuntimeSetModelSession {
codexThreadModelProviderId?: string | null;
codexCindyRemoteCompactionCompatible?: boolean | null;
model: string;
- setModel: (model: string, opts?: { providerId?: string | null; effort?: Effort }) => Promise<void>;
+ setModel: (
+ model: string,
+ opts?: { providerId?: string | null; effort?: Effort },
+ ) => Promise<void>;
}
interface RuntimeSetModelActiveSession {
@@ -55,6 +58,8 @@ export interface ApplyRuntimeSetModelChangeInput {
* 形态相同,也必须沿用 credential-switch 的 idle close / busy defer 边界。
*/
forceSessionRebuild?: boolean;
+ /** Fail closed before an otherwise-required runtime replacement mutates route state. */
+ assertSessionCloseSupported?: () => void;
isSessionInTurn?: (sessionId: string) => boolean;
/**
* 会话自己正在跑 turn 时的延迟生效登记(PendingCredentialSwitchService.register)。
@@ -108,6 +113,24 @@ export type ApplyRuntimeSetModelChangeResult =
/** 凭证形态要换但会话自己在跑:已登记 pending,turn 结束后自动生效。 */
| { status: 'deferred'; persistedRoute?: never };
+export async function closeRejectedRuntimeAndRestoreControlStores(input: {
+ closeRuntime: () => Promise<void>;
+ restoreControlStores: () => void;
+ reportCloseError: (error: unknown) => void;
+ assertRuntimeClosed: () => void;
+}): Promise<void> {
+ try {
+ await input.closeRuntime();
+ } catch (error) {
+ input.reportCloseError(error);
+ } finally {
+ // The old control route must match the unchanged persistent route even when
+ // teardown rejects. The caller then verifies that no rejected handle remains.
+ input.restoreControlStores();
+ }
+ input.assertRuntimeClosed();
+}
+
export function isRemoteModelSwitchRouteChangeError(error: unknown): boolean {
return (
(error as { code?: unknown } | null)?.code === 'REMOTE_MODEL_SWITCH_ROUTE_CHANGE' ||
@@ -142,9 +165,7 @@ export async function applyRuntimeSetModelChange(
// 新来源、再换模型时,决策与登记都要沿用那个来源,不能回落到 store 里的旧值
// (否则会把 pending 的来源覆盖丢)。
const pendingTarget =
- normalizedProviderId === undefined
- ? input.getPendingCredentialSwitch?.(sessionId)
- : undefined;
+ normalizedProviderId === undefined ? input.getPendingCredentialSwitch?.(sessionId) : undefined;
const nextProviderId =
normalizedProviderId !== undefined
? normalizedProviderId
@@ -152,7 +173,8 @@ export async function applyRuntimeSetModelChange(
? pendingTarget.providerId
: currentProviderId;
const shouldCloseSession = sess
- ? input.forceSessionRebuild === true || shouldCloseSessionForCredentialSwitch({
+ ? input.forceSessionRebuild === true ||
+ shouldCloseSessionForCredentialSwitch({
agentKind: sess.agentKind,
remoteHostId: sess.remoteHostId,
currentProviderId,
@@ -161,8 +183,7 @@ export async function applyRuntimeSetModelChange(
nextModel: model,
currentCodexProxyActive: sess.codexProxyActive,
currentCodexThreadModelProviderId: sess.codexThreadModelProviderId,
- currentCodexCindyRemoteCompactionCompatible:
- sess.codexCindyRemoteCompactionCompatible,
+ currentCodexCindyRemoteCompactionCompatible: sess.codexCindyRemoteCompactionCompatible,
codexAuthInjection: input.codexAuthInjection,
})
: false;
@@ -173,9 +194,7 @@ export async function applyRuntimeSetModelChange(
let selfBusyMemo: boolean | undefined;
const isSelfBusy = (): boolean => {
if (selfBusyMemo !== undefined) return selfBusyMemo;
- const active = maker
- .listActiveSessions()
- .find((candidate) => candidate.id === sessionId);
+ const active = maker.listActiveSessions().find((candidate) => candidate.id === sessionId);
selfBusyMemo = active
? isLocalSessionBusy(active, isSessionInTurn)
: isSessionInTurn?.(sessionId) === true;
@@ -229,6 +248,7 @@ export async function applyRuntimeSetModelChange(
}
if (sess && (shouldCloseSession || requiresCodexThreadRelink)) {
+ input.assertSessionCloseSupported?.();
if (isSelfBusy() && input.registerPendingCredentialSwitch) {
await input.registerPendingCredentialSwitch(sessionId, {
model,
@@ -325,9 +345,9 @@ export async function applyRuntimeSetModelChange(
await sess.setModel(model, {
// model-only 且内存尚未确认来源时不要把 providerId:null 传进 runtime,
// 否则未 hydrate 的 custom 会话会被清成默认网关。
- ...(normalizedProviderId !== undefined
- || hasSessionProvider(sessionId)
- || pendingTarget !== undefined
+ ...(normalizedProviderId !== undefined ||
+ hasSessionProvider(sessionId) ||
+ pendingTarget !== undefined
? { providerId: nextProviderId }
: {}),
...(effort !== undefined ? { effort } : {}),
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index 9545ea03de..25d715d72d 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -78,7 +78,7 @@ interface ForkNativeSource {
nextSwitch: MessagePosition | null;
/** false = 原生会话已因同引擎换窗失效,只复制可见历史,首次发送走交接。 */
reuseVendorSession: boolean;
- rebuildReason?: 'context-overflow' | 'pi-prompt-timeout';
+ rebuildReason?: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout';
}
interface ForkTimelineMessage {
@@ -115,7 +115,7 @@ async function seedForkHandoffAfterSameEngineRebuild(opts: {
agentKind: DbAgentKind;
model: string;
providerId: string | null;
- reason: 'context-overflow' | 'pi-prompt-timeout';
+ reason: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout';
}): Promise<void> {
const handoffMessages: HandoffSourceMessage[] = opts.rows
.filter(
@@ -159,7 +159,7 @@ async function seedForkHandoffAfterSameEngineRebuild(opts: {
}
interface ParsedContextRebuildBoundary {
- reason: 'context-overflow' | 'pi-prompt-timeout';
+ reason: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout';
sourceAgentKind?: DbAgentKind;
sourceModel?: string | null;
sourceProviderId?: string | null;
@@ -168,7 +168,11 @@ interface ParsedContextRebuildBoundary {
function parseContextRebuildBoundary(content: string): ParsedContextRebuildBoundary | null {
try {
const parsed = JSON.parse(content) as Record<string, unknown>;
- if (parsed.reason !== 'context-overflow' && parsed.reason !== 'pi-prompt-timeout') {
+ if (
+ parsed.reason !== 'context-overflow' &&
+ parsed.reason !== 'model-window-switch' &&
+ parsed.reason !== 'pi-prompt-timeout'
+ ) {
return null;
}
return {
@@ -193,7 +197,7 @@ function parseContextRebuildBoundary(content: string): ParsedContextRebuildBound
function parseContextRebuildReason(
content: string,
-): 'context-overflow' | 'pi-prompt-timeout' | null {
+): 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout' | null {
return parseContextRebuildBoundary(content)?.reason ?? null;
}
diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
index 47cc3e4e97..05726c8634 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
@@ -3,12 +3,240 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
-const chatInputSource = readFileSync(
- resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
- 'utf8',
+const normalizeSourceText = (source: string): string => source.replace(/\r\n?/g, '\n');
+const chatInputSource = normalizeSourceText(
+ readFileSync(
+ resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
+ 'utf8',
+ ),
);
describe('ChatInput model source switching wiring', () => {
+ it('normalizes Windows checkout line endings before matching guard order', () => {
+ const windowsCheckoutSource = chatInputSource.replace(/\n/g, '\r\n');
+ expect(normalizeSourceText(windowsCheckoutSource)).toBe(chatInputSource);
+ });
+
+ it('uses the unified 90% switch-rebuild line instead of a harness compaction setting', () => {
+ const start = chatInputSource.indexOf('const confirmModelSwitchContextGuard = useCallback(');
+ const end = chatInputSource.indexOf('// session-agent-switch', start);
+ const guard = chatInputSource.slice(start, end);
+ expect(guard).toContain(
+ 'autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT',
+ );
+ expect(guard).not.toContain('compactionGetState');
+ });
+
+ it('guards same-model provider route changes with the target provider window', () => {
+ const guardStart = chatInputSource.indexOf('const confirmModelSwitchContextGuard = useCallback(');
+ const guardEnd = chatInputSource.indexOf('// session-agent-switch', guardStart);
+ const guard = chatInputSource.slice(guardStart, guardEnd);
+ expect(guard).toContain('resolveProviderModelContextWindow({');
+ expect(guard).toContain('providerId: targetRouteProviderId');
+
+ const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
+ const providerEnd = chatInputSource.indexOf('const handleProviderChange = useCallback(', providerStart);
+ const providerChange = chatInputSource.slice(providerStart, providerEnd);
+ expect(providerChange).toContain(
+ '(reconciledModelId !== activeModel || newProviderId !== effectiveSourceId)',
+ );
+ expect(providerChange).toMatch(
+ /confirmModelSwitchContextGuard\(\s*reconciledModelId,\s*sourceRemoteDeviceId,\s*newProviderId/,
+ );
+ });
+
+ it('guards model-only duplicate ids with the provider preserved by the final route', () => {
+ const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
+ const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
+ const modelChange = chatInputSource.slice(modelStart, providerStart);
+
+ expect(modelChange).toMatch(
+ /confirmModelSwitchContextGuard\(\s*newModelId,\s*sourceRemoteDeviceId,\s*effectiveSourceId,/,
+ );
+ expect(modelChange).toContain(
+ 'const { efforts, defaultEffort } = resolveModelEfforts(newModelId, effectiveSourceId);',
+ );
+ expect(modelChange).toMatch(
+ /setModelWithFinalWindowConfirmation\(\s*newModelId,\s*effectiveSourceId,/,
+ );
+ expect(modelChange).toMatch(
+ /maker\.setModel\(\s*sessionId,\s*newModelId,\s*undefined,/,
+ );
+ });
+
+ it('keeps exact-window confirmation local and removes it from device-link calls', () => {
+ const guardStart = chatInputSource.indexOf(
+ 'const confirmModelSwitchContextGuard = useCallback(',
+ );
+ const guardEnd = chatInputSource.indexOf(
+ 'const setModelWithFinalWindowConfirmation',
+ guardStart,
+ );
+ const guard = chatInputSource.slice(guardStart, guardEnd);
+ expect(guard).toContain(
+ 'return accepted && targetContextWindow ? targetContextWindow : accepted',
+ );
+
+ const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
+ const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
+ const modelChange = chatInputSource.slice(modelStart, providerStart);
+ const providerChange = chatInputSource.slice(providerStart);
+ for (const route of [modelChange, providerChange]) {
+ const remoteSet = route.indexOf('const remoteSetModelResult = await remoteMaker.setModel(');
+ const localSet = route.indexOf('await setModelWithFinalWindowConfirmation(', remoteSet);
+ expect(remoteSet).toBeGreaterThan(-1);
+ expect(localSet).toBeGreaterThan(remoteSet);
+ const remoteRoute = route.slice(remoteSet, localSet);
+ expect(remoteRoute).not.toContain('setModelWithFinalWindowConfirmation');
+ expect(remoteRoute).not.toContain('confirmedContextWindow');
+ expect(route.slice(localSet)).toContain('confirmedFinalWindow ?? confirmedGuardContextWindow');
+ }
+ expect(chatInputSource).not.toContain('CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1');
+ });
+
+ it('passes the guard-confirmed window into both initial trusted local set-model calls', () => {
+ const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
+ const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
+ const providerEnd = chatInputSource.indexOf(
+ 'const handleProviderChange = useCallback(',
+ providerStart,
+ );
+ const modelChange = chatInputSource.slice(modelStart, providerStart);
+ const providerChange = chatInputSource.slice(providerStart, providerEnd);
+
+ for (const route of [modelChange, providerChange]) {
+ expect(route).toContain("if (typeof proceed === 'number') confirmedGuardContextWindow = proceed;");
+ expect(route).toMatch(
+ /const confirmedContextWindow =\s*confirmedFinalWindow \?\? confirmedGuardContextWindow;\s*return window\.electronAPI\.maker\.setModel/,
+ );
+ expect(route.indexOf("if (!proceed ||")).toBeLessThan(
+ route.indexOf('window.electronAPI.maker.setModel('),
+ );
+ }
+ });
+
+ it('confirms pressure first revealed by Pi final-window verification before retrying', () => {
+ const helperStart = chatInputSource.indexOf(
+ 'const setModelWithFinalWindowConfirmation = useCallback(',
+ );
+ const helperEnd = chatInputSource.indexOf('// session-agent-switch', helperStart);
+ const helper = chatInputSource.slice(helperStart, helperEnd);
+
+ expect(helper).toContain('contextWindowConfirmationRequired');
+ expect(helper).toContain('contextTokensForConfirmation');
+ expect(helper).toMatch(
+ /confirmModelSwitchContextGuard\(\s*modelId,\s*undefined,\s*providerId,\s*requiredWindow,/,
+ );
+ expect(helper).toContain('if (accepted !== requiredWindow) return { accepted: false };');
+ expect(helper).toContain('result = await invoke(accepted)');
+ expect(helper).not.toContain('result = await invoke(requiredWindow)');
+ expect(chatInputSource.split('await setModelWithFinalWindowConfirmation(')).toHaveLength(3);
+ expect(chatInputSource).toContain('? { confirmedContextWindow }');
+ });
+
+ it('keeps authoritative final-window confirmation ahead of stale snapshot shortcuts', () => {
+ const guardStart = chatInputSource.indexOf(
+ 'const confirmModelSwitchContextGuard = useCallback(',
+ );
+ const helperStart = chatInputSource.indexOf(
+ 'const setModelWithFinalWindowConfirmation = useCallback(',
+ guardStart,
+ );
+ const helperEnd = chatInputSource.indexOf('// session-agent-switch', helperStart);
+ const guard = chatInputSource.slice(guardStart, helperStart);
+ const helper = chatInputSource.slice(helperStart, helperEnd);
+ const piBypass = guard.indexOf("runtimeAgentKind === 'pi' &&");
+ const sameOrExpand = guard.indexOf('targetContextWindow >= currentContextWindow');
+ const localVerdictShortcut = guard.indexOf("verdict.level === 'ok'");
+ const confirmation = guard.indexOf('const accepted = await confirmDialog({');
+
+ expect(guard).toContain(
+ 'const contextTokens = requireDestructiveConfirmation\n ? verifiedContextTokens',
+ );
+ expect(guard.slice(0, piBypass)).toContain('!requireDestructiveConfirmation &&');
+ expect(guard.slice(piBypass, sameOrExpand)).toContain(
+ '!requireDestructiveConfirmation &&\n hasVerifiedWindows',
+ );
+ expect(guard.slice(0, sameOrExpand)).toContain(
+ 'requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)',
+ );
+ expect(guard.slice(sameOrExpand, localVerdictShortcut)).toContain(
+ '!requireDestructiveConfirmation &&\n (!trustedContextTokens || trustedContextTokens <= 0)',
+ );
+ expect(guard.slice(localVerdictShortcut - 40, confirmation)).toContain(
+ '!requireDestructiveConfirmation && verdict.level',
+ );
+ expect(confirmation).toBeGreaterThan(localVerdictShortcut);
+ expect(helper).toContain('if (accepted !== requiredWindow) return { accepted: false };');
+ expect(helper).toContain('result = await invoke(accepted);');
+ });
+
+ it('gates the device-link Pi estimate bypass on the controlled host window guard', () => {
+ const start = chatInputSource.indexOf('const confirmModelSwitchContextGuard = useCallback(');
+ const end = chatInputSource.indexOf('// session-agent-switch', start);
+ const guard = chatInputSource.slice(start, end);
+ const piCapability = guard.indexOf('const remotePiWindowGuardSupported =');
+ const piRuntimeBypass = guard.indexOf("runtimeAgentKind === 'pi' &&");
+ const catalogTargetResolution = guard.indexOf('const targetRouteProviderId =');
+ const remoteGuard = guard.indexOf('const hasVerifiedWindows =');
+ const legacyPiGuard = guard.indexOf('shouldBlockLegacyRemotePiModelWindowSwitch({');
+ const remoteUnknownBlock = guard.indexOf(
+ 'if (remoteHostId && (!hasVerifiedWindows || !hasVerifiedUsage)) return false;',
+ );
+ const zeroUsagePass = guard.indexOf(
+ '!requireDestructiveConfirmation &&\n (!trustedContextTokens || trustedContextTokens <= 0)',
+ );
+ const remoteBlock = guard.indexOf("verdict.level === 'danger' || verdict.level === 'overflow'");
+ const warningPath = guard.indexOf("verdict.level === 'warn'");
+ const confirmPath = guard.indexOf('const accepted = await confirmDialog({');
+
+ expect(piCapability).toBeGreaterThan(-1);
+ expect(piCapability).toBeLessThan(piRuntimeBypass);
+ expect(piRuntimeBypass).toBeLessThan(catalogTargetResolution);
+ expect(guard).toContain('remoteDeviceId === deviceLinkDeviceId');
+ expect(guard).toContain('supportsModelWindowSwitchGuard === true');
+ expect(guard).not.toContain("if (remoteDeviceId && runtimeAgentKind === 'pi') return true;");
+ expect(guard.slice(piCapability, piRuntimeBypass)).toContain(
+ '!requireDestructiveConfirmation &&',
+ );
+ expect(remoteGuard).toBeGreaterThan(catalogTargetResolution);
+ expect(legacyPiGuard).toBeGreaterThan(remoteGuard);
+ expect(legacyPiGuard).toBeLessThan(zeroUsagePass);
+ expect(guard.slice(legacyPiGuard, remoteUnknownBlock)).toContain('return false;');
+ expect(remoteGuard).toBeLessThan(remoteBlock);
+ const shrinkGate = guard.slice(remoteGuard, remoteBlock);
+ expect(shrinkGate).toContain('agentStatus.isRunning');
+ expect(shrinkGate).toContain('targetContextWindow >= currentContextWindow');
+ expect(shrinkGate).toContain(
+ '!requireDestructiveConfirmation &&\n hasVerifiedWindows',
+ );
+ expect(shrinkGate).toContain(
+ 'requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)',
+ );
+ expect(shrinkGate).toContain("typeof contextTokens === 'number'");
+ expect(shrinkGate).toContain('const hasVerifiedUsage = trustedContextTokens !== undefined;');
+ expect(shrinkGate).toContain('!hasVerifiedWindows || !hasVerifiedUsage');
+ expect(remoteUnknownBlock).toBeGreaterThan(legacyPiGuard);
+ expect(zeroUsagePass).toBeGreaterThan(remoteUnknownBlock);
+ expect(shrinkGate).toContain('return true;');
+ expect(guard).toContain(
+ "if (!requireDestructiveConfirmation && verdict.level === 'ok') return true;",
+ );
+ expect(remoteBlock).toBeLessThan(warningPath);
+ expect(remoteBlock).toBeLessThan(confirmPath);
+ const blocked = guard.slice(remoteBlock, warningPath);
+ expect(guard).toContain('(remoteHostId || remoteDeviceId)');
+ expect(guard.indexOf('(remoteHostId || remoteDeviceId)')).toBeLessThan(remoteBlock);
+ expect(blocked).toContain("verdict.level === 'danger' || verdict.level === 'overflow'");
+ expect(blocked).toContain('overflowDescriptionRemote');
+ expect(blocked).toContain('toast.error(');
+ expect(blocked).toContain('return false;');
+ const localConfirm = guard.slice(confirmPath);
+ expect(localConfirm).not.toContain('overflowDescriptionRemote');
+ expect(localConfirm).toContain('overflowDescription');
+ expect(localConfirm).toContain('confirmSwitch');
+ });
+
it('lets a disconnected source reselect the highlighted fallback provider row', () => {
const selectorStart = chatInputSource.lastIndexOf('<ModelSelector');
expect(selectorStart).toBeGreaterThanOrEqual(0);
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index 21baf43e4f..c1fa1fda28 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -960,8 +960,8 @@ describe('远程交互接线不变式', () => {
const src = read('components/new-chat/ChatInput.tsx');
const start = src.indexOf('if (sourceRemoteDeviceId) {');
expect(start).toBeGreaterThan(-1);
- const body = src.slice(start, start + 2800);
- const atomic = body.indexOf('? { effort: newEffort, fastMode: restoredFast }');
+ const body = src.slice(start, start + 4400);
+ const atomic = body.indexOf('effort: newEffort,', body.indexOf('useAtomicSelection'));
const fallback = body.indexOf('if (!useAtomicSelection) {');
const persist = body.indexOf('fastPersisted = await persistFastModeChange(restoredFast, {');
const sync = body.indexOf('syncSessionDraftModelPrefs(');
@@ -985,7 +985,7 @@ describe('远程交互接线不变式', () => {
expect(start).toBeGreaterThan(-1);
expect(end).toBeGreaterThan(start);
const body = src.slice(start, end);
- const atomic = body.indexOf('? { effort: targetEffort, fastMode: restoredFast }');
+ const atomic = body.indexOf('effort: targetEffort,', body.indexOf('useAtomicSelection'));
const fallback = body.indexOf('if (!useAtomicSelection) {');
const persist = body.indexOf('fastPersisted = await persistFastModeChange(restoredFast, {');
const sync = body.indexOf('syncSessionDraftModelPrefs(');
@@ -1078,7 +1078,9 @@ describe('远程交互接线不变式', () => {
const providerBody = src.slice(providerStart, providerEnd);
expect(modelBody).toContain('remoteDeviceId: sourceRemoteDeviceId');
expect(modelBody).toContain('onEffortDidChange?.(newEffort, sessionId, sourceRemoteDeviceId)');
- expect(modelBody).toContain('confirmModelSwitchContextGuard(newModelId, sourceRemoteDeviceId)');
+ expect(modelBody).toMatch(
+ /confirmModelSwitchContextGuard\(\s*newModelId,\s*sourceRemoteDeviceId,\s*effectiveSourceId,/,
+ );
expect(modelBody).toMatch(
/persistFastModeChange\(restoredFast,\s*\{[\s\S]*?remoteDeviceId: sourceRemoteDeviceId/,
);
@@ -1269,13 +1271,13 @@ describe('远程交互接线不变式', () => {
const end = src.indexOf('const handleNavigateToProviders', start);
expect(end).toBeGreaterThan(start);
const body = src.slice(start, end);
- const runtimeGate = body.indexOf(
- 'const setModelResult = await window.electronAPI.maker.setModel(',
- );
- const atomicSelection = body.indexOf('{ effort: eff, fastMode: restoredFast }');
+ const runtimeGate = body.indexOf('await setModelWithFinalWindowConfirmation(');
+ const atomicSelection = body.indexOf('effort: eff,', runtimeGate);
+ const atomicFast = body.indexOf('fastMode: restoredFast,', atomicSelection);
const applyUi = body.indexOf('applyProviderSelection();');
expect(runtimeGate).toBeGreaterThan(-1);
expect(atomicSelection).toBeGreaterThan(runtimeGate);
+ expect(atomicFast).toBeGreaterThan(atomicSelection);
expect(applyUi).toBeGreaterThan(-1);
expect(atomicSelection).toBeLessThan(applyUi);
expect(body).not.toContain('await sessionService.update(sessionId, {');
@@ -1288,16 +1290,13 @@ describe('远程交互接线不变式', () => {
expect(start).toBeGreaterThan(-1);
expect(end).toBeGreaterThan(start);
const body = src.slice(start, end);
- const runtimeGate = body.indexOf(
- 'const setModelResult = await window.electronAPI.maker.setModel(',
- );
- const atomicSelection = body.indexOf(
- '{ effort: newEffort, fastMode: restoredFast }',
- runtimeGate,
- );
+ const runtimeGate = body.indexOf('await setModelWithFinalWindowConfirmation(');
+ const atomicSelection = body.indexOf('effort: newEffort,', runtimeGate);
+ const atomicFast = body.indexOf('fastMode: restoredFast,', atomicSelection);
const applyUi = body.indexOf('onModelDidChange?.(newModelId)');
expect(runtimeGate).toBeGreaterThan(-1);
expect(atomicSelection).toBeGreaterThan(runtimeGate);
+ expect(atomicFast).toBeGreaterThan(atomicSelection);
expect(applyUi).toBeGreaterThan(-1);
expect(atomicSelection).toBeLessThan(applyUi);
expect(body).not.toContain('await sessionService.update(sessionId, {');
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
index bb1a022d65..fd0d45b9b0 100644
--- a/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
@@ -17,6 +17,7 @@ const { useCodexRuntimeRouteMock } = vi.hoisted(() => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: '3rdParty', init: () => undefined },
}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
@@ -33,6 +34,7 @@ vi.mock('@/hooks/useCodexSessionExpiredPrompt', () => ({
}));
import { ErrorBanner } from '@/components/chat/ErrorBanner';
+import { ErrorMessageCard } from '@/components/chat/ErrorMessageCard';
import { UPSTREAM_STREAM_INTERRUPTED_REASON } from '@/utils/streamInterruptError';
const STREAM_RAW =
@@ -85,6 +87,34 @@ describe('ErrorBanner — LiteLLM 流中断', () => {
});
});
+describe('runtime-selection-cancelled 本地化', () => {
+ const fallback =
+ 'Deferred model switch was cancelled because safe context rebuild is unsupported. The previous model remains active.';
+ const reason = 'runtime-selection-cancelled';
+ const key = 'newChat.chatInput.switchFailed';
+
+ it('live ErrorBanner uses the stable localized reason instead of the English fallback', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: fallback,
+ errorReason: reason,
+ onRetry: vi.fn(),
+ agentKind: 'pi',
+ }),
+ );
+
+ expect(screen.getByText(key)).toBeTruthy();
+ expect(screen.queryByText(fallback)).toBeNull();
+ });
+
+ it('persisted ErrorMessageCard uses the same localized reason instead of the English fallback', () => {
+ render(createElement(ErrorMessageCard, { message: fallback, reason }));
+
+ expect(screen.getByText(key)).toBeTruthy();
+ expect(screen.queryByText(fallback)).toBeNull();
+ });
+});
+
describe('ErrorBanner — Codex oversized history', () => {
it('hides Retry locally and does not show a strip-fork button', () => {
render(
diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
index bcbdbc05e6..465e16f58b 100644
--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
@@ -963,10 +963,12 @@ describe('ChatInput 的入口门控与调用路由', () => {
expect(source).toContain(
'expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported',
);
- expect(source).toContain('? { effort: newEffort, fastMode: restoredFast }');
- expect(source).toContain('? { effort: targetEffort, fastMode: restoredFast }');
+ expect(source).toContain('effort: newEffort,');
+ expect(source).toContain('effort: targetEffort,');
+ expect(source).toContain('fastMode: restoredFast,');
expect(source).toContain('if (!useAtomicSelection) {');
expect(source).toContain('if (remoteSetModelResult?.superseded) {');
+ expect(source).not.toContain('if (!accepted || remoteSetModelResult?.superseded) {');
expect(source).toContain('if (setModelResult?.superseded) {');
expect(source).toContain('result.sameEngineRevision,');
});
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 8243276a40..d0194c525c 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -19,6 +19,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'silent-stop-exhausted': 'logic.errors.silentStopExhausted',
tool_use_loop_detected: 'logic.errors.toolUseLoopDetected',
'permission-tighten-interrupt-failed': 'logic.errors.permissionTightenInterruptFailed',
+ 'runtime-selection-cancelled': 'newChat.chatInput.switchFailed',
'codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable',
'host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',
upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index bd39d921f1..50a580c2c0 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -313,6 +313,7 @@ import {
deriveModelsFromProviders,
filterChatBridgedCodexProviders,
resolveFastSupported,
+ resolveProviderModelContextWindow,
resolveProviderModelEfforts,
} from '@/lib/providerModels';
import {
@@ -348,7 +349,11 @@ import {
makerChatStore,
} from '@/lib/makerChatStore';
// 切模型前的上下文容量预检(大窗口 → 小窗口护栏), 纯函数与 main 共用。
-import { assessModelSwitchContext } from '../../../shared/modelSwitchAssessment';
+import {
+ assessModelSwitchContext,
+ MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ shouldBlockLegacyRemotePiModelWindowSwitch,
+} from '../../../shared/modelSwitchAssessment';
import { useVoiceInput } from '@/voice-input/useVoiceInput';
import { useVoiceInputSettings } from '@/hooks/useVoiceInputSettings';
import { VoiceInputStatusNotice } from '@/voice-input/VoiceInputStatusNotice';
@@ -6085,59 +6090,202 @@ export function ChatInput({
* 分级语义见 shared/modelSwitchAssessment.ts。overflow 确认后由 host 交接换窗,
* 不要再建议用户先 /compact —— 小窗口模型压整段历史同样会失败。
* 返回 false = 用户取消, 调用方直接放弃本次切换(无任何副作用)。
- * fail-open: 占用未知(0)/ 目标窗口未知 / 阈值读取失败都不拦。
+ * fail-open: 占用未知(0)/ 目标窗口未知时不拦;三个 harness 的强制换窗线统一为 90%。
*/
const confirmModelSwitchContextGuard = useCallback(
- async (newModelId: string, sourceRemoteDeviceId?: string): Promise<boolean> => {
+ async (
+ newModelId: string,
+ sourceRemoteDeviceId?: string,
+ targetProviderId?: string | null,
+ verifiedTargetContextWindow?: number,
+ verifiedContextTokens?: number,
+ requireDestructiveConfirmation = false,
+ ): Promise<boolean | number> => {
if (!sessionId) return true;
- const contextTokens = makerChatStore.getSnapshot(sessionId).agentStatus.contextTokens;
- if (!contextTokens || contextTokens <= 0) return true;
- // device-link 远程会话: 目标模型窗口必须查被控端能力缓存(模型 id 跨设备不唯一)。
- // 优先复用操作开始时捕获的 device scope,relay origin 暂失时不能退回本机目录。
+ const agentStatus = makerChatStore.getSnapshot(sessionId).agentStatus;
+ const contextTokens = requireDestructiveConfirmation
+ ? verifiedContextTokens
+ : (verifiedContextTokens ?? agentStatus.contextTokens);
+ const currentContextWindow = agentStatus.contextWindow;
+ // 显式来源必须按完整 route 查窗口:同 model id 在不同 provider 可分别为 1M / 200K。
+ // 无来源的旧 flat 入口才沿用设备能力缓存的 model-id 回退。
const remoteDeviceId = sourceRemoteDeviceId ?? getSessionDeviceId(sessionId) ?? undefined;
- const targetContextWindow = getModelById(newModelId, remoteDeviceId)?.contextWindow;
- let autoCompactThresholdPct: number | undefined;
- try {
- autoCompactThresholdPct = (await window.electronAPI.maker.compactionGetState()).pct;
- } catch {
- // 阈值读不到 → assessment 内部回退默认 90, 不阻断切换。
+ // Pi 目录窗口只是展示估值;只有明确声明最终 runtime 窗口护栏的新 host
+ // 才能跳过控制端估值,并交给被控端 set_model + get_state 裁决。
+ const remotePiWindowGuardSupported =
+ remoteDeviceId === deviceLinkDeviceId &&
+ (piCaps.capabilities as { supportsModelWindowSwitchGuard?: unknown } | null)
+ ?.supportsModelWindowSwitchGuard === true;
+ if (
+ !requireDestructiveConfirmation &&
+ remoteDeviceId &&
+ runtimeAgentKind === 'pi' &&
+ remotePiWindowGuardSupported
+ ) {
+ return true;
+ }
+ const targetRouteProviderId =
+ targetProviderId !== undefined && currentModelAgentKind
+ ? effectiveSourceIdForModel(
+ providers,
+ targetProviderId,
+ newModelId,
+ currentModelAgentKind,
+ )
+ : null;
+ const targetContextWindow =
+ verifiedTargetContextWindow ??
+ (targetProviderId !== undefined
+ ? targetRouteProviderId && currentModelAgentKind
+ ? resolveProviderModelContextWindow({
+ providers,
+ providerId: targetRouteProviderId,
+ modelId: newModelId,
+ agentKind: currentModelAgentKind,
+ })
+ : undefined
+ : getModelById(newModelId, remoteDeviceId)?.contextWindow);
+ const hasVerifiedTargetWindow =
+ typeof targetContextWindow === 'number' &&
+ Number.isFinite(targetContextWindow) &&
+ targetContextWindow > 0;
+ const hasVerifiedWindows =
+ Number.isFinite(currentContextWindow) &&
+ currentContextWindow > 0 &&
+ hasVerifiedTargetWindow;
+ const trustedContextTokens =
+ typeof contextTokens === 'number' && Number.isFinite(contextTokens) && contextTokens >= 0
+ ? contextTokens
+ : undefined;
+ const hasVerifiedUsage = trustedContextTokens !== undefined;
+ if (requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)) {
+ return false;
+ }
+ if (
+ remoteDeviceId &&
+ runtimeAgentKind === 'pi' &&
+ shouldBlockLegacyRemotePiModelWindowSwitch({
+ hostGuardSupported: remotePiWindowGuardSupported,
+ contextTokens,
+ currentContextWindow,
+ targetContextWindow,
+ })
+ ) {
+ return false;
+ }
+ if (remoteHostId && agentStatus.isRunning) return false;
+ // Main 的最终窗口确认属于权威破坏性请求,不得被旧 snapshot 的同窗/扩窗估值跳过。
+ if (
+ !requireDestructiveConfirmation &&
+ hasVerifiedWindows &&
+ targetContextWindow >= currentContextWindow
+ ) {
+ return true;
+ }
+ // SSH 不做远端 handoff。缩窗判据的任一事实未知时继续关闭。
+ if (remoteHostId && (!hasVerifiedWindows || !hasVerifiedUsage)) return false;
+ if (
+ !requireDestructiveConfirmation &&
+ (!trustedContextTokens || trustedContextTokens <= 0)
+ ) {
+ return true;
}
+ const contextTokensForAssessment = trustedContextTokens ?? 0;
const verdict = assessModelSwitchContext({
- contextTokens,
+ contextTokens: contextTokensForAssessment,
targetContextWindow,
- autoCompactThresholdPct,
+ // 切窗安全线独立于各 harness 的日常 auto-compaction 设置。
+ autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
});
- if (verdict.level === 'ok') return true;
+ if (!requireDestructiveConfirmation && verdict.level === 'ok') return true;
const fmtTokens = (n: number): string =>
n >= 1_000_000
? `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
: `${Math.round(n / 1000)}K`;
const vars = {
- used: fmtTokens(contextTokens),
+ used: fmtTokens(contextTokensForAssessment),
total: fmtTokens(targetContextWindow ?? 0),
pct: verdict.projectedPct,
};
- if (verdict.level === 'warn' || verdict.level === 'danger') {
+ if (
+ (remoteHostId || remoteDeviceId) &&
+ (verdict.level === 'danger' || verdict.level === 'overflow')
+ ) {
+ toast.error(
+ t('newChat.chatInput.modelSwitchContextGuard.overflowDescriptionRemote', vars),
+ { duration: 5000 },
+ );
+ return false;
+ }
+ if (
+ !requireDestructiveConfirmation &&
+ (verdict.level === 'warn' || verdict.level === 'danger')
+ ) {
toast.warning(t('newChat.chatInput.modelSwitchContextGuard.warnToast', vars), {
duration: 4000,
});
return true;
}
- // overflow (≥100%): 弹确认。默认焦点保持在取消(Radix 默认)——
- // 期望用户先取消回去压缩(点上下文圆环)或新开会话, "仍然切换"是次选。
- return confirmDialog({
+ // Local overflow (≥100%): host performs a bounded handoff before switching.
+ const accepted = await confirmDialog({
title: t('newChat.chatInput.modelSwitchContextGuard.title'),
- description: t(
- remoteHostId
- ? 'newChat.chatInput.modelSwitchContextGuard.overflowDescriptionRemote'
- : 'newChat.chatInput.modelSwitchContextGuard.overflowDescription',
- vars,
- ),
+ description: t('newChat.chatInput.modelSwitchContextGuard.overflowDescription', vars),
confirmText: t('newChat.chatInput.modelSwitchContextGuard.confirmSwitch'),
cancelText: t('newChat.chatInput.modelSwitchContextGuard.cancelSwitch'),
});
+ return accepted && targetContextWindow ? targetContextWindow : accepted;
},
- [sessionId, remoteHostId, confirmDialog, t],
+ [
+ sessionId,
+ remoteHostId,
+ confirmDialog,
+ t,
+ providers,
+ currentModelAgentKind,
+ runtimeAgentKind,
+ deviceLinkDeviceId,
+ piCaps.capabilities,
+ ],
+ );
+
+ const setModelWithFinalWindowConfirmation = useCallback(
+ async (
+ modelId: string,
+ providerId: string | null | undefined,
+ invoke: (confirmedContextWindow?: number) =>
+ Promise<{ deferred: boolean; superseded?: boolean } | undefined>,
+ ): Promise<{
+ accepted: boolean;
+ result?: { deferred: boolean; superseded?: boolean };
+ }> => {
+ let result = await invoke();
+ const finalPressure = result as {
+ contextWindowConfirmationRequired?: unknown;
+ contextTokensForConfirmation?: unknown;
+ } | null;
+ const requiredWindow = finalPressure?.contextWindowConfirmationRequired;
+ if (typeof requiredWindow !== 'number' || requiredWindow <= 0) {
+ return { accepted: true, result };
+ }
+ const accepted = await confirmModelSwitchContextGuard(
+ modelId,
+ undefined,
+ providerId,
+ requiredWindow,
+ typeof finalPressure?.contextTokensForConfirmation === 'number'
+ ? finalPressure.contextTokensForConfirmation
+ : undefined,
+ true,
+ );
+ if (accepted !== requiredWindow) return { accepted: false };
+ result = await invoke(accepted);
+ if (
+ typeof (result as { contextWindowConfirmationRequired?: unknown } | null)
+ ?.contextWindowConfirmationRequired === 'number'
+ ) return { accepted: false };
+ return { accepted: true, result };
+ },
+ [confirmModelSwitchContextGuard],
);
// session-agent-switch 意图制:选中「只属于另一家引擎」的模型 → 只向 main 登记
@@ -6720,9 +6868,15 @@ export function ChatInput({
const isSourceSessionCurrent = () =>
isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current);
// 容量护栏最先跑: 用户取消时直接 return, 不留任何副作用(effort 快照都不动)。
+ let confirmedGuardContextWindow: number | undefined;
if (sessionId && newModelId !== activeModel) {
- const proceed = await confirmModelSwitchContextGuard(newModelId, sourceRemoteDeviceId);
+ const proceed = await confirmModelSwitchContextGuard(
+ newModelId,
+ sourceRemoteDeviceId,
+ effectiveSourceId,
+ );
if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return false;
+ if (typeof proceed === 'number') confirmedGuardContextWindow = proceed;
}
// 切换意图期:此时列表展示的是目标引擎(乐观翻转),改选模型 = 更新意图,
// 绝不能走普通 SET_MODEL 链路(main 会清意图、renderer 乐观态失配)。
@@ -6796,7 +6950,12 @@ export function ChatInput({
newModelId,
selectedProviderId,
expectedAgentSwitchRevision,
- useAtomicSelection ? { effort: newEffort, fastMode: restoredFast } : undefined,
+ useAtomicSelection
+ ? ({
+ effort: newEffort,
+ fastMode: restoredFast,
+ } as { effort: string; fastMode: boolean })
+ : undefined,
);
if (remoteSetModelResult?.superseded) {
if (isSourceSessionCurrent()) setPendingRemoteSwitch(null);
@@ -6841,13 +7000,30 @@ export function ChatInput({
const rollbackSeq = (switchSeqBySession.get(sessionId) ?? 0) + 1;
switchSeqBySession.set(sessionId, rollbackSeq);
rollbackModelAfterPersistFailure = { model: activeModel, seq: rollbackSeq };
- const setModelResult = await window.electronAPI.maker.setModel(
- sessionId,
- newModelId,
- undefined,
- expectedAgentSwitchRevision,
- { effort: newEffort, fastMode: restoredFast },
- );
+ const { accepted, result: setModelResult } =
+ await setModelWithFinalWindowConfirmation(
+ newModelId,
+ effectiveSourceId,
+ (confirmedFinalWindow) => {
+ const confirmedContextWindow =
+ confirmedFinalWindow ?? confirmedGuardContextWindow;
+ return window.electronAPI.maker.setModel(
+ sessionId,
+ newModelId,
+ undefined,
+ expectedAgentSwitchRevision,
+ {
+ effort: newEffort,
+ fastMode: restoredFast,
+ ...(confirmedContextWindow ? { confirmedContextWindow } : {}),
+ } as { effort: string; fastMode: boolean },
+ );
+ },
+ );
+ if (!accepted) {
+ rollbackModelAfterPersistFailure = null;
+ return false;
+ }
if (setModelResult?.superseded) {
rollbackModelAfterPersistFailure = null;
return false;
@@ -6947,6 +7123,7 @@ export function ChatInput({
syncSessionDraftModelPrefs,
fastMode,
confirmModelSwitchContextGuard,
+ setModelWithFinalWindowConfirmation,
performAgentSwitch,
remoteAtomicModelSelectionSupported,
settingsLocked,
@@ -7234,14 +7411,21 @@ export function ChatInput({
// 容量护栏(与 handleModelChange 同款): 切来源若连带换到更小窗口的模型
// (典型: 官方 Claude 1M → 折扣 GPT 272K, 在选择器里是跨分组点击、走本路径而非
// handleModelChange —— 2026-07-06 实测踩中), 同样要先过上下文容量确认。
- // 同模型只切来源不拦: 窗口按 model id 取自目录, 来源不变窗口, 无新增风险。
+ // route 的任一维度变化都按目标来源窗口评估;同 model id 跨来源也可能是 1M → 200K。
// 放在函数最前: 本地分支此前无任何乐观状态写入, 用户取消 = 零副作用直接 return。
- if (sessionId && reconciledModelId && reconciledModelId !== activeModel) {
+ let confirmedGuardContextWindow: number | undefined;
+ if (
+ sessionId &&
+ reconciledModelId &&
+ (reconciledModelId !== activeModel || newProviderId !== effectiveSourceId)
+ ) {
const proceed = await confirmModelSwitchContextGuard(
reconciledModelId,
sourceRemoteDeviceId,
+ newProviderId,
);
if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return false;
+ if (typeof proceed === 'number') confirmedGuardContextWindow = proceed;
}
// 切换意图期:列表展示的是目标引擎(乐观翻转),(来源,模型) 改选 = 更新意图,
// 不走普通 set-model 链路(main 会清意图、renderer 乐观态失配)。
@@ -7313,7 +7497,12 @@ export function ChatInput({
targetModel,
newProviderId,
expectedAgentSwitchRevision,
- useAtomicSelection ? { effort: targetEffort, fastMode: restoredFast } : undefined,
+ useAtomicSelection
+ ? ({
+ effort: targetEffort,
+ fastMode: restoredFast,
+ } as { effort: string; fastMode: boolean })
+ : undefined,
);
if (remoteSetModelResult?.superseded) {
if (isSourceSessionCurrent()) {
@@ -7384,13 +7573,30 @@ export function ChatInput({
// deferred = 会话自己在跑,main 已登记 pending、turn 结束自动生效(选择不丢);
// DB 照常落盘(重启也生效),但跳过 runtime setEffort/setFastMode —— 会话
// turn 结束会被关闭重建,别去动还在跑的旧 turn。
- const setModelResult = await window.electronAPI.maker.setModel(
- sessionId,
- modelId,
- newProviderId,
- expectedAgentSwitchRevision,
- { effort: eff, fastMode: restoredFast },
- );
+ const { accepted, result: setModelResult } =
+ await setModelWithFinalWindowConfirmation(
+ modelId,
+ newProviderId,
+ (confirmedFinalWindow) => {
+ const confirmedContextWindow =
+ confirmedFinalWindow ?? confirmedGuardContextWindow;
+ return window.electronAPI.maker.setModel(
+ sessionId,
+ modelId,
+ newProviderId,
+ expectedAgentSwitchRevision,
+ {
+ effort: eff,
+ fastMode: restoredFast,
+ ...(confirmedContextWindow ? { confirmedContextWindow } : {}),
+ } as { effort: string; fastMode: boolean },
+ );
+ },
+ );
+ if (!accepted) {
+ rollbackProviderAfterPersistFailure = null;
+ return false;
+ }
if (setModelResult?.superseded) {
rollbackProviderAfterPersistFailure = null;
return false;
@@ -7508,8 +7714,10 @@ export function ChatInput({
fastMode,
modelFastSupported,
selectedProviderId,
+ effectiveSourceId,
t,
confirmModelSwitchContextGuard,
+ setModelWithFinalWindowConfirmation,
performAgentSwitch,
remoteAtomicModelSelectionSupported,
settingsLocked,
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 2b941b407e..f35980f5a7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -30,7 +30,11 @@ import {
isCodexResumeNotReadyProjectionError,
type AgentInputReference,
} from '@cindy/maker-shared/agent-input-projection';
-import { connectedProvidersForAgent, providerOffersModel } from '@cindy/model-providers';
+import {
+ connectedProvidersForAgent,
+ EFFORT_VALUES,
+ providerOffersModel,
+} from '@cindy/model-providers';
import type { SubagentRunsListResponse } from '@cindy/maker-shared/subagent-workspace';
import { useProportionalWidth } from '@/hooks/useProportionalWidth';
import {
@@ -60,6 +64,7 @@ import { useStopOrcaCollab } from './hooks/useStopOrcaCollab';
import { useWorkerProjection, useWorkerProjectionOwner } from './hooks/workerProjectionStore';
import { CreateWorkerPopover, type CreateWorkerForm } from './CreateWorkerPopover';
import { createWorkerLabel } from './workerLabel';
+import { setModelWithWindowConfirmation } from './lib/modelWindowConfirmation';
import { TakeoverMask } from '@/components/new-chat/TakeoverMask';
import { WorktreeCreatingOverlay } from '@/components/new-chat/WorktreeCreatingOverlay';
import { PermissionPrompt } from '@/components/new-chat/PermissionPrompt';
@@ -3714,27 +3719,68 @@ export function CCAgentSessionView({
if (!sessionId || !session || !canSwitchToClaudeSubscription) return;
const model = session.model;
const previousProviderId = session.providerId ?? null;
-
- await window.electronAPI.maker.setModel(sessionId, model, 'anthropic');
- try {
- await sessionService.update(sessionId, {
- model,
- providerId: 'anthropic',
- });
- } catch (error) {
- // runtime route 已先切换;若持久化失败就回滚,避免当前进程与 DB 对同一会话
- // 产生两个 provider 真源。
- await window.electronAPI.maker
- .setModel(sessionId, model, previousProviderId)
- .catch((rollbackError) => {
- log.warn('Claude subscription recovery rollback failed', rollbackError);
+ const retryEffort =
+ typeof session.effort === 'string' &&
+ (EFFORT_VALUES as readonly string[]).includes(session.effort)
+ ? session.effort
+ : null;
+ const fmtTokens = (value: number): string =>
+ value >= 1_000_000
+ ? `${(value / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
+ : `${Math.round(value / 1000)}K`;
+
+ const switched = await setModelWithWindowConfirmation({
+ invoke: (confirmedContextWindow) =>
+ window.electronAPI.maker.setModel(
+ sessionId,
+ model,
+ 'anthropic',
+ undefined,
+ confirmedContextWindow
+ ? ({
+ effort: retryEffort,
+ fastMode,
+ confirmedContextWindow,
+ } as { effort: string; fastMode: boolean })
+ : undefined,
+ ),
+ confirm: ({ contextWindow, contextTokens }) =>
+ confirmDialog({
+ title: t('newChat.chatInput.modelSwitchContextGuard.title'),
+ description: t('newChat.chatInput.modelSwitchContextGuard.overflowDescription', {
+ used: fmtTokens(contextTokens),
+ total: fmtTokens(contextWindow),
+ pct: Math.round((contextTokens / contextWindow) * 100),
+ }),
+ confirmText: t('newChat.chatInput.modelSwitchContextGuard.confirmSwitch'),
+ cancelText: t('newChat.chatInput.modelSwitchContextGuard.cancelSwitch'),
+ }),
+ });
+ if (!switched) return;
+ if (switched === 'applied') {
+ try {
+ await sessionService.update(sessionId, {
+ model,
+ providerId: 'anthropic',
});
- throw error;
+ } catch (error) {
+ // runtime route 已先切换;若持久化失败就回滚,避免当前进程与 DB 对同一会话
+ // 产生两个 provider 真源。确认后的原子重试已由 Main 持久化,不走此分支。
+ await window.electronAPI.maker
+ .setModel(sessionId, model, previousProviderId)
+ .catch((rollbackError) => {
+ log.warn('Claude subscription recovery rollback failed', rollbackError);
+ });
+ throw error;
+ }
}
await refreshServerSession();
await retryLastError();
- }, [canSwitchToClaudeSubscription, refreshServerSession, retryLastError, session, sessionId]);
+ }, [
+ canSwitchToClaudeSubscription, confirmDialog, fastMode, refreshServerSession,
+ retryLastError, session, sessionId, t,
+ ]);
const handleSilentStopContinue = useCallback(() => {
continueAfterSilentStop();
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/modelWindowConfirmation.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/modelWindowConfirmation.test.ts
new file mode 100644
index 0000000000..6f76ba2213
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/modelWindowConfirmation.test.ts
@@ -0,0 +1,112 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { setModelWithWindowConfirmation } from '../lib/modelWindowConfirmation';
+
+const pressure = {
+ deferred: false,
+ superseded: false,
+ contextWindowConfirmationRequired: 200_000,
+ contextTokensForConfirmation: 180_000,
+};
+
+describe('Claude subscription model-window confirmation', () => {
+ it('gates the subscription recovery route before persistence and retry', () => {
+ const source = readFileSync(new URL('../CCAgentSessionView.tsx', import.meta.url), 'utf8');
+ const start = source.indexOf('const handleSwitchToClaudeSubscription = useCallback');
+ const end = source.indexOf('const handleSilentStopContinue', start);
+ const handler = source.slice(start, end);
+
+ expect(handler).toContain('setModelWithWindowConfirmation({');
+ expect(handler).toContain('confirmedContextWindow');
+ expect(handler).toContain('(EFFORT_VALUES as readonly string[]).includes(session.effort)');
+ expect(handler).toContain(': null;');
+ expect(handler).toContain('effort: retryEffort,');
+ expect(handler).not.toContain('effort: session.effort');
+ expect(handler.indexOf('if (!switched) return;')).toBeLessThan(
+ handler.indexOf('sessionService.update(sessionId'),
+ );
+ expect(handler.indexOf('sessionService.update(sessionId')).toBeLessThan(
+ handler.indexOf('retryLastError()'),
+ );
+ });
+
+ it('keeps the ordinary route when Main reports no destructive pressure', async () => {
+ const invoke = vi.fn().mockResolvedValue({ deferred: false, superseded: false });
+ await expect(
+ setModelWithWindowConfirmation({ invoke, confirm: async () => true }),
+ ).resolves.toBe('applied');
+ expect(invoke).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry or apply when the first 1M to 200K pressure is cancelled', async () => {
+ const invoke = vi.fn().mockResolvedValue(pressure);
+ const confirm = vi.fn().mockResolvedValue(false);
+
+ await expect(setModelWithWindowConfirmation({ invoke, confirm })).resolves.toBe(false);
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledWith();
+ expect(confirm).toHaveBeenCalledWith({ contextWindow: 200_000, contextTokens: 180_000 });
+ });
+
+ it('retries only with the exact confirmed target window', async () => {
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce(pressure)
+ .mockResolvedValueOnce({ deferred: false, superseded: false });
+
+ await expect(
+ setModelWithWindowConfirmation({ invoke, confirm: async () => true }),
+ ).resolves.toBe('confirmed');
+ expect(invoke.mock.calls).toEqual([[], [200_000]]);
+ });
+
+ it('fails closed when the final window drifts before the confirmed retry', async () => {
+ const invoke = vi.fn().mockResolvedValueOnce(pressure).mockResolvedValueOnce({
+ deferred: false,
+ superseded: false,
+ contextWindowConfirmationRequired: 180_000,
+ contextTokensForConfirmation: 180_000,
+ });
+
+ await expect(
+ setModelWithWindowConfirmation({ invoke, confirm: async () => true }),
+ ).resolves.toBe(false);
+ });
+
+ it('fails closed on malformed confirmation facts and propagated busy/unknown errors', async () => {
+ await expect(
+ setModelWithWindowConfirmation({
+ invoke: async () => ({
+ deferred: false,
+ superseded: false,
+ contextWindowConfirmationRequired: 200_000,
+ }),
+ confirm: async () => true,
+ }),
+ ).rejects.toThrow('verified model-window confirmation is invalid');
+
+ await expect(
+ setModelWithWindowConfirmation({
+ invoke: async () => undefined,
+ confirm: async () => true,
+ }),
+ ).rejects.toThrow('did not return an applied result');
+ await expect(
+ setModelWithWindowConfirmation({
+ invoke: async () => ({ deferred: true, superseded: false }),
+ confirm: async () => true,
+ }),
+ ).rejects.toThrow('did not return an applied result');
+
+ const busy = new Error('wait for the current turn');
+ await expect(
+ setModelWithWindowConfirmation({
+ invoke: async () => {
+ throw busy;
+ },
+ confirm: async () => true,
+ }),
+ ).rejects.toBe(busy);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/modelWindowConfirmation.ts b/apps/desktop/src/renderer/features/cc-agent/lib/modelWindowConfirmation.ts
new file mode 100644
index 0000000000..d5f218cd86
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/modelWindowConfirmation.ts
@@ -0,0 +1,41 @@
+export interface ModelWindowConfirmationResult {
+ deferred: boolean;
+ superseded?: boolean;
+ contextWindowConfirmationRequired?: number;
+ contextTokensForConfirmation?: number;
+}
+
+interface ConfirmedModelSwitchOptions {
+ invoke(confirmedContextWindow?: number): Promise<ModelWindowConfirmationResult | undefined>;
+ confirm(input: { contextWindow: number; contextTokens: number }): Promise<boolean>;
+}
+
+function confirmationFromResult(result: ModelWindowConfirmationResult | undefined): {
+ contextWindow: number;
+ contextTokens: number;
+} | null {
+ if (!result || result.deferred !== false || result.superseded !== false)
+ throw new Error('model-window switch did not return an applied result');
+ const contextWindow = result.contextWindowConfirmationRequired;
+ const contextTokens = result.contextTokensForConfirmation;
+ if (contextWindow === undefined && contextTokens === undefined) return null;
+ const validWindow =
+ typeof contextWindow === 'number' && Number.isSafeInteger(contextWindow) && contextWindow > 0;
+ const validTokens =
+ typeof contextTokens === 'number' && Number.isFinite(contextTokens) && contextTokens > 0;
+ if (!validWindow || !validTokens)
+ throw new Error('verified model-window confirmation is invalid');
+ return { contextWindow, contextTokens };
+}
+
+/** First call only discovers pressure; an exact-window retry may perform the rebuild. */
+export async function setModelWithWindowConfirmation(
+ options: ConfirmedModelSwitchOptions,
+): Promise<'applied' | 'confirmed' | false> {
+ const confirmation = confirmationFromResult(await options.invoke());
+ if (!confirmation) return 'applied';
+ if (!(await options.confirm(confirmation))) return false;
+ return confirmationFromResult(await options.invoke(confirmation.contextWindow)) === null
+ ? 'confirmed'
+ : false;
+}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCompactionSettings.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCompactionSettings.test.ts
index 9dc0bc9531..84f4adcdce 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCompactionSettings.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCompactionSettings.test.ts
@@ -19,13 +19,13 @@ describe('useCompactionSettings', () => {
const piCompactionSetPct = vi.fn().mockResolvedValue({
pct: 80,
isCustomized: true,
- defaultPct: 75,
+ defaultPct: 90,
});
const maker = {
piCompactionGetState: vi.fn().mockResolvedValue({
- pct: 75,
+ pct: 90,
isCustomized: false,
- defaultPct: 75,
+ defaultPct: 90,
}),
piCompactionSetPct,
piCompactionResetPct: vi.fn(),
diff --git a/apps/desktop/src/renderer/hooks/useCompactionSettings.ts b/apps/desktop/src/renderer/hooks/useCompactionSettings.ts
index 570446c1aa..dd59f042c2 100644
--- a/apps/desktop/src/renderer/hooks/useCompactionSettings.ts
+++ b/apps/desktop/src/renderer/hooks/useCompactionSettings.ts
@@ -7,7 +7,7 @@ const log = createLogger('UseCompactionSettings');
// main (compaction-settings-store) 是 clamp 的唯一 source of truth: IPC 返回值已是
// [50,95] 内的合法整数, Slider 也用 min/max/step 约束输入。
-const DEFAULT_PCT = 75;
+const DEFAULT_PCT = 90;
const WRITE_DEBOUNCE_MS = 300;
export type CompactionAgent = 'claude' | 'pi';
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 9f1e5e0917..c251ef8323 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7319,7 +7319,7 @@
"title": "This model can't fit the current conversation",
"warnToast": "This conversation already uses {{used}} — about {{pct}}% of the new model's {{total}} capacity",
"overflowDescription": "This conversation already uses {{used}}, more than the new model can hold ({{total}}, about {{pct}}%). If you switch, Cindy will make a short summary and continue. Your chat history stays; it just won't all be passed through verbatim.",
- "overflowDescriptionRemote": "This conversation already uses {{used}}, more than the new model can hold ({{total}}, about {{pct}}%). On a remote session Cindy cannot rebuild a fresh agent context, so the next request may still fail. You can switch anyway, or keep this model.",
+ "overflowDescriptionRemote": "This remote task already uses {{used}} / {{total}} of the smaller model's context (about {{pct}}%), so Cindy cannot switch safely. Keep the current model or start a new task before choosing this model.",
"confirmSwitch": "Switch and continue",
"cancelSwitch": "Keep this model"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9f04793763..f0a8f32124 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7311,7 +7311,7 @@
"title": "このモデルには今の会話が収まりません",
"warnToast": "この会話はすでに {{used}} 使っています。切替後は新しいモデルの容量({{total}})の約 {{pct}}% になります",
"overflowDescription": "この会話はすでに {{used}} 使っており、新しいモデルが扱える {{total}}(約 {{pct}}%)を超えています。切り替えると、Cindy が要約してから続けます。チャット履歴は残りますが、全文をそのままは渡しません。",
- "overflowDescriptionRemote": "この会話はすでに {{used}} 使っており、新しいモデルが扱える {{total}}(約 {{pct}}%)を超えています。リモートのタスクでは自動的に新しいエージェント文脈へ引き継げないため、次の送信が失敗する可能性があります。このまま切り替えるか、今のモデルのままにしてください。",
+ "overflowDescriptionRemote": "このリモートタスクのコンテキストは、小さいモデルの {{total}} に対して {{used}}(約 {{pct}}%)を使用しているため、安全に切り替えられません。現在のモデルを維持するか、新しいタスクを作成してからこのモデルを選択してください。",
"confirmSwitch": "切り替えて続ける",
"cancelSwitch": "今は切り替えない"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 202a2cfce8..361faefa06 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7311,7 +7311,7 @@
"title": "이 모델에는 지금 대화를 다 넣을 수 없습니다",
"warnToast": "이 대화는 이미 {{used}}를 사용 중입니다. 바꾸면 새 모델 용량({{total}})의 약 {{pct}}%가 됩니다",
"overflowDescription": "이 대화는 이미 {{used}}를 사용 중이며, 새 모델이 담을 수 있는 {{total}}(약 {{pct}}%)를 넘습니다. 바꾸면 Cindy가 요약을 만든 뒤 이어서 진행합니다. 채팅 기록은 그대로 있고, 전체를 그대로 넘기지는 않습니다.",
- "overflowDescriptionRemote": "이 대화는 이미 {{used}}를 사용 중이며, 새 모델이 담을 수 있는 {{total}}(약 {{pct}}%)를 넘습니다. 원격 작업에서는 자동으로 새 에이전트 문맥을 이어갈 수 없어 다음 요청이 실패할 수 있습니다. 그대로 바꾸거나 현재 모델을 유지하세요.",
+ "overflowDescriptionRemote": "이 원격 작업의 컨텍스트는 더 작은 모델의 {{total}} 중 {{used}}(약 {{pct}}%)를 사용 중이므로 안전하게 전환할 수 없습니다. 현재 모델을 유지하거나 새 작업을 만든 뒤 이 모델을 선택하세요.",
"confirmSwitch": "바꾸고 계속하기",
"cancelSwitch": "지금은 바꾸지 않기"
},
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 4d731c199c..6c1af75962 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7303,7 +7303,7 @@
"title": "这个模型装不下当前对话",
"warnToast": "这段对话已经用了 {{used}},换过去大约会占新模型容量({{total}})的 {{pct}}%",
"overflowDescription": "这段对话已经用了 {{used}},超过新模型能放下的 {{total}}(约 {{pct}}%)。换过去后,Cindy 会先整理一份摘要再继续;对话记录还在,只是不会整段原样带给新模型。",
- "overflowDescriptionRemote": "这段对话已经用了 {{used}},超过新模型能放下的 {{total}}(约 {{pct}}%)。远程任务不会自动换窗,下一次发送仍可能失败。可以仍然切换,或留在当前模型。",
+ "overflowDescriptionRemote": "当前远程任务的上下文已用 {{used}} / {{total}}(约 {{pct}}%),无法安全切换到这个小窗口模型。请保留当前模型,或新建任务后再选择。",
"confirmSwitch": "切换并继续",
"cancelSwitch": "先不换"
},
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 6c17ac84de..f871bbcaa7 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7303,7 +7303,7 @@
"title": "這個模型裝不下目前的對話",
"warnToast": "這段對話已經用了 {{used}},換過去大約會佔新模型容量({{total}})的 {{pct}}%",
"overflowDescription": "這段對話已經用了 {{used}},超過新模型能放下的 {{total}}(約 {{pct}}%)。換過去後,Cindy 會先整理一份摘要再繼續;對話記錄還在,只是不會整段原樣帶給新模型。",
- "overflowDescriptionRemote": "這段對話已經用了 {{used}},超過新模型能放下的 {{total}}(約 {{pct}}%)。遠端任務不會自動換窗,下一次傳送仍可能失敗。可以仍然切換,或留在目前模型。",
+ "overflowDescriptionRemote": "目前遠端任務的上下文已用 {{used}} / {{total}}(約 {{pct}}%),無法安全切換到這個小視窗模型。請保留目前模型,或新增任務後再選擇。",
"confirmSwitch": "切換並繼續",
"cancelSwitch": "先不換"
},
diff --git a/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts
index 0688321794..6e766b21b7 100644
--- a/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/providerModelEfforts.test.ts
@@ -211,7 +211,11 @@ describe('resolveProviderModelEfforts', () => {
/resolveModelEfforts\(\s*newModelId,\s*effectiveSourceId,?\s*\)/,
);
expect(source.slice(providerChangeStart, providerChangeEnd)).toContain(
- '{ effort: eff, fastMode: restoredFast }',
+ 'setModelWithFinalWindowConfirmation(',
+ );
+ expect(source.slice(providerChangeStart, providerChangeEnd)).toContain('effort: eff,');
+ expect(source.slice(providerChangeStart, providerChangeEnd)).toContain(
+ 'fastMode: restoredFast,',
);
});
});
diff --git a/apps/desktop/src/renderer/lib/__tests__/providerModelsAgentKind.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerModelsAgentKind.test.ts
index eb45a1c751..05ffc08e2e 100644
--- a/apps/desktop/src/renderer/lib/__tests__/providerModelsAgentKind.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/providerModelsAgentKind.test.ts
@@ -2,7 +2,10 @@ import type { AgentKind, ProviderView } from '@cindy/model-providers';
import { describe, expect, it } from 'vitest';
import type { ModelDescriptor } from '@/hooks/useAgentCapabilities';
-import { resolveVisibleModelAgentKind } from '../providerModels';
+import {
+ resolveProviderModelContextWindow,
+ resolveVisibleModelAgentKind,
+} from '../providerModels';
const model = (id: string): ModelDescriptor => ({
id,
@@ -12,18 +15,23 @@ const model = (id: string): ModelDescriptor => ({
defaultEffort: 'high',
});
-const provider = (agent: AgentKind, models: ModelDescriptor[]): ProviderView =>
+const provider = (
+ agent: AgentKind,
+ models: ModelDescriptor[],
+ id: string = agent,
+): ProviderView =>
({
- id: agent,
- name: agent,
+ id,
+ name: id,
connected: true,
agents: [agent],
+ routing: { [agent]: {} },
models: {
[agent]: models.map((entry) => ({ ...entry, name: entry.displayName })),
},
}) as unknown as ProviderView;
-describe('resolveVisibleModelAgentKind', () => {
+describe('provider model routing helpers', () => {
const claude = model('claude-opus-4-7');
const codex = model('gpt-5.5');
@@ -64,6 +72,32 @@ describe('resolveVisibleModelAgentKind', () => {
).toBe('claude-code');
});
+ it('resolves duplicate model ids by provider route instead of first-wins order', () => {
+ const wide = { ...model('shared-model'), contextWindow: 1_000_000 };
+ const narrow = { ...model('shared-model'), contextWindow: 200_000 };
+ const providers = [
+ provider('claude-code', [wide], 'wide-source'),
+ provider('claude-code', [narrow], 'narrow-source'),
+ ];
+
+ expect(
+ resolveProviderModelContextWindow({
+ providers,
+ providerId: 'wide-source',
+ modelId: 'shared-model',
+ agentKind: 'claude-code',
+ }),
+ ).toBe(1_000_000);
+ expect(
+ resolveProviderModelContextWindow({
+ providers,
+ providerId: 'narrow-source',
+ modelId: 'shared-model',
+ agentKind: 'claude-code',
+ }),
+ ).toBe(200_000);
+ });
+
it('honors an explicitly filtered agent', () => {
expect(
resolveVisibleModelAgentKind({
diff --git a/apps/desktop/src/renderer/lib/providerModels.ts b/apps/desktop/src/renderer/lib/providerModels.ts
index 8576e9bccc..10032c0b53 100644
--- a/apps/desktop/src/renderer/lib/providerModels.ts
+++ b/apps/desktop/src/renderer/lib/providerModels.ts
@@ -28,6 +28,18 @@ import {
import type { AgentCapabilities, ModelDescriptor } from '@/hooks/useAgentCapabilities';
import { isSubscriptionDirectModel } from '../../shared/subscriptionModels';
+/** Resolve a context window by the complete runtime route, never a first-wins model id. */
+export function resolveProviderModelContextWindow(params: {
+ providers: ProviderView[];
+ providerId: string;
+ modelId: string;
+ agentKind: AgentKind;
+}): number | undefined {
+ const { providers, providerId, modelId, agentKind } = params;
+ const provider = providersForAgent(providers, agentKind).find((entry) => entry.id === providerId);
+ return findCatalogModel(provider, modelId, agentKind)?.contextWindow;
+}
+
/**
* 按目标 `(provider, agent, model)` 读取 effort 能力。
*
diff --git a/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts b/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts
index 6595cc6651..4b30b4091a 100644
--- a/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts
+++ b/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts
@@ -2,9 +2,47 @@ import { describe, expect, it } from 'vitest';
import {
assessModelSwitchContext,
+ shouldBlockLegacyRemotePiModelWindowSwitch,
shouldHandoffAfterContextAssessment,
} from '../modelSwitchAssessment';
+describe('legacy remote Pi model-window guard', () => {
+ const legacyPiSwitch = {
+ hostGuardSupported: false,
+ contextTokens: 180_000,
+ currentContextWindow: 1_000_000,
+ targetContextWindow: 200_000,
+ };
+
+ it('blocks every old-host Pi route estimate', () => {
+ const estimatedRoutes = {
+ lowPressure: { ...legacyPiSwitch, contextTokens: 100_000 },
+ exact90Percent: legacyPiSwitch,
+ sameWindow: { ...legacyPiSwitch, targetContextWindow: 1_000_000 },
+ expansion: { ...legacyPiSwitch, targetContextWindow: 2_000_000 },
+ unknownUsage: { ...legacyPiSwitch, contextTokens: undefined },
+ unknownCurrentWindow: { ...legacyPiSwitch, currentContextWindow: undefined },
+ unknownTargetWindow: { ...legacyPiSwitch, targetContextWindow: undefined },
+ };
+ for (const route of Object.values(estimatedRoutes)) {
+ expect(shouldBlockLegacyRemotePiModelWindowSwitch(route)).toBe(true);
+ }
+ });
+
+ it('delegates guarded Pi routes to host-side final runtime verification', () => {
+ expect(shouldBlockLegacyRemotePiModelWindowSwitch({
+ ...legacyPiSwitch,
+ hostGuardSupported: true,
+ })).toBe(false);
+ expect(shouldBlockLegacyRemotePiModelWindowSwitch({
+ hostGuardSupported: true,
+ contextTokens: undefined,
+ currentContextWindow: undefined,
+ targetContextWindow: undefined,
+ })).toBe(false);
+ });
+});
+
describe('assessModelSwitchContext', () => {
it('fail-open: unknown context tokens → ok', () => {
expect(
diff --git a/apps/desktop/src/shared/modelSwitchAssessment.ts b/apps/desktop/src/shared/modelSwitchAssessment.ts
index 6e516047c8..c61aeac9f5 100644
--- a/apps/desktop/src/shared/modelSwitchAssessment.ts
+++ b/apps/desktop/src/shared/modelSwitchAssessment.ts
@@ -8,11 +8,12 @@
*
* - ok : 占用 < 70% —— 直接切
* - warn : 70% ≤ 占用 < 自动压缩阈值 —— 允许切, 轻提示
- * - danger : 自动压缩阈值 ≤ 占用 < 100% —— 允许切, 轻提示(切过去会立即触发自动压缩)
- * - overflow : 占用 ≥ 100% —— 弹确认;确认后由 host 交接换窗,而不是用新模型压缩
+ * - danger : 自动压缩阈值 ≤ 占用 < 100% —— host 先交接换窗,再切目标模型
+ * - overflow : 占用 ≥ 100% —— 确认后由 host 交接换窗,而不是用新模型压缩
*
- * danger 档阈值取用户当前的 auto-compact 触发百分比(设置页 50-95%), 语义统一为
- * "切过去就会立刻顶到压缩线"; 读不到 / 非法时回退 90。此时同样走交接,不再先 compact。
+ * danger 档默认 90%;调用方仍可为其他恢复场景传 50-95 的显式阈值。模型切换事务固定传
+ * `MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT`,不读取各 harness 的日常 auto-compact 设置。
+ * 命中时走交接,不再先 compact。
*
* fail-open 原则: 目标窗口未知(目录查不到)或当前占用未知(=0, 新会话 / 状态未回流)
* 时一律放行 —— 预检是护栏不是闸门, 缺数据时不能挡住用户操作。
@@ -27,7 +28,9 @@ export interface ModelSwitchContextAssessment {
}
const WARN_RATIO = 0.7;
-const DEFAULT_DANGER_PCT = 90;
+/** All harnesses use this target-window line for forced switch handoff/rebuild. */
+export const MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT = 90;
+const DEFAULT_DANGER_PCT = MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT;
// 与 maker-core AutoCompactController / 设置页 Slider 的合法区间一致。
const MIN_THRESHOLD_PCT = 50;
const MAX_THRESHOLD_PCT = 95;
@@ -41,6 +44,17 @@ export interface AssessModelSwitchContextInput {
autoCompactThresholdPct?: number;
}
+/** Mixed-version device-link Pi guard; this only vetoes unsafe switches and never rebuilds remotely. */
+export function shouldBlockLegacyRemotePiModelWindowSwitch(input: {
+ hostGuardSupported: boolean;
+ contextTokens: number | null | undefined;
+ currentContextWindow: number | null | undefined;
+ targetContextWindow: number | null | undefined;
+}): boolean {
+ // 旧 Host 无法通过 Pi set_model + get_state 裁决最终 runtime 窗口;目录估值不能放行。
+ return !input.hostGuardSupported;
+}
+
export function assessModelSwitchContext(
input: AssessModelSwitchContextInput,
): ModelSwitchContextAssessment {
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 48ac02a140..ea595d8232 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -175,6 +175,7 @@ import {
import {
buildSessionRuntimeOptions,
normalizeMobileAgentCapabilities,
+ reconcileRuntimeDraftWithCapabilities,
type MobileAgentCapabilities,
type MobileModelOption,
type MobileSessionRuntimeOptions,
@@ -186,6 +187,7 @@ import type { MobileModelMemoryAccessors } from '@/session/draftModelMemory';
import { ModelPickerSheet } from '@/session/ModelPickerSheet';
import { MobileModelIconMark } from '@/session/MobileProviderMark';
import { getModel } from '@cindy/model-providers/registry';
+import { shouldBlockLegacyRemoteModelWindowSwitch } from '@cindy/maker-shared/agent-capabilities';
import { clearSessionMirror, makeSessionMirrorAccessors } from '@/session/sessionModelMirror';
import { effortLabelFromRuntime, rowFastEditable } from '@/session/modelPickerRows';
import {
@@ -7641,7 +7643,7 @@ export default function SessionScreen() {
* 改为回读权威会话收敛乐观维度;回读也失败(多半同一网络故障)才退回本地回滚。
*/
const runControlAction = useCallback(async (
- action: () => Promise<void>,
+ action: () => Promise<void | boolean>,
optimisticPatch?: Partial<RemoteSession>,
opts?: { recover?: 'rollback' | 'refetch' },
) => {
@@ -7666,7 +7668,10 @@ export default function SessionScreen() {
remoteSessionStore.applySessionPatch(deviceId, sessionId, optimisticPatch);
}
try {
- await action();
+ const applied = await action();
+ if (applied === false && rollbackPatch && deviceId) {
+ remoteSessionStore.applySessionPatch(deviceId, sessionId, rollbackPatch);
+ }
} catch (err) {
if (rollbackPatch && optimisticPatch && deviceId) {
let recovered = false;
@@ -8072,6 +8077,72 @@ export default function SessionScreen() {
void runGoalAction(() => maker.goal.clear(sessionId), null);
}, [maker, runGoalAction, sessionId]);
+ const showRemoteModelWindowUnsupported = useCallback((
+ targetContextWindow: number | undefined,
+ fallbackDescription?: string,
+ ): void => {
+ const contextTokens = currentSession?.contextTokens;
+ const description =
+ typeof contextTokens === 'number' &&
+ Number.isFinite(contextTokens) &&
+ contextTokens > 0 &&
+ typeof targetContextWindow === 'number' &&
+ Number.isFinite(targetContextWindow) &&
+ targetContextWindow > 0
+ ? t('models.contextWindowSwitch.remoteDescription', {
+ used: formatModelWindowTokens(contextTokens),
+ total: formatModelWindowTokens(targetContextWindow),
+ pct: Math.round((contextTokens / targetContextWindow) * 100),
+ })
+ : fallbackDescription;
+ Alert.alert(t('models.contextWindowSwitch.remoteTitle'), description, [
+ { text: t('models.contextWindowSwitch.cancel'), style: 'cancel' },
+ ]);
+ }, [currentSession?.contextTokens, t]);
+
+ const setComposerModel = useCallback(async (args: {
+ model: string;
+ providerId?: string;
+ targetContextWindow?: number;
+ selection?: { effort: string | null; fastMode: boolean };
+ }): Promise<boolean> => {
+ if (shouldBlockLegacyRemoteModelWindowSwitch({
+ hostGuardSupported: modelSheetCapabilities?.supportsModelWindowSwitchGuard === true,
+ agentKind: sessionAgentKind,
+ contextTokens: currentSession?.contextTokens,
+ currentContextWindow: currentSession?.contextWindow,
+ targetContextWindow: args.targetContextWindow,
+ })) {
+ showRemoteModelWindowUnsupported(args.targetContextWindow);
+ return false;
+ }
+ try {
+ await maker.setModel(sessionId, args.model, args.providerId, args.selection);
+ return true;
+ } catch (err) {
+ const reason = formatRemoteError(err);
+ const isRemoteModelWindowUnsupported =
+ reason.includes('remote model-window rebuild is unsupported') ||
+ reason.includes('remote model-window confirmation is unsupported');
+ if (
+ !isPreconditionFailedRemoteError(err) ||
+ !isRemoteModelWindowUnsupported
+ ) {
+ throw err;
+ }
+ showRemoteModelWindowUnsupported(args.targetContextWindow, reason);
+ return false;
+ }
+ }, [
+ currentSession?.contextTokens,
+ currentSession?.contextWindow,
+ maker,
+ modelSheetCapabilities?.supportsModelWindowSwitchGuard,
+ sessionAgentKind,
+ sessionId,
+ showRemoteModelWindowUnsupported,
+ ]);
+
// 选行 = 原子切「来源 + 模型 + effort + fast」(effort 优先级与桌面同源:该 (来源,模型) 的
// 会话镜像记忆 → 沿用当前档 → 模型默认;同模型换来源不沿用;fast 按镜像恢复、fastEditable 门控)。
const selectComposerModelRow = useCallback((row: ProviderModelRow) => {
@@ -8096,26 +8167,38 @@ export default function SessionScreen() {
});
return;
}
- void runControlAction(async () => {
- await maker.setModel(sessionId, next.model, next.providerId);
- if (next.effort && next.effort !== modelSheetSelection.effort) {
- await maker.setEffort(sessionId, next.effort);
- }
- // 只按值变化写穿,不做 fastEditable 门控:切到不支持 fast 的模型时
- // resolveRowSelection 已算出 fastMode=false,门控会跳过清零、让服务端残留 true。
- if (next.fastMode !== modelSheetSelection.fastMode) {
- await maker.setFastMode(sessionId, next.fastMode);
- }
- }, {
- // 乐观 patch:原子切换的三个维度一次上屏。
- model: next.model,
- providerId: next.providerId,
- ...(next.effort ? { effort: next.effort } : {}),
- fastMode: next.fastMode,
- ...(agentSwitchIntent ? { agentSwitchIntent: null } : {}),
- // 多步 RPC(setModel → setEffort → setFastMode)可能部分成功,失败时回读权威
- // 会话收敛而非本地回滚,避免手机显示与远端已生效状态脱节(codex review R16)。
- }, { recover: 'refetch' });
+ const atomicSelection = modelSheetCapabilities?.supportsModelWindowSwitchGuard === true
+ ? { effort: next.effort || null, fastMode: next.fastMode }
+ : undefined;
+ void (async () => {
+ await runControlAction(async () => {
+ const applied = await setComposerModel({
+ model: next.model,
+ providerId: next.providerId,
+ targetContextWindow: row.model.contextWindow,
+ selection: atomicSelection,
+ });
+ if (!applied) return false;
+ // 新 host 在 SET_MODEL 的 session lock 内落定全部轴,再唤醒重建后的输入队列。
+ // 旧 host 不懂 selection,保留原有低压/same/expand 兼容链;90% 缩窗已在上方拒绝。
+ if (!atomicSelection && next.effort && next.effort !== modelSheetSelection.effort) {
+ await maker.setEffort(sessionId, next.effort);
+ }
+ // 只按值变化写穿,不做 fastEditable 门控:切到不支持 fast 的模型时
+ // resolveRowSelection 已算出 fastMode=false,门控会跳过清零、让服务端残留 true。
+ if (!atomicSelection && next.fastMode !== modelSheetSelection.fastMode) {
+ await maker.setFastMode(sessionId, next.fastMode);
+ }
+ }, {
+ // 乐观 patch:原子切换的三个维度一次上屏。
+ model: next.model,
+ providerId: next.providerId,
+ ...(next.effort ? { effort: next.effort } : {}),
+ fastMode: next.fastMode,
+ ...(agentSwitchIntent ? { agentSwitchIntent: null } : {}),
+ // 旧 host 的兼容 RPC 链可能部分成功;失败时回读权威会话收敛而非本地回滚。
+ }, { recover: 'refetch' });
+ })();
}, [
agentSwitchIntent,
canUseRemoteSessionControls,
@@ -8128,16 +8211,37 @@ export default function SessionScreen() {
sessionAgentKind,
sessionId,
sessionMirrorAccessors,
+ setComposerModel,
writeSessionAgentSwitchIntent,
]);
const selectComposerFlatModel = useCallback((option: MobileModelOption) => {
setModelSheetOpen(false);
if (!canUseRemoteSessionControls || modelSheetAgentKind !== sessionAgentKind) return;
- void runControlAction(() => maker.setModel(sessionId, option.id), {
+ const next = reconcileRuntimeDraftWithCapabilities({
model: option.id,
- ...(agentSwitchIntent ? { agentSwitchIntent: null } : {}),
- });
- }, [agentSwitchIntent, canUseRemoteSessionControls, maker, modelSheetAgentKind, runControlAction, sessionAgentKind, sessionId]);
+ effort: modelSheetSelection?.effort ?? '',
+ permissionMode: currentSession?.permissionMode ?? 'default',
+ fastMode: modelSheetSelection?.fastMode ?? false,
+ }, modelSheetCapabilities);
+ const atomicSelection = modelSheetCapabilities?.supportsModelWindowSwitchGuard === true
+ ? { effort: next.effort || null, fastMode: next.fastMode }
+ : undefined;
+ void (async () => {
+ await runControlAction(
+ () => setComposerModel({
+ model: option.id,
+ targetContextWindow: option.contextWindow,
+ selection: atomicSelection,
+ }),
+ {
+ model: option.id,
+ ...(atomicSelection?.effort ? { effort: atomicSelection.effort } : {}),
+ ...(atomicSelection ? { fastMode: atomicSelection.fastMode } : {}),
+ ...(agentSwitchIntent ? { agentSwitchIntent: null } : {}),
+ },
+ );
+ })();
+ }, [agentSwitchIntent, canUseRemoteSessionControls, currentSession?.permissionMode, modelSheetAgentKind, modelSheetCapabilities, modelSheetSelection?.effort, modelSheetSelection?.fastMode, runControlAction, sessionAgentKind, setComposerModel]);
const browseComposerModelAgent = useCallback(async (next: MobileSessionAgentKind) => {
if (next === modelSheetAgentKind) return true;
if (next !== sessionAgentKind) {
@@ -10599,6 +10703,12 @@ function ComposerActivityStatus({
);
}
+function formatModelWindowTokens(value: number): string {
+ return value >= 1_000_000
+ ? `${(value / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
+ : `${Math.round(value / 1_000)}K`;
+}
+
function formatComposerActivityElapsed(seconds: number): string {
const safeSeconds = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(safeSeconds / 60);
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index d7949bb996..9f1b2f5de4 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import {
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
@@ -285,6 +287,68 @@ describe('mobile maker transport', () => {
]);
});
+ it('does not advertise or emit the unimplemented model-window confirmation protocol', async () => {
+ const contextSource = readFileSync(
+ resolve(process.cwd(), 'src/device-link/DeviceLinkContext.tsx'),
+ 'utf8',
+ );
+ const transportSource = readFileSync(
+ resolve(process.cwd(), 'src/device-link/mobileMakerTransport.ts'),
+ 'utf8',
+ );
+ const { calls, maker } = harness();
+
+ await maker.setModel('s1', 'small-model', 'anthropic');
+
+ expect(contextSource).not.toContain('CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1');
+ expect(contextSource).not.toContain('model-window-confirmation-v1');
+ expect(transportSource).not.toContain('confirmedOverflow');
+ expect(transportSource).not.toContain('confirmedContextWindow');
+ expect(calls).toEqual([
+ {
+ deviceId: 'dev-1',
+ channel: 'maker:set-model',
+ args: ['s1', 'small-model', 'anthropic'],
+ },
+ ]);
+ });
+
+ it('sends model/provider/effort/Fast as one atomic set-model selection', async () => {
+ const { calls, maker } = harness();
+
+ await maker.setModel('s1', 'fixed-model', 'provider-a', {
+ effort: null,
+ fastMode: false,
+ });
+
+ expect(calls).toEqual([{
+ deviceId: 'dev-1',
+ channel: 'maker:set-model',
+ args: [
+ 's1',
+ 'fixed-model',
+ 'provider-a',
+ null,
+ { effort: null, fastMode: false },
+ ],
+ }]);
+ });
+
+ it('fails closed when a legacy Desktop returns model-window confirmation data', async () => {
+ const invoke: RemoteInvoke = async () => ({
+ deferred: false,
+ contextWindowConfirmationRequired: 272_000,
+ contextTokensForConfirmation: 244_800,
+ }) as never;
+ const maker = createMobileMakerTransport({ deviceId: 'dev-1', invoke });
+
+ await expect(maker.setModel('s1', 'pi-model')).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ });
+ });
+
it('routes runtime controls and queue operations with stable channel names', async () => {
const { calls, maker } = harness();
diff --git a/apps/mobile/src/__tests__/modelWindowSwitchConfirmation.test.ts b/apps/mobile/src/__tests__/modelWindowSwitchConfirmation.test.ts
new file mode 100644
index 0000000000..062cc1c0bb
--- /dev/null
+++ b/apps/mobile/src/__tests__/modelWindowSwitchConfirmation.test.ts
@@ -0,0 +1,78 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
+
+import { i18n } from "@/i18n";
+import { confirmMobileModelWindowSwitch } from "@/session/modelWindowSwitchConfirmation";
+
+beforeAll(async () => {
+ await i18n.changeLanguage("zh-CN");
+});
+
+describe("confirmMobileModelWindowSwitch", () => {
+ it("keeps unknown and below-capacity model switches unchanged", async () => {
+ const showAlert = vi.fn();
+
+ await expect(
+ confirmMobileModelWindowSwitch(199_999, 200_000, null, showAlert),
+ ).resolves.toBe(true);
+ await expect(
+ confirmMobileModelWindowSwitch(300_000, undefined, "ssh-host", showAlert),
+ ).resolves.toBe(true);
+ expect(showAlert).not.toHaveBeenCalled();
+ });
+
+ it("blocks overflow switches on cancel or dismiss", async () => {
+ const cancel = vi.fn((_title, _message, buttons) =>
+ buttons?.[0]?.onPress?.(),
+ );
+ await expect(
+ confirmMobileModelWindowSwitch(300_000, 272_000, null, cancel),
+ ).resolves.toBe(false);
+
+ const dismiss = vi.fn((_title, _message, _buttons, options) =>
+ options?.onDismiss?.(),
+ );
+ await expect(
+ confirmMobileModelWindowSwitch(300_000, 272_000, null, dismiss),
+ ).resolves.toBe(false);
+ });
+
+ it("allows overflow rebuild only after explicit confirmation", async () => {
+ const showAlert = vi.fn((_title, _message, buttons) =>
+ buttons?.[1]?.onPress?.(),
+ );
+
+ await expect(
+ confirmMobileModelWindowSwitch(300_000, 272_000, null, showAlert),
+ ).resolves.toBe(true);
+ expect(showAlert.mock.calls[0]?.[0]).toBe("这个模型装不下当前对话");
+ expect(showAlert.mock.calls[0]?.[1]).toContain("300K");
+ expect(showAlert.mock.calls[0]?.[1]).toContain("272K");
+ expect(showAlert.mock.calls[0]?.[1]).toContain("110%");
+ });
+
+ it("blocks pressured SSH switches without offering a continue action", async () => {
+ const showAlert = vi.fn((_title, _message, buttons) =>
+ buttons?.[0]?.onPress?.(),
+ );
+
+ await expect(
+ confirmMobileModelWindowSwitch(180_000, 200_000, "ssh-host", showAlert),
+ ).resolves.toBe(false);
+ expect(showAlert.mock.calls[0]?.[0]).toBe("当前远程任务无法安全切换模型");
+ expect(showAlert.mock.calls[0]?.[1]).toContain("无法安全切换");
+ expect(showAlert.mock.calls[0]?.[2]).toHaveLength(1);
+
+ const lowPressureAlert = vi.fn();
+ await expect(
+ confirmMobileModelWindowSwitch(
+ 179_999,
+ 200_000,
+ "ssh-host",
+ lowPressureAlert,
+ ),
+ ).resolves.toBe(true);
+ expect(lowPressureAlert).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
index 4881230119..5980c4b36c 100644
--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
@@ -26,4 +26,101 @@ describe('session Agent switch UI wiring', () => {
expect(source).toContain('selectedProviderId={modelSheetSelection.providerId}');
expect(source).toContain('agentKind={agentSwitchIntent.targetAgentKind}');
});
+
+ it('preflights legacy hosts and isolates only rebuild-unsupported preconditions', () => {
+ const source = readSource('app/sessions/[sessionId].tsx');
+ const rowSelector = source.slice(
+ source.indexOf('const selectComposerModelRow'),
+ source.indexOf('const selectComposerFlatModel'),
+ );
+ const flatSelector = source.slice(
+ source.indexOf('const selectComposerFlatModel'),
+ source.indexOf('const browseComposerModelAgent'),
+ );
+ const helperStart = source.indexOf('const setComposerModel = useCallback');
+ const alertHelper = source.slice(
+ source.indexOf('const showRemoteModelWindowUnsupported = useCallback'),
+ helperStart,
+ );
+ const helper = source.slice(
+ helperStart,
+ source.indexOf('// 选行 = 原子切', helperStart),
+ );
+ const controlAction = source.slice(
+ source.indexOf('const runControlAction = useCallback'),
+ source.indexOf('const writeSessionAgentSwitchIntent'),
+ );
+
+ const legacyGuard = helper.indexOf('shouldBlockLegacyRemoteModelWindowSwitch({');
+ const setModel = helper.indexOf(
+ 'await maker.setModel(sessionId, args.model, args.providerId, args.selection)',
+ );
+ expect(legacyGuard).toBeGreaterThan(-1);
+ expect(legacyGuard).toBeLessThan(setModel);
+ expect(helper.slice(legacyGuard, setModel)).toContain('return false;');
+ expect(helper).toContain(
+ 'hostGuardSupported: modelSheetCapabilities?.supportsModelWindowSwitchGuard === true',
+ );
+ expect(helper).toContain('agentKind: sessionAgentKind');
+ expect(helper).not.toContain('isSsh');
+ expect(helper).toContain('contextTokens: currentSession?.contextTokens');
+ expect(helper).toContain('currentContextWindow: currentSession?.contextWindow');
+ expect(helper).toContain('targetContextWindow: args.targetContextWindow');
+ expect(helper).toContain('showRemoteModelWindowUnsupported(args.targetContextWindow);');
+ expect(rowSelector).toContain(
+ 'modelSheetCapabilities?.supportsModelWindowSwitchGuard === true',
+ );
+ expect(rowSelector).toContain('selection: atomicSelection,');
+ expect(rowSelector).toContain('setComposerModel({');
+ expect(rowSelector).toContain('if (!applied) return false;');
+ expect(rowSelector).toContain('if (!atomicSelection && next.effort');
+ expect(rowSelector).toContain('if (!atomicSelection && next.fastMode');
+ expect(rowSelector.indexOf('if (!applied) return false;')).toBeLessThan(
+ rowSelector.indexOf('await maker.setEffort('),
+ );
+ expect(rowSelector.indexOf('if (!applied) return false;')).toBeLessThan(
+ rowSelector.indexOf('await maker.setFastMode('),
+ );
+ expect(rowSelector).toContain('targetContextWindow: row.model.contextWindow');
+ expect(flatSelector).toContain('reconcileRuntimeDraftWithCapabilities({');
+ expect(flatSelector).toContain(
+ 'modelSheetCapabilities?.supportsModelWindowSwitchGuard === true',
+ );
+ expect(flatSelector).toContain('targetContextWindow: option.contextWindow');
+ expect(flatSelector).toContain('selection: atomicSelection,');
+ expect(flatSelector).toContain(
+ 'atomicSelection?.effort ? { effort: atomicSelection.effort }',
+ );
+ expect(flatSelector).toContain('{ fastMode: atomicSelection.fastMode }');
+ expect(source).not.toContain('confirmMobileModelWindowSwitch');
+ expect(source).not.toContain('confirmComposerModelWindowSwitch');
+ expect(source).not.toContain('setComposerModelWithFinalWindowConfirmation');
+ expect(source).not.toContain('contextWindowConfirmationRequired');
+ expect(source).not.toContain('contextTokensForConfirmation');
+ expect(source).not.toContain('confirmedContextWindow');
+ expect(helper).toContain('const reason = formatRemoteError(err);');
+ expect(helper).toContain('const isRemoteModelWindowUnsupported =');
+ expect(helper).toContain("reason.includes('remote model-window rebuild is unsupported') ||");
+ expect(helper).toContain("reason.includes('remote model-window confirmation is unsupported')");
+ expect(helper).toContain('!isPreconditionFailedRemoteError(err) ||');
+ expect(helper).toContain('!isRemoteModelWindowUnsupported');
+ expect(helper).toContain('throw err;');
+ expect(helper).not.toContain('Alert.alert(reason);');
+ expect(helper).toContain(
+ 'showRemoteModelWindowUnsupported(args.targetContextWindow, reason);',
+ );
+ expect(alertHelper).toContain("t('models.contextWindowSwitch.remoteTitle')");
+ expect(alertHelper).toContain("t('models.contextWindowSwitch.remoteDescription', {");
+ expect(alertHelper).toContain('used: formatModelWindowTokens(contextTokens)');
+ expect(alertHelper).toContain('total: formatModelWindowTokens(targetContextWindow)');
+ expect(alertHelper).toContain('pct: Math.round((contextTokens / targetContextWindow) * 100)');
+ expect(alertHelper).toContain(': fallbackDescription;');
+ expect(alertHelper).toContain(
+ "{ text: t('models.contextWindowSwitch.cancel'), style: 'cancel' }",
+ );
+ expect(helper.match(/return false;/g)).toHaveLength(2);
+ expect(helper).not.toContain('setError(');
+ expect(controlAction).toContain('applied === false && rollbackPatch && deviceId');
+ expect(controlAction).toContain('setError(formatRemoteError(err));');
+ });
});
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index eb0fbd3185..b5e0e36f03 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -151,9 +151,10 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('testID="session.modelSheet"');
expect(source).not.toContain('composerOverlayPanel');
expect(source).toContain('onPress={toggleComposerModelPicker}');
- // 选行 fast 写穿只按值变化,不做 fastEditable 门控:切到不支持 fast 的模型时必须把
- // 服务端残留的 fastMode=true 清零(review P1 回归锚)。
- expect(source).toContain('if (next.fastMode !== modelSheetSelection.fastMode)');
+ // 新 host 把 fast 纳入原子 selection;旧 host 的兼容写穿仍只按值变化,不做
+ // fastEditable 门控,切到不支持 fast 的模型时必须把服务端残留的 true 清零。
+ expect(source).toContain('fastMode: next.fastMode');
+ expect(source).toContain('if (!atomicSelection && next.fastMode !== modelSheetSelection.fastMode)');
expect(source).not.toContain('fastEditable && next.fastMode');
// + 号打开可拖动 Context 面板(附件 / 计划模式 / 目标模式收在面板内)。
expect(source).toContain('testID="session.contextSheet"');
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 1578abc52b..e2da4dff09 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -427,7 +427,12 @@ export interface MobileMakerTransport {
* 切模型。可选第 3 参 providerId = 同时切来源(被控端按其路由 + 持久化 provider_id)。
* 不传 providerId = 老 2 参语义,不动会话当前来源选择。
*/
- setModel(sessionId: string, model: string, providerId?: string): Promise<void>;
+ setModel(
+ sessionId: string,
+ model: string,
+ providerId?: string,
+ selection?: { effort: string | null; fastMode: boolean },
+ ): Promise<{ deferred?: boolean; superseded?: boolean } | undefined>;
/** 登记跨 Agent 切换意图;真正切换在下一条消息发送时由 desktop main 执行。 */
switchSessionAgent(
sessionId: string,
@@ -681,8 +686,31 @@ export function createMobileMakerTransport({
send: (sessionId, message, createOpts, sendOpts) =>
call('maker:send', [sessionId, message, createOpts, sendOpts]),
listActiveSessions: () => call('maker:list-active'),
- setModel: (sessionId, model, providerId) =>
- call('maker:set-model', providerId ? [sessionId, model, providerId] : [sessionId, model]),
+ setModel: async (sessionId, model, providerId, selection) => {
+ const wireArgs = selection
+ ? [sessionId, model, providerId ?? null, null, selection]
+ : providerId
+ ? [sessionId, model, providerId]
+ : [sessionId, model];
+ const result = await call<{ deferred?: boolean; superseded?: boolean } | undefined>(
+ 'maker:set-model',
+ wireArgs,
+ );
+ if (
+ result !== null &&
+ typeof result === 'object' &&
+ ('contextWindowConfirmationRequired' in result ||
+ 'contextTokensForConfirmation' in result)
+ ) {
+ throw Object.assign(
+ new Error(
+ 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ ),
+ { code: 'PRECONDITION_FAILED' },
+ );
+ }
+ return result;
+ },
switchSessionAgent: (
sessionId,
targetAgentKind,
diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.json
index e98937f796..29386cc295 100644
--- a/apps/mobile/src/i18n/locales/en/models.json
+++ b/apps/mobile/src/i18n/locales/en/models.json
@@ -39,6 +39,14 @@
"ultra": "Ultra"
}
},
+ "contextWindowSwitch": {
+ "title": "This model can't fit the current conversation",
+ "remoteTitle": "This remote model switch isn't supported",
+ "description": "This conversation already uses {{used}}, more than the new model can hold ({{total}}, about {{pct}}%). If you switch, Cindy will make a short summary and continue. Your chat history stays; it just won't all be passed through verbatim.",
+ "remoteDescription": "This remote task already uses {{used}} / {{total}} of the smaller model's context (about {{pct}}%), so Cindy cannot switch safely. Keep the current model or start a new task before choosing this model.",
+ "cancel": "Keep this model",
+ "confirm": "Switch and continue"
+ },
"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 240a32f054..9d5de4816b 100644
--- a/apps/mobile/src/i18n/locales/ja/models.json
+++ b/apps/mobile/src/i18n/locales/ja/models.json
@@ -39,6 +39,14 @@
"ultra": "究極"
}
},
+ "contextWindowSwitch": {
+ "title": "このモデルには現在の会話が収まりません",
+ "remoteTitle": "このリモートタスクではモデルを安全に切り替えられません",
+ "description": "現在の会話はすでに {{used}} を使用しており、新しいモデルの上限 {{total}}(約 {{pct}}%)を超えています。切り替えると、Cindy は短い要約を作成して続行します。会話履歴は残りますが、すべてがそのまま新しいモデルに渡されるわけではありません。",
+ "remoteDescription": "このリモートタスクのコンテキストは、小さいモデルの {{total}} に対して {{used}}(約 {{pct}}%)を使用しているため、安全に切り替えられません。現在のモデルを維持するか、新しいタスクを作成してからこのモデルを選択してください。",
+ "cancel": "現在のモデルを維持",
+ "confirm": "切り替えて続行"
+ },
"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 6f4326b897..4cf288da68 100644
--- a/apps/mobile/src/i18n/locales/ko/models.json
+++ b/apps/mobile/src/i18n/locales/ko/models.json
@@ -39,6 +39,14 @@
"ultra": "극한"
}
},
+ "contextWindowSwitch": {
+ "title": "이 모델에는 현재 대화가 모두 들어가지 않습니다",
+ "remoteTitle": "이 원격 작업에서는 모델을 안전하게 전환할 수 없습니다",
+ "description": "현재 대화에서 이미 {{used}}를 사용해 새 모델의 한도 {{total}}(약 {{pct}}%)를 초과했습니다. 전환하면 Cindy가 짧은 요약을 만든 후 계속합니다. 대화 기록은 유지되지만 모든 내용이 새 모델에 그대로 전달되지는 않습니다.",
+ "remoteDescription": "이 원격 작업의 컨텍스트는 더 작은 모델의 {{total}} 중 {{used}}(약 {{pct}}%)를 사용 중이므로 안전하게 전환할 수 없습니다. 현재 모델을 유지하거나 새 작업을 만든 뒤 이 모델을 선택하세요.",
+ "cancel": "현재 모델 유지",
+ "confirm": "전환하고 계속"
+ },
"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 cb6431aae2..b9b59ff672 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/models.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json
@@ -39,6 +39,14 @@
"ultra": "极致"
}
},
+ "contextWindowSwitch": {
+ "title": "这个模型装不下当前对话",
+ "remoteTitle": "当前远程任务无法安全切换模型",
+ "description": "当前对话已使用 {{used}},超过新模型可容纳的 {{total}}(约 {{pct}}%)。继续切换时,Cindy 会先生成简短摘要再继续;对话记录仍会保留,但不会再逐字传给新模型。",
+ "remoteDescription": "当前远程任务的上下文已用 {{used}} / {{total}}(约 {{pct}}%),无法安全切换到这个小窗口模型。请保留当前模型,或新建任务后再选择。",
+ "cancel": "保留当前模型",
+ "confirm": "切换并继续"
+ },
"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 603765a31b..aa22497d26 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/models.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/models.json
@@ -39,6 +39,14 @@
"ultra": "極致"
}
},
+ "contextWindowSwitch": {
+ "title": "此模型無法容納目前對話",
+ "remoteTitle": "目前遠端任務無法安全切換模型",
+ "description": "目前對話已使用 {{used}},超過新模型可容納的 {{total}}(約 {{pct}}%)。若繼續切換,Cindy 會先產生簡短摘要再繼續;對話記錄仍會保留,但不會再逐字傳給新模型。",
+ "remoteDescription": "目前遠端任務的上下文已用 {{used}} / {{total}}(約 {{pct}}%),無法安全切換到這個小視窗模型。請保留目前模型,或新增任務後再選擇。",
+ "cancel": "保留目前模型",
+ "confirm": "切換並繼續"
+ },
"agentSwitch": {
"browseAccessibility": "瀏覽 {{agent}} 模型",
"confirmTitle": "切換到 {{agent}}?",
diff --git a/apps/mobile/src/session/modelWindowSwitchConfirmation.ts b/apps/mobile/src/session/modelWindowSwitchConfirmation.ts
new file mode 100644
index 0000000000..a13b69ac58
--- /dev/null
+++ b/apps/mobile/src/session/modelWindowSwitchConfirmation.ts
@@ -0,0 +1,90 @@
+/** Mobile confirmation gate before a smaller model window replaces native context. */
+import { Alert, type AlertButton, type AlertOptions } from "react-native";
+
+import { i18n } from "@/i18n";
+
+type ShowAlert = (
+ title: string,
+ message?: string,
+ buttons?: AlertButton[],
+ options?: AlertOptions,
+) => void;
+
+function formatTokens(value: number): string {
+ return value >= 1_000_000
+ ? `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`
+ : `${Math.round(value / 1_000)}K`;
+}
+
+/**
+ * Matches Desktop's switch boundary: pressured SSH sessions (usage >= 90% of the
+ * target) are blocked, while local overflow requires confirmation. Unknown values
+ * and ordinary low-pressure switches keep existing semantics.
+ */
+export function confirmMobileModelWindowSwitch(
+ contextTokens: number | null | undefined,
+ targetContextWindow: number | null | undefined,
+ remoteHostId: string | null | undefined,
+ showAlert: ShowAlert = Alert.alert,
+): Promise<boolean> {
+ if (
+ typeof contextTokens !== "number" ||
+ !Number.isFinite(contextTokens) ||
+ contextTokens <= 0 ||
+ typeof targetContextWindow !== "number" ||
+ !Number.isFinite(targetContextWindow) ||
+ targetContextWindow <= 0
+ ) {
+ return Promise.resolve(true);
+ }
+
+ const ratio = contextTokens / targetContextWindow;
+ const pressuredRemote = !!remoteHostId && ratio >= 0.9;
+ if (!pressuredRemote && ratio < 1) return Promise.resolve(true);
+
+ const vars = {
+ used: formatTokens(contextTokens),
+ total: formatTokens(targetContextWindow),
+ pct: Math.round(ratio * 100),
+ };
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (confirmed: boolean) => {
+ if (settled) return;
+ settled = true;
+ resolve(confirmed);
+ };
+ showAlert(
+ i18n.t(
+ pressuredRemote
+ ? "models.contextWindowSwitch.remoteTitle"
+ : "models.contextWindowSwitch.title",
+ ),
+ i18n.t(
+ pressuredRemote
+ ? "models.contextWindowSwitch.remoteDescription"
+ : "models.contextWindowSwitch.description",
+ vars,
+ ),
+ pressuredRemote
+ ? [
+ {
+ text: i18n.t("models.contextWindowSwitch.cancel"),
+ onPress: () => finish(false),
+ },
+ ]
+ : [
+ {
+ text: i18n.t("models.contextWindowSwitch.cancel"),
+ style: "cancel",
+ onPress: () => finish(false),
+ },
+ {
+ text: i18n.t("models.contextWindowSwitch.confirm"),
+ onPress: () => finish(true),
+ },
+ ],
+ { cancelable: true, onDismiss: () => finish(false) },
+ );
+ });
+}
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index b5c821e652..7b45117a1a 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -46,9 +46,15 @@ Cindy 保底压缩是**一套**流程,不是剥图 / 换窗两套功能。装
不另开一档:官方 compact 会先清旧工具结果;官方失败后交接不带 tool_result 正文。
可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时
由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援路径不得依赖额外模型调用。
-切模型预检的数学仍在 `assessModelSwitchContext`;确认切小窗后动作端应以
-`tokens='violated'` 调用同一决定走 rebuild,不再走独立 handoff(本版尚未并入)。
-token 破了只认:终态超限、占用 ≥ 100%、官方 compact 确定性失败;普通 timeout 不算。
+切模型预检的数学仍在 `assessModelSwitchContext`。同引擎切到更小窗口时,main 必须在
+set-model 与 send 共用的 session 锁内按目标窗口评估;Claude Code/Codex/Pi 的强制换窗线
+统一固定为目标窗口 90%,与各 harness 的日常 auto-compaction 百分比解耦;Claude Code
+与 Pi 的日常默认值也设为 90%,对齐 Codex 口径,但用户已有显式 override 继续生效。命中
+`danger`/`overflow` 的本机会话先走同一套 `context_rebuild` bounded handoff,再落目标
+route,不能 resume 旧原生窗口。
+正在运行的 turn、SSH 远端缺少本地交接能力、或已有恢复动作在途时必须 fail closed,不能
+先热切再发送。三个 harness 的同模型自动压缩所有权保持不变。token 破了只认:终态超限、
+占用 ≥ 100%、官方 compact 确定性失败;普通 timeout 不算。
Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断。stderr 仍只作诊断日志,
不得用 `remote compaction v2` 文案驱动恢复动作。普通 timeout、纯文本大历史和网络失败
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 071db10aa3..21ee07e34b 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -59,9 +59,14 @@ Cindy 显式设置:models.json、`settings.json` 的 `transport:sse` 与 `retry.
(`retry.provider.maxRetries` 保持 0)、`--append-system-prompt`、`--session-dir`、启动时 RPC
`set_auto_compaction{enabled:true}` / `set_thinking_level`。Pi 原生负责 threshold 与 overflow 压缩;
Cindy 消费 compaction 事件做 UI、usage、digest 投影,并只在本机原生自动压缩确定性失败后锁存
-下一次发送前换窗。设置页的 Pi 百分比在每次启动或恢复 Pi 任务时冻结,并写入该任务 `settings.json` 的
-`compaction.reserveTokens`(`window * (1 - pct/100)`);切模只按这份快照重算,不回读最新全局值。
-Claude Code 仍用独立百分比。env:`CINDY_PI_API_KEY`、
+下一次发送前换窗。设置页的 Pi 百分比默认 90%(已有显式 override 保留),在每次启动或恢复
+Pi 任务时冻结,并写入该任务 `settings.json` 的 `compaction.reserveTokens`
+(`window * (1 - pct/100)`);切模只按这份快照重算,不回读最新全局值。
+大窗切小窗先由 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`、
`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)。
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index 2f450dd47c..84958443b7 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -118,6 +118,10 @@ export const CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 = 'provider-logo-kinds
export const CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1 =
'set-model-explicit-provider-null-v1';
+/** 控制端会为有损模型换窗携带用户明确确认过的精确窗口。 */
+export const CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1 =
+ 'model-window-confirmation-v1';
+
/**
* 控制端能消费 `maker:event:batch` 微批帧(拆包后逐条按原路消费)。
* 被控端只对声明了本能力的控制端发批,未声明者照旧逐帧转发——旧控制端
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 306dc475d5..073d1115fe 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -404,6 +404,13 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
// 走的正是本模型,不标会在 send 前被 PiImageInputUnsupportedError 拒收。
supportsImageInput: true,
},
+ {
+ id: 'pi-test-small-model',
+ displayName: 'Pi Test Small Model',
+ contextWindow: 100_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
@@ -479,6 +486,42 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'keeps the target runtime after a context-window settings reload',
+ { timeout: 60_000 },
+ async () => {
+ const agent = new PiAgent(buildDeps());
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-model-reload-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ const requestsBefore = seenRequests.length;
+ try {
+ handle = await agent.startSession({
+ sessionId: 'itest-model-reload-session',
+ workingDir,
+ model: 'pi-test-model',
+ });
+ await handle.setModel?.('pi-test-small-model');
+ expect(handle.model).toBe('pi-test-small-model');
+ expect(handle.getUsageSnapshot().contextWindow).toBe(100_000);
+
+ const done = (async () => {
+ for await (const event of handle!.events()) {
+ if (event.type === 'done') return;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'after model switch' });
+ await done;
+
+ const request = seenRequests.slice(requestsBefore).at(-1);
+ expect(request).toBeDefined();
+ expect(JSON.parse(request!.body)).toMatchObject({ model: 'pi-test-small-model' });
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
it(
'keeps provider cindy and sends a gateway Responses model to /v1/responses',
{ timeout: 60_000 },
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 3edd317a0f..de150afac9 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
@@ -54,6 +54,10 @@ const captured = vi.hoisted(() => ({
onAfterSetModel: null as null | (() => void),
// 卡住 set_model 的回包,让测试能在"RPC 在飞"的那一刻观察盘上的路由快照。
holdSetModel: null as null | Promise<void>,
+ launchProvider: null as string | null,
+ launchModel: null as string | null,
+ runtimeProvider: null as string | null,
+ runtimeModel: null as string | null,
closed: false,
}));
@@ -66,6 +70,12 @@ vi.mock('../transport.js', () => ({
// spawn 参数断言移到 transport 工厂(spawn 行为在 stdio transport)。
captured.args = opts.args;
captured.env = opts.env;
+ const providerIndex = opts.args.indexOf('--provider');
+ const modelIndex = opts.args.indexOf('--model');
+ captured.launchProvider = providerIndex >= 0 ? (opts.args[providerIndex + 1] ?? null) : null;
+ captured.launchModel = modelIndex >= 0 ? (opts.args[modelIndex + 1] ?? null) : null;
+ captured.runtimeProvider = captured.launchProvider;
+ captured.runtimeModel = captured.launchModel;
opts.onProcessSpawned?.(1234);
return {
writeLine: async () => {},
@@ -101,6 +111,16 @@ vi.mock('../rpc-client.js', () => ({
captured.onAfterSetModel?.();
return { success: false };
}
+ if (cmd.type === 'set_model') {
+ captured.runtimeProvider = typeof cmd.provider === 'string' ? cmd.provider : null;
+ captured.runtimeModel = typeof cmd.modelId === 'string' ? cmd.modelId : null;
+ return { success: true, data: { contextWindow: 200_000 } };
+ }
+ if (cmd.type === 'switch_session') {
+ captured.runtimeProvider = captured.launchProvider;
+ captured.runtimeModel = captured.launchModel;
+ return { success: true, data: {} };
+ }
if (cmd.type === 'prompt' && captured.failPrompt) {
return { command: 'prompt', success: false };
}
@@ -121,7 +141,11 @@ vi.mock('../rpc-client.js', () => ({
captured.failNextGetState = false;
throw new Error('pi rpc timeout after 5000ms: get_state');
}
- return { success: true, data: { sessionFile: '/mock/session.jsonl', model: { contextWindow: 200000 },
+ return { success: true, data: { sessionFile: '/mock/session.jsonl', model: {
+ provider: captured.runtimeProvider,
+ id: captured.runtimeModel,
+ contextWindow: 200000,
+ },
isStreaming: false,
isCompacting: false,
pendingMessageCount: 0,
@@ -205,6 +229,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
captured.onPrompt = null;
captured.onAfterSetModel = null;
captured.holdSetModel = null;
+ captured.launchProvider = null;
+ captured.launchModel = null;
+ captured.runtimeProvider = null;
+ captured.runtimeModel = null;
captured.closed = false;
agentHome = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-home-'));
cwd = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-cwd-'));
@@ -750,6 +778,8 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
))).toBe(true));
const published = JSON.stringify({ response, events });
expect(published).toContain('restart-cindy-to-refresh-packages');
+ // The receipt is intentionally published before async runtime retirement.
+ // Wait for teardown instead of assuming both become observable in one tick.
await vi.waitFor(() => expect(captured.closed).toBe(true));
} finally {
await handle.close();
@@ -2773,9 +2803,11 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
release();
await Promise.all([first, second]);
- // 两次切换按调用序抵达 pi,终态是最后一次、且已确认。
+ // 两次切换按调用序抵达 Pi;每次 settings reload 都重放同一路由后才确认终态。
const setModelCalls = captured.requests.filter((r) => r.type === 'set_model');
- expect(setModelCalls.map((r) => r.modelId)).toEqual(['m-first', 'm-second']);
+ expect(setModelCalls.map((r) => r.modelId)).toEqual([
+ 'm-first', 'm-first', 'm-second', 'm-second',
+ ]);
const after = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;
expect(after.model).toBe('m-second');
expect(after.pending).toBeUndefined();
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 189ed4381b..65d3884579 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
@@ -14,6 +14,14 @@ const knobs = vi.hoisted(() => ({
rpcCalls: [] as Array<Record<string, unknown>>,
switchSessionSuccess: true,
autoCompactionSuccess: true,
+ runtimeProvider: "cindy",
+ runtimeModel: "m",
+ runtimeContextWindow: 200_000,
+ targetRuntimeContextWindow: 100_000,
+ setModelReportsContextWindow: true,
+ verifiedContextWindows: [] as number[],
+ closeCalls: 0,
+ stateModelOverride: null as null | string,
onEvent: null as
null | ((event: { type: string; [key: string]: unknown }) => void),
}));
@@ -55,7 +63,11 @@ vi.mock("../rpc-client.js", () => ({
success: true,
data: {
sessionFile: "/mock/s.jsonl",
- model: { contextWindow: 200_000 },
+ model: {
+ provider: knobs.runtimeProvider,
+ id: knobs.stateModelOverride ?? knobs.runtimeModel,
+ contextWindow: knobs.verifiedContextWindows.shift() ?? knobs.runtimeContextWindow,
+ },
},
};
}
@@ -70,17 +82,33 @@ vi.mock("../rpc-client.js", () => ({
: { success: false, error: "runtime rejected" };
}
if (cmd.type === "set_model") {
- return { success: true, data: { contextWindow: 100_000 } };
+ knobs.runtimeProvider = String(cmd.provider);
+ knobs.runtimeModel = String(cmd.modelId);
+ knobs.runtimeContextWindow = knobs.runtimeModel === "n"
+ ? knobs.targetRuntimeContextWindow
+ : 200_000;
+ return {
+ success: true,
+ data: knobs.setModelReportsContextWindow
+ ? { contextWindow: knobs.runtimeContextWindow }
+ : {},
+ };
}
if (cmd.type === "switch_session") {
- return knobs.switchSessionSuccess
- ? { success: true, data: {} }
- : { success: false, error: "reload denied" };
+ if (!knobs.switchSessionSuccess) {
+ return { success: false, error: "reload denied" };
+ }
+ // Real Pi reconstructs from the process' original CLI route.
+ knobs.runtimeProvider = "cindy";
+ knobs.runtimeModel = "m";
+ knobs.runtimeContextWindow = 200_000;
+ return { success: true, data: {} };
}
return { success: true, data: { entries: [] } };
}
send(): void {}
async close(): Promise<void> {
+ knobs.closeCalls += 1;
this.isClosed = true;
}
},
@@ -137,6 +165,14 @@ describe("PiAgent native auto-compaction ownership", () => {
knobs.rpcCalls = [];
knobs.switchSessionSuccess = true;
knobs.autoCompactionSuccess = true;
+ knobs.runtimeProvider = "cindy";
+ knobs.runtimeModel = "m";
+ knobs.runtimeContextWindow = 200_000;
+ knobs.targetRuntimeContextWindow = 100_000;
+ knobs.setModelReportsContextWindow = true;
+ knobs.verifiedContextWindows = [];
+ knobs.closeCalls = 0;
+ knobs.stateModelOverride = null;
knobs.onEvent = null;
agentHome = mkdtempSync(path.join(tmpdir(), "pi-native-ac-home-"));
cwd = mkdtempSync(path.join(tmpdir(), "pi-native-ac-cwd-"));
@@ -379,7 +415,94 @@ describe("PiAgent native auto-compaction ownership", () => {
expect(readLatestPiSettings().compaction?.reserveTokens).toBe(50_000);
await handle.setModel!("n");
expect(readLatestPiSettings().compaction?.reserveTokens).toBe(25_000);
- expect(knobs.rpcCalls.some((call) => call.type === "switch_session")).toBe(true);
+ const switchIndex = knobs.rpcCalls.findIndex((call) => call.type === "switch_session");
+ const setModelIndexes = knobs.rpcCalls
+ .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(knobs.runtimeProvider).toBe("cindy");
+ expect(knobs.runtimeModel).toBe("n");
+ expect(handle.getUsageSnapshot().contextWindow).toBe(100_000);
+ await handle.close();
+ });
+
+ it("recomputes reserve tokens from the final verified runtime window", async () => {
+ const deps = buildDeps();
+ deps.runtimeConfig = {
+ ...deps.runtimeConfig,
+ autoCompactThresholdPct: 90,
+ piAutoCompactThresholdPct: 90,
+ };
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: "s1",
+ workingDir: cwd,
+ model: "m",
+ });
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(20_000);
+
+ knobs.targetRuntimeContextWindow = 1_000_000;
+ knobs.setModelReportsContextWindow = false;
+ knobs.rpcCalls = [];
+ 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(handle.getUsageSnapshot().contextWindow).toBe(1_000_000);
+ await handle.close();
+ });
+
+ it("verifies a missing set_model window even when the catalog estimate is unchanged", async () => {
+ const deps = buildDeps();
+ deps.runtimeConfig = {
+ ...deps.runtimeConfig,
+ autoCompactThresholdPct: 90,
+ piAutoCompactThresholdPct: 90,
+ };
+ deps.capabilityAdditions = {
+ availableModels: deps.capabilityAdditions!.availableModels.map((model) =>
+ model.id === "n" ? { ...model, contextWindow: 200_000 } : model,
+ ),
+ };
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: "s1",
+ workingDir: cwd,
+ model: "m",
+ });
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(20_000);
+
+ knobs.setModelReportsContextWindow = false;
+ knobs.rpcCalls = [];
+ 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(handle.getUsageSnapshot().contextWindow).toBe(100_000);
+ await handle.close();
+ });
+
+ it("terminates when the runtime window changes again during settings verification", async () => {
+ const handle = await start();
+ knobs.targetRuntimeContextWindow = 1_000_000;
+ knobs.setModelReportsContextWindow = false;
+ knobs.verifiedContextWindows = [1_000_000, 500_000];
+
+ await expect(handle.setModel!("n")).rejects.toThrow(/未能重载压缩阈值/);
+ expect(knobs.closeCalls).toBe(1);
+ await handle.close();
+ });
+
+ it("terminates the session when the reloaded runtime does not confirm the target model", async () => {
+ const handle = await start();
+ knobs.stateModelOverride = "m";
+ await expect(handle.setModel!("n")).rejects.toThrow(/未能重载压缩阈值/);
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 81b845b073..2462982dd4 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
@@ -1,32 +1,49 @@
-import { createHash } from 'node:crypto';
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createHash } from "node:crypto";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.setConfig({ testTimeout: 30_000 });
-import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
-import { CINDY_SUBAGENT_EXTENSION_SOURCE } from '../cindy-subagent-source.js';
+import { CINDY_BRIDGE_EXTENSION_SOURCE } from "../cindy-bridge-source.js";
+import { CINDY_SUBAGENT_EXTENSION_SOURCE } from "../cindy-subagent-source.js";
const captured = vi.hoisted(() => ({
args: [] as string[],
env: {} as Record<string, string | undefined>,
requests: [] as Array<Record<string, unknown>>,
- requestOptions: [] as Array<{
- timeoutMs?: number;
- refreshTimeoutOnEvent?: (event: { type: string }) => boolean;
- } | undefined>,
+ requestOptions: [] as Array<
+ | {
+ timeoutMs?: number;
+ refreshTimeoutOnEvent?: (event: { type: string }) => boolean;
+ }
+ | undefined
+ >,
closes: 0,
- requestHandler: undefined as undefined | ((command: Record<string, unknown>) => Promise<{
- success: boolean;
- command?: unknown;
- data?: unknown;
- error?: string;
- }>),
+ initialProvider: undefined as string | undefined,
+ initialModel: undefined as string | undefined,
+ runtimeProvider: undefined as string | undefined,
+ runtimeModel: undefined as string | undefined,
+ requestHandler: undefined as
+ | undefined
+ | ((command: Record<string, unknown>) => Promise<{
+ success: boolean;
+ command?: unknown;
+ data?: unknown;
+ error?: string;
+ }>),
}));
-vi.mock('../transport.js', () => ({
+vi.mock("../transport.js", () => ({
createPiStdioTransport: (opts: {
args: string[];
env: Record<string, string | undefined>;
@@ -49,15 +66,15 @@ vi.mock('../transport.js', () => ({
attachJsonlReader: () => {},
}));
-vi.mock('../rpc-client.js', () => {
+vi.mock("../rpc-client.js", () => {
class PiRpcRequestTimeoutError extends Error {
- readonly code = 'PI_RPC_TIMEOUT';
+ readonly code = "PI_RPC_TIMEOUT";
constructor(
readonly commandType: string,
readonly timeoutMs: number,
) {
super(`pi rpc timeout after ${timeoutMs}ms: ${commandType}`);
- this.name = 'PiRpcRequestTimeoutError';
+ this.name = "PiRpcRequestTimeoutError";
}
}
return {
@@ -73,26 +90,77 @@ vi.mock('../rpc-client.js', () => {
) {
captured.requests.push(command);
captured.requestOptions.push(options);
- if (captured.requestHandler) return captured.requestHandler(command);
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ const argValue = (flag: string): string | undefined => {
+ const index = captured.args.indexOf(flag);
+ return index >= 0 ? captured.args[index + 1] : undefined;
+ };
+ captured.initialProvider ??= argValue("--provider");
+ captured.initialModel ??= argValue("--model");
+ captured.runtimeProvider ??= captured.initialProvider;
+ captured.runtimeModel ??= captured.initialModel;
+ const response = captured.requestHandler
+ ? await captured.requestHandler(command)
+ : command.type === "get_state"
+ ? {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ }
+ : { success: true, data: {} };
+ if (response.success && command.type === "set_model") {
+ captured.runtimeProvider = String(command.provider);
+ captured.runtimeModel = String(command.modelId);
+ } else if (response.success && command.type === "switch_session") {
+ captured.runtimeProvider = captured.initialProvider;
+ captured.runtimeModel = captured.initialModel;
}
- return { success: true, data: {} };
+ if (response.success && command.type === "get_state") {
+ const data = (response.data ?? {}) as Record<string, unknown>;
+ const model =
+ data.model && typeof data.model === "object"
+ ? (data.model as Record<string, unknown>)
+ : {};
+ return {
+ ...response,
+ data: {
+ ...data,
+ model: {
+ ...model,
+ provider: captured.runtimeProvider,
+ id: captured.runtimeModel,
+ },
+ },
+ };
+ }
+ return response;
}
send(): void {}
- async close(): Promise<void> { this.isClosed = true; captured.closes += 1; }
+ async close(): Promise<void> {
+ this.isClosed = true;
+ captured.closes += 1;
+ }
},
};
});
-import { PiAgent } from '../index.js';
-import { PiRpcRequestTimeoutError } from '../rpc-client.js';
-import { PiNativeProviderProxyNotReadyError, type AgentDeps } from '../../base-agent.js';
-import type { ModelDescriptor } from '../../../types/capabilities.js';
-import type { Logger } from '../../../interfaces/logger.js';
+import { PiAgent } from "../index.js";
+import { PiRpcRequestTimeoutError } from "../rpc-client.js";
+import {
+ PiNativeProviderProxyNotReadyError,
+ type AgentDeps,
+} from "../../base-agent.js";
+import type { ModelDescriptor } from "../../../types/capabilities.js";
+import type { Logger } from "../../../interfaces/logger.js";
const noopLogger: Logger = {
- trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
+ trace: () => {},
+ debug: () => {},
+ info: () => {},
+ warn: () => {},
+ error: () => {},
+ fatal: () => {},
child: () => noopLogger,
};
@@ -100,8 +168,11 @@ function testSubagentRunnerHost() {
const handle = {
pid: 4321,
killed: false,
- once(event: 'spawn' | 'error' | 'exit' | 'close', listener: (...args: unknown[]) => void) {
- if (event === 'spawn') queueMicrotask(listener);
+ once(
+ event: "spawn" | "error" | "exit" | "close",
+ listener: (...args: unknown[]) => void,
+ ) {
+ if (event === "spawn") queueMicrotask(listener);
return handle;
},
kill: () => true,
@@ -109,29 +180,38 @@ function testSubagentRunnerHost() {
return handle as never;
}
-describe('Pi provider-aware model routing', () => {
- let agentHome = '';
+describe("Pi provider-aware model routing", () => {
+ let agentHome = "";
/**
* runtime 文件名带每运行时 nonce(dev + 打包版 / passive 共用 userData 时的跨实例隔离),
* 所以按「前缀 + sessionId」找,不能再拼死名字。前缀含 sessionId → 不会串到别的用例。
*/
const runtimeFileOf = (prefix: string, sessionId: string): string => {
- const dir = path.join(agentHome, 'runtime');
- const name = readdirSync(dir).find((f) => f.startsWith(prefix + '-' + sessionId + '-'));
- if (!name) throw new Error('runtime file not found: ' + prefix + '-' + sessionId + '-*');
+ const dir = path.join(agentHome, "runtime");
+ const name = readdirSync(dir).find((f) =>
+ f.startsWith(prefix + "-" + sessionId + "-"),
+ );
+ if (!name)
+ throw new Error(
+ "runtime file not found: " + prefix + "-" + sessionId + "-*",
+ );
return path.join(dir, name);
};
- let cwd = '';
+ let cwd = "";
beforeEach(() => {
captured.args = [];
captured.requests = [];
captured.requestOptions = [];
captured.closes = 0;
+ captured.initialProvider = undefined;
+ captured.initialModel = undefined;
+ captured.runtimeProvider = undefined;
+ captured.runtimeModel = undefined;
captured.requestHandler = undefined;
- agentHome = mkdtempSync(path.join(tmpdir(), 'pi-provider-home-'));
- cwd = mkdtempSync(path.join(tmpdir(), 'pi-provider-cwd-'));
+ agentHome = mkdtempSync(path.join(tmpdir(), "pi-provider-home-"));
+ cwd = mkdtempSync(path.join(tmpdir(), "pi-provider-cwd-"));
});
afterEach(() => {
@@ -139,38 +219,54 @@ describe('Pi provider-aware model routing', () => {
rmSync(cwd, { recursive: true, force: true });
});
- it('uses providerId as the primary key when duplicate model ids exist', async () => {
+ it("uses providerId as the primary key when duplicate model ids exist", async () => {
const authProviderIds: Array<string | null | undefined> = [];
const apiResolver = vi.fn((providerId: string | null | undefined) =>
- providerId === 'openai' ? 'anthropic-messages' as const : 'openai-responses' as const,
+ providerId === "openai"
+ ? ("anthropic-messages" as const)
+ : ("openai-responses" as const),
+ );
+ const descriptorResolver = vi.fn(
+ (providerId: string | null | undefined, modelId: string) => ({
+ id: modelId,
+ displayName:
+ providerId === "openai" ? "Subscription Shared" : "XD Shared",
+ contextWindow: providerId === "openai" ? 128_000 : 200_000,
+ maxOutputTokens: providerId === "openai" ? 16_000 : 32_000,
+ cost:
+ providerId === "openai"
+ ? { input: 1, output: 2 }
+ : { input: 9, output: 10 },
+ efforts: [],
+ defaultEffort: null,
+ }),
);
- const descriptorResolver = vi.fn((providerId: string | null | undefined, modelId: string) => ({
- id: modelId,
- displayName: providerId === 'openai' ? 'Subscription Shared' : 'XD Shared',
- contextWindow: providerId === 'openai' ? 128_000 : 200_000,
- maxOutputTokens: providerId === 'openai' ? 16_000 : 32_000,
- cost: providerId === 'openai'
- ? { input: 1, output: 2 }
- : { input: 9, output: 10 },
- efforts: [],
- defaultEffort: null,
- }));
const deps: AgentDeps = {
auth: {
getState: async (options) => {
authProviderIds.push(options?.providerId);
- return { authenticated: true, identity: 'test', authSource: 'api-key' as const };
+ return {
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ };
},
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'shared-model', displayName: 'Shared', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ {
+ id: "shared-model",
+ displayName: "Shared",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
@@ -178,8 +274,20 @@ describe('Pi provider-aware model routing', () => {
resolvePiGatewayModelApi: apiResolver,
resolvePiNativeProviders: async () => ({
providers: [
- { id: 'native-a', name: 'Native A', baseUrl: 'http://a.test', api: 'openai-completions', models: [{ id: 'shared-model' }] },
- { id: 'native-b', name: 'Native B', baseUrl: 'http://b.test', api: 'openai-completions', models: [{ id: 'shared-model' }] },
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "shared-model" }],
+ },
+ {
+ id: "native-b",
+ name: "Native B",
+ baseUrl: "http://b.test",
+ api: "openai-completions",
+ models: [{ id: "shared-model" }],
+ },
],
env: {},
}),
@@ -188,207 +296,335 @@ describe('Pi provider-aware model routing', () => {
// 同名模型显式选 OpenAI 订阅时必须走 compat gateway,而不是被任一 BYOM 抢走。
const handle = await agent.startSession({
- sessionId: 'provider-routing',
+ sessionId: "provider-routing",
workingDir: cwd,
- model: 'shared-model',
- providerId: 'openai',
+ model: "shared-model",
+ providerId: "openai",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'cindy']);
- expect(authProviderIds).toEqual(['openai']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "cindy"]);
+ expect(authProviderIds).toEqual(["openai"]);
// models.json 现落在每会话隔离的 configHome(PI_CODING_AGENT_DIR),不再在共享 agentHome 根。
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as {
- providers: Record<string, {
- models: Array<{
- id: string;
- name?: string;
- api?: string;
- contextWindow?: number;
- maxTokens?: number;
- cost?: Record<string, number>;
- }>;
- }>;
+ providers: Record<
+ string,
+ {
+ models: Array<{
+ id: string;
+ name?: string;
+ api?: string;
+ contextWindow?: number;
+ maxTokens?: number;
+ cost?: Record<string, number>;
+ }>;
+ }
+ >;
};
- expect(apiResolver).toHaveBeenCalledWith('openai', 'shared-model', { remote: false });
- expect(descriptorResolver).toHaveBeenCalledWith('openai', 'shared-model');
- expect(models.providers.cindy?.models.find((model) => model.id === 'shared-model')).toMatchObject({
- name: 'Subscription Shared',
- api: 'anthropic-messages',
+ expect(apiResolver).toHaveBeenCalledWith("openai", "shared-model", {
+ remote: false,
+ });
+ expect(descriptorResolver).toHaveBeenCalledWith("openai", "shared-model");
+ expect(
+ models.providers.cindy?.models.find(
+ (model) => model.id === "shared-model",
+ ),
+ ).toMatchObject({
+ name: "Subscription Shared",
+ api: "anthropic-messages",
contextWindow: 128_000,
maxTokens: 16_000,
cost: { input: 1, output: 2 },
});
- expect(models.providers['native-a']?.models.some((model) => model.id === 'shared-model')).toBe(true);
- expect(models.providers['native-b']?.models.some((model) => model.id === 'shared-model')).toBe(true);
+ expect(
+ models.providers["native-a"]?.models.some(
+ (model) => model.id === "shared-model",
+ ),
+ ).toBe(true);
+ expect(
+ models.providers["native-b"]?.models.some(
+ (model) => model.id === "shared-model",
+ ),
+ ).toBe(true);
- await expect(handle.setModel!('shared-model', { providerId: 'xd' })).rejects.toThrow(
- /restart the Pi session to change provider API/,
- );
+ await expect(
+ handle.setModel!("shared-model", { providerId: "xd" }),
+ ).rejects.toThrow(/restart the Pi session to change provider API/);
expect(captured.requests).not.toContainEqual({
- type: 'set_model',
- provider: 'cindy',
- modelId: 'shared-model',
+ type: "set_model",
+ provider: "cindy",
+ modelId: "shared-model",
});
- await handle.setModel!('shared-model', { providerId: 'native-b' });
+ await handle.setModel!("shared-model", { providerId: "native-b" });
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'native-b',
- modelId: 'shared-model',
+ type: "set_model",
+ provider: "native-b",
+ modelId: "shared-model",
});
await handle.close();
const nativeHandle = await agent.startSession({
- sessionId: 'provider-routing-native',
+ sessionId: "provider-routing-native",
workingDir: cwd,
- model: 'shared-model',
- providerId: 'native-a',
+ model: "shared-model",
+ providerId: "native-a",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'native-a']);
- expect(authProviderIds).toEqual(['openai', 'native-a']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "native-a"]);
+ expect(authProviderIds).toEqual(["openai", "native-a"]);
await nativeHandle.close();
});
- it('uses explicit output caps and a context-bounded fallback for gateway and native models', async () => {
+ it("uses explicit output caps and a context-bounded fallback for gateway and native models", async () => {
const availableModels: ModelDescriptor[] = [
{
- id: 'gateway-fallback-model', displayName: 'Gateway fallback', contextWindow: 128_000,
- efforts: [], defaultEffort: null,
+ id: "gateway-fallback-model",
+ displayName: "Gateway fallback",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
},
{
- id: 'gateway-explicit-model', displayName: 'Gateway explicit', contextWindow: 200_000,
- maxOutputTokens: 90_000, efforts: [], defaultEffort: null,
+ id: "gateway-explicit-model",
+ displayName: "Gateway explicit",
+ contextWindow: 200_000,
+ maxOutputTokens: 90_000,
+ efforts: [],
+ defaultEffort: null,
},
{
- id: 'gateway-small-context-model', displayName: 'Gateway small context', contextWindow: 32_000,
- efforts: [], defaultEffort: null,
+ id: "gateway-small-context-model",
+ displayName: "Gateway small context",
+ contextWindow: 32_000,
+ efforts: [],
+ defaultEffort: null,
},
{
- id: 'native-fallback-model', displayName: 'Native fallback', contextWindow: 200_000,
- efforts: [], defaultEffort: null,
+ id: "native-fallback-model",
+ displayName: "Native fallback",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
},
{
- id: 'native-explicit-model', displayName: 'Native explicit', contextWindow: 200_000,
- efforts: [], defaultEffort: null,
+ id: "native-explicit-model",
+ displayName: "Native explicit",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
},
{
- id: 'native-small-context-model', displayName: 'Native small context', contextWindow: 32_000,
- efforts: [], defaultEffort: null,
+ id: "native-small-context-model",
+ displayName: "Native small context",
+ contextWindow: 32_000,
+ efforts: [],
+ defaultEffort: null,
},
];
- const descriptorResolver = (_providerId: string | null | undefined, modelId: string) =>
- availableModels.find((candidate) => candidate.id === modelId)!;
+ const descriptorResolver = (
+ _providerId: string | null | undefined,
+ modelId: string,
+ ) => availableModels.find((candidate) => candidate.id === modelId)!;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9988" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: { availableModels },
resolvePiAgentHome: () => agentHome,
resolvePiGatewayModelDescriptor: descriptorResolver,
- resolvePiGatewayModelApi: () => 'anthropic-messages',
+ resolvePiGatewayModelApi: () => "anthropic-messages",
resolvePiNativeProviders: async () => ({
- providers: [{
- id: 'native', name: 'Native', baseUrl: 'http://native.test', api: 'openai-completions',
- models: [
- { id: 'native-fallback-model', contextWindow: 200_000 },
- { id: 'native-explicit-model', contextWindow: 200_000, maxTokens: 90_000 },
- { id: 'native-small-context-model', contextWindow: 32_000 },
- ],
- }],
+ providers: [
+ {
+ id: "native",
+ name: "Native",
+ baseUrl: "http://native.test",
+ api: "openai-completions",
+ models: [
+ { id: "native-fallback-model", contextWindow: 200_000 },
+ {
+ id: "native-explicit-model",
+ contextWindow: 200_000,
+ maxTokens: 90_000,
+ },
+ { id: "native-small-context-model", contextWindow: 32_000 },
+ ],
+ },
+ ],
env: {},
}),
});
const gatewayHandle = await agent.startSession({
- sessionId: 'max-tokens-gateway', workingDir: cwd, model: 'gateway-fallback-model', providerId: 'openai',
+ sessionId: "max-tokens-gateway",
+ workingDir: cwd,
+ model: "gateway-fallback-model",
+ providerId: "openai",
});
const gatewayModels = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as { providers: Record<string, { models?: Array<Record<string, unknown>> }> };
- expect(gatewayModels.providers.cindy?.models).toEqual(expect.arrayContaining([
- expect.objectContaining({ id: 'gateway-fallback-model', maxTokens: 65_536 }),
- expect.objectContaining({ id: 'gateway-explicit-model', maxTokens: 90_000 }),
- expect.objectContaining({ id: 'gateway-small-context-model', maxTokens: 32_000 }),
- ]));
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<string, { models?: Array<Record<string, unknown>> }>;
+ };
+ expect(gatewayModels.providers.cindy?.models).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "gateway-fallback-model",
+ maxTokens: 65_536,
+ }),
+ expect.objectContaining({
+ id: "gateway-explicit-model",
+ maxTokens: 90_000,
+ }),
+ expect.objectContaining({
+ id: "gateway-small-context-model",
+ maxTokens: 32_000,
+ }),
+ ]),
+ );
await gatewayHandle.close();
const nativeHandle = await agent.startSession({
- sessionId: 'max-tokens-native', workingDir: cwd, model: 'native-fallback-model', providerId: 'native',
+ sessionId: "max-tokens-native",
+ workingDir: cwd,
+ model: "native-fallback-model",
+ providerId: "native",
});
const nativeModels = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as { providers: Record<string, { models?: Array<Record<string, unknown>> }> };
- expect(nativeModels.providers.native?.models).toEqual(expect.arrayContaining([
- expect.objectContaining({ id: 'native-fallback-model', maxTokens: 65_536 }),
- expect.objectContaining({ id: 'native-explicit-model', maxTokens: 90_000 }),
- expect.objectContaining({ id: 'native-small-context-model', maxTokens: 32_000 }),
- ]));
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<string, { models?: Array<Record<string, unknown>> }>;
+ };
+ expect(nativeModels.providers.native?.models).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "native-fallback-model",
+ maxTokens: 65_536,
+ }),
+ expect.objectContaining({
+ id: "native-explicit-model",
+ maxTokens: 90_000,
+ }),
+ expect.objectContaining({
+ id: "native-small-context-model",
+ maxTokens: 32_000,
+ }),
+ ]),
+ );
await nativeHandle.close();
});
- it('routes host subscriptions through PI native providers and wire model ids', async () => {
+ it("routes host subscriptions through PI native providers and wire model ids", async () => {
const authProviderIds: Array<string | null | undefined> = [];
let resolveProxyProviderId: (() => string | null) | undefined;
const proxyRegistrations: Array<{
token: string;
providerId: string | null;
- scope?: 'session' | 'subagent-route';
+ scope?: "session" | "subagent-route";
}> = [];
const availableModels: ModelDescriptor[] = [
{
- id: 'chatgpt/gpt-cindy-daily-test', displayName: 'GPT Daily', contextWindow: 272_000,
- efforts: ['low', 'high'], defaultEffort: 'high',
+ id: "chatgpt/gpt-cindy-daily-test",
+ displayName: "GPT Daily",
+ contextWindow: 272_000,
+ efforts: ["low", "high"],
+ defaultEffort: "high",
},
{
- id: 'chatgpt/gpt-5.6-luna', displayName: 'GPT 5.6 Luna', contextWindow: 272_000,
- efforts: ['medium'], defaultEffort: 'medium',
+ id: "chatgpt/gpt-5.6-luna",
+ displayName: "GPT 5.6 Luna",
+ contextWindow: 272_000,
+ efforts: ["medium"],
+ defaultEffort: "medium",
},
{
- id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 1_000_000,
- efforts: ['high'], defaultEffort: 'high',
+ id: "xai/grok-4.5",
+ displayName: "Grok 4.5",
+ contextWindow: 1_000_000,
+ efforts: ["high"],
+ defaultEffort: "high",
},
{
- id: 'xai/grok-4.20', displayName: 'Grok 4.20', contextWindow: 1_000_000,
- efforts: ['high'], defaultEffort: 'high',
+ id: "xai/grok-4.20",
+ displayName: "Grok 4.20",
+ contextWindow: 1_000_000,
+ efforts: ["high"],
+ defaultEffort: "high",
},
{
- id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 1_000_000,
- efforts: ['medium'], defaultEffort: 'medium',
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 1_000_000,
+ efforts: ["medium"],
+ defaultEffort: "medium",
},
{
- id: 'claude-opus-5', displayName: 'Claude Opus 5', contextWindow: 1_000_000,
- efforts: ['high'], defaultEffort: 'high',
+ id: "claude-opus-5",
+ displayName: "Claude Opus 5",
+ contextWindow: 1_000_000,
+ efforts: ["high"],
+ defaultEffort: "high",
},
];
const deps: AgentDeps = {
auth: {
getState: async (options) => {
authProviderIds.push(options?.providerId);
- return { authenticated: true, identity: 'test', authSource: 'oauth' as const };
+ return {
+ authenticated: true,
+ identity: "test",
+ authSource: "oauth" as const,
+ };
},
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9988" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: { availableModels },
resolvePiAgentHome: () => agentHome,
spawnPiSubagentRunner: testSubagentRunnerHost,
- resolvePiGatewayModelApi: () => 'openai-responses',
- registerPiProxySession: (_sessionId, token, resolveProviderId, options) => {
- if (options?.scope !== 'subagent-route') resolveProxyProviderId = resolveProviderId;
+ resolvePiGatewayModelApi: () => "openai-responses",
+ registerPiProxySession: (
+ _sessionId,
+ token,
+ resolveProviderId,
+ options,
+ ) => {
+ if (options?.scope !== "subagent-route")
+ resolveProxyProviderId = resolveProviderId;
proxyRegistrations.push({
token,
providerId: resolveProviderId(),
@@ -398,304 +634,400 @@ describe('Pi provider-aware model routing', () => {
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'anthropic', sourceProviderId: 'anthropic', name: 'Anthropic',
- baseUrl: 'http://127.0.0.1:9988', inheritModels: true,
+ id: "anthropic",
+ sourceProviderId: "anthropic",
+ name: "Anthropic",
+ baseUrl: "http://127.0.0.1:9988",
+ inheritModels: true,
headers: {
- 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
- 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
- 'x-cindy-pi-provider-id': 'anthropic',
+ "x-cindy-pi-session-id": "$CINDY_PI_SESSION_ID",
+ "x-cindy-pi-session-token": "$CINDY_PI_SESSION_TOKEN",
+ "x-cindy-pi-provider-id": "anthropic",
},
- models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],
+ models: [{ id: "claude-opus-5", wireId: "claude-opus-5" }],
},
{
- id: 'openai-codex', sourceProviderId: 'openai', name: 'OpenAI',
- baseUrl: 'http://127.0.0.1:9988', inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_OPENAI_PROXY_KEY',
+ id: "openai-codex",
+ sourceProviderId: "openai",
+ name: "OpenAI",
+ baseUrl: "http://127.0.0.1:9988",
+ inheritModels: true,
+ apiKeyEnvVar: "CINDY_PI_OPENAI_PROXY_KEY",
headers: {
- 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
- 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
- 'x-cindy-pi-provider-id': 'openai',
+ "x-cindy-pi-session-id": "$CINDY_PI_SESSION_ID",
+ "x-cindy-pi-session-token": "$CINDY_PI_SESSION_TOKEN",
+ "x-cindy-pi-provider-id": "openai",
},
models: [
{
- id: 'chatgpt/gpt-5.6-sol',
- wireId: 'gpt-5.6-sol',
- api: 'openai-codex-responses',
+ id: "chatgpt/gpt-5.6-sol",
+ wireId: "gpt-5.6-sol",
+ api: "openai-codex-responses",
contextWindow: 1_000_000,
maxTokens: 128_000,
},
{
- id: 'chatgpt/gpt-cindy-daily-test',
- wireId: 'gpt-cindy-daily-test',
+ id: "chatgpt/gpt-cindy-daily-test",
+ wireId: "gpt-cindy-daily-test",
catalogAddition: true,
contextWindow: 272_000,
maxTokens: 32_000,
},
{
- id: 'gpt-5.6-luna',
- wireId: 'gpt-5.6-luna',
+ id: "gpt-5.6-luna",
+ wireId: "gpt-5.6-luna",
contextWindow: 272_000,
maxTokens: 32_000,
},
],
},
{
- id: 'xai', sourceProviderId: 'xai', name: 'xAI',
- baseUrl: 'http://127.0.0.1:9988/v1', inheritModels: true,
+ id: "xai",
+ sourceProviderId: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9988/v1",
+ inheritModels: true,
headers: {
- 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
- 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
- 'x-cindy-pi-provider-id': 'xai',
+ "x-cindy-pi-session-id": "$CINDY_PI_SESSION_ID",
+ "x-cindy-pi-session-token": "$CINDY_PI_SESSION_TOKEN",
+ "x-cindy-pi-provider-id": "xai",
},
models: [
- { id: 'xai/grok-4.5', wireId: 'grok-4.5' },
- { id: 'grok-4.6', wireId: 'grok-4.6' },
+ { id: "xai/grok-4.5", wireId: "grok-4.5" },
+ { id: "grok-4.6", wireId: "grok-4.6" },
{
- id: 'grok-4.6', wireId: 'grok-4.6', catalogAddition: true,
- contextWindow: 500_000, maxTokens: 500_000,
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ catalogAddition: true,
+ contextWindow: 500_000,
+ maxTokens: 500_000,
},
{
- id: 'xai/grok-4.20', wireId: 'grok-4.20', api: 'openai-responses',
- contextWindow: 1_000_000, maxTokens: 64_000,
+ id: "xai/grok-4.20",
+ wireId: "grok-4.20",
+ api: "openai-responses",
+ contextWindow: 1_000_000,
+ maxTokens: 64_000,
cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
compat: { supportsStrictTools: true },
},
],
},
],
- env: { CINDY_PI_OPENAI_PROXY_KEY: 'placeholder-jwt' },
+ env: { CINDY_PI_OPENAI_PROXY_KEY: "placeholder-jwt" },
}),
};
const handle = await new PiAgent(deps).startSession({
- sessionId: 'native-subscription-routing',
+ sessionId: "native-subscription-routing",
workingDir: cwd,
- model: 'chatgpt/gpt-cindy-daily-test',
- effort: 'high',
+ model: "chatgpt/gpt-cindy-daily-test",
+ effort: "high",
});
- expect(authProviderIds).toEqual(['openai']);
- expect(resolveProxyProviderId?.()).toBe('openai');
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))
- .toEqual(['--provider', 'openai-codex', '--model', 'gpt-cindy-daily-test']);
+ expect(authProviderIds).toEqual(["openai"]);
+ expect(resolveProxyProviderId?.()).toBe("openai");
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 4,
+ ),
+ ).toEqual([
+ "--provider",
+ "openai-codex",
+ "--model",
+ "gpt-cindy-daily-test",
+ ]);
const configHome = captured.env.PI_CODING_AGENT_DIR as string;
- const models = JSON.parse(readFileSync(path.join(configHome, 'models.json'), 'utf8')) as {
- providers: Record<string, { api?: string; models?: Array<{ id: string; api?: string }> }>;
+ const models = JSON.parse(
+ readFileSync(path.join(configHome, "models.json"), "utf8"),
+ ) as {
+ providers: Record<
+ string,
+ { api?: string; models?: Array<{ id: string; api?: string }> }
+ >;
};
- expect(models.providers.anthropic).not.toHaveProperty('api');
+ expect(models.providers.anthropic).not.toHaveProperty("api");
expect(models.providers.anthropic?.models).toBeUndefined();
- expect(models.providers['openai-codex']).not.toHaveProperty('api');
- expect(models.providers['openai-codex']?.models).toEqual([
+ expect(models.providers["openai-codex"]).not.toHaveProperty("api");
+ expect(models.providers["openai-codex"]?.models).toEqual([
expect.objectContaining({
- id: 'gpt-5.6-sol',
- api: 'openai-codex-responses',
+ id: "gpt-5.6-sol",
+ api: "openai-codex-responses",
contextWindow: 1_000_000,
maxTokens: 128_000,
}),
- expect.objectContaining({ id: 'gpt-cindy-daily-test' }),
+ expect.objectContaining({ id: "gpt-cindy-daily-test" }),
]);
- expect(models.providers['openai-codex']?.models?.[1]).not.toHaveProperty('api');
- expect(models.providers.xai).not.toHaveProperty('api');
+ expect(models.providers["openai-codex"]?.models?.[1]).not.toHaveProperty(
+ "api",
+ );
+ expect(models.providers.xai).not.toHaveProperty("api");
expect(models.providers.xai?.models).toEqual([
expect.objectContaining({
- id: 'grok-4.6',
+ id: "grok-4.6",
contextWindow: 500_000,
maxTokens: 500_000,
}),
expect.objectContaining({
- id: 'grok-4.20',
- api: 'openai-responses',
+ id: "grok-4.20",
+ api: "openai-responses",
cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
compat: { supportsStrictTools: true },
}),
]);
- expect(models.providers.xai?.models?.[0]).not.toHaveProperty('api');
- expect(JSON.parse(readFileSync(path.join(configHome, 'settings.json'), 'utf8')))
- .toEqual({
- transport: 'sse',
- retry: {
- enabled: true,
- maxRetries: 6,
- baseDelayMs: 2000,
- provider: { maxRetries: 0 },
- },
- });
- const runtimeText = readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8');
- expect(runtimeText).not.toContain('proxySessionToken');
- expect(proxyRegistrations.filter((registration) => registration.scope === 'subagent-route'))
- .toEqual(expect.arrayContaining([
- expect.objectContaining({ providerId: 'anthropic', scope: 'subagent-route' }),
- expect.objectContaining({ providerId: 'openai', scope: 'subagent-route' }),
- expect.objectContaining({ providerId: 'xai', scope: 'subagent-route' }),
- ]));
- expect(new Set(proxyRegistrations.map((registration) => registration.token)).size)
- .toBe(proxyRegistrations.length);
+ expect(models.providers.xai?.models?.[0]).not.toHaveProperty("api");
+ expect(
+ JSON.parse(readFileSync(path.join(configHome, "settings.json"), "utf8")),
+ ).toEqual({
+ transport: "sse",
+ retry: {
+ enabled: true,
+ maxRetries: 6,
+ baseDelayMs: 2000,
+ provider: { maxRetries: 0 },
+ },
+ });
+ const runtimeText = readFileSync(
+ runtimeFileOf("subagent", "native-subscription-routing"),
+ "utf8",
+ );
+ expect(runtimeText).not.toContain("proxySessionToken");
+ expect(
+ proxyRegistrations.filter(
+ (registration) => registration.scope === "subagent-route",
+ ),
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ providerId: "anthropic",
+ scope: "subagent-route",
+ }),
+ expect.objectContaining({
+ providerId: "openai",
+ scope: "subagent-route",
+ }),
+ expect.objectContaining({ providerId: "xai", scope: "subagent-route" }),
+ ]),
+ );
+ expect(
+ new Set(proxyRegistrations.map((registration) => registration.token))
+ .size,
+ ).toBe(proxyRegistrations.length);
expect(JSON.parse(runtimeText)).toMatchObject({
- model: 'gpt-cindy-daily-test',
- provider: 'openai-codex',
- modelRoutes: {
- 'chatgpt/gpt-cindy-daily-test': [
- { provider: 'openai-codex', model: 'gpt-cindy-daily-test' },
- { provider: 'cindy', model: 'chatgpt/gpt-cindy-daily-test' },
- ],
- 'chatgpt/gpt-5.6-luna': [
- {
- provider: 'openai-codex', model: 'gpt-5.6-luna', sourceProviderId: 'openai',
- proxySessionAuth: true,
- },
- { provider: 'cindy', model: 'chatgpt/gpt-5.6-luna' },
- ],
- 'claude-opus-5': [
- {
- provider: 'anthropic', model: 'claude-opus-5', sourceProviderId: 'anthropic',
- proxySessionAuth: true,
- },
- { provider: 'cindy', model: 'claude-opus-5' },
- ],
- 'xai/grok-4.6': [
- { provider: 'xai', model: 'grok-4.6', sourceProviderId: 'xai', proxySessionAuth: true },
- { provider: 'cindy', model: 'xai/grok-4.6' },
- ],
- 'xai/grok-4.20': [
- { provider: 'xai', model: 'grok-4.20', sourceProviderId: 'xai', proxySessionAuth: true },
- { provider: 'cindy', model: 'xai/grok-4.20' },
- ],
- },
- });
+ model: "gpt-cindy-daily-test",
+ provider: "openai-codex",
+ modelRoutes: {
+ "chatgpt/gpt-cindy-daily-test": [
+ { provider: "openai-codex", model: "gpt-cindy-daily-test" },
+ { provider: "cindy", model: "chatgpt/gpt-cindy-daily-test" },
+ ],
+ "chatgpt/gpt-5.6-luna": [
+ {
+ provider: "openai-codex",
+ model: "gpt-5.6-luna",
+ sourceProviderId: "openai",
+ proxySessionAuth: true,
+ },
+ { provider: "cindy", model: "chatgpt/gpt-5.6-luna" },
+ ],
+ "claude-opus-5": [
+ {
+ provider: "anthropic",
+ model: "claude-opus-5",
+ sourceProviderId: "anthropic",
+ proxySessionAuth: true,
+ },
+ { provider: "cindy", model: "claude-opus-5" },
+ ],
+ "xai/grok-4.6": [
+ {
+ provider: "xai",
+ model: "grok-4.6",
+ sourceProviderId: "xai",
+ proxySessionAuth: true,
+ },
+ { provider: "cindy", model: "xai/grok-4.6" },
+ ],
+ "xai/grok-4.20": [
+ {
+ provider: "xai",
+ model: "grok-4.20",
+ sourceProviderId: "xai",
+ proxySessionAuth: true,
+ },
+ { provider: "cindy", model: "xai/grok-4.20" },
+ ],
+ },
+ });
- await handle.setModel!('xai/grok-4.5', { providerId: 'xai' });
+ await handle.setModel!("xai/grok-4.5", { providerId: "xai" });
expect(captured.requests).toContainEqual({
- type: 'set_model', provider: 'xai', modelId: 'grok-4.5',
- });
- expect(resolveProxyProviderId?.()).toBe('xai');
- expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))
- .toMatchObject({ model: 'grok-4.5', provider: 'xai' });
+ type: "set_model",
+ provider: "xai",
+ modelId: "grok-4.5",
+ });
+ expect(resolveProxyProviderId?.()).toBe("xai");
+ expect(
+ JSON.parse(
+ readFileSync(
+ runtimeFileOf("subagent", "native-subscription-routing"),
+ "utf8",
+ ),
+ ),
+ ).toMatchObject({ model: "grok-4.5", provider: "xai" });
- await handle.setModel!('claude-opus-5', { providerId: 'anthropic' });
+ await handle.setModel!("claude-opus-5", { providerId: "anthropic" });
expect(captured.requests).toContainEqual({
- type: 'set_model', provider: 'anthropic', modelId: 'claude-opus-5',
+ type: "set_model",
+ provider: "anthropic",
+ modelId: "claude-opus-5",
});
- expect(resolveProxyProviderId?.()).toBe('anthropic');
+ expect(resolveProxyProviderId?.()).toBe("anthropic");
await handle.close();
}, 30_000);
- it('serializes inheritModels Grok 4.6 capability corrections into models.json', async () => {
+ it("serializes inheritModels Grok 4.6 capability corrections into models.json", async () => {
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9988" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: ['low', 'medium', 'high', 'xhigh'],
- defaultEffort: 'high',
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: ["low", "medium", "high", "xhigh"],
+ defaultEffort: "high",
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => ({
- providers: [{
- id: 'xai',
- sourceProviderId: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9988/v1',
- inheritModels: true,
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-completions',
- reasoning: true,
- thinkingLevelMap: {
- minimal: null,
- low: 'low',
- medium: 'medium',
- high: 'high',
- xhigh: 'xhigh',
- max: null,
- },
- compat: {
- supportsStore: false,
- supportsDeveloperRole: false,
- supportsReasoningEffort: true,
- },
- }],
- }],
+ providers: [
+ {
+ id: "xai",
+ sourceProviderId: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9988/v1",
+ inheritModels: true,
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-completions",
+ reasoning: true,
+ thinkingLevelMap: {
+ minimal: null,
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: null,
+ },
+ compat: {
+ supportsStore: false,
+ supportsDeveloperRole: false,
+ supportsReasoningEffort: true,
+ },
+ },
+ ],
+ },
+ ],
env: {},
}),
});
const handle = await agent.startSession({
- sessionId: 'grok-46-capability-correction',
+ sessionId: "grok-46-capability-correction",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- effort: 'xhigh',
+ model: "grok-4.6",
+ providerId: "xai",
+ effort: "xhigh",
});
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as { providers: Record<string, { models?: Array<Record<string, unknown>> }> };
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<string, { models?: Array<Record<string, unknown>> }>;
+ };
expect(models.providers.xai?.models).toEqual([
expect.objectContaining({
- id: 'grok-4.6',
- api: 'openai-completions',
+ id: "grok-4.6",
+ api: "openai-completions",
reasoning: true,
- thinkingLevelMap: expect.objectContaining({ xhigh: 'xhigh' }),
+ thinkingLevelMap: expect.objectContaining({ xhigh: "xhigh" }),
compat: expect.objectContaining({ supportsReasoningEffort: true }),
}),
]);
- expect(captured.requests).toContainEqual({ type: 'set_thinking_level', level: 'xhigh' });
+ expect(captured.requests).toContainEqual({
+ type: "set_thinking_level",
+ level: "xhigh",
+ });
await handle.close();
});
- it('routes a persisted BYOM id through its namespaced PI runtime provider', async () => {
+ it("routes a persisted BYOM id through its namespaced PI runtime provider", async () => {
const authProviderIds: Array<string | null | undefined> = [];
const deps: AgentDeps = {
auth: {
getState: async (options) => {
authProviderIds.push(options?.providerId);
- return { authenticated: true, identity: 'custom', authSource: 'api-key' as const };
+ return {
+ authenticated: true,
+ identity: "custom",
+ authSource: "api-key" as const,
+ };
},
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9988" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'chatgpt/gpt-5.6-sol',
- displayName: 'Same-name Custom Model',
- contextWindow: 128_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "chatgpt/gpt-5.6-sol",
+ displayName: "Same-name Custom Model",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'openai-codex',
- sourceProviderId: 'openai',
- name: 'OpenAI (ChatGPT)',
- baseUrl: 'http://127.0.0.1:9988',
+ id: "openai-codex",
+ sourceProviderId: "openai",
+ name: "OpenAI (ChatGPT)",
+ baseUrl: "http://127.0.0.1:9988",
inheritModels: true,
- models: [{ id: 'chatgpt/gpt-5.6-sol', wireId: 'gpt-5.6-sol' }],
+ models: [{ id: "chatgpt/gpt-5.6-sol", wireId: "gpt-5.6-sol" }],
},
{
- id: 'cindy-byom-openai-codex',
- sourceProviderId: 'openai-codex',
- name: 'User endpoint',
- baseUrl: 'https://user.example/v1',
- api: 'openai-completions',
- models: [{ id: 'chatgpt/gpt-5.6-sol' }],
+ id: "cindy-byom-openai-codex",
+ sourceProviderId: "openai-codex",
+ name: "User endpoint",
+ baseUrl: "https://user.example/v1",
+ api: "openai-completions",
+ models: [{ id: "chatgpt/gpt-5.6-sol" }],
},
],
env: {},
@@ -703,49 +1035,77 @@ describe('Pi provider-aware model routing', () => {
};
const handle = await new PiAgent(deps).startSession({
- sessionId: 'namespaced-byom-routing',
+ sessionId: "namespaced-byom-routing",
workingDir: cwd,
- model: 'chatgpt/gpt-5.6-sol',
- providerId: 'openai-codex',
+ model: "chatgpt/gpt-5.6-sol",
+ providerId: "openai-codex",
});
- expect(authProviderIds).toEqual(['openai-codex']);
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))
- .toEqual(['--provider', 'cindy-byom-openai-codex', '--model', 'chatgpt/gpt-5.6-sol']);
+ expect(authProviderIds).toEqual(["openai-codex"]);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 4,
+ ),
+ ).toEqual([
+ "--provider",
+ "cindy-byom-openai-codex",
+ "--model",
+ "chatgpt/gpt-5.6-sol",
+ ]);
const configHome = captured.env.PI_CODING_AGENT_DIR as string;
- const models = JSON.parse(readFileSync(path.join(configHome, 'models.json'), 'utf8')) as {
+ const models = JSON.parse(
+ readFileSync(path.join(configHome, "models.json"), "utf8"),
+ ) as {
providers: Record<string, { baseUrl?: string }>;
};
- expect(models.providers['openai-codex']?.baseUrl).toBe('http://127.0.0.1:9988');
- expect(models.providers['cindy-byom-openai-codex']?.baseUrl).toBe('https://user.example/v1');
- expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'namespaced-byom-routing'), 'utf8')))
- .toMatchObject({ model: 'chatgpt/gpt-5.6-sol', provider: 'cindy-byom-openai-codex' });
+ expect(models.providers["openai-codex"]?.baseUrl).toBe(
+ "http://127.0.0.1:9988",
+ );
+ expect(models.providers["cindy-byom-openai-codex"]?.baseUrl).toBe(
+ "https://user.example/v1",
+ );
+ expect(
+ JSON.parse(
+ readFileSync(
+ runtimeFileOf("subagent", "namespaced-byom-routing"),
+ "utf8",
+ ),
+ ),
+ ).toMatchObject({
+ model: "chatgpt/gpt-5.6-sol",
+ provider: "cindy-byom-openai-codex",
+ });
await handle.close();
});
- it('keeps xAI and custom providers in one snapshot and switches both directions', async () => {
+ it("keeps xAI and custom providers in one snapshot and switches both directions", async () => {
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
{
- id: 'xai/grok-4.6',
- displayName: 'Grok 4.6',
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
contextWindow: 500_000,
- efforts: ['minimal', 'low', 'medium', 'high'],
- defaultEffort: 'medium',
+ efforts: ["minimal", "low", "medium", "high"],
+ defaultEffort: "medium",
},
{
- id: 'local-model',
- displayName: 'Local Model',
+ id: "local-model",
+ displayName: "Local Model",
contextWindow: 128_000,
efforts: [],
defaultEffort: null,
@@ -757,421 +1117,551 @@ describe('Pi provider-aware model routing', () => {
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9',
- api: 'anthropic-messages',
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9",
+ api: "anthropic-messages",
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
headers: {
- 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
- 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ "x-cindy-pi-session-id": "$CINDY_PI_SESSION_ID",
+ "x-cindy-pi-session-token": "$CINDY_PI_SESSION_TOKEN",
},
modelIdAliases: {
- 'grok-4.6': 'xai/grok-4.6',
- 'xai/grok-4.6': 'xai/grok-4.6',
+ "grok-4.6": "xai/grok-4.6",
+ "xai/grok-4.6": "xai/grok-4.6",
},
- models: [{
- id: 'xai/grok-4.6',
- api: 'anthropic-messages',
- contextWindow: 500_000,
- maxTokens: 500_000,
- input: ['text', 'image'],
- reasoning: true,
- compat: {
- supportsStore: false,
- supportsDeveloperRole: false,
- supportsReasoningEffort: false,
+ models: [
+ {
+ id: "xai/grok-4.6",
+ api: "anthropic-messages",
+ contextWindow: 500_000,
+ maxTokens: 500_000,
+ input: ["text", "image"],
+ reasoning: true,
+ compat: {
+ supportsStore: false,
+ supportsDeveloperRole: false,
+ supportsReasoningEffort: false,
+ },
},
- }],
+ ],
},
{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
},
],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
}),
});
const handle = await agent.startSession({
- sessionId: 'grok-46-native',
+ sessionId: "grok-46-native",
workingDir: cwd,
- model: 'xai/grok-4.6',
- providerId: 'xai',
- effort: 'medium',
- });
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'xai']);
- expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))
- .toEqual(['--model', 'xai/grok-4.6']);
- expect(captured.env.CINDY_PI_API_KEY).toBe('gateway-key');
- expect(captured.env.CINDY_PI_XAI_PROXY_API_KEY).toBe('xai-proxy-placeholder');
+ model: "xai/grok-4.6",
+ providerId: "xai",
+ effort: "medium",
+ });
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "xai"]);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--model"),
+ captured.args.indexOf("--model") + 2,
+ ),
+ ).toEqual(["--model", "xai/grok-4.6"]);
+ expect(captured.env.CINDY_PI_API_KEY).toBe("gateway-key");
+ expect(captured.env.CINDY_PI_XAI_PROXY_API_KEY).toBe(
+ "xai-proxy-placeholder",
+ );
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as { providers: Record<string, { apiKey: string; models: Array<Record<string, unknown>> }> };
- expect(models.providers.cindy?.apiKey).toBe('$CINDY_PI_API_KEY');
- expect(models.providers.xai?.apiKey).toBe('$CINDY_PI_XAI_PROXY_API_KEY');
- expect(models.providers.xai?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({
- api: 'anthropic-messages',
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<
+ string,
+ { apiKey: string; models: Array<Record<string, unknown>> }
+ >;
+ };
+ expect(models.providers.cindy?.apiKey).toBe("$CINDY_PI_API_KEY");
+ expect(models.providers.xai?.apiKey).toBe("$CINDY_PI_XAI_PROXY_API_KEY");
+ expect(
+ models.providers.xai?.models.find((model) => model.id === "xai/grok-4.6"),
+ ).toMatchObject({
+ api: "anthropic-messages",
contextWindow: 500_000,
maxTokens: 500_000,
- input: ['text', 'image'],
+ input: ["text", "image"],
compat: {
supportsStore: false,
supportsDeveloperRole: false,
supportsReasoningEffort: false,
},
});
- expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'grok-46-native'), 'utf8'))).toEqual({
- model: 'xai/grok-4.6',
- provider: 'xai',
+ expect(
+ JSON.parse(
+ readFileSync(runtimeFileOf("subagent", "grok-46-native"), "utf8"),
+ ),
+ ).toEqual({
+ model: "xai/grok-4.6",
+ provider: "xai",
modelRoutes: expect.any(Object),
});
- await handle.setModel!('local-model', { providerId: 'native-a' });
- await handle.setModel!('xai/grok-4.6', { providerId: 'xai' });
+ await handle.setModel!("local-model", { providerId: "native-a" });
+ await handle.setModel!("xai/grok-4.6", { providerId: "xai" });
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'native-a',
- modelId: 'local-model',
+ type: "set_model",
+ provider: "native-a",
+ modelId: "local-model",
});
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'xai',
- modelId: 'xai/grok-4.6',
+ type: "set_model",
+ provider: "xai",
+ modelId: "xai/grok-4.6",
});
await handle.close();
});
- it('does not reissue set_model when the live session is already on the requested SuperGrok route', async () => {
+ it("does not reissue set_model when the live session is already on the requested SuperGrok route", async () => {
captured.requestHandler = async (command) => {
- if (command.type === 'set_model') {
- return { success: false, error: 'Model "grok-4.6" not found for provider "xai"' };
+ if (command.type === "set_model") {
+ return {
+ success: false,
+ error: 'Model "grok-4.6" not found for provider "xai"',
+ };
}
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
return { success: true, data: {} };
};
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => ({
- providers: [{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9',
- api: 'anthropic-messages',
- models: [{ id: 'grok-4.6' }],
- }],
+ providers: [
+ {
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9",
+ api: "anthropic-messages",
+ models: [{ id: "grok-4.6" }],
+ },
+ ],
env: {},
}),
});
const handle = await agent.startSession({
- sessionId: 'grok-46-same-route',
+ sessionId: "grok-46-same-route",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
+ model: "grok-4.6",
+ providerId: "xai",
});
captured.requests.length = 0;
- await expect(handle.setModel!('grok-4.6', { providerId: 'xai' })).resolves.toBeUndefined();
- expect(captured.requests.filter((request) => request.type === 'set_model')).toEqual([]);
+ await expect(
+ handle.setModel!("grok-4.6", { providerId: "xai" }),
+ ).resolves.toBeUndefined();
+ expect(
+ captured.requests.filter((request) => request.type === "set_model"),
+ ).toEqual([]);
await handle.close();
});
- it('rebuilds a missing subagent snapshot on same-route SuperGrok setModel without RPC', async () => {
+ it("rebuilds a missing subagent snapshot on same-route SuperGrok setModel without RPC", async () => {
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
- triggerLogin: async () => ({ authenticated: true }),
- logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
- providers: [{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9',
- api: 'anthropic-messages',
- models: [{ id: 'grok-4.6' }],
- }],
+ providers: [
+ {
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9",
+ api: "anthropic-messages",
+ models: [{ id: "grok-4.6" }],
+ },
+ ],
env: {},
}),
});
const handle = await agent.startSession({
- sessionId: 'grok-46-snapshot-retry',
+ sessionId: "grok-46-snapshot-retry",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
+ model: "grok-4.6",
+ providerId: "xai",
});
- const snapshotPath = runtimeFileOf('subagent', 'grok-46-snapshot-retry');
+ const snapshotPath = runtimeFileOf("subagent", "grok-46-snapshot-retry");
rmSync(snapshotPath, { force: true });
captured.requests.length = 0;
- await expect(handle.setModel!('grok-4.6', { providerId: 'xai' })).resolves.toBeUndefined();
- expect(captured.requests.filter((request) => request.type === 'set_model')).toEqual([]);
+ await expect(
+ handle.setModel!("grok-4.6", { providerId: "xai" }),
+ ).resolves.toBeUndefined();
+ expect(
+ captured.requests.filter((request) => request.type === "set_model"),
+ ).toEqual([]);
// The snapshot also persists the alias route table for Subagent model
// normalization, so assert the rebuilt identity rather than exact shape.
- expect(JSON.parse(readFileSync(snapshotPath, 'utf8'))).toMatchObject({
- model: 'grok-4.6',
- provider: 'xai',
+ expect(JSON.parse(readFileSync(snapshotPath, "utf8"))).toMatchObject({
+ model: "grok-4.6",
+ provider: "xai",
});
await handle.close();
});
- it('clears a stuck pending subagent snapshot on same-route SuperGrok setModel', async () => {
+ it("clears a stuck pending subagent snapshot on same-route SuperGrok setModel", async () => {
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
- providers: [{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9',
- api: 'anthropic-messages',
- models: [{ id: 'grok-4.6' }],
- }],
+ providers: [
+ {
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9",
+ api: "anthropic-messages",
+ models: [{ id: "grok-4.6" }],
+ },
+ ],
env: {},
}),
});
const handle = await agent.startSession({
- sessionId: 'grok-46-pending-clear',
+ sessionId: "grok-46-pending-clear",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- });
- const snapshotPath = runtimeFileOf('subagent', 'grok-46-pending-clear');
- writeFileSync(snapshotPath, JSON.stringify({
- model: 'grok-4.6',
- provider: 'xai',
- pending: true,
- }) + '\n');
+ model: "grok-4.6",
+ providerId: "xai",
+ });
+ const snapshotPath = runtimeFileOf("subagent", "grok-46-pending-clear");
+ writeFileSync(
+ snapshotPath,
+ JSON.stringify({
+ model: "grok-4.6",
+ provider: "xai",
+ pending: true,
+ }) + "\n",
+ );
captured.requests.length = 0;
- await expect(handle.setModel!('grok-4.6', { providerId: 'xai' })).resolves.toBeUndefined();
- expect(captured.requests.filter((request) => request.type === 'set_model')).toEqual([]);
- const cleared = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;
- expect(cleared).toMatchObject({ model: 'grok-4.6', provider: 'xai' });
+ await expect(
+ handle.setModel!("grok-4.6", { providerId: "xai" }),
+ ).resolves.toBeUndefined();
+ expect(
+ captured.requests.filter((request) => request.type === "set_model"),
+ ).toEqual([]);
+ const cleared = JSON.parse(readFileSync(snapshotPath, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ expect(cleared).toMatchObject({ model: "grok-4.6", provider: "xai" });
// The point of this test: the stuck pending flag must be gone.
expect(cleared.pending).toBeUndefined();
await handle.close();
});
- it('rejects a same-route gateway heartbeat when the live session wire protocol is stale', async () => {
- let gatewayApi: 'anthropic-messages' | 'openai-responses' = 'anthropic-messages';
+ it("rejects a same-route gateway heartbeat when the live session wire protocol is stale", async () => {
+ let gatewayApi: "anthropic-messages" | "openai-responses" =
+ "anthropic-messages";
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'shared-model',
- displayName: 'Shared',
- contextWindow: 128_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "shared-model",
+ displayName: "Shared",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
resolvePiGatewayModelApi: () => gatewayApi,
});
const handle = await agent.startSession({
- sessionId: 'gateway-same-route-stale',
+ sessionId: "gateway-same-route-stale",
workingDir: cwd,
- model: 'shared-model',
- providerId: 'xd',
+ model: "shared-model",
+ providerId: "xd",
});
- gatewayApi = 'openai-responses';
+ gatewayApi = "openai-responses";
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([]);
+ 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([]);
await handle.close();
});
- it('reloads models.json via switch_session when SuperGrok appears after session start', async () => {
+ it("reloads models.json via switch_session when SuperGrok appears after session start", async () => {
const xaiProvider = {
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
modelIdAliases: {
- 'grok-4.6': 'grok-4.6',
- 'xai/grok-4.6': 'grok-4.6',
+ "grok-4.6": "grok-4.6",
+ "xai/grok-4.6": "grok-4.6",
},
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- name: 'Grok 4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- contextWindow: 500_000,
- }],
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ name: "Grok 4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ contextWindow: 500_000,
+ },
+ ],
};
let includeXai = false;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
{
- id: 'xai/grok-4.6',
- displayName: 'Grok 4.6',
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
contextWindow: 500_000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
+ efforts: ["low", "medium", "high"],
+ defaultEffort: "medium",
},
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => (includeXai
- ? { providers: [xaiProvider], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } }
- : {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
- }),
+ resolvePiNativeProviders: async () =>
+ includeXai
+ ? {
+ providers: [xaiProvider],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ }
+ : {
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ },
});
const handle = await agent.startSession({
- sessionId: 'late-xai',
+ sessionId: "late-xai",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
includeXai = true;
- await handle.setModel!('xai/grok-4.6', { providerId: 'xai' });
+ await handle.setModel!("xai/grok-4.6", { providerId: "xai" });
expect(captured.requests).toContainEqual({
- type: 'switch_session',
- sessionPath: '/mock/s.jsonl',
+ type: "switch_session",
+ sessionPath: "/mock/s.jsonl",
});
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'xai',
- modelId: 'grok-4.6',
+ type: "set_model",
+ provider: "xai",
+ modelId: "grok-4.6",
});
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as { providers: Record<string, { models: Array<{ id: string; api?: string }> }> };
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<
+ string,
+ { models: Array<{ id: string; api?: string }> }
+ >;
+ };
expect(models.providers.xai?.models).toEqual([
- expect.objectContaining({ id: 'grok-4.6', api: 'openai-responses' }),
+ expect.objectContaining({ id: "grok-4.6", api: "openai-responses" }),
]);
await handle.close();
});
- it('keeps the live context window when a late catalog reload rewrites settings', async () => {
+ it("keeps the live context window when a late catalog reload rewrites settings", async () => {
const xaiProvider = {
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
modelIdAliases: {
- 'grok-4.6': 'grok-4.6',
- 'xai/grok-4.6': 'grok-4.6',
+ "grok-4.6": "grok-4.6",
+ "xai/grok-4.6": "grok-4.6",
},
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- name: 'Grok 4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- contextWindow: 100_000,
- }],
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ name: "Grok 4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ contextWindow: 100_000,
+ },
+ ],
};
let includeXai = false;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
runtimeConfig: {
- endpoint: 'http://127.0.0.1:9',
+ endpoint: "http://127.0.0.1:9",
piAutoCompactThresholdPct: 75,
},
- binaryPath: path.join(agentHome, 'pi'),
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'wide-model', displayName: 'Wide', contextWindow: 200_000, efforts: [], defaultEffort: null },
- { id: 'narrow-model', displayName: 'Narrow', contextWindow: 100_000, efforts: [], defaultEffort: null },
{
- id: 'xai/grok-4.6',
- displayName: 'Grok 4.6',
+ id: "wide-model",
+ displayName: "Wide",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "narrow-model",
+ displayName: "Narrow",
+ contextWindow: 100_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
contextWindow: 100_000,
efforts: [],
defaultEffort: null,
@@ -1179,456 +1669,685 @@ describe('Pi provider-aware model routing', () => {
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => (includeXai
- ? { providers: [xaiProvider], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } }
- : {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'wide-model' }, { id: 'narrow-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
- }),
+ resolvePiNativeProviders: async () =>
+ includeXai
+ ? {
+ providers: [xaiProvider],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ }
+ : {
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "wide-model" }, { id: "narrow-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ },
});
const handle = await agent.startSession({
- sessionId: 'catalog-keeps-live-window',
+ sessionId: "catalog-keeps-live-window",
workingDir: cwd,
- model: 'wide-model',
- providerId: 'native-a',
+ model: "wide-model",
+ providerId: "native-a",
});
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'set_model') {
+ if (command.type === "set_model") {
return { success: true, data: { contextWindow: 100_000 } };
}
return { success: true, data: {} };
};
- await handle.setModel!('narrow-model', { providerId: 'native-a' });
+ await handle.setModel!("narrow-model", { providerId: "native-a" });
includeXai = true;
- await handle.setModel!('xai/grok-4.6', { providerId: 'xai' });
+ await handle.setModel!("xai/grok-4.6", { providerId: "xai" });
const settings = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'settings.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "settings.json"),
+ "utf8",
+ ),
) as { compaction?: { reserveTokens?: number } };
- expect(settings.compaction?.reserveTokens).toBe(25_000);
+ expect(settings.compaction?.reserveTokens).toBe(50_000);
await handle.close();
});
- it('rolls models.json back when switch_session fails after an xAI catalog refresh', async () => {
+ it("rolls models.json back when switch_session fails after an xAI catalog refresh", async () => {
const xaiProvider = {
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: { 'xai/grok-4.6': 'grok-4.6', 'grok-4.6': 'grok-4.6' },
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }],
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: { "xai/grok-4.6": "grok-4.6", "grok-4.6": "grok-4.6" },
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ],
};
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'switch_session') {
- return { success: false, error: 'reload failed' };
+ if (command.type === "switch_session") {
+ return { success: false, error: "reload failed" };
}
return { success: true, data: {} };
};
let includeXai = false;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => (includeXai
- ? { providers: [xaiProvider], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } }
- : {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
- }),
+ resolvePiNativeProviders: async () =>
+ includeXai
+ ? {
+ providers: [xaiProvider],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ }
+ : {
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ },
});
const handle = await agent.startSession({
- sessionId: 'xai-reload-rollback',
+ sessionId: "xai-reload-rollback",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
includeXai = true;
- await expect(handle.setModel!('xai/grok-4.6', { providerId: 'xai' })).rejects.toThrow(/reload models/);
+ await expect(
+ handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
+ ).rejects.toThrow(/reload models/);
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as { providers: Record<string, unknown> };
expect(models.providers.xai).toBeUndefined();
await handle.close();
});
- it('terminates the session when catalog rollback cannot be written after switch_session fails', async () => {
+ it("terminates the session when catalog rollback cannot be written after switch_session fails", async () => {
const xaiProvider = {
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: { 'xai/grok-4.6': 'grok-4.6', 'grok-4.6': 'grok-4.6' },
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }],
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: { "xai/grok-4.6": "grok-4.6", "grok-4.6": "grok-4.6" },
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ],
};
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'switch_session') {
- const modelsPath = path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json');
+ if (command.type === "switch_session") {
+ 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: "reload failed" };
}
return { success: true, data: {} };
};
let includeXai = false;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => (includeXai
- ? { providers: [xaiProvider], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } }
- : {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
- }),
+ resolvePiNativeProviders: async () =>
+ includeXai
+ ? {
+ providers: [xaiProvider],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ }
+ : {
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ },
});
const handle = await agent.startSession({
- sessionId: 'xai-reload-rollback-unwritable',
+ sessionId: "xai-reload-rollback-unwritable",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
includeXai = true;
- await expect(handle.setModel!('xai/grok-4.6', { providerId: 'xai' })).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
+ await expect(
+ handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
+ ).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
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 switch_session neither confirms nor rejects after an xAI catalog refresh", async () => {
const xaiProvider = {
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: { 'xai/grok-4.6': 'grok-4.6', 'grok-4.6': 'grok-4.6' },
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }],
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: { "xai/grok-4.6": "grok-4.6", "grok-4.6": "grok-4.6" },
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ],
};
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'switch_session') {
- throw new Error('pi rpc timeout after 30000ms: switch_session');
+ if (command.type === "switch_session") {
+ throw new Error("pi rpc timeout after 30000ms: switch_session");
}
return { success: true, data: {} };
};
let includeXai = false;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => (includeXai
- ? { providers: [xaiProvider], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } }
- : {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
- }),
+ resolvePiNativeProviders: async () =>
+ includeXai
+ ? {
+ providers: [xaiProvider],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ }
+ : {
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ },
});
const handle = await agent.startSession({
- sessionId: 'xai-reload-unconfirmed',
+ sessionId: "xai-reload-unconfirmed",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
includeXai = true;
- await expect(handle.setModel!('xai/grok-4.6', { providerId: 'xai' })).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
+ await expect(
+ handle.setModel!("xai/grok-4.6", { providerId: "xai" }),
+ ).rejects.toThrow(/PI_CATALOG_RELOAD_UNCONFIRMED/);
expect(captured.closes).toBeGreaterThan(0);
});
- it('refuses a live xAI refresh when the provider endpoint would change', async () => {
+ it("refuses a live xAI refresh when the provider endpoint would change", async () => {
let call = 0;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 500_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "xai/grok-4.5",
+ displayName: "Grok 4.5",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => {
call += 1;
return {
- providers: [{
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: call === 1 ? 'http://127.0.0.1:9/v1' : 'http://evil.test/v1',
- inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: {
- 'xai/grok-4.5': 'grok-4.5',
- 'grok-4.5': 'grok-4.5',
- 'xai/grok-4.6': 'grok-4.6',
- 'grok-4.6': 'grok-4.6',
+ providers: [
+ {
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl:
+ call === 1 ? "http://127.0.0.1:9/v1" : "http://evil.test/v1",
+ inheritModels: true,
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: {
+ "xai/grok-4.5": "grok-4.5",
+ "grok-4.5": "grok-4.5",
+ "xai/grok-4.6": "grok-4.6",
+ "grok-4.6": "grok-4.6",
+ },
+ models:
+ call === 1
+ ? [
+ {
+ id: "grok-4.5",
+ wireId: "grok-4.5",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ]
+ : [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ],
},
- models: call === 1
- ? [{
- id: 'grok-4.5',
- wireId: 'grok-4.5',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }]
- : [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
};
},
});
const handle = await agent.startSession({
- sessionId: 'xai-endpoint-guard',
+ sessionId: "xai-endpoint-guard",
workingDir: cwd,
- model: 'xai/grok-4.5',
- providerId: 'xai',
+ model: "xai/grok-4.5",
+ providerId: "xai",
});
- await expect(handle.setModel!('xai/grok-4.6', { providerId: 'xai' })).rejects.toThrow(
- /cannot serve model/,
+ 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" }),
);
- expect(captured.requests).not.toContainEqual(expect.objectContaining({ type: 'switch_session' }));
await handle.close();
});
- it('does not refresh when switching to a bundled inheritModels xAI model', async () => {
+ it("does not refresh when switching to a bundled inheritModels xAI model", async () => {
let resolves = 0;
+ captured.requestHandler = async (command) =>
+ command.type === "get_state"
+ ? {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: {
+ contextWindow:
+ captured.runtimeModel === "grok-4.5" ? 500_000 : 128_000,
+ },
+ },
+ }
+ : { success: true, data: {} };
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 500_000, efforts: [], defaultEffort: null },
- ],
- },
- resolvePiAgentHome: () => agentHome,
- resolvePiNativeProviders: async () => {
- resolves += 1;
- return {
- providers: [
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.5",
+ displayName: "Grok 4.5",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ },
+ resolvePiAgentHome: () => agentHome,
+ resolvePiNativeProviders: async () => {
+ resolves += 1;
+ return {
+ providers: [
{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
},
{
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9/v1',
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9/v1",
inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: { 'xai/grok-4.5': 'grok-4.5', 'grok-4.5': 'grok-4.5' },
- models: [{ id: 'grok-4.5', wireId: 'grok-4.5' }],
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: {
+ "xai/grok-4.5": "grok-4.5",
+ "grok-4.5": "grok-4.5",
+ },
+ models: [{ id: "grok-4.5", wireId: "grok-4.5" }],
},
],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
};
},
});
const handle = await agent.startSession({
- sessionId: 'bundled-xai-switch',
+ sessionId: "bundled-xai-switch",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
expect(resolves).toBe(1);
captured.requests.length = 0;
- await handle.setModel!('xai/grok-4.5', { providerId: 'xai' });
+ await handle.setModel!("xai/grok-4.5", { providerId: "xai" });
expect(resolves).toBe(1);
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'xai',
- modelId: 'grok-4.5',
+ type: "set_model",
+ provider: "xai",
+ modelId: "grok-4.5",
});
- expect(captured.requests.filter((request) => request.type === 'switch_session')).toHaveLength(1);
+ expect(
+ captured.requests.filter((request) => request.type === "switch_session"),
+ ).toHaveLength(1);
await handle.close();
});
- it('does not live-refresh xAI when the caller pins the gateway with providerId null', async () => {
+ it("does not live-refresh xAI when the caller pins the gateway with providerId null", async () => {
let resolves = 0;
+ captured.requestHandler = async (command) =>
+ command.type === "get_state"
+ ? {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: {
+ contextWindow:
+ captured.runtimeModel === "xai/grok-4.6" ? 500_000 : 128_000,
+ },
+ },
+ }
+ : { success: true, data: {} };
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'local-model', displayName: 'Local', contextWindow: 128_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
- resolvePiGatewayModelApi: () => 'openai-responses',
+ resolvePiGatewayModelApi: () => "openai-responses",
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => {
resolves += 1;
return {
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- models: [{ id: 'local-model' }],
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
};
},
});
const handle = await agent.startSession({
- sessionId: 'gateway-pin-skips-xai-reload',
+ sessionId: "gateway-pin-skips-xai-reload",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
expect(resolves).toBe(1);
captured.requests.length = 0;
- await handle.setModel!('xai/grok-4.6', { providerId: null });
+ await handle.setModel!("xai/grok-4.6", { providerId: null });
expect(resolves).toBe(1);
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'cindy',
- modelId: 'xai/grok-4.6',
+ type: "set_model",
+ provider: "cindy",
+ modelId: "xai/grok-4.6",
});
- expect(captured.requests.filter((request) => request.type === 'switch_session')).toHaveLength(1);
+ expect(
+ captured.requests.filter((request) => request.type === "switch_session"),
+ ).toHaveLength(1);
await handle.close();
});
- it('refuses to add a remote xAI proxy that was not provisioned at startup', async () => {
+ it("refuses to add a remote xAI proxy that was not provisioned at startup", async () => {
let resolves = 0;
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'user', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "user",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9', remoteEndpoint: 'https://gateway.example.test' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: {
+ endpoint: "http://127.0.0.1:9",
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
- { id: 'gateway-model', displayName: 'Gateway model', contextWindow: 200_000, efforts: [], defaultEffort: null },
- { id: 'xai/grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ {
+ id: "gateway-model",
+ displayName: "Gateway model",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "xai/grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiGatewayModelApi: () => 'anthropic-messages',
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ resolvePiGatewayModelApi: () => "anthropic-messages",
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiFileOps: () => ({
mkdirp: async () => {},
writeFile: async () => {},
@@ -1644,91 +2363,105 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
ensureHostProxyForward: async () => {},
}),
resolvePiNativeProviders: async () => {
resolves += 1;
if (resolves === 1) {
- return { providers: [], env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' } };
+ return {
+ providers: [],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
+ };
}
return {
- providers: [{
- id: 'xai',
- sourceProviderId: 'xai' as const,
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:47989',
- inheritModels: true,
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- modelIdAliases: { 'xai/grok-4.6': 'grok-4.6', 'grok-4.6': 'grok-4.6' },
- models: [{
- id: 'grok-4.6',
- wireId: 'grok-4.6',
- api: 'openai-responses' as const,
- catalogAddition: true,
- }],
- hostProxyForward: {
- localUrl: 'http://127.0.0.1:18765',
- remotePort: 47989,
+ providers: [
+ {
+ id: "xai",
+ sourceProviderId: "xai" as const,
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:47989",
+ inheritModels: true,
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ modelIdAliases: {
+ "xai/grok-4.6": "grok-4.6",
+ "grok-4.6": "grok-4.6",
+ },
+ models: [
+ {
+ id: "grok-4.6",
+ wireId: "grok-4.6",
+ api: "openai-responses" as const,
+ catalogAddition: true,
+ },
+ ],
+ hostProxyForward: {
+ localUrl: "http://127.0.0.1:18765",
+ remotePort: 47989,
+ },
},
- }],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ ],
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
};
},
});
const handle = await agent.startSession({
- sessionId: 'remote-xai-after-login',
+ sessionId: "remote-xai-after-login",
workingDir: cwd,
- model: 'gateway-model',
- providerId: 'xd',
- remoteHostId: 'remote-host',
+ model: "gateway-model",
+ providerId: "xd",
+ remoteHostId: "remote-host",
});
- await expect(handle.setModel!('xai/grok-4.6', { providerId: 'xai' })).rejects.toThrow(
- /cannot serve model/,
+ 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" }),
);
- expect(captured.requests).not.toContainEqual(expect.objectContaining({ type: 'switch_session' }));
await handle.close();
});
- it('applies each native provider alias during provider-less compatibility routing', async () => {
+ it("applies each native provider alias during provider-less compatibility routing", async () => {
const provider = (id: string, aliases?: Record<string, string>) => ({
id,
name: id,
baseUrl: `http://${id}.test`,
- api: 'anthropic-messages' as const,
+ api: "anthropic-messages" as const,
...(aliases ? { modelIdAliases: aliases } : {}),
- models: [{ id: id === 'xai' ? 'xai/grok-4.6' : 'other-model' }],
+ models: [{ id: id === "xai" ? "xai/grok-4.6" : "other-model" }],
});
const agent = new PiAgent({
auth: {
getState: async (options) => ({
authenticated: true,
- identity: options?.providerId === 'xai' ? 'SuperGrok' : 'test',
- authSource: 'oauth' as const,
+ identity: options?.providerId === "xai" ? "SuperGrok" : "test",
+ authSource: "oauth" as const,
}),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: [],
- defaultEffort: null,
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => ({
providers: [
- provider('other'),
- provider('xai', {
- 'grok-4.6': 'xai/grok-4.6',
- 'xai/grok-4.6': 'xai/grok-4.6',
+ provider("other"),
+ provider("xai", {
+ "grok-4.6": "xai/grok-4.6",
+ "xai/grok-4.6": "xai/grok-4.6",
}),
],
env: {},
@@ -1736,176 +2469,249 @@ describe('Pi provider-aware model routing', () => {
});
const bare = await agent.startSession({
- sessionId: 'providerless-grok-bare',
+ sessionId: "providerless-grok-bare",
workingDir: cwd,
- model: 'grok-4.6',
+ model: "grok-4.6",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'xai']);
- expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))
- .toEqual(['--model', 'xai/grok-4.6']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "xai"]);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--model"),
+ captured.args.indexOf("--model") + 2,
+ ),
+ ).toEqual(["--model", "xai/grok-4.6"]);
await bare.close();
const namespaced = await agent.startSession({
- sessionId: 'providerless-grok-namespaced',
+ sessionId: "providerless-grok-namespaced",
workingDir: cwd,
- model: 'xai/grok-4.6',
+ model: "xai/grok-4.6",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'xai']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "xai"]);
await namespaced.close();
});
- it('normalizes Subagent aliases to the catalog wire id without a guessed gateway fallback', async () => {
- const deps = byomDeps(async () => ({
- providers: [{
- id: 'xai',
- sourceProviderId: 'xai',
- name: 'xAI',
- baseUrl: 'http://xai.test',
- api: 'anthropic-messages',
- modelIdAliases: {
- 'grok-4.6': 'xai/grok-4.6',
- 'xai/grok-4.6': 'xai/grok-4.6',
+ it("normalizes Subagent aliases to the catalog wire id without a guessed gateway fallback", async () => {
+ const deps = byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "xai",
+ sourceProviderId: "xai",
+ name: "xAI",
+ baseUrl: "http://xai.test",
+ api: "anthropic-messages",
+ modelIdAliases: {
+ "grok-4.6": "xai/grok-4.6",
+ "xai/grok-4.6": "xai/grok-4.6",
+ },
+ models: [{ id: "xai/grok-4.6", wireId: "x-ai/grok-4.6" }],
+ },
+ ],
+ env: {},
+ }),
+ [
+ {
+ id: "gateway-model",
+ displayName: "Gateway",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
},
- models: [{ id: 'xai/grok-4.6', wireId: 'x-ai/grok-4.6' }],
- }],
- env: {},
- }), [
- { id: 'gateway-model', displayName: 'Gateway', contextWindow: 200_000, efforts: [], defaultEffort: null },
- { id: 'grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
- ]);
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ );
deps.resolvePiGatewayModelApi = (_providerId, modelId) =>
- modelId === 'gateway-model' ? 'openai-responses' : undefined;
+ modelId === "gateway-model" ? "openai-responses" : undefined;
const handle = await new PiAgent(deps).startSession({
- sessionId: 'subagent-wire-normalization',
+ sessionId: "subagent-wire-normalization",
workingDir: cwd,
- model: 'gateway-model',
- providerId: 'xd',
+ model: "gateway-model",
+ providerId: "xd",
});
const runtime = JSON.parse(
- readFileSync(runtimeFileOf('subagent', 'subagent-wire-normalization'), 'utf8'),
- ) as { modelRoutes: Record<string, Array<{ provider: string; model: string; sourceProviderId?: string }>> };
- expect(runtime.modelRoutes['grok-4.6']).toEqual([
- { provider: 'xai', model: 'x-ai/grok-4.6', sourceProviderId: 'xai' },
+ readFileSync(
+ runtimeFileOf("subagent", "subagent-wire-normalization"),
+ "utf8",
+ ),
+ ) as {
+ modelRoutes: Record<
+ string,
+ Array<{ provider: string; model: string; sourceProviderId?: string }>
+ >;
+ };
+ expect(runtime.modelRoutes["grok-4.6"]).toEqual([
+ { provider: "xai", model: "x-ai/grok-4.6", sourceProviderId: "xai" },
]);
- expect(runtime.modelRoutes['xai/grok-4.6']).toEqual([
- { provider: 'xai', model: 'x-ai/grok-4.6', sourceProviderId: 'xai' },
+ expect(runtime.modelRoutes["xai/grok-4.6"]).toEqual([
+ { provider: "xai", model: "x-ai/grok-4.6", sourceProviderId: "xai" },
]);
- expect(runtime.modelRoutes['gateway-model']).toEqual([
+ expect(runtime.modelRoutes["gateway-model"]).toEqual([
{
- provider: 'cindy',
- model: 'gateway-model',
- sourceProviderId: 'cindy-gateway',
+ provider: "cindy",
+ model: "gateway-model",
+ sourceProviderId: "cindy-gateway",
proxySessionAuth: true,
},
]);
await handle.close();
});
- it('fails closed when provider-less aliases are ambiguous', async () => {
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- {
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-completions',
- modelIdAliases: { legacy: 'native-a-model' },
- models: [{ id: 'native-a-model' }],
- },
- {
- id: 'native-b',
- name: 'Native B',
- baseUrl: 'http://b.test',
- api: 'openai-completions',
- modelIdAliases: { legacy: 'native-b-model' },
- models: [{ id: 'native-b-model' }],
- },
- ],
- env: {},
- })));
- await expect(agent.startSession({
- sessionId: 'providerless-alias-conflict',
- workingDir: cwd,
- model: 'legacy',
- })).rejects.toThrow(/matches multiple native providers.*refusing to guess an endpoint/);
+ it("fails closed when provider-less aliases are ambiguous", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ modelIdAliases: { legacy: "native-a-model" },
+ models: [{ id: "native-a-model" }],
+ },
+ {
+ id: "native-b",
+ name: "Native B",
+ baseUrl: "http://b.test",
+ api: "openai-completions",
+ modelIdAliases: { legacy: "native-b-model" },
+ models: [{ id: "native-b-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
+ await expect(
+ agent.startSession({
+ sessionId: "providerless-alias-conflict",
+ workingDir: cwd,
+ model: "legacy",
+ }),
+ ).rejects.toThrow(
+ /matches multiple native providers.*refusing to guess an endpoint/,
+ );
expect(captured.args).toEqual([]);
});
- it('surfaces a first-party Pi proxy-not-ready failure for provider-less and legacy Grok sessions', async () => {
+ it("surfaces a first-party Pi proxy-not-ready failure for provider-less and legacy Grok sessions", async () => {
const proxyNotReady = new PiNativeProviderProxyNotReadyError();
- const agent = new PiAgent(byomDeps(async () => {
- throw proxyNotReady;
- }, [
- { id: 'grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
- ]));
-
- for (const [index, model] of ['grok-4.6', 'xai/grok-4.6'].entries()) {
- await expect(agent.startSession({
- sessionId: `providerless-grok-proxy-not-ready-${index}`,
- workingDir: cwd,
- model,
- })).rejects.toBe(proxyNotReady);
+ const agent = new PiAgent(
+ byomDeps(async () => {
+ throw proxyNotReady;
+ }, [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ]),
+ );
+
+ for (const [index, model] of ["grok-4.6", "xai/grok-4.6"].entries()) {
+ await expect(
+ agent.startSession({
+ sessionId: `providerless-grok-proxy-not-ready-${index}`,
+ workingDir: cwd,
+ model,
+ }),
+ ).rejects.toBe(proxyNotReady);
}
expect(captured.args).toEqual([]);
});
- it('fails closed when an explicit xAI selection cannot build the Pi native provider', async () => {
+ it("fails closed when an explicit xAI selection cannot build the Pi native provider", async () => {
const deps: AgentDeps = {
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
- availableModels: [{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
- contextWindow: 500_000,
- efforts: ['minimal', 'low', 'medium', 'high'],
- defaultEffort: 'medium',
- }],
+ availableModels: [
+ {
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
+ contextWindow: 500_000,
+ efforts: ["minimal", "low", "medium", "high"],
+ defaultEffort: "medium",
+ },
+ ],
},
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: async () => {
- throw new Error('xAI token unavailable');
+ throw new Error("xAI token unavailable");
},
};
- await expect(new PiAgent(deps).startSession({
- sessionId: 'grok-46-native-failed',
- workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- })).rejects.toThrow(/BYOM provider 'xai' cannot serve model 'grok-4.6'.*refusing to fall back/);
+ await expect(
+ new PiAgent(deps).startSession({
+ sessionId: "grok-46-native-failed",
+ workingDir: cwd,
+ model: "grok-4.6",
+ providerId: "xai",
+ }),
+ ).rejects.toThrow(
+ /BYOM provider 'xai' cannot serve model 'grok-4.6'.*refusing to fall back/,
+ );
expect(captured.args).toEqual([]);
});
- it('passes resume identity so a historical xAI model can stay private to the restored session', async () => {
+ it("passes resume identity so a historical xAI model can stay private to the restored session", async () => {
const resolver = vi.fn(async (ctx) => ({
- providers: [{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:9',
- api: 'anthropic-messages' as const,
- modelIdAliases: { 'grok-retired': 'xai/grok-retired' },
- models: [{ id: 'xai/grok-retired', api: 'anthropic-messages' as const }],
- }],
+ providers: [
+ {
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:9",
+ api: "anthropic-messages" as const,
+ modelIdAliases: { "grok-retired": "xai/grok-retired" },
+ models: [
+ { id: "xai/grok-retired", api: "anthropic-messages" as const },
+ ],
+ },
+ ],
env: {},
}));
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "SuperGrok",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'provider-auth-placeholder' }),
+ getAuthEnv: async () => ({
+ CINDY_PI_API_KEY: "provider-auth-placeholder",
+ }),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: { availableModels: [] },
resolvePiAgentHome: () => agentHome,
@@ -1913,117 +2719,153 @@ describe('Pi provider-aware model routing', () => {
});
const handle = await agent.startSession({
- sessionId: 'historical-xai-resume',
- resumeSessionId: 'pi-sdk-session-old',
+ sessionId: "historical-xai-resume",
+ resumeSessionId: "pi-sdk-session-old",
workingDir: cwd,
- model: 'grok-retired',
- providerId: 'xai',
+ model: "grok-retired",
+ providerId: "xai",
});
- expect(resolver).toHaveBeenCalledWith(expect.objectContaining({
- providerId: 'xai',
- model: 'grok-retired',
- resumeSessionId: 'pi-sdk-session-old',
- }));
- expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))
- .toEqual(['--model', 'xai/grok-retired']);
+ expect(resolver).toHaveBeenCalledWith(
+ expect.objectContaining({
+ providerId: "xai",
+ model: "grok-retired",
+ resumeSessionId: "pi-sdk-session-old",
+ }),
+ );
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--model"),
+ captured.args.indexOf("--model") + 2,
+ ),
+ ).toEqual(["--model", "xai/grok-retired"]);
await handle.close();
});
- it('restores a retired OpenAI context profile through its native subscription provider', async () => {
+ it("restores a retired OpenAI context profile through its native subscription provider", async () => {
const resolver = vi.fn(async () => ({
- providers: [{
- id: 'openai-codex',
- sourceProviderId: 'openai',
- name: 'OpenAI (ChatGPT)',
- baseUrl: 'http://127.0.0.1:9',
- inheritModels: true,
- models: [{
- id: 'chatgpt/gpt-5.6-sol[1m]',
- wireId: 'gpt-5.6-sol[1m]',
- catalogAddition: true,
- }],
- }],
+ providers: [
+ {
+ id: "openai-codex",
+ sourceProviderId: "openai",
+ name: "OpenAI (ChatGPT)",
+ baseUrl: "http://127.0.0.1:9",
+ inheritModels: true,
+ models: [
+ {
+ id: "chatgpt/gpt-5.6-sol[1m]",
+ wireId: "gpt-5.6-sol[1m]",
+ catalogAddition: true,
+ },
+ ],
+ },
+ ],
env: {},
}));
const agent = new PiAgent({
auth: {
- getState: async () => ({ authenticated: true, identity: 'ChatGPT', authSource: 'oauth' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "ChatGPT",
+ authSource: "oauth" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: { availableModels: [] },
resolvePiAgentHome: () => agentHome,
resolvePiNativeProviders: resolver,
resolvePiRuntimeModelDescriptor: () => ({
- id: 'chatgpt/gpt-5.6-sol[1m]',
- displayName: 'GPT-5.6-Sol (1M · Higher usage)',
+ id: "chatgpt/gpt-5.6-sol[1m]",
+ displayName: "GPT-5.6-Sol (1M · Higher usage)",
contextWindow: 1_000_000,
- efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'],
- defaultEffort: 'medium',
+ efforts: ["minimal", "low", "medium", "high", "xhigh"],
+ defaultEffort: "medium",
}),
});
const handle = await agent.startSession({
- sessionId: 'historical-openai-profile-resume',
- resumeSessionId: 'pi-sdk-session-openai-profile',
+ sessionId: "historical-openai-profile-resume",
+ resumeSessionId: "pi-sdk-session-openai-profile",
workingDir: cwd,
- model: 'chatgpt/gpt-5.6-sol[1m]',
- providerId: 'openai',
+ model: "chatgpt/gpt-5.6-sol[1m]",
+ providerId: "openai",
});
- expect(resolver).toHaveBeenCalledWith(expect.objectContaining({
- providerId: 'openai',
- model: 'chatgpt/gpt-5.6-sol[1m]',
- resumeSessionId: 'pi-sdk-session-openai-profile',
- }));
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'openai-codex']);
- expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))
- .toEqual(['--model', 'gpt-5.6-sol[1m]']);
+ expect(resolver).toHaveBeenCalledWith(
+ expect.objectContaining({
+ providerId: "openai",
+ model: "chatgpt/gpt-5.6-sol[1m]",
+ resumeSessionId: "pi-sdk-session-openai-profile",
+ }),
+ );
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "openai-codex"]);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--model"),
+ captured.args.indexOf("--model") + 2,
+ ),
+ ).toEqual(["--model", "gpt-5.6-sol[1m]"]);
await handle.close();
});
- it('keeps built-in gateway reasoning when a same-id non-reasoning BYOM empties the flat effort intersection', async () => {
- const resolver = vi.fn((_providerId: string | null | undefined, modelId: string) => {
- if (modelId !== 'shared-model') return null;
- return {
- id: modelId,
- displayName: 'Shared through Cindy',
- contextWindow: 200_000,
- efforts: ['minimal', 'low', 'high'] as const,
- defaultEffort: 'high' as const,
- };
- });
+ it("keeps built-in gateway reasoning when a same-id non-reasoning BYOM empties the flat effort intersection", async () => {
+ const resolver = vi.fn(
+ (_providerId: string | null | undefined, modelId: string) => {
+ if (modelId !== "shared-model") return null;
+ return {
+ id: modelId,
+ displayName: "Shared through Cindy",
+ contextWindow: 200_000,
+ efforts: ["minimal", "low", "high"] as const,
+ defaultEffort: "high" as const,
+ };
+ },
+ );
const deps: AgentDeps = {
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
// 模拟 flat availableModels 已因 non-reasoning BYOM 同 id 冲突收敛为空。
availableModels: [
- { id: 'shared-model', displayName: 'Shared', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ {
+ id: "shared-model",
+ displayName: "Shared",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiGatewayModelApi: () => 'anthropic-messages',
+ resolvePiGatewayModelApi: () => "anthropic-messages",
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
- models: [{ id: 'shared-model', reasoning: false }],
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [{ id: "shared-model", reasoning: false }],
},
],
env: {},
@@ -2033,120 +2875,158 @@ describe('Pi provider-aware model routing', () => {
const agent = new PiAgent(deps);
const handle = await agent.startSession({
- sessionId: 'gateway-reasoning-collision',
+ sessionId: "gateway-reasoning-collision",
workingDir: cwd,
- model: 'shared-model',
- providerId: 'openai',
- effort: 'high',
+ model: "shared-model",
+ providerId: "openai",
+ effort: "high",
});
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as {
- providers: Record<string, { models: Array<{ id: string; reasoning: boolean }> }>;
+ providers: Record<
+ string,
+ { models: Array<{ id: string; reasoning: boolean }> }
+ >;
};
- expect(resolver).toHaveBeenCalledWith('openai', 'shared-model');
- expect(models.providers.cindy?.models.find((model) => model.id === 'shared-model')).toMatchObject({
+ expect(resolver).toHaveBeenCalledWith("openai", "shared-model");
+ expect(
+ models.providers.cindy?.models.find(
+ (model) => model.id === "shared-model",
+ ),
+ ).toMatchObject({
reasoning: true,
});
- expect(models.providers['native-a']?.models.find((model) => model.id === 'shared-model')).toMatchObject({
+ expect(
+ models.providers["native-a"]?.models.find(
+ (model) => model.id === "shared-model",
+ ),
+ ).toMatchObject({
reasoning: false,
});
- expect(captured.requests).toContainEqual({ type: 'set_thinking_level', level: 'high' });
+ expect(captured.requests).toContainEqual({
+ type: "set_thinking_level",
+ level: "high",
+ });
await handle.close();
});
it.each([
- ['anthropic-messages', 'messages-model', undefined],
- ['openai-responses', 'responses-model', 'http://127.0.0.1:9988/v1'],
- ['openai-completions', 'moonshotai/kimi-k3', 'http://127.0.0.1:9988/v1'],
- ['google-generative-ai', 'google/gemini-3.6-flash', 'http://127.0.0.1:9988/v1beta'],
+ ["anthropic-messages", "messages-model", undefined],
+ ["openai-responses", "responses-model", "http://127.0.0.1:9988/v1"],
+ ["openai-completions", "moonshotai/kimi-k3", "http://127.0.0.1:9988/v1"],
+ [
+ "google-generative-ai",
+ "google/gemini-3.6-flash",
+ "http://127.0.0.1:9988/v1beta",
+ ],
] as const)(
- 'keeps provider cindy while emitting Gateway API %s',
+ "keeps provider cindy while emitting Gateway API %s",
async (api, modelId, baseUrl) => {
- const deps: AgentDeps = {
- auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
- triggerLogin: async () => ({ authenticated: true }),
- logout: async () => {},
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
- },
- runtimeConfig: { endpoint: 'http://127.0.0.1:9988/' },
- binaryPath: path.join(agentHome, 'pi'),
- logger: noopLogger,
- capabilityAdditions: {
- availableModels: [
- {
- id: modelId,
- displayName: modelId,
- contextWindow: 200_000,
- efforts: [],
- defaultEffort: null,
- },
- ],
- },
- resolvePiAgentHome: () => agentHome,
- resolvePiGatewayModelApi: () => api,
- resolvePiGatewayModelSpec: () => ({
- api,
- ...(api === 'openai-completions'
- ? {
- compat: {
- maxTokensField: 'max_tokens',
- thinkingFormat: 'openai',
- requiresReasoningContentOnAssistantMessages: true,
- deferredToolsMode: 'kimi',
- },
- }
- : {}),
- }),
- };
-
- const handle = await new PiAgent(deps).startSession({
- sessionId: `gateway-${api}`,
- workingDir: cwd,
- model: modelId,
- providerId: 'xd',
- });
-
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'cindy']);
- const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
- ) as {
- providers: Record<string, {
- api: string;
- models: Array<{
- id: string;
- api?: string;
- baseUrl?: string;
- headers?: Record<string, string>;
- compat?: Record<string, unknown>;
- }>;
- }>;
- };
- expect(models.providers.cindy?.api).toBe('anthropic-messages');
- const model = models.providers.cindy?.models.find((candidate) => candidate.id === modelId);
- expect(model).toMatchObject({ api });
- expect(model?.baseUrl).toBe(baseUrl);
- if (api === 'openai-completions') {
- expect(model?.compat).toMatchObject({
- maxTokensField: 'max_tokens',
- thinkingFormat: 'openai',
- requiresReasoningContentOnAssistantMessages: true,
- deferredToolsMode: 'kimi',
- });
- }
- if (api === 'google-generative-ai') {
- expect(model?.headers).toEqual({
- authorization: 'Bearer $CINDY_PI_API_KEY',
- 'x-goog-api-key': '$CINDY_PI_API_KEY',
- });
- }
- await handle.close();
- });
-
- it('writes Gateway thinkingLevelMap from server efforts when catalog api mismatches', async () => {
+ const deps: AgentDeps = {
+ auth: {
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
+ },
+ runtimeConfig: { endpoint: "http://127.0.0.1:9988/" },
+ binaryPath: path.join(agentHome, "pi"),
+ logger: noopLogger,
+ capabilityAdditions: {
+ availableModels: [
+ {
+ id: modelId,
+ displayName: modelId,
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ },
+ resolvePiAgentHome: () => agentHome,
+ resolvePiGatewayModelApi: () => api,
+ resolvePiGatewayModelSpec: () => ({
+ api,
+ ...(api === "openai-completions"
+ ? {
+ compat: {
+ maxTokensField: "max_tokens",
+ thinkingFormat: "openai",
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: "kimi",
+ },
+ }
+ : {}),
+ }),
+ };
+
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: `gateway-${api}`,
+ workingDir: cwd,
+ model: modelId,
+ providerId: "xd",
+ });
+
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "cindy"]);
+ const models = JSON.parse(
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
+ ) as {
+ providers: Record<
+ string,
+ {
+ api: string;
+ models: Array<{
+ id: string;
+ api?: string;
+ baseUrl?: string;
+ headers?: Record<string, string>;
+ compat?: Record<string, unknown>;
+ }>;
+ }
+ >;
+ };
+ expect(models.providers.cindy?.api).toBe("anthropic-messages");
+ const model = models.providers.cindy?.models.find(
+ (candidate) => candidate.id === modelId,
+ );
+ expect(model).toMatchObject({ api });
+ expect(model?.baseUrl).toBe(baseUrl);
+ if (api === "openai-completions") {
+ expect(model?.compat).toMatchObject({
+ maxTokensField: "max_tokens",
+ thinkingFormat: "openai",
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: "kimi",
+ });
+ }
+ if (api === "google-generative-ai") {
+ expect(model?.headers).toEqual({
+ authorization: "Bearer $CINDY_PI_API_KEY",
+ "x-goog-api-key": "$CINDY_PI_API_KEY",
+ });
+ }
+ await handle.close();
+ },
+ );
+
+ it('writes Gateway thinkingLevelMap from server efforts when catalog api mismatches', async () => {
const deps: AgentDeps = {
auth: {
getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
@@ -2261,19 +3141,23 @@ describe('Pi provider-aware model routing', () => {
it('keeps BYOM startup when the model is outside the XD v3 Pi catalog', async () => {
const deps: AgentDeps = {
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
{
- id: 'byom-only-model',
- displayName: 'BYOM Only Model',
+ id: "byom-only-model",
+ displayName: "BYOM Only Model",
contextWindow: 128_000,
efforts: [],
defaultEffort: null,
@@ -2286,11 +3170,11 @@ describe('Pi provider-aware model routing', () => {
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'my-local',
- name: 'My Local',
- baseUrl: 'http://127.0.0.1:11434/v1',
- api: 'openai-completions',
- models: [{ id: 'byom-only-model' }],
+ id: "my-local",
+ name: "My Local",
+ baseUrl: "http://127.0.0.1:11434/v1",
+ api: "openai-completions",
+ models: [{ id: "byom-only-model" }],
},
],
env: {},
@@ -2298,44 +3182,64 @@ describe('Pi provider-aware model routing', () => {
};
const handle = await new PiAgent(deps).startSession({
- sessionId: 'byom-outside-xd-v3',
+ sessionId: "byom-outside-xd-v3",
workingDir: cwd,
- model: 'byom-only-model',
- providerId: 'my-local',
+ model: "byom-only-model",
+ providerId: "my-local",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'my-local']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "my-local"]);
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as {
- providers: Record<string, {
- models: Array<{ id: string; api?: string }>;
- }>;
+ providers: Record<
+ string,
+ {
+ models: Array<{ id: string; api?: string }>;
+ }
+ >;
};
- expect(models.providers.cindy?.models.find((model) => model.id === 'byom-only-model'))
- .toBeUndefined();
- expect(models.providers['my-local']?.models.find((model) => model.id === 'byom-only-model'))
- .toMatchObject({ id: 'byom-only-model' });
+ expect(
+ models.providers.cindy?.models.find(
+ (model) => model.id === "byom-only-model",
+ ),
+ ).toBeUndefined();
+ expect(
+ models.providers["my-local"]?.models.find(
+ (model) => model.id === "byom-only-model",
+ ),
+ ).toMatchObject({ id: "byom-only-model" });
await handle.close();
});
- it('omits an unsupported Gateway route without aborting a same-id BYOM session', async () => {
+ it("omits an unsupported Gateway route without aborting a same-id BYOM session", async () => {
const deps: AgentDeps = {
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
{
- id: 'shared-future-model',
- displayName: 'Shared Future Model',
+ id: "shared-future-model",
+ displayName: "Shared Future Model",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
@@ -2347,11 +3251,11 @@ describe('Pi provider-aware model routing', () => {
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'my-local',
- name: 'My Local',
- baseUrl: 'http://127.0.0.1:11434/v1',
- api: 'openai-completions',
- models: [{ id: 'shared-future-model' }],
+ id: "my-local",
+ name: "My Local",
+ baseUrl: "http://127.0.0.1:11434/v1",
+ api: "openai-completions",
+ models: [{ id: "shared-future-model" }],
},
],
env: {},
@@ -2359,72 +3263,88 @@ describe('Pi provider-aware model routing', () => {
};
const handle = await new PiAgent(deps).startSession({
- sessionId: 'unsupported-xd-same-id-byom',
+ sessionId: "unsupported-xd-same-id-byom",
workingDir: cwd,
- model: 'shared-future-model',
- providerId: 'my-local',
+ model: "shared-future-model",
+ providerId: "my-local",
});
const models = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as { providers: Record<string, { models: Array<{ id: string }> }> };
- expect(models.providers.cindy?.models.find((model) => model.id === 'shared-future-model'))
- .toBeUndefined();
- expect(models.providers['my-local']?.models.find((model) => model.id === 'shared-future-model'))
- .toMatchObject({ id: 'shared-future-model' });
+ expect(
+ models.providers.cindy?.models.find(
+ (model) => model.id === "shared-future-model",
+ ),
+ ).toBeUndefined();
+ expect(
+ models.providers["my-local"]?.models.find(
+ (model) => model.id === "shared-future-model",
+ ),
+ ).toMatchObject({ id: "shared-future-model" });
await handle.close();
});
- it('reconciles a stale persisted effort to the selected BYOM model default before startup', async () => {
- const resolver = vi.fn((providerId: string | null | undefined, modelId: string) => {
- if (providerId !== 'native-a' || modelId !== 'shared-model') return null;
- return {
- id: modelId,
- displayName: 'Shared through BYOM',
- contextWindow: 200_000,
- efforts: ['low', 'xhigh'] as const,
- defaultEffort: 'xhigh' as const,
- };
- });
+ it("reconciles a stale persisted effort to the selected BYOM model default before startup", async () => {
+ const resolver = vi.fn(
+ (providerId: string | null | undefined, modelId: string) => {
+ if (providerId !== "native-a" || modelId !== "shared-model")
+ return null;
+ return {
+ id: modelId,
+ displayName: "Shared through BYOM",
+ contextWindow: 200_000,
+ efforts: ["low", "xhigh"] as const,
+ defaultEffort: "xhigh" as const,
+ };
+ },
+ );
const deps: AgentDeps = {
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels: [
{
- id: 'shared-model',
- displayName: 'Shared',
+ id: "shared-model",
+ displayName: "Shared",
contextWindow: 200_000,
- efforts: ['low'],
- defaultEffort: 'low',
+ efforts: ["low"],
+ defaultEffort: "low",
},
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiGatewayModelApi: () => 'anthropic-messages',
+ resolvePiGatewayModelApi: () => "anthropic-messages",
resolvePiNativeProviders: async () => ({
providers: [
{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
models: [
{
- id: 'shared-model',
+ id: "shared-model",
reasoning: true,
thinkingLevelMap: {
minimal: null,
- low: 'low',
+ low: "low",
medium: null,
high: null,
- xhigh: 'xhigh',
+ xhigh: "xhigh",
max: null,
},
},
@@ -2438,210 +3358,366 @@ describe('Pi provider-aware model routing', () => {
const agent = new PiAgent(deps);
const handle = await agent.startSession({
- sessionId: 'stale-effort',
+ sessionId: "stale-effort",
workingDir: cwd,
- model: 'shared-model',
- providerId: 'native-a',
+ model: "shared-model",
+ providerId: "native-a",
// 旧任务保存的 high 已在用户收窄能力后失效;必须走当前路由默认 xhigh,不能发 high→null。
- effort: 'high',
+ effort: "high",
});
- expect(resolver).toHaveBeenCalledWith('native-a', 'shared-model');
- expect(captured.requests).toContainEqual({ type: 'set_thinking_level', level: 'xhigh' });
- expect(captured.requests).not.toContainEqual({ type: 'set_thinking_level', level: 'high' });
+ expect(resolver).toHaveBeenCalledWith("native-a", "shared-model");
+ expect(captured.requests).toContainEqual({
+ type: "set_thinking_level",
+ level: "xhigh",
+ });
+ expect(captured.requests).not.toContainEqual({
+ type: "set_thinking_level",
+ level: "high",
+ });
await handle.close();
});
- it('freezes active BYOM effort selection to the startup models.json snapshot', async () => {
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- {
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
- models: [{
- id: 'local-model',
- reasoning: true,
- thinkingLevelMap: {
- minimal: null,
- low: 'low',
- medium: null,
- high: null,
- xhigh: null,
- max: null,
- },
- }],
- },
- ],
- env: {},
- })));
+ it("freezes active BYOM effort selection to the startup models.json snapshot", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "local-model",
+ reasoning: true,
+ thinkingLevelMap: {
+ minimal: null,
+ low: "low",
+ medium: null,
+ high: null,
+ xhigh: null,
+ max: null,
+ },
+ },
+ ],
+ },
+ ],
+ env: {},
+ })),
+ );
const handle = await agent.startSession({
- sessionId: 'frozen-effort-snapshot',
+ sessionId: "frozen-effort-snapshot",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
- effort: 'low',
+ model: "local-model",
+ providerId: "native-a",
+ effort: "low",
+ });
+ const startupRequests = captured.requests.filter(
+ (request) => request.type === "set_thinking_level",
+ );
+ expect(startupRequests).toContainEqual({
+ type: "set_thinking_level",
+ level: "low",
});
- const startupRequests = captured.requests.filter((request) => request.type === 'set_thinking_level');
- expect(startupRequests).toContainEqual({ type: 'set_thinking_level', level: 'low' });
// provider 保存后 renderer 目录可能已出现 xhigh,但这个活动 Pi 进程仍读旧 models.json。
- await expect(handle.setEffort!('xhigh')).rejects.toThrow(/startup model snapshot.*restart the Pi session/);
- expect(captured.requests.filter((request) => request.type === 'set_thinking_level')).toHaveLength(
- startupRequests.length,
+ await expect(handle.setEffort!("xhigh")).rejects.toThrow(
+ /startup model snapshot.*restart the Pi session/,
);
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "set_thinking_level",
+ ),
+ ).toHaveLength(startupRequests.length);
- await handle.setEffort!('low');
- expect(captured.requests.filter((request) => request.type === 'set_thinking_level')).toHaveLength(
- startupRequests.length + 1,
- );
+ await handle.setEffort!("low");
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "set_thinking_level",
+ ),
+ ).toHaveLength(startupRequests.length + 1);
await handle.close();
});
- it('rejects an atomic model switch before set_model when its effort is outside the startup snapshot', async () => {
+ it("rejects an atomic model switch before set_model when its effort is outside the startup snapshot", async () => {
const lowOnly = {
reasoning: true,
thinkingLevelMap: {
minimal: null,
- low: 'low',
+ low: "low",
medium: null,
high: null,
xhigh: null,
max: null,
},
} as const;
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
- models: [
- { id: 'local-model', ...lowOnly },
- { id: 'target-model', ...lowOnly },
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "local-model", ...lowOnly },
+ { id: "target-model", ...lowOnly },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 200_000,
+ efforts: ["low"],
+ defaultEffort: "low",
+ },
+ {
+ id: "target-model",
+ displayName: "Target",
+ contextWindow: 200_000,
+ efforts: ["low"],
+ defaultEffort: "low",
+ },
],
- }],
- env: {},
- }), [
- { id: 'local-model', displayName: 'Local', contextWindow: 200_000, efforts: ['low'], defaultEffort: 'low' },
- { id: 'target-model', displayName: 'Target', contextWindow: 200_000, efforts: ['low'], defaultEffort: 'low' },
- ]));
+ ),
+ );
const handle = await agent.startSession({
- sessionId: 'atomic-effort-preflight',
+ sessionId: "atomic-effort-preflight",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
- effort: 'low',
+ model: "local-model",
+ providerId: "native-a",
+ effort: "low",
});
const beforeSwitch = captured.requests.length;
// renderer catalog 热更新后把目标模型显示成 high;活动 Pi 的 models.json 仍只允许 low。
- await expect(handle.setModel!('target-model', { providerId: 'native-a', effort: 'high' }))
- .rejects.toThrow(/startup model snapshot/);
+ await expect(
+ handle.setModel!("target-model", {
+ providerId: "native-a",
+ effort: "high",
+ }),
+ ).rejects.toThrow(/startup model snapshot/);
expect(captured.requests.slice(beforeSwitch)).not.toContainEqual({
- type: 'set_model',
- provider: 'native-a',
- modelId: 'target-model',
+ type: "set_model",
+ provider: "native-a",
+ modelId: "target-model",
});
- expect(handle.model).toBe('local-model');
+ expect(handle.model).toBe("local-model");
await handle.close();
});
- it('freezes omitted BYOM reasoning to an empty startup capability snapshot', async () => {
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
- // buildPiNativeProvidersFromConfigs omits reasoning for this model; models.json writes false.
- models: [{ id: 'local-model' }],
- }],
- env: {},
- })));
+ it("freezes omitted BYOM reasoning to an empty startup capability snapshot", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ // buildPiNativeProvidersFromConfigs omits reasoning for this model; models.json writes false.
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
const handle = await agent.startSession({
- sessionId: 'frozen-non-reasoning-snapshot',
+ sessionId: "frozen-non-reasoning-snapshot",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
- await expect(handle.setEffort!('xhigh')).rejects.toThrow(/startup model snapshot/);
- expect(captured.requests.some((request) => request.type === 'set_thinking_level')).toBe(false);
+ await expect(handle.setEffort!("xhigh")).rejects.toThrow(
+ /startup model snapshot/,
+ );
+ expect(
+ captured.requests.some(
+ (request) => request.type === "set_thinking_level",
+ ),
+ ).toBe(false);
await handle.close();
});
- it('accepts the low placeholder after switching to a non-reasoning gateway model', async () => {
+ it("accepts the low placeholder after switching to a non-reasoning gateway model", async () => {
const availableModels: readonly ModelDescriptor[] = [
- { id: 'local-model', displayName: 'Local', contextWindow: 200_000, efforts: ['low'], defaultEffort: 'low' },
- { id: 'gateway-model', displayName: 'Gateway', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 200_000,
+ efforts: ["low"],
+ defaultEffort: "low",
+ },
+ {
+ id: "gateway-model",
+ displayName: "Gateway",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
];
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [{
- id: 'native-a',
- name: 'Native A',
- baseUrl: 'http://a.test',
- api: 'openai-responses',
- models: [{
- id: 'local-model',
- reasoning: true,
- thinkingLevelMap: {
- minimal: null,
- low: 'low',
- medium: null,
- high: null,
- xhigh: null,
- max: null,
- },
- }],
- }],
- env: {},
- }), availableModels));
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "local-model",
+ reasoning: true,
+ thinkingLevelMap: {
+ minimal: null,
+ low: "low",
+ medium: null,
+ high: null,
+ xhigh: null,
+ max: null,
+ },
+ },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ availableModels,
+ ),
+ );
const handle = await agent.startSession({
- sessionId: 'switch-to-non-reasoning-gateway',
+ sessionId: "switch-to-non-reasoning-gateway",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
- effort: 'low',
- });
- const beforePlaceholder = captured.requests.filter((request) => request.type === 'set_thinking_level').length;
-
- await handle.setModel!('gateway-model', { providerId: null });
- await expect(handle.setEffort!('low')).resolves.toBeUndefined();
- expect(captured.requests.filter((request) => request.type === 'set_thinking_level')).toHaveLength(
- beforePlaceholder,
- );
+ model: "local-model",
+ providerId: "native-a",
+ effort: "low",
+ });
+ const beforePlaceholder = captured.requests.filter(
+ (request) => request.type === "set_thinking_level",
+ ).length;
+
+ await handle.setModel!("gateway-model", { providerId: null });
+ await expect(handle.setEffort!("low")).resolves.toBeUndefined();
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "set_thinking_level",
+ ),
+ ).toHaveLength(beforePlaceholder);
await handle.close();
});
const byomDeps = (
- resolvePiNativeProviders: AgentDeps['resolvePiNativeProviders'],
+ resolvePiNativeProviders: AgentDeps["resolvePiNativeProviders"],
availableModels: readonly ModelDescriptor[] = [
- { id: 'local-model', displayName: 'Local', contextWindow: 200_000, efforts: [], defaultEffort: null },
+ {
+ id: "local-model",
+ displayName: "Local",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
],
): AgentDeps => ({
auth: {
- getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ getState: async () => ({
+ authenticated: true,
+ identity: "test",
+ authSource: "api-key" as const,
+ }),
triggerLogin: async () => ({ authenticated: true }),
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
- binaryPath: path.join(agentHome, 'pi'),
+ runtimeConfig: { endpoint: "http://127.0.0.1:9" },
+ binaryPath: path.join(agentHome, "pi"),
logger: noopLogger,
capabilityAdditions: {
availableModels,
},
resolvePiAgentHome: () => agentHome,
spawnPiSubagentRunner: testSubagentRunnerHost,
- resolvePiGatewayModelApi: () => 'anthropic-messages',
+ resolvePiGatewayModelApi: () => "anthropic-messages",
resolvePiNativeProviders,
});
- it('omits remote Google Gateway routes that cannot sanitize x-goog-api-key', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ 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") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
+ }
+ if (command.type === "set_model") {
+ return { success: true, data: { contextWindow: 200_000 } };
+ }
+ return { success: true, data: {} };
+ };
+ const models: readonly ModelDescriptor[] = [
+ {
+ id: "model-a",
+ displayName: "A",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "model-b",
+ displayName: "B",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ];
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "model-a" }, { id: "model-b" }],
+ },
+ ],
+ env: {},
+ }),
+ models,
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "verify-same-sized-target",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ });
+
+ 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",
+ ]);
+ await handle.close();
+ });
+
+ it("omits remote Google Gateway routes that cannot sanitize x-goog-api-key", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -2649,26 +3725,32 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const written = new Map<string, string>();
- const modelId = 'google/gemini-3.6-flash';
- const base = byomDeps(async () => ({ providers: [], env: {} }), [
- {
- id: modelId,
- displayName: 'Gemini 3.6 Flash',
- contextWindow: 200_000,
- efforts: [],
- defaultEffort: null,
- },
- ]);
+ const modelId = "google/gemini-3.6-flash";
+ const base = byomDeps(
+ async () => ({ providers: [], env: {} }),
+ [
+ {
+ id: modelId,
+ displayName: "Gemini 3.6 Flash",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ );
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolvePiGatewayModelApi: () => 'google-generative-ai',
- resolvePiGatewayModelSpec: () => ({ api: 'google-generative-ai' }),
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolvePiGatewayModelApi: () => "google-generative-ai",
+ resolvePiGatewayModelSpec: () => ({ api: "google-generative-ai" }),
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async () => remoteStub,
getRemotePiFileOps: () => ({
mkdirp: async () => {},
@@ -2681,16 +3763,20 @@ describe('Pi provider-aware model routing', () => {
}),
});
- await expect(agent.startSession({
- sessionId: 'remote-google-header-sanitizer',
- workingDir: cwd,
- model: modelId,
- providerId: 'xd',
- remoteHostId: 'remote-host',
- })).rejects.toThrow(/\[PI_GATEWAY_PROTOCOL_UNAVAILABLE\]/);
- const modelsJson = [...written.entries()].find(([filePath]) => filePath.endsWith('models.json'))?.[1];
+ await expect(
+ agent.startSession({
+ sessionId: "remote-google-header-sanitizer",
+ workingDir: cwd,
+ model: modelId,
+ providerId: "xd",
+ remoteHostId: "remote-host",
+ }),
+ ).rejects.toThrow(/\[PI_GATEWAY_PROTOCOL_UNAVAILABLE\]/);
+ const modelsJson = [...written.entries()].find(([filePath]) =>
+ filePath.endsWith("models.json"),
+ )?.[1];
expect(modelsJson).toBeTruthy();
- expect(modelsJson).not.toContain('x-goog-api-key');
+ expect(modelsJson).not.toContain("x-goog-api-key");
const models = JSON.parse(modelsJson!) as {
providers: Record<string, { models: Array<{ id: string }> }>;
};
@@ -2698,291 +3784,387 @@ describe('Pi provider-aware model routing', () => {
});
function installPlanModeExtension(): void {
- const extension = path.join(path.dirname(path.join(agentHome, 'pi')), 'examples', 'extensions', 'plan-mode', 'index.ts');
+ const extension = path.join(
+ path.dirname(path.join(agentHome, "pi")),
+ "examples",
+ "extensions",
+ "plan-mode",
+ "index.ts",
+ );
mkdirSync(path.dirname(extension), { recursive: true });
- writeFileSync(extension, '// mocked plan-mode extension');
+ writeFileSync(extension, "// mocked plan-mode extension");
}
- it('fails closed for an explicit BYOM route when native provider resolution throws (no silent gateway fallback)', async () => {
+ it("fails closed for an explicit BYOM route when native provider resolution throws (no silent gateway fallback)", async () => {
// 显式选自定义 provider 但配置/safeStorage 暂时读不到:必须抛,不能静默改发 Cindy 网关。
- const agent = new PiAgent(byomDeps(async () => {
- throw new Error('safeStorage temporarily unavailable');
- }));
- await expect(agent.startSession({
- sessionId: 'byom-resolve-fail',
- workingDir: cwd,
- model: 'local-model',
- providerId: 'my-local',
- })).rejects.toThrow(/BYOM provider 'my-local' cannot serve model 'local-model'/);
+ const agent = new PiAgent(
+ byomDeps(async () => {
+ throw new Error("safeStorage temporarily unavailable");
+ }),
+ );
+ await expect(
+ agent.startSession({
+ sessionId: "byom-resolve-fail",
+ workingDir: cwd,
+ model: "local-model",
+ providerId: "my-local",
+ }),
+ ).rejects.toThrow(
+ /BYOM provider 'my-local' cannot serve model 'local-model'/,
+ );
// 未走到 spawn(--provider 参数从未拼装)。
expect(captured.args).toEqual([]);
});
- it('fails closed when an explicit BYOM provider exists but no longer offers the model', async () => {
+ it("fails closed when an explicit BYOM provider exists but no longer offers the model", async () => {
// 用户编辑配置后从现有 provider 删/改了当前 model:provider 仍在,但不含该 model。
// resolveProviderForModel 会静默回落 cindy(local-model 网关目录里也有 → 会“成功”);
// 显式 BYOM 必须 fail closed,不能悄悄把请求发往网关(codex review P1)。
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- { id: 'my-local', name: 'My Local', baseUrl: 'http://l.test', api: 'openai-completions', models: [{ id: 'other-model' }] },
- ],
- env: {},
- })));
- await expect(agent.startSession({
- sessionId: 'byom-model-removed',
- workingDir: cwd,
- model: 'local-model',
- providerId: 'my-local',
- })).rejects.toThrow(/cannot serve model 'local-model'.*refusing to fall back/s);
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "my-local",
+ name: "My Local",
+ baseUrl: "http://l.test",
+ api: "openai-completions",
+ models: [{ id: "other-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
+ await expect(
+ agent.startSession({
+ sessionId: "byom-model-removed",
+ workingDir: cwd,
+ model: "local-model",
+ providerId: "my-local",
+ }),
+ ).rejects.toThrow(
+ /cannot serve model 'local-model'.*refusing to fall back/s,
+ );
expect(captured.args).toEqual([]);
});
- it('fails closed for an explicit BYOM route absent from the resolved provider set', async () => {
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- { id: 'native-a', name: 'Native A', baseUrl: 'http://a.test', api: 'openai-completions', models: [{ id: 'local-model' }] },
- ],
- env: {},
- })));
- await expect(agent.startSession({
- sessionId: 'byom-absent',
- workingDir: cwd,
- model: 'local-model',
- providerId: 'my-local',
- })).rejects.toThrow(/refusing to fall back to the Cindy gateway/);
+ it("fails closed for an explicit BYOM route absent from the resolved provider set", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
+ await expect(
+ agent.startSession({
+ sessionId: "byom-absent",
+ workingDir: cwd,
+ model: "local-model",
+ providerId: "my-local",
+ }),
+ ).rejects.toThrow(/refusing to fall back to the Cindy gateway/);
expect(captured.args).toEqual([]);
});
- it('fails closed when setModel selects a BYOM provider added after the session started', async () => {
+ it("fails closed when setModel selects a BYOM provider added after the session started", async () => {
// 启动快照只含 native-a;会话中途选一个启动后才新增的自定义 provider 必须抛(提示重启),
// 不能静默回落 cindy 网关(codex review P1)。
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- { id: 'native-a', name: 'Native A', baseUrl: 'http://a.test', api: 'openai-completions', models: [{ id: 'local-model' }] },
- ],
- env: {},
- })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
const handle = await agent.startSession({
- sessionId: 'byom-setmodel',
+ sessionId: "byom-setmodel",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
- await expect(handle.setModel!('local-model', { providerId: 'added-later' }))
- .rejects.toThrow(/cannot serve model 'local-model'|restart the session/);
+ await expect(
+ handle.setModel!("local-model", { providerId: "added-later" }),
+ ).rejects.toThrow(/cannot serve model 'local-model'|restart the session/);
// 已在快照里的 provider 仍可正常切换。
- await expect(handle.setModel!('local-model', { providerId: 'native-a' })).resolves.toBeUndefined();
+ await expect(
+ handle.setModel!("local-model", { providerId: "native-a" }),
+ ).resolves.toBeUndefined();
await handle.close();
});
- it('fails closed when setModel picks a model the pinned BYOM provider does not offer', async () => {
+ it("fails closed when setModel picks a model the pinned BYOM provider does not offer", async () => {
// provider 在启动快照里,但用户切到一个该 provider 不提供的 model:同样不得静默回落网关。
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- { id: 'native-a', name: 'Native A', baseUrl: 'http://a.test', api: 'openai-completions', models: [{ id: 'local-model' }] },
- ],
- env: {},
- })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
const handle = await agent.startSession({
- sessionId: 'byom-setmodel-modelgone',
+ sessionId: "byom-setmodel-modelgone",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-a',
+ model: "local-model",
+ providerId: "native-a",
});
- await expect(handle.setModel!('ghost-model', { providerId: 'native-a' }))
- .rejects.toThrow(/cannot serve model 'ghost-model'/);
+ await expect(
+ handle.setModel!("ghost-model", { providerId: "native-a" }),
+ ).rejects.toThrow(/cannot serve model 'ghost-model'/);
await handle.close();
});
- it('guards image prompts by the startup provider-model capability and follows model switches', async () => {
+ it("guards image prompts by the startup provider-model capability and follows model switches", async () => {
const gatewayModels: ModelDescriptor[] = [
{
- id: 'gateway-text',
- displayName: 'Gateway Text',
+ id: "gateway-text",
+ displayName: "Gateway Text",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
supportsImageInput: false,
},
{
- id: 'gateway-vision',
- displayName: 'Gateway Vision',
+ id: "gateway-vision",
+ displayName: "Gateway Vision",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
supportsImageInput: true,
},
{
- id: 'gateway-unknown',
- displayName: 'Gateway Unknown',
+ id: "gateway-unknown",
+ displayName: "Gateway Unknown",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
},
{
- id: 'local-model',
- displayName: 'Local',
+ id: "local-model",
+ displayName: "Local",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
},
];
- const resolveGatewayModel = vi.fn((_providerId: string | null | undefined, modelId: string) =>
- gatewayModels.find((candidate) => candidate.id === modelId) ?? null,
+ const resolveGatewayModel = vi.fn(
+ (_providerId: string | null | undefined, modelId: string) =>
+ gatewayModels.find((candidate) => candidate.id === modelId) ?? null,
);
const agent = new PiAgent({
- ...byomDeps(async () => ({
- providers: [
- {
- id: 'native-text',
- name: 'Native Text',
- baseUrl: 'http://text.test',
- api: 'openai-completions',
- models: [{ id: 'local-model', input: ['text'] }],
- },
- {
- id: 'native-vision',
- name: 'Native Vision',
- baseUrl: 'http://vision.test',
- api: 'openai-completions',
- models: [{ id: 'local-model', input: ['text', 'image'] }],
- },
- ],
- env: {},
- }), gatewayModels),
+ ...byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-text",
+ name: "Native Text",
+ baseUrl: "http://text.test",
+ api: "openai-completions",
+ models: [{ id: "local-model", input: ["text"] }],
+ },
+ {
+ id: "native-vision",
+ name: "Native Vision",
+ baseUrl: "http://vision.test",
+ api: "openai-completions",
+ models: [{ id: "local-model", input: ["text", "image"] }],
+ },
+ ],
+ env: {},
+ }),
+ gatewayModels,
+ ),
resolvePiGatewayModelDescriptor: resolveGatewayModel,
});
const handle = await agent.startSession({
- sessionId: 'image-capability',
+ sessionId: "image-capability",
workingDir: cwd,
- model: 'local-model',
- providerId: 'native-text',
+ model: "local-model",
+ providerId: "native-text",
});
- const imagePath = path.join(cwd, 'screenshot.png');
+ const imagePath = path.join(cwd, "screenshot.png");
writeFileSync(
imagePath,
Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
- 'base64',
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
+ "base64",
),
);
const imageMessage = {
- type: 'user' as const,
- content: [{
- type: 'image' as const,
- path: imagePath,
- managedUrl: 'xdt-image://pi-managed/screenshot.png',
- }],
+ type: "user" as const,
+ content: [
+ {
+ type: "image" as const,
+ path: imagePath,
+ managedUrl: "xdt-image://pi-managed/screenshot.png",
+ },
+ ],
};
const mixedMessage = {
- type: 'user' as const,
+ type: "user" as const,
content: [
- { type: 'text' as const, text: 'describe this image' },
- { type: 'image' as const, path: imagePath },
+ { type: "text" as const, text: "describe this image" },
+ { type: "image" as const, path: imagePath },
],
};
const instructedMessage = {
- type: 'user' as const,
+ type: "user" as const,
content: [
- { type: 'text' as const, text: '$识图 请读取附件' },
- { type: 'image' as const, path: imagePath },
+ { type: "text" as const, text: "$识图 请读取附件" },
+ { type: "image" as const, path: imagePath },
],
};
const multiImageMessage = {
- type: 'user' as const,
+ type: "user" as const,
content: [
- { type: 'image' as const, path: imagePath },
- { type: 'image' as const, path: imagePath },
+ { type: "image" as const, path: imagePath },
+ { type: "image" as const, path: imagePath },
],
};
const modelsJson = JSON.parse(
- readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ readFileSync(
+ path.join(captured.env.PI_CODING_AGENT_DIR as string, "models.json"),
+ "utf8",
+ ),
) as {
- providers: Record<string, { models: Array<{ id: string; input: string[] }> }>;
+ providers: Record<
+ string,
+ { models: Array<{ id: string; input: string[] }> }
+ >;
};
- expect(modelsJson.providers.cindy?.models).toEqual(expect.arrayContaining([
- expect.objectContaining({ id: 'gateway-text', input: ['text'] }),
- expect.objectContaining({ id: 'gateway-vision', input: ['text', 'image'] }),
- expect.objectContaining({ id: 'gateway-unknown', input: ['text'] }),
- ]));
+ expect(modelsJson.providers.cindy?.models).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: "gateway-text", input: ["text"] }),
+ expect.objectContaining({
+ id: "gateway-vision",
+ input: ["text", "image"],
+ }),
+ expect.objectContaining({ id: "gateway-unknown", input: ["text"] }),
+ ]),
+ );
captured.requests.length = 0;
await expect(handle.send(imageMessage)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
await expect(handle.steer!(imageMessage)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
- expect(captured.requests.some((request) => request.type === 'prompt' || request.type === 'steer'))
- .toBe(false);
+ expect(
+ captured.requests.some(
+ (request) => request.type === "prompt" || request.type === "steer",
+ ),
+ ).toBe(false);
- await handle.setModel!('local-model', { providerId: 'native-vision' });
+ await handle.setModel!("local-model", { providerId: "native-vision" });
captured.requests.length = 0;
await handle.send(imageMessage);
- expect(captured.requests).toContainEqual(expect.objectContaining({
- type: 'prompt',
- message: expect.stringContaining(JSON.stringify({
- image: 1,
- uri: 'xdt-image://pi-managed/screenshot.png',
- })),
- images: [expect.objectContaining({ type: 'image', mimeType: 'image/png' })],
- }));
+ expect(captured.requests).toContainEqual(
+ expect.objectContaining({
+ type: "prompt",
+ message: expect.stringContaining(
+ JSON.stringify({
+ image: 1,
+ uri: "xdt-image://pi-managed/screenshot.png",
+ }),
+ ),
+ images: [
+ expect.objectContaining({ type: "image", mimeType: "image/png" }),
+ ],
+ }),
+ );
captured.requests.length = 0;
await handle.steer!(imageMessage);
- expect(captured.requests).toContainEqual(expect.objectContaining({
- type: 'steer',
- message: expect.stringContaining(JSON.stringify({
- image: 1,
- uri: 'xdt-image://pi-managed/screenshot.png',
- })),
- images: [expect.objectContaining({ type: 'image', mimeType: 'image/png' })],
- }));
+ expect(captured.requests).toContainEqual(
+ expect.objectContaining({
+ type: "steer",
+ message: expect.stringContaining(
+ JSON.stringify({
+ image: 1,
+ uri: "xdt-image://pi-managed/screenshot.png",
+ }),
+ ),
+ images: [
+ expect.objectContaining({ type: "image", mimeType: "image/png" }),
+ ],
+ }),
+ );
// 网关纯文本模型在 Pi/provider 调用前拒绝所有带图形态;文本指令不能绕过能力门。
- await handle.setModel!('gateway-text', { providerId: null });
+ await handle.setModel!("gateway-text", { providerId: null });
captured.requests.length = 0;
- for (const message of [imageMessage, mixedMessage, instructedMessage, multiImageMessage]) {
+ for (const message of [
+ imageMessage,
+ mixedMessage,
+ instructedMessage,
+ multiImageMessage,
+ ]) {
await expect(handle.send(message)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
}
await expect(handle.steer!(mixedMessage)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
- expect(captured.requests.some((request) => request.type === 'prompt' || request.type === 'steer'))
- .toBe(false);
+ expect(
+ captured.requests.some(
+ (request) => request.type === "prompt" || request.type === "steer",
+ ),
+ ).toBe(false);
// 能力未知同样 fail closed;活动会话只认启动时写入 models.json 的能力快照。
- await handle.setModel!('gateway-unknown', { providerId: null });
+ await handle.setModel!("gateway-unknown", { providerId: null });
await expect(handle.send(imageMessage)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
gatewayModels[0]!.supportsImageInput = true;
- await handle.setModel!('gateway-text', { providerId: null });
+ await handle.setModel!("gateway-text", { providerId: null });
await expect(handle.send(imageMessage)).rejects.toMatchObject({
- code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ code: "PI_IMAGE_INPUT_UNSUPPORTED",
});
// 明确支持图片的网关模型保留全部图片块,多图不被剥离或改写。
- await handle.setModel!('gateway-vision', { providerId: null });
+ await handle.setModel!("gateway-vision", { providerId: null });
captured.requests.length = 0;
await handle.send(multiImageMessage);
- expect(captured.requests).toContainEqual(expect.objectContaining({
- type: 'prompt',
- images: [
- expect.objectContaining({ type: 'image', mimeType: 'image/png' }),
- expect.objectContaining({ type: 'image', mimeType: 'image/png' }),
- ],
- }));
+ expect(captured.requests).toContainEqual(
+ expect.objectContaining({
+ type: "prompt",
+ images: [
+ expect.objectContaining({ type: "image", mimeType: "image/png" }),
+ expect.objectContaining({ type: "image", mimeType: "image/png" }),
+ ],
+ }),
+ );
// 轮 40-w4-t6 CRITICAL:用户显式图片读取失败 → fail-before-dispatch(抛错),
// 不再静默降级文本占位(否则 DB/UI 与 Pi 实际输入分叉)。
- await handle.setModel!('local-model', { providerId: 'native-text' });
+ await handle.setModel!("local-model", { providerId: "native-text" });
captured.requests.length = 0;
await expect(
handle.send({
- type: 'user',
- content: [{ type: 'image', path: path.join(cwd, 'missing.png') }],
+ type: "user",
+ content: [{ type: "image", path: path.join(cwd, "missing.png") }],
}),
).rejects.toThrow(/failed to read image attachment/);
// 未发送任何 prompt(失败在 dispatch 前)
@@ -2990,204 +4172,283 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
- it('waits through Pi preflight compaction when accepting a prompt', async () => {
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ it("waits through Pi preflight compaction when accepting a prompt", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'prompt-acceptance-budget',
+ sessionId: "prompt-acceptance-budget",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
});
- await handle.send({ type: 'user', content: 'continue the goal' });
+ await handle.send({ type: "user", content: "continue the goal" });
- const promptIndex = captured.requests.findIndex((request) => request.type === 'prompt');
+ const promptIndex = captured.requests.findIndex(
+ (request) => request.type === "prompt",
+ );
expect(promptIndex).toBeGreaterThanOrEqual(0);
- expect(captured.requestOptions[promptIndex]).toMatchObject({ timeoutMs: 600_000 });
+ expect(captured.requestOptions[promptIndex]).toMatchObject({
+ timeoutMs: 600_000,
+ });
const refresh = captured.requestOptions[promptIndex]?.refreshTimeoutOnEvent;
- expect(refresh?.({ type: 'compaction_start' })).toBe(true);
- expect(refresh?.({ type: 'summarization_retry_scheduled' })).toBe(true);
- expect(refresh?.({ type: 'agent_start' })).toBe(false);
+ expect(refresh?.({ type: "compaction_start" })).toBe(true);
+ expect(refresh?.({ type: "summarization_retry_scheduled" })).toBe(true);
+ expect(refresh?.({ type: "agent_start" })).toBe(false);
await handle.close();
});
- it('marks a true prompt acceptance timeout as an unconfirmed dispatch', async () => {
+ it("marks a true prompt acceptance timeout as an unconfirmed dispatch", async () => {
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'prompt') {
- throw new PiRpcRequestTimeoutError('prompt', 600_000);
+ if (command.type === "prompt") {
+ throw new PiRpcRequestTimeoutError("prompt", 600_000);
}
return { success: true, data: {} };
};
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'prompt-acceptance-timeout',
+ sessionId: "prompt-acceptance-timeout",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
});
- await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({
- name: 'TurnDispatchUnconfirmedError',
- code: 'TURN_DISPATCH_UNCONFIRMED',
+ await expect(
+ handle.send({ type: "user", content: "continue the goal" }),
+ ).rejects.toMatchObject({
+ name: "TurnDispatchUnconfirmedError",
+ code: "TURN_DISPATCH_UNCONFIRMED",
});
await handle.close();
});
it.each([
- ['transport close before response', new Error('pi process exited (code=null, signal=null)')],
- ['unknown write result', new Error('write EPIPE')],
- ['malformed response envelope', new Error('pi rpc: response for prompt missing boolean success')],
- ])('marks %s after prompt request starts as an unconfirmed dispatch', async (_label, failure) => {
- captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
- }
- if (command.type === 'prompt') throw failure;
- return { success: true, data: {} };
- };
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({
- sessionId: `prompt-unknown-${String(_label).replaceAll(' ', '-')}`,
- workingDir: cwd,
- model: 'local-model',
- });
+ [
+ "transport close before response",
+ new Error("pi process exited (code=null, signal=null)"),
+ ],
+ ["unknown write result", new Error("write EPIPE")],
+ [
+ "malformed response envelope",
+ new Error("pi rpc: response for prompt missing boolean success"),
+ ],
+ ])(
+ "marks %s after prompt request starts as an unconfirmed dispatch",
+ async (_label, failure) => {
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
+ }
+ if (command.type === "prompt") throw failure;
+ return { success: true, data: {} };
+ };
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: `prompt-unknown-${String(_label).replaceAll(" ", "-")}`,
+ workingDir: cwd,
+ model: "local-model",
+ });
- await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({
- name: 'TurnDispatchUnconfirmedError',
- code: 'TURN_DISPATCH_UNCONFIRMED',
- cause: failure,
- });
- expect(captured.requests.filter((request) => request.type === 'prompt')).toHaveLength(1);
- await handle.close();
- });
+ await expect(
+ handle.send({ type: "user", content: "continue the goal" }),
+ ).rejects.toMatchObject({
+ name: "TurnDispatchUnconfirmedError",
+ code: "TURN_DISPATCH_UNCONFIRMED",
+ cause: failure,
+ });
+ expect(
+ captured.requests.filter((request) => request.type === "prompt"),
+ ).toHaveLength(1);
+ await handle.close();
+ },
+ );
- it('keeps an explicit prompt rejection as a confirmed undispatched error', async () => {
+ it("keeps an explicit prompt rejection as a confirmed undispatched error", async () => {
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'prompt') {
+ if (command.type === "prompt") {
return {
- command: 'prompt',
+ command: "prompt",
success: false,
- error: 'prompt rejected before acceptance',
+ error: "prompt rejected before acceptance",
};
}
return { success: true, data: {} };
};
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'prompt-explicit-rejection',
+ sessionId: "prompt-explicit-rejection",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
});
- await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({
- name: 'TurnDispatchRejectedError',
- code: 'TURN_DISPATCH_REJECTED',
- message: 'pi prompt rejected before acceptance: prompt rejected before acceptance',
+ await expect(
+ handle.send({ type: "user", content: "continue the goal" }),
+ ).rejects.toMatchObject({
+ name: "TurnDispatchRejectedError",
+ code: "TURN_DISPATCH_REJECTED",
+ message:
+ "pi prompt rejected before acceptance: prompt rejected before acceptance",
});
await handle.close();
});
it.each([
- ['missing command', { success: false, error: 'prompt rejected before acceptance' }],
[
- 'non-string command',
- { command: { type: 'prompt' }, success: false, error: 'prompt rejected before acceptance' },
+ "missing command",
+ { success: false, error: "prompt rejected before acceptance" },
],
[
- 'mismatched command',
- { command: 'steer', success: false, error: 'prompt rejected before acceptance' },
+ "non-string command",
+ {
+ command: { type: "prompt" },
+ success: false,
+ error: "prompt rejected before acceptance",
+ },
],
- ])('treats a rejected prompt response with %s as an unconfirmed dispatch', async (
- label,
- rejectionResponse,
- ) => {
- captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return {
- success: true,
- data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } },
- };
- }
- if (command.type === 'prompt') return rejectionResponse;
- return { success: true, data: {} };
- };
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({
- sessionId: `prompt-rejection-${label.replaceAll(' ', '-')}`,
- workingDir: cwd,
- model: 'local-model',
- });
+ [
+ "mismatched command",
+ {
+ command: "steer",
+ success: false,
+ error: "prompt rejected before acceptance",
+ },
+ ],
+ ])(
+ "treats a rejected prompt response with %s as an unconfirmed dispatch",
+ async (label, rejectionResponse) => {
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
+ }
+ if (command.type === "prompt") return rejectionResponse;
+ return { success: true, data: {} };
+ };
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: `prompt-rejection-${label.replaceAll(" ", "-")}`,
+ workingDir: cwd,
+ model: "local-model",
+ });
- await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({
- name: 'TurnDispatchUnconfirmedError',
- code: 'TURN_DISPATCH_UNCONFIRMED',
- cause: expect.objectContaining({
- message: 'pi prompt rejection response missing matching command',
- }),
- });
- expect(captured.requests.filter((request) => request.type === 'prompt')).toHaveLength(1);
- await handle.close();
- });
+ await expect(
+ handle.send({ type: "user", content: "continue the goal" }),
+ ).rejects.toMatchObject({
+ name: "TurnDispatchUnconfirmedError",
+ code: "TURN_DISPATCH_UNCONFIRMED",
+ cause: expect.objectContaining({
+ message: "pi prompt rejection response missing matching command",
+ }),
+ });
+ expect(
+ captured.requests.filter((request) => request.type === "prompt"),
+ ).toHaveLength(1);
+ await handle.close();
+ },
+ );
- it('keeps a leading /skill: command at the prompt start even when Extra Dirs are configured', async () => {
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ it("keeps a leading /skill: command at the prompt start even when Extra Dirs are configured", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'skill-extradir',
+ sessionId: "skill-extradir",
workingDir: cwd,
- model: 'local-model',
- extraDirs: ['/refs/project-docs'],
+ model: "local-model",
+ extraDirs: ["/refs/project-docs"],
});
captured.requests.length = 0;
- await handle.send({ type: 'user', content: '/skill:code-review please' });
- const prompt = captured.requests.find((r) => r.type === 'prompt');
+ await handle.send({ type: "user", content: "/skill:code-review please" });
+ const prompt = captured.requests.find((r) => r.type === "prompt");
// /skill: 必须仍在 prompt 起始(未被 Extra Dir 引用段挤走),否则 Pi 不加载技能。
- expect(String(prompt?.message).startsWith('/skill:code-review')).toBe(true);
+ expect(String(prompt?.message).startsWith("/skill:code-review")).toBe(true);
// 对照:普通消息仍前置 Extra Dir 引用段。
captured.requests.length = 0;
- await handle.send({ type: 'user', content: 'just a normal message' });
- const normal = captured.requests.find((r) => r.type === 'prompt');
- expect(String(normal?.message).startsWith('/skill:')).toBe(false);
- expect(String(normal?.message)).toContain('project-docs');
+ await handle.send({ type: "user", content: "just a normal message" });
+ const normal = captured.requests.find((r) => r.type === "prompt");
+ expect(String(normal?.message).startsWith("/skill:")).toBe(false);
+ expect(String(normal?.message)).toContain("project-docs");
await handle.close();
});
- it('executes only runtime-confirmed commands from enabled Cindy-managed Pi packages', async () => {
- const packageRoot = path.join(agentHome, 'managed-package');
- const extensionPath = path.join(packageRoot, 'extensions', 'index.ts');
+ it("executes only runtime-confirmed commands from enabled Cindy-managed Pi packages", async () => {
+ const packageRoot = path.join(agentHome, "managed-package");
+ const extensionPath = path.join(packageRoot, "extensions", "index.ts");
mkdirSync(path.dirname(extensionPath), { recursive: true });
- writeFileSync(extensionPath, '// managed extension');
+ writeFileSync(extensionPath, "// managed extension");
let releaseCommandCatalog!: () => void;
const commandCatalogGate = new Promise<void>((resolve) => {
releaseCommandCatalog = resolve;
});
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'get_commands') {
+ if (command.type === "get_commands") {
await commandCatalogGate;
return {
- type: 'response',
- command: 'get_commands',
+ type: "response",
+ command: "get_commands",
success: true,
data: {
commands: [
{
- name: 'managed-run',
- description: 'Managed package command',
- source: 'extension',
- sourceInfo: { path: extensionPath, source: 'extension' },
+ name: "managed-run",
+ description: "Managed package command",
+ source: "extension",
+ sourceInfo: { path: extensionPath, source: "extension" },
},
{
- name: 'user-run',
- description: 'Unmanaged user command',
- source: 'extension',
- sourceInfo: { path: '/private/user/.pi/extensions/index.ts', source: 'extension' },
+ name: "user-run",
+ description: "Unmanaged user command",
+ source: "extension",
+ sourceInfo: {
+ path: "/private/user/.pi/extensions/index.ts",
+ source: "extension",
+ },
},
],
},
@@ -3203,165 +4464,226 @@ describe('Pi provider-aware model routing', () => {
packageRoots: [packageRoot],
});
const handle = await new PiAgent(deps).startSession({
- sessionId: 'managed-command',
+ sessionId: "managed-command",
workingDir: cwd,
- model: 'local-model',
- extraDirs: ['/refs/project-docs'],
+ model: "local-model",
+ extraDirs: ["/refs/project-docs"],
});
captured.requests.length = 0;
- const firstSend = handle.send({ type: 'user', content: '/managed-run now' });
+ const firstSend = handle.send({
+ type: "user",
+ content: "/managed-run now",
+ });
await Promise.resolve();
- expect(captured.requests.some((request) => request.type === 'prompt')).toBe(false);
+ expect(captured.requests.some((request) => request.type === "prompt")).toBe(
+ false,
+ );
releaseCommandCatalog();
await firstSend;
- const manifest = await new Promise<ReturnType<NonNullable<typeof handle.getRuntimeCapabilities>>>((resolve) => {
+ const manifest = await new Promise<
+ ReturnType<NonNullable<typeof handle.getRuntimeCapabilities>>
+ >((resolve) => {
const current = handle.getRuntimeCapabilities?.();
- if (current?.status === 'loaded') {
+ if (current?.status === "loaded") {
resolve(current);
return;
}
let unsubscribe: (() => void) | undefined;
unsubscribe = handle.onRuntimeCapabilitiesChange?.((next) => {
- if (next?.status !== 'loaded') return;
+ if (next?.status !== "loaded") return;
unsubscribe?.();
resolve(next);
});
});
- expect(manifest?.managedPackageCommandNames).toEqual(['managed-run']);
- const managed = captured.requests.find((request) => request.type === 'prompt');
- expect(managed?.message).toBe('/managed-run now');
+ expect(manifest?.managedPackageCommandNames).toEqual(["managed-run"]);
+ const managed = captured.requests.find(
+ (request) => request.type === "prompt",
+ );
+ expect(managed?.message).toBe("/managed-run now");
captured.requests.length = 0;
- await handle.send({ type: 'user', content: '/user-run now' });
- const unmanaged = captured.requests.find((request) => request.type === 'prompt');
+ await handle.send({ type: "user", content: "/user-run now" });
+ const unmanaged = captured.requests.find(
+ (request) => request.type === "prompt",
+ );
expect(String(unmanaged?.message)).not.toMatch(/^\/user-run/);
- expect(String(unmanaged?.message)).toContain('/user-run now');
+ expect(String(unmanaged?.message)).toContain("/user-run now");
await handle.close();
});
- it('routes a null providerId to the gateway even when a BYOM offers the same model', async () => {
+ it("routes a null providerId to the gateway even when a BYOM offers the same model", async () => {
// null = 显式清除来源(session-provider-store 语义);Main 在恢复/setModel 时传它。绝不能
// 按模型自动挑同名 BYOM,否则默认路由的会话把提示词发往用户未选的 BYOM 端点(codex review P1)。
- const agent = new PiAgent(byomDeps(async () => ({
- providers: [
- { id: 'native-a', name: 'Native A', baseUrl: 'http://a.test', api: 'openai-completions', models: [{ id: 'local-model' }] },
- ],
- env: {},
- })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-completions",
+ models: [{ id: "local-model" }],
+ },
+ ],
+ env: {},
+ })),
+ );
const handle = await agent.startSession({
- sessionId: 'null-provider',
+ sessionId: "null-provider",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
providerId: null,
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'cindy']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "cindy"]);
// 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' });
+ await handle.setModel!("local-model", { providerId: null });
+ expect(captured.requests).toContainEqual({
+ type: "set_model",
+ provider: "cindy",
+ modelId: "local-model",
+ });
await handle.close();
});
- it('serializes rapid permission-mode switches so the file converges to the latest intent', async () => {
+ it("serializes rapid permission-mode switches so the file converges to the latest intent", async () => {
// 并发/连续切档:串行化 + 代际跳过保证权限档最终 = 最后一次意图(ask),较早的 bypass 写
// 不得在其后 stale 覆盖(否则 bridge 现读到 bypassPermissions,而 host/UI 已是 Ask)。
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({ sessionId: 'perm-race', workingDir: cwd, model: 'local-model' });
- const permFile = runtimeFileOf('perm', 'perm-race');
- const a = handle.setPermissionMode!('bypassPermissions');
- const b = handle.setPermissionMode!('ask');
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: "perm-race",
+ workingDir: cwd,
+ model: "local-model",
+ });
+ const permFile = runtimeFileOf("perm", "perm-race");
+ const a = handle.setPermissionMode!("bypassPermissions");
+ const b = handle.setPermissionMode!("ask");
await Promise.all([a, b]);
- expect(JSON.parse(readFileSync(permFile, 'utf8')).mode).toBe('ask');
+ expect(JSON.parse(readFileSync(permFile, "utf8")).mode).toBe("ask");
await handle.close();
});
- it('recovers the permission-write chain after a failed write (no permanent poisoning)', async () => {
+ it("recovers the permission-write chain after a failed write (no permanent poisoning)", async () => {
// 瞬时 fs 故障不得永久污染串行链:否则文件系统恢复后的重写也追加不进去,bridge 一直卡在旧档。
- const fsp = await import('node:fs');
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const fsp = await import("node:fs");
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'perm-recover',
+ sessionId: "perm-recover",
workingDir: cwd,
- model: 'local-model',
- permissionMode: 'ask',
+ model: "local-model",
+ permissionMode: "ask",
});
- const permFile = runtimeFileOf('perm', 'perm-recover');
+ const permFile = runtimeFileOf("perm", "perm-recover");
// 下一次写(尝试放宽到 Full)失败一次;旧文件仍是安全的 ask,此后恢复真实写。
- const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('transient EIO'));
- await handle.setPermissionMode!('bypassPermissions').catch(() => {});
+ const spy = vi
+ .spyOn(fsp.promises, "writeFile")
+ .mockRejectedValueOnce(new Error("transient EIO"));
+ await handle.setPermissionMode!("bypassPermissions").catch(() => {});
spy.mockRestore();
// 若链被污染,这次 auto 写的 .then 永不执行,文件会停在 ask;恢复后应写成 auto。
- await handle.setPermissionMode!('auto');
- expect(JSON.parse(readFileSync(permFile, 'utf8')).mode).toBe('auto');
+ await handle.setPermissionMode!("auto");
+ expect(JSON.parse(readFileSync(permFile, "utf8")).mode).toBe("auto");
await handle.close();
});
- it('does not replay a failed Full-access intent when Extra Dirs are updated later', async () => {
- const fsp = await import('node:fs');
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ it("does not replay a failed Full-access intent when Extra Dirs are updated later", async () => {
+ const fsp = await import("node:fs");
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'perm-failed-intent',
+ sessionId: "perm-failed-intent",
workingDir: cwd,
- model: 'local-model',
- permissionMode: 'ask',
+ model: "local-model",
+ permissionMode: "ask",
});
- const permFile = runtimeFileOf('perm', 'perm-failed-intent');
- const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('transient EIO'));
- await expect(handle.setPermissionMode!('bypassPermissions')).rejects.toThrow('transient EIO');
+ const permFile = runtimeFileOf("perm", "perm-failed-intent");
+ const spy = vi
+ .spyOn(fsp.promises, "writeFile")
+ .mockRejectedValueOnce(new Error("transient EIO"));
+ await expect(
+ handle.setPermissionMode!("bypassPermissions"),
+ ).rejects.toThrow("transient EIO");
spy.mockRestore();
- await handle.setExtraDirs!(['/reference-only']);
- expect(JSON.parse(readFileSync(permFile, 'utf8'))).toEqual({
- mode: 'ask',
- readOnlyRoots: ['/reference-only'],
+ await handle.setExtraDirs!(["/reference-only"]);
+ expect(JSON.parse(readFileSync(permFile, "utf8"))).toEqual({
+ mode: "ask",
+ readOnlyRoots: ["/reference-only"],
writableRoots: [],
});
await handle.close();
});
- it('persists writable directory grants separately from read-only references', async () => {
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ it("persists writable directory grants separately from read-only references", async () => {
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'perm-writable-dirs',
+ sessionId: "perm-writable-dirs",
workingDir: cwd,
- model: 'local-model',
- permissionMode: 'auto',
- extraDirs: ['/reference-only'],
- writableDirs: ['/shared-output'],
- });
- const permFile = runtimeFileOf('perm', 'perm-writable-dirs');
- expect(JSON.parse(readFileSync(permFile, 'utf8'))).toMatchObject({
- mode: 'auto',
- readOnlyRoots: ['/reference-only'],
- writableRoots: ['/shared-output'],
- });
- await handle.setWritableDirs?.(['/replacement-output']);
- expect(JSON.parse(readFileSync(permFile, 'utf8'))).toMatchObject({
- readOnlyRoots: ['/reference-only'],
- writableRoots: ['/replacement-output'],
+ model: "local-model",
+ permissionMode: "auto",
+ extraDirs: ["/reference-only"],
+ writableDirs: ["/shared-output"],
+ });
+ const permFile = runtimeFileOf("perm", "perm-writable-dirs");
+ expect(JSON.parse(readFileSync(permFile, "utf8"))).toMatchObject({
+ mode: "auto",
+ readOnlyRoots: ["/reference-only"],
+ writableRoots: ["/shared-output"],
+ });
+ await handle.setWritableDirs?.(["/replacement-output"]);
+ expect(JSON.parse(readFileSync(permFile, "utf8"))).toMatchObject({
+ readOnlyRoots: ["/reference-only"],
+ writableRoots: ["/replacement-output"],
});
await handle.close();
});
- it('reports the stable Pi user entry id after prompt acceptance', async () => {
+ it("reports the stable Pi user entry id after prompt acceptance", async () => {
let promptAccepted = 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 === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'prompt') {
+ if (command.type === "prompt") {
promptAccepted = true;
return { success: true, data: {} };
}
- if (command.type === 'get_entries') {
+ if (command.type === "get_entries") {
return {
success: true,
data: {
entries: [
- { id: 'old-user', type: 'message', message: { role: 'user', content: 'old' } },
+ {
+ id: "old-user",
+ type: "message",
+ message: { role: "user", content: "old" },
+ },
...(promptAccepted
- ? [{ id: 'new-user', type: 'message', message: { role: 'user', content: 'new' } }]
+ ? [
+ {
+ id: "new-user",
+ type: "message",
+ message: { role: "user", content: "new" },
+ },
+ ]
: []),
],
},
@@ -3369,134 +4691,205 @@ describe('Pi provider-aware model routing', () => {
}
return { success: true, data: {} };
};
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'entry-link',
+ sessionId: "entry-link",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
});
const onTranscriptUserEntry = vi.fn();
await handle.send(
- { type: 'user', content: 'new' },
+ { type: "user", content: "new" },
{ onTranscriptUserEntry },
);
expect(onTranscriptUserEntry).toHaveBeenCalledOnce();
- expect(onTranscriptUserEntry).toHaveBeenCalledWith('new-user');
+ expect(onTranscriptUserEntry).toHaveBeenCalledWith("new-user");
await handle.close();
});
- it('closes the Pi process if tightening a persisted Full-access file fails', async () => {
- const fsp = await import('node:fs');
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ it("closes the Pi process if tightening a persisted Full-access file fails", async () => {
+ const fsp = await import("node:fs");
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
const handle = await agent.startSession({
- sessionId: 'perm-tighten-fail',
+ sessionId: "perm-tighten-fail",
workingDir: cwd,
- model: 'local-model',
- permissionMode: 'bypassPermissions',
- });
- const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('disk unavailable'));
- await expect(handle.setPermissionMode!('ask')).rejects.toThrow('disk unavailable');
+ model: "local-model",
+ permissionMode: "bypassPermissions",
+ });
+ const spy = vi
+ .spyOn(fsp.promises, "writeFile")
+ .mockRejectedValueOnce(new Error("disk unavailable"));
+ await expect(handle.setPermissionMode!("ask")).rejects.toThrow(
+ "disk unavailable",
+ );
spy.mockRestore();
// 子进程 bridge 仍会从旧文件读到 Full access;必须终止会话,不能只收紧 host 镜像。
expect(captured.closes).toBe(1);
await handle.close();
});
- it('serializes concurrent plan-mode requests so same-target toggles only once', async () => {
+ it("serializes concurrent plan-mode requests so same-target toggles only once", async () => {
installPlanModeExtension();
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({ sessionId: 'plan-race', workingDir: cwd, model: 'local-model' });
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: "plan-race",
+ workingDir: cwd,
+ model: "local-model",
+ });
expect(handle.getPlanMode!()).toBe(false);
await Promise.all([handle.setPlanMode!(true), handle.setPlanMode!(true)]);
- expect(captured.requests.filter((request) => request.type === 'prompt' && request.message === '/plan')).toHaveLength(1);
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "prompt" && request.message === "/plan",
+ ),
+ ).toHaveLength(1);
expect(handle.getPlanMode!()).toBe(true);
await handle.close();
});
- it('keeps plan mode unknown after sync failure and refuses a blind toggle until it can resync', async () => {
+ it("keeps plan mode unknown after sync failure and refuses a blind toggle until it can resync", async () => {
installPlanModeExtension();
let entriesAvailable = 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 === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'get_entries') {
+ if (command.type === "get_entries") {
return entriesAvailable
- ? { success: true, data: { entries: [{ customType: 'plan-mode', data: { enabled: true } }] } }
- : { success: false, error: 'temporary rpc failure' };
+ ? {
+ success: true,
+ data: {
+ entries: [{ customType: "plan-mode", data: { enabled: true } }],
+ },
+ }
+ : { success: false, error: "temporary rpc failure" };
}
return { success: true, data: {} };
};
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({ sessionId: 'plan-unknown', workingDir: cwd, model: 'local-model' });
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: "plan-unknown",
+ workingDir: cwd,
+ model: "local-model",
+ });
expect(handle.getPlanMode!()).toBeNull();
- await expect(handle.setPlanMode!(false)).rejects.toThrow(/state is unavailable/);
- expect(captured.requests.some((request) => request.type === 'prompt' && request.message === '/plan')).toBe(false);
+ await expect(handle.setPlanMode!(false)).rejects.toThrow(
+ /state is unavailable/,
+ );
+ expect(
+ captured.requests.some(
+ (request) => request.type === "prompt" && request.message === "/plan",
+ ),
+ ).toBe(false);
entriesAvailable = true;
await handle.setPlanMode!(false);
- expect(captured.requests.filter((request) => request.type === 'prompt' && request.message === '/plan')).toHaveLength(1);
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "prompt" && request.message === "/plan",
+ ),
+ ).toHaveLength(1);
expect(handle.getPlanMode!()).toBe(false);
await handle.close();
});
- it('marks plan mode unknown when a toggle transport failure may have happened after execution', async () => {
+ it("marks plan mode unknown when a toggle transport failure may have happened after execution", async () => {
installPlanModeExtension();
let persistedEnabled = false;
let failNextToggle = true;
captured.requestHandler = async (command) => {
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: { contextWindow: 200_000 },
+ },
+ };
}
- if (command.type === 'get_entries') {
+ if (command.type === "get_entries") {
return {
success: true,
- data: { entries: [{ customType: 'plan-mode', data: { enabled: persistedEnabled } }] },
+ data: {
+ entries: [
+ { customType: "plan-mode", data: { enabled: persistedEnabled } },
+ ],
+ },
};
}
- if (command.type === 'prompt' && command.message === '/plan') {
+ if (command.type === "prompt" && command.message === "/plan") {
persistedEnabled = !persistedEnabled; // Pi 已执行,但本地 transport 随后超时。
if (failNextToggle) {
failNextToggle = false;
- throw new Error('rpc timeout');
+ throw new Error("rpc timeout");
}
}
return { success: true, data: {} };
};
- const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
- const handle = await agent.startSession({ sessionId: 'plan-timeout', workingDir: cwd, model: 'local-model' });
+ const agent = new PiAgent(
+ byomDeps(async () => ({ providers: [], env: {} })),
+ );
+ const handle = await agent.startSession({
+ sessionId: "plan-timeout",
+ workingDir: cwd,
+ model: "local-model",
+ });
- await expect(handle.setPlanMode!(true)).rejects.toThrow('rpc timeout');
+ await expect(handle.setPlanMode!(true)).rejects.toThrow("rpc timeout");
expect(handle.getPlanMode!()).toBeNull();
// 下一次同目标先读回 persisted=true,不能再 toggle 一次把 Pi 反向关掉。
await handle.setPlanMode!(true);
- expect(captured.requests.filter((request) => request.type === 'prompt' && request.message === '/plan')).toHaveLength(1);
+ expect(
+ captured.requests.filter(
+ (request) => request.type === "prompt" && request.message === "/plan",
+ ),
+ ).toHaveLength(1);
expect(handle.getPlanMode!()).toBe(true);
await handle.close();
});
- it('does not fail closed for a gateway/subscription route when native resolution throws', async () => {
+ it("does not fail closed for a gateway/subscription route when native resolution throws", async () => {
// openai(订阅直连)在 nativeProviders 缺席是正常的,应照常走网关块,不触发 BYOM 拦截。
- const agent = new PiAgent(byomDeps(async () => {
- throw new Error('resolve failed');
- }));
+ const agent = new PiAgent(
+ byomDeps(async () => {
+ throw new Error("resolve failed");
+ }),
+ );
const handle = await agent.startSession({
- sessionId: 'subscription-ok',
+ sessionId: "subscription-ok",
workingDir: cwd,
- model: 'local-model',
- providerId: 'openai',
+ model: "local-model",
+ providerId: "openai",
});
- expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
- .toEqual(['--provider', 'cindy']);
+ expect(
+ captured.args.slice(
+ captured.args.indexOf("--provider"),
+ captured.args.indexOf("--provider") + 2,
+ ),
+ ).toEqual(["--provider", "cindy"]);
await handle.close();
});
- it('rejects a loopback-only BYOM provider for remote Pi sessions (fail-fast)', async () => {
+ it("rejects a loopback-only BYOM provider for remote Pi sessions (fail-fast)", async () => {
// 轮 42 P2(codex-connector):远端 Pi + baseUrl 指向本机 loopback 的 BYOM
// (Ollama @ localhost 等)在创建时拒绝 —— 远端进程在 SSH 主机上连 localhost
// 是远端自己, 用户本机服务不可达, 首回合必然失败/错配。
- const remoteStub: import('../transport.js').PiTransport = {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -3504,18 +4897,18 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const deps: AgentDeps = {
...byomDeps(async () => ({
providers: [
{
- id: 'ollama',
- name: 'Ollama',
- baseUrl: 'http://localhost:11434',
- api: 'openai-completions' as const,
- models: [{ id: 'local-model' }],
+ id: "ollama",
+ name: "Ollama",
+ baseUrl: "http://localhost:11434",
+ api: "openai-completions" as const,
+ models: [{ id: "local-model" }],
},
],
env: {},
@@ -3530,27 +4923,29 @@ describe('Pi provider-aware model routing', () => {
}),
};
const agent = new PiAgent(deps);
- await expect(agent.startSession({
- sessionId: 'remote-loopback-byom',
- workingDir: cwd,
- model: 'local-model',
- providerId: 'ollama',
- remoteHostId: 'remote-host',
- })).rejects.toThrow(/\[REMOTE_LOCAL_ONLY_PROVIDER\]/);
+ await expect(
+ agent.startSession({
+ sessionId: "remote-loopback-byom",
+ workingDir: cwd,
+ model: "local-model",
+ providerId: "ollama",
+ remoteHostId: "remote-host",
+ }),
+ ).rejects.toThrow(/\[REMOTE_LOCAL_ONLY_PROVIDER\]/);
// 未走到 spawn(transport 从未创建)。
expect(captured.args).toEqual([]);
});
- it('rejects a local-only OpenAI context profile before resolving or spawning remote Pi', async () => {
+ it("rejects a local-only OpenAI context profile before resolving or spawning remote Pi", async () => {
const resolver = vi.fn(async () => ({ providers: [], env: {} }));
const transport = vi.fn(async () => {
- throw new Error('remote transport must not be created');
+ throw new Error("remote transport must not be created");
});
const agent = new PiAgent({
...byomDeps(resolver, [
{
- id: 'chatgpt/gpt-5.6-sol[1m]',
- displayName: 'GPT-5.6-Sol 1M',
+ id: "chatgpt/gpt-5.6-sol[1m]",
+ displayName: "GPT-5.6-Sol 1M",
contextWindow: 1_000_000,
efforts: [],
defaultEffort: null,
@@ -3559,20 +4954,22 @@ describe('Pi provider-aware model routing', () => {
getRemotePiTransport: transport,
});
- await expect(agent.startSession({
- sessionId: 'remote-openai-context-profile',
- workingDir: cwd,
- model: 'chatgpt/gpt-5.6-sol[1m]',
- providerId: 'openai',
- remoteHostId: 'remote-host',
- })).rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
+ await expect(
+ agent.startSession({
+ sessionId: "remote-openai-context-profile",
+ workingDir: cwd,
+ model: "chatgpt/gpt-5.6-sol[1m]",
+ providerId: "openai",
+ remoteHostId: "remote-host",
+ }),
+ ).rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
expect(resolver).not.toHaveBeenCalled();
expect(transport).not.toHaveBeenCalled();
expect(captured.args).toEqual([]);
});
- it('rejects switching a running remote Pi session to a local-only OpenAI context profile', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("rejects switching a running remote Pi session to a local-only OpenAI context profile", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -3580,29 +4977,35 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
- const base = byomDeps(async () => ({ providers: [], env: {} }), [
- {
- id: 'gateway-model',
- displayName: 'Gateway model',
- contextWindow: 200_000,
- efforts: [],
- defaultEffort: null,
- },
- {
- id: 'chatgpt/gpt-5.6-sol[1m]',
- displayName: 'GPT-5.6-Sol 1M',
- contextWindow: 1_000_000,
- efforts: [],
- defaultEffort: null,
- },
- ]);
+ const base = byomDeps(
+ async () => ({ providers: [], env: {} }),
+ [
+ {
+ id: "gateway-model",
+ displayName: "Gateway model",
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: "chatgpt/gpt-5.6-sol[1m]",
+ displayName: "GPT-5.6-Sol 1M",
+ contextWindow: 1_000_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ );
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async () => remoteStub,
getRemotePiFileOps: () => ({
mkdirp: async () => {},
@@ -3613,23 +5016,26 @@ describe('Pi provider-aware model routing', () => {
}),
});
const handle = await agent.startSession({
- sessionId: 'remote-gateway-context-profile-switch',
+ sessionId: "remote-gateway-context-profile-switch",
workingDir: cwd,
- model: 'gateway-model',
- providerId: 'xd',
- remoteHostId: 'remote-host',
+ model: "gateway-model",
+ providerId: "xd",
+ remoteHostId: "remote-host",
});
captured.requests.length = 0;
- await expect(handle.setModel!('chatgpt/gpt-5.6-sol[1m]', { providerId: 'openai' }))
- .rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
- expect(handle.model).toBe('gateway-model');
- expect(captured.requests).not.toContainEqual(expect.objectContaining({ type: 'set_model' }));
+ await expect(
+ handle.setModel!("chatgpt/gpt-5.6-sol[1m]", { providerId: "openai" }),
+ ).rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
+ expect(handle.model).toBe("gateway-model");
+ expect(captured.requests).not.toContainEqual(
+ expect.objectContaining({ type: "set_model" }),
+ );
await handle.close();
});
- it('allows an explicitly forwarded remote xAI provider and keeps proxy auth in the remote env', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("allows an explicitly forwarded remote xAI provider and keeps proxy auth in the remote env", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -3637,12 +5043,12 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
ensureHostProxyForward: async () => {},
};
let transportOptions:
- Parameters<NonNullable<AgentDeps['getRemotePiTransport']>>[1] | undefined;
+ Parameters<NonNullable<AgentDeps["getRemotePiTransport"]>>[1] | undefined;
const remoteWrittenFiles: string[] = [];
let registeredToken: string | undefined;
let disposed = 0;
@@ -3650,39 +5056,39 @@ describe('Pi provider-aware model routing', () => {
async () => ({
providers: [
{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:47989',
- api: 'anthropic-messages',
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:47989",
+ api: "anthropic-messages",
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
headers: {
- 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
- 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ "x-cindy-pi-session-id": "$CINDY_PI_SESSION_ID",
+ "x-cindy-pi-session-token": "$CINDY_PI_SESSION_TOKEN",
},
- models: [{ id: 'xai/grok-4.6' }],
+ models: [{ id: "xai/grok-4.6" }],
modelIdAliases: {
- 'grok-4.6': 'xai/grok-4.6',
- 'xai/grok-4.6': 'xai/grok-4.6',
+ "grok-4.6": "xai/grok-4.6",
+ "xai/grok-4.6": "xai/grok-4.6",
},
hostProxyForward: {
- localUrl: 'http://127.0.0.1:18765',
+ localUrl: "http://127.0.0.1:18765",
remotePort: 47989,
},
},
],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
}),
[
{
- id: 'gateway-model',
- displayName: 'Gateway model',
+ id: "gateway-model",
+ displayName: "Gateway model",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
},
{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
contextWindow: 500_000,
efforts: [],
defaultEffort: null,
@@ -3690,24 +5096,26 @@ describe('Pi provider-aware model routing', () => {
],
);
const stableTokens = new Map([
- ['remote-xai-forward', 'a'.repeat(43)],
- ['remote-xai-other', 'b'.repeat(43)],
+ ["remote-xai-forward", "a".repeat(43)],
+ ["remote-xai-other", "b".repeat(43)],
]);
- const derivePiProxySessionToken = vi.fn((sessionId: string) => stableTokens.get(sessionId)!);
+ const derivePiProxySessionToken = vi.fn((sessionId: string) =>
+ stableTokens.get(sessionId)!,
+ );
const agentDeps: AgentDeps = {
...base,
auth: {
...base.auth,
getState: async () => ({
authenticated: true,
- identity: 'SuperGrok',
- authSource: 'oauth',
+ identity: "SuperGrok",
+ authSource: "oauth",
}),
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
runtimeConfig: {
...base.runtimeConfig,
- remoteEndpoint: 'https://gateway.example.test',
+ remoteEndpoint: "https://gateway.example.test",
},
registerPiProxySession: (_sessionId, token) => {
registeredToken = token;
@@ -3717,10 +5125,12 @@ describe('Pi provider-aware model routing', () => {
},
derivePiProxySessionToken,
mutatePiManagedPackage: vi.fn(async () => ({ changed: true })),
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiFileOps: () => ({
mkdirp: async () => {},
- writeFile: async (file) => { remoteWrittenFiles.push(file); },
+ writeFile: async (file) => {
+ remoteWrittenFiles.push(file);
+ },
stat: async () => ({ isFile: true }),
rm: async () => {},
listDir: async () => [],
@@ -3732,60 +5142,79 @@ describe('Pi provider-aware model routing', () => {
};
const agent = new PiAgent(agentDeps);
const handle = await agent.startSession({
- sessionId: 'remote-xai-forward',
+ sessionId: "remote-xai-forward",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- remoteHostId: 'remote-host',
+ model: "grok-4.6",
+ providerId: "xai",
+ remoteHostId: "remote-host",
});
expect(transportOptions?.hostProxyForwards).toEqual([
- { localUrl: 'http://127.0.0.1:18765', remotePort: 47989 },
+ { localUrl: "http://127.0.0.1:18765", remotePort: 47989 },
]);
expect(registeredToken).toMatch(/^[A-Za-z0-9_-]{40,}$/);
- expect(transportOptions?.env.CINDY_PI_API_KEY).toBe('gateway-key');
- expect(transportOptions?.env.CINDY_PI_XAI_PROXY_API_KEY).toBe('xai-proxy-placeholder');
- expect(JSON.parse(transportOptions?.env.CINDY_PI_SECRET_ENV_NAMES ?? '[]')).toEqual(
- expect.arrayContaining(['CINDY_PI_API_KEY', 'CINDY_PI_XAI_PROXY_API_KEY']),
+ expect(transportOptions?.env.CINDY_PI_API_KEY).toBe("gateway-key");
+ expect(transportOptions?.env.CINDY_PI_XAI_PROXY_API_KEY).toBe(
+ "xai-proxy-placeholder",
+ );
+ expect(
+ JSON.parse(transportOptions?.env.CINDY_PI_SECRET_ENV_NAMES ?? "[]"),
+ ).toEqual(
+ expect.arrayContaining([
+ "CINDY_PI_API_KEY",
+ "CINDY_PI_XAI_PROXY_API_KEY",
+ ]),
);
expect(transportOptions?.env.CINDY_PI_SESSION_TOKEN).toBe(registeredToken);
- expect(transportOptions?.args).not.toContain('/remote/cindy-subagent.ts');
- expect(transportOptions?.args.some((arg) => arg.endsWith('/cindy-subagent.ts'))).toBe(false);
+ expect(transportOptions?.args).not.toContain("/remote/cindy-subagent.ts");
+ expect(
+ transportOptions?.args.some((arg) => arg.endsWith("/cindy-subagent.ts")),
+ ).toBe(false);
expect(transportOptions?.env.CINDY_PI_SUBAGENT_BINARY).toBeUndefined();
- expect(transportOptions?.env.CINDY_PI_SUBAGENT_RUNTIME_FILE).toBeUndefined();
+ expect(
+ transportOptions?.env.CINDY_PI_SUBAGENT_RUNTIME_FILE,
+ ).toBeUndefined();
expect(transportOptions?.env.CINDY_PI_SUBAGENT_RUN_ROOT).toBeUndefined();
expect(transportOptions?.env.CINDY_PI_SUBAGENT_RUNNER_FILE).toBeUndefined();
expect(transportOptions?.env.CINDY_PI_SUBAGENT_NODE).toBeUndefined();
- expect(remoteWrittenFiles.some((file) => file.endsWith('/cindy-subagent.ts'))).toBe(false);
- expect(remoteWrittenFiles.some((file) => file.endsWith('/cindy-subagent-runner.cjs'))).toBe(false);
+ expect(
+ remoteWrittenFiles.some((file) => file.endsWith("/cindy-subagent.ts")),
+ ).toBe(false);
+ expect(
+ remoteWrittenFiles.some((file) =>
+ file.endsWith("/cindy-subagent-runner.cjs"),
+ ),
+ ).toBe(false);
expect(transportOptions?.env.CINDY_PI_PACKAGE_MANAGEMENT).toBeUndefined();
const firstToken = registeredToken;
const firstSpawnEnv = { ...transportOptions?.env };
captured.requests.length = 0;
- await handle.setModel!('gateway-model', { providerId: 'xd' });
- await handle.setModel!('grok-4.6', { providerId: 'xai' });
+ await handle.setModel!("gateway-model", { providerId: "xd" });
+ await handle.setModel!("grok-4.6", { providerId: "xai" });
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'cindy',
- modelId: 'gateway-model',
+ type: "set_model",
+ provider: "cindy",
+ modelId: "gateway-model",
});
expect(captured.requests).toContainEqual({
- type: 'set_model',
- provider: 'xai',
- modelId: 'xai/grok-4.6',
+ type: "set_model",
+ provider: "xai",
+ modelId: "xai/grok-4.6",
});
- expect(remoteWrittenFiles.some((file) => file.includes('/subagent-'))).toBe(false);
+ expect(remoteWrittenFiles.some((file) => file.includes("/subagent-"))).toBe(
+ false,
+ );
await handle.close();
expect(disposed).toBe(1);
// Reconstruct the agent to model a Desktop restart. The host-owned
// derivation survives while maker-core process-local state does not.
const reattached = await new PiAgent(agentDeps).startSession({
- sessionId: 'remote-xai-forward',
+ sessionId: "remote-xai-forward",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- remoteHostId: 'remote-host',
+ model: "grok-4.6",
+ providerId: "xai",
+ remoteHostId: "remote-host",
});
expect(registeredToken).toBe(firstToken);
expect(transportOptions?.env).toEqual(firstSpawnEnv);
@@ -3794,16 +5223,18 @@ describe('Pi provider-aware model routing', () => {
expect(disposed).toBe(2);
const otherSession = await new PiAgent(agentDeps).startSession({
- sessionId: 'remote-xai-other',
+ sessionId: "remote-xai-other",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- remoteHostId: 'remote-host',
+ model: "grok-4.6",
+ providerId: "xai",
+ remoteHostId: "remote-host",
});
expect(registeredToken).not.toBe(firstToken);
expect(transportOptions?.env.CINDY_PI_SESSION_TOKEN).toBe(registeredToken);
- expect(derivePiProxySessionToken).toHaveBeenCalledWith('remote-xai-forward');
- expect(derivePiProxySessionToken).toHaveBeenCalledWith('remote-xai-other');
+ expect(derivePiProxySessionToken).toHaveBeenCalledWith(
+ "remote-xai-forward",
+ );
+ expect(derivePiProxySessionToken).toHaveBeenCalledWith("remote-xai-other");
await otherSession.close();
expect(disposed).toBe(3);
@@ -3812,31 +5243,31 @@ describe('Pi provider-aware model routing', () => {
derivePiProxySessionToken: undefined,
};
const legacy = await new PiAgent(legacyDeps).startSession({
- sessionId: 'remote-xai-legacy',
+ sessionId: "remote-xai-legacy",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- remoteHostId: 'remote-host',
+ model: "grok-4.6",
+ providerId: "xai",
+ remoteHostId: "remote-host",
});
const legacyToken = registeredToken;
await legacy.close();
const legacyReattached = await new PiAgent(legacyDeps).startSession({
- sessionId: 'remote-xai-legacy',
+ sessionId: "remote-xai-legacy",
workingDir: cwd,
- model: 'grok-4.6',
- providerId: 'xai',
- remoteHostId: 'remote-host',
+ model: "grok-4.6",
+ providerId: "xai",
+ remoteHostId: "remote-host",
});
expect(registeredToken).toBe(legacyToken);
await legacyReattached.close();
expect(disposed).toBe(5);
});
- it('defers the remote xAI forward until a running gateway session actually switches to xAI', async () => {
+ it("defers the remote xAI forward until a running gateway session actually switches to xAI", async () => {
const forwardEvents: string[] = [];
let rejectForward = true;
let remoteWrites = 0;
- const remoteStub: import('../transport.js').PiTransport = {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -3844,48 +5275,48 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
ensureHostProxyForward: async (spec) => {
forwardEvents.push(`forward:${spec.localUrl}:${spec.remotePort}`);
- if (rejectForward) throw new Error('remote port already in use');
+ if (rejectForward) throw new Error("remote port already in use");
},
};
let transportOptions:
- Parameters<NonNullable<AgentDeps['getRemotePiTransport']>>[1] | undefined;
+ Parameters<NonNullable<AgentDeps["getRemotePiTransport"]>>[1] | undefined;
const base = byomDeps(
async () => ({
providers: [
{
- id: 'xai',
- name: 'xAI',
- baseUrl: 'http://127.0.0.1:47989',
- api: 'anthropic-messages',
- apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
- models: [{ id: 'xai/grok-4.6' }],
+ id: "xai",
+ name: "xAI",
+ baseUrl: "http://127.0.0.1:47989",
+ api: "anthropic-messages",
+ apiKeyEnvVar: "CINDY_PI_XAI_PROXY_API_KEY",
+ models: [{ id: "xai/grok-4.6" }],
modelIdAliases: {
- 'grok-4.6': 'xai/grok-4.6',
- 'xai/grok-4.6': 'xai/grok-4.6',
+ "grok-4.6": "xai/grok-4.6",
+ "xai/grok-4.6": "xai/grok-4.6",
},
hostProxyForward: {
- localUrl: 'http://127.0.0.1:18765',
+ localUrl: "http://127.0.0.1:18765",
remotePort: 47989,
},
},
],
- env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },
+ env: { CINDY_PI_XAI_PROXY_API_KEY: "xai-proxy-placeholder" },
}),
[
{
- id: 'gateway-model',
- displayName: 'Gateway model',
+ id: "gateway-model",
+ displayName: "Gateway model",
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
},
{
- id: 'grok-4.6',
- displayName: 'Grok 4.6',
+ id: "grok-4.6",
+ displayName: "Grok 4.6",
contextWindow: 500_000,
efforts: [],
defaultEffort: null,
@@ -3893,22 +5324,31 @@ describe('Pi provider-aware model routing', () => {
],
);
captured.requestHandler = async (command) => {
- if (command.type === 'set_model') forwardEvents.push('set_model');
- return command.type === 'get_state'
- ? { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } }
+ if (command.type === "set_model") forwardEvents.push("set_model");
+ return command.type === "get_state"
+ ? {
+ success: true,
+ data: {
+ sessionFile: "/mock/s.jsonl",
+ model: {
+ contextWindow:
+ captured.runtimeModel === "xai/grok-4.6" ? 500_000 : 200_000,
+ },
+ },
+ }
: { success: true, data: {} };
};
const agent = new PiAgent({
...base,
auth: {
...base.auth,
- getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),
+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: "gateway-key" }),
},
runtimeConfig: {
...base.runtimeConfig,
- remoteEndpoint: 'https://gateway.example.test',
+ remoteEndpoint: "https://gateway.example.test",
},
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiFileOps: () => ({
mkdirp: async () => {},
writeFile: async () => {
@@ -3924,11 +5364,11 @@ describe('Pi provider-aware model routing', () => {
},
});
const handle = await agent.startSession({
- sessionId: 'remote-gateway-then-xai',
+ sessionId: "remote-gateway-then-xai",
workingDir: cwd,
- model: 'gateway-model',
- providerId: 'xd',
- remoteHostId: 'remote-host',
+ model: "gateway-model",
+ providerId: "xd",
+ remoteHostId: "remote-host",
});
expect(transportOptions?.hostProxyForwards).toEqual([]);
@@ -3936,28 +5376,30 @@ describe('Pi provider-aware model routing', () => {
captured.requests.length = 0;
remoteWrites = 0;
- await expect(handle.setModel!('grok-4.6', { providerId: 'xai' })).rejects.toThrow(
- /remote port already in use/,
- );
+ await expect(
+ handle.setModel!("grok-4.6", { providerId: "xai" }),
+ ).rejects.toThrow(/remote port already in use/);
expect(remoteWrites).toBe(0);
expect(captured.requests).not.toContainEqual({
- type: 'set_model',
- provider: 'xai',
- modelId: 'xai/grok-4.6',
+ type: "set_model",
+ provider: "xai",
+ modelId: "xai/grok-4.6",
});
rejectForward = false;
forwardEvents.length = 0;
- await handle.setModel!('grok-4.6', { providerId: 'xai' });
+ await handle.setModel!("grok-4.6", { providerId: "xai" });
expect(forwardEvents).toEqual([
- 'forward:http://127.0.0.1:18765:47989',
- 'set_model',
+ "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();
});
- it('hashes the remote permission snapshot into spawn env so a later Full-access attach restarts', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("hashes the remote permission snapshot into spawn env so a later Full-access attach restarts", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -3965,7 +5407,7 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];
@@ -3976,12 +5418,15 @@ describe('Pi provider-aware model routing', () => {
rm: async () => {},
listDir: async () => [],
};
- const startRemote = async (permissionMode: 'ask' | 'bypassPermissions') => {
+ const startRemote = async (permissionMode: "ask" | "bypassPermissions") => {
const base = byomDeps(async () => ({ providers: [], env: {} }));
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async (_hostId, opts) => {
capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
return remoteStub;
@@ -3989,32 +5434,40 @@ describe('Pi provider-aware model routing', () => {
getRemotePiFileOps: () => remoteFileOps,
});
const handle = await agent.startSession({
- sessionId: 'remote-perm-hash',
+ sessionId: "remote-perm-hash",
workingDir: cwd,
- model: 'local-model',
+ model: "local-model",
permissionMode,
- remoteHostId: 'remote-host',
+ remoteHostId: "remote-host",
});
await handle.close();
};
- await startRemote('ask');
- await startRemote('bypassPermissions');
+ await startRemote("ask");
+ await startRemote("bypassPermissions");
expect(capturedRemoteEnvs).toHaveLength(2);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH).toMatch(/^[0-9a-f]{16}$/);
- expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH).toMatch(/^[0-9a-f]{16}$/);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH)
- .not.toBe(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_FILE)
- .not.toBe(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_FILE)
- .toContain(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH);
- expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE)
- .toContain(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH);
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH).toMatch(
+ /^[0-9a-f]{16}$/,
+ );
+ expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH).toMatch(
+ /^[0-9a-f]{16}$/,
+ );
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH).not.toBe(
+ capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH,
+ );
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_FILE).not.toBe(
+ capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE,
+ );
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_FILE).toContain(
+ capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH,
+ );
+ expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE).toContain(
+ capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH,
+ );
});
- it('puts a deterministic Cindy extension bundle hash into remote spawn env', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("puts a deterministic Cindy extension bundle hash into remote spawn env", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -4022,7 +5475,7 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];
@@ -4030,8 +5483,11 @@ describe('Pi provider-aware model routing', () => {
const base = byomDeps(async () => ({ providers: [], env: {} }));
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async (_hostId, opts) => {
capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
return remoteStub;
@@ -4045,30 +5501,34 @@ describe('Pi provider-aware model routing', () => {
}),
});
const handle = await agent.startSession({
- sessionId: 'remote-extension-hash',
+ sessionId: "remote-extension-hash",
workingDir: cwd,
- model: 'local-model',
- remoteHostId: 'remote-host',
+ model: "local-model",
+ remoteHostId: "remote-host",
});
await handle.close();
};
await startRemote();
await startRemote();
- const expected = createHash('sha256')
+ const expected = createHash("sha256")
.update(CINDY_BRIDGE_EXTENSION_SOURCE)
- .update('\n')
+ .update("\n")
.update(CINDY_SUBAGENT_EXTENSION_SOURCE)
- .digest('hex')
+ .digest("hex")
.slice(0, 16);
expect(capturedRemoteEnvs).toHaveLength(2);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_EXTENSION_BUNDLE_HASH).toBe(expected);
- expect(capturedRemoteEnvs[1]!.CINDY_PI_EXTENSION_BUNDLE_HASH).toBe(expected);
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_EXTENSION_BUNDLE_HASH).toBe(
+ expected,
+ );
+ expect(capturedRemoteEnvs[1]!.CINDY_PI_EXTENSION_BUNDLE_HASH).toBe(
+ expected,
+ );
expect(expected).toMatch(/^[0-9a-f]{16}$/);
});
- it('isolates remote configHome by models.json hash so a later route change does not overwrite the live child', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("isolates remote configHome by models.json hash so a later route change does not overwrite the live child", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -4076,7 +5536,7 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];
@@ -4085,7 +5545,7 @@ describe('Pi provider-aware model routing', () => {
const agent = new PiAgent({
...base,
runtimeConfig: { ...base.runtimeConfig, remoteEndpoint },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async (_hostId, opts) => {
capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
return remoteStub;
@@ -4099,29 +5559,33 @@ describe('Pi provider-aware model routing', () => {
}),
});
const handle = await agent.startSession({
- sessionId: 'remote-config-hash',
+ sessionId: "remote-config-hash",
workingDir: cwd,
- model: 'local-model',
- remoteHostId: 'remote-host',
+ model: "local-model",
+ remoteHostId: "remote-host",
});
await handle.close();
};
- await startRemote('https://gateway-a.example.test');
- await startRemote('https://gateway-b.example.test');
+ await startRemote("https://gateway-a.example.test");
+ await startRemote("https://gateway-b.example.test");
expect(capturedRemoteEnvs).toHaveLength(2);
- expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR)
- .not.toBe(capturedRemoteEnvs[1]!.PI_CODING_AGENT_DIR);
- expect(capturedRemoteEnvs[0]!.CINDY_PI_MODELS_JSON_HASH)
- .not.toBe(capturedRemoteEnvs[1]!.CINDY_PI_MODELS_JSON_HASH);
- expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR)
- .toContain((capturedRemoteEnvs[0]!.CINDY_PI_MODELS_JSON_HASH ?? '').slice(0, 16));
- expect(capturedRemoteEnvs[1]!.PI_CODING_AGENT_DIR)
- .toContain((capturedRemoteEnvs[1]!.CINDY_PI_MODELS_JSON_HASH ?? '').slice(0, 16));
+ expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR).not.toBe(
+ capturedRemoteEnvs[1]!.PI_CODING_AGENT_DIR,
+ );
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_MODELS_JSON_HASH).not.toBe(
+ capturedRemoteEnvs[1]!.CINDY_PI_MODELS_JSON_HASH,
+ );
+ expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR).toContain(
+ (capturedRemoteEnvs[0]!.CINDY_PI_MODELS_JSON_HASH ?? "").slice(0, 16),
+ );
+ expect(capturedRemoteEnvs[1]!.PI_CODING_AGENT_DIR).toContain(
+ (capturedRemoteEnvs[1]!.CINDY_PI_MODELS_JSON_HASH ?? "").slice(0, 16),
+ );
});
- it('includes settings.json in the remote launch identity so retry config restarts the child', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("includes settings.json in the remote launch identity so retry config restarts the child", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -4129,7 +5593,7 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
const written = new Map<string, string>();
@@ -4137,8 +5601,11 @@ describe('Pi provider-aware model routing', () => {
const base = byomDeps(async () => ({ providers: [], env: {} }));
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async (_hostId, opts) => {
capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
return remoteStub;
@@ -4154,31 +5621,39 @@ describe('Pi provider-aware model routing', () => {
}),
});
const handle = await agent.startSession({
- sessionId: 'remote-settings-hash',
+ sessionId: "remote-settings-hash",
workingDir: cwd,
- model: 'local-model',
- remoteHostId: 'remote-host',
+ model: "local-model",
+ remoteHostId: "remote-host",
});
await handle.close();
- const modelsJson = [...written.entries()].find(([filePath]) => filePath.endsWith('models.json'))?.[1];
- const settingsJson = [...written.entries()].find(([filePath]) => filePath.endsWith('settings.json'))?.[1];
+ const modelsJson = [...written.entries()].find(([filePath]) =>
+ filePath.endsWith("models.json"),
+ )?.[1];
+ const settingsJson = [...written.entries()].find(([filePath]) =>
+ filePath.endsWith("settings.json"),
+ )?.[1];
expect(modelsJson).toBeTruthy();
expect(settingsJson).toBeTruthy();
- const modelsOnlyHash = createHash('sha256').update(modelsJson!).digest('hex');
- const launchHash = createHash('sha256')
+ const modelsOnlyHash = createHash("sha256")
+ .update(modelsJson!)
+ .digest("hex");
+ const launchHash = createHash("sha256")
.update(modelsJson!)
- .update('\n')
+ .update("\n")
.update(settingsJson!)
- .digest('hex');
+ .digest("hex");
expect(launchHash).not.toBe(modelsOnlyHash);
expect(capturedRemoteEnvs).toHaveLength(1);
expect(capturedRemoteEnvs[0]!.CINDY_PI_MODELS_JSON_HASH).toBe(launchHash);
- expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR).toContain(launchHash.slice(0, 16));
+ expect(capturedRemoteEnvs[0]!.PI_CODING_AGENT_DIR).toContain(
+ launchHash.slice(0, 16),
+ );
});
- it('inlines remote text attachments and rejects local path mentions before dispatch', async () => {
- const remoteStub: import('../transport.js').PiTransport = {
+ it("inlines remote text attachments and rejects local path mentions before dispatch", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
onLine: () => () => {},
onStderr: () => () => {},
@@ -4186,16 +5661,19 @@ describe('Pi provider-aware model routing', () => {
close: async () => {},
pid: 4321,
isClosed: () => false,
- remoteBinaryPath: '/remote/pi',
+ remoteBinaryPath: "/remote/pi",
killRemoteSession: async () => {},
};
- const attachment = path.join(cwd, 'notes.txt');
- writeFileSync(attachment, 'remote-inline-body');
+ const attachment = path.join(cwd, "notes.txt");
+ writeFileSync(attachment, "remote-inline-body");
const base = byomDeps(async () => ({ providers: [], env: {} }));
const agent = new PiAgent({
...base,
- runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
- resolveRemotePiBinaryPath: async () => '/remote/pi',
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
getRemotePiTransport: async () => remoteStub,
getRemotePiFileOps: () => ({
mkdirp: async () => {},
@@ -4206,28 +5684,32 @@ describe('Pi provider-aware model routing', () => {
}),
});
const handle = await agent.startSession({
- sessionId: 'remote-attach',
+ sessionId: "remote-attach",
workingDir: cwd,
- model: 'local-model',
- remoteHostId: 'remote-host',
+ model: "local-model",
+ remoteHostId: "remote-host",
});
captured.requests.length = 0;
await handle.send({
- type: 'user',
+ type: "user",
content: [
- { type: 'text', text: 'please read this' },
- { type: 'file', path: attachment },
+ { type: "text", text: "please read this" },
+ { type: "file", path: attachment },
],
});
- const prompt = captured.requests.find((r) => r.type === 'prompt');
- expect(String(prompt?.message)).toContain('remote-inline-body');
+ const prompt = captured.requests.find((r) => r.type === "prompt");
+ expect(String(prompt?.message)).toContain("remote-inline-body");
expect(String(prompt?.message)).not.toContain(attachment);
- await expect(handle.send({
- type: 'user',
- content: [{ type: 'mention', name: 'local-dir', path: cwd, kind: 'dir' }],
- })).rejects.toThrow(/cannot use local path mentions/);
+ await expect(
+ handle.send({
+ type: "user",
+ content: [
+ { type: "mention", name: "local-dir", path: cwd, kind: "dir" },
+ ],
+ }),
+ ).rejects.toThrow(/cannot use local path mentions/);
await handle.close();
});
});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 31b0a0cdbd..df74cdd8e1 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -5521,18 +5521,10 @@ export class PiAgent extends BaseAgent {
}
throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);
}
- // pi 已确认 → 清掉 pending 标记放行派发。写失败时**不**抛错:模型切换本身确实成功了,
- // 谎报失败会让上层与 UI 状态和 pi 真实状态背离。代价是这个会话的子代理一直被 pending
- // 挡住(可见的降级、拒绝时有明确文案),而它是安全方向 —— 绝不会把委派发到错误 endpoint。
- if (
- subagentRoutingEnabled
- && !(await writeSubagentRuntimeFile({ model: wireModel, provider }))
- ) {
- deps.logger.error(
- 'pi: model switch confirmed but the subagent routing snapshot stayed pending; ' +
- 'subagent delegation stays disabled for this session (fail-closed)',
- );
- }
+ // 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.
mutableModel = model;
mutableWireModel = wireModel;
mutablePiProviderId = provider;
@@ -5550,17 +5542,27 @@ export class PiAgent extends BaseAgent {
// 换模型 / 换路由可能正好修掉了审阅器不可用的原因;换完又不可用值得再提醒一次。
autoReviewUnavailableNotice.reset();
autoReviewConfirmUndeliveredNotice.reset();
- const previousWindow = ctx.contextWindow;
const data = (resp.data ?? {}) as { contextWindow?: number };
- const nextWindow =
+ const setModelReportedWindow =
typeof data.contextWindow === 'number' && data.contextWindow > 0
? data.contextWindow
- : (this.deps.resolvePiRuntimeModelDescriptor?.(mutableProviderId ?? null, model)?.contextWindow
- ?? this.capabilities.availableModels.find((candidate) => candidate.id === model)?.contextWindow
- ?? ctx.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;
- if (nextWindow > 0 && nextWindow !== previousWindow) {
+ // 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,
@@ -5579,6 +5581,70 @@ export class PiAgent extends BaseAgent {
`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,
+ piCompactionPct: sessionPiAutoCompactPct,
+ });
+ 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),
@@ -5596,6 +5662,18 @@ export class PiAgent extends BaseAgent {
);
}
}
+ // 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.
+ if (
+ subagentRoutingEnabled &&
+ !(await writeSubagentRuntimeFile({ model: wireModel, provider }))
+ ) {
+ deps.logger.error(
+ 'pi: model switch confirmed but the subagent routing snapshot stayed pending; ' +
+ 'subagent delegation stays disabled for this session (fail-closed)',
+ );
+ }
};
const handle: AgentSessionHandle = {
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 4b55d0c0e4..1b56f22255 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -1188,8 +1188,11 @@ describe('Maker session close events', () => {
expect(startSession).toHaveBeenCalledTimes(2);
});
- it('retries a failed crash cleanup before recreating the session', async () => {
- const crashingHandle = createHandle({ id: 'thread-crashed-close-retry' });
+ it('retries a retained Pi error handle before recreating the session', async () => {
+ const crashingHandle = createHandle({
+ id: 'thread-crashed-close-retry',
+ agentKind: 'pi',
+ });
crashingHandle.events = () => ({
[Symbol.asyncIterator]() {
return {
@@ -1204,29 +1207,35 @@ describe('Maker session close events', () => {
closeAttempts += 1;
if (closeAttempts === 1) throw new Error('transport close failed');
});
- const healthyHandle = createHandle({ id: 'thread-rebuilt-after-close-retry' });
+ const healthyHandle = createHandle({
+ id: 'thread-rebuilt-after-close-retry',
+ agentKind: 'pi',
+ });
const startSession = vi.fn()
.mockResolvedValueOnce(crashingHandle)
.mockResolvedValueOnce(healthyHandle);
const maker = new Maker({
- agents: { codex: createAgent(startSession) },
+ agents: { pi: createAgent(startSession, 'pi') },
storage: createStorage(),
logger: createLogger(),
});
const options: CreateSessionOptions = {
id: 'session-crash-close-retry',
- agentKind: 'codex',
+ agentKind: 'pi',
workingDir: '/repo',
- model: 'gpt-5.4',
+ model: 'pi-model',
};
const crashed = await maker.createSession(options);
await vi.waitFor(() => expect(crashed.getStatus()).toBe('error'));
expect(maker.getSession('session-crash-close-retry')).toBe(crashed);
+ expect(maker.listActiveSessions()).toEqual([crashed]);
const rebuilt = await maker.createSession(options);
expect(rebuilt.sdkSessionId).toBe('thread-rebuilt-after-close-retry');
expect(maker.getSession('session-crash-close-retry')).toBe(rebuilt);
+ expect(maker.listActiveSessions()).toEqual([rebuilt]);
+ expect(maker.listActiveSessions()).not.toContain(crashed);
expect(closeAttempts).toBe(2);
expect(startSession).toHaveBeenCalledTimes(2);
});
diff --git a/packages/maker-shared/src/__tests__/agentCapabilities.test.ts b/packages/maker-shared/src/__tests__/agentCapabilities.test.ts
index ebfcb591fc..288b67e282 100644
--- a/packages/maker-shared/src/__tests__/agentCapabilities.test.ts
+++ b/packages/maker-shared/src/__tests__/agentCapabilities.test.ts
@@ -6,6 +6,7 @@ import {
compactEnglishEffortLabel,
normalizeMobileAgentCapabilities,
reconcileRuntimeDraftWithCapabilities,
+ shouldBlockLegacyRemoteModelWindowSwitch,
} from '../agentCapabilities';
const desktopCapabilitiesPayload = {
@@ -65,6 +66,10 @@ describe('agent capabilities shared model', () => {
'claude-sonnet-4-6',
'claude-haiku-4-6',
]);
+ expect(capabilities?.availableModels.map((item) => item.contextWindow)).toEqual([
+ 200_000,
+ 200_000,
+ ]);
// 已知档 id 在 normalize 单点换成中文词表名(被控端给的英文 displayName 被覆盖)。
expect(capabilities?.effortLevels.map((item) => item.label)).toEqual([
'低',
@@ -78,12 +83,91 @@ describe('agent capabilities shared model', () => {
'plan',
]);
expect(capabilities?.supportsSessionAgentSwitch).toBe(false);
+ expect(capabilities?.supportsModelWindowSwitchGuard).toBe(false);
expect(capabilities?.availableModels[0].newSessionDefault).toEqual(['claude-code', 'codex', 'pi']);
expect('newSessionDefault' in (capabilities?.availableModels[1] ?? {})).toBe(false);
expect(normalizeMobileAgentCapabilities({
...desktopCapabilitiesPayload,
supportsSessionAgentSwitch: true,
})?.supportsSessionAgentSwitch).toBe(true);
+ expect(normalizeMobileAgentCapabilities({
+ ...desktopCapabilitiesPayload,
+ supportsModelWindowSwitchGuard: true,
+ })?.supportsModelWindowSwitchGuard).toBe(true);
+ });
+
+ describe('legacy host model-window guard', () => {
+ const pressuredShrink = {
+ hostGuardSupported: false,
+ agentKind: 'codex',
+ contextTokens: 180_000,
+ currentContextWindow: 1_000_000,
+ targetContextWindow: 200_000,
+ };
+
+ it('blocks non-Pi legacy shrinks at 90% while preserving same/expand, low pressure, and SSH semantics', () => {
+ expect(shouldBlockLegacyRemoteModelWindowSwitch(pressuredShrink)).toBe(true);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ contextTokens: 179_999,
+ })).toBe(false);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ targetContextWindow: 1_000_000,
+ })).toBe(false);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ targetContextWindow: 2_000_000,
+ })).toBe(false);
+ const pressuredSshShrink = { ...pressuredShrink, isSsh: true };
+ expect(shouldBlockLegacyRemoteModelWindowSwitch(pressuredSshShrink)).toBe(true);
+ });
+
+ it('fails closed for every estimated legacy Pi route and defers guarded Pi to the host', () => {
+ const legacyPiSwitch = { ...pressuredShrink, agentKind: 'pi' };
+ const estimatedPiRoutes = {
+ lowPressure: { ...legacyPiSwitch, contextTokens: 179_999 },
+ exact90Percent: legacyPiSwitch,
+ sameWindow: { ...legacyPiSwitch, targetContextWindow: 1_000_000 },
+ expansion: { ...legacyPiSwitch, targetContextWindow: 2_000_000 },
+ unknownUsage: { ...legacyPiSwitch, contextTokens: undefined },
+ unknownCurrentWindow: { ...legacyPiSwitch, currentContextWindow: undefined },
+ unknownTargetWindow: { ...legacyPiSwitch, targetContextWindow: undefined },
+ };
+ for (const route of Object.values(estimatedPiRoutes)) {
+ expect(shouldBlockLegacyRemoteModelWindowSwitch(route)).toBe(true);
+ }
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...legacyPiSwitch,
+ hostGuardSupported: true,
+ })).toBe(false);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...legacyPiSwitch,
+ hostGuardSupported: true,
+ contextTokens: undefined,
+ targetContextWindow: undefined,
+ })).toBe(false);
+ });
+
+ it('fails closed when legacy-host window or usage facts are unknown', () => {
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ contextTokens: undefined,
+ })).toBe(true);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ currentContextWindow: undefined,
+ })).toBe(true);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ targetContextWindow: undefined,
+ })).toBe(true);
+ expect(shouldBlockLegacyRemoteModelWindowSwitch({
+ ...pressuredShrink,
+ contextTokens: undefined,
+ targetContextWindow: 1_000_000,
+ })).toBe(false);
+ });
});
it('uses the current model efforts and model-specific labels', () => {
diff --git a/packages/maker-shared/src/agentCapabilities.ts b/packages/maker-shared/src/agentCapabilities.ts
index fbd40d54bd..c62ed3d624 100644
--- a/packages/maker-shared/src/agentCapabilities.ts
+++ b/packages/maker-shared/src/agentCapabilities.ts
@@ -6,6 +6,8 @@ export interface MobileModelOption {
effortDisplayNames: Record<string, string>;
defaultEffort: string | null;
supportsFastMode: boolean;
+ /** Host-advertised catalog window when available; omitted by older Desktop versions. */
+ contextWindow?: number;
/** 区域门控后的新任务默认标记。 */
newSessionDefault?: ('claude-code' | 'codex' | 'pi')[];
}
@@ -25,6 +27,8 @@ export interface MobileAgentCapabilities {
planModeSupported: boolean;
/** desktop host 是否支持同一会话 Claude Code / Codex pending-intent 切换;旧 host 缺省 false。 */
supportsSessionAgentSwitch?: boolean;
+ /** host 是否在 set-model 内执行强制模型窗口保护;旧 host 缺省 false。 */
+ supportsModelWindowSwitchGuard?: boolean;
}
export interface MobileSessionRuntimeOptions {
@@ -154,9 +158,39 @@ export function normalizeMobileAgentCapabilities(value: unknown): MobileAgentCap
hasFastMode: value.hasFastMode === true,
planModeSupported: isRecord(value.planMode) && value.planMode.supported === true,
supportsSessionAgentSwitch: value.supportsSessionAgentSwitch === true,
+ supportsModelWindowSwitchGuard: value.supportsModelWindowSwitchGuard === true,
};
}
+export function shouldBlockLegacyRemoteModelWindowSwitch(args: {
+ hostGuardSupported: boolean;
+ agentKind: string | null | undefined;
+ contextTokens: number | null | undefined;
+ currentContextWindow: number | null | undefined;
+ targetContextWindow: number | null | undefined;
+}): boolean {
+ if (args.hostGuardSupported) return false;
+ if (args.agentKind === 'pi') return true;
+ const { contextTokens, currentContextWindow, targetContextWindow } = args;
+ const hasKnownWindows =
+ typeof currentContextWindow === 'number' &&
+ Number.isFinite(currentContextWindow) &&
+ currentContextWindow > 0 &&
+ typeof targetContextWindow === 'number' &&
+ Number.isFinite(targetContextWindow) &&
+ targetContextWindow > 0;
+ if (!hasKnownWindows) return true;
+ if (targetContextWindow >= currentContextWindow) return false;
+ if (
+ typeof contextTokens !== 'number' ||
+ !Number.isFinite(contextTokens) ||
+ contextTokens < 0
+ ) {
+ return true;
+ }
+ return contextTokens / targetContextWindow >= 0.9;
+}
+
export function buildSessionRuntimeOptions(
session: { model: string },
capabilities: MobileAgentCapabilities | null,
@@ -305,6 +339,12 @@ function normalizeModelOption(value: unknown): MobileModelOption | null {
typeof entry[1] === 'string',
))
: {};
+ const contextWindow =
+ typeof value.contextWindow === 'number' &&
+ Number.isFinite(value.contextWindow) &&
+ value.contextWindow > 0
+ ? value.contextWindow
+ : undefined;
const newSessionDefault = Array.isArray(value.newSessionDefault)
? [...new Set(value.newSessionDefault.filter(
(item): item is 'claude-code' | 'codex' | 'pi' =>
@@ -321,6 +361,7 @@ function normalizeModelOption(value: unknown): MobileModelOption | null {
effortDisplayNames,
defaultEffort: readString(value.defaultEffort),
supportsFastMode: value.supportsFastMode === true,
+ ...(contextWindow ? { contextWindow } : {}),
...(newSessionDefault.length > 0 ? { newSessionDefault } : {}),
};
}