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。

fix(models): 没拨过的显示开关跟随目录默认 (#4217)

Chris Zhangabcf92c2b34e
diff --git a/apps/desktop/src/renderer/__tests__/gatewayModelArrival.test.tsx b/apps/desktop/src/renderer/__tests__/gatewayModelArrival.test.tsx
index b417eef7ed..9e3d4557a7 100644
--- a/apps/desktop/src/renderer/__tests__/gatewayModelArrival.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/gatewayModelArrival.test.tsx
@@ -57,7 +57,7 @@ it.each(['google/gemini-3.8-flash', 'google/gemini-99-pro-preview'])(
},
);
-it('lists downloaded Gateway models in settings without enabling them until the user chooses them', async () => {
+it('lists downloaded Gateway models in settings and follows catalog defaults until the user switches them', async () => {
Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: {
claimLegacyModelVisibilityOwner: () => ({ dataOwnerId: 'arrival-test', ownerGeneration: 1,
canWriteOwnerScoped: true, claimed: true, canInitialize: true, profileOrigin: 'new' }),
@@ -115,15 +115,15 @@ it('lists downloaded Gateway models in settings without enabling them until the
// Settings now keeps disabled visibility rows expanded, while picker filtering stays off.
expect(screen.getByText('Future Model 9')).toBeTruthy();
expect(screen.getByRole('switch', { name: /Future Model 9/ }).getAttribute('aria-checked')).toBe(
- 'false',
+ 'true',
);
const pickerEntries = () => unifiedModelEntries({ providers: [snapshot()],
isVisible: (providerId, model, agent) => isModelEnabled(agent, providerId, model) });
- expect(pickerEntries().some((entry) => entry.modelId === 'new-labs/future-9')).toBe(false);
- await act(async () => fireEvent.click(screen.getByRole('switch', { name: /Future Model 9/ })));
- expect(screen.getByRole('switch', { name: /Future Model 9/ }).getAttribute('aria-checked')).toBe('true');
expect(pickerEntries().some((entry) => entry.modelId === 'new-labs/future-9')).toBe(true);
expect(screen.getByText('new-labs')).toBeTruthy();
+ await act(async () => fireEvent.click(screen.getByRole('switch', { name: /Future Model 9/ })));
+ expect(screen.getByRole('switch', { name: /Future Model 9/ }).getAttribute('aria-checked')).toBe('false');
+ expect(pickerEntries().some((entry) => entry.modelId === 'new-labs/future-9')).toBe(false);
expect(snapshot().models['claude-code']?.find((m) => m.id === 'new-labs/future-9')).toMatchObject(
{
contextWindow: 500_000,
diff --git a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts
index 0b9897d97b..a355bcfb3f 100644
--- a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts
+++ b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts
@@ -209,7 +209,7 @@ describe('refreshLocalCatalogSnapshot', () => {
expect(mocks.commitCapabilities).toHaveBeenCalledTimes(recovers ? 1 : 0);
if (recovers) {
expect(mocks.commitProviders).toHaveBeenLastCalledWith(2, providers);
- expect(sync).toHaveBeenLastCalledWith('owner-a', 1, { 'pi:xd:recommended': true },
+ expect(sync).toHaveBeenLastCalledWith('owner-a', 1, {},
expect.not.objectContaining({ pending: true }));
expect(prefs.isModelEnabled('pi', 'xd', { id: 'recommended' })).toBe(true);
} else {
diff --git a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
index 7b15118ca9..2d9e2d6a68 100644
--- a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
@@ -137,15 +137,15 @@ describe('local profile visibility adoption', () => {
let prefs = await import('../state/modelVisibilityPrefs');
await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(false);
expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: false })).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'added', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'added', defaultEnabled: true })).toBe(true);
expect(prefs.isModelEnabled('pi', 'xd', { id: 'restored', defaultEnabled: true })).toBe(true);
expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [{ ...catalog,
agents: ['codex'], models: { codex: [{ id: 'late', defaultEnabled: true }] },
} as ProviderView])).toBe(true);
- expect(prefs.isModelEnabled('codex', 'xd', { id: 'late', defaultEnabled: false })).toBe(true);
+ expect(prefs.isModelEnabled('codex', 'xd', { id: 'late', defaultEnabled: false })).toBe(false);
expect(JSON.parse(memStorage.getItem(initKey('local-v1'))!)).toEqual(source);
await prefs.setModelVisibility('pi', 'xd', 'default', false);
vi.resetModules();
@@ -156,7 +156,7 @@ describe('local profile visibility adoption', () => {
ownerClaim.profileOrigin = 'existing';
await prefs.setModelVisibilityOwner('owner-b', 2, 'cloud');
expect(await prefs.migrateModelVisibilityDefaults('owner-b', 2, [catalog])).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(true);
});
it('keeps target overrides and initialized scopes authoritative', async () => {
@@ -169,8 +169,8 @@ describe('local profile visibility adoption', () => {
const prefs = await import('../state/modelVisibilityPrefs');
await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'restored', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: true })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'restored', defaultEnabled: true })).toBe(true);
});
it.each([false, true])('preserves target restore-default choices through adoption and restart (interrupted: %s)', async (interrupted) => {
@@ -231,7 +231,7 @@ describe('local profile visibility adoption', () => {
prefs = await import('../state/modelVisibilityPrefs');
await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(false);
expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
});
@@ -241,8 +241,8 @@ describe('local profile visibility adoption', () => {
const prefs = await import('../state/modelVisibilityPrefs');
await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog]);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: true })).toBe(true);
});
it('waits for adoption provenance even when the target already has initialization artifacts', async () => {
@@ -257,7 +257,51 @@ describe('local profile visibility adoption', () => {
expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(false);
ownerClaim.profileOrigin = 'adopted-local';
expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'default', defaultEnabled: false })).toBe(false);
+ });
+
+ it('does not adopt a corrupt local map as empty catalog defaults', async () => {
+ seed();
+ memStorage.setItem(mapKey('local-v1'), '{ not valid json');
+ const prefs = await import('../state/modelVisibilityPrefs');
+ await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBeNull();
+ expect(memStorage.getItem(mapKey('owner-a'))).toBeNull();
+ memStorage.setItem(mapKey('local-v1'), JSON.stringify({ 'pi:xd:off': false }));
+ expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBe('1');
+ });
+
+ it('keeps source corruption latched when the cloud target map is already valid', async () => {
+ seed();
+ memStorage.setItem(mapKey('local-v1'), '{ not valid json');
+ memStorage.setItem(mapKey('owner-a'), JSON.stringify({ 'pi:xd:on': false }));
+ const prefs = await import('../state/modelVisibilityPrefs');
+ await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBeNull();
+ memStorage.setItem(mapKey('local-v1'), JSON.stringify({ 'pi:xd:off': false }));
+ expect(await prefs.migrateModelVisibilityDefaults('owner-a', 1, [catalog])).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBe('1');
+ });
+
+ it('repairs a corrupt cloud target then retries adopted-local handoff', async () => {
+ seed();
+ memStorage.setItem(mapKey('owner-a'), '{ not valid json');
+ const prefs = await import('../state/modelVisibilityPrefs');
+ await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBeNull();
+ expect(await prefs.setModelVisibility('pi', 'xd', 'manual', false)).toBe(true);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBe('1');
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'off', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'on', defaultEnabled: false })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'manual' })).toBe(false);
});
});
@@ -326,6 +370,40 @@ describe('model visibility across renderer windows', () => {
expect(prefs.isModelEnabled('pi', 'xd', model('pi'))).toBe(false);
});
+ it('retries adopted-local handoff when another window repairs the local source', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.initialization.owner.local-v1', JSON.stringify({
+ eligibleForDefaults: true, defaults: { 'pi:xd:pi': true },
+ scopes: [JSON.stringify(['xd', 'pi'])], followCatalogKeys: [],
+ }));
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.local-v1', '{ not valid json');
+ setOwnerClaim('owner-a', 1, false, false, true);
+ ownerClaim.profileOrigin = 'adopted-local';
+ const prefs = await import('../state/modelVisibilityPrefs');
+ await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'other', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBeNull();
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.local-v1', JSON.stringify({ 'pi:xd:pi': false }));
+ await locks.settle();
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.local-adoption.owner.owner-a')).toBe('1');
+ expect(prefs.isModelEnabled('pi', 'xd', model('pi'))).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'other', defaultEnabled: true })).toBe(true);
+ });
+
+ it('retries legacy migration when another window repairs the global key', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1', '{ not valid json');
+ setOwnerClaim('owner-a', 1, true, true);
+ ownerClaim.profileOrigin = 'existing';
+ const prefs = await import('../state/modelVisibilityPrefs');
+ await prefs.setModelVisibilityOwner('owner-a', 1, 'cloud');
+ expect(prefs.isModelEnabled('codex', 'openai', { id: 'other', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a')).toBeNull();
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1', JSON.stringify({ 'codex:openai:gpt-5.6': false }));
+ await locks.settle();
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a')).toBe('1');
+ expect(prefs.isModelEnabled('codex', 'openai', { id: 'gpt-5.6', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('codex', 'openai', { id: 'other', defaultEnabled: true })).toBe(true);
+ });
+
it('serializes first catalogs without optimistic overwrites and keeps the first baseline frozen', async () => {
const { a, b } = await windows();
const release = locks.hold();
@@ -336,17 +414,17 @@ describe('model visibility across renderer windows', () => {
await Promise.all([first, second]);
await locks.settle();
for (const prefs of [a, b]) {
- expect(prefs.isModelEnabled('pi', 'xd', model('pi', false))).toBe(true);
- expect(prefs.isModelEnabled('codex', 'xd', model('codex', false))).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', model('pi', false))).toBe(false);
+ expect(prefs.isModelEnabled('codex', 'xd', model('codex', false))).toBe(false);
}
const changed = catalog('pi', false);
changed.models.pi!.push(model('later'));
await b.migrateModelVisibilityDefaults('owner-a', 1, [changed]);
vi.resetModules();
const restarted = await loadModuleForOwner();
- expect(restarted.isModelEnabled('pi', 'xd', model('pi', false))).toBe(true);
- expect(restarted.isModelEnabled('pi', 'xd', model('later'))).toBe(false);
- expect(restarted.isModelEnabled('codex', 'xd', model('codex', false))).toBe(true);
+ expect(restarted.isModelEnabled('pi', 'xd', model('pi', false))).toBe(false);
+ expect(restarted.isModelEnabled('pi', 'xd', model('later'))).toBe(true);
+ expect(restarted.isModelEnabled('codex', 'xd', model('codex', false))).toBe(false);
});
it('rebases concurrent restores, explicit switches, and another initialized scope', async () => {
@@ -372,11 +450,11 @@ describe('model visibility across renderer windows', () => {
expect(prefs.isModelEnabled(agent, 'xd', model(agent, false))).toBe(false);
expect(prefs.isModelVisibilityCustomized(agent, 'xd', agent)).toBe(false);
}
- expect(prefs.isModelEnabled('claude-code', 'xd', model('claude-code', false))).toBe(true);
+ expect(prefs.isModelEnabled('claude-code', 'xd', model('claude-code', false))).toBe(false);
expect(prefs.isModelEnabled('pi', 'xd', model('manual', false))).toBe(true);
}
expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-a', 1,
- expect.objectContaining({ 'claude-code:xd:claude-code': true, 'pi:xd:manual': true }),
+ expect.objectContaining({ 'pi:xd:manual': true }),
expect.objectContaining({ followCatalogKeys: expect.arrayContaining(['pi:xd:pi', 'codex:xd:codex']) }));
});
@@ -405,7 +483,7 @@ describe('model visibility across renderer windows', () => {
expect(await stale).toBe(false);
expect(JSON.parse(memStorage.getItem(initKey)!).scopes).toEqual([]);
await a.migrateModelVisibilityDefaults('owner-a', 1, [catalog('pi', false)]);
- expect(a.isModelEnabled('pi', 'xd', model('pi'))).toBe(false);
+ expect(a.isModelEnabled('pi', 'xd', model('pi'))).toBe(true);
});
it('returns lock failures without writing outside the lock and permits retry', async () => {
@@ -424,8 +502,8 @@ describe('model visibility across renderer windows', () => {
setOwnerClaim('owner-a', 1);
await a.migrateModelVisibilityDefaults('owner-a', 1, [catalog('pi')]);
await locks.settle();
- expect(b.isModelEnabled('pi', 'xd', model('pi', false))).toBe(true);
- expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-a', 1, { 'pi:xd:pi': true },
+ expect(b.isModelEnabled('pi', 'xd', model('pi', false))).toBe(false);
+ expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-a', 1, {},
expect.not.objectContaining({ pending: true }));
});
});
@@ -585,13 +663,24 @@ describe('modelVisibilityPrefs store', () => {
expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(true);
expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-b')).toBeNull();
- expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-b', 2, {}, expect.objectContaining({ pending: true }));
+ expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-b', 2, {}, expect.objectContaining({ followCatalogKeys: [] }));
setOwnerClaim('owner-a', 3, true, true);
await module.setModelVisibilityOwner('owner-a', 3, 'cloud');
expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(false);
});
+ it('非独占推迟导入时不把尚未迁入的关闭开关当成目录默认开', async () => {
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1',
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+ setOwnerClaim('owner-a', 1, true, false);
+ ownerClaim.profileOrigin = 'existing';
+ const module = await loadModuleForOwner();
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6', defaultEnabled: true })).toBe(false);
+ });
+
it('已归属但非独占时保存新 override,恢复独占后合并旧值且新值优先', async () => {
memStorage.setItem(
'xdt:modelVisibilityPrefs:v1',
@@ -738,6 +827,79 @@ describe('modelVisibilityPrefs store', () => {
expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(false);
});
+ it('旧配置损坏时不因 scoped 增量而提交迁移完成', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1', '{ not valid json');
+ setOwnerClaim('owner-a', 1, true, false);
+ ownerClaim.profileOrigin = 'existing';
+ const module = await loadModuleForOwner();
+ expect(await module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);
+ setOwnerClaim('owner-a', 1, true, true);
+ ownerClaim.profileOrigin = 'existing';
+ expect(await module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a')).toBeNull();
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6', defaultEnabled: true })).toBe(false);
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1', JSON.stringify({ 'codex:openai:gpt-5.6': false }));
+ expect(await module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6', defaultEnabled: true })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a')).toBe('1');
+ });
+
+ it('配置损坏时仍尊重 Restore defaults 的跟随目录路线', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.owner-a', '{ not valid json');
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a', '1');
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.initialization.owner.owner-a', JSON.stringify({
+ eligibleForDefaults: false,
+ defaults: {},
+ scopes: [JSON.stringify(['xd', 'claude-code'])],
+ followCatalogKeys: ['claude-code:xd:claude-opus-4-8'],
+ }));
+ const { isModelEnabled } = await loadModuleForOwner();
+ expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8', defaultEnabled: true })).toBe(true);
+ expect(isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6', defaultEnabled: true })).toBe(false);
+ });
+
+ it('写入显式开关时清除对应的 Restore defaults 标记', async () => {
+ const module = await loadModuleForOwner();
+ expect(await module.resetModelVisibilities('xd', [{ agent: 'claude-code', modelId: 'claude-opus-4-8' }])).toBe(true);
+ expect(await module.setModelVisibility('claude-code', 'xd', 'claude-opus-4-8', false)).toBe(true);
+ const init = JSON.parse(memStorage.getItem('xdt:modelVisibilityPrefs:v1.initialization.owner.owner-a')!);
+ expect(init.followCatalogKeys).not.toContain('claude-code:xd:claude-opus-4-8');
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.owner-a', '{ not valid json');
+ vi.resetModules();
+ const restarted = await loadModuleForOwner();
+ expect(restarted.isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8', defaultEnabled: true })).toBe(false);
+ });
+
+ it('override 写入失败时保留 Restore defaults 标记', async () => {
+ const module = await loadModuleForOwner();
+ expect(await module.resetModelVisibilities('xd', [{ agent: 'claude-code', modelId: 'claude-opus-4-8' }])).toBe(true);
+ const write = memStorage.setItem.bind(memStorage);
+ vi.spyOn(memStorage, 'setItem').mockImplementation((key, value) => {
+ if (key === 'xdt:modelVisibilityPrefs:v1.owner.owner-a') throw new Error('disk full');
+ write(key, value);
+ });
+ expect(await module.setModelVisibility('claude-code', 'xd', 'claude-opus-4-8', false)).toBe(false);
+ const init = JSON.parse(memStorage.getItem('xdt:modelVisibilityPrefs:v1.initialization.owner.owner-a')!);
+ expect(init.followCatalogKeys).toContain('claude-code:xd:claude-opus-4-8');
+ });
+
+ it('owner-scoped 配置损坏时不把目录默认当成开启', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.owner-a', '{ not valid json');
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a', '1');
+ const { isModelEnabled } = await loadModuleForOwner();
+ expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8', defaultEnabled: true })).toBe(false);
+ });
+
+ it('写入修好损坏配置后恢复跟随目录默认', async () => {
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.owner.owner-a', '{ not valid json');
+ memStorage.setItem('xdt:modelVisibilityPrefs:v1.migration-complete.owner.owner-a', '1');
+ const module = await loadModuleForOwner();
+ expect(module.isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8', defaultEnabled: true })).toBe(false);
+ expect(await module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(true);
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(false);
+ expect(module.isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8', defaultEnabled: true })).toBe(true);
+ });
+
it('脏数据条目(value 非 boolean)被过滤', async () => {
memStorage.setItem(
'xdt:modelVisibilityPrefs:v1',
@@ -749,8 +911,8 @@ describe('modelVisibilityPrefs store', () => {
);
const { isModelEnabled } = await loadModuleForOwner();
expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(false); // 合法 override 生效
- expect(isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6' })).toBe(false); // 无有效旧开关,不自动开启
- expect(isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(false); // 无有效旧开关,不自动开启
+ expect(isModelEnabled('claude-code', 'xd', { id: 'claude-sonnet-4-6' })).toBe(true);
+ expect(isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(true);
});
});
@@ -807,7 +969,7 @@ describe('compact model defaults upgrade', () => {
expect(JSON.parse(memStorage.getItem(scopedKey)!)).toEqual({});
});
- it('preserves old on/off switches without enabling history, favorites, or new defaults', async () => {
+ it('preserves old on/off switches without treating history or favorites as switches', async () => {
memStorage.setItem('xdt:modelVisibilityPrefs:v1', JSON.stringify({
'claude-code:xd:chatgpt/fable-5': true,
'claude-code:xd:chatgpt/fable-5-1': false,
@@ -821,22 +983,15 @@ describe('compact model defaults upgrade', () => {
favorites.addModelFavorite({ providerId: 'xd', modelId: 'fable-5', agent: 'pi' });
const prefs = await upgrade();
expect(prefs.isModelEnabled('claude-code', 'xd', { id: 'chatgpt/fable-5', defaultEnabled: false })).toBe(true);
- for (const agent of provider.agents) {
- for (const model of provider.models[agent]!) {
- if (agent === 'claude-code' && model.id === 'chatgpt/fable-5') continue;
- expect(prefs.isModelEnabled(agent, 'xd', { ...model, defaultEnabled: true })).toBe(false);
- }
- }
- const entries = unifiedModelEntries({ providers: [provider], isVisible: (pid, model, agent) => prefs.isModelEnabled(agent, pid, model) });
- expect(entries).toHaveLength(1);
- expect(entries[0]!.candidates).toEqual(['claude-code']);
- expect(entries[0]!.capabilities['claude-code']?.protocolMode).toBe('compatibility');
+ expect(prefs.isModelEnabled('claude-code', 'xd', { id: 'chatgpt/fable-5-1', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(true);
});
- it('does not initialize an existing owner even when its override map is empty', async () => {
+ it('follows catalog defaults when an existing owner has no switches', async () => {
memStorage.setItem(scopedKey, '{}');
const prefs = await upgrade();
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'fable-5', defaultEnabled: false })).toBe(false);
});
it.each(['existing', undefined] as const)('does not infer a new profile from empty model storage (origin: %s)', async (origin) => {
@@ -844,7 +999,7 @@ describe('compact model defaults upgrade', () => {
const prefs = await upgrade();
for (const agent of provider.agents) {
for (const model of provider.models[agent]!) {
- expect(prefs.isModelEnabled(agent, 'xd', { ...model, defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled(agent, 'xd', model)).toBe(model.defaultEnabled !== false);
}
}
expect(JSON.parse(memStorage.getItem(markerKey)!)).toMatchObject({ eligibleForDefaults: false, defaults: {} });
@@ -852,7 +1007,7 @@ describe('compact model defaults upgrade', () => {
vi.resetModules();
const restarted = await upgrade();
expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini' })).toBe(true);
- expect(restarted.isModelEnabled('pi', 'xd', { id: 'fable-5' })).toBe(false);
+ expect(restarted.isModelEnabled('pi', 'xd', { id: 'fable-5', defaultEnabled: false })).toBe(false);
});
it('waits for Main profile creation before writing migration artifacts or consuming defaults', async () => {
@@ -872,7 +1027,7 @@ describe('compact model defaults upgrade', () => {
const prefs = await loadModuleForOwner();
if (emptySnapshot) await prefs.migrateModelVisibilityDefaults('owner-a', 1, []);
expect(syncModelVisibility).toHaveBeenLastCalledWith('owner-a', 1, {},
- expect.objectContaining({ pending: true }));
+ expect.objectContaining({ followCatalogKeys: [] }));
vi.resetModules();
const restarted = await upgrade();
@@ -933,7 +1088,7 @@ describe('compact model defaults upgrade', () => {
}
}
expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'pi-added', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'pi-added', defaultEnabled: true })).toBe(true);
expect(prefs.isModelEnabled('pi', 'other-provider', { id: 'pi-added', defaultEnabled: true })).toBe(true);
});
@@ -942,9 +1097,9 @@ describe('compact model defaults upgrade', () => {
defaults: { 'pi:xd:gemini': true }, scopes: [JSON.stringify(['xd', 'pi'])], followCatalogKeys: [],
}));
const prefs = await upgrade();
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(true);
- expect(prefs.isModelEnabled('codex', 'xd', { id: 'fable-5', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(false);
+ expect(prefs.isModelEnabled('codex', 'xd', { id: 'fable-5', defaultEnabled: true })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(true);
});
it('revokes pending eligibility when deferred ownership reveals a legacy profile after restart', async () => {
@@ -957,7 +1112,7 @@ describe('compact model defaults upgrade', () => {
const restarted = await upgrade();
expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(false);
expect(restarted.isModelEnabled('pi', 'xd', { id: 'fable-5', defaultEnabled: false })).toBe(true);
- expect(restarted.isModelEnabled('pi', 'xd', { id: 'fable-5-1', defaultEnabled: true })).toBe(false);
+ expect(restarted.isModelEnabled('pi', 'xd', { id: 'fable-5-1', defaultEnabled: true })).toBe(true);
});
it('freezes a new profile initial defaults and keeps later additions off across restart', async () => {
@@ -970,14 +1125,14 @@ describe('compact model defaults upgrade', () => {
] },
};
await prefs.migrateModelVisibilityDefaults('owner-a', 1, [changed]);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(true);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'fable-5', defaultEnabled: true })).toBe(false);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'fable-5', defaultEnabled: true })).toBe(true);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(true);
expect(prefs.isModelVisibilityCustomized('pi', 'xd', 'gemini')).toBe(false);
vi.resetModules();
const restarted = await upgrade('owner-a', 1, changed);
- expect(restarted.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(false);
- expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(true);
+ expect(restarted.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(true);
+ expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(false);
});
it('preserves manually disabled defaults and allows manually enabling a new model', async () => {
@@ -998,7 +1153,7 @@ describe('compact model defaults upgrade', () => {
expect(restarted.isModelVisibilityCustomized('pi', 'xd', 'gemini')).toBe(false);
expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(true);
expect(restarted.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: false })).toBe(false);
- expect(restarted.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(false);
+ expect(restarted.isModelEnabled('pi', 'xd', { id: 'brand-new', defaultEnabled: true })).toBe(true);
});
it.each(['claude-code', 'codex'] as const)('late %s routes preserve explicit switches but never auto-enable missing switches', async (agent) => {
@@ -1009,14 +1164,14 @@ describe('compact model defaults upgrade', () => {
vi.resetModules();
const prefs = await upgrade();
expect(prefs.isModelEnabled(agent, 'xd', { id: wireId, defaultEnabled: false })).toBe(true);
- expect(prefs.isModelEnabled(agent, 'xd', { id: 'new-late-model', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled(agent, 'xd', { id: 'new-late-model', defaultEnabled: true })).toBe(true);
});
it('maps only declared same-engine switches without replacing versions or restoring a reset alias', async () => {
memStorage.setItem(scopedKey, JSON.stringify({ 'claude-code:xd:fable-5': true }));
const prefs = await upgrade();
expect(prefs.isModelEnabled('claude-code', 'xd', { id: 'chatgpt/fable-5', defaultEnabled: false })).toBe(true);
- expect(prefs.isModelEnabled('claude-code', 'xd', { id: 'chatgpt/fable-5-1', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('claude-code', 'xd', { id: 'chatgpt/fable-5-1', defaultEnabled: true })).toBe(true);
expect(await prefs.resetModelVisibilities('xd', [{ agent: 'claude-code', modelId: 'chatgpt/fable-5' }])).toBe(true);
await prefs.migrateModelVisibilityDefaults('owner-a', 1, [provider]);
expect(prefs.isModelVisibilityCustomized('claude-code', 'xd', 'chatgpt/fable-5')).toBe(false);
@@ -1029,7 +1184,7 @@ describe('compact model defaults upgrade', () => {
expect(memStorage.getItem(markerKey)).toBeNull();
setOwnerClaim('owner-a', 1);
await prefs.migrateModelVisibilityDefaults('owner-a', 1, [provider]);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(false);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(true);
expect(memStorage.getItem(markerKey)).not.toBeNull();
});
@@ -1054,7 +1209,7 @@ describe('compact model defaults upgrade', () => {
else expect(JSON.parse(memStorage.getItem(markerKey)!)).toMatchObject({ eligibleForDefaults: true, scopes: [] });
setOwnerClaim('owner-a', 1);
await prefs.migrateModelVisibilityDefaults('owner-a', 1, [provider]);
- expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(!hasLegacy);
+ expect(prefs.isModelEnabled('pi', 'xd', { id: 'gemini', defaultEnabled: true })).toBe(true);
expect(prefs.isModelEnabled('pi', 'xd', { id: 'fable-5-1', defaultEnabled: true })).toBe(false);
});
diff --git a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
index 5304ba56e5..9582ffd8fd 100644
--- a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
+++ b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
@@ -5,8 +5,8 @@
* 背景:
* 每个来源(provider)在某个 agent 下可能提供很多模型(XD 网关 Claude Code 有 20 个),
* 用户本地全列出来会很长。设置 → 模型供应商 展开来源后,用户可逐个开关哪些模型显示。
- * 显式开关与新用户首次初始化的启用清单分开保存。既有账号不再跟随目录自动加模型;
- * 只有用户点名恢复默认的路线继续读取目录 defaultEnabled。
+ * 显式开关与目录 defaultEnabled 分开:没拨过的跟当前下发默认,拨过的升级也不清。
+ * 目录新增的默认开模型会显示出来;客户端不得把「没开关记录」做成全关。
*
* 为什么 key 必须带 agent:
* 同一来源可同时服务多个 agent(XD = claude-code + codex),且两个 agent 下模型集不同、
@@ -15,7 +15,7 @@
*
* 与系统默认值的关系(configuration-and-overrides.md 模型可见性例外):
* - 原 key 只记显式 override(布尔),独立 owner key 保存一次性的初始化清单。
- * - 新用户初始化后默认不再漂移;老用户缺少开关记录的路线不会被自动补开。
+ * - 没拨过的路线跟随当前目录 defaultEnabled;手动开/关作为 override 跨升级保留。
* - 收藏、历史选择不能改变开关;恢复默认只授权点名路线跟随当前/未来目录。
* - 「全部开启 / 全部关闭」是显式批量动作 → 为当前 agent 该来源的每个模型写显式 override。
*
@@ -71,6 +71,10 @@ function sanitize(raw: unknown): VisibilityMap {
// 进程内缓存(惰性加载)。读多写少,避免每次读都 parse localStorage。
let cache: VisibilityMap | null = null;
+/** Owner/legacy JSON 无法解析时 fail-closed:不能当成「从没拨过」去跟目录默认。 */
+let mapCorrupt = false;
+/** adopt-local 源损坏时保持 latch,不因目标 map 合法而提前清掉。 */
+let adoptionSourceCorrupt = false;
let activeOwnerId: string | null = null;
let activeOwnerGeneration = 0;
let activeOwnerReadyForWrites = false;
@@ -147,11 +151,20 @@ function adoptLocalModelVisibility(ownerId: string): void {
followCatalogKeys: [...new Set([...source.followCatalogKeys.filter((key) => !hasTargetScope(key)), ...target?.followCatalogKeys ?? []])],
};
const targetFollowCatalogKeys = new Set(target?.followCatalogKeys ?? []);
- const sourceOverrides = readStoredMap(window.localStorage.getItem(ownerStorageKey(LOCAL_OWNER_ID)));
+ const sourceParsed = parseStoredMap(window.localStorage.getItem(ownerStorageKey(LOCAL_OWNER_ID)));
+ const targetParsed = parseStoredMap(window.localStorage.getItem(ownerStorageKey(ownerId)));
+ if (sourceParsed.corrupt || targetParsed.corrupt) {
+ // Don't copy an empty sanitization of a broken local map, and don't mark adoption
+ // complete — the source can still be retried after it is repaired.
+ mapCorrupt = true;
+ adoptionSourceCorrupt = sourceParsed.corrupt;
+ return;
+ }
+ adoptionSourceCorrupt = false;
const overrides = {
// Restore defaults is an explicit target choice even though it has no override.
- ...Object.fromEntries(Object.entries(sourceOverrides).filter(([key]) => !targetFollowCatalogKeys.has(key))),
- ...readStoredMap(window.localStorage.getItem(ownerStorageKey(ownerId))),
+ ...Object.fromEntries(Object.entries(sourceParsed.map).filter(([key]) => !targetFollowCatalogKeys.has(key))),
+ ...targetParsed.map,
};
// A failed write leaves the handoff pending. Re-reading and merging under the locks
// makes retry/restart safe without overwriting intervening target choices.
@@ -201,7 +214,7 @@ async function withOwnerLock(
if (ownerId !== activeOwnerId || ownerGeneration !== activeOwnerGeneration
|| activeOwnerMode === 'signed-out') return false;
const snapshot = (): string => JSON.stringify([
- cache, initialization, mayInitializeDefaults, activeOwnerReadyForWrites, activeOwnerMigrationPending,
+ cache, initialization, mayInitializeDefaults, activeOwnerReadyForWrites, activeOwnerMigrationPending, mapCorrupt, adoptionSourceCorrupt,
]);
const before = snapshot();
try {
@@ -235,9 +248,7 @@ async function withOwnerLock(
}
}
function effectiveMap(map: VisibilityMap): VisibilityMap {
- const defaults = { ...initialization?.defaults };
- for (const key of initialization?.followCatalogKeys ?? []) delete defaults[key];
- return { ...defaults, ...map };
+ return { ...map };
}
@@ -249,15 +260,22 @@ function ownerMigrationCompleteKey(ownerId: string): string {
return `${MIGRATION_COMPLETE_KEY_PREFIX}.${encodeURIComponent(ownerId)}`;
}
-function readStoredMap(raw: string | null): VisibilityMap {
- if (!raw) return {};
+function parseStoredMap(raw: string | null): { map: VisibilityMap; corrupt: boolean } {
+ if (raw === null || raw === '') return { map: {}, corrupt: false };
try {
- return sanitize(JSON.parse(raw));
+ return { map: sanitize(JSON.parse(raw)), corrupt: false };
} catch {
- return {};
+ return { map: {}, corrupt: true };
}
}
+function readStoredMap(raw: string | null): VisibilityMap {
+ const parsed = parseStoredMap(raw);
+ if (parsed.corrupt) mapCorrupt = true;
+ else if (raw !== null && raw !== '' && !adoptionSourceCorrupt) mapCorrupt = false;
+ return parsed.map;
+}
+
/**
* 把旧版唯一全局 key 的快照交给 Main 已原子认领的 owner。旧 key 故意保留给并发运行的
* 旧版本;新版本只认 owner-scoped key,所以其它账号不会再次导入这份数据。
@@ -325,9 +343,20 @@ function migrateLegacyVisibility(ownerId: string, ownerGeneration: number): Migr
return { readyForWrites: true, migrationPending: true };
}
- const legacyRaw = window.localStorage.getItem(LEGACY_STORAGE_KEY);
- const legacy = readStoredMap(legacyRaw);
- const scoped = readStoredMap(window.localStorage.getItem(scopedKey));
+ const legacyParsed = parseStoredMap(window.localStorage.getItem(LEGACY_STORAGE_KEY));
+ const scopedParsed = parseStoredMap(window.localStorage.getItem(scopedKey));
+ if (scopedParsed.corrupt) {
+ mapCorrupt = true;
+ return BLOCKED_MIGRATION;
+ }
+ if (legacyParsed.corrupt) {
+ // Don't import a broken snapshot as empty, and don't mark complete just because
+ // the scoped key already has incremental writes from the deferred-import window.
+ mapCorrupt = true;
+ return { readyForWrites: true, migrationPending: true };
+ }
+ const legacy = legacyParsed.map;
+ const scoped = scopedParsed.map;
// 非独占期间可能已经有新设置;完成迁移时由新设置覆盖同槽旧值,其余历史值仍被保留。
window.localStorage.setItem(scopedKey, JSON.stringify({ ...legacy, ...scoped }));
// 快照先落盘再标完成;任一步失败都会在下次写入/登录时幂等重试。
@@ -390,8 +419,11 @@ function mirrorToMain(map: VisibilityMap): void {
const generation = activeOwnerGeneration;
const pending = !!ownerId && (activeOwnerMigrationPending
|| (mayInitializeDefaults && !initialization?.scopes.length));
- const policy = ownerId ? { fallback: false as const,
- followCatalogKeys: initialization?.followCatalogKeys ?? [], ...(pending ? { pending: true as const } : {}) } : undefined;
+ const policy = ownerId ? {
+ followCatalogKeys: initialization?.followCatalogKeys ?? [],
+ ...(pending ? { pending: true as const } : {}),
+ ...(mapCorrupt ? { fallback: false as const } : {}),
+ } : undefined;
const snapshot = effectiveMap(map);
const send = (attempt: number): void => {
if (revision !== mirrorRevision || ownerId !== activeOwnerId || generation !== activeOwnerGeneration) return;
@@ -447,9 +479,19 @@ function persist(map: VisibilityMap, context: VisibilityWriteContext): boolean {
}
// 先确认落盘成功,再更新受控开关状态,避免界面显示成功但重启后设置丢失。
cache = map;
+ if (!adoptionSourceCorrupt) mapCorrupt = false;
+ retryPendingLocalAdoption();
return true;
}
+function retryPendingLocalAdoption(): void {
+ if (!activeOwnerId || activeOwnerMode !== 'cloud' || activeOwnerId === LOCAL_OWNER_ID) return;
+ const completed = `${LOCAL_ADOPTION_KEY_PREFIX}.${encodeURIComponent(activeOwnerId)}`;
+ if (window.localStorage.getItem(completed) === '1') return;
+ adoptLocalModelVisibility(activeOwnerId);
+ if (window.localStorage.getItem(completed) === '1') readOwnerState(activeOwnerId);
+}
+
function subscribe(cb: () => void): () => void {
listeners.add(cb);
return () => {
@@ -478,6 +520,8 @@ export async function setModelVisibilityOwner(
activeOwnerReadyForWrites = false;
activeOwnerMigrationPending = !!ownerId && mode !== 'signed-out';
cache = null;
+ mapCorrupt = false;
+ adoptionSourceCorrupt = false;
initialization = null;
mayInitializeDefaults = false;
if (ownerId && mode !== 'signed-out') {
@@ -492,10 +536,9 @@ export async function setModelVisibilityOwner(
}
/**
- * Initialize a new profile's first nonempty provider/agent catalogs once. Existing profiles
- * keep their explicit switches; history/favorites never grant permission to enable a model.
- * Missing routes remain off. Baselines are separate from user overrides so customization
- * and Restore defaults retain their meaning. No remote catalog enters this path.
+ * Record first-seen provider/agent catalogs for restore-default and alias mapping.
+ * Visibility itself is override ?? current catalog defaultEnabled; this snapshot no longer
+ * hides models the catalog says should be on. History/favorites never write an on switch.
*/
export async function migrateModelVisibilityDefaults(
ownerId: string | null,
@@ -553,9 +596,9 @@ export async function migrateModelVisibilityDefaults(
}
/**
- * 该 (agent, 来源, 模型) 当前是否应显示:显式开关优先,其次初始化清单;未知路线关闭。
+ * 该 (agent, 来源, 模型) 当前是否应显示:显式开关优先,否则跟随当前目录 defaultEnabled。
+ * 偏好 JSON 无法解析、或旧开关尚未迁入 owner namespace 时 fail-closed(不当成从没拨过)。
* model 至少需带 id + 可选 defaultEnabled(直接传 CatalogModel 即可)。
- * 只有首次新用户与明确恢复默认的路线读取目录默认值。
*/
export function isModelEnabled(
agent: AgentKind,
@@ -565,12 +608,14 @@ export function isModelEnabled(
const key = keyOf(agent, providerId, model.id);
const override = load()[key];
if (override !== undefined) return override;
- if (initialization?.followCatalogKeys.includes(key)) return isModelVisible(undefined, model.defaultEnabled);
- if (initialization && (!mayInitializeDefaults || initialization.scopes.length > 0)) {
- return initialization.defaults[key] ?? false;
+ // Restore defaults 记在独立 initialization 里:偏好 map 损坏时仍跟随目录。
+ if (initialization?.followCatalogKeys.includes(key)) {
+ return isModelVisible(undefined, model.defaultEnabled);
}
- return !activeOwnerId || (mayInitializeDefaults && !activeOwnerMigrationPending)
- ? isModelVisible(undefined, model.defaultEnabled) : false;
+ if (mapCorrupt) return false;
+ // 旧全局开关还在等独占导入:不能用目录默认把用户关过的模型暂时打开。
+ if (activeOwnerMigrationPending && !mayInitializeDefaults) return false;
+ return isModelVisible(undefined, model.defaultEnabled);
}
async function setVisibilityTargets(
@@ -598,14 +643,24 @@ async function setVisibilityTargets(
const map = load();
let changed = false;
const next = { ...map };
+ const keys: string[] = [];
for (const { agent, modelId } of targets) {
const k = keyOf(agent, providerId, modelId);
+ keys.push(k);
if (next[k] !== enabled) {
next[k] = enabled;
changed = true;
}
}
- return changed ? persist(next, context) : true;
+ if (changed && !persist(next, context)) return false;
+ const state = initialization ?? emptyInitialization();
+ const follows = new Set(state.followCatalogKeys);
+ let followChanged = false;
+ for (const key of keys) {
+ if (follows.delete(key)) followChanged = true;
+ }
+ if (followChanged && !saveInitialization({ ...state, followCatalogKeys: [...follows] })) return false;
+ return true;
});
}
@@ -704,19 +759,27 @@ export async function resetModelVisibilities(
// trusting event.newValue, which may already be stale when the event is delivered.
const removeStorageListener = (() => {
if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
+ const watchesPendingSource = (key: string): boolean => {
+ if (!activeOwnerId) return false;
+ if (key === LEGACY_STORAGE_KEY) {
+ return activeOwnerMode !== 'signed-out'
+ && activeOwnerMigrationPending
+ && window.localStorage.getItem(ownerMigrationCompleteKey(activeOwnerId)) !== '1';
+ }
+ if (activeOwnerMode !== 'cloud' || activeOwnerId === LOCAL_OWNER_ID) return false;
+ if (window.localStorage.getItem(`${LOCAL_ADOPTION_KEY_PREFIX}.${encodeURIComponent(activeOwnerId)}`) === '1') {
+ return false;
+ }
+ return key === initializationKey(LOCAL_OWNER_ID) || key === ownerStorageKey(LOCAL_OWNER_ID);
+ };
const onStorage = (event: StorageEvent): void => {
if (!activeOwnerId || (event.storageArea && event.storageArea !== window.localStorage)) return;
if (event.key !== null && event.key !== initializationKey(activeOwnerId)
&& event.key !== ownerStorageKey(activeOwnerId)
- && event.key !== ownerMigrationCompleteKey(activeOwnerId)) return;
+ && event.key !== ownerMigrationCompleteKey(activeOwnerId)
+ && !watchesPendingSource(event.key)) return;
const ownerId = activeOwnerId;
- void withOwnerLock(ownerId, activeOwnerGeneration, () => {
- if (window.localStorage.getItem(ownerMigrationCompleteKey(ownerId)) === '1') {
- activeOwnerReadyForWrites = true;
- activeOwnerMigrationPending = false;
- }
- return true;
- });
+ void withOwnerLock(ownerId, activeOwnerGeneration, ensureActiveOwnerReadyForWrites);
};
window.addEventListener('storage', onStorage);
return () => window.removeEventListener('storage', onStorage);
@@ -744,6 +807,8 @@ export function __resetForTest(): void {
const currentMigrationKey = activeOwnerId ? ownerMigrationCompleteKey(activeOwnerId) : null;
if (activeOwnerId) window.localStorage.removeItem(initializationKey(activeOwnerId));
cache = null;
+ mapCorrupt = false;
+ adoptionSourceCorrupt = false;
initialization = null;
mayInitializeDefaults = false;
activeOwnerId = null;
diff --git a/apps/desktop/src/shared/modelVisibility.ts b/apps/desktop/src/shared/modelVisibility.ts
index 3dc34bf100..68567911f3 100644
--- a/apps/desktop/src/shared/modelVisibility.ts
+++ b/apps/desktop/src/shared/modelVisibility.ts
@@ -28,11 +28,12 @@ export function isModelVisibilityLegacyOwnerClaim(
);
}
-/** Optional append-only IPC policy; omitted by older renderers. */
+/** Optional IPC policy; omitted by older renderers. */
export interface ModelVisibilityPolicy {
- fallback: false;
+ /** false = missing routes off (legacy freeze). Omit to follow catalog defaultEnabled. */
+ fallback?: false;
/** Renderer still needs the catalog/legacy claim; this is not an effective snapshot. */
pending?: true;
- /** Only an explicit Restore defaults action may follow future catalog defaults. */
+ /** Restore-default routes; unused when catalog fallback is in effect. */
followCatalogKeys: string[];
}
diff --git a/docs/dev-rules/configuration-and-overrides.md b/docs/dev-rules/configuration-and-overrides.md
index 6504af3561..ed4641e5b7 100644
--- a/docs/dev-rules/configuration-and-overrides.md
+++ b/docs/dev-rules/configuration-and-overrides.md
@@ -34,24 +34,16 @@ token)与 [`engineering-conventions.md`](engineering-conventions.md)(i18n)
模型资料的系统层再区分公共默认、供应商默认、供应商实报与服务端明确修正;用户覆盖始终最高。
发现快照和用户字段分开持久化,详见 [模型资料优先级](../product-rules/model-metadata-precedence.md)。
-### 模型可见性例外(2026-09-07 用户定稿)
-
-模型启用清单只在新用户首次使用时初始化,不能随目录默认值更新而扩展或重置。
-此例外仅适用于模型显示开关,不改变思考深度等其它配置的通用契约。
-
-- 新用户首次出现的非空 provider/agent 目录保存独立初始化清单,不标记为用户自定义。
- 新配置资格只由 Main 在新建账号本地数据库前持久记录;已有或迁入数据库没有该记录时
- 按老配置处理,不能用模型相关 localStorage 为空推断新用户。数据库创建尚未就绪时等待。
- 首次初始化资格先于迁移产物持久保存,完成状态按来源与引擎分别记录;目录到达前退出、
- 写入失败或操作其它模型开关不取消待初始化范围的资格。同一来源与引擎后续新增的模型
- 默认关闭;初始化结果跨重启保持。
-- 同账号的初始化、手动开关与恢复默认写入共用跨窗口锁,锁内重读最新记录后应用本次操作;
- 保存完成才返回成功,其他窗口重读持久状态并刷新主进程镜像,不能靠整表乐观覆盖后重算清单。
-- 老用户已有明确开启、关闭记录均优先保留,兼容引擎也一样;收藏、历史选择、引擎偏好
- 不能作为重新开启模型的依据。缺少旧开关记录时不猜测、不补开。
-- 手动开关始终覆盖初始化清单。用户明确恢复默认时,只清除本次点名路线的 override,
- 允许这些路线重新跟随目录默认值;这不授权未来新增路线自动开启。
-- 桌面、IM 与远端模型列表使用同一有效开关;旧客户端通过普通布尔开关快照获得结果。
+### 模型可见性(2026-09-13 用户更正)
+
+显示开关的有效值是 **用户显式 override ?? 当前目录 defaultEnabled**。此条只约束模型显示开关。
+
+- 目录下发哪些默认开、哪些默认关,没拨过开关的路线一律跟随。目录后来新增的默认开模型
+ 要显示出来;客户端不得把「没有开关记录」做成全关。
+- 用户手动开过或关过的写成 override,升级不清、不覆盖。
+- 「恢复默认」只删除本次点名路线的 override,重新跟随当前目录。
+- 收藏、历史选择、引擎偏好不能当成开关。
+- 桌面、IM 与远端用同一套 override;没 override 的路线由各端按当时目录 defaultEnabled 计算。
## 3. 默认值演进与迁移