Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Greptile 2026-10-24 两条 P1(#4598)
Zhang Yunjin64450221263c
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex c853561e59..42e0cfcd67 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -24,6 +24,19 @@ const bootstrapSource = readFileSync(bootstrapSourcePath, 'utf8').replace(/\r\n?const goalStorageSourcePath = resolve(__dirname, '..', 'goal-host', 'storage.ts');const goalStorageSource = readFileSync(goalStorageSourcePath, 'utf8').replace(/\r\n?/g, '\n');+/**+ * 任务窗口预算的对账函数(源切片,供下面两条用例直接执行):+ * 依赖全部注入,避免为了两个记账断言去搭整套 register harness。+ */+function loadBudgetReconciler() {+ const start = source.indexOf(' const reconcileSessionContextWindowBudgetUnderLock = async (');+ const end = source.indexOf(' sessionContextWindowBudgetApplier = async (sessionId, change) => {', start);+ if (start < 0 || end < 0) throw new Error('budget reconciler source changed');+ const code = source.slice(start, end);+ const js = transpileModule(code, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;+ return { code, js };+}+describe('maker:event hot path ordering', () => {it('finishes mandatory runtime cleanup when optional remote refresh throws at an owner boundary', () => {const start = source.indexOf('function cleanupClosedSessionRuntime(');@@ -1204,3 +1217,50 @@ function readEventModule(name: string): string {.replace(/\r\n?/g, '\n').replaceAll('deps.', '');}++describe('session context window budget reconciler', () => {+ it.each([+ ['applied', true],+ ['deferred', false],+ ] as const)('records the applied budget only after %s reaches the live session', async (status, recorded) => {+ // 回合中登记的重建会返回 deferred(只挂了 pending)。这时若就记 dedup,之后的同值+ // 对账全被挡掉;而 pending 又可能被「重选当前模型」清掉(SET_MODEL 成功路径会+ // agentSwitchPending.clear),预算就永久不生效(Greptile P1,2026-10-24)。+ const { code, js } = loadBudgetReconciler();+ const applied = new Map<string, number | null>();+ const applyRuntimeSetModelChange = vi.fn(async () => ({ status }));+ 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,+ contextWindowBudgetChangesEffectiveWindow: () => true,+ getPendingCredentialSwitchTarget: () => null,+ registerPendingCredentialSwitchForSession: vi.fn(),+ applyRuntimeSetModelChange,+ runtimeMutationDeps: () => ({}),+ log: { debug: vi.fn(), info: vi.fn() },+ };+ expect(code).toContain("result.status === 'applied'");+ const reconcile = new Function(+ ...Object.keys(deps),+ `${js}; return reconcileSessionContextWindowBudgetUnderLock;`,+ )(...Object.values(deps)) as (sessionId: string, previous: number | null) => Promise<void>;++ await reconcile('task-1', null);+ expect(applyRuntimeSetModelChange).toHaveBeenCalledOnce();+ if (recorded) expect(applied.get('task-1')).toBe(300_000);+ else expect(applied.has('task-1')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex c0741e3125..96d68997ba 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -915,6 +915,15 @@ describe('local-db:sessions:update handler wiring', () => {expect(isSessionContextWindowBudgetCustomized('cc-local')).toBe(false);});+ 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)。+ h.captureOwnerScope = true;+ h.ownerCurrent = false;+ await invokeUpdate('cc-local', { contextWindowBudget: 300_000 });+ expect(readSessionContextWindowBudget('cc-local')).toBeNull();+ });+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/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 69fe53df6b..b14eba69f3 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -2493,7 +2493,12 @@ export async function updateSessionInDb(// 广播之后再把新预算应用到活实例:UI 先看到新选择,重建/延迟登记失败也不回滚设置。// 只有本函数会写这份偏好,不存在平行写入链路;回调缺失(宿主未注入)时静默跳过,// 新值在下次启动/恢复时按 start options 生效。- if (hasContextWindowBudgetChange) {+ //+ // 账号边界必须在这里**重新**核对:偏好文件按「当前」账号的 userData 解析+ // (ownerScopedUserDataPath),而 DB 更新是 await 出来的 —— 期间切账号的话,+ // 这条过期请求会把原任务的预算写进新账号的文件,原账号反而没保存+ // (Greptile P1,2026-10-24;相邻广播本来就是同一口径)。+ if (hasContextWindowBudgetChange && isOwnerScopeCurrent(ownerScope)) {const nextContextWindowBudget = writeSessionContextWindowBudget(sid, p.contextWindowBudget ?? null);if (opts.applyContextWindowBudget) {try {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d43fa7f700..f95c8c7beb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -6486,89 +6486,115 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)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),+ /**+ * 预算对账(**锁内**,调用方已持 send 锁):把偏好文件里的当前预算落到活实例。+ *+ * 两条调用路径共用:+ * - 偏好变更通知(回合中登记 pending、空闲直接重建);+ * - 发送边界重放 —— 回合中登记的重建意图可能被随后的「重选当前模型」清掉+ * (SET_MODEL 成功路径会 `agentSwitchPending.clear`),而预算通知只来一次,+ * 光靠通知就再也没有第二次机会,活实例会永久停在旧窗口(Greptile P1,2026-10-24)。+ */+ const reconcileSessionContextWindowBudgetUnderLock = async (+ sessionId: string,+ previous: number | null,+ ): Promise<void> => {+ const live = getMakerIfReady()?.getSession(sessionId);+ if (!live) {+ appliedContextWindowBudgets.delete(sessionId);+ return;+ }+ // 已应用(偏好文件里的当前值 == 记账值)→ 立即返回:发送边界每次都会调这里,+ // 正常路径必须只有一次内存/文件比较,不能为此多查一次会话行。+ 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;+ }+ // 会话行(路由快照)必须在**锁内**重读:锁外读到的是「加锁前」的路由,若期间用户切了模,+ // 有效窗口判定会按旧路由算成「没变」而漏掉一次必需的重建(第 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();+ // 并发改档位(双窗口、连点)时两条通知会乱序到达:`latestBudget` 取的是**当下偏好文件+ // 里的值**(上面已读),让 live 与落库终值对齐(否则后执行的旧通知会把活实例重建回旧窗口)。+ // 有效窗口(预算与模型级上限取更紧者)没变就不重建:避免每次改档位都关活实例。+ if (!contextWindowBudgetChangesEffectiveWindow({+ catalog, agent, providerId, modelId: row.model,+ previous, next: latestBudget,+ })) {+ log.debug('session context window budget does not change the effective window', {+ sessionId, 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,+ next: latestBudget, targetModel: pendingTarget.model,+ });+ return;+ }+ // 无凭证 pending 时(含仅轴 pending / runtime-control 显式路由 pending / 跨引擎切换):+ // 以**当前 live 路由**补一个 forceSessionRebuild。取舍说明:这几套意图各自存在别的 store,+ // 这里不会覆盖它们,但确实会多登记一条「当前引擎」的凭证 pending —— 它与跨引擎意图在同一个+ // 收口边界先后生效,最坏是多一次关会话/重建(写入的路由就等于 live 路由,不会复活旧路由);+ // 换来的是「跨引擎切换被取消时预算仍会生效」这个更强保证(第 3 轮 review 的反向要求)。+ // 少登记一条会反过来丢掉那个保证,所以这里选择保留登记。+ const result = await applyRuntimeSetModelChange({+ ...runtimeMutationDeps(),+ sessionId,+ model: live.model,+ providerId: getSessionProvider(sessionId),+ forceSessionRebuild: true,+ });+ // **只有真正落到活实例**才算已应用:回合中这条路返回 `deferred`(只登记了+ // pending),此时记 dedup 会让后续同值对账全部被挡掉;一旦那条 pending 被+ // 随后的「重选当前模型」清掉,预算就永久不生效(Greptile P1,2026-10-24)。+ // 不记的话发送边界的对账会一直重试,直到新实例确实采用预算。+ if (result.status === 'applied') {appliedContextWindowBudgets.set(sessionId, latestBudget);log.info('session context window budget applied via runtime rebuild', {- sessionId, previous: change.previous, next: latestBudget,+ sessionId, previous, next: latestBudget,});+ return;+ }+ log.info('session context window budget rebuild deferred to the send boundary', {+ sessionId, previous, next: latestBudget,});};+ sessionContextWindowBudgetApplier = async (sessionId, change) => {+ const activeMaker = getMakerIfReady();+ if (!activeMaker || !activeMaker.getSession(sessionId)) return;+ await withSendToSessionLock(sessionId, () => (+ reconcileSessionContextWindowBudgetUnderLock(sessionId, change.previous)+ ));+ };setModelContextRuntimeRefreshListener(() => {if (!getMakerIfReady()) return;@@ -11404,6 +11430,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)signal,});}+ // 预算对账的重放:回合中登记的预算重建意图可能被「重选当前模型」清掉,而预算+ // 变更通知只来一次 —— 不在这里补一次,活实例会一直按旧窗口跑(Greptile P1)。+ // 已应用(dedup == 偏好值)时内部立即返回,多发一条消息只多一次内存比较。+ stage = 'direct-send:reconcileContextWindowBudget';+ await reconcileSessionContextWindowBudgetUnderLock(+ sessionId,+ appliedContextWindowBudgets.get(sessionId) ?? null,+ );let resolvedSelection: ScheduledModelSelection | undefined;if (selection) {stage = 'direct-send:applyScheduledModelSelection';