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): 拒绝 isolated 落到正式 profile,DEVICE_MISMATCH 不再删盘

Dasha240c9284248
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
index ea3dc0b000..58367f5485 100644
--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
@@ -41,10 +41,25 @@ describe('passive shared-userData instance auth isolation', () => {
// packaged 恒不设置该 env,但仍保留 isPackaged 双保险,防 ambient env 污染线上语义。
expect(body).toContain('!app.isPackaged');
expect(body).toContain("process.env.XDT_PASSIVE_SHARED_USER_DATA === '1'");
- // 不新增判定通道:isolated 沙箱有独立 userData 与 deviceId,不该出现在这条判定里。
+ // 不新增判定通道:是否共库由启动期 profileKind 落地成这个 env,本函数只读结果。
expect(body).not.toContain('XDT_ISOLATED');
});
+ it('DEVICE_MISMATCH 只登出本进程,不删磁盘 refresh token', () => {
+ expect(authSource).toContain("action.kind === 'foreign-device'");
+ expect(authSource).toContain(
+ 'cold-start refresh: DEVICE_MISMATCH — this process starts logged out and keeps the persisted refresh token',
+ );
+ expect(authSource).toContain(
+ 'runtime refresh: DEVICE_MISMATCH — expiring this process and keeping the persisted refresh token',
+ );
+ const runtimeIdx = authSource.indexOf(
+ 'runtime refresh: DEVICE_MISMATCH — expiring this process and keeping the persisted refresh token',
+ );
+ const preserveIdx = authSource.indexOf('preservePersistedRefreshToken: true', runtimeIdx);
+ expect(preserveIdx).toBeGreaterThan(runtimeIdx);
+ });
+
it('clearAuth:passive 共享实例不删磁盘 refresh token', () => {
const body = sliceBody('function clearAuth(', 'commitActiveAppSession');
diff --git a/apps/desktop/src/main/__tests__/authRefreshFailure.test.ts b/apps/desktop/src/main/__tests__/authRefreshFailure.test.ts
index b503682c66..f20ff9b12b 100644
--- a/apps/desktop/src/main/__tests__/authRefreshFailure.test.ts
+++ b/apps/desktop/src/main/__tests__/authRefreshFailure.test.ts
@@ -11,6 +11,7 @@ import {
DEFINITIVE_REFRESH_FAILURE_CODES,
getRefreshTokenReplacementCandidate,
isDefinitiveRefreshFailure,
+ isForeignDeviceRefreshFailure,
pickRefreshTokenReplacementCandidate,
resolveRefreshFailureAction,
resolveSessionExpiredReason,
@@ -41,16 +42,17 @@ describe('isDefinitiveRefreshFailure', () => {
});
it('确定性凭据失效码 → 删除 token', () => {
- for (const code of [
- 'REFRESH_TOKEN_EXPIRED',
- 'INVALID_REFRESH_TOKEN',
- 'DEVICE_MISMATCH',
- 'MEMBERSHIP_DISABLED',
- ]) {
+ for (const code of ['REFRESH_TOKEN_EXPIRED', 'INVALID_REFRESH_TOKEN', 'MEMBERSHIP_DISABLED']) {
expect(isDefinitiveRefreshFailure({ ok: false, data: { error: { code } } })).toBe(true);
}
});
+ it('DEVICE_MISMATCH 不是确定性失效,不得授权删盘', () => {
+ const result = { ok: false, data: { error: { code: 'DEVICE_MISMATCH' } } };
+ expect(isDefinitiveRefreshFailure(result)).toBe(false);
+ expect(isForeignDeviceRefreshFailure(result)).toBe(true);
+ });
+
it('429 限流(RATE_LIMITED)→ 瞬时失败,保留 token', () => {
expect(
isDefinitiveRefreshFailure({ ok: false, data: { error: { code: 'RATE_LIMITED' } } }),
@@ -75,7 +77,6 @@ describe('isDefinitiveRefreshFailure', () => {
it('确定性错误码集合保持冻结(防止误增删改变删除语义)', () => {
expect([...DEFINITIVE_REFRESH_FAILURE_CODES].sort()).toEqual([
- 'DEVICE_MISMATCH',
'INVALID_REFRESH_TOKEN',
'MEMBERSHIP_DISABLED',
'REFRESH_TOKEN_EXPIRED',
@@ -197,14 +198,20 @@ describe('refresh token replacement detection', () => {
expect(resolveRefreshFailureAction(expiredToken, 'rt-old', 'rt-new')).toEqual({
kind: 'definitive-failure',
});
- expect(resolveRefreshFailureAction(deviceMismatch, 'rt-old', 'rt-new')).toEqual({
- kind: 'definitive-failure',
- });
expect(resolveRefreshFailureAction(membershipDisabled, 'rt-old', 'rt-new')).toEqual({
kind: 'definitive-failure',
});
});
+ it('DEVICE_MISMATCH 即使磁盘已有其它 token 也不删盘,只判 foreign-device', () => {
+ expect(resolveRefreshFailureAction(deviceMismatch, 'rt-old', 'rt-new')).toEqual({
+ kind: 'foreign-device',
+ });
+ expect(resolveRefreshFailureAction(deviceMismatch, 'rt-old', 'rt-old')).toEqual({
+ kind: 'foreign-device',
+ });
+ });
+
it('确定性失败且磁盘 token 未变化 → 清登录态', () => {
expect(resolveRefreshFailureAction(invalidToken, 'rt-old', 'rt-old')).toEqual({
kind: 'definitive-failure',
@@ -305,7 +312,7 @@ describe('refresh token replacement detection', () => {
requestedToken: 'rt-old',
replacementRetries: 0,
replacementRetryExhausted: false,
- failureAction: { kind: 'definitive-failure' },
+ failureAction: { kind: 'foreign-device' },
});
expect(sleep).not.toHaveBeenCalled();
expect(doRefresh).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/main/__tests__/devCliFlags.test.ts b/apps/desktop/src/main/__tests__/devCliFlags.test.ts
index 64855b1d13..ac7f687127 100644
--- a/apps/desktop/src/main/__tests__/devCliFlags.test.ts
+++ b/apps/desktop/src/main/__tests__/devCliFlags.test.ts
@@ -5,7 +5,9 @@ import { tmpdir } from 'node:os';
import { basename, dirname, join } from 'node:path';
import {
+ isIsolatedIdentityOnProductionProfile,
resolveDevCliFlags,
+ resolveDevProfileKind,
resolveSingleInstanceLockUserDataDir,
shouldEnforcePassiveMigrationCompatibility,
shouldRequestSingleInstanceLock,
@@ -45,6 +47,8 @@ describe('resolveDevCliFlags', () => {
expect(resolveDevCliFlags(base)).toEqual({
schedulerPassive: false,
isolated: false,
+ profileKind: 'production-shared',
+ isolatedOnProductionProfile: false,
userDataDirOverride: null,
isolatedDirIsEpochDerived: false,
needsIsolatedDeviceId: false,
@@ -357,6 +361,46 @@ describe('resolveDevCliFlags', () => {
});
expect(flags.userDataDirOverride).toBe('/custom/sandbox');
expect(flags.needsIsolatedDeviceId).toBe(true);
+ expect(flags.profileKind).toBe('custom');
+ expect(flags.isolatedOnProductionProfile).toBe(false);
+ });
+
+ it('--isolated + 正式 profile 目录判定为非法第三态', () => {
+ const flags = resolveDevCliFlags({
+ ...base,
+ argv: [...base.argv, '--isolated'],
+ envUserDataDir: '/AppData/xdt-maker',
+ });
+ expect(flags.isolated).toBe(true);
+ expect(flags.needsIsolatedDeviceId).toBe(true);
+ expect(flags.profileKind).toBe('production-shared');
+ expect(flags.isolatedOnProductionProfile).toBe(true);
+ expect(flags.isolatedDirIsEpochDerived).toBe(false);
+ });
+
+ it('--isolated 指向另一地区正式目录也是非法第三态', () => {
+ const toCn = resolveDevCliFlags({
+ ...base,
+ argv: [...base.argv, '--isolated'],
+ envUserDataDir: '/AppData/Cindy',
+ });
+ expect(toCn.profileKind).toBe('production-shared');
+ expect(toCn.isolatedOnProductionProfile).toBe(true);
+ expect(toCn.needsIsolatedDeviceId).toBe(true);
+
+ const toGlobal = resolveDevCliFlags({
+ ...base,
+ argv: [...base.argv, '--isolated'],
+ envUserDataDir: '/AppData/CindyGlobal',
+ });
+ expect(toGlobal.profileKind).toBe('production-shared');
+ expect(toGlobal.isolatedOnProductionProfile).toBe(true);
+ });
+
+ it('--isolated 默认沙箱是 isolated-sandbox,不是正式 profile', () => {
+ const flags = resolveDevCliFlags({ ...base, argv: [...base.argv, '--isolated'] });
+ expect(flags.profileKind).toBe('isolated-sandbox');
+ expect(flags.isolatedOnProductionProfile).toBe(false);
});
it('仅设 XDT_USER_DATA_DIR(无隔离意图)沿用原语义,不派生设备标识', () => {
@@ -378,6 +422,8 @@ describe('resolveDevCliFlags', () => {
expect(flags).toEqual({
schedulerPassive: false,
isolated: false,
+ profileKind: 'production-shared',
+ isolatedOnProductionProfile: false,
userDataDirOverride: null,
isolatedDirIsEpochDerived: false,
needsIsolatedDeviceId: false,
@@ -412,32 +458,83 @@ describe('resolveDevCliFlags', () => {
});
expect(flags.schedulerPassive).toBe(true);
expect(flags.isolated).toBe(true);
+ expect(flags.profileKind).toBe('isolated-sandbox');
expect(flags.userDataDirOverride).toBe('/AppData/xdt-maker-dev2-feature-a');
expect(flags.isolationName).toBe('feature-a');
});
});
+describe('resolveDevProfileKind / isIsolatedIdentityOnProductionProfile', () => {
+ it('正式目录一律是 production-shared,isolated 旗标不能把它变成沙箱', () => {
+ expect(
+ resolveDevProfileKind({
+ isolatedDirIsEpochDerived: false,
+ effectiveUserDataDir: '/AppData/xdt-maker',
+ productionUserDataDir: '/AppData/xdt-maker',
+ }),
+ ).toBe('production-shared');
+ expect(
+ isIsolatedIdentityOnProductionProfile({
+ isolated: true,
+ effectiveUserDataDir: '/AppData/xdt-maker',
+ productionUserDataDir: '/AppData/xdt-maker',
+ }),
+ ).toBe(true);
+ });
+
+ it('另一地区正式目录也算正式 profile,不能当成 custom', () => {
+ expect(
+ resolveDevProfileKind({
+ isolatedDirIsEpochDerived: false,
+ effectiveUserDataDir: '/AppData/Cindy',
+ productionUserDataDir: '/AppData/CindyGlobal',
+ }),
+ ).toBe('production-shared');
+ expect(
+ resolveDevProfileKind({
+ isolatedDirIsEpochDerived: false,
+ effectiveUserDataDir: '/AppData/CindyGlobal',
+ productionUserDataDir: '/AppData/Cindy',
+ }),
+ ).toBe('production-shared');
+ expect(
+ isIsolatedIdentityOnProductionProfile({
+ isolated: true,
+ effectiveUserDataDir: '/AppData/Cindy',
+ productionUserDataDir: '/AppData/CindyGlobal',
+ }),
+ ).toBe(true);
+ });
+});
+
describe('shouldEnforcePassiveMigrationCompatibility', () => {
- it('只对共享 userData 的 passive dev 启用,isolated 与 packaged 不启用', () => {
+ it('只对共享正式 profile 的 passive dev 启用,沙箱 / custom / packaged 不启用', () => {
expect(
shouldEnforcePassiveMigrationCompatibility({
isPackaged: false,
schedulerPassive: true,
- isolated: false,
+ profileKind: 'production-shared',
}),
).toBe(true);
expect(
shouldEnforcePassiveMigrationCompatibility({
isPackaged: false,
schedulerPassive: true,
- isolated: true,
+ profileKind: 'isolated-sandbox',
+ }),
+ ).toBe(false);
+ expect(
+ shouldEnforcePassiveMigrationCompatibility({
+ isPackaged: false,
+ schedulerPassive: true,
+ profileKind: 'custom',
}),
).toBe(false);
expect(
shouldEnforcePassiveMigrationCompatibility({
isPackaged: true,
schedulerPassive: true,
- isolated: false,
+ profileKind: 'production-shared',
}),
).toBe(false);
});
diff --git a/apps/desktop/src/main/__tests__/isolatedOnProductionProfileStartup.test.ts b/apps/desktop/src/main/__tests__/isolatedOnProductionProfileStartup.test.ts
new file mode 100644
index 0000000000..7dcff15828
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/isolatedOnProductionProfileStartup.test.ts
@@ -0,0 +1,27 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * isolated 身份落在正式 profile 上必须在换目录 / 换 deviceId 之前拒绝启动。
+ * 2026-08-16:cindy-pi-live-model-catalog 自称 isolated、目录仍是正式 Cindy,
+ * DEVICE_MISMATCH 后清掉正式版 refresh token。
+ */
+describe('isolated-on-production-profile startup refuse', () => {
+ const indexSource = readFileSync(resolve(process.cwd(), 'src/main/index.ts'), 'utf8').replace(
+ /\r\n/g,
+ '\n',
+ );
+
+ it('main process fail-closes before applying userData or isolated deviceId', () => {
+ const refuseIdx = indexSource.indexOf('if (devFlags.isolatedOnProductionProfile)');
+ const setPathIdx = indexSource.indexOf("app.setPath('userData', devFlags.userDataDirOverride)");
+ const deviceIdx = indexSource.indexOf('if (devFlags.needsIsolatedDeviceId)');
+ expect(refuseIdx).toBeGreaterThan(-1);
+ expect(setPathIdx).toBeGreaterThan(refuseIdx);
+ expect(deviceIdx).toBeGreaterThan(refuseIdx);
+ expect(indexSource).toContain("isolated: devFlags.profileKind === 'isolated-sandbox'");
+ expect(indexSource).toContain('isolationIntent: devFlags.isolated');
+ expect(indexSource).toContain('profileKind: devFlags.profileKind');
+ });
+});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 705ddf7006..709c8f4f44 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -366,9 +366,9 @@ function createAuthClient(
* 发生过一次,当时只把静默半死改成明确弹重登(见 authSessionExpiredDetection.test.ts),
* 没有堵住 passive 的销毁权。
*
- * packaged 恒不设置该 env(index.ts 启动时对 packaged / isolated 显式 delete 兜底,
- * 防 ambient env 污染),线上零影响;`--isolated` 沙箱有独立 userData 与 deviceId,
- * 本来就不共享,不受此闸门约束。
+ * packaged 恒不设置该 env(index.ts 启动时对 packaged / 非正式共享 profile 显式
+ * delete 兜底,防 ambient env 污染),线上零影响。env 由解析后的 profileKind ===
+ * production-shared 且 passive 落地,不看 isolated 旗标。
*/
function isPassiveSharedUserDataInstance(): boolean {
return !app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1';
@@ -2516,6 +2516,10 @@ async function runColdStartRefreshFlow(
clearConfirmedDeadRefreshTokens(storedRealm, confirmedDeadTokens);
}
resetActiveAuthRealmToBuild();
+ } else if (action.kind === 'foreign-device') {
+ log.warn(
+ 'cold-start refresh: DEVICE_MISMATCH — this process starts logged out and keeps the persisted refresh token',
+ );
} else if (action.kind === 'replacement-retry') {
log.warn(
`cold-start refresh failed for a stale token after ${attempts} attempt(s) — keeping latest refresh token, starting logged out`,
@@ -3233,6 +3237,15 @@ export async function refresh(): Promise<boolean> {
const previousUserId =
currentUser?.id ?? getActiveAppSession().dataOwnerId ?? 'signed-out';
await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));
+ } else if (action.kind === 'foreign-device') {
+ log.warn(
+ 'runtime refresh: DEVICE_MISMATCH — expiring this process and keeping the persisted refresh token',
+ );
+ const previousUserId =
+ currentUser?.id ?? getActiveAppSession().dataOwnerId ?? 'signed-out';
+ await expireRuntimeAuth(previousUserId, 'device-mismatch', {
+ preservePersistedRefreshToken: true,
+ });
} else if (action.kind === 'replacement-retry') {
log.warn(
`runtime refresh failed for a stale token after replacement retries status=${result.status} code=${code ?? '<none>'} — retrying in ${RUNTIME_REFRESH_RETRY_MS / 1000}s`,
diff --git a/apps/desktop/src/main/authRefreshFailure.ts b/apps/desktop/src/main/authRefreshFailure.ts
index c1033609fa..bde99997fd 100644
--- a/apps/desktop/src/main/authRefreshFailure.ts
+++ b/apps/desktop/src/main/authRefreshFailure.ts
@@ -13,10 +13,16 @@
export const DEFINITIVE_REFRESH_FAILURE_CODES: ReadonlySet<string> = new Set([
'REFRESH_TOKEN_EXPIRED',
'INVALID_REFRESH_TOKEN',
- 'DEVICE_MISMATCH',
'MEMBERSHIP_DISABLED',
]);
+/**
+ * 当前进程的 device 配不上这枚 token。token 对真正的那台设备可能仍然有效,
+ * 不能单凭这个错误码删盘(2026-08-16:isolated 身份落在正式 profile 上,
+ * DEVICE_MISMATCH 后删掉正式版 refresh token)。
+ */
+export const FOREIGN_DEVICE_REFRESH_FAILURE_CODE = 'DEVICE_MISMATCH';
+
/** 只有这个错误码可能来自同机多实例轮换竞态;其它确定性错误换 token 无效。 */
const REPLACEMENT_RETRY_ELIGIBLE_CODES: ReadonlySet<string> = new Set(['INVALID_REFRESH_TOKEN']);
@@ -27,8 +33,8 @@ export interface RefreshErrorBody {
/**
* 判断一次 `/api/auth/refresh` 调用结果是否为「确定性凭据失效」——即应当从本地清除
- * refresh token。返回 `false` 表示:要么成功,要么是应当**保留** token 的瞬时失败
- * (429 限流 / 5xx / 断网 status:0 / 无识别码的 4xx)。
+ * refresh token。返回 `false` 表示:要么成功,要么是应当**保留** token 的失败
+ * (429 限流 / 5xx / 断网 status:0 / 无识别码的 4xx / DEVICE_MISMATCH)。
*
* @param result apiFetch 返回值的最小子集:`ok` + 响应体 `data`。
*/
@@ -38,6 +44,11 @@ export function isDefinitiveRefreshFailure(result: { ok: boolean; data: unknown
return typeof code === 'string' && DEFINITIVE_REFRESH_FAILURE_CODES.has(code);
}
+export function isForeignDeviceRefreshFailure(result: { ok: boolean; data: unknown }): boolean {
+ if (result.ok) return false;
+ return getRefreshErrorCode(result) === FOREIGN_DEVICE_REFRESH_FAILURE_CODE;
+}
+
function getRefreshErrorCode(result: { data: unknown }): string | undefined {
return (result.data as RefreshErrorBody | null)?.error?.code;
}
@@ -119,11 +130,13 @@ export function resolveSessionExpiredReason(code: string | undefined): SessionEx
export type RefreshFailureAction =
| { kind: 'transient-failure' }
| { kind: 'definitive-failure' }
+ | { kind: 'foreign-device' }
| { kind: 'replacement-retry'; refreshToken: string };
/**
- * 把 refresh 失败分为三类:
+ * 把 refresh 失败分为四类:
* - transient: 网络/限流/服务端临时问题,保留 token 后续自愈;
+ * - foreign-device: 当前进程 device 配不上这枚 token,本进程登出但不得删盘;
* - definitive: 当前磁盘 token 也已失败,清态重登;
* - replacement-retry: 本次请求用的是 stale token,磁盘已有别的实例写入的新 token。
*/
@@ -135,6 +148,7 @@ export function resolveRefreshFailureAction(
requestedToken: string,
latestStoredToken: string | null,
): RefreshFailureAction {
+ if (isForeignDeviceRefreshFailure(result)) return { kind: 'foreign-device' };
if (!isDefinitiveRefreshFailure(result)) return { kind: 'transient-failure' };
if (!isReplacementRetryEligibleFailure(result)) return { kind: 'definitive-failure' };
const replacement = getRefreshTokenReplacementCandidate(requestedToken, latestStoredToken);
diff --git a/apps/desktop/src/main/devCliFlags.ts b/apps/desktop/src/main/devCliFlags.ts
index 0622f629b7..9a192587b6 100644
--- a/apps/desktop/src/main/devCliFlags.ts
+++ b/apps/desktop/src/main/devCliFlags.ts
@@ -111,6 +111,12 @@ function defaultCanonicalizePath(p: string): string {
*/
const ISOLATION_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
+/**
+ * 同机所有正式区域 profile 的目录名。当前构建区域只决定默认目录和沙箱派生,
+ * 不能缩小保护集合:Global 启动指到 CN 的 Cindy、反向同理,都仍是正式 profile。
+ */
+export const OFFICIAL_USER_DATA_DIR_NAMES = ['Cindy', 'CindyGlobal', 'CindyDev'] as const;
+
export interface DevCliFlagsInput {
argv: readonly string[];
isPackaged: boolean;
@@ -148,11 +154,18 @@ export interface DevCliFlagsInput {
envEndpointsCdn: string | undefined;
}
+/** 解析后的实际 profile 归属。安全权限必须看这个,不能只看启动旗标。 */
+export type DevProfileKind = 'production-shared' | 'isolated-sandbox' | 'custom';
+
export interface DevCliFlags {
/** --passive:本实例定时任务不自动触发(scheduler-host 读 XDT_SCHEDULER_PASSIVE)。 */
schedulerPassive: boolean;
/** 是否由 --isolated / XDT_ISOLATED 明确进入独立 userData 沙箱。 */
isolated: boolean;
+ /** 实际落地的 profile 种类。isolated 旗标指向正式目录时仍是 production-shared。 */
+ profileKind: DevProfileKind;
+ /** isolated 身份却落在正式 profile 上:启动器必须拒绝。 */
+ isolatedOnProductionProfile: boolean;
/**
* 生效的 userData 覆写目录;null = 不覆写。来源优先级:
* 显式 XDT_USER_DATA_DIR > 隔离模式默认沙箱目录(<userData>-dev2[-<名字>])> 不覆写。
@@ -224,18 +237,71 @@ export function resolveSingleInstanceLockUserDataDir(input: {
}
/**
- * passive 只有在共享 userData 时才需要禁止 migration。
+ * passive 只有在共享正式 profile 时才需要禁止 migration。
*
* 显式 isolated 沙箱没有其它实例替它初始化数据库,仍按正常启动路径迁移;packaged
* 不接受任何 dev-only passive 语义。调用方会把这个纯判定同步成内部 env,供延后加载
* 的 localDb 模块在首次打开用户数据库时执行硬闸。
+ *
+ * 判定看解析后的 profileKind,不看 isolated 旗标:旗标说 isolated、目录却是正式版时
+ * 仍按 production-shared 处理(启动器应先拒绝这种组合)。
*/
export function shouldEnforcePassiveMigrationCompatibility(input: {
isPackaged: boolean;
schedulerPassive: boolean;
+ profileKind: DevProfileKind;
+}): boolean {
+ return !input.isPackaged && input.schedulerPassive && input.profileKind === 'production-shared';
+}
+
+export function resolveOfficialUserDataDirs(defaultUserDataDir: string): string[] {
+ const parent = dirname(defaultUserDataDir);
+ return [
+ defaultUserDataDir,
+ ...OFFICIAL_USER_DATA_DIR_NAMES.map((name) => join(parent, name)),
+ ];
+}
+
+function isOfficialUserDataDir(
+ dir: string,
+ officialDirs: readonly string[],
+ canonicalize: (value: string) => string,
+): boolean {
+ const target = canonicalize(dir);
+ return officialDirs.some((official) => canonicalize(official) === target);
+}
+
+export function isIsolatedIdentityOnProductionProfile(input: {
isolated: boolean;
+ effectiveUserDataDir: string;
+ productionUserDataDir?: string;
+ officialUserDataDirs?: readonly string[];
+ canonicalizePath?: (value: string) => string;
}): boolean {
- return !input.isPackaged && input.schedulerPassive && !input.isolated;
+ if (!input.isolated) return false;
+ const canonicalize = input.canonicalizePath ?? defaultCanonicalizePath;
+ const officialDirs =
+ input.officialUserDataDirs ??
+ resolveOfficialUserDataDirs(input.productionUserDataDir ?? input.effectiveUserDataDir);
+ return isOfficialUserDataDir(input.effectiveUserDataDir, officialDirs, canonicalize);
+}
+
+export function resolveDevProfileKind(input: {
+ isolatedDirIsEpochDerived: boolean;
+ effectiveUserDataDir: string;
+ productionUserDataDir?: string;
+ officialUserDataDirs?: readonly string[];
+ canonicalizePath?: (value: string) => string;
+}): DevProfileKind {
+ const canonicalize = input.canonicalizePath ?? defaultCanonicalizePath;
+ const officialDirs =
+ input.officialUserDataDirs ??
+ resolveOfficialUserDataDirs(input.productionUserDataDir ?? input.effectiveUserDataDir);
+ if (isOfficialUserDataDir(input.effectiveUserDataDir, officialDirs, canonicalize)) {
+ return 'production-shared';
+ }
+ if (input.isolatedDirIsEpochDerived) return 'isolated-sandbox';
+ return 'custom';
}
export function resolveDevCliFlags(input: DevCliFlagsInput): DevCliFlags {
@@ -243,6 +309,8 @@ export function resolveDevCliFlags(input: DevCliFlagsInput): DevCliFlags {
return {
schedulerPassive: false,
isolated: false,
+ profileKind: 'production-shared',
+ isolatedOnProductionProfile: false,
userDataDirOverride: null,
isolatedDirIsEpochDerived: false,
needsIsolatedDeviceId: false,
@@ -310,9 +378,25 @@ export function resolveDevCliFlags(input: DevCliFlagsInput): DevCliFlags {
explicitDirTrusted &&
userDataDirOverride !== null &&
canonicalize(userDataDirOverride) === canonicalize(epochDerivedDir);
+ const effectiveUserDataDir = userDataDirOverride ?? input.defaultUserDataDir;
+ const officialUserDataDirs = resolveOfficialUserDataDirs(input.defaultUserDataDir);
+ const isolatedOnProductionProfile = isIsolatedIdentityOnProductionProfile({
+ isolated,
+ effectiveUserDataDir,
+ officialUserDataDirs,
+ canonicalizePath: canonicalize,
+ });
+ const profileKind = resolveDevProfileKind({
+ isolatedDirIsEpochDerived,
+ effectiveUserDataDir,
+ officialUserDataDirs,
+ canonicalizePath: canonicalize,
+ });
return {
schedulerPassive: input.argv.includes('--passive') || input.envSchedulerPassive === '1',
isolated,
+ profileKind,
+ isolatedOnProductionProfile,
userDataDirOverride,
isolatedDirIsEpochDerived,
needsIsolatedDeviceId: isolated && !input.envDeviceIdOverride?.trim(),
diff --git a/apps/desktop/src/main/devStartupStatus.ts b/apps/desktop/src/main/devStartupStatus.ts
index ae6a0504b9..eac1b8d300 100644
--- a/apps/desktop/src/main/devStartupStatus.ts
+++ b/apps/desktop/src/main/devStartupStatus.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
+import type { DevProfileKind } from './devCliFlags.js';
export type DesktopDevMode = 'remote' | 'local' | 'unknown';
export type DesktopDevInstanceState = 'starting' | 'ready' | 'failed';
@@ -28,7 +29,12 @@ export interface DesktopDevInstanceRecord {
/** 构建区域;共享 userData 启动器据此拒绝跨区域 passive 预览。 */
region: CindyRegion;
passive: boolean;
+ /** 解析后是否真的落在独立纪元沙箱。不是「有 userData 覆写」。 */
isolated: boolean;
+ /** 启动旗标是否声明了 --isolated / XDT_ISOLATED。 */
+ isolationIntent?: boolean;
+ /** 解析后的实际 profile 归属。 */
+ profileKind?: DevProfileKind;
userDataDir: string;
state: DesktopDevInstanceState;
failure?: {
@@ -46,6 +52,8 @@ export interface BeginDesktopDevInstanceOptions {
region?: CindyRegion;
passive: boolean;
isolated: boolean;
+ isolationIntent?: boolean;
+ profileKind?: DevProfileKind;
pid?: number;
startedAtMs?: number;
instanceId?: string;
@@ -139,6 +147,8 @@ export function beginDesktopDevInstance(
region: options.region ?? 'global',
passive: options.passive,
isolated: options.isolated,
+ ...(options.isolationIntent !== undefined ? { isolationIntent: options.isolationIntent } : {}),
+ ...(options.profileKind !== undefined ? { profileKind: options.profileKind } : {}),
userDataDir: path.resolve(options.userDataDir),
state: 'starting',
};
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 5b87625258..06e0fc1f3a 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -101,6 +101,17 @@ const devFlags = resolveDevCliFlags({
envSchedulerPassive: process.env.XDT_SCHEDULER_PASSIVE,
envEndpointsCdn: process.env.XDT_ENDPOINTS_CDN,
});
+if (devFlags.isolatedOnProductionProfile) {
+ // isolated 身份会换独立 deviceId;正式 profile 上的 refresh token 属于正式版设备。
+ // 两者叠在同一目录 = 必然 DEVICE_MISMATCH,再删盘会把正式版踢下线(2026-08-16)。
+ // 报实际目标目录:可能是当前区域,也可能是另一地区的正式 profile。
+ const targetDir = devFlags.userDataDirOverride ?? app.getPath('userData');
+ stderr.write(
+ `[cindy] FATAL: --isolated cannot use the official Cindy profile (${targetDir}). ` +
+ 'Use the default sandbox, --isolated=<name>, or a directory that is not an official userData.\n',
+ );
+ exit(1);
+}
if (devFlags.schedulerPassive) {
// 统一收敛到 env:scheduler-host 只认 XDT_SCHEDULER_PASSIVE,不重复解析 argv。
process.env.XDT_SCHEDULER_PASSIVE = '1';
@@ -109,7 +120,7 @@ if (devFlags.schedulerPassive) {
if (shouldEnforcePassiveMigrationCompatibility({
isPackaged: app.isPackaged,
schedulerPassive: devFlags.schedulerPassive,
- isolated: devFlags.isolated,
+ profileKind: devFlags.profileKind,
})) {
// 内部启动契约:共享 userData 的 passive dev 只能打开与当前 checkout migration
// 完全一致的数据库,且不得自行迁移。localDb 在用户数据库首次打开时消费本标记。
@@ -228,7 +239,9 @@ if (devFlags.needsIsolatedDeviceId) {
mode,
region: CURRENT_CINDY_REGION,
passive: devFlags.schedulerPassive,
- isolated: Boolean(devFlags.userDataDirOverride),
+ isolated: devFlags.profileKind === 'isolated-sandbox',
+ isolationIntent: devFlags.isolated,
+ profileKind: devFlags.profileKind,
});
app.once('will-quit', cleanupDevInstance);
}
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index a70c55eb72..5dc332d9e0 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -37,9 +37,14 @@ Cindy 内部而拒绝重启,或因目标 userData 被其他 checkout 占用而
数据」时用。**未合入主干的 migration 必须在 `--isolated` 沙箱里跑,不得连共享 userData**
(见 [`database-and-migrations.md`](database-and-migrations.md))。沙箱(及任何 dev
userData 覆写)内不触发首登旧数据迁移(mToc):不探测老目录、不弹确认窗、不把正式
- 数据复制进沙箱。
-- `--passive`:定时任务被动模式,本实例不自动触发 schedule,但数据仍与其它实例共享;
- 多开导致定时任务重复、需要让位给 primary 时用。共享 userData 的 passive 实例对
+ 数据复制进沙箱。**`--isolated` 不得落在任一正式 profile 上**:显式 `XDT_USER_DATA_DIR`
+ 若指向 CN / Global / Dev 任一正式目录(不限当前构建区域),启动器与主进程都 fail closed。isolated 会换独立 deviceId,
+ 正式目录里的 refresh token 属于正式版设备,叠在一起必然 `DEVICE_MISMATCH`,再删盘会
+ 把正式版踢下线(2026-08-16)。
+- `--passive`:定时任务被动模式,本实例不自动触发 schedule。多开导致定时任务重复、
+ 需要让位给 primary 时用。它可以和 `--isolated` 组合(隔离沙箱只看 UI、不跑定时任务
+ 是合法的)。**共库只读契约不是这个旗标本身**,而是解析后的正式 profile + passive
+ 才落地。共享正式 profile 的 passive 实例对
userData 布局保持只读:不执行 owner-namespace 迁移(claim 推迟到下次独占启动),
legacy 数据导入(`hasLegacyOwnerNamespaceClaim` 门控的 secret/IM/brain 搬账)
一并等待。非 passive 实例执行该迁移前也会先查 `.dev-instances` 实例注册表
@@ -58,14 +63,16 @@ Cindy 内部而拒绝重启,或因目标 userData 被其他 checkout 占用而
refresh token——那写入的是有效凭证,primary 侧由 replacement-retry 消化。反过来让
passive 停止续期,会使它的 access token 过期后再无替换途径(primary 的续期只更新磁盘
token,不更新 passive 进程的内存态,而直接走 `apiFetch` 的路径没有 401 refresh/retry)。
-- `--preserve-running`:并行 dev,不停止任何已有 Cindy dev 进程,每个新实例强制 passive
- 并共享当前区域的 userData/登录态;启动前必须由 `.dev-instances` 存活记录证明已运行
+- `--preserve-running`:启动编排,不是运行期模式。默认 restart 本来就不会关正式版和
+ 其它 worktree,只替换**当前 checkout** 的旧 dev;本旗标连这份旧 dev 也保留,再并排
+ 开一个共库预览,并强制 `--passive`。启动前必须由 `.dev-instances` 存活记录证明已运行
实例与目标区域一致,旧记录没有 region 或跨区域都会 fail closed。仅供能证明实例归属的
- 上层编排,或用户明确「不要关当前实例/不要重新登录」时用。仅支持 remote,禁止与
- `--isolated` 组合。共享实例若只发现没有 realm 的旧版裸 refresh token,也不得猜区域迁移
- 或轮换,保持本进程登出,交给同区域独占实例完成凭证迁移。
+ 上层编排,或用户明确「不要关当前实例/不要重新登录」时用。仅支持 remote。禁止与
+ `--isolated` 或环境里的 `XDT_ISOLATED=1` 组合。共享实例若只发现没有 realm 的旧版裸
+ refresh token,也不得猜区域迁移或轮换,保持本进程登出,交给同区域独占实例完成凭证迁移。
已手动设 `XDT_USER_DATA_DIR` 时尊重用户值,不覆盖,也不探测或迁移正式区域目录。
+唯一例外:`--isolated` / `XDT_ISOLATED=1` 把该目录指到正式 profile 时直接拒绝启动。
正式版目录保持历史兼容:CN → `Cindy`,Global → `CindyGlobal`,不在启动时改名或搬迁用户数据。
非隔离 dev 也使用当前区域对应的正式 profile;`--isolated` 沙箱再按相同区域映射派生目录。
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index a0c5c8e3fc..ab8785e94b 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -11,7 +11,11 @@ import {
commandUsesUserDataDir,
defaultIsolatedUserDataDir,
devEnvPrefix,
+ hasIsolationIntent,
+ isOfficialProductionUserDataDir,
isRepositoryDesktopDevProcess,
+ officialProductionUserDataDirs,
+ resolveRestartTargetUserDataDir,
formatDesktopStartupFailure,
inspectSharedUserDataRegion,
partitionDesktopDevProcesses,
@@ -151,6 +155,46 @@ test("default isolated userData path is region-aware", () => {
assert.equal(path.basename(defaultIsolatedUserDataDir("review", "dev")), "CindyDev-dev2-review");
});
+test("hasIsolationIntent sees argv and ambient XDT_ISOLATED=1", () => {
+ assert.equal(hasIsolationIntent([]), false);
+ assert.equal(hasIsolationIntent(["--isolated"]), true);
+ assert.equal(hasIsolationIntent(["--isolated=review"]), true);
+ assert.equal(hasIsolationIntent([], { XDT_ISOLATED: "1" }), true);
+ assert.equal(hasIsolationIntent([], { XDT_ISOLATED: "0" }), false);
+});
+
+test("isOfficialProductionUserDataDir matches every official region profile", () => {
+ assert.equal(isOfficialProductionUserDataDir(productionUserDataDir("cn")), true);
+ assert.equal(isOfficialProductionUserDataDir(productionUserDataDir("global")), true);
+ assert.equal(isOfficialProductionUserDataDir(productionUserDataDir("dev")), true);
+ assert.equal(isOfficialProductionUserDataDir(defaultIsolatedUserDataDir("", "cn")), false);
+ assert.ok(officialProductionUserDataDirs().some((dir) => path.basename(dir) === "Cindy"));
+ assert.ok(officialProductionUserDataDirs().some((dir) => path.basename(dir) === "CindyGlobal"));
+});
+
+test("isolated restart target pointing at the other region's official profile is refused", () => {
+ const cnFromGlobal = resolveRestartTargetUserDataDir({
+ envUserDataDir: productionUserDataDir("cn"),
+ isolatedArg: "--isolated",
+ selectedRegion: "global",
+ });
+ assert.equal(isOfficialProductionUserDataDir(cnFromGlobal), true);
+ const globalFromCn = resolveRestartTargetUserDataDir({
+ envUserDataDir: productionUserDataDir("global"),
+ isolatedArg: "--isolated",
+ selectedRegion: "cn",
+ });
+ assert.equal(isOfficialProductionUserDataDir(globalFromCn), true);
+});
+
+test("isolated official-profile refuse happens before mkdir in the restart main flow", () => {
+ const source = fs.readFileSync(new URL("../restart-desktop-remote.mjs", import.meta.url), "utf8");
+ const refuseIdx = source.indexOf("isOfficialProductionUserDataDir(targetUserDataDir)");
+ const mkdirIdx = source.indexOf("fs.mkdirSync(process.env.XDT_USER_DATA_DIR");
+ assert.ok(refuseIdx > 0);
+ assert.ok(mkdirIdx > refuseIdx);
+});
+
test("preserve-running only shares a target with live records from the same region", () => {
const userData = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-shared-region-"));
const records = path.join(userData, ".dev-instances");
diff --git a/scripts/desktop-whoami.mjs b/scripts/desktop-whoami.mjs
index 7f36bac2be..7b15495c2a 100644
--- a/scripts/desktop-whoami.mjs
+++ b/scripts/desktop-whoami.mjs
@@ -271,6 +271,8 @@ export function mergeDesktopInstanceRecords(scanned, records, worktrees) {
region: record.region ?? null,
passive: Boolean(record.passive),
isolated: Boolean(record.isolated),
+ isolationIntent: record.isolationIntent === true,
+ profileKind: typeof record.profileKind === 'string' ? record.profileKind : null,
userDataDir: record.userDataDir,
commit: record.commit ?? null,
commitVerified: typeof record.commit === 'string' && record.commit.length > 0,
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index 7595e01177..1624858629 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -6,6 +6,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
applyDesktopDevStartupConfig,
+ DESKTOP_DEV_REGIONS,
desktopUserDataDirNameForRegion,
resolveDesktopDevRegion,
} from './shared/desktop-dev-region.mjs';
@@ -449,6 +450,31 @@ function userDataDirNamed(dirName) {
return path.join(xdgConfig, dirName);
}
+export function hasIsolationIntent(argv = [], env = process.env) {
+ return argv.some((arg) => arg === '--isolated' || arg.startsWith('--isolated='))
+ || env.XDT_ISOLATED === '1';
+}
+
+export function officialProductionUserDataDirs() {
+ return DESKTOP_DEV_REGIONS.map((region) => productionUserDataDir(region));
+}
+
+export function isOfficialProductionUserDataDir(dir) {
+ const resolved = path.resolve(dir);
+ return officialProductionUserDataDirs().some((official) => path.resolve(official) === resolved);
+}
+
+export function resolveRestartTargetUserDataDir({
+ envUserDataDir,
+ isolatedArg,
+ selectedRegion,
+}) {
+ return envUserDataDir
+ || (isolatedArg
+ ? defaultIsolatedUserDataDir(parseIsolationName(isolatedArg), selectedRegion)
+ : productionUserDataDir(selectedRegion));
+}
+
export function defaultIsolatedUserDataDir(isolationName, region = 'global') {
// 目录纪元 v2(-dev2),与 devCliFlags.ts 的派生保持一字不差:#871 起隔离沙箱用
// CindyDev 钥匙串身份,旧 -dev 目录留给旧 checkout(#912 review)。
@@ -791,9 +817,9 @@ async function main() {
'--preserve-running only supports remote mode: sharing remote login storage with a local auth server could invalidate the persisted credential',
);
}
- if (preserveRunning && isolatedArg) {
+ if (preserveRunning && hasIsolationIntent(argv, process.env)) {
throw new Error(
- '--preserve-running reuses the current Cindy login via shared userData and cannot be combined with --isolated',
+ '--preserve-running reuses the current Cindy login via shared userData and cannot be combined with --isolated or XDT_ISOLATED=1',
);
}
if (startupConfig) {
@@ -853,8 +879,6 @@ async function main() {
// 路径以默认身份打开造成双身份互写(#912 review P1)。
process.env.XDT_USER_DATA_DIR_EPOCH = '1';
}
- fs.mkdirSync(process.env.XDT_USER_DATA_DIR, { recursive: true });
- console.log(`==> Isolated dev user data${isolationName ? ` (sandbox "${isolationName}")` : ''}: ${process.env.XDT_USER_DATA_DIR}`);
}
if (startupConfig) ensureDesktopEnv();
@@ -887,10 +911,25 @@ async function main() {
// --isolated 名字,或用户自己停掉那个实例。preserve-running 不进此门 ——
// 它的语义就是共享 userData 的被动预览。检测是尽力而为:靠 helper 进程命令行
// 上的 --user-data-dir,对方实例刚启动还没起 helper 时可能漏检。
- const targetUserDataDir = process.env.XDT_USER_DATA_DIR
- || (isolatedArg
- ? defaultIsolatedUserDataDir(parseIsolationName(isolatedArg), selectedRegion)
- : productionUserDataDir(selectedRegion));
+ const targetUserDataDir = resolveRestartTargetUserDataDir({
+ envUserDataDir: process.env.XDT_USER_DATA_DIR,
+ isolatedArg,
+ selectedRegion,
+ });
+ if (
+ hasIsolationIntent(argv, process.env)
+ && isOfficialProductionUserDataDir(targetUserDataDir)
+ ) {
+ throw new Error(
+ `--isolated cannot use the official Cindy profile (${targetUserDataDir}). ` +
+ 'Omit XDT_USER_DATA_DIR, or point it at a sandbox directory.',
+ );
+ }
+ if (startupConfig && isolatedArg && process.env.XDT_USER_DATA_DIR) {
+ fs.mkdirSync(process.env.XDT_USER_DATA_DIR, { recursive: true });
+ const isolationName = parseIsolationName(isolatedArg);
+ console.log(`==> Isolated dev user data${isolationName ? ` (sandbox "${isolationName}")` : ''}: ${process.env.XDT_USER_DATA_DIR}`);
+ }
if (!preserveRunning) {
const conflicts = listDesktopDevProcesses().filter(
(proc) => !commandContainsPath(proc.command, rootDir)