Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 收紧模型开关并发写入边界
liugaowei6a63a1cc27d6
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex 346c19508c..08859a13ed 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -268,7 +268,7 @@ describe('claimLegacyOwnerNamespace', () => {expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(true);});- it('prunes a schema-v1 record after proving that its PID was reused', async () => {+ it('does not delete a registry record after proving that its PID was reused', async () => {const root = await tempRoot();const startedAtMs = 1_000_000;const recordPath = path.join(root, '.dev-instances', '4242.json');@@ -288,54 +288,8 @@ describe('claimLegacyOwnerNamespace', () => {}),);- await expect(fs.access(recordPath)).rejects.toMatchObject({ code: 'ENOENT' });expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(true);- });-- it('keeps a replacement record that changes during stale-PID cleanup', async () => {- const root = await tempRoot();- const startedAtMs = 1_000_000;- const recordPath = path.join(root, '.dev-instances', '4242.json');- await writeDevInstanceRecord(root, 4242, root, {- instanceId: 'stale-instance',- startedAtMs,- });- const originalRaw = await fs.readFile(recordPath, 'utf-8');- const replacementRaw = JSON.stringify({- schemaVersion: 1,- instanceId: 'replacement-instance',- pid: 4242,- userDataDir: root,- startedAtMs: startedAtMs + 1,- });- let recordReads = 0;-- await __testing.warmStaleProcessProvenance(- root,- realFsDeps(- root,- {- isPidAlive: (pid) => pid === 4242,- readProcessIdentity: () => ({- startedAtMs: startedAtMs + 120_000,- command: 'C:\\Windows\\System32\\OpenConsole.exe --server',- }),- },- {- readFile: async (file: string) => {- if (file !== recordPath) return fs.readFile(file, 'utf-8');- recordReads += 1;- if (recordReads === 1) return originalRaw;- await fs.writeFile(recordPath, replacementRaw, 'utf-8');- return replacementRaw;- },- },- ),- );-- expect(recordReads).toBeGreaterThanOrEqual(2);await expect(fs.access(recordPath)).resolves.toBeUndefined();- expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);});it('keeps local startup fail-closed when provenance warmup cannot read identity', async () => {@@ -3171,7 +3125,11 @@ describe('hasExclusiveSharedLegacyUserDataAccess', () => {it('reuses async stale-pid proof in sync guards and invalidates it when the record changes', async () => {const root = await tempRoot();const startedAtMs = 1_000_000;- await writeDevInstanceRecord(root, 4242, root, { startedAtMs });+ const recordPath = path.join(root, '.dev-instances', '4242.json');+ await writeDevInstanceRecord(root, 4242, root, {+ instanceId: 'stale-instance',+ startedAtMs,+ });await claimLegacyOwnerNamespace({ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },@@ -3186,10 +3144,20 @@ describe('hasExclusiveSharedLegacyUserDataAccess', () => {expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(true);- await writeDevInstanceRecord(root, 4242, root, {+ const replacementRaw = JSON.stringify({+ schemaVersion: 1,+ instanceId: 'replacement-instance',+ pid: 4242,+ userDataDir: root,+ passive: false,startedAtMs: startedAtMs + 1,});+ const replacementPath = `${recordPath}.replacement`;+ await fs.writeFile(replacementPath, replacementRaw, 'utf-8');+ await fs.rename(replacementPath, recordPath);+expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);+ await expect(fs.readFile(recordPath, 'utf-8')).resolves.toBe(replacementRaw);});});diff --git a/apps/desktop/src/main/maker-host/__tests__/model-visibility-owner-claim.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-visibility-owner-claim.test.tsindex 19b6874537..c25e47ac31 100644--- a/apps/desktop/src/main/maker-host/__tests__/model-visibility-owner-claim.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/model-visibility-owner-claim.test.ts@@ -76,6 +76,7 @@ describe('model visibility legacy Renderer owner claim', () => {expect(claimLegacyModelVisibilityOwner()).toEqual({dataOwnerId: 'owner-a',ownerGeneration: 1,+ canWriteOwnerScoped: true,claimed: true,claimedByOtherOwner: false,canInitialize: true,@@ -90,6 +91,7 @@ describe('model visibility legacy Renderer owner claim', () => {expect(claimLegacyModelVisibilityOwner()).toEqual({dataOwnerId: 'owner-b',ownerGeneration: 2,+ canWriteOwnerScoped: true,claimed: false,claimedByOtherOwner: true,canInitialize: false,@@ -117,14 +119,23 @@ describe('model visibility legacy Renderer owner claim', () => {it('does not claim from signed-out, boundary-pending, or shared access', () => {harness.mode = 'signed-out';harness.ownerId = null;- expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);+ expect(claimLegacyModelVisibilityOwner()).toMatchObject({+ canWriteOwnerScoped: false,+ claimed: false,+ });harness.mode = 'cloud';harness.ownerId = 'owner-a';harness.boundaryPending = true;- expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);+ expect(claimLegacyModelVisibilityOwner()).toMatchObject({+ canWriteOwnerScoped: false,+ claimed: false,+ });harness.boundaryPending = false;harness.exclusive = false;- expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);+ expect(claimLegacyModelVisibilityOwner()).toMatchObject({+ canWriteOwnerScoped: true,+ claimed: false,+ });expect(fs.existsSync(path.join(harness.root, markerName))).toBe(false);});@@ -142,6 +153,7 @@ describe('model visibility legacy Renderer owner claim', () => {expect(claimLegacyModelVisibilityOwner().canInitialize).toBe(true);harness.exclusive = false;expect(claimLegacyModelVisibilityOwner()).toMatchObject({+ canWriteOwnerScoped: true,claimed: true,claimedByOtherOwner: false,canInitialize: false,@@ -151,6 +163,7 @@ describe('model visibility legacy Renderer owner claim', () => {it('fails closed instead of replacing a malformed marker', () => {fs.writeFileSync(path.join(harness.root, markerName), '{broken', 'utf-8');expect(claimLegacyModelVisibilityOwner()).toMatchObject({+ canWriteOwnerScoped: true,claimed: false,claimedByOtherOwner: false,canInitialize: false,diff --git a/apps/desktop/src/main/maker-host/model-visibility-owner-claim.ts b/apps/desktop/src/main/maker-host/model-visibility-owner-claim.tsindex a1bf6fb54f..fb27026553 100644--- a/apps/desktop/src/main/maker-host/model-visibility-owner-claim.ts+++ b/apps/desktop/src/main/maker-host/model-visibility-owner-claim.ts@@ -69,6 +69,7 @@ export function claimLegacyModelVisibilityOwner(): ModelVisibilityLegacyOwnerCla) {return {...stamp,+ canWriteOwnerScoped: false,claimed: false,claimedByOtherOwner: false,canInitialize: false,@@ -110,6 +111,7 @@ export function claimLegacyModelVisibilityOwner(): ModelVisibilityLegacyOwnerClaconst claimed = state.kind === 'valid' && state.marker.ownerKey === ownerKey;return {...stamp,+ canWriteOwnerScoped: true,claimed,claimedByOtherOwner: state.kind === 'valid' && !claimed,canInitialize:diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 47c5c18f44..11d295b439 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -106,8 +106,6 @@ interface MigrationDeps {}interface RegisteredInstanceRecord {- schemaVersion?: number;- instanceId?: string;pid?: number;userDataDir?: string;startedAtMs?: number;@@ -556,42 +554,6 @@ function recordedPidMayStillBeLive(return looksLikeCindyRuntime(identity.command, rootDir);}-type StaleRegistrySettlement = 'pruned' | 'gone' | 'changed' | 'retained';--/** Delete only the exact schema-v1 `<pid>.json` payload that the OS identity scan proved stale. */-async function settleStaleRegistryRecord(- deps: MigrationDeps,- registryDir: string,- candidate: {- raw: string;- fileName: string;- schemaVersion: number | undefined;- instanceId: string | undefined;- pid: number;- },-): Promise<StaleRegistrySettlement> {- if (- candidate.schemaVersion !== 1- || typeof candidate.instanceId !== 'string'- || candidate.instanceId.length === 0- || candidate.fileName !== `${candidate.pid}.json`- ) {- return 'retained';- }- const filePath = path.join(registryDir, candidate.fileName);- try {- if (await deps.readFile(filePath) !== candidate.raw) return 'changed';- } catch (error) {- return isMissing(error) ? 'gone' : 'changed';- }- try {- await deps.unlink(filePath);- return 'pruned';- } catch (error) {- return isMissing(error) ? 'gone' : 'retained';- }-}-/*** Synchronous twin of findConcurrentLiveInstancePids for importer and sidebar* guards. It never launches an OS inspection command from these reusable main@@ -2493,8 +2455,6 @@ async function findConcurrentLiveInstancePids(const candidates: Array<{raw: string;fileName: string;- schemaVersion: number | undefined;- instanceId: string | undefined;pid: number;recordedAtMs: number | undefined;rootDir: string | undefined;@@ -2529,8 +2489,6 @@ async function findConcurrentLiveInstancePids(candidates.push({raw,fileName: name,- schemaVersion: record.schemaVersion,- instanceId: record.instanceId,pid,recordedAtMs: record.startedAtMs,rootDir: record.rootDir,@@ -2548,23 +2506,10 @@ async function findConcurrentLiveInstancePids(if (recordedPidMayStillBeLive(candidate.recordedAtMs, candidate.rootDir, identity)) {pids.push(candidate.pid);} else {- const settlement = await settleStaleRegistryRecord(deps, registryDir, candidate);- if (settlement === 'changed') {- // The identity belongs to the old payload; a replacement remains unproven in this pass.- pids.push(candidate.pid);- continue;- }- if (settlement === 'retained') {- rememberStaleProcessProof(- processProofKey(userDataDir, 'registry', `${candidate.fileName}\u0000${candidate.raw}`),- );- }- log.info(- settlement === 'pruned'- ? 'pruned stale instance registry record after PID reuse'- : 'ignoring stale instance registry record after PID reuse',- { pid: candidate.pid },+ rememberStaleProcessProof(+ processProofKey(userDataDir, 'registry', `${candidate.fileName}\u0000${candidate.raw}`),);+ log.info('ignoring stale instance registry record after PID reuse', { pid: candidate.pid });}}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 822d0ae31c..a475127698 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5142,6 +5142,7 @@ contextBridge.exposeInMainWorld('electronAPI', {: {dataOwnerId: null,ownerGeneration: 0,+ canWriteOwnerScoped: false,claimed: false,claimedByOtherOwner: false,canInitialize: false,diff --git a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.tsindex 8124c44394..e5ab3948af 100644--- a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts@@ -7,10 +7,11 @@* 3. set/get 往返 + owner-scoped localStorage 持久化(模拟 app 重启)* 4. 按 (agent, providerId, modelId) 分槽:同名模型在 cc / codex 互不覆盖* 5. setManyVisibility 批量(全部关 / 全部开)写显式 override- * 6. 同值写入短路(不抛)- * 7. 旧全局 key 只由 Main 仲裁出的首个 owner 认领,新账号默认隔离- * 8. schema 损坏 / 脏数据 → 静默回退,跟随目录默认- * 9. main 镜像同步异步失败时不产生未处理 rejection+ * 6. 跨 agent 的一次用户操作原子落盘,失败不留下部分状态+ * 7. 同值写入短路(不抛)+ * 8. 旧全局 key 只由 Main 仲裁出的首个 owner 认领,新账号默认隔离+ * 9. schema 损坏 / 脏数据 → 静默回退,跟随目录默认+ * 10. main 镜像同步异步失败时不产生未处理 rejection** 项目 vitest env=node,无 window。沿用 providerModelMemory.test.ts 的最小 localStorage stub。*/@@ -39,6 +40,7 @@ const logToMain = vi.fn();let ownerClaim: {dataOwnerId: string | null;ownerGeneration: number;+ canWriteOwnerScoped: boolean;claimed: boolean;claimedByOtherOwner?: boolean;canInitialize: boolean;@@ -50,10 +52,12 @@ function setOwnerClaim(claimed = true,canInitialize = true,claimedByOtherOwner = false,+ canWriteOwnerScoped = true,): void {ownerClaim = {dataOwnerId,ownerGeneration,+ canWriteOwnerScoped,claimed,claimedByOtherOwner,canInitialize,@@ -152,6 +156,54 @@ describe('modelVisibilityPrefs store', () => {expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(true);});+ it('setModelVisibilities:跨 agent 一次落盘并同时更新全部目标', async () => {+ const module = await loadModuleForOwner();+ const setItem = vi.spyOn(memStorage, 'setItem');++ expect(+ module.setModelVisibilities(+ 'xd',+ [+ { agent: 'claude-code', modelId: 'claude-sonnet-4-6' },+ { agent: 'codex', modelId: 'gpt-5.6' },+ ],+ false,+ ),+ ).toBe(true);++ expect(+ setItem.mock.calls.filter(([key]) => key === 'xdt:modelVisibilityPrefs:v1.owner.owner-a'),+ ).toHaveLength(1);+ expect(module.isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6' })).toBe(false);+ expect(module.isModelEnabled('codex', 'xd', { id: 'gpt-5.6' })).toBe(false);+ setItem.mockRestore();+ });++ it('setModelVisibilities:落盘失败不部分提交,按同一方向重试可整体成功', async () => {+ const module = await loadModuleForOwner();+ const storageKey = 'xdt:modelVisibilityPrefs:v1.owner.owner-a';+ const rawBeforeFailure = memStorage.getItem(storageKey);+ const mirrorCallsBeforeFailure = syncModelVisibility.mock.calls.length;+ const setItem = vi.spyOn(memStorage, 'setItem').mockImplementationOnce(() => {+ throw new Error('injected storage failure');+ });+ const targets = [+ { agent: 'claude-code' as const, modelId: 'claude-sonnet-4-6' },+ { agent: 'codex' as const, modelId: 'gpt-5.6' },+ ];++ expect(module.setModelVisibilities('xd', targets, false)).toBe(false);+ expect(memStorage.getItem(storageKey)).toBe(rawBeforeFailure);+ expect(module.isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6' })).toBe(true);+ expect(module.isModelEnabled('codex', 'xd', { id: 'gpt-5.6' })).toBe(true);+ expect(syncModelVisibility).toHaveBeenCalledTimes(mirrorCallsBeforeFailure);++ expect(module.setModelVisibilities('xd', targets, false)).toBe(true);+ expect(module.isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6' })).toBe(false);+ expect(module.isModelEnabled('codex', 'xd', { id: 'gpt-5.6' })).toBe(false);+ setItem.mockRestore();+ });+it('同值写入短路:不抛,值保持', async () => {const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();expect(setModelVisibility('codex', 'openai', 'gpt-5.4', false)).toBe(true);@@ -217,7 +269,7 @@ describe('modelVisibilityPrefs store', () => {)).toBe('1');});- it('旧 key 尚未归属任何账号时继续阻止写入,避免抢占未知 owner 的迁移输入', async () => {+ it('旧 key 尚未认领时仍允许稳定 owner 写自己的隔离 key', async () => {memStorage.setItem('xdt:modelVisibilityPrefs:v1',JSON.stringify({ 'codex:openai:gpt-5.6': false }),@@ -225,10 +277,28 @@ describe('modelVisibilityPrefs store', () => {setOwnerClaim('owner-a', 1, false, false);const module = await loadModuleForOwner();- expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(false);+ expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);++ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-a')).toBe(+ JSON.stringify({ 'codex:openai:gpt-5.5': false }),+ );+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1')).toBe(+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),+ );+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(false);+ setOwnerClaim('owner-a', 1, true, true);+ expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(false);+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(false);+ });++ it('当前 owner 会话尚未稳定时继续阻止写入', async () => {+ setOwnerClaim('owner-a', 1, false, false, false, false);+ const module = await loadModuleForOwner();++ expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(false);expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-a')).toBeNull();- expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(true);expect(logToMain).toHaveBeenCalledWith('warn','ModelVisibilityPrefs',diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsxindex f025592484..5fcd135261 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx@@ -109,7 +109,7 @@ vi.mock('@/lib/providerSubtitle', () => ({vi.mock('@/state/modelVisibilityPrefs', () => ({isModelEnabled: () => true,- setManyVisibility: vi.fn(),+ setModelVisibilities: vi.fn(),setModelVisibility: vi.fn(),useModelVisibilityVersion: () => 0,}));diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsxindex 8a28bb1e7e..7025527e0e 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx@@ -15,7 +15,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ProviderView } from '@cindy/model-providers';-const { wizardSpy, providersState, codexAuthState, codexAuthActions, toastError } = vi.hoisted(+const {+ wizardSpy,+ providersState,+ codexAuthState,+ codexAuthActions,+ toastError,+ setModelVisibilitiesSpy,+} = vi.hoisted(() => ({wizardSpy: vi.fn(),providersState: { providers: [] as unknown[], order: [] as string[] },@@ -31,6 +38,7 @@ const { wizardSpy, providersState, codexAuthState, codexAuthActions, toastErrorlogout: vi.fn(async () => undefined),},toastError: vi.fn(),+ setModelVisibilitiesSpy: vi.fn(() => true),}),);@@ -93,7 +101,7 @@ vi.mock('@/lib/providerSubtitle', () => ({vi.mock('@/state/modelVisibilityPrefs', () => ({isModelEnabled: () => true,- setManyVisibility: vi.fn(),+ setModelVisibilities: setModelVisibilitiesSpy,setModelVisibility: vi.fn(),useModelVisibilityVersion: () => 0,}));@@ -300,6 +308,53 @@ describe('ProvidersSection — 深链定位', () => {await waitFor(() => expect(screen.getByTestId('search').textContent).toBe('?tab=providers'));});+ it('统一模型开关跨 agent 一次提交,失败时提示用户', async () => {+ providersState.providers = [+ makeProvider('dual', {+ name: 'Dual',+ connected: true,+ agents: ['claude-code', 'codex'],+ models: {+ 'claude-code': [+ {+ id: 'shared',+ name: 'Shared',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ codex: [+ {+ id: 'shared',+ name: 'Shared',+ contextWindow: 272_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ },+ }),+ ];+ setModelVisibilitiesSpy.mockReturnValueOnce(false);+ renderAt('?tab=providers');++ fireEvent.click(await screen.findByRole('switch', { name: 'Shared' }));++ expect(setModelVisibilitiesSpy).toHaveBeenCalledOnce();+ expect(setModelVisibilitiesSpy).toHaveBeenCalledWith(+ 'dual',+ [+ { agent: 'claude-code', modelId: 'shared' },+ { agent: 'codex', modelId: 'shared' },+ ],+ false,+ );+ expect(toastError).toHaveBeenCalledWith(+ 'settings.providers.models.visibilityWriteFailed',+ );+ });+it('authorization-code 自定义供应商登录期间卸载时取消本视图拥有的授权', async () => {const providerOAuthLogin = vi.fn<(providerId: string, options?: { ownerId?: string }) => Promise<{ ok: boolean }>diff --git a/apps/desktop/src/renderer/__tests__/providersSectionUnavailableModels.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionUnavailableModels.test.tsxindex 88a31c672b..fd8066f7dd 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionUnavailableModels.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionUnavailableModels.test.tsx@@ -167,7 +167,7 @@ vi.mock('@/lib/providerSubtitle', () => ({vi.mock('@/state/modelVisibilityPrefs', () => ({isModelEnabled: () => true,- setManyVisibility: vi.fn(),+ setModelVisibilities: vi.fn(),setModelVisibility: vi.fn(),useModelVisibilityVersion: () => 0,}));diff --git a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.tsindex c938ba6e3c..d0549de207 100644--- a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts+++ b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts@@ -50,6 +50,7 @@ beforeEach(() => {claimLegacyModelVisibilityOwner: () => ({dataOwnerId: 'test-owner',ownerGeneration: 1,+ canWriteOwnerScoped: true,claimed: true,claimedByOtherOwner: false,canInitialize: true,diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsxindex bc2c028709..71e95b573c 100644--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx@@ -46,7 +46,7 @@ import {} from '@/components/new-chat/sourceSwitch';import {isModelEnabled,- setManyVisibility,+ setModelVisibilities,setModelVisibility,useModelVisibilityVersion,} from '@/state/modelVisibilityPrefs';@@ -481,35 +481,36 @@ export function UnifiedModelList({const toggleRow = useCallback((row: UnionModelRow) => {const next = !rowAnyEnabled(provider.id, row);- let failed = false;- for (const a of row.avail) {- const m = row.byAgent[a];- if (m && setModelVisibility(a, provider.id, m.id, next) === false) failed = true;+ const targets = row.avail.flatMap((agent) => {+ const model = row.byAgent[agent];+ return model ? [{ agent, modelId: model.id }] : [];+ });+ if (setModelVisibilities(provider.id, targets, next) === false) {+ showVisibilityWriteFailure();}- if (failed) showVisibilityWriteFailure();},[provider.id, showVisibilityWriteFailure],);- /** 全部显示 / 隐藏:逐 agent 批量写(单 agent 一次落盘)。只作用于**对话模型的显示轴**+ /** 全部显示 / 隐藏:跨 agent 一次落盘。只作用于**对话模型的显示轴*** —— 能力模型没有显示轴,停用行没有可显示态,都不写(写了 = 无效 override 污染存储,* 且历史上会把图像模型漏进选择器)。停用判定含乐观覆盖(pendingDisabled,按规范化* 行 key):刚停用、快照未回来的行同样不写(PR #744 review)。 */const handleBulk = useCallback(() => {const next = !allOn;- let failed = false;- for (const agent of provider.agents) {- const ids = (provider.models[agent] ?? [])+ const targets = provider.agents.flatMap((agent) =>+ (provider.models[agent] ?? []).filter((m) =>isAgentSelectableModel(m, { userProvider: provider.source === 'user' }) &&(pendingDisabled[canonicalModelKey(provider, agent, m.id)] ?? m.disabled === true) !==true,)- .map((m) => m.id);- if (setManyVisibility(agent, provider.id, ids, next) === false) failed = true;+ .map((model) => ({ agent, modelId: model.id })),+ );+ if (setModelVisibilities(provider.id, targets, next) === false) {+ showVisibilityWriteFailure();}- if (failed) showVisibilityWriteFailure();}, [allOn, provider, pendingDisabled, showVisibilityWriteFailure]);/** 行级「⋯」菜单(hover 显现;菜单打开期间保持可见):停用动作的唯一入口。 */diff --git a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts b/apps/desktop/src/renderer/state/modelVisibilityPrefs.tsindex 5781a3581b..b89c53affc 100644--- a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts+++ b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts@@ -20,7 +20,7 @@* - 「全部开启 / 全部关闭」是显式批量动作 → 为当前 agent 该来源的每个模型写显式 override。** 谁读谁写:- * - 写:ProvidersSection 的模型开关 / 批量按钮(setModelVisibility / setManyVisibility)。+ * - 写:ProvidersSection 的模型开关 / 批量按钮(setModelVisibility / setModelVisibilities)。* - 读:ModelSelector 的右栏过滤(isModelEnabled);ProvidersSection 的计数与开关态。** 持久化频率低(仅用户点开关触发),同步写 localStorage,不做 batch / debounce —— 与@@ -112,7 +112,11 @@ function migrateLegacyVisibility(ownerId: string, ownerGeneration: number): Migr// Main 用模型可见性专属 marker 把旧 key 原子归属给升级时的当前稳定 local/cloud owner;// canInitialize 还保证此刻没有另一个共享 userData 的旧进程在并发改写迁移输入。const claim = window.electronAPI?.maker?.claimLegacyModelVisibilityOwner?.();- if (claim?.dataOwnerId !== ownerId || claim.ownerGeneration !== ownerGeneration) {+ if (+ claim?.dataOwnerId !== ownerId+ || claim.ownerGeneration !== ownerGeneration+ || claim.canWriteOwnerScoped !== true+ ) {return BLOCKED_MIGRATION;}if (claim.claimedByOtherOwner === true) {@@ -123,7 +127,12 @@ function migrateLegacyVisibility(ownerId: string, ownerGeneration: number): MigrmigrationPending: false,};}- if (claim.claimed !== true) return BLOCKED_MIGRATION;+ if (claim.claimed !== true) {+ // A missing/blocked legacy marker only defers importing the pre-account snapshot. The+ // stable current owner can still write its isolated key; a later import merges scoped+ // values last, so these new settings win without mutating the legacy input.+ return { readyForWrites: true, migrationPending: true };+ }if (claim.canInitialize !== true) {// 归属已经明确时,新设置可以安全写进 owner namespace;只把旧全局快照的导入推迟到独占时。return { readyForWrites: true, migrationPending: true };@@ -203,7 +212,8 @@ const listeners = new Set<() => void>();interface VisibilityWriteContext {operation: 'single' | 'bulk';- agent: AgentKind;+ agent?: AgentKind;+ agentCount?: number;providerId: string;enabled: boolean;modelId?: string;@@ -291,24 +301,17 @@ export function isModelEnabled(return isModelVisible(load()[keyOf(agent, providerId, model.id)], model.defaultEnabled);}-/** 写单个 (agent, 来源, 模型) 的可见性 override。同值短路,避免无意义落盘 / 通知。 */-export function setModelVisibility(- agent: AgentKind,+function setVisibilityTargets(providerId: string,- modelId: string,+ targets: readonly { agent: AgentKind; modelId: string }[],enabled: boolean,+ context: VisibilityWriteContext,): boolean {- const context: VisibilityWriteContext = {- operation: 'single',- agent,- providerId,- modelId,- enabled,- };- if (!providerId || !modelId) {+ if (!providerId || targets.some(({ modelId }) => !modelId)) {log.warn('model visibility write rejected', { reason: 'invalid-target', ...context });return false;}+ if (targets.length === 0) return true;if (!ensureActiveOwnerReadyForWrites()) {log.warn('model visibility write rejected', {reason: 'owner-write-not-ready',@@ -320,9 +323,33 @@ export function setModelVisibility(return false;}const map = load();- const k = keyOf(agent, providerId, modelId);- if (map[k] === enabled) return true;- return persist({ ...map, [k]: enabled }, context);+ let changed = false;+ const next = { ...map };+ for (const { agent, modelId } of targets) {+ const k = keyOf(agent, providerId, modelId);+ if (next[k] !== enabled) {+ next[k] = enabled;+ changed = true;+ }+ }+ return changed ? persist(next, context) : true;+}++/** 写单个 (agent, 来源, 模型) 的可见性 override。同值短路,避免无意义落盘 / 通知。 */+export function setModelVisibility(+ agent: AgentKind,+ providerId: string,+ modelId: string,+ enabled: boolean,+): boolean {+ const context: VisibilityWriteContext = {+ operation: 'single',+ agent,+ providerId,+ modelId,+ enabled,+ };+ return setVisibilityTargets(providerId, [{ agent, modelId }], enabled, context);}/**@@ -343,32 +370,30 @@ export function setManyVisibility(modelCount: modelIds.length,enabled,};- if (!providerId) {- log.warn('model visibility write rejected', { reason: 'invalid-target', ...context });- return false;- }- if (modelIds.length === 0) return true;- if (!ensureActiveOwnerReadyForWrites()) {- log.warn('model visibility write rejected', {- reason: 'owner-write-not-ready',- ...context,- ownerGeneration: activeOwnerGeneration,- mode: activeOwnerMode,- migrationPending: activeOwnerMigrationPending,- });- return false;- }- const map = load();- let changed = false;- const next = { ...map };- for (const id of modelIds) {- const k = keyOf(agent, providerId, id);- if (next[k] !== enabled) {- next[k] = enabled;- changed = true;- }- }- return changed ? persist(next, context) : true;+ return setVisibilityTargets(+ providerId,+ modelIds.map((modelId) => ({ agent, modelId })),+ enabled,+ context,+ );+}++/**+ * 跨 agent 原子写一组模型可见性。统一列表的一次用户操作必须只落盘一次,避免前一+ * agent 成功、后一 agent 失败后界面进入部分提交状态,导致重试方向反转。+ */+export function setModelVisibilities(+ providerId: string,+ targets: readonly { agent: AgentKind; modelId: string }[],+ enabled: boolean,+): boolean {+ return setVisibilityTargets(providerId, targets, enabled, {+ operation: 'bulk',+ providerId,+ agentCount: new Set(targets.map(({ agent }) => agent)).size,+ modelCount: targets.length,+ enabled,+ });}/**diff --git a/apps/desktop/src/shared/__tests__/modelVisibility.test.ts b/apps/desktop/src/shared/__tests__/modelVisibility.test.tsindex 44d8112deb..e1c6a68c10 100644--- a/apps/desktop/src/shared/__tests__/modelVisibility.test.ts+++ b/apps/desktop/src/shared/__tests__/modelVisibility.test.ts@@ -7,6 +7,7 @@ describe('model visibility legacy owner claim validation', () => {expect(isModelVisibilityLegacyOwnerClaim({dataOwnerId: 'owner-a',ownerGeneration: 1,+ canWriteOwnerScoped: true,claimed: true,claimedByOtherOwner: false,canInitialize: true,@@ -17,12 +18,14 @@ describe('model visibility legacy owner claim validation', () => {expect(isModelVisibilityLegacyOwnerClaim({dataOwnerId: 'owner-a',ownerGeneration: 1,+ claimedByOtherOwner: false,claimed: true,canInitialize: true,})).toBe(false);expect(isModelVisibilityLegacyOwnerClaim({dataOwnerId: 'owner-a',ownerGeneration: -1,+ canWriteOwnerScoped: true,claimed: false,claimedByOtherOwner: true,canInitialize: false,diff --git a/apps/desktop/src/shared/modelVisibility.ts b/apps/desktop/src/shared/modelVisibility.tsindex a3dd114d22..88241626e3 100644--- a/apps/desktop/src/shared/modelVisibility.ts+++ b/apps/desktop/src/shared/modelVisibility.ts@@ -2,6 +2,8 @@ import { isDataOwnerPushStamp, type DataOwnerPushStamp } from './dataOwnerPush.j/** Main's decision for importing the one pre-account model visibility namespace. */export interface ModelVisibilityLegacyOwnerClaim extends DataOwnerPushStamp {+ /** The stamped local/cloud owner is stable and may write only its owner-scoped preference key. */+ readonly canWriteOwnerScoped: boolean;/** The model visibility legacy marker belongs to the active stable local/cloud owner. */readonly claimed: boolean;/** The model visibility legacy marker durably belongs to another account. */@@ -15,6 +17,7 @@ export function isModelVisibilityLegacyOwnerClaim(): value is ModelVisibilityLegacyOwnerClaim {return (isDataOwnerPushStamp(value) &&+ typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).canWriteOwnerScoped === 'boolean' &&typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).claimed === 'boolean' &&typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).claimedByOtherOwner === 'boolean' &&typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).canInitialize === 'boolean'