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。

feat(desktop): scope chat embedding defaults by account (#3345)

Lizi23f40a42643a
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index 61ba579f28..a5af26efb6 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -258,8 +258,15 @@ describe('auth login-flow reset', () => {
expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');
expect(refreshBody).toContain('writePersistedAuthSession(data.refreshToken, refreshRealm);');
expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');
- expect(refreshBody).toContain('previousUserId !== nextUser.id || authRealmChanged');
- expect(refreshBody).toContain('if (authRealmChanged) {\n notifyAuthListeners();');
+ expect(refreshBody).toContain(
+ 'const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',
+ );
+ expect(refreshBody).toContain(
+ 'previousUserId !== nextUser.id || authRealmChanged || membershipKindChanged',
+ );
+ expect(refreshBody).toContain(
+ 'if (authRealmChanged || membershipKindChanged) {\n notifyAuthListeners();',
+ );
expect(deviceLinkSource).toContain('restartDeviceLinkForAuthRealmChange();');
expect(deviceLinkSource).toContain('void stopArbitrationAndTeardown()');
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 946f4a1a8c..170087be60 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -3480,8 +3480,10 @@ export async function refresh(): Promise<boolean> {
// otherwise renderer state could still show account A while API calls use B.
persistedRefreshTokenNeedsIdentityCheck = true;
const previousUserId = currentUser?.id ?? null;
+ const previousMembershipKind = currentUser?.membershipKind ?? null;
const nextUser = mergeMembershipWithExisting(data.membership, currentUser);
const accountSwitched = previousUserId !== null && previousUserId !== nextUser.id;
+ const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;
if (accountSwitched) {
log.warn(
`runtime replacement refresh switched authenticated user from ${previousUserId} to ${nextUser.id}; reconciling auth state`,
@@ -3544,13 +3546,15 @@ export async function refresh(): Promise<boolean> {
});
scheduleRefresh(data.accessToken);
notifyRenderer();
- if (previousUserId !== nextUser.id || authRealmChanged) {
+ if (previousUserId !== nextUser.id || authRealmChanged || membershipKindChanged) {
notifyAuthListeners();
}
return true;
}
+ const previousMembershipKind = currentUser?.membershipKind ?? null;
const nextUser = mergeMembershipWithExisting(data.membership, currentUser);
+ const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;
await withCloudOwnerCommit({
previousOwnerId: getActiveAppSession().dataOwnerId,
nextOwnerId: nextUser.id,
@@ -3576,7 +3580,7 @@ export async function refresh(): Promise<boolean> {
persistedRefreshTokenNeedsIdentityCheck = false;
scheduleRefresh(data.accessToken);
notifyRenderer();
- if (authRealmChanged) {
+ if (authRealmChanged || membershipKindChanged) {
notifyAuthListeners();
}
return true;
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b54dfafb3c..290abba2d6 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -672,6 +672,12 @@ import {
resetChatEmbeddingSettings,
writeChatEmbeddingEnabled,
} from './maker-host/chat-embedding-settings-store.js';
+import {
+ isChatEmbeddingOwnerStampCurrent,
+ parseChatEmbeddingOwnerStamp,
+} from './maker-host/chat-embedding-owner-stamp.js';
+import { rethrowChatEmbeddingPersistError } from './maker-host/chat-embedding-persist-error.js';
+import { createChatEmbeddingSettingsWatcher } from './maker-host/chat-embedding-settings-watcher.js';
import {
readGitSafetySettingsState,
resetGitSafetySettings,
@@ -812,6 +818,7 @@ import {
activeOwnerScopeKey,
beginAppSessionBoundary,
getActiveAppSession,
+ getActiveDataOwnerPushStamp,
isAppSessionBoundaryPending,
ownerScopedUserDataPath,
} from './appSessionState.js';
@@ -1080,12 +1087,42 @@ function isChatEmbeddingAvailable(): boolean {
}
}
+function chatEmbeddingDefaultContext() {
+ const state = authManager.getAuthState();
+ return {
+ mode: state.mode,
+ isAuthenticated: state.isAuthenticated,
+ userId: state.user?.id ?? null,
+ membershipKind: state.user?.membershipKind ?? null,
+ };
+}
+
+function assertChatEmbeddingMutationOwner(raw: unknown): void {
+ const expected = parseChatEmbeddingOwnerStamp(raw);
+ if (!expected) {
+ throwIpcError('INVALID_PARAMS', 'chat embedding owner stamp required');
+ }
+ if (
+ !isChatEmbeddingOwnerStampCurrent(
+ expected,
+ getActiveDataOwnerPushStamp(),
+ isAppSessionBoundaryPending(),
+ )
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Chat embedding setting belongs to a stale account session.',
+ );
+ }
+}
+
function attemptStartEmbeddingHost(): void {
// 谁都不要用就别启:插件 consumer 的标记由 ensureEmbeddingServiceForPluginVector
// 在回调本函数之前打上,所以这里读到的是"含本次请求"的最新意向。
const chatAvailable = isChatEmbeddingAvailable();
setEmbeddingSourceSuspended('chat', !chatAvailable);
- const chatEnabled = chatAvailable && readChatEmbeddingSettings().enabled;
+ const chatEnabled =
+ chatAvailable && readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled;
if (!chatEnabled && !isPluginVectorConsumerActive()) {
console.log(
'[bootstrap-electron] no embedding consumer active (chat off, no plugin vector); embeddingHost not started',
@@ -1154,15 +1191,21 @@ registerEmbeddingHostLazyStart(attemptStartEmbeddingHost);
let chatEmbeddingRuntimeReconcile: Promise<void> = Promise.resolve();
-function scheduleChatEmbeddingRuntimeReconcile(): void {
+function scheduleChatEmbeddingRuntimeReconcile(): Promise<void> {
// Stop new enqueue work before an async host shutdown can run. The queued
- // reconciliation re-reads the latest catalog so rapid refreshes are last-write-wins.
+ // reconciliation re-reads the latest account, preference and catalog so rapid refreshes are
+ // last-write-wins across both provider and auth boundaries.
const chatAvailable = isChatEmbeddingAvailable();
+ const chatEnabled =
+ chatAvailable && readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled;
setEmbeddingSourceSuspended('chat', !chatAvailable);
- if (!chatAvailable) setChatEmbeddingEnabled(false);
+ if (!chatEnabled) setChatEmbeddingEnabled(false);
chatEmbeddingRuntimeReconcile = chatEmbeddingRuntimeReconcile
.then(async () => {
- if (isChatEmbeddingAvailable() && readChatEmbeddingSettings().enabled) {
+ if (
+ isChatEmbeddingAvailable()
+ && readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled
+ ) {
attemptStartEmbeddingHost();
} else {
await shutdownChatEmbeddingConsumer();
@@ -1173,10 +1216,34 @@ function scheduleChatEmbeddingRuntimeReconcile(): void {
error: String(err),
});
});
+ return chatEmbeddingRuntimeReconcile;
}
setProviderAccessRuntimeRefreshListener(scheduleChatEmbeddingRuntimeReconcile);
+function broadcastChatEmbeddingSettingsChanged(): void {
+ const stamp = getActiveDataOwnerPushStamp();
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed() && !win.webContents.isDestroyed()) {
+ win.webContents.send(MAKER_PUSH.CHAT_EMBEDDING_CHANGED, stamp);
+ }
+ }
+}
+
+const chatEmbeddingSettingsWatcher = createChatEmbeddingSettingsWatcher(() => {
+ void scheduleChatEmbeddingRuntimeReconcile().finally(() => {
+ broadcastChatEmbeddingSettingsChanged();
+ });
+});
+
+function rebindChatEmbeddingSettingsWatcher(): void {
+ chatEmbeddingSettingsWatcher.rebind(
+ ownerScopedUserDataPath('chat-embedding-settings.json'),
+ );
+}
+
+app.once('will-quit', () => chatEmbeddingSettingsWatcher.dispose());
+
/**
* 「聊天嵌入」关闭时的收尾: 总是让 chat 的 enqueue 守卫立即失效; 但只有在没有插件
* 向量 consumer 时才停 host —— 否则会把另一个 consumer 的能力一起关掉 (插件的
@@ -4249,39 +4316,59 @@ const registerIpcHandlers = () => {
ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_GET, async () => {
return chatEmbeddingWire();
});
- ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET, async (_e, enabled: unknown) => {
- if (typeof enabled !== 'boolean') {
- throwIpcError('INVALID_PARAMS', 'chat embedding enabled required (boolean)');
- }
- if (enabled && !isChatEmbeddingAvailable()) {
- throwIpcError(
- 'UNSUPPORTED_CAPABILITY',
- 'Chat embedding is not available for this account or region.',
- );
- }
- // 先落盘 setting (即使后续 host 启停失败, 用户偏好已记下, 下次启动会用)
- writeChatEmbeddingEnabled(enabled);
- if (enabled) {
- // ON: 交给 attemptStartEmbeddingHost —— 它会读新 settings, host 没起就起、
- // 已被插件 consumer 起过就复用, 两种情况都补上 setupChatHistoryEmbedder +
- // setChatEmbeddingEnabled(true) (后者第一次为 true 时写 cutoff)。
- attemptStartEmbeddingHost();
- } else {
- // OFF: 先 setEnabled(false) 让 hook 守卫立即生效 (新消息不再 enqueue);
- // 没有插件向量 consumer 时才停 Worker setInterval + reset 模块级 state。
- await shutdownChatEmbeddingConsumer();
- }
- return chatEmbeddingWire();
- });
- ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET, async () => {
- const settings = resetChatEmbeddingSettings();
- if (settings.enabled) {
- attemptStartEmbeddingHost();
- } else {
- await shutdownChatEmbeddingConsumer();
- }
- return chatEmbeddingWire();
- });
+ ipcMain.handle(
+ MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET,
+ async (_e, enabled: unknown, owner: unknown) => {
+ if (typeof enabled !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'chat embedding enabled required (boolean)');
+ }
+ assertChatEmbeddingMutationOwner(owner);
+ if (enabled && !isChatEmbeddingAvailable()) {
+ throwIpcError(
+ 'UNSUPPORTED_CAPABILITY',
+ 'Chat embedding is not available for this account or region.',
+ );
+ }
+ // 先把用户选择原子写入当前 owner;锁等待期间切号会 fail closed,不会把 A 的选择写给 B。
+ try {
+ await writeChatEmbeddingEnabled(enabled, chatEmbeddingDefaultContext());
+ } catch (error) {
+ // 写入可能在跨进程锁或 owner boundary 上失败;无论如何按磁盘最新真值 reconcile,
+ // 避免 UI 收到错误时 runtime 仍沿用旧开关。
+ await scheduleChatEmbeddingRuntimeReconcile();
+ if (!isIpcError(error)) {
+ createSchedulerLogger('chat-embedding-settings').error(
+ 'Failed to save chat embedding settings',
+ { error: error instanceof Error ? error.message : String(error) },
+ );
+ }
+ rethrowChatEmbeddingPersistError(error, 'Failed to save chat embedding settings');
+ }
+ // 运行时 reconcile 总是重读最新账号。即使写入完成后立刻切号,旧请求也不会直接控制新账号。
+ await scheduleChatEmbeddingRuntimeReconcile();
+ return chatEmbeddingWire();
+ },
+ );
+ ipcMain.handle(
+ MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET,
+ async (_e, owner: unknown) => {
+ assertChatEmbeddingMutationOwner(owner);
+ try {
+ await resetChatEmbeddingSettings(chatEmbeddingDefaultContext());
+ } catch (error) {
+ await scheduleChatEmbeddingRuntimeReconcile();
+ if (!isIpcError(error)) {
+ createSchedulerLogger('chat-embedding-settings').error(
+ 'Failed to reset chat embedding settings',
+ { error: error instanceof Error ? error.message : String(error) },
+ );
+ }
+ rethrowChatEmbeddingPersistError(error, 'Failed to reset chat embedding settings');
+ }
+ await scheduleChatEmbeddingRuntimeReconcile();
+ return chatEmbeddingWire();
+ },
+ );
// Git safety settings IPC —— store 独立于 Maker 单例,提前注册以便 renderer
// 启动时同步本地镜像。SET 只影响之后的 turn 边界,已运行 turn 不追溯。
@@ -5982,7 +6069,13 @@ const registerIpcHandlers = () => {
});
disposeProviderAccessAuthListener = authManager.onAuthStateChange(() => {
refreshProviderAccessAfterAuthChange();
+ rebindChatEmbeddingSettingsWatcher();
+ // Chat embedding has an account-derived default in addition to provider availability.
+ // Reconcile on every committed auth projection so same-owner membership changes cannot
+ // leave the previous default running until an unrelated provider refresh occurs.
+ void scheduleChatEmbeddingRuntimeReconcile();
});
+ rebindChatEmbeddingSettingsWatcher();
// 默认插件同步不能依赖用户先打开插件页。启动时本地 owner 已经稳定则立刻
// 复用市场快照;云端登录/切号的通知可能早于 owner boundary 释放,因此
// 延迟到当前调用栈结束后再按已提交的新 owner 补跑一次。
@@ -8721,7 +8814,7 @@ function compactionWire() {
}
function chatEmbeddingWire() {
- const state = readChatEmbeddingSettingsState();
+ const state = readChatEmbeddingSettingsState(chatEmbeddingDefaultContext());
const available = isChatEmbeddingAvailable();
return {
enabled: available && state.value.enabled,
diff --git a/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts
index a9d49b73f4..194e1aa7ff 100644
--- a/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts
+++ b/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts
@@ -296,11 +296,14 @@ describe('embedding-host 多 consumer 启停', () => {
});
describe('chat embedding availability wiring', () => {
- it('reconciles the runtime whenever provider access changes', () => {
+ it('reconciles the runtime whenever provider access or another process changes settings', () => {
expect(makerHostSource).toContain('providerAccessRuntimeRefreshListener?.();');
expect(bootstrapSource).toContain(
'setProviderAccessRuntimeRefreshListener(scheduleChatEmbeddingRuntimeReconcile);',
);
+ expect(bootstrapSource).toContain('createChatEmbeddingSettingsWatcher(() => {');
+ expect(bootstrapSource).toContain('rebindChatEmbeddingSettingsWatcher();');
+ expect(bootstrapSource).toContain('MAKER_PUSH.CHAT_EMBEDDING_CHANGED');
});
it('keeps provider broadcasts alive when runtime reconciliation throws', () => {
const refreshStart = makerHostSource.indexOf(
@@ -326,26 +329,67 @@ describe('chat embedding availability wiring', () => {
"setEmbeddingSourceSuspended('chat', !chatAvailable);",
);
expect(bootstrapSource).toContain(
- 'if (!chatAvailable) setChatEmbeddingEnabled(false);',
+ 'if (!chatEnabled) setChatEmbeddingEnabled(false);',
);
expect(bootstrapSource).toContain(
- 'if (isChatEmbeddingAvailable() && readChatEmbeddingSettings().enabled)',
+ 'readChatEmbeddingSettings(chatEmbeddingDefaultContext()).enabled',
);
expect(bootstrapSource).toContain('await shutdownChatEmbeddingConsumer();');
});
it('routes unavailable enable requests through the stable capability error', () => {
- const start = bootstrapSource.indexOf(
- 'ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET',
- );
- const end = bootstrapSource.indexOf(
- 'ipcMain.handle(MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET',
- start,
- );
+ const start = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET');
+ const end = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET', start);
expect(start).toBeGreaterThanOrEqual(0);
expect(end).toBeGreaterThan(start);
const handler = bootstrapSource.slice(start, end);
expect(handler).toMatch(/throwIpcError\(\s*'UNSUPPORTED_CAPABILITY'/);
expect(handler).not.toContain("requireAppCapability('canUseCindyGateway'");
});
+
+ it('rejects stale renderer owner stamps before mutating an account setting', () => {
+ const setStart = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET');
+ const resetStart = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET', setStart);
+ const resetEnd = bootstrapSource.indexOf('MAKER_IPC_INVOKE.GIT_SAFETY_GET', resetStart);
+ const setHandler = bootstrapSource.slice(setStart, resetStart);
+ const resetHandler = bootstrapSource.slice(resetStart, resetEnd);
+
+ const setGuard = setHandler.indexOf('assertChatEmbeddingMutationOwner(owner);');
+ const setWrite = setHandler.indexOf('await writeChatEmbeddingEnabled');
+ const resetGuard = resetHandler.indexOf('assertChatEmbeddingMutationOwner(owner);');
+ const resetWrite = resetHandler.indexOf('await resetChatEmbeddingSettings');
+ expect(setGuard).toBeGreaterThanOrEqual(0);
+ expect(setWrite).toBeGreaterThan(setGuard);
+ expect(resetGuard).toBeGreaterThanOrEqual(0);
+ expect(resetWrite).toBeGreaterThan(resetGuard);
+ expect(bootstrapSource).toMatch(/throwIpcError\(\s*'PRECONDITION_FAILED'/);
+ });
+
+ it('converts persist failures to a stable IPC error after runtime reconcile', () => {
+ expect(bootstrapSource).toContain(
+ "import { rethrowChatEmbeddingPersistError } from './maker-host/chat-embedding-persist-error.js';",
+ );
+
+ const setStart = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_SET');
+ const resetStart = bootstrapSource.indexOf('MAKER_IPC_INVOKE.CHAT_EMBEDDING_RESET', setStart);
+ const resetEnd = bootstrapSource.indexOf('MAKER_IPC_INVOKE.GIT_SAFETY_GET', resetStart);
+ const setHandler = bootstrapSource.slice(setStart, resetStart);
+ const resetHandler = bootstrapSource.slice(resetStart, resetEnd);
+
+ const setReconcile = setHandler.indexOf('await scheduleChatEmbeddingRuntimeReconcile();');
+ const setRethrow = setHandler.indexOf(
+ "rethrowChatEmbeddingPersistError(error, 'Failed to save chat embedding settings')",
+ );
+ expect(setReconcile).toBeGreaterThanOrEqual(0);
+ expect(setRethrow).toBeGreaterThan(setReconcile);
+ expect(setHandler).not.toMatch(/throw error;?/);
+
+ const resetReconcile = resetHandler.indexOf('await scheduleChatEmbeddingRuntimeReconcile();');
+ const resetRethrow = resetHandler.indexOf(
+ "rethrowChatEmbeddingPersistError(error, 'Failed to reset chat embedding settings')",
+ );
+ expect(resetReconcile).toBeGreaterThanOrEqual(0);
+ expect(resetRethrow).toBeGreaterThan(resetReconcile);
+ expect(resetHandler).not.toMatch(/throw error;?/);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/chat-embedding-owner-stamp.test.ts b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-owner-stamp.test.ts
new file mode 100644
index 0000000000..0e2bca66bc
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-owner-stamp.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isChatEmbeddingOwnerStampCurrent,
+ parseChatEmbeddingOwnerStamp,
+} from '../chat-embedding-owner-stamp.js';
+
+describe('chat embedding mutation owner stamp', () => {
+ it('parses only a complete owner stamp', () => {
+ expect(parseChatEmbeddingOwnerStamp({ dataOwnerId: 'owner-a', ownerGeneration: 3 })).toEqual({
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 3,
+ });
+ expect(parseChatEmbeddingOwnerStamp({ dataOwnerId: null, ownerGeneration: 0 })).toEqual({
+ dataOwnerId: null,
+ ownerGeneration: 0,
+ });
+ expect(parseChatEmbeddingOwnerStamp({ dataOwnerId: 'owner-a' })).toBeNull();
+ expect(
+ parseChatEmbeddingOwnerStamp({ dataOwnerId: 'owner-a', ownerGeneration: 1.5 }),
+ ).toBeNull();
+ expect(parseChatEmbeddingOwnerStamp(null)).toBeNull();
+ });
+
+ it('accepts only the same owner and generation outside an account boundary', () => {
+ const current = { dataOwnerId: 'owner-a', ownerGeneration: 4 };
+
+ expect(
+ isChatEmbeddingOwnerStampCurrent(
+ { dataOwnerId: 'owner-a', ownerGeneration: 4 },
+ current,
+ false,
+ ),
+ ).toBe(true);
+ expect(
+ isChatEmbeddingOwnerStampCurrent(
+ { dataOwnerId: 'owner-b', ownerGeneration: 4 },
+ current,
+ false,
+ ),
+ ).toBe(false);
+ expect(
+ isChatEmbeddingOwnerStampCurrent(
+ { dataOwnerId: 'owner-a', ownerGeneration: 3 },
+ current,
+ false,
+ ),
+ ).toBe(false);
+ expect(
+ isChatEmbeddingOwnerStampCurrent(
+ { dataOwnerId: 'owner-a', ownerGeneration: 4 },
+ current,
+ true,
+ ),
+ ).toBe(false);
+ expect(
+ isChatEmbeddingOwnerStampCurrent(
+ { dataOwnerId: null, ownerGeneration: 4 },
+ { dataOwnerId: null, ownerGeneration: 4 },
+ false,
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/chat-embedding-persist-error.test.ts b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-persist-error.test.ts
new file mode 100644
index 0000000000..8fbd5a297b
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-persist-error.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { createIpcError } from '../../../shared/ipc-errors.js';
+import { rethrowChatEmbeddingPersistError } from '../chat-embedding-persist-error.js';
+
+describe('rethrowChatEmbeddingPersistError', () => {
+ it('forwards an existing IPC error unchanged', () => {
+ const original = createIpcError(
+ 'PRECONDITION_FAILED',
+ 'Chat embedding setting belongs to a stale account session.',
+ );
+ expect(() =>
+ rethrowChatEmbeddingPersistError(original, 'Failed to save chat embedding settings'),
+ ).toThrow(original);
+ });
+
+ it('rewrites filesystem failures to a stable INTERNAL code without leaking the path', () => {
+ const leakedPath =
+ '/Users/example/Library/Application Support/Cindy/owners/abc/chat-embedding-settings.json';
+ try {
+ rethrowChatEmbeddingPersistError(
+ new Error(`ENOENT: no such file or directory, unlink '${leakedPath}'`),
+ 'Failed to reset chat embedding settings',
+ );
+ throw new Error('expected persist error to be rewritten');
+ } catch (error) {
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toMatchObject({ code: 'INTERNAL' });
+ expect((error as Error).message).toBe('[INTERNAL] Failed to reset chat embedding settings');
+ expect((error as Error).message).not.toContain(leakedPath);
+ expect((error as Error).message).not.toContain('ENOENT');
+ }
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-store.test.ts
new file mode 100644
index 0000000000..5fc4488d2c
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-store.test.ts
@@ -0,0 +1,359 @@
+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,
+ generation: 1,
+ boundaryPending: false,
+ exclusive: true,
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: (name: string) => (name === 'userData' ? harness.root : os.tmpdir()) },
+}));
+
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => `${harness.mode}:${harness.ownerId ?? 'none'}:${harness.generation}`,
+ dataOwnerStorageKey: (ownerId: string) => `key-${ownerId}`,
+ getActiveAppSession: () => ({
+ mode: harness.mode,
+ dataOwnerId: harness.ownerId,
+ generation: harness.generation,
+ }),
+ isAppSessionBoundaryPending: () => harness.boundaryPending,
+ ownerScopedUserDataPath: (...parts: string[]) =>
+ harness.ownerId
+ ? path.join(harness.root, 'owners', `key-${harness.ownerId}`, ...parts)
+ : path.join(harness.root, 'no-session', ...parts),
+}));
+
+vi.mock('../../ownerNamespaceMigration.js', () => ({
+ hasExclusiveSharedLegacyUserDataAccess: () => harness.exclusive,
+}));
+
+vi.mock('../logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({ info: vi.fn(), warn: vi.fn() }),
+ },
+}));
+
+async function loadStore() {
+ return import('../chat-embedding-settings-store.js');
+}
+
+const orgContext = {
+ mode: 'cloud' as const,
+ isAuthenticated: true,
+ userId: 'owner-a',
+ membershipKind: 'org' as const,
+};
+const personalContext = {
+ mode: 'cloud' as const,
+ isAuthenticated: true,
+ userId: 'owner-a',
+ membershipKind: 'personal' as const,
+};
+
+beforeEach(() => {
+ vi.resetModules();
+ harness.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-chat-embedding-settings-'));
+ harness.mode = 'cloud';
+ harness.ownerId = 'owner-a';
+ harness.generation = 1;
+ harness.boundaryPending = false;
+ harness.exclusive = true;
+});
+
+afterEach(() => {
+ fs.rmSync(harness.root, { recursive: true, force: true });
+});
+
+describe('chat embedding account defaults', () => {
+ it('enables only an authenticated organization cloud membership by default', async () => {
+ const { resolveChatEmbeddingDefault } = await loadStore();
+
+ expect(resolveChatEmbeddingDefault(orgContext)).toBe(true);
+ expect(resolveChatEmbeddingDefault(personalContext)).toBe(false);
+ expect(
+ resolveChatEmbeddingDefault({
+ mode: 'cloud',
+ isAuthenticated: false,
+ userId: null,
+ membershipKind: 'org',
+ }),
+ ).toBe(false);
+ expect(
+ resolveChatEmbeddingDefault({
+ mode: 'local',
+ isAuthenticated: false,
+ userId: null,
+ membershipKind: null,
+ }),
+ ).toBe(false);
+ expect(
+ resolveChatEmbeddingDefault({
+ mode: 'signed-out',
+ isAuthenticated: false,
+ userId: null,
+ membershipKind: null,
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps explicit choices isolated per owner and reset follows the current account default', async () => {
+ const {
+ readChatEmbeddingSettingsState,
+ resetChatEmbeddingSettings,
+ writeChatEmbeddingEnabled,
+ } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ defaults: { enabled: true },
+ isCustomized: false,
+ });
+ await writeChatEmbeddingEnabled(false, orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+
+ harness.ownerId = 'owner-b';
+ harness.generation += 1;
+ const ownerBContext = { ...personalContext, userId: 'owner-b' };
+ expect(readChatEmbeddingSettingsState(ownerBContext)).toMatchObject({
+ value: { enabled: false },
+ defaults: { enabled: false },
+ isCustomized: false,
+ });
+ await writeChatEmbeddingEnabled(true, ownerBContext);
+ expect(readChatEmbeddingSettingsState(ownerBContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: true,
+ });
+
+ harness.ownerId = 'owner-a';
+ harness.generation += 1;
+ expect(readChatEmbeddingSettingsState(orgContext).value.enabled).toBe(false);
+ await resetChatEmbeddingSettings(orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: false,
+ });
+ });
+
+ it('persists a user choice even when it equals the organization default', async () => {
+ const { readChatEmbeddingSettingsState, writeChatEmbeddingEnabled } = await loadStore();
+
+ await writeChatEmbeddingEnabled(true, orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext).isCustomized).toBe(true);
+ expect(
+ JSON.parse(
+ fs.readFileSync(
+ path.join(harness.root, 'owners', 'key-owner-a', 'chat-embedding-settings.json'),
+ 'utf-8',
+ ),
+ ),
+ ).toEqual({ enabled: true });
+ });
+
+ it('rejects a cloud context that no longer matches the active owner', async () => {
+ const { writeChatEmbeddingEnabled } = await loadStore();
+ harness.ownerId = 'owner-b';
+ harness.generation += 1;
+
+ await expect(writeChatEmbeddingEnabled(true, orgContext)).rejects.toThrow(/stable data owner/);
+ expect(
+ fs.existsSync(
+ path.join(harness.root, 'owners', 'key-owner-b', 'chat-embedding-settings.json'),
+ ),
+ ).toBe(false);
+ });
+
+ it('reloads an owner override written by another process', async () => {
+ const { readChatEmbeddingSettingsState } = await loadStore();
+ const ownerDir = path.join(harness.root, 'owners', 'key-owner-a');
+ const file = path.join(ownerDir, 'chat-embedding-settings.json');
+
+ expect(readChatEmbeddingSettingsState(orgContext).value.enabled).toBe(true);
+ fs.mkdirSync(ownerDir, { recursive: true });
+ fs.writeFileSync(file, JSON.stringify({ enabled: false }), 'utf-8');
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+
+ fs.writeFileSync(file, JSON.stringify({ enabled: true }), 'utf-8');
+ const future = new Date(Date.now() + 5_000);
+ fs.utimesSync(file, future, future);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: true,
+ });
+ });
+});
+
+describe('legacy machine-wide setting migration', () => {
+ it('moves the recognizable legacy opt-out to the first stable cloud owner only', async () => {
+ fs.writeFileSync(
+ path.join(harness.root, 'chat-embedding-settings.json'),
+ JSON.stringify({ enabled: false }),
+ 'utf-8',
+ );
+ const { readChatEmbeddingSettingsState, resetChatEmbeddingSettings } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ expect(fs.existsSync(path.join(harness.root, 'chat-embedding-settings.json'))).toBe(false);
+ expect(
+ JSON.parse(
+ fs.readFileSync(
+ path.join(harness.root, 'owners', 'key-owner-a', 'chat-embedding-settings.json'),
+ 'utf-8',
+ ),
+ ),
+ ).toEqual({ enabled: false });
+ expect(
+ JSON.parse(
+ fs.readFileSync(
+ path.join(harness.root, '.chat-embedding-settings-owner-claim-v1.json'),
+ 'utf-8',
+ ),
+ ),
+ ).toEqual({ version: 1, ownerKey: 'key-owner-a', complete: true });
+
+ await resetChatEmbeddingSettings(orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: false,
+ });
+
+ harness.ownerId = 'owner-b';
+ harness.generation += 1;
+ expect(readChatEmbeddingSettingsState({ ...orgContext, userId: 'owner-b' })).toMatchObject({
+ value: { enabled: true },
+ isCustomized: false,
+ });
+ });
+
+ it('does not let local mode claim a setting that was never exposed there', async () => {
+ fs.writeFileSync(
+ path.join(harness.root, 'chat-embedding-settings.json'),
+ JSON.stringify({ enabled: false }),
+ 'utf-8',
+ );
+ harness.mode = 'local';
+ harness.ownerId = 'local-v1';
+ const { readChatEmbeddingSettingsState } = await loadStore();
+
+ expect(
+ readChatEmbeddingSettingsState({
+ mode: 'local',
+ isAuthenticated: false,
+ userId: null,
+ membershipKind: null,
+ }),
+ ).toMatchObject({ value: { enabled: false }, isCustomized: false });
+ expect(fs.existsSync(path.join(harness.root, 'chat-embedding-settings.json'))).toBe(true);
+ expect(
+ fs.existsSync(path.join(harness.root, '.chat-embedding-settings-owner-claim-v1.json')),
+ ).toBe(false);
+ });
+
+ it('temporarily honors a legacy opt-out when exclusive migration is unavailable', async () => {
+ fs.writeFileSync(
+ path.join(harness.root, 'chat-embedding-settings.json'),
+ JSON.stringify({ enabled: false }),
+ 'utf-8',
+ );
+ harness.exclusive = false;
+ const { readChatEmbeddingSettingsState, resetChatEmbeddingSettings } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ await expect(resetChatEmbeddingSettings(orgContext)).rejects.toThrow(
+ /migration is still pending/,
+ );
+ expect(fs.existsSync(path.join(harness.root, 'chat-embedding-settings.json'))).toBe(true);
+ });
+
+ it('defers an incomplete same-owner claim without exclusivity and resumes it later', async () => {
+ fs.writeFileSync(
+ path.join(harness.root, 'chat-embedding-settings.json'),
+ JSON.stringify({ enabled: false }),
+ 'utf-8',
+ );
+ fs.writeFileSync(
+ path.join(harness.root, '.chat-embedding-settings-owner-claim-v1.json'),
+ JSON.stringify({ version: 1, ownerKey: 'key-owner-a', complete: false }),
+ 'utf-8',
+ );
+ harness.exclusive = false;
+ const { readChatEmbeddingSettingsState } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ expect(
+ fs.existsSync(
+ path.join(harness.root, 'owners', 'key-owner-a', 'chat-embedding-settings.json'),
+ ),
+ ).toBe(false);
+
+ harness.exclusive = true;
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ expect(
+ JSON.parse(
+ fs.readFileSync(
+ path.join(harness.root, '.chat-embedding-settings-owner-claim-v1.json'),
+ 'utf-8',
+ ),
+ ),
+ ).toEqual({ version: 1, ownerKey: 'key-owner-a', complete: true });
+ });
+
+ it('fails closed on a blocked legacy setting until explicit reset acknowledges it', async () => {
+ fs.writeFileSync(path.join(harness.root, 'chat-embedding-settings.json'), '{broken', 'utf-8');
+ const { readChatEmbeddingSettingsState, resetChatEmbeddingSettings } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ await resetChatEmbeddingSettings(orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: false,
+ });
+ });
+
+ it('fails closed on an unreadable owner override and allows explicit reset recovery', async () => {
+ const ownerDir = path.join(harness.root, 'owners', 'key-owner-a');
+ fs.mkdirSync(ownerDir, { recursive: true });
+ fs.writeFileSync(path.join(ownerDir, 'chat-embedding-settings.json'), '{broken', 'utf-8');
+ const { readChatEmbeddingSettingsState, resetChatEmbeddingSettings } = await loadStore();
+
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: false },
+ isCustomized: true,
+ });
+ await resetChatEmbeddingSettings(orgContext);
+ expect(readChatEmbeddingSettingsState(orgContext)).toMatchObject({
+ value: { enabled: true },
+ isCustomized: false,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-watcher.test.ts b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-watcher.test.ts
new file mode 100644
index 0000000000..fc3dc46451
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/chat-embedding-settings-watcher.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createChatEmbeddingSettingsWatcher } from '../chat-embedding-settings-watcher.js';
+
+describe('chat embedding settings watcher', () => {
+ it('rebinds across owners and forwards external file changes', () => {
+ const listeners = new Map<string, () => void>();
+ const deps = {
+ watchFile: vi.fn(
+ (
+ file: string,
+ _options: { persistent: boolean; interval: number },
+ listener: () => void,
+ ) => {
+ listeners.set(file, listener);
+ },
+ ),
+ unwatchFile: vi.fn((file: string) => {
+ listeners.delete(file);
+ }),
+ };
+ const onChange = vi.fn();
+ const watcher = createChatEmbeddingSettingsWatcher(onChange, deps);
+
+ watcher.rebind('owner-a/chat-embedding-settings.json');
+ expect(deps.watchFile).toHaveBeenCalledWith(
+ 'owner-a/chat-embedding-settings.json',
+ { persistent: false, interval: 750 },
+ expect.any(Function),
+ );
+ listeners.get('owner-a/chat-embedding-settings.json')?.();
+ expect(onChange).toHaveBeenCalledTimes(1);
+
+ watcher.rebind('owner-b/chat-embedding-settings.json');
+ expect(deps.unwatchFile).toHaveBeenCalledWith(
+ 'owner-a/chat-embedding-settings.json',
+ expect.any(Function),
+ );
+ expect(listeners.has('owner-a/chat-embedding-settings.json')).toBe(false);
+ listeners.get('owner-b/chat-embedding-settings.json')?.();
+ expect(onChange).toHaveBeenCalledTimes(2);
+
+ watcher.rebind('owner-b/chat-embedding-settings.json');
+ expect(deps.watchFile).toHaveBeenCalledTimes(2);
+ watcher.dispose();
+ expect(deps.unwatchFile).toHaveBeenLastCalledWith(
+ 'owner-b/chat-embedding-settings.json',
+ expect.any(Function),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/chat-embedding-owner-stamp.ts b/apps/desktop/src/main/maker-host/chat-embedding-owner-stamp.ts
new file mode 100644
index 0000000000..02064f773c
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/chat-embedding-owner-stamp.ts
@@ -0,0 +1,33 @@
+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';
+
+export interface ChatEmbeddingOwnerStamp {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+}
+
+export function parseChatEmbeddingOwnerStamp(raw: unknown): ChatEmbeddingOwnerStamp | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const dataOwnerId = (raw as { dataOwnerId?: unknown }).dataOwnerId;
+ const ownerGeneration = (raw as { ownerGeneration?: unknown }).ownerGeneration;
+ if (
+ !(typeof dataOwnerId === 'string' || dataOwnerId === null) ||
+ typeof ownerGeneration !== 'number' ||
+ !Number.isSafeInteger(ownerGeneration)
+ ) {
+ return null;
+ }
+ return { dataOwnerId, ownerGeneration };
+}
+
+export function isChatEmbeddingOwnerStampCurrent(
+ expected: ChatEmbeddingOwnerStamp,
+ current: DataOwnerPushStamp,
+ boundaryPending: boolean,
+): boolean {
+ return (
+ !boundaryPending &&
+ expected.dataOwnerId !== null &&
+ expected.dataOwnerId === current.dataOwnerId &&
+ expected.ownerGeneration === current.ownerGeneration
+ );
+}
diff --git a/apps/desktop/src/main/maker-host/chat-embedding-persist-error.ts b/apps/desktop/src/main/maker-host/chat-embedding-persist-error.ts
new file mode 100644
index 0000000000..5cde916ee4
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/chat-embedding-persist-error.ts
@@ -0,0 +1,8 @@
+import { isIpcError } from '../../shared/ipc-errors.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** Convert settings persist failures to a stable IPC error that cannot leak filesystem paths. */
+export function rethrowChatEmbeddingPersistError(error: unknown, message: string): never {
+ if (isIpcError(error)) throw error;
+ throwIpcError('INTERNAL', message);
+}
diff --git a/apps/desktop/src/main/maker-host/chat-embedding-settings-store.ts b/apps/desktop/src/main/maker-host/chat-embedding-settings-store.ts
index cf95f28783..9d68159da7 100644
--- a/apps/desktop/src/main/maker-host/chat-embedding-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/chat-embedding-settings-store.ts
@@ -1,32 +1,30 @@
/**
- * chat-embedding-settings-store —— 聊天嵌入开关的 main 端持久化 source of truth。
+ * chat-embedding-settings-store —— 对话语义索引开关的 main 端持久化真值。
*
- * 落盘文件: <userData>/chat-embedding-settings.json
- * { "enabled": true }
+ * 新设置按 data owner 落在 <userData>/owners/<ownerKey>/chat-embedding-settings.json。
+ * 文件只记录用户明确拨动的 override;有效默认值由当前稳定账号决定:企业组织账号开,
+ * 个人账号 / 本地模式 / 未登录关。恢复默认只删除 override,不快照当时的账号默认。
*
- * 默认 true —— 聊天语义搜索默认全员开启以提升搜索体验。embedding 走 voyage-4
- * (~¥0.09/天/重度用户, 经 XD Gateway + 公司 LiteLLM bearer 集中承担, 不计用户钱包)。
- * "默认开"靠"无设置文件 → 用 DEFAULTS"实现: 全新装包 + 老用户从没碰过开关的,
- * 都会自动启用; 显式 toggle 关过 (文件 enabled:false) 的用户保持关闭, 不被覆盖。
- * 用户随时可在 Settings → 个性化 关闭。
- *
- * 注: 默认开只索引"开启之后"的新消息 (cutoff 语义, 不 backfill 历史, 见
- * chat-history-embedder.ts), 老对话仍由 FTS 在混合检索里兜底。
- *
- * 形态与 compat-mode-store / memory-settings-store 完全一致, 保持运维心智一致:
- * - 同步 R/W (文件极小, < 30B), 不会卡 main 主线程
- * - 写入用 .tmp + rename 原子语义, 防写一半崩 → JSON 截断
- * - 内存 cache, 第一次从盘读, 后续走 cache
- * - read 失败 (corrupt JSON / 权限) → fallback DEFAULTS + 删坏文件避免反复报错
- *
- * 注意: 启用状态 (enabled) 是 per-machine settings (跟 compat-mode 一样落 userData);
- * 而"cutoff timestamp" 是 per-DB 的事实 (落在 embedding_meta 表里, 见
- * chat-history-embedder.ts), 两者分开存。
+ * 旧版把设置写在 <userData>/chat-embedding-settings.json,且系统默认 true,因此只有
+ * enabled:false 能证明用户明确关闭过。升级时把这份 opt-out 归给第一个稳定云账号;
+ * 本地模式过去不展示该开关,不参与认领。
*/
import { app } from 'electron';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
import path from 'node:path';
+import {
+ activeOwnerScopeKey,
+ dataOwnerStorageKey,
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+ type AppSessionMode,
+} from '../appSessionState.js';
+import { hasExclusiveSharedLegacyUserDataAccess } from '../ownerNamespaceMigration.js';
+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
import { desktopMakerLogger } from './logger-adapter.js';
import {
createOverrideSettingsFile,
@@ -34,50 +32,321 @@ import {
} from './override-settings-file.js';
const log = desktopMakerLogger.child('chat-embedding-settings-store');
+const SETTINGS_FILE = 'chat-embedding-settings.json';
+const LEGACY_CLAIM_FILE = '.chat-embedding-settings-owner-claim-v1.json';
+const MAX_SETTINGS_BYTES = 1_024;
+const STORAGE_DEFAULTS: ChatEmbeddingSettings = { enabled: false };
export interface ChatEmbeddingSettings {
enabled: boolean;
}
-const DEFAULTS: ChatEmbeddingSettings = {
- enabled: true,
-};
+export interface ChatEmbeddingDefaultContext {
+ mode: AppSessionMode;
+ isAuthenticated: boolean;
+ userId: string | null;
+ membershipKind: 'personal' | 'org' | null;
+}
+
+interface LegacyClaimMarker {
+ version: 1;
+ ownerKey: string;
+ complete: boolean;
+}
+
+type LegacyClaimRead =
+ { kind: 'valid'; marker: LegacyClaimMarker } | { kind: 'missing' } | { kind: 'blocked' };
+
+type LegacyChoiceRead = 'missing' | 'disabled' | 'not-disabled' | 'blocked';
+
+export function resolveChatEmbeddingDefault(context: ChatEmbeddingDefaultContext): boolean {
+ return context.mode === 'cloud' && context.isAuthenticated && context.membershipKind === 'org';
+}
function settingsFilePath(): string {
- return path.join(app.getPath('userData'), 'chat-embedding-settings.json');
+ return ownerScopedUserDataPath(SETTINGS_FILE);
+}
+
+function legacySettingsFilePath(): string {
+ return path.join(app.getPath('userData'), SETTINGS_FILE);
+}
+
+function legacyClaimFilePath(): string {
+ return path.join(app.getPath('userData'), LEGACY_CLAIM_FILE);
}
function normalize(raw: unknown): ChatEmbeddingSettings {
- if (!raw || typeof raw !== 'object') return { ...DEFAULTS };
- const r = raw as Record<string, unknown>;
+ if (!raw || typeof raw !== 'object') return { ...STORAGE_DEFAULTS };
return {
- enabled: typeof r.enabled === 'boolean' ? r.enabled : DEFAULTS.enabled,
+ enabled:
+ typeof (raw as { enabled?: unknown }).enabled === 'boolean'
+ ? (raw as { enabled: boolean }).enabled
+ : STORAGE_DEFAULTS.enabled,
};
}
const store = createOverrideSettingsFile<ChatEmbeddingSettings>({
filePath: settingsFilePath,
- defaults: DEFAULTS,
+ defaults: STORAGE_DEFAULTS,
normalize,
log,
label: 'chat embedding',
+ scopeKey: activeOwnerScopeKey,
+ maxBytes: MAX_SETTINGS_BYTES,
+ preserveUnreadableFile: true,
});
-/** 同步读 —— 第一次从磁盘, 后续走内存 cache。 */
-export function readChatEmbeddingSettings(): ChatEmbeddingSettings {
- return store.read();
+function readLegacyClaim(): LegacyClaimRead {
+ try {
+ const bytes = readBoundedFileNoFollowSync(legacyClaimFilePath(), MAX_SETTINGS_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' &&
+ typeof (parsed as { complete?: unknown }).complete === 'boolean'
+ ) {
+ return { kind: 'valid', marker: parsed as LegacyClaimMarker };
+ }
+ return { kind: 'blocked' };
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
+ ? { kind: 'missing' }
+ : { kind: 'blocked' };
+ }
+}
+
+function readLegacyChoice(): LegacyChoiceRead {
+ try {
+ const bytes = readBoundedFileNoFollowSync(legacySettingsFilePath(), MAX_SETTINGS_BYTES);
+ if (bytes === null) return 'blocked';
+ const parsed: unknown = JSON.parse(bytes.toString('utf-8'));
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'blocked';
+ return (parsed as { enabled?: unknown }).enabled === false ? 'disabled' : 'not-disabled';
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'blocked';
+ }
+}
+
+function tryCreateLegacyClaim(ownerKey: string): LegacyClaimRead {
+ const markerPath = legacyClaimFilePath();
+ const temporaryPath = `${markerPath}.init-${process.pid}-${randomUUID()}`;
+ try {
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
+ fs.writeFileSync(
+ temporaryPath,
+ JSON.stringify({ version: 1, ownerKey, complete: false } satisfies LegacyClaimMarker),
+ { encoding: 'utf-8', flag: 'wx', mode: 0o600 },
+ );
+ fs.linkSync(temporaryPath, markerPath);
+ log.info('legacy chat embedding owner claimed', { ownerKey });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
+ log.warn('failed to claim legacy chat embedding setting', {
+ ownerKey,
+ errorCode: (error as NodeJS.ErrnoException).code ?? 'UNKNOWN',
+ });
+ }
+ } finally {
+ try {
+ fs.unlinkSync(temporaryPath);
+ } catch {
+ // The temporary file is not authoritative until the hard link exists.
+ }
+ }
+ return readLegacyClaim();
+}
+
+function completeLegacyClaim(ownerKey: string): boolean {
+ const markerPath = legacyClaimFilePath();
+ const temporaryPath = `${markerPath}.complete-${process.pid}-${randomUUID()}`;
+ try {
+ fs.writeFileSync(
+ temporaryPath,
+ JSON.stringify({ version: 1, ownerKey, complete: true } satisfies LegacyClaimMarker),
+ { encoding: 'utf-8', flag: 'wx', mode: 0o600 },
+ );
+ fs.renameSync(temporaryPath, markerPath);
+ return true;
+ } catch (error) {
+ log.warn('failed to complete legacy chat embedding owner claim', {
+ ownerKey,
+ errorCode: (error as NodeJS.ErrnoException).code ?? 'UNKNOWN',
+ });
+ return false;
+ } finally {
+ try {
+ fs.unlinkSync(temporaryPath);
+ } catch {
+ // rename already consumed the temporary file, or creation failed.
+ }
+ }
+}
+
+/**
+ * Returns true while a recognizable legacy opt-out still needs to be honored for this owner.
+ * The synchronous migration is safe because it only runs for a stable owner while this process
+ * has exclusive access to the shared legacy userData root.
+ */
+function migrateLegacyOptOut(context: ChatEmbeddingDefaultContext): boolean {
+ const session = getActiveAppSession();
+ if (
+ context.mode !== 'cloud' ||
+ !context.isAuthenticated ||
+ !context.membershipKind ||
+ session.mode !== 'cloud' ||
+ !session.dataOwnerId ||
+ context.userId !== session.dataOwnerId ||
+ isAppSessionBoundaryPending()
+ ) {
+ return false;
+ }
+
+ const ownerKey = dataOwnerStorageKey(session.dataOwnerId);
+ let claim = readLegacyClaim();
+ if (claim.kind === 'valid' && claim.marker.ownerKey !== ownerKey) return false;
+ if (claim.kind === 'valid' && claim.marker.complete) return false;
+
+ const legacyChoice = readLegacyChoice();
+ if (legacyChoice === 'blocked') return true;
+ if (legacyChoice !== 'disabled') return false;
+
+ if (claim.kind === 'missing') {
+ if (!hasExclusiveSharedLegacyUserDataAccess()) return true;
+ claim = tryCreateLegacyClaim(ownerKey);
+ }
+
+ if (claim.kind !== 'valid') return true;
+ if (claim.marker.ownerKey !== ownerKey) return false;
+ if (claim.marker.complete) return false;
+ if (!hasExclusiveSharedLegacyUserDataAccess()) return true;
+
+ store.invalidateIfChanged();
+ const current = store.readState();
+ if (!current.customizedKeys.includes('enabled')) {
+ try {
+ store.writePatch({ enabled: false }, { preserveDefaults: true });
+ } catch (error) {
+ log.warn('failed to preserve legacy chat embedding opt-out', {
+ ownerKey,
+ errorCode: (error as NodeJS.ErrnoException).code ?? 'UNKNOWN',
+ });
+ return true;
+ }
+ }
+
+ if (!completeLegacyClaim(ownerKey)) return true;
+ try {
+ fs.unlinkSync(legacySettingsFilePath());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn('failed to remove migrated legacy chat embedding setting', {
+ ownerKey,
+ errorCode: (error as NodeJS.ErrnoException).code ?? 'UNKNOWN',
+ });
+ }
+ }
+ return false;
+}
+
+function acknowledgePendingLegacyForReset(context: ChatEmbeddingDefaultContext): boolean {
+ const session = getActiveAppSession();
+ if (
+ context.mode !== 'cloud' ||
+ !context.isAuthenticated ||
+ !session.dataOwnerId ||
+ context.userId !== session.dataOwnerId ||
+ isAppSessionBoundaryPending() ||
+ !hasExclusiveSharedLegacyUserDataAccess()
+ ) {
+ return false;
+ }
+
+ const ownerKey = dataOwnerStorageKey(session.dataOwnerId);
+ let claim = readLegacyClaim();
+ if (claim.kind === 'missing') claim = tryCreateLegacyClaim(ownerKey);
+ if (claim.kind === 'blocked') return completeLegacyClaim(ownerKey);
+ if (claim.kind !== 'valid' || claim.marker.ownerKey !== ownerKey) return false;
+ return claim.marker.complete || completeLegacyClaim(ownerKey);
}
-export function readChatEmbeddingSettingsState(): OverrideSettingsState<ChatEmbeddingSettings> {
- return store.readState();
+function assertActiveOwner(context: ChatEmbeddingDefaultContext): void {
+ const session = getActiveAppSession();
+ if (
+ !session.dataOwnerId ||
+ isAppSessionBoundaryPending() ||
+ (context.mode === 'cloud' && context.userId !== session.dataOwnerId)
+ ) {
+ throw new Error('chat embedding settings require a stable data owner');
+ }
}
-/** 同步写 enabled 字段 + 更新 cache; 失败抛错让 IPC handler 反馈给 UI。 */
-export function writeChatEmbeddingEnabled(enabled: boolean): void {
- store.writePatch({ enabled });
+function projectState(
+ context: ChatEmbeddingDefaultContext,
+): OverrideSettingsState<ChatEmbeddingSettings> {
+ store.invalidateIfChanged();
+ const defaultEnabled = resolveChatEmbeddingDefault(context);
+ const pendingLegacyOptOut = migrateLegacyOptOut(context);
+ const state = store.readState();
+ const hasEnabledOverride = state.customizedKeys.includes('enabled');
+ // A preserved but unreadable owner file may contain an opt-out. Because a valid empty override
+ // file is never emitted by createOverrideSettingsFile, file-present + no enabled key fails closed.
+ // Project it as customized so Settings exposes the explicit Reset recovery path.
+ const unreadableOrUnknownOwnerOverride = !hasEnabledOverride && fs.existsSync(settingsFilePath());
+ const enabled = hasEnabledOverride
+ ? state.value.enabled
+ : pendingLegacyOptOut || unreadableOrUnknownOwnerOverride
+ ? false
+ : defaultEnabled;
+ const isCustomized =
+ hasEnabledOverride || pendingLegacyOptOut || unreadableOrUnknownOwnerOverride;
+ return {
+ value: { enabled },
+ defaults: { enabled: defaultEnabled },
+ isCustomized,
+ customizedKeys: isCustomized ? ['enabled'] : [],
+ };
+}
+
+export function readChatEmbeddingSettings(
+ context: ChatEmbeddingDefaultContext,
+): ChatEmbeddingSettings {
+ return projectState(context).value;
+}
+
+export function readChatEmbeddingSettingsState(
+ context: ChatEmbeddingDefaultContext,
+): OverrideSettingsState<ChatEmbeddingSettings> {
+ return projectState(context);
+}
+
+export async function writeChatEmbeddingEnabled(
+ enabled: boolean,
+ context: ChatEmbeddingDefaultContext,
+): Promise<OverrideSettingsState<ChatEmbeddingSettings>> {
+ assertActiveOwner(context);
+ await store.writePatchAtomic({ enabled }, { preserveDefaults: true });
log.info('chat embedding setting written', { enabled });
+ return projectState(context);
}
-export function resetChatEmbeddingSettings(): ChatEmbeddingSettings {
- return store.reset();
+export async function resetChatEmbeddingSettings(
+ context: ChatEmbeddingDefaultContext,
+): Promise<OverrideSettingsState<ChatEmbeddingSettings>> {
+ assertActiveOwner(context);
+ const pendingLegacyOptOut = migrateLegacyOptOut(context);
+ if (pendingLegacyOptOut && !acknowledgePendingLegacyForReset(context)) {
+ throw new Error('legacy chat embedding setting migration is still pending');
+ }
+ await store.resetAtomic();
+ return projectState(context);
}
+
+export const __testing = {
+ normalize,
+ readLegacyChoice,
+ resolveChatEmbeddingDefault,
+};
diff --git a/apps/desktop/src/main/maker-host/chat-embedding-settings-watcher.ts b/apps/desktop/src/main/maker-host/chat-embedding-settings-watcher.ts
new file mode 100644
index 0000000000..9b1f9cbead
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/chat-embedding-settings-watcher.ts
@@ -0,0 +1,47 @@
+import fs from 'node:fs';
+
+interface WatchDeps {
+ watchFile(
+ file: string,
+ options: { persistent: boolean; interval: number },
+ listener: () => void,
+ ): void;
+ unwatchFile(file: string, listener: () => void): void;
+}
+
+export interface ChatEmbeddingSettingsWatcher {
+ rebind(file: string): void;
+ dispose(): void;
+}
+
+const productionDeps: WatchDeps = {
+ watchFile: (file, options, listener) => fs.watchFile(file, options, listener),
+ unwatchFile: (file, listener) => fs.unwatchFile(file, listener),
+};
+
+/**
+ * Watch the active owner's tiny override file so another Cindy process sharing userData can make
+ * this process reconcile its enqueue/query runtime. `watchFile` also observes create/delete, which
+ * is required because reset removes the override file rather than writing the default.
+ */
+export function createChatEmbeddingSettingsWatcher(
+ onChange: () => void,
+ deps: WatchDeps = productionDeps,
+): ChatEmbeddingSettingsWatcher {
+ let watchedFile: string | null = null;
+ const listener = () => onChange();
+
+ return {
+ rebind(file: string) {
+ if (watchedFile === file) return;
+ if (watchedFile) deps.unwatchFile(watchedFile, listener);
+ watchedFile = file;
+ deps.watchFile(file, { persistent: false, interval: 750 }, listener);
+ },
+ dispose() {
+ if (!watchedFile) return;
+ deps.unwatchFile(watchedFile, listener);
+ watchedFile = null;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 6c7f7ae5a2..d1c9f10a0c 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -385,12 +385,11 @@ export const MAKER_INVOKE = {
LSP_MODE_GET: 'maker:lsp-mode:get',
LSP_MODE_SET: 'maker:lsp-mode:set',
/**
- * 聊天嵌入开关 (Phase 1.2 chat-history-embedder) ——
- * - GET: 启动期 renderer 同步 localStorage 镜像
- * - SET: 用户 toggle 时落 <userData>/chat-embedding-settings.json, 立即触发
- * chat-history-embedder.setChatEmbeddingEnabled(); 第一次开启时
- * 初始化 cutoff (embedding_meta.chat_embedding_started_at)。
- * 默认 false (新装包不会自动产生 ~¥0.09/天 embedding 费用)。
+ * 对话语义索引开关 (chat-history-embedder) ——
+ * - GET: 启动期及账号切换时同步 owner-scoped renderer 镜像
+ * - SET: 用户 toggle 时写入当前 owner 的明确 override,并立即 reconcile runtime;
+ * 第一次开启时初始化 cutoff (embedding_meta.chat_embedding_started_at)。
+ * - 默认:已认证企业组织账号开启,其余账号 / 本地模式 / 未登录关闭。
*/
CHAT_EMBEDDING_GET: 'maker:chat-embedding:get',
CHAT_EMBEDDING_SET: 'maker:chat-embedding:set',
@@ -813,6 +812,8 @@ export const MAKER_PUSH = {
* 模型选择器 live 刷新)。无 payload;收到即重拉 listProviders。
*/
PROVIDER_CHANGED: 'maker:provider:changed',
+ /** 当前 owner 的对话语义索引设置由另一窗口 / 进程改动。payload 为 owner stamp。 */
+ CHAT_EMBEDDING_CHANGED: 'maker:chat-embedding:changed',
/** 本机 Ollama 运行态变化(设置页右栏 + 发消息前就绪)。 */
LOCAL_MODEL_STATUS: 'maker:local-model:status',
/** 本机 Ollama /api/pull 进度。 */
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 701f2f7ddf..a0bbdca8ec 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -660,6 +660,7 @@ const fanOutMakerAuthStateChanged = createIpcFanOut('maker:auth:state-changed');
const fanOutMakerAuthLoginProgress = createIpcFanOut('maker:auth:login-progress');
// 自定义供应商增删改广播 → 各 useProviders 实例 refetch(设置页列表 + 对话模型选择器 live 刷新)。
const fanOutMakerProvidersChanged = createIpcFanOut('maker:provider:changed');
+const fanOutMakerChatEmbeddingChanged = createIpcFanOut('maker:chat-embedding:changed');
const fanOutMakerLocalModelStatus = createIpcFanOut('maker:local-model:status');
const fanOutMakerLocalModelPullProgress = createIpcFanOut('maker:local-model:pull-progress');
const fanOutMakerLocalModelInstallProgress = createIpcFanOut('maker:local-model:install-progress');
@@ -6224,22 +6225,27 @@ contextBridge.exposeInMainWorld('electronAPI', {
lspModeSet: (enabled: boolean): Promise<{ effective: 'next-session' }> =>
ipcRenderer.invoke('maker:lsp-mode:set', enabled),
- // 聊天嵌入开关 —— 控制 chat-history-embedder 是否对新消息入队嵌入。
- // 默认 false; 关闭状态下零成本 (createMessage hook 在 enabled 守卫处直接 return)。
+ // 对话语义索引开关 —— 按 owner 保存;企业组织账号默认开,其余默认关。
+ // 关闭状态下 createMessage hook 直接 return,历史搜索回退到 FTS。
chatEmbeddingGet: (): Promise<{
enabled: boolean;
isCustomized?: boolean;
defaultEnabled?: boolean;
}> => ipcRenderer.invoke('maker:chat-embedding:get'),
+ onChatEmbeddingChanged: fanOutMakerChatEmbeddingChanged,
chatEmbeddingSet: (
enabled: boolean,
+ owner: { dataOwnerId: string | null; ownerGeneration: number },
): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>
- ipcRenderer.invoke('maker:chat-embedding:set', enabled),
- chatEmbeddingReset: (): Promise<{
+ ipcRenderer.invoke('maker:chat-embedding:set', enabled, owner),
+ chatEmbeddingReset: (owner: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }): Promise<{
enabled: boolean;
isCustomized: boolean;
defaultEnabled: boolean;
- }> => ipcRenderer.invoke('maker:chat-embedding:reset'),
+ }> => ipcRenderer.invoke('maker:chat-embedding:reset', owner),
// Git safety workflow —— 控制 turn end 自动 XDT snapshot commit。
// 默认 false; Codex rewind 按钮跟随该开关显示。
diff --git a/apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx b/apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx
index 1e461be8ea..f8d91851f8 100644
--- a/apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx
+++ b/apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx
@@ -16,7 +16,7 @@ import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
import { Switch } from '@/components/ui/switch';
import { createLogger } from '@/lib/logger';
-import { chatEmbeddingFailureKey } from '@/lib/chatEmbeddingStore';
+import { chatEmbeddingFailureKey, refreshChatEmbeddingFromMain } from '@/lib/chatEmbeddingStore';
import { useChatEmbedding } from '@/hooks/useChatEmbedding';
import { DefaultOverrideControls } from './DefaultOverrideControls';
@@ -24,47 +24,60 @@ const log = createLogger('ChatEmbeddingCell');
export function ChatEmbeddingCell() {
const { t } = useTranslation();
- const { enabled, isCustomized, setEnabled, setIsCustomized } = useChatEmbedding();
+ const { enabled, isCustomized, beginMutation, completeMutation, rollbackMutation } =
+ useChatEmbedding();
const [pending, setPending] = useState(false);
const handleToggle = useCallback(
async (next: boolean) => {
- // 乐观更新: toggle 视觉立即跟手, IPC 内部就是写一个 JSON 文件, 几乎不会失败
- const prev = enabled;
- setEnabled(next);
+ const token = beginMutation(next);
setPending(true);
try {
- const settings = await window.electronAPI.maker.chatEmbeddingSet(next);
- setEnabled(settings.enabled);
- setIsCustomized(settings.isCustomized);
- toast.success(
- t(next ? 'settings.chatEmbedding.toast.enabled' : 'settings.chatEmbedding.toast.disabled'),
- );
+ const settings = await window.electronAPI.maker.chatEmbeddingSet(next, {
+ dataOwnerId: token.dataOwnerId,
+ ownerGeneration: token.ownerGeneration,
+ });
+ if (completeMutation(token, settings)) {
+ toast.success(
+ t(
+ next
+ ? 'settings.chatEmbedding.toast.enabled'
+ : 'settings.chatEmbedding.toast.disabled',
+ ),
+ );
+ }
} catch (err) {
log.warn('chatEmbeddingSet failed', err);
- toast.error(t(chatEmbeddingFailureKey(err)));
- setEnabled(prev); // 回滚乐观值
+ if (rollbackMutation(token)) {
+ toast.error(t(chatEmbeddingFailureKey(err)));
+ void refreshChatEmbeddingFromMain();
+ }
} finally {
setPending(false);
}
},
- [enabled, setEnabled, setIsCustomized, t],
+ [beginMutation, completeMutation, rollbackMutation, t],
);
const handleReset = useCallback(async () => {
+ const token = beginMutation();
setPending(true);
try {
- const next = await window.electronAPI.maker.chatEmbeddingReset();
- setEnabled(next.enabled);
- setIsCustomized(next.isCustomized);
- toast.success(t('settings.defaults.restored'));
+ const next = await window.electronAPI.maker.chatEmbeddingReset({
+ dataOwnerId: token.dataOwnerId,
+ ownerGeneration: token.ownerGeneration,
+ });
+ if (completeMutation(token, next)) toast.success(t('settings.defaults.restored'));
} catch (err) {
log.warn('chatEmbeddingReset failed', err);
- toast.error(err instanceof Error ? err.message : t('settings.defaults.restoreFailed'));
+ if (rollbackMutation(token)) {
+ toast.error(t('settings.defaults.restoreFailed'));
+ void refreshChatEmbeddingFromMain();
+ }
} finally {
setPending(false);
}
- }, [setEnabled, setIsCustomized, t]);
+ }, [beginMutation, completeMutation, rollbackMutation, t]);
return (
<div className="flex items-center justify-between gap-3 px-4 py-[14px]">
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index 64efb24ca9..7781f1ea11 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -33,6 +33,10 @@ import {
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { setUserPromptOwner } from '@/lib/userPromptStore';
import { bootstrapMemorySettingsFromMain, setMemorySettingsOwner } from '@/lib/memorySettingsStore';
+import {
+ refreshChatEmbeddingFromMain,
+ setChatEmbeddingSettingsOwner,
+} from '@/lib/chatEmbeddingStore';
import { sessionsStore } from '@/lib/sessionsStore';
import { isSidebarWindow } from '@/lib/sidebarWindow';
import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
@@ -199,6 +203,14 @@ export function AuthProvider({
setDeferredUiAssignmentOwner(state.dataOwnerId);
setUserPromptOwner(state.dataOwnerId);
setModelVisibilityOwner(state.dataOwnerId, state.ownerGeneration, state.mode);
+ const chatEmbeddingOwnerChanged = setChatEmbeddingSettingsOwner(
+ state.dataOwnerId,
+ state.ownerGeneration,
+ state.mode === 'cloud'
+ && state.isAuthenticated
+ && state.user?.membershipKind === 'org',
+ );
+ if (chatEmbeddingOwnerChanged) void refreshChatEmbeddingFromMain();
if (ownerChanged) {
setMemorySettingsOwner(state.dataOwnerId);
void bootstrapMemorySettingsFromMain();
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useChatEmbedding.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useChatEmbedding.test.ts
index dd5e1abf24..72429a635f 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useChatEmbedding.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useChatEmbedding.test.ts
@@ -2,7 +2,15 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { chatEmbeddingFailureKey } from '../../lib/chatEmbeddingStore';
+import {
+ chatEmbeddingFailureKey,
+ refreshChatEmbeddingFromMain,
+ setChatEmbeddingSettingsOwner,
+} from '../../lib/chatEmbeddingStore';
+import {
+ __testing as dataOwnerGenerationTesting,
+ setDataOwnerGeneration,
+} from '../../contexts/dataOwnerGeneration';
import { useChatEmbedding } from '../useChatEmbedding';
type Settings = {
@@ -13,6 +21,10 @@ type Settings = {
describe('useChatEmbedding', () => {
beforeEach(() => {
+ dataOwnerGenerationTesting.reset();
+ localStorage.clear();
+ setChatEmbeddingSettingsOwner('__test-reset__', 1, false);
+ setChatEmbeddingSettingsOwner(null, 2, false);
localStorage.clear();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
@@ -34,6 +46,7 @@ describe('useChatEmbedding', () => {
listeners.add(listener);
return () => listeners.delete(listener);
}),
+ onChatEmbeddingChanged: vi.fn(() => () => undefined),
};
(window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
@@ -44,8 +57,10 @@ describe('useChatEmbedding', () => {
act(() => {
for (const listener of listeners) listener();
});
- await waitFor(() => expect(hook.result.current.enabled).toBe(false));
- expect(hook.result.current.isCustomized).toBe(true);
+ await waitFor(() => {
+ expect(hook.result.current.enabled).toBe(false);
+ expect(hook.result.current.isCustomized).toBe(true);
+ });
await act(async () => {
resolveInitial({ enabled: true, isCustomized: false, defaultEnabled: true });
@@ -58,6 +73,222 @@ describe('useChatEmbedding', () => {
expect(listeners.size).toBe(0);
});
+ it('drops a delayed response from the previous data owner', async () => {
+ let resolveOwnerA!: (settings: Settings) => void;
+ const chatEmbeddingGet = vi
+ .fn<() => Promise<Settings>>()
+ .mockReturnValueOnce(
+ new Promise<Settings>((resolve) => {
+ resolveOwnerA = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({ enabled: false, isCustomized: false, defaultEnabled: false });
+ const maker = {
+ chatEmbeddingGet,
+ onProvidersChanged: vi.fn(() => () => undefined),
+ onChatEmbeddingChanged: vi.fn(() => () => undefined),
+ };
+ (window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
+
+ setChatEmbeddingSettingsOwner('owner-a', 3, true);
+ const hook = renderHook(() => useChatEmbedding());
+ expect(hook.result.current.enabled).toBe(true);
+
+ act(() => {
+ setChatEmbeddingSettingsOwner('owner-b', 4, false);
+ });
+ await act(async () => {
+ await refreshChatEmbeddingFromMain();
+ });
+ expect(hook.result.current.enabled).toBe(false);
+
+ await act(async () => {
+ resolveOwnerA({ enabled: true, isCustomized: true, defaultEnabled: true });
+ await Promise.resolve();
+ });
+ expect(hook.result.current).toMatchObject({
+ enabled: false,
+ isCustomized: false,
+ defaultEnabled: false,
+ });
+ });
+
+ it('does not let a provider refresh overwrite an optimistic mutation', async () => {
+ let resolveRefresh!: (settings: Settings) => void;
+ const listeners = new Set<() => void>();
+ const chatEmbeddingGet = vi
+ .fn<() => Promise<Settings>>()
+ .mockResolvedValueOnce({ enabled: false, isCustomized: false, defaultEnabled: false })
+ .mockReturnValueOnce(
+ new Promise<Settings>((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
+ const maker = {
+ chatEmbeddingGet,
+ onProvidersChanged: vi.fn((listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+ onChatEmbeddingChanged: vi.fn(() => () => undefined),
+ };
+ (window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
+
+ setChatEmbeddingSettingsOwner('owner-personal', 5, false);
+ const hook = renderHook(() => useChatEmbedding());
+ await waitFor(() => expect(chatEmbeddingGet).toHaveBeenCalledTimes(1));
+
+ let token!: ReturnType<typeof hook.result.current.beginMutation>;
+ act(() => {
+ token = hook.result.current.beginMutation(true);
+ for (const listener of listeners) listener();
+ });
+ expect(hook.result.current.enabled).toBe(true);
+
+ await act(async () => {
+ resolveRefresh({ enabled: false, isCustomized: false, defaultEnabled: false });
+ await Promise.resolve();
+ });
+ expect(hook.result.current.enabled).toBe(true);
+
+ act(() => {
+ expect(
+ hook.result.current.completeMutation(token, {
+ enabled: true,
+ isCustomized: true,
+ defaultEnabled: false,
+ }),
+ ).toBe(true);
+ });
+ expect(hook.result.current).toMatchObject({ enabled: true, isCustomized: true });
+ });
+
+ it('replays a provider refresh that was deferred by a failed mutation', async () => {
+ let resolveProviderRefresh!: (settings: Settings) => void;
+ const listeners = new Set<() => void>();
+ const chatEmbeddingGet = vi
+ .fn<() => Promise<Settings>>()
+ .mockResolvedValueOnce({ enabled: false, isCustomized: false, defaultEnabled: false })
+ .mockReturnValueOnce(
+ new Promise<Settings>((resolve) => {
+ resolveProviderRefresh = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({ enabled: true, isCustomized: false, defaultEnabled: true });
+ const maker = {
+ chatEmbeddingGet,
+ onProvidersChanged: vi.fn((listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+ onChatEmbeddingChanged: vi.fn(() => () => undefined),
+ };
+ (window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
+
+ setChatEmbeddingSettingsOwner('owner-org', 6, true);
+ const hook = renderHook(() => useChatEmbedding());
+ await waitFor(() => expect(chatEmbeddingGet).toHaveBeenCalledTimes(1));
+
+ let token!: ReturnType<typeof hook.result.current.beginMutation>;
+ act(() => {
+ token = hook.result.current.beginMutation(false);
+ for (const listener of listeners) listener();
+ });
+ await act(async () => {
+ resolveProviderRefresh({ enabled: true, isCustomized: false, defaultEnabled: true });
+ await Promise.resolve();
+ });
+
+ act(() => {
+ expect(hook.result.current.rollbackMutation(token)).toBe(true);
+ });
+ await waitFor(() => {
+ expect(chatEmbeddingGet).toHaveBeenCalledTimes(3);
+ expect(hook.result.current).toMatchObject({
+ enabled: true,
+ isCustomized: false,
+ defaultEnabled: true,
+ });
+ });
+ });
+
+ it('reconciles a cross-window storage update skipped during a mutation', async () => {
+ const chatEmbeddingGet = vi
+ .fn<() => Promise<Settings>>()
+ .mockResolvedValueOnce({ enabled: false, isCustomized: false, defaultEnabled: false })
+ .mockResolvedValueOnce({ enabled: false, isCustomized: true, defaultEnabled: true });
+ const maker = {
+ chatEmbeddingGet,
+ onProvidersChanged: vi.fn(() => () => undefined),
+ onChatEmbeddingChanged: vi.fn(() => () => undefined),
+ };
+ (window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
+
+ setChatEmbeddingSettingsOwner('owner-cross-window', 7, true);
+ const hook = renderHook(() => useChatEmbedding());
+ await waitFor(() => expect(chatEmbeddingGet).toHaveBeenCalledTimes(1));
+
+ let token!: ReturnType<typeof hook.result.current.beginMutation>;
+ act(() => {
+ token = hook.result.current.beginMutation(true);
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'chatEmbedding.settings.owner-cross-window',
+ }),
+ );
+ expect(
+ hook.result.current.completeMutation(token, {
+ enabled: true,
+ isCustomized: true,
+ defaultEnabled: true,
+ }),
+ ).toBe(true);
+ });
+
+ await waitFor(() => {
+ expect(chatEmbeddingGet).toHaveBeenCalledTimes(2);
+ expect(hook.result.current).toMatchObject({ enabled: false, isCustomized: true });
+ });
+ });
+
+ it('refreshes only for a settings-changed push stamped to the active owner', async () => {
+ let onSettingsChanged!: (stamp: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }) => void;
+ const chatEmbeddingGet = vi
+ .fn<() => Promise<Settings>>()
+ .mockResolvedValueOnce({ enabled: false, isCustomized: true, defaultEnabled: true })
+ .mockResolvedValueOnce({ enabled: true, isCustomized: true, defaultEnabled: true });
+ const maker = {
+ chatEmbeddingGet,
+ onProvidersChanged: vi.fn(() => () => undefined),
+ onChatEmbeddingChanged: vi.fn((listener: typeof onSettingsChanged) => {
+ onSettingsChanged = listener;
+ return () => undefined;
+ }),
+ };
+ (window as unknown as { electronAPI: { maker: typeof maker } }).electronAPI = { maker };
+
+ setDataOwnerGeneration('owner-push', 8);
+ setChatEmbeddingSettingsOwner('owner-push', 8, true);
+ const hook = renderHook(() => useChatEmbedding());
+ await waitFor(() => expect(chatEmbeddingGet).toHaveBeenCalledTimes(1));
+
+ act(() => {
+ onSettingsChanged({ dataOwnerId: 'other-owner', ownerGeneration: 8 });
+ });
+ expect(chatEmbeddingGet).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ onSettingsChanged({ dataOwnerId: 'owner-push', ownerGeneration: 8 });
+ });
+ await waitFor(() => {
+ expect(chatEmbeddingGet).toHaveBeenCalledTimes(2);
+ expect(hook.result.current.enabled).toBe(true);
+ });
+ });
+
it('maps IPC failures to localized chat embedding messages', () => {
expect(
chatEmbeddingFailureKey(
diff --git a/apps/desktop/src/renderer/hooks/useChatEmbedding.ts b/apps/desktop/src/renderer/hooks/useChatEmbedding.ts
index f3bf8837bc..3ae4ea77dc 100644
--- a/apps/desktop/src/renderer/hooks/useChatEmbedding.ts
+++ b/apps/desktop/src/renderer/hooks/useChatEmbedding.ts
@@ -1,56 +1,60 @@
-/**
- * useChatEmbedding — React 包装, 订阅 chatEmbeddingStore 的变化。
- *
- * 真正 storage 在 lib/chatEmbeddingStore.ts, 本 hook 只接入 React 状态。
- * 形态与 useCompatMode 完全一致。
- */
+/** React subscription and mutation helpers for the owner-scoped chat embedding mirror. */
import { useCallback, useEffect, useState } from 'react';
import {
- getChatEmbeddingEnabled,
- setChatEmbeddingEnabled,
- subscribeChatEmbeddingEnabled,
+ beginChatEmbeddingMutation,
+ completeChatEmbeddingMutation,
+ getChatEmbeddingSnapshot,
+ refreshChatEmbeddingFromMain,
+ rollbackChatEmbeddingMutation,
+ subscribeChatEmbeddingSnapshot,
+ type ChatEmbeddingMutationToken,
+ type ChatEmbeddingSnapshot,
} from '@/lib/chatEmbeddingStore';
+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';
-export function useChatEmbedding(): {
- enabled: boolean;
- isCustomized: boolean;
- setEnabled: (next: boolean) => void;
- setIsCustomized: (next: boolean) => void;
+export function useChatEmbedding(): ChatEmbeddingSnapshot & {
+ beginMutation: (optimisticEnabled?: boolean) => ChatEmbeddingMutationToken;
+ completeMutation: (token: ChatEmbeddingMutationToken, settings: ChatEmbeddingSnapshot) => boolean;
+ rollbackMutation: (token: ChatEmbeddingMutationToken) => boolean;
} {
- const [enabled, setEnabledState] = useState<boolean>(getChatEmbeddingEnabled);
- const [isCustomized, setIsCustomized] = useState(false);
-
- const setEnabled = useCallback((next: boolean) => {
- setChatEmbeddingEnabled(next);
- }, []);
+ const [snapshot, setSnapshot] = useState<ChatEmbeddingSnapshot>(getChatEmbeddingSnapshot);
useEffect(() => {
- let cancelled = false;
- let refreshVersion = 0;
- const refresh = async () => {
- const version = ++refreshVersion;
- try {
- const settings = await window.electronAPI.maker.chatEmbeddingGet();
- if (cancelled || version !== refreshVersion) return;
- setChatEmbeddingEnabled(settings.enabled);
- setIsCustomized(Boolean(settings.isCustomized));
- } catch {
- // Main may still be starting; the next provider change or mount retries.
- }
- };
- const unsubscribe = subscribeChatEmbeddingEnabled(setEnabledState);
+ const unsubscribe = subscribeChatEmbeddingSnapshot(setSnapshot);
const unsubscribeProviders = window.electronAPI.maker.onProvidersChanged(() => {
- void refresh();
+ void refreshChatEmbeddingFromMain();
});
- void refresh();
+ const unsubscribeSettings = window.electronAPI.maker.onChatEmbeddingChanged((stamp) => {
+ if (isDataOwnerPushStampCurrent(stamp)) void refreshChatEmbeddingFromMain();
+ });
+ void refreshChatEmbeddingFromMain();
return () => {
- cancelled = true;
unsubscribe();
unsubscribeProviders();
+ unsubscribeSettings();
};
}, []);
- return { enabled, isCustomized, setEnabled, setIsCustomized };
+ const beginMutation = useCallback(
+ (optimisticEnabled?: boolean) => beginChatEmbeddingMutation(optimisticEnabled),
+ [],
+ );
+ const completeMutation = useCallback(
+ (token: ChatEmbeddingMutationToken, settings: ChatEmbeddingSnapshot) =>
+ completeChatEmbeddingMutation(token, settings),
+ [],
+ );
+ const rollbackMutation = useCallback(
+ (token: ChatEmbeddingMutationToken) => rollbackChatEmbeddingMutation(token),
+ [],
+ );
+
+ return {
+ ...snapshot,
+ beginMutation,
+ completeMutation,
+ rollbackMutation,
+ };
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3a4341e1bc..a0898772c5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2701,7 +2701,7 @@
"chatEmbedding": {
"cell": {
"label": "Enable chat semantic indexing",
- "description": "New chat messages are embedded into a local vector store (voyage-4) for future semantic search. Stays on this device. Only messages after enabling are indexed; existing history is not backfilled."
+ "description": "New messages and semantic search queries are sent to the vector model (voyage-4) to create vectors. Message vectors are stored in a local index. Only messages created after this setting is enabled are indexed; existing chat history is not backfilled."
},
"toggleAria": "Toggle chat semantic indexing",
"toast": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d4acd6d1bc..e3cb3dda0e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2700,7 +2700,7 @@
"chatEmbedding": {
"cell": {
"label": "チャット履歴の意味索引を有効化",
- "description": "新規メッセージをローカルのベクトルストア (voyage-4) に埋め込み、今後の意味検索に使います。データはこの端末のみ。有効化以降のメッセージだけが索引化され、既存履歴は補填されません。"
+ "description": "新しいメッセージと意味検索のクエリは、ベクトル生成のためにベクトルモデル(voyage-4)へ送信されます。メッセージのベクトルはローカル索引に保存されます。有効化後のメッセージのみが索引化され、既存のチャット履歴は遡って索引化されません。"
},
"toggleAria": "チャット履歴の意味索引を切り替え",
"toast": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8c7f860132..43f6c66f24 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2700,7 +2700,7 @@
"chatEmbedding": {
"cell": {
"label": "채팅 기록 의미 색인 활성화",
- "description": "새 메시지를 로컬 벡터 저장소(voyage-4)에 임베딩하여 향후 의미 검색에 사용합니다. 이 기기에만 보관됩니다. 활성화 이후 새 메시지만 색인되며 기존 기록은 채워지지 않습니다."
+ "description": "새 메시지와 의미 검색 쿼리는 벡터 생성을 위해 벡터 모델(voyage-4)로 전송됩니다. 메시지 벡터는 로컬 색인에 저장됩니다. 활성화 후 생성된 메시지만 색인되며 기존 채팅 기록은 소급하여 색인되지 않습니다."
},
"toggleAria": "채팅 기록 의미 색인 전환",
"toast": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 337a19b9bc..93ba92a647 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2692,7 +2692,7 @@
"chatEmbedding": {
"cell": {
"label": "启用对话记录语义索引",
- "description": "新消息嵌入到本地向量库 (voyage-4) 供未来语义搜索,仅本机访问,不外传。开启时机起的消息才被索引,历史不补。"
+ "description": "新消息和语义搜索查询会发送给向量模型(voyage-4)生成向量;消息向量保存在本机索引中。仅索引启用后的消息,不会为既有对话记录补建索引。"
},
"toggleAria": "切换对话记录语义索引",
"toast": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 5780c71dd7..d3984ec905 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2692,7 +2692,7 @@
"chatEmbedding": {
"cell": {
"label": "啟用對話記錄語義索引",
- "description": "新訊息嵌入到本地向量庫 (voyage-4) 供未來語義搜尋,僅本機訪問,不外傳。開啟時機起的訊息才被索引,歷史不補。"
+ "description": "新訊息和語義搜尋查詢會傳送給向量模型(voyage-4)產生向量;訊息向量儲存在本機索引中。僅索引啟用後的訊息,不會為既有對話記錄補建索引。"
},
"toggleAria": "切換對話記錄語義索引",
"toast": {
diff --git a/apps/desktop/src/renderer/lib/chatEmbeddingStore.ts b/apps/desktop/src/renderer/lib/chatEmbeddingStore.ts
index c4cf390db8..acde353891 100644
--- a/apps/desktop/src/renderer/lib/chatEmbeddingStore.ts
+++ b/apps/desktop/src/renderer/lib/chatEmbeddingStore.ts
@@ -1,32 +1,88 @@
/**
- * chatEmbeddingStore — 聊天嵌入开关的 renderer 端镜像。
+ * chatEmbeddingStore — 对话语义索引开关的 renderer 镜像。
*
- * **真正的 source of truth 是 main 的 <userData>/chat-embedding-settings.json**
- * (apps/desktop/src/main/maker-host/chat-embedding-settings-store.ts), 这里
- * localStorage 只是 renderer UI 即时态镜像 (同 compatModeStore 形态)。
- *
- * 同步路径:
- * - 启动: bootstrapChatEmbeddingFromMain() 调 IPC 拉 main 真值, 写 localStorage
- * - toggle: ChatEmbeddingCell 调 IPC, 然后调 setChatEmbeddingEnabled() 更新本地镜像
- * - provider 变化: useChatEmbedding 重新拉 main 有效值,避免运行时可用性切换留下旧镜像
- * - main 是 source of truth, renderer 不会从其它路径篡改
- *
- * 二态:
- * - true : 新消息会被 enqueue 到 embedding_jobs, Worker 异步嵌入到 chat_messages_vec_v1
- * - false : createMessage hook 在 enabled 守卫处直接 return, 零成本
- *
- * **偏好默认 true** —— 与 main DEFAULTS 对齐。本镜像只用于设置 UI 即时态; 真正的
- * enqueue 守卫在 main (chat-history-embedder)。bootstrap 在 renderer 启动早期从 main
- * 拉取有效值;请求完成后,不可用或显式关过的状态会同步成 false。
+ * Main 的 owner-scoped settings file 是唯一真值;这里按 dataOwnerId 缓存完整 UI 快照,
+ * 仅用于设置页即时渲染。账号切换、Provider 刷新和用户拨动都带 revision fence,旧账号或
+ * 旧请求的迟到结果不能覆盖当前 owner。
*/
import { extractIpcError } from '@/utils/ipcError';
-const STORAGE_KEY = 'chatEmbedding.enabled';
+const STORAGE_KEY_PREFIX = 'chatEmbedding.settings';
+
+export interface ChatEmbeddingSnapshot {
+ enabled: boolean;
+ isCustomized: boolean;
+ defaultEnabled: boolean;
+}
+
+export interface ChatEmbeddingMutationToken {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ ownerRevision: number;
+ mutationRevision: number;
+ previous: ChatEmbeddingSnapshot;
+}
-type Subscriber = (value: boolean) => void;
+type Subscriber = (value: ChatEmbeddingSnapshot) => void;
const subscribers = new Set<Subscriber>();
+let activeOwnerId: string | null = null;
+let activeOwnerGeneration = 0;
+let activeDefaultEnabled = false;
+let ownerRevision = 0;
+let mutationRevision = 0;
+let refreshRevision = 0;
+let activeMutationRevision: number | null = null;
+let synchronizationDeferredDuringMutation = false;
+let inMemorySnapshot: ChatEmbeddingSnapshot = {
+ enabled: false,
+ isCustomized: false,
+ defaultEnabled: false,
+};
+
+function storageKey(): string {
+ return `${STORAGE_KEY_PREFIX}.${activeOwnerId ?? 'signed-out'}`;
+}
+
+function normalizeSnapshot(raw: unknown): ChatEmbeddingSnapshot | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Partial<ChatEmbeddingSnapshot>;
+ if (
+ typeof value.enabled !== 'boolean' ||
+ typeof value.isCustomized !== 'boolean' ||
+ typeof value.defaultEnabled !== 'boolean'
+ ) {
+ return null;
+ }
+ return {
+ enabled: value.enabled,
+ isCustomized: value.isCustomized,
+ defaultEnabled: value.defaultEnabled,
+ };
+}
+
+function readStoredSnapshot(): ChatEmbeddingSnapshot | null {
+ try {
+ const raw = localStorage.getItem(storageKey());
+ return raw ? normalizeSnapshot(JSON.parse(raw)) : null;
+ } catch {
+ return null;
+ }
+}
+
+function publishSnapshot(next: ChatEmbeddingSnapshot, persist = true): void {
+ inMemorySnapshot = { ...next };
+ if (persist) {
+ try {
+ localStorage.setItem(storageKey(), JSON.stringify(inMemorySnapshot));
+ } catch {
+ // localStorage is only a cache; Main remains authoritative.
+ }
+ }
+ subscribers.forEach((cb) => cb({ ...inMemorySnapshot }));
+}
+
/** Stable chat-embedding IPC errors to localized settings copy. */
export function chatEmbeddingFailureKey(error: unknown): string {
return extractIpcError(error)?.code === 'UNSUPPORTED_CAPABILITY'
@@ -34,35 +90,67 @@ export function chatEmbeddingFailureKey(error: unknown): string {
: 'settings.chatEmbedding.toast.toggleFailed';
}
+export function getChatEmbeddingSnapshot(): ChatEmbeddingSnapshot {
+ return { ...inMemorySnapshot };
+}
+
/**
- * 同步读 — 默认开 (与 main DEFAULTS 对齐): 仅当显式存过 'false' 才关; 没存过 (null)
- * 或 localStorage 不可用 → true。bootstrap 会用 main 真值覆盖 (显式关过的用户同步成 false)。
+ * Switch the renderer mirror synchronously at the auth boundary. Returns true when the owner or
+ * its account-derived default changed and Main should be refreshed.
*/
-export function getChatEmbeddingEnabled(): boolean {
- try {
- return localStorage.getItem(STORAGE_KEY) !== 'false';
- } catch {
- return true;
+export function setChatEmbeddingSettingsOwner(
+ ownerId: string | null,
+ ownerGeneration: number,
+ defaultEnabled: boolean,
+): boolean {
+ if (
+ activeOwnerId === ownerId &&
+ activeOwnerGeneration === ownerGeneration &&
+ activeDefaultEnabled === defaultEnabled
+ ) {
+ return false;
}
-}
+ activeOwnerId = ownerId;
+ activeOwnerGeneration = ownerGeneration;
+ activeDefaultEnabled = defaultEnabled;
+ ownerRevision += 1;
+ mutationRevision += 1;
+ refreshRevision += 1;
+ activeMutationRevision = null;
+ synchronizationDeferredDuringMutation = false;
-/** 同步写 — 落 localStorage + 通知 subscriber */
-export function setChatEmbeddingEnabled(next: boolean): void {
- try {
- localStorage.setItem(STORAGE_KEY, next ? 'true' : 'false');
- } catch {
- // localStorage 不可用 — 忽略
- }
- subscribers.forEach((cb) => cb(next));
+ const stored = readStoredSnapshot();
+ const next = stored
+ ? {
+ ...stored,
+ enabled:
+ !stored.isCustomized && stored.defaultEnabled !== defaultEnabled
+ ? defaultEnabled
+ : stored.enabled,
+ defaultEnabled,
+ }
+ : {
+ enabled: defaultEnabled,
+ isCustomized: false,
+ defaultEnabled,
+ };
+ publishSnapshot(next);
+ return true;
}
-/** 订阅变化 — hook 用, 也可以给非 React 路径用。返回 unsubscribe。 */
-export function subscribeChatEmbeddingEnabled(cb: Subscriber): () => void {
+export function subscribeChatEmbeddingSnapshot(cb: Subscriber): () => void {
subscribers.add(cb);
- const storageHandler = (e: StorageEvent) => {
- if (e.key !== STORAGE_KEY) return;
- cb(getChatEmbeddingEnabled());
+ const storageHandler = (event: StorageEvent) => {
+ if (event.key !== storageKey()) return;
+ if (activeMutationRevision !== null) {
+ synchronizationDeferredDuringMutation = true;
+ return;
+ }
+ const next = readStoredSnapshot();
+ if (!next) return;
+ mutationRevision += 1;
+ publishSnapshot(next, false);
};
window.addEventListener('storage', storageHandler);
@@ -72,19 +160,90 @@ export function subscribeChatEmbeddingEnabled(cb: Subscriber): () => void {
};
}
-/**
- * 启动期一次性从 main 拉真值同步到 localStorage。
- * app entry (index.tsx) 在启动早期触发异步读取;完成后更新 localStorage 和 subscriber。
- *
- * 失败兜底: IPC 错误 (preload 未就绪 / main 异常) 静默 — 留旧值, 用户 toggle
- * 时仍能通过 IPC 写 main, 下次启动恢复正常。
- */
-export async function bootstrapChatEmbeddingFromMain(): Promise<void> {
+export function beginChatEmbeddingMutation(
+ optimisticEnabled?: boolean,
+): ChatEmbeddingMutationToken {
+ mutationRevision += 1;
+ activeMutationRevision = mutationRevision;
+ synchronizationDeferredDuringMutation = false;
+ const token: ChatEmbeddingMutationToken = {
+ dataOwnerId: activeOwnerId,
+ ownerGeneration: activeOwnerGeneration,
+ ownerRevision,
+ mutationRevision,
+ previous: getChatEmbeddingSnapshot(),
+ };
+ if (typeof optimisticEnabled === 'boolean') {
+ publishSnapshot({
+ ...inMemorySnapshot,
+ enabled: optimisticEnabled,
+ isCustomized: true,
+ });
+ }
+ return token;
+}
+
+function isCurrentMutation(token: ChatEmbeddingMutationToken): boolean {
+ return token.ownerRevision === ownerRevision && token.mutationRevision === activeMutationRevision;
+}
+
+export function completeChatEmbeddingMutation(
+ token: ChatEmbeddingMutationToken,
+ settings: ChatEmbeddingSnapshot,
+): boolean {
+ if (!isCurrentMutation(token)) return false;
+ const shouldRefresh = synchronizationDeferredDuringMutation;
+ activeMutationRevision = null;
+ synchronizationDeferredDuringMutation = false;
+ mutationRevision += 1;
+ publishSnapshot(settings);
+ if (shouldRefresh) void refreshChatEmbeddingFromMain();
+ return true;
+}
+
+export function rollbackChatEmbeddingMutation(token: ChatEmbeddingMutationToken): boolean {
+ if (!isCurrentMutation(token)) return false;
+ const shouldRefresh = synchronizationDeferredDuringMutation;
+ activeMutationRevision = null;
+ synchronizationDeferredDuringMutation = false;
+ mutationRevision += 1;
+ publishSnapshot(token.previous);
+ if (shouldRefresh) void refreshChatEmbeddingFromMain();
+ return true;
+}
+
+/** Load the current Main truth and drop stale owner/provider/mutation responses. */
+export async function refreshChatEmbeddingFromMain(): Promise<void> {
+ const requestOwnerRevision = ownerRevision;
+ const requestMutationRevision = mutationRevision;
+ const requestRevision = ++refreshRevision;
try {
const settings = await window.electronAPI.maker.chatEmbeddingGet();
- if (getChatEmbeddingEnabled() === settings.enabled) return;
- setChatEmbeddingEnabled(settings.enabled);
+ if (requestOwnerRevision !== ownerRevision || requestRevision !== refreshRevision) {
+ return;
+ }
+ if (activeMutationRevision !== null) {
+ synchronizationDeferredDuringMutation = true;
+ return;
+ }
+ if (requestMutationRevision !== mutationRevision) {
+ void refreshChatEmbeddingFromMain();
+ return;
+ }
+ publishSnapshot({
+ enabled: settings.enabled,
+ isCustomized: Boolean(settings.isCustomized),
+ defaultEnabled: Boolean(settings.defaultEnabled),
+ });
} catch {
- // preload 未就绪 / IPC 异常 — 留旧 localStorage
+ // Main may still be starting. Auth/provider changes and component mount retry.
}
}
+
+export async function bootstrapChatEmbeddingFromMain(): Promise<void> {
+ await refreshChatEmbeddingFromMain();
+}
+
+export const __testing = {
+ normalizeSnapshot,
+};
diff --git a/apps/desktop/src/renderer/main-entry.tsx b/apps/desktop/src/renderer/main-entry.tsx
index 901f1d2f4d..de605fe86d 100644
--- a/apps/desktop/src/renderer/main-entry.tsx
+++ b/apps/desktop/src/renderer/main-entry.tsx
@@ -67,8 +67,8 @@ const disposeHiddenAnimationGate = installHiddenAnimationGate();
migrateLegacyVoiceInputRendererStorage();
void syncVoiceInputGlobalShortcut(getVoiceInputSettings().shortcut);
void bootstrapSilentEncryptedRetryFromMain();
-// chat embedding 开关 (Phase 1.2) — 同款镜像同步方式, 让 Settings UI 第一次渲染时
-// localStorage 已是真值, 用户能看到正确的初始 toggle 状态。
+// 对话语义索引开关 —— 先同步 signed-out 镜像;AuthContext 提交稳定 owner 后会切换
+// owner 分区并重拉 Main 真值,迟到的启动响应会被 revision fence 丢弃。
void bootstrapChatEmbeddingFromMain();
// LSP Beta 开关 (Phase 1) — admin-only, 默认 false; 同款镜像同步方式。
void bootstrapLspModeFromMain();
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 66894925f4..4ced23a3d4 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5645,17 +5645,24 @@ interface ElectronAPI {
/** 仅对新 session 生效; 已开 session 的 mcp providers 已固化 */
lspModeSet: (enabled: boolean) => Promise<{ effective: 'next-session' }>;
- /** 聊天嵌入开关 — 控制 chat-history-embedder 是否对新消息入队嵌入到本地向量库 */
+ /** 对话语义索引开关 — owner-scoped;企业组织账号默认开,其余默认关 */
chatEmbeddingGet: () => Promise<{
enabled: boolean;
isCustomized?: boolean;
defaultEnabled?: boolean;
}>;
+ onChatEmbeddingChanged: (
+ cb: (stamp: { dataOwnerId: string | null; ownerGeneration: number }) => void,
+ ) => () => void;
/** 立即生效; 第一次开启时 main 会在 embedding_meta 表写入 cutoff 时间戳 */
chatEmbeddingSet: (
enabled: boolean,
+ owner: { dataOwnerId: string | null; ownerGeneration: number },
) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;
- chatEmbeddingReset: () => Promise<{
+ chatEmbeddingReset: (owner: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }) => Promise<{
enabled: boolean;
isCustomized: boolean;
defaultEnabled: boolean;