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(desktop): 按账号隔离模型可见性设置

liugaowei85d1392b500d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b188b5603a..3961670edd 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -449,6 +449,7 @@ import {
} from './maker-host/createDesktopProviderService.js';
import { isCindyEmbeddingModelAvailable } from './maker-host/provider-access-policy.js';
import { setCustomProviders } from './maker-host/active-catalog.js';
+import { clearModelVisibilityMirror } from './maker-host/model-visibility-mirror.js';
import { setClaudeSupportedModelsListener } from '@cindy/maker-core';
import {
noteAnthropicSdkSupportedModels,
@@ -1178,6 +1179,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// before any Agent route can start. A failed DB read therefore stays fail-closed (empty)
// instead of retaining the previous owner's endpoint or model entries.
setCustomProviders([]);
+ clearModelVisibilityMirror();
// 远程会话的镜像冷缓存里是别的设备的聊天内容。owner 命名空间已经保证下一个账号读不到
// 它,但登出后不该在盘上留着 —— 这里 owner 还指向**旧账号**(commitActiveAppSession 在
// teardown 之后才切),正是唯一能清准的时机。
diff --git a/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
index daa3c45095..9100dae916 100644
--- a/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/model-visibility-mirror.test.ts
@@ -7,9 +7,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
__resetModelVisibilityMirrorForTest,
+ clearModelVisibilityMirror,
getModelVisibilityOverride,
setModelVisibilityMirror,
syncModelVisibilityMirror,
+ syncModelVisibilityMirrorForOwner,
} from '../model-visibility-mirror.js';
afterEach(() => {
@@ -40,6 +42,12 @@ describe('model-visibility-mirror', () => {
expect(getModelVisibilityOverride('claude-code', 'xd', 'b')).toBe(true);
});
+ it('账号边界同步清空旧 owner 的进程内镜像', () => {
+ setModelVisibilityMirror({ 'codex:openai:gpt-5.6': false });
+ clearModelVisibilityMirror();
+ expect(getModelVisibilityOverride('codex', 'openai', 'gpt-5.6')).toBeUndefined();
+ });
+
it('仅在净化后的整表实际变化时返回 true,供调用方广播目录失效事件', () => {
expect(setModelVisibilityMirror({
'claude-code:xd:a': false,
@@ -77,4 +85,42 @@ describe('model-visibility-mirror', () => {
setModelVisibilityMirror(null);
expect(getModelVisibilityOverride('claude-code', 'xd', 'a')).toBeUndefined();
});
+
+ it('只接受当前稳定 owner 的快照,拒绝切换中和迟到 generation', () => {
+ const invalidate = vi.fn();
+ const activeOwner = { dataOwnerId: 'owner-b', ownerGeneration: 2 };
+
+ expect(syncModelVisibilityMirrorForOwner(
+ { 'codex:openai:gpt-5.6': false },
+ { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ activeOwner,
+ false,
+ invalidate,
+ )).toBe(false);
+ expect(syncModelVisibilityMirrorForOwner(
+ { 'codex:openai:gpt-5.6': false },
+ { dataOwnerId: 'owner-b', ownerGeneration: 1 },
+ { dataOwnerId: 'owner-b', ownerGeneration: 3 },
+ false,
+ invalidate,
+ )).toBe(false);
+ expect(syncModelVisibilityMirrorForOwner(
+ { 'codex:openai:gpt-5.6': false },
+ activeOwner,
+ activeOwner,
+ true,
+ invalidate,
+ )).toBe(false);
+ expect(getModelVisibilityOverride('codex', 'openai', 'gpt-5.6')).toBeUndefined();
+
+ expect(syncModelVisibilityMirrorForOwner(
+ { 'codex:openai:gpt-5.6': false },
+ activeOwner,
+ activeOwner,
+ false,
+ invalidate,
+ )).toBe(true);
+ expect(getModelVisibilityOverride('codex', 'openai', 'gpt-5.6')).toBe(false);
+ expect(invalidate).toHaveBeenCalledOnce();
+ });
});
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.ts
new file mode 100644
index 0000000000..9c67a2df5b
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/model-visibility-owner-claim.test.ts
@@ -0,0 +1,114 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const harness = vi.hoisted(() => ({
+ root: '',
+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
+ ownerId: 'owner-a' as string | null,
+ ownerGeneration: 1,
+ boundaryPending: false,
+ exclusive: true,
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: () => harness.root },
+}));
+
+vi.mock('../../appSessionState.js', () => ({
+ dataOwnerStorageKey: (ownerId: string) => `key-${ownerId}`,
+ getActiveAppSession: () => ({
+ mode: harness.mode,
+ dataOwnerId: harness.ownerId,
+ }),
+ getActiveDataOwnerPushStamp: () => ({
+ dataOwnerId: harness.ownerId,
+ ownerGeneration: harness.ownerGeneration,
+ }),
+ isAppSessionBoundaryPending: () => harness.boundaryPending,
+}));
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }),
+}));
+
+vi.mock('../../ownerNamespaceMigration.js', () => ({
+ hasExclusiveSharedLegacyUserDataAccess: () => harness.exclusive,
+}));
+
+import { claimLegacyModelVisibilityOwner } from '../model-visibility-owner-claim.js';
+
+const markerName = 'model-visibility-renderer-legacy-owner.v1.json';
+
+beforeEach(() => {
+ harness.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-model-visibility-owner-'));
+ harness.mode = 'cloud';
+ harness.ownerId = 'owner-a';
+ harness.ownerGeneration = 1;
+ harness.boundaryPending = false;
+ harness.exclusive = true;
+});
+
+afterEach(() => {
+ fs.rmSync(harness.root, { recursive: true, force: true });
+});
+
+describe('model visibility legacy Renderer owner claim', () => {
+ it('atomically binds the legacy key to the active verified cloud account only once', () => {
+ expect(claimLegacyModelVisibilityOwner()).toEqual({
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 1,
+ claimed: true,
+ claimedByOtherOwner: false,
+ canInitialize: true,
+ });
+ expect(JSON.parse(fs.readFileSync(path.join(harness.root, markerName), 'utf-8'))).toEqual({
+ version: 1,
+ ownerKey: 'key-owner-a',
+ });
+
+ harness.ownerId = 'owner-b';
+ harness.ownerGeneration = 2;
+ expect(claimLegacyModelVisibilityOwner()).toEqual({
+ dataOwnerId: 'owner-b',
+ ownerGeneration: 2,
+ claimed: false,
+ claimedByOtherOwner: true,
+ canInitialize: false,
+ });
+ });
+
+ it('does not claim from signed-out, local, boundary-pending, or shared access', () => {
+ harness.mode = 'local';
+ expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);
+ harness.mode = 'cloud';
+ harness.boundaryPending = true;
+ expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);
+ harness.boundaryPending = false;
+ harness.exclusive = false;
+ expect(claimLegacyModelVisibilityOwner().claimed).toBe(false);
+ expect(fs.existsSync(path.join(harness.root, markerName))).toBe(false);
+ });
+
+ it('keeps a claimed owner readable but blocks legacy initialization without exclusivity', () => {
+ expect(claimLegacyModelVisibilityOwner().canInitialize).toBe(true);
+ harness.exclusive = false;
+ expect(claimLegacyModelVisibilityOwner()).toMatchObject({
+ claimed: true,
+ claimedByOtherOwner: false,
+ canInitialize: false,
+ });
+ });
+
+ it('fails closed instead of replacing a malformed marker', () => {
+ fs.writeFileSync(path.join(harness.root, markerName), '{broken', 'utf-8');
+ expect(claimLegacyModelVisibilityOwner()).toMatchObject({
+ claimed: false,
+ claimedByOtherOwner: false,
+ canInitialize: false,
+ });
+ expect(fs.readFileSync(path.join(harness.root, markerName), 'utf-8')).toBe('{broken');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/model-visibility-mirror.ts b/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
index df41d7b81c..347c3868a2 100644
--- a/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
+++ b/apps/desktop/src/main/maker-host/model-visibility-mirror.ts
@@ -18,6 +18,8 @@
import type { AgentKind } from '@cindy/model-providers';
+import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';
+
/** override 表:key=`${agent}:${providerId}:${modelId}` → 用户显式设定的可见性。 */
type VisibilityMap = Record<string, boolean>;
@@ -67,6 +69,28 @@ export function syncModelVisibilityMirror(
return true;
}
+/**
+ * 只接受当前稳定 owner 的 renderer 快照。账号切换期间或旧 generation 的迟到 invoke 必须
+ * fail closed,否则 A 的内存镜像会在 B 登录后继续影响 IM /model 与 device-link 控制端。
+ */
+export function syncModelVisibilityMirrorForOwner(
+ raw: unknown,
+ requestedOwner: unknown,
+ activeOwner: DataOwnerPushStamp,
+ boundaryPending: boolean,
+ onChanged: () => void,
+): boolean {
+ if (
+ boundaryPending
+ || !isDataOwnerPushStamp(requestedOwner)
+ || requestedOwner.dataOwnerId !== activeOwner.dataOwnerId
+ || requestedOwner.ownerGeneration !== activeOwner.ownerGeneration
+ ) {
+ return false;
+ }
+ return syncModelVisibilityMirror(raw, onChanged);
+}
+
/**
* 取某 (agent, 来源, 模型) 的可见性 override(用户没显式开关过 ⇒ undefined,调用方回落目录默认)。
* 与共享包 `isModelVisible(override, defaultEnabled)` 配合得到最终可见性。
@@ -87,7 +111,12 @@ export function getModelVisibilityMirrorSnapshot(): Record<string, boolean> {
return { ...mirror };
}
+/** Clear the process-global mirror at an account boundary before the next owner is committed. */
+export function clearModelVisibilityMirror(): void {
+ mirror = {};
+}
+
/** 测试用 —— 重置镜像。 */
export function __resetModelVisibilityMirrorForTest(): void {
- mirror = {};
+ clearModelVisibilityMirror();
}
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.ts
new file mode 100644
index 0000000000..a14f1a8afb
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/model-visibility-owner-claim.ts
@@ -0,0 +1,116 @@
+import { app } from 'electron';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ dataOwnerStorageKey,
+ getActiveAppSession,
+ getActiveDataOwnerPushStamp,
+ isAppSessionBoundaryPending,
+} from '../appSessionState.js';
+import { createLogger } from '../logger.js';
+import { hasExclusiveSharedLegacyUserDataAccess } from '../ownerNamespaceMigration.js';
+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
+import type { ModelVisibilityLegacyOwnerClaim } from '../../shared/modelVisibility.js';
+
+const MARKER_FILE = 'model-visibility-renderer-legacy-owner.v1.json';
+const MAX_MARKER_BYTES = 1_024;
+
+interface OwnerMarker {
+ version: 1;
+ ownerKey: string;
+}
+
+type OwnerMarkerRead =
+ | { kind: 'valid'; marker: OwnerMarker }
+ | { kind: 'missing' }
+ | { kind: 'blocked' };
+
+const log = createLogger('modelVisibilityOwnerClaim');
+
+function readOwnerMarker(markerPath: string): OwnerMarkerRead {
+ try {
+ const bytes = readBoundedFileNoFollowSync(markerPath, MAX_MARKER_BYTES);
+ if (bytes === null) return { kind: 'blocked' };
+ const parsed: unknown = JSON.parse(bytes.toString('utf-8'));
+ if (
+ !parsed
+ || typeof parsed !== 'object'
+ || Array.isArray(parsed)
+ || (parsed as { version?: unknown }).version !== 1
+ || typeof (parsed as { ownerKey?: unknown }).ownerKey !== 'string'
+ ) {
+ return { kind: 'blocked' };
+ }
+ return { kind: 'valid', marker: parsed as OwnerMarker };
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
+ ? { kind: 'missing' }
+ : { kind: 'blocked' };
+ }
+}
+
+/**
+ * Atomically binds the pre-account Renderer preference key to the cloud account that is active
+ * during this upgrade. The marker is model-visibility-specific: older general migrations may have
+ * been claimed by a historical account and therefore cannot establish who owns this localStorage.
+ */
+export function claimLegacyModelVisibilityOwner(): ModelVisibilityLegacyOwnerClaim {
+ const stamp = getActiveDataOwnerPushStamp();
+ const session = getActiveAppSession();
+ if (
+ session.mode !== 'cloud'
+ || !stamp.dataOwnerId
+ || session.dataOwnerId !== stamp.dataOwnerId
+ || isAppSessionBoundaryPending()
+ ) {
+ return {
+ ...stamp,
+ claimed: false,
+ claimedByOtherOwner: false,
+ canInitialize: false,
+ };
+ }
+
+ const ownerKey = dataOwnerStorageKey(stamp.dataOwnerId);
+ const markerPath = path.join(app.getPath('userData'), MARKER_FILE);
+ const exclusiveAtStart = hasExclusiveSharedLegacyUserDataAccess();
+ let state = readOwnerMarker(markerPath);
+ if (state.kind === 'missing' && exclusiveAtStart) {
+ const temporaryPath = `${markerPath}.init-${process.pid}-${randomUUID()}`;
+ try {
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
+ fs.writeFileSync(
+ temporaryPath,
+ JSON.stringify({ version: 1, ownerKey } satisfies OwnerMarker),
+ { encoding: 'utf-8', flag: 'wx', mode: 0o600 },
+ );
+ fs.linkSync(temporaryPath, markerPath);
+ log.info('legacy Renderer model visibility owner claimed', { ownerKey });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
+ log.warn('failed to claim legacy Renderer model visibility owner', {
+ ownerKey,
+ errorCode: (error as NodeJS.ErrnoException).code ?? 'UNKNOWN',
+ });
+ }
+ } finally {
+ try {
+ fs.unlinkSync(temporaryPath);
+ } catch {
+ // The temporary marker is never authoritative until its hard link exists.
+ }
+ }
+ state = readOwnerMarker(markerPath);
+ }
+
+ const claimed = state.kind === 'valid' && state.marker.ownerKey === ownerKey;
+ return {
+ ...stamp,
+ claimed,
+ claimedByOtherOwner: state.kind === 'valid' && !claimed,
+ canInitialize:
+ claimed && exclusiveAtStart && hasExclusiveSharedLegacyUserDataAccess(),
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 270525789f..06198fafa5 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -222,9 +222,12 @@ export const MAKER_INVOKE = {
/**
* renderer → main 单向镜像「模型显示/隐藏」override(modelVisibilityPrefs)。
* override 真源仍在 renderer localStorage;main 只缓存一份内存副本,供 IM `/model`
- * 派生模型列表时复用同一套可见性过滤(两端列表口径一致)。fire-and-forget,不落盘。
+ * 派生模型列表时复用同一套可见性过滤(两端列表口径一致)。入参带 dataOwnerId +
+ * ownerGeneration,Main 拒绝账号切换期间的迟到快照。fire-and-forget,不落盘。
*/
MODEL_VISIBILITY_SYNC: 'maker:model-visibility:sync',
+ /** Sync read: which verified cloud owner may import the pre-account Renderer preference key. */
+ MODEL_VISIBILITY_LEGACY_OWNER_CLAIM_SYNC: 'maker:model-visibility:legacy-owner-claim-sync',
/**
* 「模型 / 供应商停用」override 写入(model-disable-store,main 侧持久化真源)。
* 入参 = { kind:'model', providerId, modelIds: string[], disabled: boolean }
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ceda46f646..55799957da 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -41,7 +41,11 @@ import {
} from '@cindy/device-link';
import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
-import { getActiveAppSession, getActiveDataOwnerPushStamp } from '../appSessionState.js';
+import {
+ getActiveAppSession,
+ getActiveDataOwnerPushStamp,
+ isAppSessionBoundaryPending,
+} from '../appSessionState.js';
import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';
import type { AgentMeta } from '../../renderer/lib/ccAgent.types';
import {
@@ -726,8 +730,9 @@ import {
import { setSessionEffort, setSessionFastMode } from '../maker-host/session-effort-store.js';
import {
getModelVisibilityMirrorSnapshot,
- syncModelVisibilityMirror,
+ syncModelVisibilityMirrorForOwner,
} from '../maker-host/model-visibility-mirror.js';
+import { claimLegacyModelVisibilityOwner } from '../maker-host/model-visibility-owner-claim.js';
import {
clearProviderDisableOverrides,
setModelsDisabled,
@@ -13132,10 +13137,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// main 缓存供 IM /model 与 device-link provider:list 复用同一套可见性过滤。值实变时
// 复用 PROVIDER_CHANGED 目录失效事件,让已连接控制端驱逐缓存并重拉 override 快照。
// 容错存储(非对象 ⇒ 清空),无错误路径,故不需要 throwIpcError。
- ipcMain.handle(MAKER_INVOKE.MODEL_VISIBILITY_SYNC, async (_e, map: unknown) => {
- syncModelVisibilityMirror(map, () => {
- broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
- });
+ ipcMain.on(MAKER_INVOKE.MODEL_VISIBILITY_LEGACY_OWNER_CLAIM_SYNC, (event) => {
+ assertTrustedAppRendererEvent(event);
+ event.returnValue = claimLegacyModelVisibilityOwner();
+ });
+
+ ipcMain.handle(MAKER_INVOKE.MODEL_VISIBILITY_SYNC, async (
+ event,
+ dataOwnerId: unknown,
+ ownerGeneration: unknown,
+ map: unknown,
+ ) => {
+ assertTrustedAppRendererEvent(event);
+ syncModelVisibilityMirrorForOwner(
+ map,
+ { dataOwnerId, ownerGeneration },
+ getActiveDataOwnerPushStamp(),
+ isAppSessionBoundaryPending(),
+ () => {
+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});
+ },
+ );
});
// 附加只读引用目录的运行时 closure 推送。DB 持久化由 renderer 同步调
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 1e26348286..a950e17a96 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -83,6 +83,10 @@ import type {
SubagentModelSettingsState,
SubagentModelSettingsWriteResult,
} from '../shared/subagentModelSettings';
+import {
+ isModelVisibilityLegacyOwnerClaim,
+ type ModelVisibilityLegacyOwnerClaim,
+} from '../shared/modelVisibility';
import type { VoiceInputAsrMode, VoiceInputProviderKind } from '../shared/voiceInputAsrProfiles';
import type {
VoiceInputRefinerProviderKind,
@@ -5088,10 +5092,28 @@ contextBridge.exposeInMainWorld('electronAPI', {
/**
* renderer → main 单向镜像「模型显示/隐藏」override 整张快照(modelVisibilityPrefs)。
* 让 IM /model 在 main 侧复用同一套可见性过滤,与应用内模型列表逐模型一致。
- * fire-and-forget(忽略返回),main 仅缓存于内存、不落盘。
+ * dataOwnerId + ownerGeneration 用于拒绝账号切换期间的迟到快照;main 仅缓存于内存、不落盘。
*/
- syncModelVisibility: (map: Record<string, boolean>): Promise<void> =>
- ipcRenderer.invoke('maker:model-visibility:sync', map),
+ syncModelVisibility: (
+ dataOwnerId: string | null,
+ ownerGeneration: number,
+ map: Record<string, boolean>,
+ ): Promise<void> =>
+ ipcRenderer.invoke('maker:model-visibility:sync', dataOwnerId, ownerGeneration, map),
+ claimLegacyModelVisibilityOwner: (): ModelVisibilityLegacyOwnerClaim => {
+ const value: unknown = ipcRenderer.sendSync(
+ 'maker:model-visibility:legacy-owner-claim-sync',
+ );
+ return isModelVisibilityLegacyOwnerClaim(value)
+ ? value
+ : {
+ dataOwnerId: null,
+ ownerGeneration: 0,
+ claimed: false,
+ claimedByOtherOwner: false,
+ canInitialize: false,
+ };
+ },
/**
* 「模型 / 供应商停用」override 写入(main 侧持久化真源 model-disable-store)。
* 成功后 main 广播 PROVIDER_CHANGED,renderer 经 useProviders 快照刷新拿到
diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
index 7bcb369e00..b37951d362 100644
--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => {
reset: vi.fn(),
getMe: vi.fn(async () => ({ role: 'user' })),
clearWorkersCache: vi.fn(),
+ setModelVisibilityOwner: vi.fn(),
invalidateProvidersSnapshot: vi.fn(),
preloadLocalCatalogSnapshot: vi.fn(async () => undefined),
confirm: vi.fn(async () => true),
@@ -56,6 +57,9 @@ vi.mock('@/lib/meService', () => ({ getMe: mocks.getMe }));
vi.mock('@/features/cc-agent/hooks/useWorkers', () => ({
clearWorkersCache: mocks.clearWorkersCache,
}));
+vi.mock('@/state/modelVisibilityPrefs', () => ({
+ setModelVisibilityOwner: mocks.setModelVisibilityOwner,
+}));
vi.mock('@/lib/providersSnapshotStore', () => ({
invalidateProvidersSnapshot: mocks.invalidateProvidersSnapshot,
}));
@@ -135,6 +139,7 @@ describe('AuthContext session cache boundaries', () => {
mocks.reset.mockClear();
mocks.getMe.mockClear();
mocks.clearWorkersCache.mockClear();
+ mocks.setModelVisibilityOwner.mockClear();
mocks.invalidateProvidersSnapshot.mockClear();
mocks.preloadLocalCatalogSnapshot.mockClear();
dataOwnerGenerationTesting.reset();
@@ -162,10 +167,12 @@ describe('AuthContext session cache boundaries', () => {
await waitFor(() => expect(view.result.current.user?.id).toBe('account-a'));
expect(mocks.reset).toHaveBeenCalledTimes(1);
expect(mocks.invalidateProvidersSnapshot).toHaveBeenCalledTimes(1);
+ expect(mocks.setModelVisibilityOwner).toHaveBeenLastCalledWith('account-a', 1, 'cloud');
act(() => mocks.emitAuth(authState('account-b')));
expect(mocks.reset).toHaveBeenCalledTimes(2);
expect(mocks.invalidateProvidersSnapshot).toHaveBeenCalledTimes(2);
+ expect(mocks.setModelVisibilityOwner).toHaveBeenLastCalledWith('account-b', 1, 'cloud');
act(() => mocks.emitAuth(authState('account-b')));
expect(mocks.reset).toHaveBeenCalledTimes(2);
@@ -174,6 +181,7 @@ describe('AuthContext session cache boundaries', () => {
act(() => mocks.emitAuth(authState(null)));
expect(mocks.reset).toHaveBeenCalledTimes(3);
expect(mocks.invalidateProvidersSnapshot).toHaveBeenCalledTimes(3);
+ expect(mocks.setModelVisibilityOwner).toHaveBeenLastCalledWith(null, 2, 'signed-out');
await act(async () => {
await view.result.current.logout();
diff --git a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
index b4814775ff..6c223c5af0 100644
--- a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
@@ -4,11 +4,12 @@
* 回归 state/modelVisibilityPrefs.ts 的核心约定:
* 1. 无 override → 跟随目录默认值(defaultEnabled 缺省=开 / =false 默认关 / =true 默认开)
* 2. set override 覆盖目录默认(把默认开的关掉 / 把默认关的打开)
- * 3. set/get 往返 + localStorage 持久化(模拟 app 重启)
+ * 3. set/get 往返 + owner-scoped localStorage 持久化(模拟 app 重启)
* 4. 按 (agent, providerId, modelId) 分槽:同名模型在 cc / codex 互不覆盖
* 5. setManyVisibility 批量(全部关 / 全部开)写显式 override
* 6. 同值写入短路(不抛)
- * 7. schema 损坏 / 脏数据 → 静默回退,跟随目录默认
+ * 7. 旧全局 key 只由 Main 仲裁出的首个 owner 认领,新账号默认隔离
+ * 8. schema 损坏 / 脏数据 → 静默回退,跟随目录默认
*
* 项目 vitest env=node,无 window。沿用 providerModelMemory.test.ts 的最小 localStorage stub。
*/
@@ -32,10 +33,44 @@ class MemLocalStorage {
}
let memStorage: MemLocalStorage;
+const syncModelVisibility = vi.fn(async () => undefined);
+let ownerClaim: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ claimed: boolean;
+ claimedByOtherOwner?: boolean;
+ canInitialize: boolean;
+};
+
+function setOwnerClaim(
+ dataOwnerId: string | null,
+ ownerGeneration: number,
+ claimed = true,
+ canInitialize = true,
+ claimedByOtherOwner = false,
+): void {
+ ownerClaim = {
+ dataOwnerId,
+ ownerGeneration,
+ claimed,
+ claimedByOtherOwner,
+ canInitialize,
+ };
+}
beforeEach(() => {
memStorage = new MemLocalStorage();
- vi.stubGlobal('window', { localStorage: memStorage });
+ syncModelVisibility.mockClear();
+ setOwnerClaim('owner-a', 1);
+ vi.stubGlobal('window', {
+ localStorage: memStorage,
+ electronAPI: {
+ maker: {
+ syncModelVisibility,
+ claimLegacyModelVisibilityOwner: () => ownerClaim,
+ },
+ },
+ });
vi.stubGlobal('localStorage', memStorage);
vi.resetModules();
});
@@ -44,9 +79,19 @@ async function loadModule() {
return await import('@/state/modelVisibilityPrefs');
}
+async function loadModuleForOwner(
+ ownerId: string | null = 'owner-a',
+ ownerGeneration = 1,
+ mode: 'signed-out' | 'local' | 'cloud' = 'cloud',
+) {
+ const module = await loadModule();
+ module.setModelVisibilityOwner(ownerId, ownerGeneration, mode);
+ return module;
+}
+
describe('modelVisibilityPrefs store', () => {
it('无 override:跟随目录默认值(缺省=开 / false=关 / true=开)', async () => {
- const { isModelEnabled } = await loadModule();
+ const { isModelEnabled } = await loadModuleForOwner();
// defaultEnabled 缺省 → 开
expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(true);
// defaultEnabled: true → 开
@@ -56,7 +101,7 @@ describe('modelVisibilityPrefs store', () => {
});
it('set override 覆盖目录默认:默认开的关掉、默认关的打开', async () => {
- const { isModelEnabled, setModelVisibility } = await loadModule();
+ const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
// 默认开 → 用户关
setModelVisibility('claude-code', 'xd', 'claude-opus-4-8', false);
expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(false);
@@ -66,17 +111,17 @@ describe('modelVisibilityPrefs store', () => {
});
it('set/get 往返 + 跨重启持久化', async () => {
- const m1 = await loadModule();
+ const m1 = await loadModuleForOwner();
m1.setModelVisibility('codex', 'xd', 'gpt-5.5', false);
expect(m1.isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(false);
vi.resetModules();
- const m2 = await loadModule();
+ const m2 = await loadModuleForOwner();
expect(m2.isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(false);
});
it('按 (agent, providerId, modelId) 分槽:同名 gpt-5.5 在 cc / codex 互不覆盖', async () => {
- const { isModelEnabled, setModelVisibility } = await loadModule();
+ const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
setModelVisibility('claude-code', 'xd', 'gpt-5.5', false); // cc 下关掉
// codex 下不受影响,仍跟随默认(开)
expect(isModelEnabled('claude-code', 'xd', { id: 'gpt-5.5' })).toBe(false);
@@ -84,14 +129,14 @@ describe('modelVisibilityPrefs store', () => {
});
it('同一来源不同 provider 互不影响(xd vs openai)', async () => {
- const { isModelEnabled, setModelVisibility } = await loadModule();
+ const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
setModelVisibility('codex', 'xd', 'gpt-5.5', false);
expect(isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(false);
expect(isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(true);
});
it('setManyVisibility:全部关 → 全部开,写显式 override(含目录默认关的也被打开)', async () => {
- const { isModelEnabled, setManyVisibility } = await loadModule();
+ const { isModelEnabled, setManyVisibility } = await loadModuleForOwner();
const ids = ['claude-opus-4-8', 'claude-sonnet-4-6', 'b'];
setManyVisibility('claude-code', 'xd', ids, false);
for (const id of ids) {
@@ -104,24 +149,104 @@ describe('modelVisibilityPrefs store', () => {
});
it('同值写入短路:不抛,值保持', async () => {
- const { isModelEnabled, setModelVisibility } = await loadModule();
+ const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
setModelVisibility('codex', 'openai', 'gpt-5.4', false);
expect(() => setModelVisibility('codex', 'openai', 'gpt-5.4', false)).not.toThrow();
expect(isModelEnabled('codex', 'openai', { id: 'gpt-5.4' })).toBe(false);
});
it('空 providerId / modelId 入参被忽略', async () => {
- const { isModelEnabled, setModelVisibility } = await loadModule();
+ const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
setModelVisibility('claude-code', '', 'x', false);
setModelVisibility('claude-code', 'xd', '', false);
// 都没写进去 → 仍跟随默认(开)
expect(isModelEnabled('claude-code', 'xd', { id: 'x' })).toBe(true);
});
+ it('首个已认领 owner 导入旧全局 override,切换到新账号后默认隔离', async () => {
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1',
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+ const module = await loadModuleForOwner('owner-a', 1);
+
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-a')).toBe(
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+
+ setOwnerClaim('owner-b', 2, false, false, true);
+ module.setModelVisibilityOwner('owner-b', 2, 'cloud');
+
+ 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, {});
+
+ setOwnerClaim('owner-a', 3, true, true);
+ module.setModelVisibilityOwner('owner-a', 3, 'cloud');
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(false);
+ });
+
+ it('仲裁暂不可用时不允许 owner 写入覆盖迁移输入,恢复后重试并保留旧 override', async () => {
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1',
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+ setOwnerClaim('owner-a', 1, true, false);
+ const module = await loadModuleForOwner();
+
+ module.setModelVisibility('codex', 'openai', 'gpt-5.5', false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-a')).toBeNull();
+
+ setOwnerClaim('owner-a', 1, true, true);
+ module.setModelVisibility('codex', 'openai', 'gpt-5.5', false);
+
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(false);
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(false);
+ });
+
+ it('已有 owner-scoped override 优先,迁移不会覆盖', async () => {
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1',
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1.owner.owner-a',
+ JSON.stringify({ 'codex:openai:gpt-5.6': true }),
+ );
+
+ const module = await loadModuleForOwner();
+
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(true);
+ });
+
+ it('未登录时不写 override,并将空镜像推给 Main 清除前账号状态', async () => {
+ const module = await loadModuleForOwner();
+ module.setModelVisibility('codex', 'openai', 'gpt-5.6', false);
+
+ module.setModelVisibilityOwner(null, 2, 'signed-out');
+ module.setModelVisibility('codex', 'openai', 'gpt-5.6', false);
+
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(true);
+ expect(syncModelVisibility).toHaveBeenLastCalledWith(null, 2, {});
+ });
+
+ it('本地 profile 使用自己的 namespace,但不会认领云账号的历史全局 key', async () => {
+ memStorage.setItem(
+ 'xdt:modelVisibilityPrefs:v1',
+ JSON.stringify({ 'codex:openai:gpt-5.6': false }),
+ );
+ const module = await loadModuleForOwner('local-v1', 1, 'local');
+
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.6' })).toBe(true);
+ module.setModelVisibility('codex', 'openai', 'gpt-5.5', false);
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(false);
+ expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1')).not.toBeNull();
+ });
+
it('schema 损坏的 localStorage → 静默回退,跟随目录默认', async () => {
memStorage.setItem('xdt:modelVisibilityPrefs:v1', '{ not valid json');
- vi.resetModules();
- const { isModelEnabled } = await loadModule();
+ const { isModelEnabled } = await loadModuleForOwner();
expect(isModelEnabled('claude-code', 'xd', { id: 'claude-opus-4-8' })).toBe(true);
});
@@ -134,8 +259,7 @@ describe('modelVisibilityPrefs store', () => {
'codex:xd:gpt-5.5': 1, // 非 boolean → 丢弃
}),
);
- vi.resetModules();
- const { isModelEnabled } = await loadModule();
+ 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(true); // 脏数据丢弃 → 默认开
expect(isModelEnabled('codex', 'xd', { id: 'gpt-5.5' })).toBe(true); // 脏数据丢弃 → 默认开
diff --git a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
index 752e79db9a..a515b7c354 100644
--- a/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
+++ b/apps/desktop/src/renderer/__tests__/unifiedModelList.test.ts
@@ -5,7 +5,7 @@
* 可见性 override 走真实 modelVisibilityPrefs(localStorage 由 jsdom 提供,用例间重置)。
*/
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
buildUnionRows,
@@ -15,7 +15,11 @@ import {
isRowDiverged,
loadCollapsedMap,
} from '@/components/settings/UnifiedModelList';
-import { __resetForTest, setModelVisibility } from '@/state/modelVisibilityPrefs';
+import {
+ __resetForTest,
+ setModelVisibility,
+ setModelVisibilityOwner,
+} from '@/state/modelVisibilityPrefs';
import type { CatalogModel, ProviderView } from '@cindy/model-providers';
@@ -37,6 +41,25 @@ const provider = {
connected: true,
} as unknown as ProviderView;
+beforeEach(() => {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ claimLegacyModelVisibilityOwner: () => ({
+ dataOwnerId: 'test-owner',
+ ownerGeneration: 1,
+ claimed: true,
+ claimedByOtherOwner: false,
+ canInitialize: true,
+ }),
+ syncModelVisibility: async () => undefined,
+ },
+ },
+ });
+ setModelVisibilityOwner('test-owner', 1, 'cloud');
+});
+
afterEach(() => {
__resetForTest();
});
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index e914298fd6..f7da2b5cb2 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -35,6 +35,7 @@ import { sessionsStore } from '@/lib/sessionsStore';
import { isSidebarWindow } from '@/lib/sidebarWindow';
import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
import { setNewMakerDraftOwner } from '@/state/newMakerDraft';
+import { setModelVisibilityOwner } from '@/state/modelVisibilityPrefs';
import { setComposerDraftOwner } from '@/lib/composerDraftStore';
import { setPendingHandoffOwner } from '@/state/pendingFirstMessage';
import { setDeferredUiAssignmentOwner } from '@/features/cc-agent/deferredUiAssignment';
@@ -184,6 +185,7 @@ export function AuthProvider({
setPendingHandoffOwner(state.dataOwnerId);
setDeferredUiAssignmentOwner(state.dataOwnerId);
setUserPromptOwner(state.dataOwnerId);
+ setModelVisibilityOwner(state.dataOwnerId, state.ownerGeneration, state.mode);
if (ownerChanged) {
setMemorySettingsOwner(state.dataOwnerId);
void bootstrapMemorySettingsFromMain();
diff --git a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
index 58ec26bf41..79e96666f6 100644
--- a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
+++ b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
@@ -1,6 +1,6 @@
/**
* modelVisibilityPrefs —— 按「(agent, 来源/provider, model) → 是否在模型选择器显示」的
- * **用户本地 override**,localStorage 持久化,跨会话 / 跨重启在本机生效。
+ * **用户本地 override**,按 dataOwnerId 隔离后写入 localStorage,跨会话 / 跨重启在本机生效。
*
* 背景:
* 每个来源(provider)在某个 agent 下可能提供很多模型(XD 网关 Claude Code 有 20 个),
@@ -35,7 +35,8 @@ import { isModelVisible } from '@cindy/model-providers';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
-const STORAGE_KEY = 'xdt:modelVisibilityPrefs:v1';
+const LEGACY_STORAGE_KEY = 'xdt:modelVisibilityPrefs:v1';
+const STORAGE_KEY_PREFIX = `${LEGACY_STORAGE_KEY}.owner`;
/** override 表:key=`${agent}:${providerId}:${modelId}` → 用户显式设定的可见性。 */
type VisibilityMap = Record<string, boolean>;
@@ -58,18 +59,77 @@ function sanitize(raw: unknown): VisibilityMap {
// 进程内缓存(惰性加载)。读多写少,避免每次读都 parse localStorage。
let cache: VisibilityMap | null = null;
+let activeOwnerId: string | null = null;
+let activeOwnerGeneration = 0;
+let activeOwnerReadyForWrites = false;
+let activeOwnerMode: 'signed-out' | 'local' | 'cloud' = 'signed-out';
-function load(): VisibilityMap {
- if (cache) return cache;
- if (typeof window === 'undefined') {
- cache = {};
- return cache;
+function ownerStorageKey(ownerId: string): string {
+ return `${STORAGE_KEY_PREFIX}.${encodeURIComponent(ownerId)}`;
+}
+
+function readStoredMap(raw: string | null): VisibilityMap {
+ if (!raw) return {};
+ try {
+ return sanitize(JSON.parse(raw));
+ } catch {
+ return {};
}
+}
+
+/**
+ * 把旧版唯一全局 key 的快照交给 Main 已原子认领的 owner。旧 key 故意保留给并发运行的
+ * 旧版本;新版本只认 owner-scoped key,所以其它账号不会再次导入这份数据。
+ */
+function migrateLegacyVisibility(ownerId: string, ownerGeneration: number): boolean {
+ if (typeof window === 'undefined') return false;
try {
- const raw = window.localStorage.getItem(STORAGE_KEY);
- cache = raw ? sanitize(JSON.parse(raw)) : {};
+ const scopedKey = ownerStorageKey(ownerId);
+ if (window.localStorage.getItem(scopedKey) !== null) return true;
+
+ // Main 用模型可见性专属 marker 把旧 key 原子归属给升级时的当前已验证云账号;
+ // canInitialize 还保证此刻没有另一个共享 userData 的旧进程在并发改写迁移输入。
+ const claim = window.electronAPI?.maker?.claimLegacyModelVisibilityOwner?.();
+ if (claim?.dataOwnerId !== ownerId || claim.ownerGeneration !== ownerGeneration) return false;
+ if (claim.claimedByOtherOwner === true) return true;
+ if (claim.claimed !== true || claim.canInitialize !== true) return false;
+
+ const legacy = readStoredMap(window.localStorage.getItem(LEGACY_STORAGE_KEY));
+ // 即使旧 key 不存在也写空表,作为该 owner 已完成一次性检查的持久标记。
+ window.localStorage.setItem(scopedKey, JSON.stringify(legacy));
+ return window.localStorage.getItem(scopedKey) !== null;
} catch {
+ // localStorage / 同步 owner 仲裁不可用时 fail closed:不读取未归属的旧数据。
+ return false;
+ }
+}
+
+function ensureActiveOwnerReadyForWrites(): boolean {
+ if (!activeOwnerId) return false;
+ if (activeOwnerReadyForWrites) return true;
+ if (activeOwnerMode === 'local') {
+ activeOwnerReadyForWrites = true;
+ return true;
+ }
+ if (activeOwnerMode !== 'cloud') return false;
+ activeOwnerReadyForWrites = migrateLegacyVisibility(activeOwnerId, activeOwnerGeneration);
+ if (!activeOwnerReadyForWrites) return false;
+ // A deferred migration may have imported the legacy map after this owner was first loaded.
+ cache = null;
+ load();
+ return true;
+}
+
+function load(): VisibilityMap {
+ if (cache !== null) return cache;
+ if (typeof window === 'undefined' || !activeOwnerId) {
cache = {};
+ } else {
+ try {
+ cache = readStoredMap(window.localStorage.getItem(ownerStorageKey(activeOwnerId)));
+ } catch {
+ cache = {};
+ }
}
// 首次加载后把整张快照镜像给 main —— 让 IM /model 在 main 侧拿到用户的可见性 override
// (override 真源仍是本地 localStorage,main 只缓存副本)。覆盖「用户从不打开模型选择器、
@@ -85,7 +145,11 @@ function load(): VisibilityMap {
*/
function mirrorToMain(map: VisibilityMap): void {
try {
- void window.electronAPI?.maker?.syncModelVisibility?.(map);
+ void window.electronAPI?.maker?.syncModelVisibility?.(
+ activeOwnerId,
+ activeOwnerGeneration,
+ map,
+ );
} catch {
// ignore — 镜像失败不影响本地可见性逻辑
}
@@ -98,9 +162,9 @@ const listeners = new Set<() => void>();
function persist(map: VisibilityMap): void {
cache = map;
version += 1;
- if (typeof window !== 'undefined') {
+ if (typeof window !== 'undefined' && activeOwnerId) {
try {
- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
+ window.localStorage.setItem(ownerStorageKey(activeOwnerId), JSON.stringify(map));
} catch {
// localStorage 满 / 私密窗口禁写 —— 忽略,不影响内存缓存。
}
@@ -121,6 +185,30 @@ function getVersion(): number {
return version;
}
+/** Select the owner namespace used by this renderer's model visibility overrides. */
+export function setModelVisibilityOwner(
+ ownerId: string | null,
+ ownerGeneration: number,
+ mode: 'signed-out' | 'local' | 'cloud',
+): void {
+ if (
+ activeOwnerId === ownerId
+ && activeOwnerGeneration === ownerGeneration
+ && activeOwnerMode === mode
+ ) return;
+ activeOwnerId = ownerId;
+ activeOwnerGeneration = ownerGeneration;
+ activeOwnerMode = mode;
+ activeOwnerReadyForWrites = mode === 'local' && ownerId !== null;
+ cache = null;
+ if (ownerId && mode === 'cloud') {
+ activeOwnerReadyForWrites = migrateLegacyVisibility(ownerId, ownerGeneration);
+ }
+ load();
+ version += 1;
+ for (const listener of listeners) listener();
+}
+
/**
* 该 (agent, 来源, 模型) 当前是否应显示:用户 override 优先,否则跟随目录默认值。
* model 至少需带 id + 可选 defaultEnabled(直接传 CatalogModel 即可)。
@@ -141,7 +229,7 @@ export function setModelVisibility(
modelId: string,
enabled: boolean,
): void {
- if (!providerId || !modelId) return;
+ if (!providerId || !modelId || !ensureActiveOwnerReadyForWrites()) return;
const map = load();
const k = keyOf(agent, providerId, modelId);
if (map[k] === enabled) return;
@@ -159,7 +247,7 @@ export function setManyVisibility(
modelIds: readonly string[],
enabled: boolean,
): void {
- if (!providerId || modelIds.length === 0) return;
+ if (!providerId || modelIds.length === 0 || !ensureActiveOwnerReadyForWrites()) return;
const map = load();
let changed = false;
const next = { ...map };
@@ -183,16 +271,22 @@ export function useModelVisibilityVersion(): number {
/** 测试用 —— 重置缓存 + 清 localStorage(其它代码不应调用)。 */
export function __resetForTest(): void {
+ const currentScopedKey = activeOwnerId ? ownerStorageKey(activeOwnerId) : null;
cache = null;
+ activeOwnerId = null;
+ activeOwnerGeneration = 0;
+ activeOwnerReadyForWrites = false;
+ activeOwnerMode = 'signed-out';
version = 0;
listeners.clear();
if (typeof window !== 'undefined') {
try {
- window.localStorage.removeItem(STORAGE_KEY);
+ window.localStorage.removeItem(LEGACY_STORAGE_KEY);
+ if (currentScopedKey) window.localStorage.removeItem(currentScopedKey);
} catch {
// ignore
}
}
}
-export const __STORAGE_KEY = STORAGE_KEY;
+export const __STORAGE_KEY = LEGACY_STORAGE_KEY;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f18ef37443..e7bac06cda 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4739,9 +4739,16 @@ interface ElectronAPI {
}>;
/**
* renderer → main 单向镜像「模型显示/隐藏」override 整张快照(modelVisibilityPrefs)。
- * 让 IM /model 在 main 侧复用同一套可见性过滤,与应用内模型列表逐模型一致。fire-and-forget。
+ * 让 IM /model 在 main 侧复用同一套可见性过滤,与应用内模型列表逐模型一致;owner stamp
+ * 用于拒绝账号切换期间的迟到快照。fire-and-forget。
*/
- syncModelVisibility: (map: Record<string, boolean>) => Promise<void>;
+ syncModelVisibility: (
+ dataOwnerId: string | null,
+ ownerGeneration: number,
+ map: Record<string, boolean>,
+ ) => Promise<void>;
+ /** Resolve the verified cloud owner allowed to import the pre-account preference key. */
+ claimLegacyModelVisibilityOwner: () => import('../shared/modelVisibility').ModelVisibilityLegacyOwnerClaim;
/**
* 「模型 / 供应商停用」override 写入(main 侧 model-disable-store);成功后 main 广播
* PROVIDER_CHANGED,useProviders 快照刷新后 UI 拿到新的 suspended / disabled 标志。
diff --git a/apps/desktop/src/shared/__tests__/modelVisibility.test.ts b/apps/desktop/src/shared/__tests__/modelVisibility.test.ts
new file mode 100644
index 0000000000..44d8112deb
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/modelVisibility.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { isModelVisibilityLegacyOwnerClaim } from '../modelVisibility.js';
+
+describe('model visibility legacy owner claim validation', () => {
+ it('accepts a complete owner-stamped claim', () => {
+ expect(isModelVisibilityLegacyOwnerClaim({
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 1,
+ claimed: true,
+ claimedByOtherOwner: false,
+ canInitialize: true,
+ })).toBe(true);
+ });
+
+ it('rejects missing or malformed fields', () => {
+ expect(isModelVisibilityLegacyOwnerClaim({
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 1,
+ claimed: true,
+ canInitialize: true,
+ })).toBe(false);
+ expect(isModelVisibilityLegacyOwnerClaim({
+ dataOwnerId: 'owner-a',
+ ownerGeneration: -1,
+ claimed: false,
+ claimedByOtherOwner: true,
+ canInitialize: false,
+ })).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/shared/modelVisibility.ts b/apps/desktop/src/shared/modelVisibility.ts
new file mode 100644
index 0000000000..1b55cad3cc
--- /dev/null
+++ b/apps/desktop/src/shared/modelVisibility.ts
@@ -0,0 +1,22 @@
+import { isDataOwnerPushStamp, type DataOwnerPushStamp } from './dataOwnerPush.js';
+
+/** Main's decision for importing the one pre-account model visibility namespace. */
+export interface ModelVisibilityLegacyOwnerClaim extends DataOwnerPushStamp {
+ /** The model visibility legacy marker belongs to the active verified cloud owner. */
+ readonly claimed: boolean;
+ /** The model visibility legacy marker durably belongs to another account. */
+ readonly claimedByOtherOwner: boolean;
+ /** This process currently has exclusive access and may snapshot the legacy Renderer key. */
+ readonly canInitialize: boolean;
+}
+
+export function isModelVisibilityLegacyOwnerClaim(
+ value: unknown,
+): value is ModelVisibilityLegacyOwnerClaim {
+ return (
+ isDataOwnerPushStamp(value) &&
+ typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).claimed === 'boolean' &&
+ typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).claimedByOtherOwner === 'boolean' &&
+ typeof (value as Partial<ModelVisibilityLegacyOwnerClaim>).canInitialize === 'boolean'
+ );
+}