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。

feat(desktop): 任务级上下文窗口档位(内核):存储、边界与各 agent 接入

Zhang Yunjin4b4b9e032a76
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.ts
index b803bb5754..bf22a25378 100644
--- a/apps/desktop/src/main/__tests__/fork.test.ts
+++ b/apps/desktop/src/main/__tests__/fork.test.ts
@@ -22,6 +22,18 @@ import { CodexResumePreparationBlockedError } from '@cindy/maker-core';
import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import { projectSessionContextWindow } from '../../shared/sessionContextWindow';
import { computeForkSourceMessagesDigest } from '../localDb/forkRecoverySnapshot.js';
+import {
+ pruneSessionContextWindowBudget,
+ readSessionContextWindowBudget,
+ writeSessionContextWindowBudget,
+} from '../maker-host/session-context-budget-store.js';
+
+/** 事务提交时正在写入的新会话 id(由 createBusinessSessionId 生成,测试从 txMock 入参里取)。 */
+function forkedSessionIdFromTx(): string {
+ const call = txCalls.find((c) => c.name === 'fork.session');
+ if (!call) throw new Error('no fork.session tx call recorded');
+ return (call.args as { newSession: { id: string } }).newSession.id;
+}
import { MAKER_INVOKE } from '../maker-ipc/channels.js';
const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
@@ -44,6 +56,11 @@ vi.mock('electron', () => ({
ipcHandlers.set(channel, handler);
},
},
+ // 预算用例经真实的 session-context-budget-store → ownerScopedUserDataPath →
+ // app.getPath('userData');mock 必须暴露 app,否则报「No "app" export is defined
+ // on the electron mock」。指向 beforeEach 建的临时目录(userDataDirRef),随
+ // tempDirs 生命周期一起清理,绝不碰真实 userData。
+ app: { getPath: (name: string) => (name === 'userData' ? userDataDirRef.current : `/tmp/cindy-fork-test/${name}`) },
}));
vi.mock('../localDb/ipc/sessionCreatedBroadcast.js', () => ({
emitSessionCreated: sessionCreatedMock,
@@ -120,6 +137,8 @@ let forkSessionStripEncrypted: typeof import('../maker-orchestration/fork').fork
const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
const originalXdtUserDataDir = process.env.XDT_USER_DATA_DIR;
const tempDirs: string[] = [];
+/** electron mock 的 app.getPath('userData') 指向的临时目录;beforeEach 里建、afterEach 随 tempDirs 清。 */
+const userDataDirRef: { current: string } = { current: '' };
beforeEach(async () => {
ipcHandlers.clear();
@@ -130,6 +149,11 @@ beforeEach(async () => {
else process.env.XDT_USER_DATA_DIR = originalXdtUserDataDir;
selectQueue.length = 0;
txCalls.length = 0;
+ // 预算文件的 userData 隔离:每个用例一个新的临时目录(electron mock 的 app.getPath 指向它)。
+ fs.mkdtemp(path.join(os.tmpdir(), 'cindy-fork-userdata-')).then((dir) => {
+ userDataDirRef.current = dir;
+ tempDirs.push(dir);
+ });
txMock.mockClear();
queryOneMock.mockReset();
queryOneMock.mockResolvedValue(null);
@@ -281,6 +305,106 @@ describe('disabled Cindy Make fork boundaries', () => {
});
describe('forkSessionAtMessage', () => {
+ it('inherits the task context-window budget (preference entry, not a session column)', async () => {
+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });
+ const priorAssistant = makeMessageRow({
+ id: 'asst-1',
+ role: 'assistant',
+ content: '"hi back"',
+ agentMeta: JSON.stringify({ uuid: 'sdk-msg-uuid-1' }),
+ createdAt: 2500,
+ });
+ const priorUser = makeMessageRow({ id: 'user-1', role: 'user', content: '"hi"', createdAt: 2000 });
+ selectQueue.push([makeSourceRow({})]);
+ selectQueue.push([target]);
+ selectQueue.push([priorUser, priorAssistant]);
+ selectQueue.push([makeSourceRow({ title: '[Fork] Project A', sdkSessionId: 'sdk-new-session-uuid' })]);
+ forkSdkSessionMock.mockResolvedValue({
+ newSdkSessionId: 'sdk-new-session-uuid',
+ uuidMap: new Map<string, string>(),
+ initialContextTokens: 123456,
+ });
+
+ writeSessionContextWindowBudget('src-session', 300_000);
+ try {
+ await forkSessionAtMessage('src-session', 'target-user');
+ const newSessionId = forkedSessionIdFromTx();
+ expect(readSessionContextWindowBudget(newSessionId)).toBe(300_000);
+ pruneSessionContextWindowBudget(newSessionId);
+ } finally {
+ pruneSessionContextWindowBudget('src-session');
+ }
+ });
+
+ it('writes the inherited budget before the commit, and rolls it back when the transaction fails', async () => {
+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });
+ const priorAssistant = makeMessageRow({
+ id: 'asst-1',
+ role: 'assistant',
+ content: '"hi back"',
+ agentMeta: JSON.stringify({ uuid: 'sdk-msg-uuid-1' }),
+ createdAt: 2500,
+ });
+ const priorUser = makeMessageRow({ id: 'user-1', role: 'user', content: '"hi"', createdAt: 2000 });
+ selectQueue.push([makeSourceRow({})]);
+ selectQueue.push([target]);
+ selectQueue.push([priorUser, priorAssistant]);
+
+ writeSessionContextWindowBudget('src-session', 262_144);
+ let budgetSeenAtCommit: number | null | undefined;
+ let committedSessionId = '';
+ txMock.mockImplementationOnce((name: string, args: unknown) => {
+ txCalls.push({ name, args });
+ committedSessionId = (args as { newSession: { id: string } }).newSession.id;
+ budgetSeenAtCommit = readSessionContextWindowBudget(committedSessionId);
+ return Promise.reject(new Error('tx boom'));
+ });
+
+ try {
+ await expect(forkSessionAtMessage('src-session', 'target-user')).rejects.toThrow('tx boom');
+ // 事务里能读到它 = 写在提交之前:写失败时不会出现「任务已建好却报整体失败」。
+ expect(budgetSeenAtCommit).toBe(262_144);
+ // 事务失败 → 刚写的条目被撤掉,不留指向不存在任务的孤儿。
+ expect(readSessionContextWindowBudget(committedSessionId)).toBeNull();
+ } finally {
+ // 一次性实现必须收回:否则会漏给下一个用例的 fork.session 事务。
+ txMock.mockReset();
+ pruneSessionContextWindowBudget('src-session');
+ }
+ });
+
+ it('inherits the task context-window budget on a strip-encrypted Codex fork too', async () => {
+ const first = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 1000 });
+ const second = makeMessageRow({ id: 'asst-1', role: 'assistant', createdAt: 2000 });
+ selectQueue.push([
+ makeSourceRow({ agentKind: 'codex', model: 'gpt-5.5', sdkSessionId: 'codex-thread-source' }),
+ ]);
+ selectQueue.push([]); // 没有已存在的剥离 fork 子会话
+ selectQueue.push([first, second]);
+ selectQueue.push([
+ makeSourceRow({
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-new',
+ parentSessionId: 'src-session',
+ }),
+ ]);
+ forkSdkSessionMock.mockResolvedValue({
+ newSdkSessionId: 'codex-thread-new',
+ uuidMap: new Map<string, string>(),
+ });
+
+ writeSessionContextWindowBudget('src-session', 250_000);
+ try {
+ await forkSessionStripEncrypted('src-session');
+ const newSessionId = forkedSessionIdFromTx();
+ expect(readSessionContextWindowBudget(newSessionId)).toBe(250_000);
+ pruneSessionContextWindowBudget(newSessionId);
+ } finally {
+ pruneSessionContextWindowBudget('src-session');
+ }
+ });
+
// Unit, PR #6529 archived-discovery regression: evaluate the real list WHERE
// against SQLite. The old queue fake cannot detect status filtering. Minimal
// input: active/archived/deleted children plus a different parent and source.
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 87c91389db..c853561e59 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -30,6 +30,9 @@ describe('maker:event hot path ordering', () => {
const code = source.slice(start, source.indexOf('\n// Keep holder reads', start));
const js = transpileModule(code, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;
const cleared = vi.fn();
+ // 任务级窗口预算的应用去重表也在这一段的 `delete` 里(见 register.ts 的
+ // cleanupClosedSessionRuntime):沙箱必须把它当依赖注入,否则抽样执行会 ReferenceError。
+ const appliedContextWindowBudgets = new Map<string, number | null>([['departing-task', 300_000]]);
const deps = {
pendingCredentialSwitchHolder: null, deferredCodexRestartHolder: null,
gatewayCodexRestartHolder: { onSessionSettled: vi.fn() },
@@ -37,6 +40,7 @@ describe('maker:event hot path ordering', () => {
refreshRemoteCodexMcpOnTurnSettledHolder: () => { throw new Error('App session is switching'); },
gitSnapshotCoordinator: { onSessionClosed: vi.fn() },
clearOrcaMcpHydrated: vi.fn(), knownNonOrcaSessionIds: new Set(),
+ appliedContextWindowBudgets,
lastReportedCostUsdBySession: new Map(), lastReportedModelUsageBySession: new Map(),
turnModelPromiseBySession: new Map(), turnUsageContextBySession: new Map(),
productTurnWallClockTracker: { clear: cleared }, productTurnUsageTargetTracker: { clear: vi.fn() },
@@ -48,6 +52,8 @@ describe('maker:event hot path ordering', () => {
expect(() => cleanup({ id: 'departing-task' })).not.toThrow();
expect(deps.gatewayCodexRestartHolder.onSessionSettled).toHaveBeenCalledOnce();
expect(cleared).toHaveBeenCalledWith('departing-task');
+ // 关闭任务时必须把窗口预算的去重记账一起清掉,否则同 id 的替换实例会沿用旧值。
+ expect(appliedContextWindowBudgets.has('departing-task')).toBe(false);
expect(deps.clearSessionPersistState).toHaveBeenCalledWith('departing-task');
expect(deps.handleAgentIslandSessionClosedAfterCleanup).toHaveBeenCalledWith('departing-task', 'process-closed');
});
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index e24d8be1b7..7e18b87c2a 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -796,6 +796,19 @@ describe('sendToSession ordering', () => {
'const opts = buildCreateOptsWithStderr({',
);
expectOrder(resumeBranch, '...directoryGrantsForRuntime(storedExtraDirs),', 'await bootstrapSession(opts);');
+ // 任务级窗口预算:worker 唤醒自己拼 opts,不经 createSession 的 prepareStartOptions 钩子。
+ // 缺这一步,预算会在引擎进程重启时丢失(2026-09-30 实测:档位卡仍显示 50%,而 Pi 的
+ // compaction.reserveTokens 被写成无预算值 → 阈值退回满窗,跑到预算窗口 100% 以上也不压缩)。
+ expectOrder(
+ resumeBranch,
+ '...directoryGrantsForRuntime(storedExtraDirs),',
+ 'await applySessionContextWindowBudgetToCreateOpts(target.sessionId, opts, getActiveCatalog());',
+ );
+ expectOrder(
+ resumeBranch,
+ 'await applySessionContextWindowBudgetToCreateOpts(target.sessionId, opts, getActiveCatalog());',
+ 'await bootstrapSession(opts);',
+ );
expect(serviceDepsBlock).toContain('resumeWorkerSession: async (target) => {');
expect(serviceDepsBlock).toContain('await orcaWorkerResumeScheduler.request(target);');
// focus 切换是纯 UI 操作:resume 只能后台调度,不能在 IPC / MCP handler 里同步 await
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 289bc84537..2b53954d5e 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -1451,6 +1451,21 @@ describe('session runtime control wiring', () => {
const liveUsageRead = setModel.indexOf('getSessionLastLiveUsage(sessionId)');
expect(liveUsageRead).toBeGreaterThan(-1);
expect(liveUsageRead).toBeLessThan(pressurePreflight);
+ // 预算必须在预检之前读到,且预检比较的目标窗口必须带预算:否则小预算任务会拿
+ // 目录默认大窗证明「有余量」,跳过冷启动核实和切换后的最终窗口校验,既有上下文
+ // 直接落进过载窗口(Greptile P1,2026-09-22)。
+ const budgetRead = setModel.indexOf('await readStoredSessionContextWindowBudget(sessionId)');
+ const targetWindowResolve = setModel.indexOf('const coldPiTargetContextWindow');
+ expect(budgetRead).toBeGreaterThan(-1);
+ expect(budgetRead).toBeLessThan(targetWindowResolve);
+ expect(targetWindowResolve).toBeLessThan(pressurePreflight);
+ expect(
+ setModel.slice(targetWindowResolve, pressurePreflight).includes('sessionContextWindowBudget'),
+ ).toBe(true);
+ // 预算只读一次,预检与后续的缩窗闸门共用同一个值(同一锁内不可能变化)。
+ expect(
+ setModel.split('await readStoredSessionContextWindowBudget(sessionId)').length - 1,
+ ).toBe(1);
expect(setModel).toContain('set-model: skipped cold Pi window verification');
expect(setModel).toContain('coldPiRouteWithoutLiveWindowCheck = true;');
// 终态活进程核验必须同步跳过,否则只是换成 'Pi target runtime could not be verified'。
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3d8bf7beed..dd91da73ba 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -794,6 +794,7 @@ import {
isSessionTurnPendingCompletion,
isSessionInTurn,
stopOrcaIdleWatcher,
+ applySessionContextWindowBudgetChange,
setGoalClearObserver,
setGoalDeferredResumeCancelObserver,
setGoalIdleObserver,
@@ -9317,6 +9318,9 @@ app.on('ready', async () => {
}
return true;
},
+ // 任务级窗口预算落库后的运行时应用:与模型级上限编辑同一套「关 handle
+ // 冷重建 / 回合中登记 pending」语义。
+ applyContextWindowBudget: applySessionContextWindowBudgetChange,
withSessionLock: withSendToSessionLock,
// Mirrors exactly what the resume handler requires (`maker-ipc/register.ts`):
// a loaded session for this task whose agent is PI. Without it a finished
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 6490032db4..c0741e3125 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -24,6 +24,10 @@ import { tx as runDbTransaction } from '../../worker/opHandlers/tx';
import type { SessionRouteLock } from '../../sessionRouteLock';
import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir';
import { isWorktreeMoveBlockedError } from '../../../../shared/worktreeMoveGuardError';
+import {
+ isSessionContextWindowBudgetCustomized,
+ readSessionContextWindowBudget,
+} from '../../../maker-host/session-context-budget-store.js';
type SessionRouteLockMock = SessionRouteLock &
MockInstance<(sessionId: string, task: () => Promise<unknown>) => Promise<unknown>>;
@@ -885,6 +889,32 @@ describe('local-db:sessions:update handler wiring', () => {
});
});
+ it('rejects an out-of-range task context window budget instead of silently clearing it', async () => {
+ // 与隧道入口同口径:<1000 会被 normalize 变成 null(等于静默清掉用户预算),
+ // 超大值会被静默夹到上限;调用方却收到成功回包。宁可显式拒绝。
+ await expect(invokeUpdate('cc-local', { contextWindowBudget: 999 })).rejects.toThrow(
+ /contextWindowBudget must be null or an integer/,
+ );
+ await expect(invokeUpdate('cc-local', { contextWindowBudget: 300_000.5 })).rejects.toThrow(
+ /contextWindowBudget must be null or an integer/,
+ );
+ await expect(invokeUpdate('cc-local', { contextWindowBudget: 100_000_001 })).rejects.toThrow(
+ /contextWindowBudget must be null or an integer/,
+ );
+ });
+
+ it('persists null and an in-range task context window budget', async () => {
+ // 任务窗口预算不是会话列(没有 context_window_budget 列),而是 main 侧偏好文件里的
+ // 条目:这里读写它自己的 store(路径由 electron 的 userData mock 指到临时目录)。
+ await invokeUpdate('cc-local', { contextWindowBudget: 300_000 });
+ expect(readSessionContextWindowBudget('cc-local')).toBe(300_000);
+ expect(isSessionContextWindowBudgetCustomized('cc-local')).toBe(true);
+
+ await invokeUpdate('cc-local', { contextWindowBudget: null });
+ expect(readSessionContextWindowBudget('cc-local')).toBeNull();
+ expect(isSessionContextWindowBudgetCustomized('cc-local')).toBe(false);
+ });
+
it.each(['model', 'harness'])('projects the saved owner choice during an automatic %s switch', async (kind) => {
const baseline = JSON.stringify({ scopeId: 'run', agentKind: 'pi', model: 'owner-model',
providerId: 'owner-provider', effort: 'high', fastMode: true });
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index 25f423e6f5..c12afaa4d6 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -98,6 +98,8 @@ export interface RegisterLocalDbIpcOpts {
lookupSessionWorktreeBinding?: (sessionId: string) => string | null;
/** Close a moved local Pi/Codex runtime after revalidating that its turn is idle. */
closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
+ /** Apply a persisted task-level context window budget to the live runtime. */
+ applyContextWindowBudget?: RegisterSessionIpcOpts['applyContextWindowBudget'];
/** Serialize startup tombstone cleanup with task restore/start/send operations. */
withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;
/**
@@ -238,6 +240,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
registerSessionIpc(getCurrentDbClientUserId, {
resolveContextWindow: opts.resolveContextWindow,
closeIdleSessionForMove: opts.closeIdleSessionForMove,
+ applyContextWindowBudget: opts.applyContextWindowBudget,
});
registerMessageIpc(opts.isSessionTurnPendingCompletion, opts.readHistoryLiveMessages);
registerRemoteHistoryIpc();
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 35fae0ca9c..69fe53df6b 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -91,10 +91,20 @@ import {
normalizeWorkingDirForStorage,
workingDirEquals,
} from '../../../shared/workingDir.js';
+import {
+ MAX_CONTEXT_WINDOW_BUDGET,
+ MIN_CONTEXT_WINDOW_BUDGET,
+ normalizeContextWindowBudget,
+} from '../../../shared/sessionContextWindowBudget.js';
import {
WORKTREE_MOVE_BLOCKED_CODE,
WORKTREE_MOVE_BLOCKED_MESSAGE,
} from '../../../shared/worktreeMoveGuardError.js';
+import {
+ pruneSessionContextWindowBudget,
+ readSessionContextWindowBudget,
+ writeSessionContextWindowBudget,
+} from '../../maker-host/session-context-budget-store.js';
import { assertRendererSessionSourceAllowed } from './sessionSourceGuard.js';
import type { SessionReference } from '../../../shared/sessionReference.js';
import * as broadcastTap from '../../device-link/broadcast-tap.js';
@@ -182,6 +192,18 @@ export interface RegisterSessionIpcOpts {
resolveContextWindow?: (session: ContextWindowSession) => number | null;
/** Close a local Pi/Codex runtime only if its current turn is idle. */
closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
+ /**
+ * 任务级上下文窗口预算(tokens)变化后,把新值应用到**活着的**运行实例上
+ * (空闲关 handle 冷重建;回合中登记 pending,回合结束后生效)。
+ *
+ * 调用时机:本函数已把新值写进 DB(本函数是唯一写入链路)。回调失败只记录、
+ * 不阻断设置保存 —— 新值仍会在下一次启动/恢复时通过 start options 生效。
+ * 入参 previous/next 是用户显式值(null = 跟随模型默认),由 host 换算有效窗口。
+ */
+ applyContextWindowBudget?: (
+ sessionId: string,
+ change: { previous: number | null; next: number | null },
+ ) => Promise<void>;
}
let sessionWorktreeRecycle: SessionWorktreeRecycle | null = null;
@@ -695,6 +717,9 @@ const REMOTE_PERSIST_FIELDS = new Set([
'planModeEnabled',
'extraDirs',
'writableDirs',
+ // 任务级窗口预算:device-link 控制端改档位后,被控端需落库并广播,否则控制端
+ // 会拿旧值回滚自己的乐观 UI。
+ 'contextWindowBudget',
]);
/**
@@ -857,13 +882,42 @@ export async function persistSessionFields(
if (persistableEffort === undefined) delete clean.effort;
else clean.effort = persistableEffort;
}
+ if (Object.prototype.hasOwnProperty.call(clean, 'contextWindowBudget')) {
+ // 镜像回流(被控端 → 本机)的值可能是旧版 peer / 手改偏好文件留下的越界值:
+ // store 的 clamp 会把越界值静默收敛(等于把本机预算改掉且没人知道),
+ // 这里显式归一化并留痕;非法值**跳过该字段**,不写偏好也不触发应用钩子。
+ const normalized = normalizeContextWindowBudget(clean.contextWindowBudget);
+ if (normalized === null && clean.contextWindowBudget !== null) {
+ console.warn('[sessions] dropping invalid mirrored context window budget', {
+ sessionId,
+ value: clean.contextWindowBudget,
+ });
+ delete clean.contextWindowBudget;
+ } else {
+ clean.contextWindowBudget = normalized;
+ }
+ }
if (Object.keys(clean).length === 0) return;
const db = getDbClient().drizzle;
- const setObj = sessionPatchToRow(clean as Parameters<typeof sessionPatchToRow>[0], {
+ // 任务窗口预算不是会话列(见 session-context-budget-store 头注),单独走偏好文件;
+ // 其余字段照旧走行更新。
+ const hasBudgetChange = clean.contextWindowBudget !== undefined;
+ const previousContextWindowBudget: number | null = hasBudgetChange
+ ? readSessionContextWindowBudget(sessionId)
+ : null;
+ const nextContextWindowBudget: number | null = hasBudgetChange
+ ? writeSessionContextWindowBudget(sessionId, (clean.contextWindowBudget as number | null) ?? null)
+ : null;
+ const rowPatch = { ...clean };
+ delete rowPatch.contextWindowBudget;
+ const setObj = sessionPatchToRow(rowPatch as Parameters<typeof sessionPatchToRow>[0], {
bumpUpdatedAt: false,
});
- if (Object.keys(setObj).length === 0) return;
- await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));
+ if (Object.keys(setObj).length > 0) {
+ await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));
+ } else if (!hasBudgetChange) {
+ return;
+ }
let runtimeProjection = {};
if (['model', 'providerId', 'effort', 'fastMode'].some((key) => key in clean)) {
const [row] = await db.select({
@@ -876,6 +930,20 @@ export async function persistSessionFields(
}
}
if (isOwnerScopeCurrent(ownerScope)) broadcastSessionPatched(sessionId, { ...clean, ...runtimeProjection }, ownerScope);
+ // 远程 set-* 落库后同样要把新预算应用到被控端活实例(语义与 updateSessionInDb 一致)。
+ if (hasBudgetChange && registeredSessionIpcOpts.applyContextWindowBudget) {
+ try {
+ await registeredSessionIpcOpts.applyContextWindowBudget(sessionId, {
+ previous: previousContextWindowBudget,
+ next: nextContextWindowBudget,
+ });
+ } catch (error) {
+ console.warn('[sessions] remote context window budget apply failed; takes effect on next start', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
}
const MAX_LIMIT = 1000;
@@ -2083,6 +2151,21 @@ export async function updateSessionInDb(
) {
throwIpcError('INVALID_PARAMS', `invalid orcaRole: ${String(p.orcaRole)}`);
}
+ // 任务窗口预算:非法值不能静默 converge(normalize 会把 <1000 变成 null = 静默清预算、
+ // 把超大值静默夹到上限),而调用方收到的是成功回包。隧道入口与本地入口必须同口径拒绝。
+ if (
+ p.contextWindowBudget !== undefined &&
+ p.contextWindowBudget !== null &&
+ (typeof p.contextWindowBudget !== 'number' ||
+ !Number.isInteger(p.contextWindowBudget) ||
+ p.contextWindowBudget < MIN_CONTEXT_WINDOW_BUDGET ||
+ p.contextWindowBudget > MAX_CONTEXT_WINDOW_BUDGET)
+ ) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `contextWindowBudget must be null or an integer within [${MIN_CONTEXT_WINDOW_BUDGET}, ${MAX_CONTEXT_WINDOW_BUDGET}]`,
+ );
+ }
if (typeof p.workingDir === 'string') {
p.workingDir = normalizeWorkingDirForStorage(p.workingDir) ?? null;
}
@@ -2091,6 +2174,7 @@ export async function updateSessionInDb(
'workspaceKind',
'model',
'providerId',
+ 'contextWindowBudget',
'effort',
'permissionMode',
'fastMode',
@@ -2200,6 +2284,7 @@ export async function updateSessionInDb(
'fastMode',
'planModeEnabled',
'providerId',
+ 'contextWindowBudget',
'orcaRole',
'extraDirs',
'writableDirs',
@@ -2209,7 +2294,11 @@ export async function updateSessionInDb(
'title',
]);
const isSettingsOnly = Object.keys(p).every((k) => SETTINGS_ONLY_FIELDS.has(k));
- const setObj = sessionPatchToRow(p as Parameters<typeof sessionPatchToRow>[0], {
+ // 任务窗口预算不进入行更新(偏好文件才是它的真源)——从行 patch 里剔除,
+ // 否则 mapper 会把未知字段当成非法写入。
+ const rowPatch = { ...p };
+ delete rowPatch.contextWindowBudget;
+ const setObj = sessionPatchToRow(rowPatch as Parameters<typeof sessionPatchToRow>[0], {
bumpUpdatedAt: !isSettingsOnly,
});
if (p.clearedAt !== undefined) {
@@ -2252,6 +2341,13 @@ export async function updateSessionInDb(
// 先记号后写库,代价只是写库失败时该会话本进程内不再自动起名 —— 用户毕竟确实
// 按下过保存,这个方向的偏差是安全的。
if (typeof p.title === 'string') noteUserTitleWritten(sid);
+ // 窗口预算不是会话列(见 session-context-budget-store 头注):旧值从偏好文件读,
+ // 下面的应用回调靠它判断「有效窗口是否真的变了」(已重新展开为同一值时不必关掉活实例)。
+ // 写入放在 UPDATE 之后(与广播同一顺序),保证 UI 先看到新选择。
+ const hasContextWindowBudgetChange = p.contextWindowBudget !== undefined;
+ const previousContextWindowBudget: number | null = hasContextWindowBudgetChange
+ ? readSessionContextWindowBudget(sid)
+ : null;
let deletedSideChats: SessionsSetTerminalStatusResult['deletedSideChats'] | undefined;
await withStatusWriteLock(
db,
@@ -2394,6 +2490,25 @@ export async function updateSessionInDb(
});
scheduleWorktreeRecycleForStatusChange(sid, p.status, { ownerScope, mediaDb: db });
notifyGhostSessionStatusChange(sid, p.status, updated.workingDir);
+ // 广播之后再把新预算应用到活实例:UI 先看到新选择,重建/延迟登记失败也不回滚设置。
+ // 只有本函数会写这份偏好,不存在平行写入链路;回调缺失(宿主未注入)时静默跳过,
+ // 新值在下次启动/恢复时按 start options 生效。
+ if (hasContextWindowBudgetChange) {
+ const nextContextWindowBudget = writeSessionContextWindowBudget(sid, p.contextWindowBudget ?? null);
+ if (opts.applyContextWindowBudget) {
+ try {
+ await opts.applyContextWindowBudget(sid, {
+ previous: previousContextWindowBudget,
+ next: nextContextWindowBudget,
+ });
+ } catch (error) {
+ console.warn('[sessions] apply context window budget failed; takes effect on next start', {
+ sessionId: sid,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
cleanupSessionTerminalArtifacts(sid, p.status);
compactTerminalSessionToolResults(dbClient, sid, p.status);
if (p.status === 'deleted' && updated.source !== 'side-chat') await deleteDependentSideChats(sid, dbClient, ownerScope, deletedSideChats);
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelContextSettings.sessionBudget.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelContextSettings.sessionBudget.test.ts
new file mode 100644
index 0000000000..51a35f4f1a
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/modelContextSettings.sessionBudget.test.ts
@@ -0,0 +1,353 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { Catalog } from '@cindy/model-providers';
+
+let mockModelLimit: number | null = null;
+
+vi.mock('../model-context-limit-store.js', () => ({
+ readModelContextLimit: () => mockModelLimit,
+ readModelContextLimits: () => ({}),
+ writeModelContextLimit: vi.fn(),
+ isModelContextLimitCustomized: () => mockModelLimit !== null,
+}));
+// 预算文件必须落临时目录:这些用例会真写预算,绝不能碰真实 userData。
+const budgetState = vi.hoisted(() => ({ dir: '' }));
+vi.mock('../../appSessionState.js', async () => {
+ const nodePath = await import('node:path');
+ return {
+ ownerScopedUserDataPath: (...parts: string[]): string => nodePath.join(budgetState.dir, ...parts),
+ // 预算 store 的 owner 隔离读它;测试里固定成同一个 key 即可。
+ activeOwnerScopeKey: (): string => 'test-owner',
+ getActiveAppSession: () => ({ dataOwnerId: 'test-owner', generation: 1 }),
+ dataOwnerStorageKey: (ownerId: string): string => ownerId,
+ };
+});
+
+vi.mock('../catalog-to-descriptors.js', async () => {
+ const shared = await import('../../../shared/sessionContextWindow.js');
+ return {
+ resolveModelContextProviderId: () => 'xd',
+ resolveVerifiedContextWindow: shared.resolveVerifiedContextWindow,
+ };
+});
+
+import { resolveConfiguredContextWindow, contextWindowBudgetChangesEffectiveWindow, resolveDesktopModelContextProviderId, resolveSessionContextWindowBounds, applySessionContextWindowBudgetToCreateOpts } from '../model-context-settings';
+import { writeSessionContextWindowBudget } from '../session-context-budget-store';
+
+/** 目录里 1M 物理上限、默认工作窗口 200K 的路由(服务端压低过默认值)。 */
+const catalog: Pick<Catalog, 'providers'> = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'long-window-model',
+ name: 'Long Window Model',
+ contextWindow: 200_000,
+ contextWindowMax: 1_000_000,
+ contextWindowVerified: true,
+ },
+ ],
+ },
+ },
+ ],
+} as unknown as Pick<Catalog, 'providers'>;
+
+/** 自定义连接未声明窗口的真实形态:未核实 + 只有兜底默认 contextWindow。 */
+const undeclaredCatalog: Pick<Catalog, 'providers'> = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'undeclared-model',
+ name: 'Undeclared Model',
+ contextWindow: 200_000,
+ contextWindowVerified: false,
+ },
+ ],
+ },
+ },
+ ],
+} as unknown as Pick<Catalog, 'providers'>;
+
+function resolve(sessionBudget?: number | null): number | null {
+ return resolveConfiguredContextWindow(
+ catalog,
+ 'claude-code',
+ 'xd',
+ 'long-window-model',
+ sessionBudget,
+ );
+}
+
+beforeEach(() => {
+ mockModelLimit = null;
+ if (!budgetState.dir) {
+ budgetState.dir = mkdtempSync(path.join(os.tmpdir(), 'ctx-budget-opts-'));
+ }
+});
+
+describe('resolveConfiguredContextWindow with a session budget', () => {
+ it('follows the catalog default when nothing is customized', () => {
+ expect(resolve()).toBe(200_000);
+ expect(resolve(null)).toBe(200_000);
+ });
+
+ it('lets the task budget tighten below the catalog default', () => {
+ expect(resolve(100_000)).toBe(100_000);
+ });
+
+ it('lets the task budget raise the working window up to the catalog max', () => {
+ expect(resolve(1_000_000)).toBe(1_000_000);
+ expect(resolve(750_000)).toBe(750_000);
+ });
+
+ it('never lets the task budget exceed the catalog physical max', () => {
+ expect(resolve(4_000_000)).toBe(1_000_000);
+ });
+
+ it('keeps the tighter model-level cap when it is below the task budget', () => {
+ mockModelLimit = 300_000;
+ expect(resolve(1_000_000)).toBe(300_000);
+ // 任务预算仍可在这条上限内继续收紧。
+ expect(resolve(150_000)).toBe(150_000);
+ });
+
+ it('falls back to the model-level cap when the task follows the default', () => {
+ mockModelLimit = 300_000;
+ expect(resolve(null)).toBe(300_000);
+ });
+});
+
+/** 发现流程只拿到 max_context_window 的真实形态:未核实 + 声明了物理上限。 */
+const unverifiedCatalog: Pick<Catalog, 'providers'> = {
+ providers: [
+ {
+ id: 'xd',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'discovered-model',
+ name: 'Discovered Model',
+ contextWindow: 100_000,
+ contextWindowMax: 400_000,
+ contextWindowVerified: false,
+ },
+ ],
+ },
+ },
+ ],
+} as unknown as Pick<Catalog, 'providers'>;
+
+describe('resolveConfiguredContextWindow on an unverified route', () => {
+ it('still clamps the session budget by the declared physical max', () => {
+ // 未核实路由没有 verified 收敛,但不能因此让任务预算越过目录声明的上限。
+ expect(
+ resolveConfiguredContextWindow(unverifiedCatalog, 'claude-code', 'xd', 'discovered-model', 10_000_000),
+ ).toBe(400_000);
+ });
+
+ it('keeps a session budget below the declared max untouched', () => {
+ expect(
+ resolveConfiguredContextWindow(unverifiedCatalog, 'claude-code', 'xd', 'discovered-model', 200_000),
+ ).toBe(200_000);
+ });
+
+ it('preserves the model-level cap as the explicit escape hatch', () => {
+ // 模型级上限刻意不夹目录上限:路由把窗口配错时用户要能强行解开(见 store 头注)。
+ mockModelLimit = 1_000_000;
+ expect(
+ resolveConfiguredContextWindow(unverifiedCatalog, 'claude-code', 'xd', 'discovered-model', null),
+ ).toBe(1_000_000);
+ });
+});
+
+describe('contextWindowBudgetChangesEffectiveWindow', () => {
+ const changes = (previous: number | null, next: number | null): boolean =>
+ contextWindowBudgetChangesEffectiveWindow({
+ catalog, agent: 'claude-code', providerId: 'xd', modelId: 'long-window-model', previous, next,
+ });
+
+ it('reports a change when the task tightens or raises the window', () => {
+ expect(changes(null, 100_000)).toBe(true);
+ expect(changes(100_000, 750_000)).toBe(true);
+ });
+
+ it('reports no change when the effective window is unchanged', () => {
+ expect(changes(null, null)).toBe(false);
+ // 选回目录默认值(= 清除预算)与「本来就是默认」等价。
+ expect(changes(null, 200_000)).toBe(false);
+ expect(changes(200_000, null)).toBe(false);
+ });
+
+ it('reports no change when a tighter model-level cap absorbs both values', () => {
+ mockModelLimit = 300_000;
+ expect(changes(500_000, 1_000_000)).toBe(false);
+ expect(changes(500_000, 250_000)).toBe(true);
+ });
+});
+
+describe('resolveSessionContextWindowBounds', () => {
+ it('returns the route bounds the controlled device would apply', () => {
+ mockModelLimit = 800_000;
+ expect(
+ resolveSessionContextWindowBounds({
+ catalog, agent: 'claude-code', providerId: 'xd', modelId: 'long-window-model',
+ }),
+ ).toEqual({
+ providerId: 'xd',
+ defaultWindow: 200_000,
+ maxWindow: 1_000_000,
+ modelLimit: 800_000,
+ budget: null,
+ budgetCustomized: false,
+ // 默认档(清掉任务预算)= min(模型级上限 800K, 物理上限 1M);已核实路由由 main 夹一次。
+ defaultEffectiveWindow: 800_000,
+ // 物理上限 = contextWindowMax(1M)。
+ maxEffectiveWindow: 1_000_000,
+ effectiveWindowsReported: true,
+ });
+ });
+
+ it('carries the task budget when the caller supplies one', () => {
+ // 任务档位与边界同源返回(偏好文件里的条目):调用方不给时默认「未自定义」。
+ expect(
+ resolveSessionContextWindowBounds({
+ catalog, agent: 'claude-code', providerId: 'xd', modelId: 'long-window-model',
+ budget: 262_144, budgetCustomized: true,
+ }),
+ ).toEqual({
+ providerId: 'xd',
+ defaultWindow: 200_000,
+ maxWindow: 1_000_000,
+ modelLimit: null,
+ budget: 262_144,
+ budgetCustomized: true,
+ // 默认档刻意不带这条预算:它是「勾选模型默认(写 null)之后」的运行窗口。
+ defaultEffectiveWindow: 200_000,
+ maxEffectiveWindow: 1_000_000,
+ effectiveWindowsReported: true,
+ });
+ });
+
+ it('resolves the implicit route source the same way the runtime does', () => {
+ // 控制端解析不了的跨 provider 同 id,被控端能解析:它按运行期同一套「隐式来源」口径选中
+ // 真正生效的那条路由,而不是退回扁平表猜。
+ const ambiguous: Pick<Catalog, 'providers'> = {
+ providers: [
+ ...catalog.providers,
+ {
+ id: 'xd-mirror',
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ { id: 'long-window-model', name: 'Mirror', contextWindow: 400_000, contextWindowVerified: true },
+ ],
+ },
+ },
+ ],
+ } as unknown as Pick<Catalog, 'providers'>;
+ const bounds = resolveSessionContextWindowBounds({
+ catalog: ambiguous, agent: 'claude-code', providerId: null, modelId: 'long-window-model',
+ });
+ expect(bounds.providerId).toBe(
+ resolveDesktopModelContextProviderId(ambiguous, 'claude-code', null, 'long-window-model'),
+ );
+ expect(bounds.defaultWindow).toBe(200_000);
+ expect(bounds.maxWindow).toBe(1_000_000);
+ });
+
+ it('reports unknown bounds for a model that is not in the catalog at all', () => {
+ // 目录里没有这个 id:来源会解析成默认网关(隐式路由),但路由窗口解不出 →
+ // 两个窗口值都为 null,调用方(控制端)据此退回「只允许收紧」。
+ const bounds = resolveSessionContextWindowBounds({
+ catalog, agent: 'claude-code', providerId: null, modelId: 'not-in-catalog',
+ });
+ expect(bounds.defaultWindow).toBeNull();
+ expect(bounds.maxWindow).toBeNull();
+ expect(bounds.modelLimit).toBeNull();
+ });
+
+ it('does not pass an unverified fallback context window off as a physical max', () => {
+ // 用户实测报障(2026-09-22):自定义连接未声明窗口 → 目录 contextWindow 只是 200K 兜底,
+ // 用户把模型级上限设成 1M。此时 main 的生效默认窗口就是 1M(未核实路由刻意不按目录夹),
+ // 若把 200K 当 maxWindow 下发,chip 的档位基准会被钉在 200K,「模型默认 1M」显示成 500%。
+ mockModelLimit = 1_000_000;
+ const bounds = resolveSessionContextWindowBounds({
+ catalog: undeclaredCatalog, agent: 'claude-code', providerId: 'xd', modelId: 'undeclared-model',
+ });
+ expect(bounds).toEqual({
+ providerId: 'xd',
+ // 兜底默认仍在(它是「跟随默认」在没有模型级上限时的运行窗口)。
+ defaultWindow: 200_000,
+ // 但它不是上限:未核实 + 未声明 → null(声明了 max_contextWindow 才算数)。
+ maxWindow: null,
+ modelLimit: 1_000_000,
+ budget: null,
+ budgetCustomized: false,
+ defaultEffectiveWindow: 1_000_000,
+ // 未核实路由没有「物理上限」这道夹(预算就是工作上限)。
+ maxEffectiveWindow: null,
+ effectiveWindowsReported: true,
+ });
+ });
+});
+
+describe('applySessionContextWindowBudgetToCreateOpts', () => {
+ afterEach(() => {
+ if (budgetState.dir) {
+ rmSync(budgetState.dir, { recursive: true, force: true });
+ budgetState.dir = '';
+ }
+ });
+
+ const optsFor = (over: Record<string, unknown> = {}) => ({
+ agentKind: 'claude-code' as const,
+ providerId: 'xd',
+ model: 'long-window-model',
+ ...over,
+ }) as {
+ contextWindowBudget?: number | null;
+ agentKind: 'claude-code';
+ providerId?: string | null;
+ model?: string | null;
+ };
+
+ it('读已存档位并按目录上限收敛后写进创建参数', async () => {
+ // worker 唤醒 / 进程重启后的恢复路径靠这一步把预算带回引擎:缺了它,Pi 的
+ // compaction.reserveTokens 会写成无预算值、阈值退回满窗(2026-09-30 实测)。
+ writeSessionContextWindowBudget('sess-1', 500_000);
+ const opts = optsFor();
+ await applySessionContextWindowBudgetToCreateOpts('sess-1', opts, catalog);
+ expect(opts.contextWindowBudget).toBe(500_000);
+ });
+
+ it('调用方显式带值时按同一口径收敛(压到目录物理上限内)', async () => {
+ const opts = optsFor({ contextWindowBudget: 4_000_000 });
+ await applySessionContextWindowBudgetToCreateOpts('sess-1', opts, catalog);
+ expect(opts.contextWindowBudget).toBe(1_000_000);
+ });
+
+ it('未自定义时不留字段(引擎回退默认,旧行为零变化)', async () => {
+ const opts = optsFor();
+ await applySessionContextWindowBudgetToCreateOpts('sess-never-set', opts, catalog);
+ expect('contextWindowBudget' in opts).toBe(false);
+ });
+
+ it('路由未定型(无 model)时不透传未收敛的值', async () => {
+ writeSessionContextWindowBudget('sess-2', 500_000);
+ const opts = optsFor({ model: undefined });
+ await applySessionContextWindowBudgetToCreateOpts('sess-2', opts, catalog);
+ expect('contextWindowBudget' in opts).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/sessionContextBudgetStore.test.ts b/apps/desktop/src/main/maker-host/__tests__/sessionContextBudgetStore.test.ts
new file mode 100644
index 0000000000..455c47914b
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/sessionContextBudgetStore.test.ts
@@ -0,0 +1,104 @@
+import { existsSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ dir: '' }));
+vi.mock('../../appSessionState.js', async () => {
+ const nodePath = await import('node:path');
+ return {
+ ownerScopedUserDataPath: (...parts: string[]): string => nodePath.join(state.dir, ...parts),
+ };
+});
+
+const {
+ copySessionContextWindowBudget,
+ isSessionContextWindowBudgetCustomized,
+ pruneSessionContextWindowBudget,
+ readSessionContextWindowBudget,
+ writeSessionContextWindowBudget,
+} = await import('../session-context-budget-store.js');
+
+const FILE = 'session-context-budget-prefs.json';
+
+function prefsFile(): string {
+ return path.join(state.dir, FILE);
+}
+
+function writePrefs(raw: unknown): void {
+ writeFileSync(prefsFile(), typeof raw === 'string' ? raw : JSON.stringify(raw), 'utf8');
+}
+
+describe('session-context-budget-store', () => {
+ beforeEach(() => {
+ state.dir = mkdtempSync(path.join(os.tmpdir(), 'cindy-session-budget-'));
+ });
+
+ afterEach(() => {
+ rmSync(state.dir, { recursive: true, force: true });
+ });
+
+ it('follows the model default until a task explicitly saves a budget', () => {
+ expect(readSessionContextWindowBudget('s1')).toBeNull();
+ expect(isSessionContextWindowBudgetCustomized('s1')).toBe(false);
+ expect(existsSync(prefsFile())).toBe(false);
+
+ expect(writeSessionContextWindowBudget('s1', 262_144)).toBe(262_144);
+ expect(readSessionContextWindowBudget('s1')).toBe(262_144);
+ expect(isSessionContextWindowBudgetCustomized('s1')).toBe(true);
+ expect(JSON.parse(readFileSync(prefsFile(), 'utf8'))).toEqual({ budgets: { s1: 262_144 } });
+ });
+
+ it('restores the default by deleting the entry instead of snapshotting it', () => {
+ writeSessionContextWindowBudget('s1', 262_144);
+ writeSessionContextWindowBudget('s2', 500_000);
+
+ expect(writeSessionContextWindowBudget('s1', null)).toBeNull();
+ expect(readSessionContextWindowBudget('s1')).toBeNull();
+ expect(readSessionContextWindowBudget('s2')).toBe(500_000);
+ // 「恢复默认」= 删条目:目录把默认窗口调大后,没自定义过的任务直接吃到新默认。
+ expect(JSON.parse(readFileSync(prefsFile(), 'utf8'))).toEqual({ budgets: { s2: 500_000 } });
+ });
+
+ it('rejects a budget below the usable floor instead of silently clearing it', () => {
+ expect(() => writeSessionContextWindowBudget('s1', 999)).toThrow(/invalid context window budget/);
+ expect(() => writeSessionContextWindowBudget('s1', Number.NaN)).toThrow(/invalid context window budget/);
+ expect(readSessionContextWindowBudget('s1')).toBeNull();
+ });
+
+ it('ignores garbage in a hand-edited file instead of propagating it', () => {
+ writePrefs({ budgets: { good: 250_000, zero: 0, text: 'x', nan: null } });
+ expect(readSessionContextWindowBudget('good')).toBe(250_000);
+ expect(readSessionContextWindowBudget('zero')).toBeNull();
+ expect(readSessionContextWindowBudget('text')).toBeNull();
+ expect(readSessionContextWindowBudget('nan')).toBeNull();
+
+ writePrefs('not json at all');
+ expect(readSessionContextWindowBudget('good')).toBeNull();
+ });
+
+ it('lets an externally edited file take effect on the next read', () => {
+ // 与另一个偏好 store(单模型上下文上限)同源:缓存以 mtime + 大小判定失效。
+ // 同毫秒内等长改写是二者的已知盲区;真正的跨进程编辑会换 mtime。
+ writeSessionContextWindowBudget('s1', 250_000);
+ writePrefs({ budgets: { s1: 900_000 } });
+ const future = new Date(Date.now() + 2_000);
+ utimesSync(prefsFile(), future, future);
+ expect(readSessionContextWindowBudget('s1')).toBe(900_000);
+ });
+
+ it('copies the entry to a forked task and prunes it when the task is gone', () => {
+ writeSessionContextWindowBudget('parent', 300_000);
+ expect(copySessionContextWindowBudget('parent', 'child')).toBe(300_000);
+ expect(readSessionContextWindowBudget('child')).toBe(300_000);
+ // 源未自定义时不动目标(新任务跟随默认,而不是复制一个默认值快照)。
+ expect(copySessionContextWindowBudget('untouched', 'child2')).toBeNull();
+ expect(readSessionContextWindowBudget('child2')).toBeNull();
+
+ expect(pruneSessionContextWindowBudget('parent')).toBe(true);
+ expect(pruneSessionContextWindowBudget('parent')).toBe(false);
+ expect(readSessionContextWindowBudget('parent')).toBeNull();
+ expect(readSessionContextWindowBudget('child')).toBe(300_000);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 4b95f8e009..03d58e0e79 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -203,7 +203,7 @@ import {
resolveModelDefaultContextWindow,
} from './catalog-to-descriptors.js';
import { readModelContextLimit } from './model-context-limit-store.js';
-import { resolveDesktopModelContextProviderId, resolveDesktopModelEfforts } from './model-context-settings.js';
+import { resolveDesktopModelContextProviderId, resolveDesktopModelEfforts, readStoredSessionContextWindowBudget, resolveConfiguredContextWindow, applySessionContextWindowBudgetToCreateOpts } from './model-context-settings.js';
import {
prepareCodexCustomContextCatalog,
prepareCodexGuestModelCatalog,
@@ -2957,6 +2957,13 @@ export function getMaker(): Maker {
opts.fastModePolicy = createSubscriptionFastPolicy(sessionId, () => getSessionProvider(sessionId)
?? resolveDesktopModelContextProviderId(getDesktopSelectableCatalog(), opts.agentKind, null, opts.model));
}
+ // 任务级工作上下文预算:调用方显式带值时同样按目录上限与模型级上限重新收敛;
+ // 未带则读本任务已保存的档位。口径见 applySessionContextWindowBudgetToCreateOpts
+ // (worker 唤醒等其它启动入口也走它,避免只在钩子这条路上生效)。
+ await applySessionContextWindowBudgetToCreateOpts(
+ sessionId, opts as Parameters<typeof applySessionContextWindowBudgetToCreateOpts>[1],
+ getActiveCatalog(),
+ );
await preparePersistedOrcaSessionStart(sessionId, opts as MakerSessionCreateOpts);
if (opts.agentKind === 'pi' && opts.thinkingEnabled === undefined) {
const thinkingEnabled = getThinkingEnabledFromMemory(
diff --git a/apps/desktop/src/main/maker-host/model-context-settings.ts b/apps/desktop/src/main/maker-host/model-context-settings.ts
index 32d2a0d433..0f885f7550 100644
--- a/apps/desktop/src/main/maker-host/model-context-settings.ts
+++ b/apps/desktop/src/main/maker-host/model-context-settings.ts
@@ -1,10 +1,15 @@
import { isCodexGatewayWireModel, type AgentKind, type Catalog, type Effort } from '@cindy/model-providers';
+import { desktopMakerLogger } from './logger-adapter.js';
+import { readSessionContextWindowBudget } from './session-context-budget-store.js';
+import { normalizeContextWindowBudget } from '../../shared/sessionContextWindowBudget.js';
import { desktopCodexAuthAdapter, readClaudeApiKey } from './auth-adapters.js';
import { hasClaudeNativeLogin } from './claude-native-auth.js';
import { gatewayDefaultRouteDecision } from './provider-route.js';
import { resolveModelContextProviderId, resolveVerifiedContextWindow } from './catalog-to-descriptors.js';
import { readModelContextLimit } from './model-context-limit-store.js';
+import { resolveRouteContextWindowBounds } from '../../shared/sessionContextWindow.js';
+import type { SessionContextWindowBounds } from '../../shared/sessionContextWindowBounds.js';
/** Shared settings identity for startup, refresh and history protection of implicit routes. */
export function resolveDesktopModelContextProviderId(
@@ -28,6 +33,151 @@ export function resolveDesktopModelContextProviderId(
return resolveModelContextProviderId(catalog, agent, providerId, modelId, defaultSource);
}
+/** 取两个可选上限中更紧的那个(都缺省时返回 null = 跟随目录默认)。 */
+function tighterBudget(
+ sessionBudget: number | null | undefined,
+ modelLimit: number | null,
+): number | null {
+ const session = typeof sessionBudget === 'number' && Number.isFinite(sessionBudget) && sessionBudget > 0
+ ? Math.round(sessionBudget) : null;
+ if (session === null) return modelLimit;
+ if (modelLimit === null) return session;
+ // 任务级预算可以比路由默认更省、也可以在上限内提高,但不得越过用户对这条路由
+ // 设过的显式上限(那是一个更强的「别再多了」意图;两者冲突时取更紧者,
+ // UI 用 buildContextWindowBudgetOptions 把上界体现在可选档位里)。
+ return Math.min(session, modelLimit);
+}
+
+/** 该任务已保存的**原始**预算值(tokens);null = 未自定义。切模/校验需要按目标路由重新收敛时用它。 */
+export async function readStoredSessionContextWindowBudget(sessionId: string): Promise<number | null> {
+ try {
+ return readSessionContextWindowBudget(sessionId);
+ } catch (error) {
+ desktopMakerLogger.warn('stored session context window budget read failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+}
+
+/**
+ * 把「本任务的工作上下文预算」写进会话创建参数(`opts.contextWindowBudget`)。
+ *
+ * 口径唯一:调用方(远程 / IM / 定时任务)显式带值时同样按目录物理上限与模型级上限
+ * 重新收敛;未带则读本任务已保存的档位。按「未自定义」处理时不留下该字段,引擎回退
+ * 到模型级上限 / 目录默认(旧行为零变化);收敛不出值时**删掉**字段而不是透传未收敛的
+ * 数字(引擎侧按「已收敛」信任,部分引擎甚至不做 >0 校验)。
+ *
+ * 为什么抽出来:会话启动有多个入口(createSession 的 prepareStartOptions 钩子、worker
+ * 唤醒时的 resumeOrcaWorkerSessionIfMissing、goal 恢复…)。曾经只有钩子那一条注入预算,
+ * worker 唤醒路径自己拼 opts 且不带预算 —— 预算就在「引擎进程重启」时静默丢失:档位卡仍
+ * 显示 50%(宿主投影照算),而 Pi 的压缩阈值退回满窗(compaction.reserveTokens 写成无预算
+ * 值),于是任务在预算窗口内跑到 100% 以上也不自动压缩(实测 reserveTokens=50000 ⇒
+ * 阈值 950K,而预算窗口只有 500K)。每条入口都必须过这里,口径不许分叉。
+ */
+export async function applySessionContextWindowBudgetToCreateOpts(
+ sessionId: string,
+ opts: {
+ contextWindowBudget?: number | null;
+ agentKind: AgentKind;
+ providerId?: string | null;
+ model?: string | null;
+ },
+ catalog: Pick<Catalog, 'providers'>,
+): Promise<void> {
+ const explicitBudget = normalizeContextWindowBudget(opts.contextWindowBudget);
+ const requestedBudget = explicitBudget ?? await readStoredSessionContextWindowBudget(sessionId);
+ if (requestedBudget === null) {
+ delete opts.contextWindowBudget;
+ return;
+ }
+ // 未定型路由(无 model)时不做收敛:宁可不带预算(引擎回退默认),也不把
+ // 未收敛的值透传给引擎。
+ if (typeof opts.model !== 'string' || opts.model.length === 0) {
+ delete opts.contextWindowBudget;
+ return;
+ }
+ const resolvedBudget = resolveConfiguredContextWindow(
+ catalog, opts.agentKind, opts.providerId ?? null, opts.model, requestedBudget,
+ );
+ if (resolvedBudget !== null) opts.contextWindowBudget = resolvedBudget;
+ else delete opts.contextWindowBudget;
+}
+
+/**
+ * 预算变化是否真的改变**有效窗口**:不变时不必关掉活实例(模型级上限更紧、或重新选回
+ * 当前档位造成的假变化都会落在 false)。收敛口径与运行时下发完全一致,否则会出现
+ * 「判为无变化»不重建」但实际上引擎报文窗口不同的分叉。
+ */
+export function contextWindowBudgetChangesEffectiveWindow(input: {
+ catalog: Pick<Catalog, 'providers'>;
+ agent: AgentKind;
+ providerId: string | null | undefined;
+ modelId: string;
+ previous: number | null;
+ next: number | null;
+}): boolean {
+ const before = resolveConfiguredContextWindow(
+ input.catalog, input.agent, input.providerId, input.modelId, input.previous,
+ );
+ const after = resolveConfiguredContextWindow(
+ input.catalog, input.agent, input.providerId, input.modelId, input.next,
+ );
+ return before !== after;
+}
+
+/**
+ * 会话级窗口边界:路由默认、路由物理上限、该路由的模型级上限。
+ *
+ * 与运行期收敛**同源**(同一批事实:目录路由唯一候选 + 该路由的模型级上限),
+ * device-link 只读查询把它交给控制端,控制端才可能在远程任务上给出「更大」的档位。
+ * 解不出路由时三个值都为 null(调用方必须退回「只允许收紧」,不要用扁平表猜)。
+ */
+export function resolveSessionContextWindowBounds(input: {
+ catalog: Pick<Catalog, 'providers'>;
+ agent: AgentKind;
+ providerId: string | null | undefined;
+ modelId: string;
+ /**
+ * 该任务已保存的预算(偏好文件里的**原始**用户值)与「是否显式设过」。
+ * 缺省 = 跟随默认:不带会话上下文的调用方(如纯路由探测)不必关心它。
+ */
+ budget?: number | null;
+ budgetCustomized?: boolean;
+}): SessionContextWindowBounds {
+ const source = resolveDesktopModelContextProviderId(
+ input.catalog, input.agent, input.providerId, input.modelId,
+ );
+ const bounds = resolveRouteContextWindowBounds(input.catalog, input.agent, source, input.modelId);
+ const modelLimit = source ? readModelContextLimit(input.agent, source, input.modelId) : null;
+ const budget = typeof input.budget === 'number' && Number.isFinite(input.budget) && input.budget > 0
+ ? Math.round(input.budget) : null;
+ return {
+ providerId: source,
+ defaultWindow: bounds?.defaultWindow ?? null,
+ maxWindow: bounds?.maxWindow ?? null,
+ // 「清掉任务预算后跟随默认会得到多少」由主进程按同一套 resolveConfiguredContextWindow 算好
+ // 下发(传 null 预算);调用方不必(也不该)自己重推。刻意不带当前预算:档位表里的「模型默认」
+ // 档选中后会写 null,运行期回到的正是这个值。
+ defaultEffectiveWindow: resolveConfiguredContextWindow(
+ input.catalog, input.agent, source, input.modelId, null,
+ ),
+ // main 会施加的物理上限。用同一支 resolveVerifiedContextWindow 传一个极大的预算取回它的
+ // `contextWindowMax ?? contextWindow`(不为任何值做第二套推导);路由不唯一/未核实 → null。
+ maxEffectiveWindow: resolveVerifiedContextWindow(
+ input.catalog, input.agent, source, input.modelId, Number.MAX_SAFE_INTEGER,
+ ),
+ // 本进程就是这两个字段的权威来源:显式申报,调用方据此区分「未核实 → 无这道夹」与
+ // 「老被控端根本没申报 → 必须退回只允许收紧」。
+ effectiveWindowsReported: true,
+ modelLimit: typeof modelLimit === 'number' && Number.isFinite(modelLimit) && modelLimit > 0
+ ? modelLimit : null,
+ budget,
+ budgetCustomized: input.budgetCustomized === true,
+ };
+}
+
/**
* Efforts declared by the route this session actually uses. Same-ID models from different
* providers can declare different efforts; null means the route is unknown or ambiguous.
@@ -50,15 +200,33 @@ export function resolveConfiguredContextWindow(
agent: AgentKind,
providerId: string | null | undefined,
modelId: string,
+ sessionBudget?: number | null,
): number | null {
const source = resolveDesktopModelContextProviderId(catalog, agent, providerId, modelId);
- const budget = source ? readModelContextLimit(agent, source, modelId) : null;
+ const modelLimit = source ? readModelContextLimit(agent, source, modelId) : null;
+ const rows = catalog.providers
+ .filter(provider => provider.id === source && provider.routing[agent]?.disabled !== true)
+ .flatMap(provider => (provider.models[agent] ?? []).filter(model => model.id === modelId));
+ const declaredMax = rows.length === 1
+ && typeof rows[0]!.contextWindowMax === 'number'
+ && Number.isFinite(rows[0]!.contextWindowMax)
+ && rows[0]!.contextWindowMax > 0
+ ? Math.round(rows[0]!.contextWindowMax)
+ : null;
+ // 任务预算是用户可写的设置,对外承诺「不越过目录声明的物理上限」:即使路由**未核实**
+ // (contextWindowVerified !== true)也要夹一次 —— 未核实但声明了 max_context_window
+ // 的目录形态真实存在(发现流程只拿到 max 时就是 verified=false + contextWindowMax 有值)。
+ // 模型级上限刻意不夹:它同时是「路由把窗口配错时用户强行解开」的逃生口
+ // (见 model-context-limit-store 头注),两者作用域不同。
+ const requested = typeof sessionBudget === 'number' && Number.isFinite(sessionBudget) && sessionBudget > 0
+ ? Math.round(sessionBudget) : null;
+ const clampedByCatalog = requested !== null && declaredMax !== null
+ ? Math.min(requested, declaredMax) : requested;
+ const budget = tighterBudget(clampedByCatalog, modelLimit);
const verified = resolveVerifiedContextWindow(catalog, agent, source, modelId, budget);
if (verified !== null) return verified;
// A saved budget configures the native runtime even if catalog capacity is
// unknown. It is a working ceiling, not evidence of physical model capacity.
- const rows = catalog.providers.filter(provider => provider.id === source && provider.routing[agent]?.disabled !== true)
- .flatMap(provider => (provider.models[agent] ?? []).filter(model => model.id === modelId));
return rows.length === 1 && rows[0]!.contextWindowVerified !== true && typeof budget === 'number' && Number.isFinite(budget) && budget > 0
? budget : null;
}
diff --git a/apps/desktop/src/main/maker-host/session-context-budget-store.ts b/apps/desktop/src/main/maker-host/session-context-budget-store.ts
new file mode 100644
index 0000000000..184f9a0d37
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/session-context-budget-store.ts
@@ -0,0 +1,163 @@
+/**
+ * session-context-budget-store —— 「任务级工作上下文预算」的持久化(main 侧唯一真源)。
+ *
+ * File: <owner-scoped userData>/session-context-budget-prefs.json
+ * 形态: { budgets: { "<sessionId>": 262144 } }
+ *
+ * ## 这个设置解决什么
+ *
+ * 自动压缩的触发是「已用 token / 上下文窗口 ≥ 阈值百分比」。`model-context-limit-store`
+ * 已经让用户能给**单个模型**设分母上限;本 store 把同一个分母收到**单个任务**上:
+ * 分档计费的路由可以选更便宜的价带,不分档的路由可以直接省 token。
+ *
+ * ## 为什么不落库(sessions 表加列)
+ *
+ * 与 `model-context-limit-store` / `compaction-settings-store` 同一条理由:这是**用户偏好**,
+ * 不是会话事实。它不参与任何查询、不需要索引、不需要与消息表同事务;而加列要走迁移链 ——
+ * 迁移一旦写进 `migration_history` 与运行时 manifest 身份,**用旧包(或官方包)打开同一个库
+ * 就会因身份不符 fail closed**。偏好文件没有这个代价:不认识它的宿主照常打开库,只是不生效。
+ *
+ * ## 为什么不放 renderer localStorage
+ *
+ * 同 `model-context-limit-store`:它参与**运行期判定**(启动/切模时收敛下发窗口),判定发生在
+ * main,renderer 窗口可能根本不存在(MCP / IM / 定时任务起的会话)。
+ *
+ * ## 语义
+ *
+ * - 只存用户显式设过的条目;缺席 = 跟随模型默认(等价于 `contextWindowBudget = null`)。
+ * - 「恢复默认」= 删除条目(不是写一份当前默认的快照),所以目录把窗口调整后,没自定义过的
+ * 任务直接吃新默认;`isSessionContextWindowBudgetCustomized()` 让 UI 能区分这两种状态。
+ * - 存的是**用户请求值**,不是收敛后的有效窗口:有效窗口在运行期按目标路由重新收敛
+ * (`resolveConfiguredContextWindow`),这样跨模型/跨来源的 fork 与切模都不会残留越界值。
+ */
+
+import { desktopMakerLogger } from './logger-adapter.js';
+import { createOverrideSettingsFile } from './override-settings-file.js';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+
+const log = desktopMakerLogger.child('session-context-budget');
+
+/** 与 model-context-limit 同口径:低于此值的预算等于让任务不可用 —— 视为误输入。 */
+const MIN_BUDGET_TOKENS = 1_000;
+/** 只挡量级荒谬的误输入;真正的上界由运行期按目录上限与模型级上限收敛。 */
+const MAX_BUDGET_TOKENS = 100_000_000;
+/**
+ * 条目总量硬上限(深防线)。任务数会随使用增长,正常路径有 IPC 边界校验与删除路径的清理,
+ * 这里兜的是「绕过 IPC 直改文件 / 未来新增写入口漏校验」,防止这份同步读写的 JSON
+ * 无界膨胀拖死 main。超限时按遍历序丢弃(= 跟随默认,无副作用)。
+ */
+const MAX_ENTRIES = 16_384;
+
+export interface SessionContextBudgetPrefs {
+ budgets: Record<string, number>;
+}
+
+const DEFAULTS: SessionContextBudgetPrefs = { budgets: {} };
+
+function clampBudget(value: unknown): number | null {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;
+ const rounded = Math.round(value);
+ if (rounded < MIN_BUDGET_TOKENS) return null;
+ return Math.min(MAX_BUDGET_TOKENS, rounded);
+}
+
+/** 只收「非空 sessionId + 可 clamp 成合法 token 数」的条目;其它形态一律丢弃 = 跟随默认。 */
+function sanitizeBudgets(raw: unknown): Record<string, number> {
+ const out: Record<string, number> = {};
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
+ let kept = 0;
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (!key) continue;
+ const budget = clampBudget(value);
+ if (budget === null) continue;
+ if (kept >= MAX_ENTRIES) {
+ log.warn('session context budget prefs truncated at hard cap on read', { cap: MAX_ENTRIES });
+ break;
+ }
+ out[key] = budget;
+ kept += 1;
+ }
+ }
+ return out;
+}
+
+function normalize(raw: unknown): SessionContextBudgetPrefs {
+ if (!raw || typeof raw !== 'object') return { budgets: {} };
+ return { budgets: sanitizeBudgets((raw as { budgets?: unknown }).budgets) };
+}
+
+const createStore = (filePath: () => string) => createOverrideSettingsFile<SessionContextBudgetPrefs>({
+ filePath,
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'session-context-budget',
+ maxBytes: 1_048_576,
+ preserveUnreadableFile: true,
+});
+
+const store = createStore(() => ownerScopedUserDataPath('session-context-budget-prefs.json'));
+
+function readPrefs(): SessionContextBudgetPrefs {
+ // 与 model-context-limit 一致:mtime 守卫让「直接手改文件」在下一次读取生效。
+ store.invalidateIfChanged();
+ return store.read();
+}
+
+/** 某个任务保存的原始预算(tokens);未自定义返回 null。 */
+export function readSessionContextWindowBudget(sessionId: string): number | null {
+ if (!sessionId) return null;
+ return readPrefs().budgets[sessionId] ?? null;
+}
+
+/** UI 用:这一条是否被用户显式设过(区分「跟随默认」与「设了一个刚好等于默认的值」)。 */
+export function isSessionContextWindowBudgetCustomized(sessionId: string): boolean {
+ if (!sessionId) return false;
+ return sessionId in readPrefs().budgets;
+}
+
+/**
+ * 写一个任务的预算。`tokens === null` = 恢复默认(删除条目),与「恢复默认 = 删 override」一致。
+ * 返回落盘后的有效值(null = 已跟随默认)。
+ */
+export function writeSessionContextWindowBudget(sessionId: string, tokens: number | null): number | null {
+ if (!sessionId) throw new Error('invalid session id');
+ const next = tokens === null ? null : clampBudget(tokens);
+ if (tokens !== null && next === null) throw new Error('invalid context window budget');
+ store.invalidateIfChanged();
+ const budgets = { ...store.read().budgets };
+ if (next === null) delete budgets[sessionId];
+ else budgets[sessionId] = next;
+ if (Object.keys(budgets).length > MAX_ENTRIES) throw new Error('session context budget capacity exceeded');
+ store.writePatch({ budgets });
+ return next;
+}
+
+/**
+ * 任务被硬删除后清掉它的条目(软删除保留行,条目仍会随 restore 复用,故不清理)。
+ * 返回是否真的删掉了一条。
+ */
+export function pruneSessionContextWindowBudget(sessionId: string): boolean {
+ if (!sessionId) return false;
+ store.invalidateIfChanged();
+ const budgets = store.read().budgets;
+ if (!(sessionId in budgets)) return false;
+ const next = { ...budgets };
+ delete next[sessionId];
+ store.writePatch({ budgets: next });
+ return true;
+}
+
+/**
+ * fork 继承:把源任务的条目复制给新任务(源未自定义时不动新任务)。
+ * 继承的是**用户请求值**,启动/切模时仍按目标路由重新收敛,所以跨模型 fork 不会
+ * 残留超出目标上限的值。
+ */
+export function copySessionContextWindowBudget(
+ sourceSessionId: string,
+ targetSessionId: string,
+): number | null {
+ const budget = readSessionContextWindowBudget(sourceSessionId);
+ if (budget === null) return null;
+ return writeSessionContextWindowBudget(targetSessionId, budget);
+}
diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.ts
index a8122d2d8f..22b1aab82e 100644
--- a/apps/desktop/src/main/maker-host/session-storage.ts
+++ b/apps/desktop/src/main/maker-host/session-storage.ts
@@ -13,6 +13,7 @@
import { and, eq, inArray, ne } from 'drizzle-orm';
import { dbToMakerAgentKind, makerToDbAgentKind } from '../../shared/agentKindConversion.js';
+import { pruneSessionContextWindowBudget } from './session-context-budget-store.js';
import type {
AgentKind,
@@ -157,6 +158,15 @@ export class DesktopSessionStorage implements SessionStorage {
async delete(id: string): Promise<void> {
const db = getDbClient().drizzle;
await db.delete(sessions).where(eq(sessions.id, id));
+ // 任务行已消失,偏好文件里的档位条目也就没有意义了(软删除保留行,故不在这里清理)。
+ try {
+ pruneSessionContextWindowBudget(id);
+ } catch (error) {
+ console.warn('[session-storage] pruning context window budget failed', {
+ sessionId: id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
}
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts
index 407fb463c3..3162eb04c9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts
@@ -84,6 +84,9 @@ it.each(['catalog', 'harness-read', 'native-preview', 'valid-harness', 'valid-mo
isSessionInTurn: () => false, registerPendingCredentialSwitchForSession: vi.fn(),
clearPendingCredentialSwitchForSession: vi.fn(), getPendingCredentialSwitchTarget: () => null,
getCodexProxyAuthInjectionState: () => null, log: { debug: vi.fn(), info: vi.fn() },
+ // 任务级窗口预算:切片里的重建判定会读它。这里 = 本用例的场景(无预算),
+ // 两项窗口都未知 → 条件短路,与本文件其余注入同一约定。
+ sessionContextWindowBudget: null, targetContextWindow: undefined, budgetCompareWindow: undefined,
};
const result = await new Function(...Object.keys(mutationDeps), mutation)(...Object.values(mutationDeps));
return { deferred: result.status === 'deferred', generation: 1 };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerResumeCleanup.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerResumeCleanup.test.ts
index d4e1be8aaa..f03a79238c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerResumeCleanup.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerResumeCleanup.test.ts
@@ -76,6 +76,11 @@ describe('resumeOrcaWorkerSessionIfMissing runtime cleanup', () => {
permissionModeOrAsk: (value: unknown) => value,
directoryGrantsForRuntime: () => ({}),
ensureRemoteReadyForSessionStart: async () => undefined,
+ // 本 PR 在 worker 唤醒路径补了任务级窗口预算注入(register.ts 的
+ // applySessionContextWindowBudgetToCreateOpts);切片执行时它作为自由变量
+ // 出现,必须注入,否则 ReferenceError 盖住被测的失败出口语义。
+ getActiveCatalog: () => undefined,
+ applySessionContextWindowBudgetToCreateOpts: async () => undefined,
bootstrapSession,
markOrcaRoleIfNeeded,
log: { info: vi.fn(), warn: vi.fn() },
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 a98b61ddf6..ca7cbe5742 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
@@ -1355,6 +1355,46 @@ describe('applyRuntimeSetModelChange', () => {
},
);
+ it('passes the target budget to the Pi preview, same as the setModel call', async () => {
+ // 预演决定要不要重建,而 switchModel 会先把预算写成新值再预演。外层预演拿旧预算
+ // 就会判「可热切」,内层按新预算发现保留量不匹配便抛错 —— 首次发送必失败。
+ const sessionId = rememberSession('runtime-set-model-pi-preview-budget');
+ setSessionProvider(sessionId, 'xai');
+ const previewModelSwitch = vi.fn(async () => ({ action: 'hot' as const,
+ targetContextWindow: 1_000_000, windowVerified: true }));
+ const setModel = vi.fn(async () => {});
+ const maker: RuntimeSetModelMaker = {
+ getSession: () => ({
+ agentKind: 'pi',
+ remoteHostId: null,
+ model: 'grok-4.6',
+ setModel,
+ previewModelSwitch,
+ }),
+ listActiveSessions: () => [
+ { id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },
+ ],
+ closeSession: vi.fn(async () => {}),
+ };
+
+ await applyRuntimeSetModelChange({
+ maker,
+ sessionId,
+ model: 'grok-4.5',
+ providerId: 'xai',
+ contextWindowBudget: 500_000,
+ });
+
+ expect(previewModelSwitch).toHaveBeenCalledWith('grok-4.5', {
+ providerId: 'xai',
+ contextWindowBudget: 500_000,
+ });
+ expect(setModel).toHaveBeenCalledWith('grok-4.5', {
+ providerId: 'xai',
+ contextWindowBudget: 500_000,
+ });
+ });
+
it('hot-switches idle Pi inside the same proxy identity without closing', async () => {
const sessionId = rememberSession('runtime-set-model-pi-same-xai');
setSessionProvider(sessionId, 'xai');
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 0bceae2495..93eabbdfcd 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -238,6 +238,22 @@ export const MAKER_INVOKE = {
SET_THINKING_ENABLED: 'maker:set-thinking-enabled',
/** 计划模式一级开关(与 permissionMode 正交), runtime-only; 持久化由 renderer sessions:update / device-link 回流负责 */
SET_PLAN_MODE: 'maker:set-plan-mode',
+ /**
+ * 任务级工作上下文窗口档位(tokens;null = 跟随模型默认)。
+ *
+ * 被控端落库并应用到活实例(空闲关 handle 冷重建 / 回合中登记 pending)。
+ * 与 SET_PLAN_MODE 同类:会话级设置、无本机 shell/UI 副作用。控制端用
+ * `deviceLink.invoke(deviceId, …)` 调;老被控端无此 channel →
+ * CHANNEL_NOT_ALLOWED → 控制端提示「该设备版本不支持」。
+ */
+ SET_CONTEXT_WINDOW_BUDGET: 'maker:set-context-window-budget',
+ /**
+ * 会话级窗口边界的**只读**查询(路由默认 / 路由物理上限 / 该路由的模型级上限)。
+ * 控制端在远程任务上打开档位菜单时按需拉取:只有被控端本地目录 + 本地上限 store 才知道
+ * 该路由能放到多大,控制端据此才敢提供「更大」的档位。老被控端无此 channel →
+ * CHANNEL_NOT_ALLOWED → 控制端退回「只允许收紧」并如实说明。
+ */
+ GET_CONTEXT_WINDOW_BOUNDS: 'maker:get-context-window-bounds',
/** 会话导出 HTML(pi 原生 export_html)。主进程弹保存对话框 + 导出 + 在文件管理器中显示;返回写入路径或 null(取消)。 */
EXPORT_SESSION_HTML: 'maker:export-session-html',
/** 手动压缩会话上下文(pi 原生 compact,可带聚焦指令)。返回 {tokensBefore?, estimatedTokensAfter?} 或 null(会话不在/不支持)。 */
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bf88cb1401..d43fa7f700 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -149,8 +149,10 @@ import { readCodexContextWindowInfo } from '../maker-host/codex-context-window.j
import { readSshCodexModelList, assertSshCodexModel, isVerifiedSshCodexResume } from '../remote-ssh/codex-model-list.js';
import { prepareCodexCustomContextCatalog } from '../maker-host/codex-custom-context-catalog.js';
import { inferProviderIdForModel } from '../maker-host/provider-route.js';
-import { resolveConfiguredContextWindow, resolveDesktopModelContextProviderId } from '../maker-host/model-context-settings.js';
import { bindGroupFastPolicy } from '../provider-group/fastPolicyRuntime.js';
+import { resolveConfiguredContextWindow, contextWindowBudgetChangesEffectiveWindow, resolveDesktopModelContextProviderId, resolveSessionContextWindowBounds, readStoredSessionContextWindowBudget, applySessionContextWindowBudgetToCreateOpts } from '../maker-host/model-context-settings.js';
+import { isSessionContextWindowBudgetCustomized, readSessionContextWindowBudget } from '../maker-host/session-context-budget-store.js';
+import { MAX_CONTEXT_WINDOW_BUDGET, MIN_CONTEXT_WINDOW_BUDGET } from '../../shared/sessionContextWindowBudget.js';
import { getCodexHome } from '../maker-host/auth-adapters.js';
import { getCachedBinaryStatus } from '../agent-binaries/index.js';
import { AsyncLocalStorage } from 'node:async_hooks';
@@ -861,6 +863,7 @@ import {
runPiPackageMutationIpcBoundary,
} from './piPackageMutationIpc.js';
import { dbToMakerAgentKind, makerToDbAgentKind } from '../../shared/agentKindConversion.js';
+import { normalizeSessionContextWindowBoundsRoute } from '../../shared/sessionContextWindowBounds.js';
import { readWorkflowProgressForSession } from '../workflow-progress/reader.js';
import { readSessionBackgroundTaskOutputTail } from '../background-task-output/reader.js';
import { AgentInputCoordinator } from './agent-input-coordinator.js';
@@ -1283,6 +1286,7 @@ import {
closeRejectedRuntimeAndRestoreControlStores,
isRemoteModelSwitchRouteChangeError,
} from './runtimeSetModel.js';
+import { updateSessionInDb } from '../localDb/ipc/sessions.js';
import { codexThreadTransferSourcePredicate, commitCodexThreadTransfer, relinkCodexProviderThread } from './codexProviderThreadRelink.js';
import {
codexCustomProviderConfigSignature,
@@ -4102,6 +4106,13 @@ function unpricedSubscriptionValueMarker(): RegionalMoney {
* (日/会话总额不受影响,PR #485 review)。turn start 清残留,防错配到下一轮。
*/
const pendingFailedTurnAssistantPersistId = new Map<string, string>();
+/**
+ * 已按某个预算值重建过活实例的会话:并发通知(双窗口/连点)会带着**同一个终值**进来,
+ * 没有这层去重就会对同一值连续冷重建两次。会话关闭(含删除/归档/取消切换)时清理 ——
+ * 否则条目常驻内存,且「关掉期间改了预算、重开后再改回旧值」会被旧条目挡掉一次。
+ * 模块级而非闭包内:会话关闭的清理在 registerMakerIpc 之外。
+ */
+const appliedContextWindowBudgets = new Map<string, number | null>();
/**
* 跟踪每个 session 的逻辑 turn 与后台节流 keepalive。外部 running guard
@@ -4372,6 +4383,24 @@ async function syncLibraryReadonlyExtraDir(
let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;
let contextOverflowRolloverHolder: ReturnType<typeof createContextOverflowRollover> | null = null;
+
+/**
+ * 任务级窗口预算落库后的运行时应用入口(由 localDb 层的 sessions:update 钩子调用)。
+ *
+ * 与 `refreshActiveModelContextSettings` 同一套语义:空闲立即关 handle、下一次发消息
+ * 冷重建;回合中登记 pending,回合结束后生效。maker 未就绪 / 无活实例 / 有效窗口未变
+ * 时 no-op —— 预算已落库,下一次启动或恢复同样会按新值启动。
+ */
+let sessionContextWindowBudgetApplier:
+ | ((sessionId: string, change: { previous: number | null; next: number | null }) => Promise<void>)
+ | null = null;
+
+export async function applySessionContextWindowBudgetChange(
+ sessionId: string,
+ change: { previous: number | null; next: number | null },
+): Promise<void> {
+ await sessionContextWindowBudgetApplier?.(sessionId, change);
+}
const overflowSuppressedBroadcasts = new Map<
string,
{ sessionId: string; event: AgentEvent; persistId?: string; resolvedContent?: unknown }
@@ -5980,6 +6009,7 @@ function cleanupClosedSessionRuntime(session: WiredSession): void {
gitSnapshotCoordinator?.onSessionClosed(session.id);
clearOrcaMcpHydrated(session.id);
knownNonOrcaSessionIds.delete(session.id);
+ appliedContextWindowBudgets.delete(session.id);
lastReportedCostUsdBySession.delete(session.id);
lastReportedModelUsageBySession.delete(session.id);
turnModelPromiseBySession.delete(session.id);
@@ -6398,6 +6428,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
// Catalog updates and explicit budget edits share one serial refresh boundary.
let contextRefresh = Promise.resolve();
+ /**
+ * 运行时路由/窗口变更的共享依赖:切模重建、目录刷新、任务级预算应用三条路径共用,
+ * codexAuthInjection 每次调用重读(凭证形态可能在两次调用之间变化)。
+ */
+ /**
+ * 该任务是否已有「尚未兑现的运行时选择」(跨引擎切换意图 / 显式路由变更 / 凭证切换)。
+ * 预算应用与目录刷新共用:待定目标的重建会自己读最新设置,别人不得以旧目标抢先登记。
+ */
+ const hasPendingRuntimeSelection = (sessionId: string): boolean => {
+ const pending = getPendingSessionRuntimeMutation(sessionId);
+ return !!agentSwitchPending.get(sessionId) ||
+ !!getPendingCredentialSwitchTarget(sessionId) ||
+ (!!pending && isPendingSessionRuntimeRouteExplicit(sessionId, pending.generation));
+ };
+ const runtimeMutationDeps = () => ({
+ maker, isSessionInTurn,
+ registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,
+ clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,
+ wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,
+ getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
+ codexAuthInjection: getCodexProxyAuthInjectionState(), logger: log,
+ });
let applyPiModelSettingsRefresh: (sessionId: string, model: string, providerId: string | null) => Promise<void> =
async () => { throw new Error('Pi model settings refresh is not ready'); };
let applyPiPendingSelection: NonNullable<PendingCredentialSwitchDeps['applyPiPending']> =
@@ -6419,6 +6471,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
targets, inferProviderId: (model, agent) => resolveDesktopModelContextProviderId(getActiveCatalog(), agent, null, model),
withSessionLock: withSendToSessionLock,
applyPiRefresh: applyPiModelSettingsRefresh,
+ // 上游口径:Pi 的待定切换已由 applyPiPending 单独处理,这里只管 agentSwitch 与
+ // 显式运行时变更;预算应用走 runtimeMutationDeps()(含凭证 pending 判定)。
hasPendingSelection: (sessionId) => {
const pending = getPendingSessionRuntimeMutation(sessionId);
return !!agentSwitchPending.get(sessionId) ||
@@ -6427,18 +6481,95 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertCurrent: () => {
if (getActiveAppSession().generation !== owner.generation) throw new Error('Account changed during context configuration');
},
- runtime: {
- maker, isSessionInTurn,
- registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,
- clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,
- wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,
- getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
- codexAuthInjection: getCodexProxyAuthInjectionState(), logger: log,
- },
+ runtime: runtimeMutationDeps(),
}));
contextRefresh = next.catch(() => {});
return next;
};
+ sessionContextWindowBudgetApplier = async (sessionId, change) => {
+ const activeMaker = getMakerIfReady();
+ if (!activeMaker || !activeMaker.getSession(sessionId)) return;
+ await withSendToSessionLock(sessionId, async () => {
+ const live = getMakerIfReady()?.getSession(sessionId);
+ if (!live) {
+ appliedContextWindowBudgets.delete(sessionId);
+ return;
+ }
+ // 会话行(路由快照)必须在**锁内**重读:锁外读到的是「加锁前」的路由,若期间用户切了模,
+ // 有效窗口判定会按旧路由算成「没变」而漏掉一次必需的重建(第 1 轮的洞在这条窄路径的复发)。
+ const [row] = await getDbClient()
+ .drizzle.select({
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!row?.model) return;
+ const agent = dbToMakerAgentKind(row.agentKind);
+ const providerId = getSessionProvider(sessionId) ?? row.providerId;
+ const catalog = getActiveCatalog();
+ // 并发改档位(双窗口、连点)时两条通知会乱序到达:以**当下 DB 里的值**为 `next`,
+ // 让 live 与落库终值对齐(否则后执行的旧通知会把活实例重建回旧窗口)。
+ const latestBudget = await readStoredSessionContextWindowBudget(sessionId);
+ // 同一终值已在锁内处理过一次(两次通知读到同一个最新值)→ 不再重复重建。
+ if (appliedContextWindowBudgets.has(sessionId)
+ && appliedContextWindowBudgets.get(sessionId) === latestBudget) {
+ log.debug('session context window budget already applied', {
+ sessionId, budget: latestBudget,
+ });
+ return;
+ }
+ // 有效窗口(预算与模型级上限取更紧者)没变就不重建:避免每次改档位都关活实例。
+ if (!contextWindowBudgetChangesEffectiveWindow({
+ catalog, agent, providerId, modelId: row.model,
+ previous: change.previous, next: latestBudget,
+ })) {
+ log.debug('session context window budget does not change the effective window', {
+ sessionId, previous: change.previous, next: latestBudget,
+ });
+ return;
+ }
+ // 待定选择是**更晚的意图**,而 pending 是整体替换:读-改-写必须在同一把锁里,
+ // 否则会在 await 窗口把用户期间新选的模型/引擎冲掉(SET_MODEL 持锁登记,我们必须在锁内对齐)。
+ const pendingTarget = getPendingCredentialSwitchTarget(sessionId);
+ if (pendingTarget) {
+ // 已登记的凭证 pending(目标模型就是用户选的 B):**原样保留其 model/provider**,
+ // 只补 forceSessionRebuild;跨引擎意图在另一套 store,不在这里动。
+ // 绝不能以「当前 live 路由」重登记 —— 那会把用户的模型选择冲掉且不报错。
+ // 这里**不**记 dedup:真正的重建发生在收口时,pending 被取消/超车的话什么都没做,
+ // 记了就会把后续同值通知全部挡掉,活实例永久停在旧窗口。
+ await registerPendingCredentialSwitchForSession(sessionId, {
+ ...pendingTarget,
+ forceSessionRebuild: true,
+ });
+ log.info('session context window budget merged into the pending route switch', {
+ sessionId, previous: change.previous,
+ next: latestBudget, targetModel: pendingTarget.model,
+ });
+ return;
+ }
+ // 无凭证 pending 时(含仅轴 pending / runtime-control 显式路由 pending / 跨引擎切换):
+ // 以**当前 live 路由**补一个 forceSessionRebuild。取舍说明:这几套意图各自存在别的 store,
+ // 这里不会覆盖它们,但确实会多登记一条「当前引擎」的凭证 pending —— 它与跨引擎意图在同一个
+ // 收口边界先后生效,最坏是多一次关会话/重建(写入的路由就等于 live 路由,不会复活旧路由);
+ // 换来的是「跨引擎切换被取消时预算仍会生效」这个更强保证(第 3 轮 review 的反向要求)。
+ // 少登记一条会反过来丢掉那个保证,所以这里选择保留登记。
+ await applyRuntimeSetModelChange({
+ ...runtimeMutationDeps(),
+ sessionId,
+ model: live.model,
+ providerId: getSessionProvider(sessionId),
+ forceSessionRebuild: true,
+ });
+ appliedContextWindowBudgets.set(sessionId, latestBudget);
+ log.info('session context window budget applied via runtime rebuild', {
+ sessionId, previous: change.previous, next: latestBudget,
+ });
+ });
+ };
+
setModelContextRuntimeRefreshListener(() => {
if (!getMakerIfReady()) return;
void refreshContextSettings().catch((error) => log.warn('model default context refresh failed', {
@@ -9216,6 +9347,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
await assertCurrent?.();
await ensureRemoteReadyForSessionStart({ createOpts: opts });
+ // 任务级窗口预算:worker 唤醒这条路径自己拼 opts,不经过 createSession 的
+ // prepareStartOptions 预算注入。缺这一步,预算会在「引擎进程重启」时静默丢失:
+ // 档位卡仍按 50% 显示(宿主投影照算),而 Pi 的压缩阈值退回满窗,任务在预算
+ // 窗口内跑到 100% 以上也不自动压缩(2026-09-30 实测:reserveTokens 写成无预算值)。
+ // 与钩子同一份收敛口径(resolveConfiguredContextWindow),不许分叉。
+ await applySessionContextWindowBudgetToCreateOpts(target.sessionId, opts, getActiveCatalog());
await assertCurrent?.();
if (isCancelled?.()) return false;
const { session: resumedSession } = await bootstrapSession(opts);
@@ -10600,6 +10737,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionRuntimeGenerationMatches(sessionId, expectedGeneration);
cancelPendingAgentSwitchHolder = (sessionId) => {
agentSwitchPending.clear(sessionId);
+ appliedContextWindowBudgets.delete(sessionId);
broadcastSessionPatched(sessionId, {
agentSwitchIntent: null,
agentSwitchIntentCanceled: true,
@@ -22568,6 +22706,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
let runtimeRouteChanged =
currentRuntimeModel !== undefined &&
(currentRuntimeModel !== model || currentProviderId !== targetRouteProviderId);
+ // 任务级窗口预算(用户显式值,null = 跟随默认):切模/校验统一按目标路由
+ // 重新收敛(min(预算, 目标路由模型级上限, 目录物理上限)),否则预算会被目录
+ // 默认值顶掉或被目标窗口校验抹平。**必须在任何 Pi 分支之前读**:冷 Pi 预检拿
+ // 「目标窗口对已知占用有余量」当跳过冷启动核实的依据,而运行期真正会应用的
+ // 是含预算的窗口;用不带预算的目录默认大窗去比,占用再高也显得有余量,缩窗
+ // 交接 / 二次确认就被整条绕过(Greptile P1,2026-09-22)。上游新增的
+ // piConfigurationRefresh 预演路径同样共用这个值。
+ const sessionContextWindowBudget = await readStoredSessionContextWindowBudget(sessionId);
const piConfigurationRefresh = runtimeAgentKind === 'pi' && internalOptions.refreshPiConfiguration === true;
const piPreview = runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh) && liveSessionBeforeRouteChange
? await liveSessionBeforeRouteChange.previewModelSwitch?.(model, {
@@ -22610,10 +22756,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 后可能低报真实占用,拿它证明「目标还有余量」会绕过缩窗交接
// (Greptile P1,2026-09-21);进程重启 / 硬杀后没有缓存时自动回退到核实。
// 无原生会话的冷 Pi 也不在本预检范围内(维持既有 fail-closed 语义)。
+ // 目标窗口与后面的 resolveWindowForRoute 同源(都带任务预算),否则
+ // 「有余量」是对默认大窗说的,实际生效的小预算窗早已进 danger/overflow。
const coldPiLastLiveUsage = getSessionLastLiveUsage(sessionId);
const coldPiTargetContextWindow = lookupVerifiedContextWindow(
(_agentKind, modelId, pid) =>
- resolveConfiguredContextWindow(getActiveCatalog(), 'pi', pid, modelId),
+ resolveConfiguredContextWindow(
+ getActiveCatalog(), 'pi', pid, modelId, sessionContextWindowBudget,
+ ),
model,
targetRouteProviderId,
'pi',
@@ -22633,6 +22783,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: coldPiLastLiveUsage?.contextWindow ?? null,
capturedAtMs: coldPiLastLiveUsage?.capturedAtMs ?? null,
targetContextWindow: coldPiTargetContextWindow,
+ sessionContextWindowBudget,
fromModel: currentRuntimeModel ?? null,
toModel: model,
currentProviderId,
@@ -22692,13 +22843,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
let targetContextWindow: number | undefined;
let verifiedCurrentWindow: number | undefined;
+ /** 目录侧(已按当前路由 + 预算收敛)的当前窗口;Pi 未上报 live 窗口时拿它做比较基准。 */
+ let budgetCompareWindow: number | undefined;
let modelWindowContextNeedsProtection = false;
let modelWindowRebuilt = false;
+ const resolveWindowForRoute = (
+ agentKind: AgentKind,
+ routeModelId: string,
+ pid: string | null,
+ ): number | null => resolveConfiguredContextWindow(
+ getActiveCatalog(), agentKind, pid, routeModelId, sessionContextWindowBudget,
+ );
if (runtimeAgentKind && (runtimeRouteChanged || piConfigurationRefresh || confirmedContextWindow !== undefined)) {
const resolveRouteWindow = (_agentKind: string, modelId: string, pid: string | null) =>
+ // SSH Codex 路由用上游新增的 SSH provider 快照解析(那边保持上游语义、不跟任务预算走);
+ // 其余路由与冷 Pi 预检共用 resolveWindowForRoute —— 含任务预算的同一支收敛。
sshCodexProviders
? resolveVerifiedContextWindow({ providers: sshCodexProviders }, runtimeAgentKind, pid ?? 'openai', modelId)
- : resolveConfiguredContextWindow(getActiveCatalog(), runtimeAgentKind, pid, modelId);
+ : resolveWindowForRoute(runtimeAgentKind, modelId, pid);
const catalogTargetWindow = lookupVerifiedContextWindow(
resolveRouteWindow,
model,
@@ -22729,6 +22891,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
? liveCurrentWindow
: undefined
: catalogCurrentWindow;
+ // 切模必须重建的**比较基准**:优先取被验证的当前窗口,其次取「运行时上报/目录收敛出的
+ // 有效窗口」,再退到「同一收敛函数解出的当前路由窗口」(与建 live env 用的是同一个
+ // resolveWindowForRoute,因此未核实但声明了 max 的路由也解得出)。
+ // 三者都不可知时**不**强制重建(fail-safe):否那么 undefined 恒不等会把无辜的同窗切模
+ // 也变成一次破坏性重建;预算本身的应用走 applier 通道,不依赖这里的判定。
+ const resolvedCurrentWindow = currentRuntimeModel
+ ? resolveWindowForRoute(runtimeAgentKind, currentRuntimeModel, currentProviderId ?? null)
+ : null;
+ // 「目标窗口相对当前窗口是否变窄」用**含预算**的同一支收敛来比(resolveRouteWindow
+ // 已按目标路由 + 任务预算解析)。预算比目录默认更小时,缩窗交接/二次确认必须
+ // 按预算后的真实目标窗判定;用不带预算的目录默认去比会漏掉一次必要的重建
+ // (Greptile P1 的同族口径)。
+ budgetCompareWindow = verifiedCurrentWindow
+ ?? (typeof resolvedCurrentWindow === 'number' && Number.isFinite(resolvedCurrentWindow)
+ && resolvedCurrentWindow > 0
+ ? resolvedCurrentWindow
+ : undefined);
const targetDoesNotShrink =
typeof verifiedCurrentWindow === 'number' &&
typeof verifiedTargetWindow === 'number' &&
@@ -23130,7 +23309,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: {}),
forceSessionRebuild:
rebuildLiveOrcaWorker ||
- (atomicSelection?.effort === null && runtimeAgentKind !== 'pi'),
+ (atomicSelection?.effort === null && runtimeAgentKind !== 'pi') ||
+ // 任务级预算:目标路由的**收敛后**窗口与当前不同就必须重建。
+ // 引擎侧的 requiresModelSwitchRebuild 在预算模式下对任意目标模型都返回
+ // 「预算 == live env」(它只知道当前预算),探测不到这次失配;
+ // 若不在这里拦截,热切后 CC 子进程 env 仍停在旧窗口(如预算 300K 切到
+ // 200K 上限的模型),压缩线会越过目标窗口。
+ // Pi 的 live 窗口只信运行时上报;未上报时依次用「运行时/目录收敛出的有效窗口」
+ // 与「当前路由的收敛值」做比较基准;三者都不可知时按 fail-closed 处理(无法证明
+ // 「当前窗口 == 目标窗口」就重建)—— 否则第 1 轮的洞(CC env 停在过大窗口、
+ // 压缩线越过目标窗口)会在这条窄路径上复发;误重建的代价只是一次冷重建。
+ // **Pi 例外**(Greptile P1,2026-10-17):Pi 的预算生效方式不同 —— 走
+ // compaction.reserveTokens(热切时 set_compaction_reserve_tokens 实时改 + 切后
+ // 重载 fail-closed),引擎自己的 requiresModelSwitchRebuild(window 比较)已会把
+ // 需要的重建标出来。预算变化时 Pi 的重建需求由引擎分支自己报。
+ // 注意:不要在这里给 Pi 注入 assertSessionCloseSupported 之类的「无条件拒绝
+ // 重建」预判 —— 上游已把 Pi 运行时退役判定交回 apply/gate(retiredRuntime),
+ // 宿主侧预判会把「跨来源切模」在远程发送边界直接打死(0.1.111 实测死锁)。
+ (runtimeAgentKind !== 'pi' &&
+ sessionContextWindowBudget !== null &&
+ targetContextWindow !== undefined &&
+ targetContextWindow !== budgetCompareWindow),
+ // 任务级预算:路由变了且已有显式预算时,把按**目标路由**重新收敛后的
+ // 窗口随热切下发给引擎(否则引擎会继续沿用旧模型的收敛值)。
+ ...(sessionContextWindowBudget !== null && targetContextWindow !== undefined
+ ? { contextWindowBudget: targetContextWindow }
+ : {}),
isSessionInTurn,
registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,
clearPendingCredentialSwitch: internalOptions.applyingPiCredentialPending
@@ -23191,9 +23395,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
// Pi reports the configured native budget, which may exceed the route
// ceiling. Final verification must not undo the history safety cap.
- const verifiedPiWindow = resolveConfiguredContextWindow(
- getActiveCatalog(), 'pi', targetRouteProviderId, model,
- );
+ const verifiedPiWindow = resolveWindowForRoute('pi', model, targetRouteProviderId);
const finalPiWindow = verifiedPiWindow === null
? reportedPiWindow : Math.min(reportedPiWindow, verifiedPiWindow);
targetContextWindow = finalPiWindow;
@@ -23466,12 +23668,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
dbToMakerAgentKind(getSessionDbAgentKind(sessionId));
const verifiedWindow = lookupVerifiedContextWindow(
(agentKind, modelId, pid) =>
- resolveConfiguredContextWindow(
- getActiveCatalog(),
- dbToMakerAgentKind(agentKind),
- pid,
- modelId,
- ),
+ resolveWindowForRoute(dbToMakerAgentKind(agentKind), modelId, pid),
model,
targetRouteProviderId,
currentAgentKind,
@@ -23879,6 +24076,87 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
});
+ ipcMain.handle(
+ MAKER_INVOKE.SET_CONTEXT_WINDOW_BUDGET,
+ async (event, sessionId: unknown, budget: unknown) => {
+ // 会话变更型 IPC 统一 sender 校验(对齐 SET_PLAN_MODE);device-link 远程
+ // 控制端已由 remoteControlEnabled + revoke + allowlist 授权。
+ if (!isDeviceLinkInvoke()) {
+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
+ }
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ if (
+ budget !== null &&
+ (typeof budget !== 'number' ||
+ !Number.isFinite(budget) ||
+ !Number.isInteger(budget) ||
+ budget < MIN_CONTEXT_WINDOW_BUDGET ||
+ budget > MAX_CONTEXT_WINDOW_BUDGET)
+ ) {
+ // 非法值不能静默收敛:normalize 会把 <1000 变成 null(等于静默清掉用户预算)、
+ // 把超大值静默夹到上限,调用方却收到成功回包。宁可选边拒绝。
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `context window budget must be null or an integer within [${MIN_CONTEXT_WINDOW_BUDGET}, ${MAX_CONTEXT_WINDOW_BUDGET}]`,
+ );
+ }
+ await assertReviewSettingsUnlocked(sessionId);
+ // 走唯一写入链路:落库 + sessions:patched 镜像 + 运行时应用钩子都在
+ // updateSessionInDb 里,不另起平行写入。
+ await updateSessionInDb(sessionId, { contextWindowBudget: budget });
+ },
+ );
+
+ ipcMain.handle(
+ MAKER_INVOKE.GET_CONTEXT_WINDOW_BOUNDS,
+ async (event, sessionId: unknown, route: unknown) => {
+ // 只读查询:不写库、不动活实例,因此不需要 review 设置锁;sender 校验与其它会话型
+ // IPC 一致(device-link 远程控制端已由 remoteControlEnabled + revoke + allowlist 授权)。
+ if (!isDeviceLinkInvoke()) {
+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
+ }
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ // 调用方可携带**界面上正在显示的路由**:延迟切换(同一引擎换模型/来源,发送边界
+ // 才落库)期间 DB 行还是旧路由,按旧行回答会让档位表与 chip 显示值一起停在旧模型上。
+ // 没携带(老调用方/畸形值)则退回会话行,与旧行为逐字节一致。
+ const requestedRoute = normalizeSessionContextWindowBoundsRoute(route);
+ const [row] = await getDbClient()
+ .drizzle.select({
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const agent = requestedRoute
+ ? requestedRoute.agent!
+ : dbToMakerAgentKind(row?.agentKind);
+ // 携带路由时整份照用(含 providerId: null = 未显式指定,由目录隐式解析);
+ // 不带时保留内存态覆盖优先(deferred 切来源期间 DB 还没落)。
+ const providerId = requestedRoute
+ ? (requestedRoute.providerId ?? null)
+ : (getSessionProvider(sessionId) ?? row?.providerId ?? null);
+ const modelId = requestedRoute?.model ?? row?.model ?? null;
+ if (!modelId) return null;
+ // 事实来自**本机**(被控端)目录与该路由的模型级上限,与运行期收敛同一套口径。
+ // 任务档位(用户显式设过的原始预算)与边界同源返回:档位表要标出当前选中的那一档,
+ // 而它是 main 侧偏好文件里的条目,远程调用方拿不到被控端的库。
+ return resolveSessionContextWindowBounds({
+ catalog: getActiveCatalog(),
+ agent,
+ providerId,
+ modelId,
+ budget: readSessionContextWindowBudget(sessionId),
+ budgetCustomized: isSessionContextWindowBudgetCustomized(sessionId),
+ });
+ },
+ );
+
ipcMain.handle(
MAKER_INVOKE.SET_PERMISSION_MODE,
async (event, sessionId: unknown, mode: unknown) => {
@@ -23998,6 +24276,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
);
+
ipcMain.handle(MAKER_INVOKE.EXPORT_SESSION_HTML, async (e, sessionId: unknown) => {
// 会弹原生保存对话框并把会话内容落盘:必须来自受信顶层页面,不能让辅助窗口 /
// WebView / 子 frame 经隐藏入口导出敏感会话(codex review)。导出非 device-link
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index 02dab2ce7a..139eab0632 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -26,7 +26,7 @@ interface RuntimeSetModelSession {
model: string;
setModel: (
model: string,
- opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean },
+ opts?: { providerId?: string | null; effort?: Effort; contextWindowBudget?: number | null; thinkingEnabled?: boolean },
) => Promise<void>;
requiresModelSwitchRebuild?: (
model: string,
@@ -34,7 +34,7 @@ interface RuntimeSetModelSession {
) => boolean | Promise<boolean>;
previewModelSwitch?: (
model: string,
- opts?: { providerId?: string | null },
+ opts?: { providerId?: string | null; contextWindowBudget?: number | null },
) => Promise<{
action: 'hot' | 'refresh' | 'rebuild' | 'unavailable';
targetContextWindow: number | null;
@@ -78,6 +78,11 @@ export interface ApplyRuntimeSetModelChangeInput {
* 形态相同,也必须沿用 credential-switch 的 idle close / busy defer 边界。
*/
forceSessionRebuild?: boolean;
+ /**
+ * 任务级工作上下文预算:host 已按**目标路由**重新收敛(含目录上限与模型级上限)。
+ * 只在会话已有显式预算且目标路由变化时下发;缺席 = 引擎保持当前预算。
+ */
+ contextWindowBudget?: number | null;
/** Re-evaluate the current Pi descriptor, including immutable spawn inputs. */
refreshPiConfiguration?: boolean;
/** Fail closed before an otherwise-required runtime replacement mutates route state. */
@@ -217,8 +222,16 @@ export async function applyRuntimeSetModelChange(
// that its native session needs replacement.
const piRouteChanged = sess?.agentKind === 'pi' &&
(sess.model !== model || currentProviderId !== nextProviderId);
+ // 预算必须与下面 setModel 拿到的**同一份**目标值:外层预演决定要不要重建,而
+ // switchModel 会先把预算写成新值再预演。用旧预算就会判「可热切」,内层按新预算
+ // 发现保留量不匹配便抛错,宿主此时已错过重建分支 —— 首次发送必失败(Greptile P1)。
const piPreview = piRouteChanged || (sess?.agentKind === 'pi' && input.refreshPiConfiguration === true)
- ? await sess.previewModelSwitch?.(model, { providerId: nextProviderId })
+ ? await sess.previewModelSwitch?.(model, {
+ providerId: nextProviderId,
+ ...(typeof input.contextWindowBudget === 'number'
+ ? { contextWindowBudget: input.contextWindowBudget }
+ : {}),
+ })
: undefined;
if ((piRouteChanged || (sess?.agentKind === 'pi' && input.refreshPiConfiguration === true)) && !piPreview) {
throw new Error('Pi model switch preview is unavailable; runtime selection was not changed');
@@ -451,6 +464,9 @@ export async function applyRuntimeSetModelChange(
? { providerId: nextProviderId }
: {}),
...(effort !== undefined ? { effort } : {}),
+ ...(input.contextWindowBudget !== undefined
+ ? { contextWindowBudget: input.contextWindowBudget }
+ : {}),
...(input.thinkingEnabled !== undefined ? { thinkingEnabled: input.thinkingEnabled } : {}),
});
} catch (err) {
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index ae09392011..c72c331277 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -27,6 +27,7 @@ import { getMaker } from '../maker-host/index.js';
import { inferProviderIdForModel } from '../maker-host/provider-route.js';
import { createBusinessSessionId } from '../sessionIds.js';
import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../shared/agentKindConversion.js';
+import { copySessionContextWindowBudget, pruneSessionContextWindowBudget } from '../maker-host/session-context-budget-store.js';
import type { AgentMeta, Session } from '../../renderer/lib/ccAgent.types';
import { buildHandoffText, type HandoffSourceMessage } from '../maker-ipc/agentHandoff.js';
import {
@@ -1068,6 +1069,14 @@ export async function forkSessionAtMessage(
const toolParentUuids = usesTailTurnFork
? []
: collectClaudeToolParentUuids(sourceMessages, claudeAnchorIndex);
+ // 6. 任务级窗口档位随 fork 继承(同一任务意图);启动时仍会按新路由重新收敛,
+ // 所以跨 agent / 跨模型的 fork 不会残留超出目标上限的值。它是偏好文件里的条目,
+ // 不是会话列,所以不在上面的行插入里。
+ //
+ // 写在事务**之前**:写失败时调用方拿到的失败与「任务还没建出来」是一致的
+ // (否则 DB 已提交、调用方却认为整体失败,会留下一个“报了错但存在”的任务);
+ // 事务失败则把刚写的条目撤掉,不留指向不存在任务的孤儿条目。
+ const inheritedBudget = copySessionContextWindowBudget(sourceSessionId, newSessionId);
try {
await getDbClient().tx('fork.session', {
sourceSessionId,
@@ -1124,6 +1133,7 @@ export async function forkSessionAtMessage(
// 轮 40-w4-t13 HIGH:SDK 侧已创建新 session file(forkSdkSession), DB 事务
// 失败时该文件成孤儿 —— 调用方收到失败, 但孤儿累积不可达。至少记录
// 可恢复线索(sdkSessionId), 供诊断/清理; 错误照常上抛。
+ if (inheritedBudget !== null) pruneSessionContextWindowBudget(newSessionId);
if (newSdkSessionId) {
console.error(
`[fork] SDK session ${newSdkSessionId} created but DB transaction failed — orphan session file left behind`,
@@ -1133,7 +1143,7 @@ export async function forkSessionAtMessage(
throw err;
}
- // 6. 返回 mapper 转过的新 session(含 messageCount)
+ // 7. 返回 mapper 转过的新 session(含 messageCount)
const [row] = await db.select().from(sessions).where(eq(sessions.id, newSessionId));
if (!row) {
throw new Error('Fork session 创建后查询失败');
@@ -1269,42 +1279,50 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis
const recoveryMarker = newSdkSessionId === null ? buildCodexForkRecoveryMarker({
source, rows: sourceMessages, newMessageIds, sessionId: newSessionId, now,
}) : undefined;
- await getDbClient().tx('fork.session', {
- sourceSessionId,
- sourceClearedAt: source.clearedAt,
- targetCreatedAt: copyBeforeCreatedAt,
- targetRowid: null,
- newSession: {
- id: newSessionId,
- title: newTitle,
- workingDir: source.workingDir,
- model: source.model,
- // 同 forkSessionAtMessage:providerId 必须继承,防止凭证形态漂移。
- providerId: source.providerId,
- effort: source.effort,
- permissionMode: source.permissionMode,
- status: 'active',
- sdkSessionId: newSdkSessionId,
- totalTokenUsage: 0,
- totalCostUsd: 0,
- contextTokens: 0,
- contextWindow: 0,
- fastMode: source.fastMode,
- clearedAt: null,
- pinnedAt: null,
- userSendAt: now,
- agentKind: source.agentKind,
- workspaceKind: source.workspaceKind,
- codexHistoryHasProductPrompt: source.codexHistoryHasProductPrompt,
- parentSessionId: source.id,
- forkedAtMessageId: null,
- createdAt: now,
- updatedAt: now,
- },
- uuidMap: Array.from(uuidMap.entries()),
- newMessageIds,
- recoveryMarker,
- });
+ // 任务级窗口档位与普通 fork 同口径继承(同一条任务意图);这是偏好文件里的条目,
+ // 与普通 fork 一样先写后提交:写失败时任务还没建出来,事务失败则撤掉条目。
+ const inheritedBudget = copySessionContextWindowBudget(sourceSessionId, newSessionId);
+ try {
+ await getDbClient().tx('fork.session', {
+ sourceSessionId,
+ sourceClearedAt: source.clearedAt,
+ targetCreatedAt: copyBeforeCreatedAt,
+ targetRowid: null,
+ newSession: {
+ id: newSessionId,
+ title: newTitle,
+ workingDir: source.workingDir,
+ model: source.model,
+ // 同 forkSessionAtMessage:providerId 必须继承,防止凭证形态漂移。
+ providerId: source.providerId,
+ effort: source.effort,
+ permissionMode: source.permissionMode,
+ status: 'active',
+ sdkSessionId: newSdkSessionId,
+ totalTokenUsage: 0,
+ totalCostUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ fastMode: source.fastMode,
+ clearedAt: null,
+ pinnedAt: null,
+ userSendAt: now,
+ agentKind: source.agentKind,
+ workspaceKind: source.workspaceKind,
+ codexHistoryHasProductPrompt: source.codexHistoryHasProductPrompt,
+ parentSessionId: source.id,
+ forkedAtMessageId: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ uuidMap: Array.from(uuidMap.entries()),
+ newMessageIds,
+ recoveryMarker,
+ });
+ } catch (err) {
+ if (inheritedBudget !== null) pruneSessionContextWindowBudget(newSessionId);
+ throw err;
+ }
const [row] = await db.select().from(sessions).where(eq(sessions.id, newSessionId));
if (!row) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4edf17eda3..4eb6dc53ce 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6739,6 +6739,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
target: import('../shared/modelContextLimit').ModelContextLimitTarget,
): Promise<import('../shared/modelContextLimit').ModelContextLimitView> =>
ipcRenderer.invoke('maker:model-context-limit:get', target),
+ /**
+ * 任务窗口档位表的**权威边界**(路由默认 / 路由物理上限 / 该路由模型级上限)。
+ * 与运行期收敛同源、与 device-link 的 maker:get-context-window-bounds 同一 handler:
+ * chip 本地/远程都读它,避免 renderer 自己解析路由时与 main 分叉(跨 provider 同 id 时
+ * renderer 解不出来源,会给出 main 一定会夹掉的档位)。
+ */
+ getSessionContextWindowBounds: (
+ sessionId: string,
+ route?: import('../shared/sessionContextWindowBounds').SessionContextWindowBoundsRoute,
+ ): Promise<import('../shared/sessionContextWindowBounds').SessionContextWindowBounds | null> =>
+ ipcRenderer.invoke('maker:get-context-window-bounds', sessionId, route),
setModelContextLimit: (
target: import('../shared/modelContextLimit').ModelContextLimitTarget,
limit: number | null,
@@ -7369,6 +7380,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 同步调 sessionService.update({ planModeEnabled })(与 setModel 双 IPC 协调先例一致)。
setPlanMode: (sessionId: string, enabled: boolean): Promise<void> =>
ipcRenderer.invoke('maker:set-plan-mode', sessionId, enabled),
+ /**
+ * 任务级工作上下文窗口档位(tokens;null = 跟随模型默认)。
+ * device-link 远程任务由控制端经隧道调本 channel,在被控端落库并应用。
+ */
+ setContextWindowBudget: (sessionId: string, budget: number | null): Promise<void> =>
+ ipcRenderer.invoke('maker:set-context-window-budget', sessionId, budget),
// 会话导出 HTML(pi 原生)。主进程弹保存对话框 + 导出 + 在文件管理器中显示。
// 返回写入的绝对路径;用户取消对话框或 agent 不支持时返回 null。
exportSessionHtml: (sessionId: string): Promise<string | null> =>
diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.ts
index d4379104df..ed332d6c55 100644
--- a/apps/desktop/src/renderer/lib/sessionService.ts
+++ b/apps/desktop/src/renderer/lib/sessionService.ts
@@ -198,6 +198,11 @@ export async function update(
totalCostUsd?: number;
contextTokens?: number;
contextWindow?: number;
+ /**
+ * 任务级工作上下文预算(tokens);null = 清除显式选择、跟随模型路由默认。
+ * 落库后 main 会把新窗口应用到活实例(空闲冷重建 / 回合中登记 pending)。
+ */
+ contextWindowBudget?: number | null;
clearedAt?: string | null;
pinnedAt?: string | null;
status?: SessionStatus;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d062a0f48d..3f2aff1f63 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5949,6 +5949,12 @@ interface ElectronAPI {
getModelContextLimit: (
target: import('../shared/modelContextLimit').ModelContextLimitTarget,
) => Promise<import('../shared/modelContextLimit').ModelContextLimitView>;
+ /** 任务窗口档位表的权威边界(与 device-link 的 maker:get-context-window-bounds 同一 handler)。 */
+ getSessionContextWindowBounds: (
+ sessionId: string,
+ // 界面上正在显示的路由:延迟切换期间会话行还是旧路由,带上它才能按显示路由回答。
+ route?: import('../shared/sessionContextWindowBounds').SessionContextWindowBoundsRoute,
+ ) => Promise<import('../shared/sessionContextWindowBounds').SessionContextWindowBounds | null>;
setModelContextLimit: (
target: import('../shared/modelContextLimit').ModelContextLimitTarget,
limit: number | null,
@@ -6535,6 +6541,8 @@ interface ElectronAPI {
setThinkingEnabled: (sessionId: string, enabled: boolean) => Promise<void>;
/** 计划模式一级开关(与 permissionMode 正交); DB 持久化由调用方另调 sessionService.update({ planModeEnabled }) */
setPlanMode: (sessionId: string, enabled: boolean) => Promise<void>;
+ /** 任务级工作上下文窗口档位(tokens;null = 跟随模型默认) */
+ setContextWindowBudget: (sessionId: string, budget: number | null) => Promise<void>;
/** 会话导出 HTML(pi 原生); 主进程弹保存对话框 + 导出 + 在文件管理器显示; 返回路径或 null(取消/不支持) */
exportSessionHtml: (sessionId: string) => Promise<string | null>;
/** 手动压缩会话上下文(pi 原生, 可带聚焦指令); 返回压缩前后 token 数 / {noop} / null(会话不在/不支持) */
diff --git a/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
index 06b51375ea..ac232a81a5 100644
--- a/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
+++ b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { Catalog, CatalogModel, Provider } from '@cindy/model-providers';
-import { projectSessionContextWindow, resolveSessionContextWindow, resolveVerifiedContextWindow } from '../sessionContextWindow';
+import { projectSessionContextWindow, resolveRouteContextWindowBounds, resolveSessionContextWindow, resolveVerifiedContextWindow } from '../sessionContextWindow';
import { shouldRebuildForModelWindowSwitch } from '../../main/maker-ipc/contextOverflowRollover';
const model: CatalogModel = {
@@ -124,3 +124,60 @@ describe('session context read projection', () => {
expect(resolveSessionContextWindow(catalog, session)).toBe(272_000);
});
});
+
+describe('route context window bounds', () => {
+ const boundsFor = (row: CatalogModel) =>
+ resolveRouteContextWindowBounds(
+ { providers: [provider('openai', row)] } as unknown as Pick<Catalog, 'providers'>,
+ 'claude-code',
+ 'openai',
+ row.id,
+ );
+
+ it('uses a verified context window as the physical max', () => {
+ // 已核实路由:resolveVerifiedContextWindow 按 min(预算, contextWindowMax ?? contextWindow)
+ // 夹,contextWindow 就是真容量。
+ expect(boundsFor({ ...model, contextWindow: 1_000_000 })).toEqual({
+ providerId: 'openai', defaultWindow: 1_000_000, maxWindow: 1_000_000,
+ });
+ });
+
+ it('prefers a declared max over the verified context window', () => {
+ expect(boundsFor({ ...model, contextWindow: 200_000, contextWindowMax: 1_000_000 })).toEqual({
+ providerId: 'openai', defaultWindow: 200_000, maxWindow: 1_000_000,
+ });
+ });
+
+ it('keeps an unverified declared max as the ceiling', () => {
+ // 发现流程只拿到 max 的形态:未核实也按它夹(resolveConfiguredContextWindow)。
+ expect(boundsFor({
+ ...model, contextWindow: 200_000, contextWindowMax: 400_000, contextWindowVerified: false,
+ })).toEqual({ providerId: 'openai', defaultWindow: 200_000, maxWindow: 400_000 });
+ });
+
+ it('does not promote an unverified fallback context window to a ceiling', () => {
+ // 自定义连接未声明窗口:contextWindow 只是兜底默认(DEFAULT_CUSTOM_CONTEXT_WINDOW=200K),
+ // main 刻意不按它夹 —— 报成 maxWindow 会把档位基准钉在 200K,让「模型默认 1M」显示成 500%
+ // (用户实测报障,2026-09-22)。默认窗口仍要给(没有模型级上限时它就是运行窗口)。
+ expect(boundsFor({ ...model, contextWindow: 200_000, contextWindowVerified: false })).toEqual({
+ providerId: 'openai', defaultWindow: 200_000, maxWindow: null,
+ });
+ });
+
+ it('falls back to a declared max when the route has no context window', () => {
+ expect(boundsFor({
+ ...model, contextWindow: 0, contextWindowMax: 400_000, contextWindowVerified: false,
+ })).toEqual({ providerId: 'openai', defaultWindow: 400_000, maxWindow: 400_000 });
+ });
+
+ it('reports nothing for an ambiguous or empty route', () => {
+ const row = { ...model, contextWindow: 200_000, contextWindowVerified: false };
+ expect(resolveRouteContextWindowBounds(
+ { providers: [provider('a', row), provider('b', row)] } as unknown as Pick<Catalog, 'providers'>,
+ 'claude-code',
+ null,
+ row.id,
+ )).toBeNull();
+ expect(boundsFor({ ...model, contextWindow: 0, contextWindowVerified: false })).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/__tests__/sessionContextWindowBounds.test.ts b/apps/desktop/src/shared/__tests__/sessionContextWindowBounds.test.ts
new file mode 100644
index 0000000000..636d10dd0e
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/sessionContextWindowBounds.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isSessionContextWindowAgentKind,
+ normalizeSessionContextWindowBounds,
+ normalizeSessionContextWindowBoundsRoute,
+} from '../sessionContextWindowBounds';
+
+describe('normalizeSessionContextWindowBounds', () => {
+ it('keeps the well-formed payload the controlled device returns', () => {
+ expect(
+ normalizeSessionContextWindowBounds({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: 1_000_000, modelLimit: 100_000,
+ budget: 250_000, budgetCustomized: true, defaultEffectiveWindow: 100_000, maxEffectiveWindow: 1_000_000,
+ }),
+ ).toEqual({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: 1_000_000, modelLimit: 100_000,
+ budget: 250_000, budgetCustomized: true, defaultEffectiveWindow: 100_000,
+ maxEffectiveWindow: 1_000_000, effectiveWindowsReported: true,
+ });
+ // 任务预算随边界一起回来(偏好文件里的条目),缂少/非法时按「未自定义」处理。
+ expect(
+ normalizeSessionContextWindowBounds({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: null, modelLimit: null,
+ }),
+ ).toEqual({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: null, modelLimit: null,
+ budget: null, budgetCustomized: false, defaultEffectiveWindow: null, maxEffectiveWindow: null,
+ effectiveWindowsReported: false,
+ });
+ expect(
+ normalizeSessionContextWindowBounds({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: null, modelLimit: null,
+ budget: -5, budgetCustomized: 'yes', defaultEffectiveWindow: 0, maxEffectiveWindow: 0,
+ }),
+ ).toEqual({
+ providerId: 'xd', defaultWindow: 200_000, maxWindow: null, modelLimit: null,
+ budget: null, budgetCustomized: false, defaultEffectiveWindow: null, maxEffectiveWindow: null,
+ effectiveWindowsReported: true,
+ });
+ });
+
+ it('treats any unusable shape as unknown instead of guessing a ceiling', () => {
+ // 老版本/畸形返回:宁可退回「只允许收紧」,也不能把某个字段当成上限。
+ expect(normalizeSessionContextWindowBounds(null)).toBeNull();
+ expect(normalizeSessionContextWindowBounds(undefined)).toBeNull();
+ expect(normalizeSessionContextWindowBounds('1000000')).toBeNull();
+ // 两个窗口都缺 → 整份不可用(即便 modelLimit 有值也算不出上限)。
+ expect(normalizeSessionContextWindowBounds({ defaultWindow: null, maxWindow: null, modelLimit: 900_000 }))
+ .toBeNull();
+ // 非数/负数/0/NaN 一律按未知处理;只有上限可批时仍可用,但 defaultWindow 为 null。
+ expect(
+ normalizeSessionContextWindowBounds({
+ providerId: '', defaultWindow: '200000', maxWindow: 400_000, modelLimit: -1,
+ }),
+ ).toEqual({
+ providerId: null, defaultWindow: null, maxWindow: 400_000, modelLimit: null,
+ budget: null, budgetCustomized: false, defaultEffectiveWindow: null, maxEffectiveWindow: null,
+ effectiveWindowsReported: false,
+ });
+ expect(normalizeSessionContextWindowBounds({ defaultWindow: 0, maxWindow: Number.NaN })).toBeNull();
+ });
+});
+
+describe('normalizeSessionContextWindowBoundsRoute', () => {
+ it('keeps a route the caller sends for the route it is displaying', () => {
+ expect(
+ normalizeSessionContextWindowBoundsRoute({
+ agent: 'pi', providerId: 'commandcode', model: 'deepseek/deepseek-v4.1-flash',
+ }),
+ ).toEqual({ agent: 'pi', providerId: 'commandcode', model: 'deepseek/deepseek-v4.1-flash' });
+ // 不显式指定来源 = 由目录隐式解析(与运行期同口径),保留 null 而不是丢掉整个路由。
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'claude-code', model: 'grok-4.6' }))
+ .toEqual({ agent: 'claude-code', providerId: null, model: 'grok-4.6' });
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: ' pi ', providerId: ' xd ', model: ' m ' }))
+ .toEqual({ agent: 'pi', providerId: 'xd', model: 'm' });
+ });
+
+ it('rejects anything that is not a complete route instead of answering half of it', () => {
+ // 缺模型或引擎就解析不了窗口:整份拒绝 → 调用方退回「按会话行回答」。
+ expect(normalizeSessionContextWindowBoundsRoute(null)).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute('pi')).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute(['pi', 'xd', 'm'])).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({})).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'pi' })).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ model: 'm' })).toBeNull();
+ // 引擎值域外的标识不能当路由用(否则会把任意字符串当 AgentKind 去查目录)。
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'cc', model: 'm' })).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'pi', model: 42 })).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'pi', providerId: 7, model: 'm' })).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'pi', model: '' })).toBeNull();
+ expect(normalizeSessionContextWindowBoundsRoute({ agent: 'pi', model: 'x'.repeat(300) })).toBeNull();
+ });
+
+ it('recognizes exactly the three maker-core engine kinds', () => {
+ expect(isSessionContextWindowAgentKind('claude-code')).toBe(true);
+ expect(isSessionContextWindowAgentKind('pi')).toBe(true);
+ expect(isSessionContextWindowAgentKind('codex')).toBe(true);
+ expect(isSessionContextWindowAgentKind('cc')).toBe(false);
+ expect(isSessionContextWindowAgentKind(null)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/shared/__tests__/sessionContextWindowBudget.test.ts b/apps/desktop/src/shared/__tests__/sessionContextWindowBudget.test.ts
new file mode 100644
index 0000000000..27ca5d34ab
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/sessionContextWindowBudget.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildContextWindowBudgetOptions,
+ contextWindowBudgetTierPercent,
+ normalizeContextWindowBudget,
+ resolveContextWindowBudgetBase,
+} from '../sessionContextWindowBudget';
+
+describe('normalizeContextWindowBudget', () => {
+ it('accepts sane token counts and rounds them', () => {
+ expect(normalizeContextWindowBudget(300_000)).toBe(300_000);
+ expect(normalizeContextWindowBudget(300_000.4)).toBe(300_000);
+ });
+
+ it('treats non-numbers and sub-floor values as "follow the model default"', () => {
+ for (const value of [null, undefined, '300000', Number.NaN, -1, 999]) {
+ expect(normalizeContextWindowBudget(value)).toBeNull();
+ }
+ });
+
+ it('clamps absurd magnitudes instead of rejecting them', () => {
+ expect(normalizeContextWindowBudget(500_000_000)).toBe(100_000_000);
+ });
+});
+
+describe('档位基准与百分比(展示层共用同一口径)', () => {
+ it('基准取物理上限与模型级上限的更紧者,缺省时退回默认窗口', () => {
+ expect(resolveContextWindowBudgetBase({ defaultWindow: 1_000_000 })).toBe(1_000_000);
+ expect(resolveContextWindowBudgetBase({ defaultWindow: 272_000, maxWindow: 1_050_000 })).toBe(1_050_000);
+ expect(resolveContextWindowBudgetBase({ defaultWindow: 272_000, maxWindow: 1_050_000, modelLimit: 300_000 }))
+ .toBe(300_000);
+ // 上限字段是畸形值(0 / 负数 / NaN)时不参与,退回默认窗口。
+ expect(resolveContextWindowBudgetBase({ defaultWindow: 300_000, maxWindow: 0, modelLimit: Number.NaN }))
+ .toBe(300_000);
+ expect(resolveContextWindowBudgetBase({ defaultWindow: null, maxWindow: null, modelLimit: null })).toBeNull();
+ });
+
+ it('每一行都用同一个公式算百分比(含默认档与旧值补档)', () => {
+ // 1,048,576 的窗口:默认档 = 100%,两个比例档 = 25% / 50%。
+ expect(contextWindowBudgetTierPercent(1_048_576, 1_048_576)).toBe(100);
+ expect(contextWindowBudgetTierPercent(262_144, 1_048_576)).toBe(25);
+ expect(contextWindowBudgetTierPercent(524_288, 1_048_576)).toBe(50);
+ // Codex 形态(默认 272K / 上限 1.05M):默认档不是满窗,如实显示 26%。
+ expect(contextWindowBudgetTierPercent(272_000, 1_050_000)).toBe(26);
+ // 旧值补的当前档:按真实占比四舍五入,不再是「没有百分比」的另一种行。
+ expect(contextWindowBudgetTierPercent(300_000, 1_000_000)).toBe(30);
+ expect(contextWindowBudgetTierPercent(333_333, 1_000_000)).toBe(33);
+ });
+
+ it('基准未知或输入非法时返回 null(该行只显示绝对值)', () => {
+ expect(contextWindowBudgetTierPercent(1_000_000, null)).toBeNull();
+ expect(contextWindowBudgetTierPercent(1_000_000, 0)).toBeNull();
+ expect(contextWindowBudgetTierPercent(1_000_000, Number.NaN)).toBeNull();
+ expect(contextWindowBudgetTierPercent(0, 1_000_000)).toBeNull();
+ expect(contextWindowBudgetTierPercent(Number.NaN, 1_000_000)).toBeNull();
+ });
+});
+
+describe('buildContextWindowBudgetOptions', () => {
+ it('returns nothing when the route window is unknown', () => {
+ expect(buildContextWindowBudgetOptions({ defaultWindow: null })).toEqual([]);
+ });
+
+ it('gives the model default plus exact 25%/50% tiers on a 1M window', () => {
+ // 基准 = 1M(默认=上限)→ 25% = 250K、50% = 500K;100% 就是默认档,不单列。
+ expect(buildContextWindowBudgetOptions({ defaultWindow: 1_000_000 })).toEqual([
+ { tokens: 250_000, kind: 'percent' },
+ { tokens: 500_000, kind: 'percent' },
+ { tokens: 1_000_000, kind: 'default' },
+ ]);
+ });
+
+ it('keeps percentages exact instead of snapping to a K grid', () => {
+ // 1,048,576 的 25% / 50% 是 262,144 / 524,288 —— 不取整到 256K / 512K。
+ const options = buildContextWindowBudgetOptions({ defaultWindow: 1_048_576 });
+ expect(options).toEqual([
+ { tokens: 262_144, kind: 'percent' },
+ { tokens: 524_288, kind: 'percent' },
+ { tokens: 1_048_576, kind: 'default' },
+ ]);
+ });
+
+ it('only offers the default tier on a 256K-class window (below the tier floor)', () => {
+ // 512K 的 50% = 256K 保留;256K 的 50% = 128K < 200K 阈值 → 只剩默认档。
+ expect(buildContextWindowBudgetOptions({ defaultWindow: 512_000 })).toEqual([
+ { tokens: 256_000, kind: 'percent' },
+ { tokens: 512_000, kind: 'default' },
+ ]);
+ expect(buildContextWindowBudgetOptions({ defaultWindow: 256_000 })).toEqual([
+ { tokens: 256_000, kind: 'default' },
+ ]);
+ });
+
+ it('keeps the 100% tier so a lowered default can still reach the physical max', () => {
+ // Codex GPT 系:默认 272K、物理上限 1.05M。25% = 262.5K 与 50%/100% 一起会让档数超上限,
+ // 按「优先保留大比例」丢掉 25%,保证能开满窗口且仍是三档。
+ const options = buildContextWindowBudgetOptions({
+ defaultWindow: 272_000,
+ maxWindow: 1_050_000,
+ });
+ expect(options).toEqual([
+ { tokens: 272_000, kind: 'default' },
+ { tokens: 525_000, kind: 'percent' },
+ { tokens: 1_050_000, kind: 'percent' },
+ ]);
+ });
+
+ it('lets a tighter model-level limit become the percentage base', () => {
+ // 物理 1.05M,但用户在高级设置里设了 300K:基准变 300K → 50% = 150K 低于阈值不出现,
+ // 只剩「默认 + 100% 上限档」。
+ const options = buildContextWindowBudgetOptions({
+ defaultWindow: 272_000,
+ maxWindow: 1_050_000,
+ modelLimit: 300_000,
+ });
+ expect(options).toEqual([
+ { tokens: 272_000, kind: 'default' },
+ { tokens: 300_000, kind: 'percent' },
+ ]);
+ });
+
+ it('never lets a percentage tier exceed its base', () => {
+ for (const base of [1_000_000, 1_048_576, 991_808, 512_000]) {
+ for (const option of buildContextWindowBudgetOptions({ defaultWindow: base })) {
+ expect(option.tokens).toBeLessThanOrEqual(base);
+ }
+ }
+ });
+});
diff --git a/apps/desktop/src/shared/sessionContextWindow.ts b/apps/desktop/src/shared/sessionContextWindow.ts
index 1fce5c22d6..e87252fa21 100644
--- a/apps/desktop/src/shared/sessionContextWindow.ts
+++ b/apps/desktop/src/shared/sessionContextWindow.ts
@@ -42,6 +42,57 @@ export function resolveVerifiedContextWindow(
return Math.min(budget, maximum);
}
+/**
+ * 该路由的窗口边界(默认工作窗口 + 声明上限),给任务级窗口档位用。
+ *
+ * 与 `resolveVerifiedContextWindow` 的区别:不要求 `contextWindowVerified === true`
+ * (路由未核实但声明了 `max_context_window` 的目录形态真实存在,主进程同样会按它夹紧),
+ * 且不借用「运行时上报才可信」那套 pi/codex 快照口径 —— 档位需要一个路由级锚点,
+ * 否则 Pi / Codex 任务会回落成跨 provider 去重的扁平表值。
+ *
+ * 仍然要求路由唯一:同一 model id 由多个 provider 提供且未限定 providerId 时返回 null
+ * (宁可只允许收紧,也不能把另一条路由的上限当成事实;这正是 availableModels 扁平表
+ * 不能兼作上限来源的原因)。解出唯一候选时回传它解析到的 `providerId`,调用方据此读
+ * 同一路由的模型级上限,不必自己再猜一遍来源。
+ */
+export function resolveRouteContextWindowBounds(
+ catalog: Pick<Catalog, 'providers'>,
+ agent: AgentKind,
+ providerId: string | null | undefined,
+ modelId: string,
+): { providerId: string; defaultWindow: number; maxWindow: number | null } | null {
+ const candidates: { providerId: string; model: CatalogModel }[] = [];
+ for (const provider of catalog.providers) {
+ if (provider.routing[agent]?.disabled === true) continue;
+ if (providerId && provider.id !== providerId) continue;
+ for (const model of provider.models[agent] ?? []) {
+ if (model.id === modelId) candidates.push({ providerId: provider.id, model });
+ }
+ }
+ if (candidates.length !== 1) return null;
+ const { providerId: sourceProviderId, model } = candidates[0];
+ const contextWindow = Number.isFinite(model.contextWindow) && model.contextWindow > 0
+ ? Math.round(model.contextWindow)
+ : null;
+ const declaredMax = typeof model.contextWindowMax === 'number' &&
+ Number.isFinite(model.contextWindowMax) && model.contextWindowMax > 0
+ ? Math.round(model.contextWindowMax)
+ : null;
+ // 「物理上限」只收 main 真会拿来夹预算的数:
+ // - 声明了 `contextWindowMax`:未核实路由也按它夹(见 resolveConfiguredContextWindow);
+ // - **已核实**路由的 `contextWindow`:resolveVerifiedContextWindow 按
+ // `min(预算, contextWindowMax ?? contextWindow)` 夹,它就是真容量;
+ // - **未核实且没声明上限**:目录里的 `contextWindow` 只是**兜底默认**(自定义连接未声明
+ // 窗口时是 DEFAULT_CUSTOM_CONTEXT_WINDOW=200K),不是容量 —— main 刻意不按它夹,
+ // 任务预算可以是它���倍且真的会生效。早先在这里兜底成 maxWindow,会让档位基准被 200K
+ // 钉死,把「模型默认 1M」显示成 500%(用户实测报障,2026-09-22)。
+ const maxWindow = declaredMax ?? (model.contextWindowVerified === true ? contextWindow : null);
+ const anchor = maxWindow ?? contextWindow;
+ if (anchor === null) return null;
+ const defaultWindow = contextWindow === null ? anchor : Math.min(contextWindow, anchor);
+ return { providerId: sourceProviderId, defaultWindow, maxWindow };
+}
+
/** Codex and Pi report their effective runtime windows; catalogs cannot replace them. */
export function resolveSessionContextWindow(
catalog: Pick<Catalog, 'providers'>,
diff --git a/apps/desktop/src/shared/sessionContextWindowBounds.ts b/apps/desktop/src/shared/sessionContextWindowBounds.ts
new file mode 100644
index 0000000000..1783dc76d7
--- /dev/null
+++ b/apps/desktop/src/shared/sessionContextWindowBounds.ts
@@ -0,0 +1,140 @@
+/**
+ * 任务窗口档位表的**权威边界** —— main 与 renderer 的共享契约。
+ *
+ * 事实来源:main 侧 `resolveSessionContextWindowBounds`(与运行期
+ * `resolveConfiguredContextWindow` 同一套口径:目录路由唯一候选 + 该路由的模型级上限
+ * + 隐式来源解析)。renderer 自己解析跨 provider 同 id 的模型时解不出来源,会给出
+ * main 一定会夹掉的档位 —— 档位表必须读这份,本地经 `maker:get-context-window-bounds`
+ * handler,远程经 device-link 的同名 channel(被控端算)。
+ *
+ * 三个窗口值都可能为 null:null = **未知**(不是无限),调用方必须退回「只允许收紧」。
+ */
+import type { MakerAgentKindWire } from './agentKindConversion.js';
+
+export interface SessionContextWindowBounds {
+ /** 实际解析到的来源 providerId;供调用方读同一路由的模型级上限/报价。 */
+ providerId: string | null;
+ /** 该路由的默认工作窗口(`min(contextWindow, contextWindowMax)`)。 */
+ defaultWindow: number | null;
+ /** 该路由声明的物理上限(`contextWindowMax`)。 */
+ maxWindow: number | null;
+ /** 用户在同一路由上设过的模型级「上下文上限」。 */
+ modelLimit: number | null;
+ /**
+ * 该任务已保存的预算(用户显式设过的**原始**值,tokens);null = 跟随默认。
+ *
+ * 与上面三个字段同源(同一个 handler / 同一条隧道):档位表既要画可选档位,也要标出
+ * 当前选中的那一档。预算是 main 侧偏好文件里的条目,不是会话列,所以随边界一起回来,
+ * 不依赖调用方手里的会话快照(远程会话拿不到被控端的库)。
+ */
+ budget: number | null;
+ /** 用户是否显式设过(区分「跟随默认」与「设了一个刚好等于默认的值」)。 */
+ budgetCustomized: boolean;
+ /**
+ * **清掉任务预算后**「跟随默认」会得到的窗口(= main 的 `resolveConfiguredContextWindow`,
+ * 传 `sessionBudget = null`:模型级上限再按已核实路由的物理上限 `contextWindowMax ?? contextWindow`
+ * 夹一次)。它是档位表里「模型默认」那一档的真实含义 —— 选中它会上报 `null`,运行期回到这个值。
+ *
+ * 刻意不带当前任务预算:把「当前生效窗口」当成默认档会让菜单显示 500K、点下去却变成 800K
+ * (任务预算被清除)。调用方也不要自己用 defaultWindow/modelLimit 重推:那套推导已经在
+ * `resolveVerifiedContextWindow` / `declaredMax` 里做过一次,重推必与运行期分叉。
+ */
+ defaultEffectiveWindow: number | null;
+ /**
+ * main 实际会施加的**物理上限**(= `resolveVerifiedContextWindow` 里的
+ * `contextWindowMax ?? contextWindow`,仅当路由唯一且 `contextWindowVerified === true` 时有值;
+ * 未核实路由没有这道夹,返回 null)。
+ *
+ * 档位基准不能只看目录声明的 `maxWindow`:已核实但**未声明** `contextWindowMax` 的路由,
+ * 运行期照样被 `contextWindow` 夹住;renderer 不知道 `contextWindowVerified`,所以这个值由
+ * main 算好下发,避免档位表给出运行期根本达不到的档。
+ */
+ maxEffectiveWindow: number | null;
+ /**
+ * 该响应是否**申报过**上面两个生效窗口字段。
+ *
+ * 用来区分两种「null」:新主进程/新被控端会显式申报(未核实路由就诚实地申报 `null` = 没有这道
+ * 物理夹),而**老被控端**根本没有这两个字段。后者必须退回保守口径(只允许收紧),否则一旦目录
+ * 没声明 `contextWindowMax`,`modelLimit` 会被误当成档位上限 —— 但被控端运行期还会被
+ * `contextWindow` 夹一次(实测:200K 的路由,远程菜单却给出 800K 档)。
+ */
+ effectiveWindowsReported: boolean;
+}
+
+/** 被控端/主进程返回值的形状收敛:缺字段或非法值一律按「未知」处理(不猜上限)。 */
+export function normalizeSessionContextWindowBounds(
+ value: unknown,
+): SessionContextWindowBounds | null {
+ if (!value || typeof value !== 'object') return null;
+ const raw = value as Record<string, unknown>;
+ const positive = (input: unknown): number | null =>
+ typeof input === 'number' && Number.isFinite(input) && input > 0 ? Math.round(input) : null;
+ const defaultWindow = positive(raw.defaultWindow);
+ const maxWindow = positive(raw.maxWindow);
+ if (defaultWindow === null && maxWindow === null) return null;
+ return {
+ providerId: typeof raw.providerId === 'string' && raw.providerId ? raw.providerId : null,
+ defaultWindow,
+ maxWindow,
+ modelLimit: positive(raw.modelLimit),
+ budget: positive(raw.budget),
+ budgetCustomized: raw.budgetCustomized === true,
+ defaultEffectiveWindow: positive(raw.defaultEffectiveWindow),
+ maxEffectiveWindow: positive(raw.maxEffectiveWindow),
+ effectiveWindowsReported:
+ 'defaultEffectiveWindow' in raw || 'maxEffectiveWindow' in raw,
+ };
+}
+
+/** 查询参数里允许携带的引擎标识(与 `maker-ipc` 的 `AgentKind` 同值域)。 */
+export function isSessionContextWindowAgentKind(
+ value: unknown,
+): value is MakerAgentKindWire {
+ return value === 'claude-code' || value === 'codex' || value === 'pi';
+}
+
+/**
+ * 边界查询的**路由**:界面上正在显示的那条路由。
+ *
+ * 为什么需要它:同名会话在「延迟切换」期间,模型选择器已经指向目标模型,而 DB 行仍是旧
+ * 路由(切模在发送边界才落库)。此时只按会话 id 查边界,被控端会按**旧行**回答,档位表与
+ * chip 显示值一起停在旧模型上(旧窗口 262K 切到 1M 模型后仍显示 262K,用户已实测报障)。
+ * 带上显示路由后,档位表始终按「用户看到的那条路由」算,与写入路径的目标路由一致。
+ */
+export interface SessionContextWindowBoundsRoute {
+ /** maker-core 引擎标识;与 `model` 一起构成路由,两者缺一即视为未携带。 */
+ agent?: MakerAgentKindWire | null;
+ /** 目标模型的显式来源;null = 未显式指定(由目录隐式解析,与运行期同口径)。 */
+ providerId?: string | null;
+ model?: string | null;
+}
+
+/** 单个路由字段的长度上限:正常 id 远小于它,超长一律视为畸形输入。 */
+const MAX_ROUTE_FIELD_LENGTH = 256;
+
+/**
+ * 收敛调用方携带的路由(renderer 或 device-link 远程控制端都可能传任意值)。
+ *
+ * 返回 null = **未携带可用路由**(调用方必须退回「按会话行回答」),而不是「按空路由回答」:
+ * 任意字段类型不对就整份拒绝,绝不用调用方给的一半路由去解析另一条来源。
+ */
+export function normalizeSessionContextWindowBoundsRoute(
+ value: unknown,
+): SessionContextWindowBoundsRoute | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const raw = value as Record<string, unknown>;
+ const text = (input: unknown): string | null | undefined => {
+ if (input === undefined || input === null) return null;
+ if (typeof input !== 'string') return undefined;
+ const trimmed = input.trim();
+ if (!trimmed) return null;
+ return trimmed.length > MAX_ROUTE_FIELD_LENGTH ? undefined : trimmed;
+ };
+ const agent = text(raw.agent);
+ const providerId = text(raw.providerId);
+ const model = text(raw.model);
+ if (agent === undefined || providerId === undefined || model === undefined) return null;
+ // 只有「引擎 + 模型」都在时才构成路由;只给 provider 无法解析窗口。
+ if (!isSessionContextWindowAgentKind(agent) || !model) return null;
+ return { agent, providerId, model };
+}
diff --git a/apps/desktop/src/shared/sessionContextWindowBudget.ts b/apps/desktop/src/shared/sessionContextWindowBudget.ts
new file mode 100644
index 0000000000..4112e10dd8
--- /dev/null
+++ b/apps/desktop/src/shared/sessionContextWindowBudget.ts
@@ -0,0 +1,140 @@
+/**
+ * 任务级工作上下文预算(session context window budget)—— 跨 main / renderer 的共享契约。
+ *
+ * 语义:用户在**单个任务**上显式选择的上下文窗口(tokens,分母),与全局的
+ * 「自动压缩阈值百分比」(分子/触发点,`compaction-settings-store`)正交:
+ * - 预算决定「这个任务最多用多大窗口」,分档计费模型据此落在不同价带;
+ * - 百分比决定「在窗口的哪一点压缩」。
+ *
+ * 约束(与 `model-context-limit-store` 同一口径):
+ * - 预算可以低于模型路由默认(更省),也可以在目录声明的物理上限内提高;
+ * - **绝不越过目录声明的 `contextWindowMax`**,也不越过用户在同一路由上设过的
+ * 模型级「上下文上限」(两者取更紧者,见 `maker-host/model-context-settings.ts`);
+ * - NULL / undefined = 未自定义,跟随模型路由默认(老任务零影响)。
+ *
+ * 本模块只做取值合法性收敛与档位推导,不读取目录、不读 DB。
+ */
+
+/** 低于这个数压缩会在第一条消息就触发,等于让任务不可用 —— 视为误输入。 */
+export const MIN_CONTEXT_WINDOW_BUDGET = 1_000;
+/** 只挡量级荒谬的值;物理上限由目录与模型级上限负责,不在这里拦。 */
+export const MAX_CONTEXT_WINDOW_BUDGET = 100_000_000;
+
+/** 把任意输入收敛成合法预算;非法(负值 / NaN / 过小 / 非数字)返回 null = 跟随默认。 */
+export function normalizeContextWindowBudget(value: unknown): number | null {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;
+ const rounded = Math.round(value);
+ if (rounded < MIN_CONTEXT_WINDOW_BUDGET) return null;
+ return Math.min(MAX_CONTEXT_WINDOW_BUDGET, rounded);
+}
+
+/**
+ * 比例档的可见下限:占模型上限 25%/50%/100% 的档位低于它就不值得再调小
+ * (256K 级窗口只给「模型默认」一档,512K 级只给「默认 + 50%」)。
+ *
+ * 取 200K 而不是 256K:1M 级窗口的 25% 是 250K、980K 级的是 246~248K,
+ * 阈值卡在 250K/256K 会让「≈1M」这一带出现有的模型有 25% 档、有的没有;
+ * 200K 让 800K 以上的窗口行为一致,同时仍把 512K/256K 级挡在门外。
+ */
+export const MIN_PERCENT_TIER_TOKENS = 200_000;
+
+/**
+ * 比例档的百分比(以**有效上限**为基准,不是以默认窗口为基准)。
+ * 100% 档只在「有效上限 > 默认窗口」时才有意义(否则它就是默认档)。
+ */
+const TIER_PERCENTS: readonly number[] = [25, 50, 100];
+
+/** 档位最多三项(默认档 + 最多两个比例档):超出时优先保留**大比例**。 */
+const MAX_PERCENT_TIERS = 2;
+
+export interface ContextWindowBudgetOption {
+ /** 选择该档后任务使用的工作窗口(tokens);比例档是**精确**的百分比值,不取整到网格。 */
+ tokens: number;
+ /**
+ * `default` = 模型路由默认(选中时上报 null = 跟随目录,不要快照当前值);
+ * `percent` = 占**模型有效上限** 25% / 50% / 100% 的档;
+ * `current` = 已存值不在档位集合里时补的“当前档”(单选组需要匹配项)。
+ */
+ kind: 'default' | 'percent' | 'current';
+}
+
+export interface BuildContextWindowBudgetOptionsInput {
+ /** 目录里该路由的默认工作窗口(`CatalogModel.contextWindow`)。 */
+ defaultWindow: number | null | undefined;
+ /** 目录里该路由的物理上限(`CatalogModel.contextWindowMax`)。未知时传 undefined。 */
+ maxWindow?: number | null;
+ /** 用户在同一路由上设过的模型级上限;设置后它可能比物理上限更紧。 */
+ modelLimit?: number | null;
+}
+
+/**
+ * 档位的**基准**(百分比分母)= `min(目录物理上限, 模型级上限)`;
+ * 两者都缺省时退回目录默认窗口(只可能更保守,不会凭空造出高过默认值的选择)。
+ * 返回 null = 连默认窗口都拿不到(调用方不要渲染档位表)。
+ */
+export function resolveContextWindowBudgetBase(
+ input: BuildContextWindowBudgetOptionsInput,
+): number | null {
+ const positive = (value: number | null | undefined): number | null =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null;
+ const ceilings = [positive(input.maxWindow), positive(input.modelLimit)]
+ .filter((value): value is number => value !== null);
+ const ceiling = ceilings.length > 0 ? Math.min(...ceilings) : null;
+ return ceiling ?? positive(input.defaultWindow);
+}
+
+/**
+ * 档位占基准的百分比(四舍五入到整数,`1000000 → 100`):展示层用它给**每一行**(含「模型默认」
+ * 与旧值补的「当前档」)算出同一个位置上的百分比,行的形态才统一(不再「默认档绝对值在前、
+ * 比例档百分比在前」)。基准未知(null/0/非法)返回 null = 该行只显示绝对值。
+ */
+export function contextWindowBudgetTierPercent(
+ tokens: number,
+ base: number | null | undefined,
+): number | null {
+ if (typeof base !== 'number' || !Number.isFinite(base) || base <= 0) return null;
+ if (!Number.isFinite(tokens) || tokens <= 0) return null;
+ return Math.round((tokens / base) * 100);
+}
+
+/**
+ * 生成可选档位:**模型默认档 + 占有效上限 25%/50%/100% 的比例档**(最多三档)。
+ *
+ * - 基准 = `min(目录物理上限, 模型级上限)`;两者都缺省时退回目录默认窗口
+ * (此时比例档至多是默认窗口的份额,不会造出「高过默认值」的选择)。
+ * - 比例档值 = `round(基准 × 百分比)`:**精确换算、不贴到 K 网格**;值低于
+ * `MIN_PERCENT_TIER_TOKENS` 或与默认档重合的不出现。
+ * - 档数上限 3:比例档超过两个时优先保留大比例(100% → 50% → 25%)。
+ * - 结果按 tokens 升序;等于路由默认的档标为 `default`,选中它应上报 null。
+ */
+export function buildContextWindowBudgetOptions(
+ input: BuildContextWindowBudgetOptionsInput,
+): ContextWindowBudgetOption[] {
+ const positive = (value: number | null | undefined): number | null =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null;
+ const defaultWindow = positive(input.defaultWindow);
+ if (defaultWindow === null && positive(input.maxWindow) === null && positive(input.modelLimit) === null) {
+ return [];
+ }
+
+ const base = resolveContextWindowBudgetBase(input);
+ if (base === null) return [];
+
+ const percentTiers: ContextWindowBudgetOption[] = [];
+ for (const percent of TIER_PERCENTS) {
+ const tokens = Math.round((base * percent) / 100);
+ if (tokens < MIN_PERCENT_TIER_TOKENS) continue;
+ if (tokens > base) continue;
+ // 与默认档重合时不单列(默认档更强:选中它 = 跟随目录)。
+ if (defaultWindow !== null && tokens === defaultWindow) continue;
+ percentTiers.push({ tokens, kind: 'percent' });
+ }
+ // 档数上限:优先保留大比例(100% → 50% → 25%)。
+ const picked = percentTiers.slice(-MAX_PERCENT_TIERS);
+
+ const options = new Map<number, ContextWindowBudgetOption>();
+ for (const option of picked) options.set(option.tokens, option);
+ if (defaultWindow !== null) options.set(defaultWindow, { tokens: defaultWindow, kind: 'default' });
+
+ return [...options.values()].sort((a, b) => a.tokens - b.tokens);
+}
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index f742dbdbfb..14f8b4b353 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -98,6 +98,45 @@ Pi 读取独立的设置页百分比,在每次启动或恢复任务时冻结
`Agent.continue()` 语义压缩续接。Cindy 只消费 Pi 的 `compaction_start`/`compaction_end` 事件做
UI、usage 与 digest 投影,不再向 Pi 注入 host 自动 compact RPC。
+### 任务级窗口预算(分母)
+
+用户可以在单个任务上选择工作上下文窗口(tokens):有效窗口 =
+`min(任务预算 ?? 模型级上限, 模型级上限, 目录 contextWindowMax)`,由
+`maker-host/model-context-settings.ts` 的 `resolveConfiguredContextWindow` 解析,经 start options
+(`StartSessionOptions.contextWindowBudget`)下发给引擎:Claude Code 落到
+`CLAUDE_CODE_MAX_CONTEXT_TOKENS`/`CLAUDE_CODE_AUTO_COMPACT_WINDOW`,Pi 落到工作窗口与
+`compaction.reserveTokens` 的换算预算,Codex 落到 `model_context_window` 与 90% 压缩线。
+
+它是**分母**,与设置页的自动压缩阈值百分比(**分子/触发点**)正交:改变预算只改变「这个任务
+能用多大窗口」,不改变「在窗口的哪一点压缩」。任务预算不得越过目录声明的物理上限,也不得越过
+用户在同一路由上设过的模型级上限(两者取更紧者);未自定义的任务完全跟随原判定(老任务零行为
+变化)。
+
+渲染层档位表(`shared/sessionContextWindowBudget.ts` 的 `buildContextWindowBudgetOptions`)给的是
+**模型默认档 + 占有效上限 25%/50%/100% 的比例档**(最多三档,超出时优先保留大比例):比例档值按
+`round(基准 × 百分比)` 精确换算、不贴 K 网格,低于 `MIN_PERCENT_TIER_TOKENS`(200K)或与默认档
+重合的不出现;100% 档只在有效上限高于默认窗口时出现,保证「开满窗口」不丢。新增引擎或改档位规则时,
+不要退回「写死 256K/512K/1M」的固定阶梯——1.048M/1.05M 这类窗口会让固定档出现「1M 与 1.0M 并列」
+且档数涨到 4~5 档。
+
+档位表的**权威边界**来自 main(本地 `maker:get-context-window-bounds`/远程 device-link 同名 channel,
+被控端自己算):查询必须携带**界面上正在显示的路由**(`{ agent, providerId, model }`)。同一引擎内换模型是
+延迟切换(发送边界才落库),期间会话行还是旧模型 —— 不带路由会被按旧行回答,档位表与显示值一起停在旧模型上
+(实测:262K 的模型切到 1M 的模型后仍显示 262K)。缓存键也必须含 `providerId`:同一模型跨来源的上限可能不同。
+
+落库后由 main 应用:空闲任务立即关 handle、下一条消息冷重建;回合中登记 pending,回合结束后生效。
+运行期真值仍以引擎上报为准(`sessions.context_window`/`context_window_runtime` 的快照口径不变,
+任务预算不参与快照覆盖)。切模时目标窗口同样按任务预算在**目标路由**上重新收敛,避免旧模型的收敛值
+被沿用。
+
+任务预算存在 main 侧偏好文件(`session-context-budget-store.ts` → owner 隔离 userData 下的
+`session-context-budget-prefs.json`,形如 `{ budgets: { "<sessionId>": tokens } }`,null/缺条目 = 跟随
+模型默认),**不是会话列**:它不影响会话行读取、不参与任何副本同步、也不需要数据库迁移,因此同一条库
+可以在不同版本的包之间自由切换。删除任务时清理条目;fork 时把条目复制给新任务(源未自定义则不动目标,
+新任务继续跟随模型默认而不是快照一个当时的默认值)。远程任务同样由**被控端**读自己的偏好文件并在
+`maker:get-context-window-bounds` 响应里回带(`budget` / `budgetCustomized`)。
+
+本机占用 ≥ 100%,或 host/bridge 自动 compact 已确定性失败(空摘要、compact 路径上的
Claude Code/Pi 本机占用 ≥ 100%,或 host/bridge 自动 compact 已确定性失败(空摘要、compact 路径上的
invalid-request 400)时,走
`host-controlled rollover + model-controlled bounded retrieval`:host 关闭旧原生窗口、写交接并
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index c7d1e88ed6..ebfe05e306 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -34,6 +34,14 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
it('allows Review start to run on the data-owning Desktop', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:review:start')).toBe(true);
});
+
+ it('allows the read-only task context-window bounds query but no generic session write', () => {
+ // 只读边界查询:控制端据此才能在远程任务上给出「更大」的档位。
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:get-context-window-bounds')).toBe(true);
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:set-context-window-budget')).toBe(true);
+ // 通用写入口不因这条查询放开。
+ expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:sessions:update')).toBe(false);
+ });
it('allows the reduced teammate directory while keeping native configuration local', () => {
for (const channel of ['local-db:bots:list', 'local-db:bots:get']) {
expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 528c193a05..387414cf0b 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -248,6 +248,14 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
// 计划模式一级开关(runtime-only, 持久化经 dispatch persistRemoteSetting 回流)。
// 老被控端无 handler → CHANNEL_NOT_ALLOWED → 控制端 UI 本就按 capabilities.planMode 缺失隐藏入口。
'maker:set-plan-mode',
+ // 任务级工作上下文窗口档位(会话级设置, 无本机 shell/UI 副作用; 控制端 DB 是被控端那份,
+ // 写本机不生效)。被控端落库并应用到活实例。老被控端无 handler → CHANNEL_NOT_ALLOWED
+ // → 控制端提示「该设备版本不支持」并保留原档位。
+ 'maker:set-context-window-budget',
+ // 任务级窗口边界的只读查询(路由默认/物理上限/该路由模型级上限):控制端打开远程档位
+ // 菜单时拉一次,才能给出「更大」的档位。无 event.sender / 无本机副作用,不写任何存储。
+ // 老被控端无 handler → CHANNEL_NOT_ALLOWED → 控制端退回「只允许收紧」。
+ 'maker:get-context-window-bounds',
'maker:set-extra-dirs',
'maker:set-writable-dirs',
// Pi 原生分支树:只读快照 + 当前会话内导航。导航业务 handler 在被控端原子同步
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 74e83b45a8..f8845cfa4c 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1934,6 +1934,12 @@ export interface StartSessionOptions {
*/
deviceHosted?: DeviceHostedSession;
model: string;
+ /**
+ * 本任务级工作上下文预算(tokens)。host 已按目录 `contextWindowMax` 与用户在同一
+ * 路由上设过的模型级上限收敛,引擎只需直接采用;缺席 = 跟随 `resolveModelContextLimit`
+ * / 目录默认(旧行为零变化)。
+ */
+ contextWindowBudget?: number;
/**
* 本次会话显式选择的供应商来源。maker-core 只用它推导子进程凭证形态;
* 具体上游路由仍由 host 的 proxy / provider catalog 负责。
@@ -2515,13 +2521,27 @@ export interface AgentSessionHandle {
/** Actual runtime reviewer, not subscription availability. Only applies to harness-dispatched tools. */
getAutoReviewOwner?(): 'native' | 'cindy';
- /** 运行时切换模型 —— 不支持时抛 NotSupportedError。thinkingEnabled = 目标模型的思考开关意图(Pi 用它收敛切模后的 thinking level)。 */
- setModel?(model: string, opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void>;
+ /** 运行时切换模型 —— 不支持时抛 NotSupportedError。
+ * thinkingEnabled = 目标模型的思考开关意图(Pi 用它收敛切模后的 thinking level)。 */
+ setModel?(
+ model: string,
+ opts?: {
+ providerId?: string | null;
+ effort?: Effort;
+ thinkingEnabled?: boolean;
+ /**
+ * 本任务级工作上下文预算(tokens);host 已按目标路由的目录上限与模型级上限
+ * 收敛。显式传 null / undefined 时保持当前预算不变(host 在预算变化时直接
+ * 触发重建,不走热切)。
+ */
+ contextWindowBudget?: number | null;
+ },
+ ): Promise<void>;
/** Read-only Pi preflight before the host changes its persisted route or context. */
previewModelSwitch?(
model: string,
- opts?: { providerId?: string | null },
+ opts?: { providerId?: string | null; contextWindowBudget?: number | null },
): Promise<PiModelSwitchPreview>;
/**
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 63496f2e72..59797245d2 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1484,7 +1484,13 @@ export class ClaudeCodeAgent extends BaseAgent {
const resolveRemoteClaudeRoute = this.deps.resolveRemoteClaudeRoute?.bind(this.deps);
const getAuthEnv = this.deps.auth.getAuthEnv.bind(this.deps.auth);
const sdkModel = sdkModelFor(opts.model);
+// 上游:sdkEffortForModel 多带 providerId(同名模型在不同来源可声明不同 effort)。
const initialSdkEffort = this.sdkEffortForModel(opts.model, opts.effort ?? 'high', opts.providerId);
+ // 任务级工作上下文预算(tokens):host 已按目录上限与模型级上限收敛。
+ // 本任务热切模型时 host 会随 setModel 下新值;缺席保持当前值。
+ // 必须早于下面的 configuredWindows (窗口表在 buildQuery 之前就要用它,
+ // 否则会撞 TDZ)。
+ let mutableContextWindowBudget: number | null = opts.contextWindowBudget ?? null;
const binaryPath = this.deps.binaryPath;
const providerRoutedModels = this.capabilities.availableModels.filter((model) =>
isProviderRoutedModel(model.id),
@@ -1514,7 +1520,11 @@ export class ClaudeCodeAgent extends BaseAgent {
})();
const configuredWindows = [...new Set([...this.capabilities.availableModels.map((model) => model.id), opts.model])]
.flatMap((model) => {
- const limit = this.deps.resolveModelContextLimit?.(opts.providerId, model);
+ // 任务级预算优先于模型级上限:本任务的窗口就是预算(host 已收敛),
+ // 其余模型条目保持目录/上限口径。
+ const limit = model === opts.model && mutableContextWindowBudget !== null
+ ? mutableContextWindowBudget
+ : this.deps.resolveModelContextLimit?.(opts.providerId, model);
return typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0
? [{ id: sdkModelFor(model), contextWindow: limit, mirrorOneMillionSuffix: false as const }]
: [];
@@ -2825,6 +2835,10 @@ export class ClaudeCodeAgent extends BaseAgent {
]),
];
const resolveModelContextWindow = (model: string, providerId = mutableProviderId): number | undefined => {
+ // 任务级预算优先:本任务的工作窗口由用户显式选定,host 已收敛到目录上限内。
+ if (mutableContextWindowBudget !== null && Number.isFinite(mutableContextWindowBudget) && mutableContextWindowBudget > 0) {
+ return mutableContextWindowBudget;
+ }
const configured = this.deps.resolveModelContextLimit?.(providerId, model);
if (configured && Number.isFinite(configured) && configured > 0) return configured;
@@ -7345,8 +7359,18 @@ export class ClaudeCodeAgent extends BaseAgent {
return expected !== liveEnv?.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
},
- async setModel(newModel: string, setModelOpts?: { providerId?: string | null; effort?: Effort }) {
+ async setModel(
+ newModel: string,
+ setModelOpts?: {
+ providerId?: string | null;
+ effort?: Effort;
+ contextWindowBudget?: number | null;
+ },
+ ) {
if (reviewMode) return;
+ if (setModelOpts?.contextWindowBudget !== undefined) {
+ mutableContextWindowBudget = setModelOpts.contextWindowBudget;
+ }
const targetProviderId = setModelOpts?.providerId !== undefined
? setModelOpts.providerId
: mutableProviderId;
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 11e22dc2b0..8a0ea54493 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -3802,6 +3802,15 @@ assertRouteCurrent();
*/
let activeTurnModel: string | undefined = opts.model;
let activeTurnContextLimit = this.deps.resolveModelContextLimit?.(opts.providerId, opts.model) ?? null;
+ /**
+ * 任务级工作上下文预算(tokens):host 已按目录上限与模型级上限收敛。
+ * 优先于模型级上限/目录默认;host 在预算变化时直接触发重建,不走热切。
+ */
+ let mutableContextWindowBudget: number | null =
+ typeof opts.contextWindowBudget === 'number' && Number.isSafeInteger(opts.contextWindowBudget)
+ && opts.contextWindowBudget > 0
+ ? opts.contextWindowBudget
+ : null;
/**
* 本 turn 实际路由的 provider,与 activeTurnModel 同时快照。
*
@@ -5077,7 +5086,7 @@ assertRouteCurrent();
?? (localAuthPolicy === 'isolated' ? 'provider-oauth' : undefined);
const resolveCodexThreadContextWindow = this.deps.resolveCodexThreadContextWindow;
let initialCustomContextWindow = !reviewMode
- ? await resolveCodexThreadContextWindow?.(opts.providerId, opts.model) ?? null
+ ? mutableContextWindowBudget ?? await resolveCodexThreadContextWindow?.(opts.providerId, opts.model) ?? null
: null;
const customContextCatalogIdentity = (
model: string,
@@ -5095,14 +5104,17 @@ assertRouteCurrent();
let usesCustomContextHost = !opts.remoteHostId && initialCustomContextCatalogIdentity !== null;
const resolveModelSwitchCatalogIdentity = async (
newModel: string,
- setOpts?: { providerId?: string | null },
+ setOpts?: { providerId?: string | null; contextWindowBudget?: number | null },
): Promise<string | null> => {
const providerId = setOpts && Object.hasOwn(setOpts, 'providerId')
? setOpts.providerId
: mutableProviderId;
+ const nextBudget = setOpts?.contextWindowBudget !== undefined
+ ? setOpts.contextWindowBudget
+ : mutableContextWindowBudget;
const contextWindow = reviewMode
? null
- : await resolveCodexThreadContextWindow?.(providerId, newModel) ?? null;
+ : nextBudget ?? await resolveCodexThreadContextWindow?.(providerId, newModel) ?? null;
return customContextCatalogIdentity(newModel, contextWindow);
};
const modelSwitchRequiresRebuild = async (
@@ -6513,6 +6525,8 @@ assertRouteCurrent();
let customProviderThreadConfig: Record<string, unknown> = {};
const currentContextLimit = (): number | null => {
+ // 任务级预算优先:本任务的工作窗口由用户显式选定,host 已收敛到目录上限内。
+ if (mutableContextWindowBudget !== null) return mutableContextWindowBudget;
const limit = this.deps.resolveModelContextLimit?.(mutableProviderId, mutableCatalogModel ?? mutableModel);
return typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? limit : null;
};
@@ -14422,8 +14436,14 @@ assertRouteCurrent();
requiresModelSwitchRebuild: modelSwitchRequiresRebuild,
// ── Phase 3: 运行时切换 (下一 turn 才生效, 内部已是 mutable 闭包) ──
- async setModel(newModel: string, setOpts?: { providerId?: string | null }) {
+ async setModel(
+ newModel: string,
+ setOpts?: { providerId?: string | null; contextWindowBudget?: number | null },
+ ) {
if (reviewMode) return;
+ if (setOpts?.contextWindowBudget !== undefined) {
+ mutableContextWindowBudget = setOpts.contextWindowBudget;
+ }
if (await modelSwitchRequiresRebuild(newModel, setOpts)) {
const error = new Error(
'Codex model switch requires rebuilding the current session handle',
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 19cf99c8c4..2d2441687c 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
@@ -698,6 +698,99 @@ describe("PiAgent native auto-compaction ownership", () => {
await handle.close();
});
+ it("never depends on the non-official reserve RPC when a task budget changes", async () => {
+ const handle = await start();
+ knobs.rpcCalls = [];
+ await handle.setModel!("n", { contextWindowBudget: 32_000 }).catch(() => undefined);
+ expect(knobs.rpcCalls.some((call) => call.type === "set_compaction_reserve_tokens")).toBe(false);
+ expect(knobs.rpcCalls.some((call) => call.type === "refresh_models")).toBe(false);
+ await handle.close();
+ });
+
+ // 任务级预算的按模型保留量(buildPiSettingsJsonContent 的 pct=75):
+ // reserve = ceil(window - budget * 0.75)
+ const budgetReserve = (window: number, budget: number): number =>
+ Math.ceil(window - budget * 0.75);
+
+ async function startWithBudget(budget: number): Promise<AgentSessionHandle> {
+ return new PiAgent(buildDeps()).startSession({
+ sessionId: "budgeted",
+ workingDir: cwd,
+ model: "m",
+ contextWindowBudget: budget,
+ });
+ }
+
+ it("writes the task budget into every selectable model's reserve at startup", async () => {
+ const handle = await startWithBudget(50_000);
+ try {
+ // 官方 Pi 1.0 切模时按 modelOverrides 选保留量:预算必须落在**每个**可选模型上,
+ // 只写顶层 reserveTokens 会被同模型的 model-level override 盖掉。
+ expect(knobs.nativeSettings?.compaction?.modelOverrides).toMatchObject({
+ "cindy/m": { reserveTokens: budgetReserve(200_000, 50_000) },
+ "cindy/n": { reserveTokens: budgetReserve(100_000, 50_000) },
+ });
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(budgetReserve(200_000, 50_000));
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it("keeps the task budget hot-switching across models instead of demanding a rebuild", async () => {
+ const handle = await startWithBudget(50_000);
+ try {
+ // 启动快照已按预算写好每个模型的保留量 ⇒ 切到另一个模型命中同保留量,保持热切。
+ const preview = await handle.previewModelSwitch?.("n");
+ expect(["hot", "refresh"]).toContain(preview?.action);
+ await handle.setModel!("n");
+ // 切换后生效窗口仍然是本任务的预算(而不是 n 自己的模型级上限 100_000)。
+ expect(handle.getUsageSnapshot().contextWindow).toBe(50_000);
+ // 切后写盘与 ctx.workingContextWindow 仍按任务预算,不能被模型级上限顶掉。
+ expect(await handle.getContextUsage!()).toMatchObject({ maxTokens: 50_000 });
+ expect(readLatestPiSettings().compaction?.reserveTokens).toBe(budgetReserve(100_000, 50_000));
+ expect(await handle.requiresModelSwitchRebuild?.("n")).toBe(false);
+ expect(knobs.rpcCalls.some((call) => call.type === "switch_session")).toBe(false);
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it("previews a rebuild when the live reserve does not match the required one", async () => {
+ const handle = await startWithBudget(50_000);
+ try {
+ // 运行中 Pi 实际配置与要求不一致(例如被控端版本旧 / 快照被别的路径改过):
+ // 预演必须返回 rebuild,而不是谎称文件改写已生效。
+ knobs.nativeSettings = {
+ ...(knobs.nativeSettings as { compaction?: Record<string, unknown> }),
+ compaction: {
+ ...(knobs.nativeSettings?.compaction as Record<string, unknown>),
+ modelOverrides: { "cindy/n": { reserveTokens: 1 } },
+ },
+ };
+ expect(await handle.previewModelSwitch?.("n")).toMatchObject({
+ action: "rebuild",
+ reason: expect.stringMatching(/native compaction settings/),
+ });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it("previews a rebuild when the task budget changes mid-session", async () => {
+ const handle = await startWithBudget(50_000);
+ try {
+ expect(await handle.previewModelSwitch?.("n")).toMatchObject({ action: expect.any(String) });
+ expect(["hot", "refresh"]).toContain((await handle.previewModelSwitch?.("n"))?.action);
+ // 预算改成另一个值 ⇒ 要求的保留量与运行中配置不再相同,走既有重建分支。
+ await expect(
+ handle.setModel!("n", { contextWindowBudget: 10_000 }),
+ ).rejects.toThrow(/native compaction settings/);
+ expect(knobs.rpcCalls.some((call) => call.type === "set_model")).toBe(false);
+ } finally {
+ await handle.close();
+ }
+ });
+
it("rejects an unexpected runtime window rather than claiming an unapplied reserve", async () => {
const deps = buildDeps();
deps.runtimeConfig = {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 563baa47a8..e1e585d483 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -2266,6 +2266,13 @@ export class PiAgent extends BaseAgent {
/** Current model context window used to translate the Pi percentage setting. */
contextWindow?: number;
workingContextWindow?: number;
+ /**
+ * 本任务的工作上下文预算(优先于每个模型自己的上限)。非空时**为全部可选模型**
+ * 生成按该预算的 compaction.modelOverrides —— 官方 Pi 1.0 在切模时按
+ * modelOverrides 选保留量,预算只落在顶层 reserveTokens 会被同模型的 override
+ * 盖掉。写成这样之后,同预算下切到别的模型命中同保留量,保持热切。
+ */
+ sessionContextWindowBudget?: number | null;
/** Session-frozen Pi auto-compact percentage. Do not re-read the live getter. */
piCompactionPct?: number;
/** Local Pi binary frozen for this session; scopes learned native windows. */
@@ -2521,7 +2528,10 @@ export class PiAgent extends BaseAgent {
// SDK retries can swallow quota errors before the agent sees them).
const compactionModelOverrides: Record<string, { reserveTokens: number }> = {};
const addBudget = (provider: string, id: string, window: number, workingWindow?: number) => {
- const settings = JSON.parse(buildPiSettingsJsonContent(window, opts.piCompactionPct, [], workingWindow));
+ // 任务级预算优先:预算存在时**每个**可选模型都按预算生成保留量(与预演、切后写盘
+ // 同一口径),否则顶层 reserveTokens 会被同模型的 model-level override 盖掉。
+ const effectiveWorkingWindow = opts.sessionContextWindowBudget ?? workingWindow;
+ const settings = JSON.parse(buildPiSettingsJsonContent(window, opts.piCompactionPct, [], effectiveWorkingWindow));
compactionModelOverrides[`${provider}/${id}`] = { reserveTokens: settings.compaction?.reserveTokens ?? 16_384 };
};
for (const model of models) addBudget(PI_PROVIDER_ID, model.id, model.contextWindow,
@@ -2889,7 +2899,28 @@ export class PiAgent extends BaseAgent {
});
}
}
- const startupWorkingContextWindow = this.deps.resolveModelContextLimit?.(authProviderId, opts.model) ?? undefined;
+ // 任务级工作上下文预算(tokens):host 已按目录上限与模型级上限收敛。
+ // 优先于模型级上限/目录默认;变化时 host 直接触发重建,热切路径也带新值。
+ let sessionContextWindowBudget: number | null =
+ typeof opts.contextWindowBudget === 'number' && Number.isSafeInteger(opts.contextWindowBudget)
+ && opts.contextWindowBudget > 0
+ ? opts.contextWindowBudget
+ : null;
+ /**
+ * 有效工作窗口的唯一口径:任务级预算优先于模型级上限。
+ *
+ * 启动快照(顶层 reserveTokens + 每个模型的 modelOverrides)、切模预演、切后写盘与
+ * requiresModelSwitchRebuild 都必须走它 —— 任何一处漏掉预算,就会出现「预演算不出
+ * 保留量差异 → 预算静默失效」或「同预算切模被误判成需要重建」两种分叉。
+ */
+ const effectiveWorkingContextWindow = (
+ source: string | null | undefined,
+ model: string,
+ ): number | undefined =>
+ sessionContextWindowBudget
+ ?? this.deps.resolveModelContextLimit?.(source, model)
+ ?? undefined;
+ const startupWorkingContextWindow = effectiveWorkingContextWindow(authProviderId, opts.model);
const nativeModel = nativeProviders.find((provider) => provider.id === initialProvider)?.models
.find((model) => (model.wireId ?? model.id) === initialWireModel);
const learnedNativeContextWindow = !remote && sessionRuntimeBinaryPath && nativeModel?.contextWindow === undefined
@@ -3296,6 +3327,7 @@ export class PiAgent extends BaseAgent {
preview: true,
contextWindow: startupContextWindow,
workingContextWindow: startupWorkingContextWindow,
+ sessionContextWindowBudget,
piCompactionPct: sessionPiAutoCompactPct,
runtimeBinaryPath: sessionRuntimeBinaryPath,
});
@@ -3313,6 +3345,7 @@ export class PiAgent extends BaseAgent {
{
remote, fileOps, contextWindow: startupContextWindow,
workingContextWindow: startupWorkingContextWindow,
+ sessionContextWindowBudget,
piCompactionPct: sessionPiAutoCompactPct,
runtimeBinaryPath: sessionRuntimeBinaryPath,
...(guestOmitsGateway ? { omitGatewayModels: true } : {}),
@@ -6649,15 +6682,27 @@ export class PiAgent extends BaseAgent {
providerRefreshStages.delete(nonce);
}
};
- const reserveForWindow = (window: number, source: string | null | undefined, model: string): number => {
+ const reserveForWindow = (
+ window: number,
+ source: string | null | undefined,
+ model: string,
+ budget: number | null = sessionContextWindowBudget,
+ ): number => {
const settings = JSON.parse(buildPiSettingsJsonContent(window, sessionPiAutoCompactPct, [],
- this.deps.resolveModelContextLimit?.(source, model) ?? undefined));
+ budget ?? this.deps.resolveModelContextLimit?.(source, model) ?? undefined));
return settings.compaction?.reserveTokens ?? 16_384;
};
const previewPiModelSwitch = async (
model: string,
- target?: { providerId?: string | null },
+ target?: { providerId?: string | null; contextWindowBudget?: number | null },
): Promise<PiModelSwitchPreview> => {
+ // 预算必须在预演里就用**目标**值:外层预演决定要不要重建,而 setModel 会先把预算
+ // 写成新值再预演。两者用不同预算时,外层判「可热切」、内层发现保留量不匹配便抛错,
+ // 宿主此时已错过重建分支 —— 第一次发送必失败(Greptile P1)。
+ // 预演只读:不写 sessionContextWindowBudget,只把它当本次预算输入。
+ const previewBudget = target && Object.hasOwn(target, 'contextWindowBudget')
+ ? target.contextWindowBudget ?? null
+ : sessionContextWindowBudget;
const requestedProviderId = target && Object.hasOwn(target, 'providerId')
? target.providerId
: mutableProviderId;
@@ -6785,7 +6830,8 @@ export class PiAgent extends BaseAgent {
{ remote, fileOps, preview: true,
allowedModelIds: hosted?.guestProvider?.modelIds,
contextWindow: targetContextWindow ?? ctx.contextWindow ?? startupContextWindow,
- workingContextWindow: this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
+ workingContextWindow: previewBudget ?? this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
+ sessionContextWindowBudget: previewBudget,
piCompactionPct: sessionPiAutoCompactPct,
runtimeBinaryPath: sessionRuntimeBinaryPath,
packages: nativePackagePaths, disabledSkills: disabledSkillLaunch,
@@ -6824,7 +6870,7 @@ export class PiAgent extends BaseAgent {
const targetModel = nativeModel?.wireId ?? nativeModel?.id ?? model;
if (targetContextWindow && targetProvider &&
resolvePiNativeReserve(liveRuntimeSettings, targetProvider, targetModel) !==
- reserveForWindow(targetContextWindow, sourceId, model)) {
+ reserveForWindow(targetContextWindow, sourceId, model, previewBudget)) {
return { action: 'rebuild', targetContextWindow, windowVerified: false,
reason: 'Pi must load the changed native compaction settings before selecting this model' };
}
@@ -6925,8 +6971,10 @@ export class PiAgent extends BaseAgent {
nextGateway ? requestedProviderId : authProviderId,
{ remote, fileOps, contextWindow: nextDescriptor?.contextWindow ?? ctx.contextWindow,
allowedModelIds: hosted?.guestProvider?.modelIds,
- workingContextWindow: this.deps.resolveModelContextLimit?.(sourceId, model) ?? undefined,
- piCompactionPct: sessionPiAutoCompactPct, runtimeBinaryPath: sessionRuntimeBinaryPath,
+ workingContextWindow: effectiveWorkingContextWindow(sourceId, model),
+ sessionContextWindowBudget,
+ piCompactionPct: sessionPiAutoCompactPct,
+ runtimeBinaryPath: sessionRuntimeBinaryPath,
packages: nativePackagePaths,
disabledSkills: disabledSkillLaunch,
...(guestOmitsGateway ? { omitGatewayModels: true } : {}) },
@@ -7091,8 +7139,13 @@ export class PiAgent extends BaseAgent {
};
const switchModel = async (
model: string,
- setOpts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean },
+ setOpts?: { providerId?: string | null; effort?: Effort; contextWindowBudget?: number | null; thinkingEnabled?: boolean },
): Promise<void> => {
+ const requestedContextWindowBudget = setOpts?.contextWindowBudget;
+ // 任务级预算变化必须走完整重写 + switch_session 重载,不能命中同路由 no-op。
+ if (requestedContextWindowBudget !== undefined) {
+ sessionContextWindowBudget = requestedContextWindowBudget ?? null;
+ }
const requestedProviderId = setOpts && Object.hasOwn(setOpts, 'providerId')
? setOpts.providerId
: undefined;
@@ -7103,6 +7156,12 @@ export class PiAgent extends BaseAgent {
if (preview.action === 'rebuild') {
throw new Error(preview.reason ?? 'Pi model route needs a new process startup input');
}
+ // 保留量(compaction reserveTokens)只在启动快照里生效,运行期改写文件不代表
+ // Pi 已更新设置。**不得**在这里探测或调用 `set_compaction_reserve_tokens`:它不是
+ // 官方 RPC,上游已连同 `refresh_models` 一起删除调用与配套补丁(见
+ // docs/research/pi-native-model-refresh.md 与 docs/dev-rules/pi-harness.md
+ // 「只适配官方 Pi」)。任务级窗口预算因此不走热改:预算变化由宿主判定有效窗口变化后
+ // 重启引擎(createOpts 重新注入),或在预演里判定需要重建后走既有恢复分支。
if (preview.action === 'refresh') await refreshLiveCatalog(model, effectiveProviderId);
// Never let a requested native source silently fall through to Cindy's
// gateway when a provider disappeared or a model was removed.
@@ -7273,12 +7332,13 @@ export class PiAgent extends BaseAgent {
}
await this.writePiRuntimeSettings(configHome, {
fileOps, contextWindow: verifiedWindow,
- workingContextWindow: this.deps.resolveModelContextLimit?.(effectiveProviderId, model) ?? undefined,
+ workingContextWindow: effectiveWorkingContextWindow(effectiveProviderId, model),
piCompactionPct: sessionPiAutoCompactPct, packages: nativePackagePaths,
disabledSkills: disabledSkillLaunch,
});
ctx.contextWindow = verifiedWindow;
- ctx.workingContextWindow = this.deps.resolveModelContextLimit?.(effectiveProviderId, model) ?? undefined;
+ // 任务预算不能在这里被模型级上限顶掉:下一次预演要按同一个口径算保留量。
+ ctx.workingContextWindow = effectiveWorkingContextWindow(effectiveProviderId, model);
} catch (error) {
await terminateUnconfirmedCatalogReload(error);
}
@@ -8185,11 +8245,13 @@ export class PiAgent extends BaseAgent {
const contextSource = (id: string | null | undefined) =>
id == null || id === 'xd' || id === PI_PROVIDER_ID ? PI_PROVIDER_ID : id;
if (model !== mutableModel || contextSource(provider) !== contextSource(mutableProviderId)) return false;
- const window = deps.resolveModelContextLimit?.(provider, model);
- return (window ?? undefined) !== ctx.workingContextWindow;
+ return effectiveWorkingContextWindow(provider, model) !== ctx.workingContextWindow;
},
- async setModel(model: string, setOpts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void> {
+ async setModel(
+ model: string,
+ setOpts?: { providerId?: string | null; effort?: Effort; contextWindowBudget?: number | null; thinkingEnabled?: boolean },
+ ): Promise<void> {
if (reviewMode) return;
// 会话级串行闸:整段"写待切换快照 → set_model RPC → 落定/回滚"必须是一个临界区。
// 并发或连点切换(本地 + 远程控制端同时切)若交错,A 写 pending、B 写 pending、A 落定 B 的
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 92b53d40e8..6f7661e854 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -1875,7 +1875,10 @@ export class Session {
// ── 运行时切换 ─────────────────────────────────────────────────────────────
- async setModel(model: string, opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void> {
+ async setModel(
+ model: string,
+ opts?: { providerId?: string | null; effort?: Effort; contextWindowBudget?: number | null; thinkingEnabled?: boolean },
+ ): Promise<void> {
if (!this.capabilities.switchModel.supported) {
throw new NotSupportedError('switchModel', this.capabilities.switchModel);
}
@@ -1887,7 +1890,7 @@ export class Session {
async previewModelSwitch(
model: string,
- opts?: { providerId?: string | null },
+ opts?: { providerId?: string | null; contextWindowBudget?: number | null },
): Promise<PiModelSwitchPreview | undefined> {
return this.handle.previewModelSwitch?.(model, opts);
}