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): 修复实例残留导致模型开关失效

liugaoweidfb014444477
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
index 8da9debb17..346c19508c 100644
--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
@@ -268,6 +268,76 @@ describe('claimLegacyOwnerNamespace', () => {
expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(true);
});
+ it('prunes a schema-v1 record after proving that its PID was reused', async () => {
+ const root = await tempRoot();
+ const startedAtMs = 1_000_000;
+ const recordPath = path.join(root, '.dev-instances', '4242.json');
+ await writeDevInstanceRecord(root, 4242, root, {
+ instanceId: 'stale-instance',
+ startedAtMs,
+ });
+
+ await __testing.warmStaleProcessProvenance(
+ root,
+ realFsDeps(root, {
+ isPidAlive: (pid) => pid === 4242,
+ readProcessIdentity: () => ({
+ startedAtMs: startedAtMs + 120_000,
+ command: 'C:\\Windows\\System32\\OpenConsole.exe --server',
+ }),
+ }),
+ );
+
+ await expect(fs.access(recordPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(true);
+ });
+
+ it('keeps a replacement record that changes during stale-PID cleanup', async () => {
+ const root = await tempRoot();
+ const startedAtMs = 1_000_000;
+ const recordPath = path.join(root, '.dev-instances', '4242.json');
+ await writeDevInstanceRecord(root, 4242, root, {
+ instanceId: 'stale-instance',
+ startedAtMs,
+ });
+ const originalRaw = await fs.readFile(recordPath, 'utf-8');
+ const replacementRaw = JSON.stringify({
+ schemaVersion: 1,
+ instanceId: 'replacement-instance',
+ pid: 4242,
+ userDataDir: root,
+ startedAtMs: startedAtMs + 1,
+ });
+ let recordReads = 0;
+
+ await __testing.warmStaleProcessProvenance(
+ root,
+ realFsDeps(
+ root,
+ {
+ isPidAlive: (pid) => pid === 4242,
+ readProcessIdentity: () => ({
+ startedAtMs: startedAtMs + 120_000,
+ command: 'C:\\Windows\\System32\\OpenConsole.exe --server',
+ }),
+ },
+ {
+ readFile: async (file: string) => {
+ if (file !== recordPath) return fs.readFile(file, 'utf-8');
+ recordReads += 1;
+ if (recordReads === 1) return originalRaw;
+ await fs.writeFile(recordPath, replacementRaw, 'utf-8');
+ return replacementRaw;
+ },
+ },
+ ),
+ );
+
+ expect(recordReads).toBeGreaterThanOrEqual(2);
+ await expect(fs.access(recordPath)).resolves.toBeUndefined();
+ expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);
+ });
+
it('keeps local startup fail-closed when provenance warmup cannot read identity', async () => {
const root = await tempRoot();
await writeDevInstanceRecord(root, 4242, root, { startedAtMs: 1_000_000 });
@@ -3195,7 +3265,7 @@ async function writeDevInstanceRecord(
root: string,
pid: number,
userDataDir: string = root,
- options: { startedAtMs?: number; rootDir?: string } = {},
+ options: { startedAtMs?: number; rootDir?: string; instanceId?: string } = {},
): Promise<void> {
const registryDir = path.join(root, '.dev-instances');
await fs.mkdir(registryDir, { recursive: true });
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 9e65172c0b..ecf1aba7e4 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -251,6 +251,8 @@ if (devFlags.needsIsolatedDeviceId) {
isolationIntent: devFlags.isolated,
profileKind: devFlags.profileKind,
});
+ // Windows updater forceQuit() ends in process.exit(0), which bypasses Electron will-quit.
+ process.once('exit', cleanupDevInstance);
app.once('will-quit', cleanupDevInstance);
}
diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.ts
index 11d295b439..47c5c18f44 100644
--- a/apps/desktop/src/main/ownerNamespaceMigration.ts
+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts
@@ -106,6 +106,8 @@ interface MigrationDeps {
}
interface RegisteredInstanceRecord {
+ schemaVersion?: number;
+ instanceId?: string;
pid?: number;
userDataDir?: string;
startedAtMs?: number;
@@ -554,6 +556,42 @@ function recordedPidMayStillBeLive(
return looksLikeCindyRuntime(identity.command, rootDir);
}
+type StaleRegistrySettlement = 'pruned' | 'gone' | 'changed' | 'retained';
+
+/** Delete only the exact schema-v1 `<pid>.json` payload that the OS identity scan proved stale. */
+async function settleStaleRegistryRecord(
+ deps: MigrationDeps,
+ registryDir: string,
+ candidate: {
+ raw: string;
+ fileName: string;
+ schemaVersion: number | undefined;
+ instanceId: string | undefined;
+ pid: number;
+ },
+): Promise<StaleRegistrySettlement> {
+ if (
+ candidate.schemaVersion !== 1
+ || typeof candidate.instanceId !== 'string'
+ || candidate.instanceId.length === 0
+ || candidate.fileName !== `${candidate.pid}.json`
+ ) {
+ return 'retained';
+ }
+ const filePath = path.join(registryDir, candidate.fileName);
+ try {
+ if (await deps.readFile(filePath) !== candidate.raw) return 'changed';
+ } catch (error) {
+ return isMissing(error) ? 'gone' : 'changed';
+ }
+ try {
+ await deps.unlink(filePath);
+ return 'pruned';
+ } catch (error) {
+ return isMissing(error) ? 'gone' : 'retained';
+ }
+}
+
/**
* Synchronous twin of findConcurrentLiveInstancePids for importer and sidebar
* guards. It never launches an OS inspection command from these reusable main
@@ -2455,6 +2493,8 @@ async function findConcurrentLiveInstancePids(
const candidates: Array<{
raw: string;
fileName: string;
+ schemaVersion: number | undefined;
+ instanceId: string | undefined;
pid: number;
recordedAtMs: number | undefined;
rootDir: string | undefined;
@@ -2489,6 +2529,8 @@ async function findConcurrentLiveInstancePids(
candidates.push({
raw,
fileName: name,
+ schemaVersion: record.schemaVersion,
+ instanceId: record.instanceId,
pid,
recordedAtMs: record.startedAtMs,
rootDir: record.rootDir,
@@ -2506,10 +2548,23 @@ async function findConcurrentLiveInstancePids(
if (recordedPidMayStillBeLive(candidate.recordedAtMs, candidate.rootDir, identity)) {
pids.push(candidate.pid);
} else {
- rememberStaleProcessProof(
- processProofKey(userDataDir, 'registry', `${candidate.fileName}\u0000${candidate.raw}`),
+ const settlement = await settleStaleRegistryRecord(deps, registryDir, candidate);
+ if (settlement === 'changed') {
+ // The identity belongs to the old payload; a replacement remains unproven in this pass.
+ pids.push(candidate.pid);
+ continue;
+ }
+ if (settlement === 'retained') {
+ rememberStaleProcessProof(
+ processProofKey(userDataDir, 'registry', `${candidate.fileName}\u0000${candidate.raw}`),
+ );
+ }
+ log.info(
+ settlement === 'pruned'
+ ? 'pruned stale instance registry record after PID reuse'
+ : 'ignoring stale instance registry record after PID reuse',
+ { pid: candidate.pid },
);
- log.info('ignoring stale instance registry record after PID reuse', { pid: candidate.pid });
}
}
diff --git a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
index 7916b4a9cb..8124c44394 100644
--- a/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelVisibilityPrefs.test.ts
@@ -35,6 +35,7 @@ class MemLocalStorage {
let memStorage: MemLocalStorage;
const syncModelVisibility = vi.fn(async () => undefined);
+const logToMain = vi.fn();
let ownerClaim: {
dataOwnerId: string | null;
ownerGeneration: number;
@@ -62,10 +63,12 @@ function setOwnerClaim(
beforeEach(() => {
memStorage = new MemLocalStorage();
syncModelVisibility.mockClear();
+ logToMain.mockClear();
setOwnerClaim('owner-a', 1);
vi.stubGlobal('window', {
localStorage: memStorage,
electronAPI: {
+ logToMain,
maker: {
syncModelVisibility,
claimLegacyModelVisibilityOwner: () => ownerClaim,
@@ -151,8 +154,8 @@ describe('modelVisibilityPrefs store', () => {
it('同值写入短路:不抛,值保持', async () => {
const { isModelEnabled, setModelVisibility } = await loadModuleForOwner();
- setModelVisibility('codex', 'openai', 'gpt-5.4', false);
- expect(() => setModelVisibility('codex', 'openai', 'gpt-5.4', false)).not.toThrow();
+ expect(setModelVisibility('codex', 'openai', 'gpt-5.4', false)).toBe(true);
+ expect(setModelVisibility('codex', 'openai', 'gpt-5.4', false)).toBe(true);
expect(isModelEnabled('codex', 'openai', { id: 'gpt-5.4' })).toBe(false);
});
@@ -222,10 +225,33 @@ describe('modelVisibilityPrefs store', () => {
setOwnerClaim('owner-a', 1, false, false);
const module = await loadModuleForOwner();
- module.setModelVisibility('codex', 'openai', 'gpt-5.5', false);
+ expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(false);
expect(memStorage.getItem('xdt:modelVisibilityPrefs:v1.owner.owner-a')).toBeNull();
expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(true);
+ expect(logToMain).toHaveBeenCalledWith(
+ 'warn',
+ 'ModelVisibilityPrefs',
+ expect.stringContaining('owner-write-not-ready'),
+ );
+ });
+
+ it('owner-scoped 存储失败时返回失败并保持旧状态', async () => {
+ const module = await loadModuleForOwner();
+ const mirrorCallsBeforeFailure = syncModelVisibility.mock.calls.length;
+ const setItem = vi.spyOn(memStorage, 'setItem').mockImplementation(() => {
+ throw new Error('injected storage failure');
+ });
+
+ expect(module.setModelVisibility('codex', 'openai', 'gpt-5.5', false)).toBe(false);
+ expect(module.isModelEnabled('codex', 'openai', { id: 'gpt-5.5' })).toBe(true);
+ expect(syncModelVisibility).toHaveBeenCalledTimes(mirrorCallsBeforeFailure);
+ expect(logToMain).toHaveBeenCalledWith(
+ 'warn',
+ 'ModelVisibilityPrefs',
+ expect.stringContaining('storage-write-failed'),
+ );
+ setItem.mockRestore();
});
it('已有 owner-scoped override 优先,迁移不会覆盖', async () => {
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index 11660377f2..bc2c028709 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -472,18 +472,23 @@ export function UnifiedModelList({
const refreshLabel = refreshing
? t('settings.providers.models.refreshingAria')
: (refreshIdleLabel ?? t('settings.providers.models.refreshAria'));
+ const showVisibilityWriteFailure = useCallback(() => {
+ toast.error(t('settings.providers.models.visibilityWriteFailed'));
+ }, [t]);
/** 单开关(显示轴):一次写该行全部可用 agent(分歧行拨动即归一)。写入用各 agent 的
* **真实模型 id**(桥接投影行两端 id 不同:chatgpt/gpt-5.5 vs gpt-5.5),不能用规范化后的 row.id。 */
const toggleRow = useCallback(
(row: UnionModelRow) => {
const next = !rowAnyEnabled(provider.id, row);
+ let failed = false;
for (const a of row.avail) {
const m = row.byAgent[a];
- if (m) setModelVisibility(a, provider.id, m.id, next);
+ if (m && setModelVisibility(a, provider.id, m.id, next) === false) failed = true;
}
+ if (failed) showVisibilityWriteFailure();
},
- [provider.id],
+ [provider.id, showVisibilityWriteFailure],
);
/** 全部显示 / 隐藏:逐 agent 批量写(单 agent 一次落盘)。只作用于**对话模型的显示轴**
@@ -492,6 +497,7 @@ export function UnifiedModelList({
* 行 key):刚停用、快照未回来的行同样不写(PR #744 review)。 */
const handleBulk = useCallback(() => {
const next = !allOn;
+ let failed = false;
for (const agent of provider.agents) {
const ids = (provider.models[agent] ?? [])
.filter(
@@ -501,9 +507,10 @@ export function UnifiedModelList({
true,
)
.map((m) => m.id);
- setManyVisibility(agent, provider.id, ids, next);
+ if (setManyVisibility(agent, provider.id, ids, next) === false) failed = true;
}
- }, [allOn, provider, pendingDisabled]);
+ if (failed) showVisibilityWriteFailure();
+ }, [allOn, provider, pendingDisabled, showVisibilityWriteFailure]);
/** 行级「⋯」菜单(hover 显现;菜单打开期间保持可见):停用动作的唯一入口。 */
const rowMenu = (row: UnionModelRow) => (
@@ -795,7 +802,11 @@ export function UnifiedModelList({
{m ? (
<Switch
checked={isModelEnabled(a, provider.id, m)}
- onCheckedChange={(v) => setModelVisibility(a, provider.id, m.id, v)}
+ onCheckedChange={(v) => {
+ if (setModelVisibility(a, provider.id, m.id, v) === false) {
+ showVisibilityWriteFailure();
+ }
+ }}
aria-label={`${rep.name} · ${AGENT_LABEL[a]}`}
/>
) : (
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f470277c36..e152d7ca56 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1575,6 +1575,7 @@
"enableModel": "Enable This Model",
"capabilityGroupHint": "Not shown in the chat model picker; used only by features like image generation.",
"accessWriteFailed": "Couldn't save the change. Please try again.",
+ "visibilityWriteFailed": "Couldn't save the model visibility setting. Try again, or restart Cindy if the problem continues.",
"disabledGroup": "Disabled",
"enableAllModels": "Enable All",
"priceOverride": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c154c963ef..62f7b9140f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1574,6 +1574,7 @@
"enableModel": "このモデルを有効にする",
"capabilityGroupHint": "チャットのモデル選択には表示されず、画像生成などの機能でのみ使用されます。",
"accessWriteFailed": "変更を保存できませんでした。もう一度お試しください。",
+ "visibilityWriteFailed": "モデルの表示設定を保存できませんでした。もう一度お試しください。問題が解決しない場合は、Cindy を再起動してください。",
"disabledGroup": "無効",
"enableAllModels": "すべて有効にする",
"priceOverride": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 382403be2c..6ac7c16164 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1574,6 +1574,7 @@
"enableModel": "이 모델 활성화",
"capabilityGroupHint": "대화 모델 선택에는 표시되지 않으며, 이미지 생성 등 기능에서만 사용됩니다.",
"accessWriteFailed": "변경 사항을 저장하지 못했습니다. 다시 시도해 주세요.",
+ "visibilityWriteFailed": "모델 표시 설정을 저장하지 못했습니다. 다시 시도해 주세요. 문제가 계속되면 Cindy를 다시 시작해 주세요.",
"disabledGroup": "비활성화됨",
"enableAllModels": "모두 활성화",
"priceOverride": {
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 6472c93790..bc5603df67 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1574,6 +1574,7 @@
"enableModel": "启用此模型",
"capabilityGroupHint": "不会出现在对话模型选择中,仅供图像生成等功能使用",
"accessWriteFailed": "停用设置未能保存,请重试",
+ "visibilityWriteFailed": "模型显示设置未能保存,请重试;如果仍然失败,请重启 Cindy。",
"disabledGroup": "已停用",
"enableAllModels": "全部启用",
"priceOverride": {
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 0f0b2e2735..fcda1965c2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1574,6 +1574,7 @@
"enableModel": "啟用此模型",
"capabilityGroupHint": "不會出現在對話模型選擇中,僅供影像生成等功能使用",
"accessWriteFailed": "停用設定未能儲存,請重試",
+ "visibilityWriteFailed": "模型顯示設定未能儲存,請重試;如果仍然失敗,請重新啟動 Cindy。",
"disabledGroup": "已停用",
"enableAllModels": "全部啟用",
"priceOverride": {
diff --git a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
index ae24e96055..5781a3581b 100644
--- a/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
+++ b/apps/desktop/src/renderer/state/modelVisibilityPrefs.ts
@@ -34,6 +34,9 @@ import { useSyncExternalStore } from 'react';
import { isModelVisible } from '@cindy/model-providers';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('ModelVisibilityPrefs');
const LEGACY_STORAGE_KEY = 'xdt:modelVisibilityPrefs:v1';
const STORAGE_KEY_PREFIX = `${LEGACY_STORAGE_KEY}.owner`;
@@ -198,19 +201,43 @@ function mirrorToMain(map: VisibilityMap): void {
let version = 0;
const listeners = new Set<() => void>();
-function persist(map: VisibilityMap): void {
+interface VisibilityWriteContext {
+ operation: 'single' | 'bulk';
+ agent: AgentKind;
+ providerId: string;
+ enabled: boolean;
+ modelId?: string;
+ modelCount?: number;
+}
+
+function persist(map: VisibilityMap, context: VisibilityWriteContext): boolean {
+ if (typeof window === 'undefined' || !activeOwnerId) {
+ log.warn('model visibility write rejected', {
+ reason: 'owner-unavailable',
+ ...context,
+ ownerGeneration: activeOwnerGeneration,
+ mode: activeOwnerMode,
+ });
+ return false;
+ }
+ try {
+ window.localStorage.setItem(ownerStorageKey(activeOwnerId), JSON.stringify(map));
+ } catch (error) {
+ log.warn('model visibility write failed', {
+ reason: 'storage-write-failed',
+ ...context,
+ ownerGeneration: activeOwnerGeneration,
+ mode: activeOwnerMode,
+ }, error);
+ return false;
+ }
+ // 先确认落盘成功,再更新受控开关状态,避免界面显示成功但重启后设置丢失。
cache = map;
version += 1;
- if (typeof window !== 'undefined' && activeOwnerId) {
- try {
- window.localStorage.setItem(ownerStorageKey(activeOwnerId), JSON.stringify(map));
- } catch {
- // localStorage 满 / 私密窗口禁写 —— 忽略,不影响内存缓存。
- }
- }
// 每次开关变更后把最新快照重推 main,保持 IM /model 与应用内可见性一致。
mirrorToMain(map);
for (const l of listeners) l();
+ return true;
}
function subscribe(cb: () => void): () => void {
@@ -270,12 +297,32 @@ export function setModelVisibility(
providerId: string,
modelId: string,
enabled: boolean,
-): void {
- if (!providerId || !modelId || !ensureActiveOwnerReadyForWrites()) return;
+): boolean {
+ const context: VisibilityWriteContext = {
+ operation: 'single',
+ agent,
+ providerId,
+ modelId,
+ enabled,
+ };
+ if (!providerId || !modelId) {
+ log.warn('model visibility write rejected', { reason: 'invalid-target', ...context });
+ return false;
+ }
+ if (!ensureActiveOwnerReadyForWrites()) {
+ log.warn('model visibility write rejected', {
+ reason: 'owner-write-not-ready',
+ ...context,
+ ownerGeneration: activeOwnerGeneration,
+ mode: activeOwnerMode,
+ migrationPending: activeOwnerMigrationPending,
+ });
+ return false;
+ }
const map = load();
const k = keyOf(agent, providerId, modelId);
- if (map[k] === enabled) return;
- persist({ ...map, [k]: enabled });
+ if (map[k] === enabled) return true;
+ return persist({ ...map, [k]: enabled }, context);
}
/**
@@ -288,8 +335,29 @@ export function setManyVisibility(
providerId: string,
modelIds: readonly string[],
enabled: boolean,
-): void {
- if (!providerId || modelIds.length === 0 || !ensureActiveOwnerReadyForWrites()) return;
+): boolean {
+ const context: VisibilityWriteContext = {
+ operation: 'bulk',
+ agent,
+ providerId,
+ modelCount: modelIds.length,
+ enabled,
+ };
+ if (!providerId) {
+ log.warn('model visibility write rejected', { reason: 'invalid-target', ...context });
+ return false;
+ }
+ if (modelIds.length === 0) return true;
+ if (!ensureActiveOwnerReadyForWrites()) {
+ log.warn('model visibility write rejected', {
+ reason: 'owner-write-not-ready',
+ ...context,
+ ownerGeneration: activeOwnerGeneration,
+ mode: activeOwnerMode,
+ migrationPending: activeOwnerMigrationPending,
+ });
+ return false;
+ }
const map = load();
let changed = false;
const next = { ...map };
@@ -300,7 +368,7 @@ export function setManyVisibility(
changed = true;
}
}
- if (changed) persist(next);
+ return changed ? persist(next, context) : true;
}
/**