Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): accept saved model choices over legacy restore state
ylliuuu66d6517ea6bd4c
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex f0337cc3c8..8114e2314c 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -10265,6 +10265,59 @@ describe('Bot self control uses the same profile authority as settings', () => {describe('Teammate model selection shares profile persistence and route reconciliation', () => {+ // #7177, DB tier: older clients leave an unversioned automation baseline+ // after a permanent choice. Existing cases only change the saved model.+ // Exercise the real IPC/transaction and cold send preparation: accepting the+ // already-saved choice must fence the old restore without editing the choice.+ it('accepts the saved permanent choice over a legacy baseline after restart', async () => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const sessionId = created.session.id as string;+ const before = await invoke('local-db:bots:get', 'bot-1');+ const legacy = JSON.stringify({ scopeId: 'legacy', agentKind: 'codex', model: 'old-model',+ providerId: 'removed-provider', effort: 'medium', fastMode: false });+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(legacy, sessionId);+ const readBaseline = () => h.sqlite!.prepare('SELECT scheduled_model_baseline FROM sessions WHERE id = ?')+ .pluck().get(sessionId) as string | null;+ await invoke('local-db:bots:update', { id: 'bot-1', acceptSavedModelSelectionVersion: before.currentVersion });+ const after = await invoke('local-db:bots:get', 'bot-1');+ expect(after.capabilities).toEqual(before.capabilities);+ expect(after.currentVersion).toBe(before.currentVersion + 1);+ expect(JSON.parse(readBaseline()!)).toMatchObject({ pendingBotProfileVersion: after.currentVersion });+ const chain = await modelSettings.readEffectiveBotModelChain(after.capabilities);+ const restoreOld = vi.fn(async () => { throw new Error('removed provider must not be restored'); });+ const cold = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain, current: { agentKind: 'codex', model: 'old-model', providerId: 'removed-provider',+ effort: 'medium', fastMode: false }, hasRuntimeOverride: false, scheduledModelBaseline: readBaseline() }),+ apply: async () => { throw new Error('route not ready'); },+ onSelectionAccepted: async (id, expected) => h.sqlite!.prepare(+ 'UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ? AND scheduled_model_baseline IS ?',+ ).run(id, expected ?? null).changes === 1,+ });+ const scope = createScheduledModelScope({ read: async () => ({ profile: {+ agentKind: 'codex', model: 'old-model', providerId: 'removed-provider', effort: 'medium', fastMode: false,+ }, baseline: readBaseline() }), write: async () => {}, apply: restoreOld, isBusy: () => false, createId: () => 'unused' });+ await scope.restore(sessionId);+ expect(restoreOld).not.toHaveBeenCalled();+ await expect(cold(sessionId)).rejects.toThrow('route not ready');+ expect(JSON.parse(readBaseline()!)).toMatchObject({ pendingBotProfileVersion: after.currentVersion });+ const applied: unknown[] = [];+ const ready = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain, current: { agentKind: 'codex', model: 'old-model', providerId: 'removed-provider',+ effort: 'medium', fastMode: false }, hasRuntimeOverride: false, scheduledModelBaseline: readBaseline() }),+ apply: async (_id, route) => { applied.push(route); },+ onSelectionAccepted: async (id, expected) => h.sqlite!.prepare(+ 'UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ? AND scheduled_model_baseline IS ?',+ ).run(id, expected ?? null).changes === 1,+ });+ await ready(sessionId);+ expect(applied).toEqual([expect.objectContaining({ model: chain[0]!.model, providerId: chain[0]!.providerId })]);+ expect(readBaseline()).toBeNull();+ await expect(invoke('local-db:bots:update', { id: 'bot-1', acceptSavedModelSelectionVersion: before.currentVersion }))+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });+// #6895 P1: the previous crash test stopped at the profile commit. A subsequent// automation could recreate A before runtime refresh. DB tier: exercise the// real save transaction, send locks, reconciler and baseline writer in both@@ -10467,6 +10520,32 @@ describe('Teammate model selection shares profile persistence and route reconcilid: JSON.stringify(['pi', 'xd', model.id]), model };}+ // #7177, DB tier: an explicit same-value tool selection must reach the+ // acceptance transaction; a plain metadata edit must retain the old scope.+ it('reaccepts the same model through the teammate tool without treating a rename as recovery', async () => {+ const { service, sessionId, id } = await setupModelControl();+ const modelChain = [{ id, effort: 'low', fastMode: false }];+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: 1, modelChain }))+ .toMatchObject({ ok: true });+ const before = await invoke('local-db:bots:get', 'bot-1');+ const legacy = JSON.stringify({ scopeId: 'legacy', agentKind: 'codex', model: 'old-model',+ providerId: 'removed-provider', effort: 'medium', fastMode: false });+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(legacy, sessionId);+ const readBaseline = () => h.sqlite!.prepare('SELECT scheduled_model_baseline FROM sessions WHERE id = ?')+ .pluck().get(sessionId) as string;+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: before.currentVersion, name: 'New name' }))+ .toMatchObject({ ok: true });+ expect(readBaseline()).toBe(legacy);+ const renamed = await invoke('local-db:bots:get', 'bot-1');+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: renamed.currentVersion, modelChain }))+ .toMatchObject({ ok: true });+ const after = await invoke('local-db:bots:get', 'bot-1');+ expect(after.capabilities).toEqual(before.capabilities);+ expect(after.name).toBe('New name');+ expect(JSON.parse(readBaseline())).toMatchObject({ pendingBotProfileVersion: after.currentVersion });+ expect(after.currentVersion).toBe(renamed.currentVersion + 1);+ });+// DB regression: a per-teammate reset follows the teammate default even if// the new-task composer changes later; previously the two were coupled.it('saves its own model chain, applies it through the send resolver, and resets independently of new tasks', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex dde303e182..fad5f6bc34 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -1962,6 +1962,16 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,const db = client.drizzle;const [current] = await db.select().from(botProfiles).where(eq(botProfiles.id, id)).limit(1);if (!current) throwIpcError('NOT_FOUND', 'Bot 不存在');+ // Explicit recovery accepts the saved choice, rather than guessing that an+ // unversioned automation baseline is stale because its provider is missing.+ const acceptsSavedModel = body.acceptSavedModelSelectionVersion !== undefined;+ if (acceptsSavedModel && (!Number.isSafeInteger(body.acceptSavedModelSelectionVersion)+ || (body.acceptSavedModelSelectionVersion as number) < 1)) {+ throwIpcError('INVALID_PARAMS', 'acceptSavedModelSelectionVersion must be a positive integer');+ }+ if (acceptsSavedModel && current.currentVersion !== body.acceptSavedModelSelectionVersion) {+ throwIpcError('PRECONDITION_FAILED', '伙伴配置已更新,请重新读取后重试');+ }if (expectedVersion !== undefined && current.currentVersion !== expectedVersion) {throwIpcError('PRECONDITION_FAILED', '伙伴配置已更新,请重新读取后重试');}@@ -2066,7 +2076,8 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,// Legacy chain-only profiles gain mirrored fields during normalization.// Compare the same representation so unrelated edits do not validate stale routes.const modelSelectionChanged = botProfileModelSelectionChanged(normalizeBotModelCapabilitiesOrThrow(previous), normalizedNextConfig);- if (modelSelectionChanged) {+ const acceptsModelSelection = modelSelectionChanged || acceptsSavedModel;+ if (acceptsModelSelection) {const primary = (await readEffectiveBotModelChain(normalizedNextConfig))[0];owner.assertCurrent();if (!primary || !await validateTaskModel(primary)) {@@ -2100,7 +2111,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,owner.assertCurrent();const changesPermissions = body.capabilities != null && typeof body.capabilities === 'object'&& Object.prototype.hasOwnProperty.call(body.capabilities, 'permissions');- const modelFollowers = modelSelectionChanged ? await db.select({ sessionId: botSessionLinks.sessionId })+ const modelFollowers = acceptsModelSelection ? await db.select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks).where(and(eq(botSessionLinks.botId, id),inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread']),isNull(botSessionLinks.archivedAt))) : [];@@ -2111,7 +2122,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,owner.assertCurrent();await client.tx('bots.updateProfile', {id,- ...(modelSelectionChanged ? { clearScheduledModelBaseline: true } : {}),+ ...(acceptsModelSelection ? { clearScheduledModelBaseline: true } : {}),...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),...(patch.description !== undefined ? { description: patch.description } : {}),@@ -2184,7 +2195,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,await syncBotProfileFolder(id, folderPatch, owner.userDataDir);owner.assertCurrent();}- if (profileContentChanged) {+ if (profileContentChanged || acceptsSavedModel) {const [canonical] = await db.select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks)@@ -2198,7 +2209,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,.limit(1);owner.assertCurrent();if (canonical) requestBotRuntimeEpochRefresh(canonical.sessionId,- modelSelectionChanged ? 'model' : 'profile');+ acceptsModelSelection ? 'model' : 'profile');}const profile = await readProfile(client, id);owner.assertCurrent();diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 11a8cd4d6a..c9dc4a3bb1 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -423,11 +423,11 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersiif (permissionMode !== undefined && !['ask', 'auto', 'bypassPermissions'].includes(permissionMode)) {throw new Error('Invalid canonical permission mode');}- const latest = editsContent || permissionMode !== undefined+ const latest = editsContent || permissionMode !== undefined || p.clearScheduledModelBaseline === true? db.prepare('SELECT capabilities_json AS json, identity_source AS identity FROM bot_profile_versions WHERE bot_id = ? AND version = ?').get(id, expectedVersion) as { json: string; identity: string } | undefined: undefined;- if ((editsContent || permissionMode !== undefined) && !latest) {+ if ((editsContent || permissionMode !== undefined || p.clearScheduledModelBaseline === true) && !latest) {throw Object.assign(new Error('Bot profile version missing'), { code: 'PRECONDITION_FAILED' });}const latestConfig = latest ? asRecord(JSON.parse(latest.json), 'capabilities') : undefined;@@ -443,7 +443,10 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersielse delete nextConfig.permissions;}// A same-value settings edit can become a real change while waiting to commit.- const changed = editsContent || (permission !== undefined && latestConfig?.permissions !== permission);+ // Reaccepting the same saved model is a durable selection event too. Give+ // it a version so cold sends can distinguish it from a legacy restore.+ const changed = editsContent || p.clearScheduledModelBaseline === true+ || (permission !== undefined && latestConfig?.permissions !== permission);const nextVersion = changed ? expectedVersion + 1 : expectedVersion;if (changed) {fields.push('current_version = ?');diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 571ec0c630..341a4aa36b 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -336,6 +336,9 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {}ctx.assertOwner();await updateBotProfile({ id: ctx.botId,+ // Supplying a model selection explicitly accepts it even when its+ // value is unchanged; unrelated profile edits retain automation state.+ ...(modelChain !== undefined ? { acceptSavedModelSelectionVersion: input.expectedVersion } : {}),...(input.name !== undefined ? { name: input.name } : {}),...(input.description !== undefined ? { description: input.description } : {}),...(input.identitySource !== undefined ? { identitySource: input.identitySource } : {}),diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex f57db17e03..4b3046139b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -16638,11 +16638,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},apply: async (sessionId, route, current) => {await stageSessionRouteSelection(sessionId, { ...route, agentDeviceId: route.agentDeviceId ?? null }, current.agentKind);- // A changed permanent companion choice supersedes the automation's saved- // preference, even if it selects the already-running temporary model.- // Profile saves retire it atomically in the DB; other route changes retire- // it only after staging succeeds. Never detach IM default following.- await updateScheduledPreference(sessionId, null);// Consume the same model/Harness intent as the normal send path. Its// verified window protection and history handoff also apply here; a Bot// settings save need not wait for a second user message. Busy runtimes@@ -16650,6 +16645,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (isSessionIdleForRouteApply(sessionId)) {await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, { bootstrapAfterSwitch: true });}+ // Keep the durable acceptance marker if the switch failed or still waits+ // for a safe boundary. Staging alone must not lose recovery after restart.+ if (agentSwitchPending.get(sessionId)) {+ throw new ScheduledModelSelectionBusyError('Saved companion route is still pending');+ }+ await updateScheduledPreference(sessionId, null);},});diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex fa003519f5..d564708b9b 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,16 @@# 跨端协议兼容+## 接受已保存的伙伴模型++既有 `local-db:bots:update` 可选接收 `acceptSavedModelSelectionVersion`(读取到的正整数+Profile 版本)。它是显式接受模型的意图;宿主重新校验模型可用性、版本及账号,在同一保存+事务中推进版本并为跟随专线登记 `pendingBotProfileVersion`。旧版无标记 baseline 不因普通+重试、能力修改或来源不可用而被删除;路由切换尚未就绪时保留恢复记录。++不新增 channel 或权限。旧调用方省略字段保持原有行为;旧宿主不支持该恢复意图,不能将+返回成功视为完成恢复,必须读回版本及发送结果。现有 `update_teammate_profile` 显式提交+`modelChain` 时走同一接受入口,包括重复选择当前值;省略模型字段不改变恢复状态。+## 任务链接保留所属电脑任务查询返回可选 `sessionUrl`,沿用 `cindy://session/<id>?device=<deviceId>`。diff --git a/docs/e2e-evidence/issue-7177-legacy-model-recovery/README.md b/docs/e2e-evidence/issue-7177-legacy-model-recovery/README.mdnew file mode 100644index 0000000000..bf7fb9a250--- /dev/null+++ b/docs/e2e-evidence/issue-7177-legacy-model-recovery/README.md@@ -0,0 +1,71 @@+# #7177:接受已保存模型的旧状态恢复验证++日期:2026-10-26。代码基线 `806b459005cbf21fb40721d35af91ff7e7f776c6`,包含 #6759 和 #6950。+修复位于本记录所属提交;推送后的运行回归另行记录其源码 SHA。++## 问题与修复++旧包 0.1.115 的例行模型恢复会按本机目录校验旧来源;已合并修复补齐了共享执行位置和永久保存的版本标记。+剩余缺口是存量无版本标记的恢复记录:即使永久配置已经保存,普通发送仍先尝试恢复旧来源。+本次复用 `local-db:bots:update`,用 `acceptSavedModelSelectionVersion` 显式接受已读取的永久选择。+同值接受也校验可用性、取得发送锁、在原事务中推进版本并写恢复标记;切换未就绪时保留标记。+现有伙伴工具显式提交完整 `modelChain` 同样走此分支;普通改名不改变恢复状态。++没有新增数据库 migration、IPC channel、UI 按钮或自动 fallback。++## 自动化验证++| 检查 | 实际结果 |+| --- | --- |+| 修复前最小回归 | exit 1:接受后版本仍为 1,预期为 2 |+| 四个相关文件 | 765 通过、1 失败;新增测试误用返回字段 `displayName`,已改为真实字段 `name` |+| 修正后两项新增回归 | exit 0:2 通过;70.51 秒,其中测试体 522ms,现有大文件收集 68.19 秒 |+| `pnpm check:test-hygiene` | exit 0 |+| Desktop 等效类型检查 | exit 0,615.72 秒,无 TypeScript 诊断 |+| `git diff --check` | exit 0 |++四文件命令:++```sh+pnpm --filter desktop exec vitest run \+ src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts \+ src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts \+ src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts \+ src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts --maxWorkers=1+```++修正后定向命令(上述第一文件):`-t 'accepts the saved permanent choice|reaccepts the same model'`。+首轮 package 类型检查 exit 1、无诊断,不计通过;等效重跑:++```sh+NODE_OPTIONS=--max-old-space-size=12288 node node_modules/typescript/bin/tsc --noEmit -p apps/desktop/tsconfig.json+```++新增用例属于 DB tier,通过真实配置 IPC、事务和既有冷态恢复/路由协调器验证:同值接受、冷态跳过旧来源、失败保留、成功清理、过期版本拒绝,以及工具同值提交与普通改名的区别。+没有新增测试文件或重复导入;运行时间主要由既有大型测试文件的加载决定。++## 提交前真实运行++在本 worktree 的 Global 独立开发实例上验证,`desktop-whoami` 返回 `DESKTOP_DEV_VERDICT=ready`、`commitVerified=true`。+启动器首次超时,实例随后完成初始化;未把超时当作成功。++只读提取旧正式数据中的模型配置和实际无标记恢复记录,在独立 QA 伙伴上建立模型状态副本。+未复制聊天、身份提示词或凭证,未将开发构建连接正式数据库。这是旧正式模型状态副本验收,**不是整个正式库副本或正式安装包升级验收**。++| 场景 | 实际结果 |+| --- | --- |+| 历史永久选择 Pi + 旧 Codex 恢复记录 | 真实输入框发送前报旧来源不可用;队首保留 1 条,未回复 |+| 显式接受已保存选择 | 配置版本 1 → 2,capabilities 完全不变 |+| 现有重试按钮处理原输入 | 实际回复 `QA7177_LEGACY_SAVED_MODEL_OK`;原 clientId 仅落库 1 条 |+| 恢复后手动例行 | history.status=success,实际结果 `QA7177_LEGACY_ROUTINE_OK` |+| 例行后的普通输入 | 实际回复 `QA7177_LEGACY_AFTER_ROUTINE_OK` |+| 当前永久共享 Codex + 同一旧恢复记录 | 接受后实际回复 `QA7177_CURRENT_SAVED_ROUTE_OK`;provider 与共享位置保持原值 |++完成时队列为空、error/recovery 为 null、执行结束、旧 baseline 清空;例行保持停用,仅手动触发。+原正式模型、provider、共享位置及 baseline 再次只读核对均未改变。++## 边界与风险++原正式库 schema=129,开发构建 migration 到 131;依照数据库规则,未用开发构建升级正式 profile。+未更新、替换或重启正式 Cindy。未声称整仓测试、远端 CI、跨账号全套验收或正式包已通过。+本记录已脱敏,不公开原始任务、伙伴、执行设备、来源标识或账号数据。diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.mdindex bf84a93254..b22ed73604 100644--- a/docs/product-rules/agent-user-parity.md+++ b/docs/product-rules/agent-user-parity.md@@ -60,6 +60,7 @@| 伙伴 | 发现伙伴、伙伴间消息 | 有 | 有 || 伙伴 | 自身关联项目:列出、添加与移除(原有文件工具按需读资料) | 有 | 无(远程设置界面可管理) || 伙伴 | 资料、能力、待办、后台任务 | 有 | 无 |+| 伙伴 | 显式重新接受已保存模型,恢复旧版遗留的自动模型记录 | 有(`update_teammate_profile` 显式提交完整 `modelChain`,即使值未变) | 无(远程设置 IPC 可按版本接受,不等于跨电脑 Agent 工具) || 伙伴 | 发现与选择 Codex Apps 连接器(继承默认保留,显式 MCP 白名单可收窄) | 有(能力工具) | 无(SSH Codex 不提供) || 伙伴 | 按已证实归属搜索跨渠道聊天、按最近活动列出旧任务 | 有 | 有(历史查询,两端需支持筛选参数) || 伙伴 | 查看自己的本机 IM 连接分配与状态 | 有 | 无 |