Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 桌面发送边界也重放预算 + 偏好写失败降级(#4598)
Zhang Yunjin287d52b4d7b0
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 5bb67f147c..f2f97a194c 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -1363,13 +1363,62 @@ describe('session context window budget reconciler', () => {expect(pending.has('task-1')).toBe(true);});- it('replays a budget at the send boundary only when a rebuild is still pending', () => {+ it.each([+ ['no boundary replay without a pending intent', false, 0],+ ['replays at the send boundary when an intent is pending', true, 1],+ ] as const)('replay gate: %s', async (_label, intentPending, expectedReconciles) => {// 任务启动时 create opts 已带上偏好预算(applySessionContextWindowBudgetToCreateOpts),// 此时 dedup 还没有条目 —— 若按「dedup 缺失」重放,首条直发会把刚配置好的实例再关一次- // (首条消息多等一次冷启动;Greptile P2,2026-10-24)。- const boundary = source.slice(source.indexOf("stage = 'direct-send:"));- expect(boundary).toContain('if (pendingSessionContextWindowBudgetReconciles.has(sessionId)) {');- expect(boundary.indexOf('pendingSessionContextWindowBudgetReconciles.has(sessionId)'))- .toBeLessThan(boundary.indexOf('reconcileSessionContextWindowBudgetUnderLock('));+ // (Greptile P2,2026-10-24)。执行真实的 replay 函数,而不是断言源码文本。+ const { js } = loadBudgetReconciler();+ const applied = new Map<string, number | null>();+ const pending = new Set<string>(intentPending ? ['task-1'] : []);+ const applyRuntimeSetModelChange = vi.fn(async () => ({ status: 'applied' as const }));+ const deps = {+ getMakerIfReady: () => ({ getSession: () => ({ model: 'grok-4.6' }) }),+ getDbClient: () => ({+ drizzle: {+ select: () => ({+ from: () => ({ where: () => ({ limit: async () => [{ agentKind: 'cc', model: 'grok-4.6', providerId: 'xd' }] }) }),+ }),+ },+ }),+ sessions: { agentKind: 'agentKind', model: 'model', providerId: 'providerId', id: 'id' },+ eq: () => ({}),+ dbToMakerAgentKind: () => 'claude-code',+ getSessionProvider: () => 'xd',+ getActiveCatalog: () => ({}),+ readStoredSessionContextWindowBudget: async () => 300_000,+ appliedContextWindowBudgets: applied,+ pendingSessionContextWindowBudgetReconciles: pending,+ contextWindowBudgetChangesEffectiveWindow: () => true,+ getPendingCredentialSwitchTarget: () => null,+ registerPendingCredentialSwitchForSession: vi.fn(),+ applyRuntimeSetModelChange,+ runtimeMutationDeps: () => ({}),+ withSendToSessionLock: (_id: string, fn: () => Promise<void>) => fn(),+ log: { debug: vi.fn(), info: vi.fn() },+ };+ const replay = new Function(+ ...Object.keys(deps),+ `${js}; return replayPendingSessionContextWindowBudgetUnderLock;`,+ )(...Object.values(deps)) as (sessionId: string, before?: () => void) => Promise<void>;++ const before = vi.fn();+ await replay('task-1', before);+ expect(applyRuntimeSetModelChange).toHaveBeenCalledTimes(expectedReconciles);+ expect(before).toHaveBeenCalledTimes(expectedReconciles);+ });++ it('replays the budget from the desktop send transaction, not only from direct sends', () => {+ // 桌面 UI 发送(createMakerSendTransaction 的 applyPendingAgentSwitch)必须与直发+ // 边界共用同一条重放:只挂直发的话,「回合中改预算 → 选择器点选清掉 pending → 从界面+ // 发消息」这条最普通的路径永远等不到预算生效(GLM-5.3 独立审查,2026-10-24)。+ const desktopSend = source.slice(+ source.indexOf('applyPendingAgentSwitch: async (sessionId, options) => {'),+ source.indexOf('providerGroupService?.beforeSend(', source.indexOf('applyPendingAgentSwitch: async (sessionId, options) => {')),+ );+ expect(desktopSend).toContain('applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId)');+ expect(desktopSend).toContain('replayPendingSessionContextWindowBudgetUnderLock(sessionId)');});});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 96d68997ba..b2b86dab22 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -27,6 +27,7 @@ import { isWorktreeMoveBlockedError } from '../../../../shared/worktreeMoveGuardimport {isSessionContextWindowBudgetCustomized,readSessionContextWindowBudget,+ writeSessionContextWindowBudget,} from '../../../maker-host/session-context-budget-store.js';type SessionRouteLockMock = SessionRouteLock &@@ -178,6 +179,11 @@ vi.mock('../../../turn-change-set/store.js', () => ({vi.mock('../../../cindy-brain/index.js', () => ({notifyGhostSessionEvent: vi.fn(),}));+// 偏好文件不可读时 store 会拒绝写(保留坏文件给人工修):个别用例需要让它抛错。+vi.mock('../../../maker-host/session-context-budget-store.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../../maker-host/session-context-budget-store.js')>();+ return { ...actual, writeSessionContextWindowBudget: vi.fn(actual.writeSessionContextWindowBudget) };+});import {applyAgentSwitchToSessionRow,@@ -915,6 +921,20 @@ describe('local-db:sessions:update handler wiring', () => {expect(isSessionContextWindowBudgetCustomized('cc-local')).toBe(false);});+ it('keeps the row update when the budget store refuses to write', async () => {+ // 偏好文件不可读时 store 拒绝写(保留坏文件给人工修)。行更新与广播都已提交,+ // 预算失败不能带走同一个 patch 里的其它字段,也不能让 IPC 抛错盖掉已生效的改名+ // (GLM-5.3 独立审查,2026-10-24)。+ vi.mocked(writeSessionContextWindowBudget).mockImplementationOnce(() => {+ throw new Error('session context budget settings file is unreadable');+ });+ await expect(invokeUpdate('cc-local', {+ contextWindowBudget: 300_000,+ title: 'renamed-despite-budget-failure',+ })).resolves.toBeDefined();+ expect(readSessionContextWindowBudget('cc-local')).toBeNull();+ });+it('does not write the context window budget into the next account after an owner change', async () => {// 偏好文件按「当前」账号的 userData 解析,而 DB 更新是 await 出来的:保存期间切账号// 时,过期请求不得把原任务的预算写进新账号的文件(Greptile P1,2026-10-24)。diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex b14eba69f3..2455576988 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -905,9 +905,6 @@ export async function persistSessionFields(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], {@@ -918,6 +915,23 @@ export async function persistSessionFields(} else if (!hasBudgetChange) {return;}+ // 预算写偏好文件放在行更新**之后**:偏好文件不可读时 store 会拒绝写(保留坏文件给+ // 人工修),若先写就会让同一个 patch 里的其它字段(改名、归档…)整包失败。+ let budgetWritten = false;+ let nextContextWindowBudget: number | null = null;+ if (hasBudgetChange) {+ try {+ nextContextWindowBudget = writeSessionContextWindowBudget(+ sessionId, (clean.contextWindowBudget as number | null) ?? null,+ );+ budgetWritten = true;+ } catch (error) {+ console.warn('[sessions] write context window budget failed; other fields already saved', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }let runtimeProjection = {};if (['model', 'providerId', 'effort', 'fastMode'].some((key) => key in clean)) {const [row] = await db.select({@@ -931,7 +945,7 @@ export async function persistSessionFields(}if (isOwnerScopeCurrent(ownerScope)) broadcastSessionPatched(sessionId, { ...clean, ...runtimeProjection }, ownerScope);// 远程 set-* 落库后同样要把新预算应用到被控端活实例(语义与 updateSessionInDb 一致)。- if (hasBudgetChange && registeredSessionIpcOpts.applyContextWindowBudget) {+ if (budgetWritten && registeredSessionIpcOpts.applyContextWindowBudget) {try {await registeredSessionIpcOpts.applyContextWindowBudget(sessionId, {previous: previousContextWindowBudget,@@ -2499,8 +2513,21 @@ export async function updateSessionInDb(// 这条过期请求会把原任务的预算写进新账号的文件,原账号反而没保存// (Greptile P1,2026-10-24;相邻广播本来就是同一口径)。if (hasContextWindowBudgetChange && isOwnerScopeCurrent(ownerScope)) {- const nextContextWindowBudget = writeSessionContextWindowBudget(sid, p.contextWindowBudget ?? null);- if (opts.applyContextWindowBudget) {+ // 偏好文件不可读时 store 会拒绝写:行更新与广播都已提交,这里只能降级为+ // 「预算未保存」(不回滚其它字段、也不让 IPC 报错盖掉已生效的改名等)——+ // 用户在档位卡上会看到旧值,重设一次即可(GLM-5.3 独立审查,2026-10-24)。+ let nextContextWindowBudget: number | null = null;+ let budgetWritten = false;+ try {+ nextContextWindowBudget = writeSessionContextWindowBudget(sid, p.contextWindowBudget ?? null);+ budgetWritten = true;+ } catch (error) {+ console.warn('[sessions] write context window budget failed; row update already applied', {+ sessionId: sid,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (budgetWritten && opts.applyContextWindowBudget) {try {await opts.applyContextWindowBudget(sid, {previous: previousContextWindowBudget,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.tsindex 23db76b3f6..f897f0a3b1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts@@ -204,6 +204,7 @@ describe('complete selection commit boundaries', () => {applyScheduledProfile: apply, contextOverflowRolloverHolder: null,// 发送边界的预算对账(register.ts):本用例只关心路由选择,注入 no-op。reconcileSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),+ replayPendingSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),appliedContextWindowBudgets: new Map<string, number | null>(),pendingSessionContextWindowBudgetReconciles: new Set<string>(),});@@ -243,6 +244,7 @@ describe('complete selection commit boundaries', () => {reconcileBotModelRoute: vi.fn(), applyPendingAgentSwitchIfIdle, isUserPendingAgentSwitchIntent,agentSwitchDeps: deps, contextOverflowRolloverHolder: null,reconcileSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),+ replayPendingSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),appliedContextWindowBudgets: new Map<string, number | null>(),pendingSessionContextWindowBudgetReconciles: new Set<string>() });const sending = directSend('queued-picker');@@ -343,6 +345,7 @@ describe('Orca model-only picker intent admission', () => {acquireSendToSessionLock: acquire, reconcileBotModelRoute: vi.fn(),applyPendingAgentSwitchIfIdle, isUserPendingAgentSwitchIntent, agentSwitchDeps: deps, contextOverflowRolloverHolder: null,reconcileSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),+ replayPendingSessionContextWindowBudgetUnderLock: vi.fn(async () => {}),appliedContextWindowBudgets: new Map<string, number | null>(),pendingSessionContextWindowBudgetReconciles: new Set<string>(),});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 90f8f1359e..68c24ed7a4 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -6620,6 +6620,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)reconcileSessionContextWindowBudgetUnderLock(sessionId, change.previous)));};+ /**+ * 预算重放(**锁内**,调用方持 send 锁):只在有未完成意图时跑一次对账。+ *+ * 两条发送边界共用:直发(IM / Goal / 定时任务)与**桌面 UI 发送事务**+ * (createMakerSendTransaction 的 applyPendingAgentSwitch)。只做直发那一处的话,+ * 回合中改预算、随后在模型选择器里点选而清掉 pending 的用户——也就是最普通的那条+ * 操作路径——永远等不到预算生效(GLM-5.3 独立审查,2026-10-24)。+ */+ const replayPendingSessionContextWindowBudgetUnderLock = async (+ sessionId: string,+ before?: () => void,+ ): Promise<void> => {+ if (!pendingSessionContextWindowBudgetReconciles.has(sessionId)) return;+ before?.();+ await reconcileSessionContextWindowBudgetUnderLock(+ sessionId, appliedContextWindowBudgets.get(sessionId) ?? null,+ );+ };setModelContextRuntimeRefreshListener(() => {if (!getMakerIfReady()) return;@@ -11462,13 +11480,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 只在**有未完成意图**时重放:任务启动本就把偏好预算带进了 create opts,此// 时 dedup 还没有条目,按「dedup 缺失」判断会把刚配置好的实例再关一次// (Greptile P2,2026-10-24)。- if (pendingSessionContextWindowBudgetReconciles.has(sessionId)) {+ await replayPendingSessionContextWindowBudgetUnderLock(sessionId, () => {stage = 'direct-send:reconcileContextWindowBudget';- await reconcileSessionContextWindowBudgetUnderLock(- sessionId,- appliedContextWindowBudgets.get(sessionId) ?? null,- );- }+ });let resolvedSelection: ScheduledModelSelection | undefined;if (selection) {stage = 'direct-send:applyScheduledModelSelection';@@ -17977,6 +17991,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)applyPendingAgentSwitch: async (sessionId, options) => {if (!options?.scheduled) await scheduledModelScope.restore(sessionId);await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId);+ // 桌面发送也是「消息真正发出去」的边界:回合中登记、随后被模型选择器取消的预算+ // 重建必须在这里补一次(调用方已持 send 锁)。+ await replayPendingSessionContextWindowBudgetUnderLock(sessionId);// Queued Orca delivery and resume both use this transaction. A failed// cross-engine preparation may retain its intent without throwing.if (agentSwitchPending.get(sessionId)) {