Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude): 开发实例共用本机 Claude Code 登录
Lizi425613b4ec9f
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex 7cc8b480e1..545f26dd4d 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -124,6 +124,7 @@ beforeEach(async () => {});afterEach(async () => {+ if (vi.isMockFunction(os.homedir)) vi.mocked(os.homedir).mockRestore();if (originalClaudeConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;else process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir;if (originalXdtUserDataDir === undefined) delete process.env.XDT_USER_DATA_DIR;@@ -1908,9 +1909,12 @@ describe('forkSessionAtMessage', () => {});});- it('claude path: locates JSONL under XDT_USER_DATA_DIR claude-home when main env has no CLAUDE_CONFIG_DIR', async () => {+ it('claude path: falls back to the legacy dev XDT_USER_DATA_DIR/claude-home when ~/.claude lacks the JSONL', async () => {const userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-user-data-'));tempDirs.push(userDataDir);+ const emptyHome = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-empty-home-'));+ tempDirs.push(emptyHome);+ vi.spyOn(os, 'homedir').mockReturnValue(emptyHome);delete process.env.CLAUDE_CONFIG_DIR;process.env.XDT_USER_DATA_DIR = userDataDir;await writeClaudeJsonlInConfigDir(diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b5843ed671..3e80c0d3d7 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -820,6 +820,7 @@ import {runClaudeCliLogin,} from './maker-host/claude-native-cli.js';import { closeClaudeCliProxyBridge } from './maker-host/claude-cli-proxy-bridge.js';+import { startLegacyClaudeConfigMigration } from './maker-host/claude-legacy-config-migration.js';import { isNativeProviderAuthBound, isNativeProviderAuthRevoked } from './maker-host/nativeProviderAuthBinding.js';import {runGrokOAuthLogin,@@ -5096,6 +5097,9 @@ const registerIpcHandlers = () => {// 启动时后台读一次(不阻塞):已连接的用户由 provider 目录加载等这次结果;// 从未连接的用户据此自动沿用本机登录。明确断开过的用户不再读。if (!isNativeProviderAuthRevoked('anthropic')) void readClaudeCliLoginStatus();+ // 旧版 dev 隔离目录 claude-home 的转录补拷到默认 ~/.claude(仅 dev 多实例;后台跑,+ // 拉起 CLI 前 getAuthEnv 再等它一次)。正式版为 no-op。+ startLegacyClaudeConfigMigration();// 退出时结束进行中的登录子进程(CLI 的本机回调监听没有超时),并关闭 CLI 的代理桥。app.once('will-quit', () => {cancelClaudeCliLogin();@@ -6365,6 +6369,10 @@ const registerIpcHandlers = () => {// setClaudeCodePath 已退役 —— agent-binaries.prepare() 成功时已写 lastReadyPath cache;// 任何需要 claude binary 路径的地方一律走 getReadyBinaryPath('claude-code')。+ // 启动时那次 CLI 登录态读取往往早于二进制就绪(读不到);就绪后补读一次,结果变化经+ // onClaudeCliLoginStatusChange 广播,供应商页随之更新连接态。已有结果时是 no-op。+ if (!isNativeProviderAuthRevoked('anthropic')) void readClaudeCliLoginStatus();+// ── Phase 2: codex 段 ────────────────────────────────────────────────────resetBeforeSegment('codex', claudeRes.downloaded === true);diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.tsindex 26e464bcd0..b3dfb2abe5 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts@@ -25,6 +25,7 @@ const h = vi.hoisted(() => ({accounts: new Map<string, 'claude' | 'xai'>(),retainPresentation: vi.fn(),readLoginCalls: [] as Array<{ maxAgeMs?: number } | undefined>,+ legacyMigrations: 0,}));vi.mock('../provider-presentation-store.js', () => ({@@ -69,7 +70,12 @@ vi.mock('../claude-native-connection.js', () => ({vi.mock('../claude-native-cli.js', () => ({claudeCliNetworkEnv: async () => ({ ...h.networkEnv }),- claudeCliConfigDirOverride: () => undefined,+}));++vi.mock('../claude-legacy-config-migration.js', () => ({+ ensureLegacyClaudeConfigMigrated: async () => {+ h.legacyMigrations += 1;+ },}));vi.mock('../subscription-account-auth.js', () => ({@@ -131,6 +137,7 @@ describe('DesktopClaudeAuthAdapter — Claude 订阅只经 CLI 自己的登录',h.accounts.clear();h.retainPresentation.mockReset();h.readLoginCalls = [];+ h.legacyMigrations = 0;});it('keeps the owner-scoped BYOK key readable when Cindy gateway access is disabled', async () => {@@ -159,6 +166,22 @@ describe('DesktopClaudeAuthAdapter — Claude 订阅只经 CLI 自己的登录',expect(env.HTTPS_PROXY).toBe('http://127.0.0.1:7890');});+ it('各来源都用 CLI 默认配置目录:不设 CLAUDE_CONFIG_DIR,拉起前先过旧 dev 目录补拷', async () => {+ h.gatewayKey = null;+ const adapter = await makeAdapter();+ const optionsList = [+ { credentialMode: 'oauth-bearer' as const },+ { credentialMode: 'gateway-key' as const },+ { credentialMode: 'provider-oauth' as const },+ undefined,+ ];+ for (const options of optionsList) {+ const env = await adapter.getAuthEnv(options);+ expect(env.CLAUDE_CONFIG_DIR).toBeUndefined();+ }+ expect(h.legacyMigrations).toBe(optionsList.length);+ });+it('订阅会话:未连接(CLI 未登录或 Cindy 未获许可)→ no_oauth', async () => {h.nativeLogin = false;const adapter = await makeAdapter();diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeLegacyConfigMigration.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeLegacyConfigMigration.test.tsnew file mode 100644index 0000000000..43ab8bc356--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/claudeLegacyConfigMigration.test.ts@@ -0,0 +1,293 @@+/**+ * claudeLegacyConfigMigration.test.ts —— 旧版 dev 隔离目录 claude-home 的一次性补拷。+ *+ * 契约:只补缺不覆盖、不删旧目录、保留 mtime、不跟随符号链接、不留临时文件;+ * 全部成功才写标记(之后不再扫描),有失败下次重试;正式版与非 dev 多实例不执行。+ */+import { promises as fs } from 'node:fs';+import type { Dirent } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ isPackaged: false,+ userDataDir: '',+ getPathError: null as Error | null,+ getPathCalls: 0,+}));++vi.mock('electron', () => ({+ app: {+ get isPackaged() {+ return h.isPackaged;+ },+ getPath: () => {+ h.getPathCalls += 1;+ if (h.getPathError) throw h.getPathError;+ return h.userDataDir;+ },+ },+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), debug: vi.fn(), error: vi.fn() }),+}));++import {+ ensureLegacyClaudeConfigMigrated,+ migrateLegacyClaudeConfigDir,+ resetLegacyClaudeConfigMigrationForTest,+} from '../claude-legacy-config-migration.js';++const MARKER = '.cindy-migrated-to-default-config';+const tempRoots: string[] = [];+const originalUserDataEnv = process.env.XDT_USER_DATA_DIR;++async function makeRoot(): Promise<string> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-claude-legacy-'));+ tempRoots.push(root);+ return root;+}++async function writeFileAt(file: string, content: string, mtime?: Date): Promise<void> {+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, content, 'utf-8');+ if (mtime) await fs.utimes(file, mtime, mtime);+}++async function listFiles(root: string): Promise<string[]> {+ const out: string[] = [];+ async function walk(dir: string): Promise<void> {+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) await walk(full);+ else out.push(path.relative(root, full));+ }+ }+ await walk(root).catch(() => undefined);+ return out.sort();+}++beforeEach(() => {+ h.isPackaged = false;+ h.userDataDir = '';+ h.getPathError = null;+ h.getPathCalls = 0;+ resetLegacyClaudeConfigMigrationForTest();+});++afterEach(async () => {+ vi.restoreAllMocks();+ if (originalUserDataEnv === undefined) delete process.env.XDT_USER_DATA_DIR;+ else process.env.XDT_USER_DATA_DIR = originalUserDataEnv;+ await Promise.all(tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));+});++describe('migrateLegacyClaudeConfigDir', () => {+ it('copies missing transcripts and file checkpoints, preserving mtime and the legacy dir', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'user-data', 'claude-home');+ const targetDir = path.join(root, 'home', '.claude');+ const mtime = new Date('2026-09-20T08:00:00Z');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy-1\n', mtime);+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1', 'subagents', 'agent-a.jsonl'), 'sub\n');+ await writeFileAt(path.join(legacyDir, 'file-history', 'sid-1', 'abc@v1'), 'checkpoint');+ await writeFileAt(path.join(legacyDir, 'settings.json'), '{}');++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 3, skipped: 0, failed: 0 });+ expect(await listFiles(targetDir)).toEqual([+ path.join('file-history', 'sid-1', 'abc@v1'),+ path.join('projects', '-work', 'sid-1', 'subagents', 'agent-a.jsonl'),+ path.join('projects', '-work', 'sid-1.jsonl'),+ ].sort());+ const copied = path.join(targetDir, 'projects', '-work', 'sid-1.jsonl');+ await expect(fs.readFile(copied, 'utf-8')).resolves.toBe('legacy-1\n');+ expect((await fs.stat(copied)).mtimeMs).toBe(mtime.getTime());+ // 旧目录原样保留(旧 checkout 仍可能用它),并写上完成标记。+ await expect(fs.readFile(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'utf-8'))+ .resolves.toBe('legacy-1\n');+ await expect(fs.stat(path.join(legacyDir, MARKER))).resolves.toBeTruthy();+ });++ it('never overwrites a file that already exists in the default dir', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy\n');+ await writeFileAt(path.join(targetDir, 'projects', '-work', 'sid-1.jsonl'), 'current\n');++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 0, skipped: 1, failed: 0 });+ await expect(fs.readFile(path.join(targetDir, 'projects', '-work', 'sid-1.jsonl'), 'utf-8'))+ .resolves.toBe('current\n');+ });++ it('runs once: a completed marker makes later calls a no-op', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'one\n');+ await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-2.jsonl'), 'two\n');++ await expect(migrateLegacyClaudeConfigDir({ legacyDir, targetDir })).resolves.toBeNull();+ expect(await listFiles(targetDir)).toEqual([path.join('projects', '-work', 'sid-1.jsonl')]);+ });++ it('does nothing and writes no marker when there is no legacy dir', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');++ await expect(migrateLegacyClaudeConfigDir({ legacyDir, targetDir })).resolves.toBeNull();+ await expect(fs.stat(legacyDir)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(fs.stat(targetDir)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('keeps going past a failed entry and leaves the marker unset so the next start retries', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ await writeFileAt(path.join(legacyDir, 'projects', 'blocked', 'sid-1.jsonl'), 'blocked\n');+ await writeFileAt(path.join(legacyDir, 'projects', 'ok', 'sid-2.jsonl'), 'ok\n');+ // 目标里同名位置是普通文件,旧目录里是目录:建子目录会失败。+ await writeFileAt(path.join(targetDir, 'projects', 'blocked'), 'not a dir');++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats?.failed).toBe(1);+ expect(stats?.copied).toBe(1);+ await expect(fs.readFile(path.join(targetDir, 'projects', 'ok', 'sid-2.jsonl'), 'utf-8'))+ .resolves.toBe('ok\n');+ await expect(fs.stat(path.join(legacyDir, MARKER))).rejects.toMatchObject({ code: 'ENOENT' });+ expect((await listFiles(targetDir)).some((file) => file.endsWith('.tmp'))).toBe(false);+ });++ it('falls back to an exclusive copy when hard links are unsupported', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy\n');+ vi.spyOn(fs, 'link').mockRejectedValue(Object.assign(new Error('nope'), { code: 'EPERM' }));++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 1, skipped: 0, failed: 0 });+ await expect(fs.readFile(path.join(targetDir, 'projects', '-work', 'sid-1.jsonl'), 'utf-8'))+ .resolves.toBe('legacy\n');+ expect(await listFiles(targetDir)).toEqual([path.join('projects', '-work', 'sid-1.jsonl')]);+ });++ it('the exclusive-copy fallback still never overwrites a file created meanwhile', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ const target = path.join(targetDir, 'projects', '-work', 'sid-1.jsonl');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy\n');+ // 硬链接失败的同时,目标被并发写入(CLI resume / 分享导入)。+ vi.spyOn(fs, 'link').mockImplementation(async () => {+ await fs.writeFile(target, 'current\n', 'utf-8');+ throw Object.assign(new Error('nope'), { code: 'EPERM' });+ });++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 0, skipped: 1, failed: 0 });+ await expect(fs.readFile(target, 'utf-8')).resolves.toBe('current\n');+ });++ it('does not let a failed temp-file cleanup undo a successful copy', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy\n');+ vi.spyOn(fs, 'rm').mockRejectedValue(Object.assign(new Error('busy'), { code: 'EPERM' }));++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 1, skipped: 0, failed: 0 });+ await expect(fs.stat(path.join(legacyDir, MARKER))).resolves.toBeTruthy();+ });++ it.skipIf(process.platform === 'win32')('does not follow symlinks out of the legacy dir', async () => {+ const root = await makeRoot();+ const legacyDir = path.join(root, 'claude-home');+ const targetDir = path.join(root, '.claude');+ const outside = path.join(root, 'outside.jsonl');+ await writeFileAt(outside, 'outside\n');+ await fs.mkdir(path.join(legacyDir, 'projects', '-work'), { recursive: true });+ await fs.symlink(outside, path.join(legacyDir, 'projects', '-work', 'linked.jsonl'));++ const stats = await migrateLegacyClaudeConfigDir({ legacyDir, targetDir });++ expect(stats).toEqual({ copied: 0, skipped: 0, failed: 0 });+ expect(await listFiles(targetDir)).toEqual([]);+ });+});++describe('ensureLegacyClaudeConfigMigrated', () => {+ async function seedDevInstance(): Promise<{ legacyDir: string; home: string }> {+ const root = await makeRoot();+ h.userDataDir = path.join(root, 'user-data');+ const home = path.join(root, 'home');+ vi.spyOn(os, 'homedir').mockReturnValue(home);+ const legacyDir = path.join(h.userDataDir, 'claude-home');+ await writeFileAt(path.join(legacyDir, 'projects', '-work', 'sid-1.jsonl'), 'legacy\n');+ return { legacyDir, home };+ }++ it('migrates a dev multi-instance legacy dir into ~/.claude before the CLI starts', async () => {+ const { home } = await seedDevInstance();+ process.env.XDT_USER_DATA_DIR = h.userDataDir;++ await ensureLegacyClaudeConfigMigrated();++ await expect(fs.readFile(path.join(home, '.claude', 'projects', '-work', 'sid-1.jsonl'), 'utf-8'))+ .resolves.toBe('legacy\n');+ });++ it('waits only once: after the first timeout later calls return immediately', async () => {+ await seedDevInstance();+ process.env.XDT_USER_DATA_DIR = h.userDataDir;+ // 补拷卡在目录遍历上,模拟超大旧目录。+ vi.spyOn(fs, 'readdir').mockImplementation(() => new Promise<Dirent[]>(() => undefined) as never);++ await ensureLegacyClaudeConfigMigrated(5);+ const started = Date.now();+ await ensureLegacyClaudeConfigMigrated(10_000);+ expect(Date.now() - started).toBeLessThan(1_000);+ });++ it('never throws when the userData path is unavailable, and does not retry in the same run', async () => {+ process.env.XDT_USER_DATA_DIR = '/tmp/cindy-dev-instance';+ h.getPathError = new Error('userData not ready');++ await expect(ensureLegacyClaudeConfigMigrated()).resolves.toBeUndefined();+ await expect(ensureLegacyClaudeConfigMigrated()).resolves.toBeUndefined();+ expect(h.getPathCalls).toBe(1);+ });++ it('is a no-op in packaged builds', async () => {+ const { home } = await seedDevInstance();+ process.env.XDT_USER_DATA_DIR = h.userDataDir;+ h.isPackaged = true;++ await ensureLegacyClaudeConfigMigrated();++ await expect(fs.stat(path.join(home, '.claude'))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('is a no-op without XDT_USER_DATA_DIR', async () => {+ const { home } = await seedDevInstance();+ delete process.env.XDT_USER_DATA_DIR;++ await ensureLegacyClaudeConfigMigrated();++ await expect(fs.stat(path.join(home, '.claude'))).rejects.toMatchObject({ code: 'ENOENT' });+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.tsindex b5a0781cad..8ca290f2f2 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeNativeCli.test.ts@@ -176,6 +176,17 @@ describe('登录态读取', () => {expect(argsOf(h.spawn.mock.calls[1])).toEqual(['auth', 'status', '--json']);});+ it('内置 CLI 尚未就绪不算失败:不进退避,就绪后下一次读取立即拉起', async () => {+ h.binary = null;+ await expect(refreshClaudeCliLoginStatus()).resolves.toEqual({ loggedIn: false });+ expect(h.spawn).not.toHaveBeenCalled();+ // 启动期二进制准备完成后的补读:不能被上一次「未就绪」挡在 30s 退避里。+ h.binary = '/opt/cindy/claude';+ h.spawn.mockImplementation(() => fakeChild({ stdout: SUBSCRIPTION }));+ await expect(readClaudeCliLoginStatus()).resolves.toMatchObject({ loggedIn: true });+ expect(h.spawn).toHaveBeenCalledTimes(1);+ });+it('staleWhileRevalidate:没有缓存时不等 CLI,后台读完再更新缓存', async () => {let release!: () => void;const gate = new Promise<void>((resolve) => { release = resolve; });diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.tsindex abc637ac7d..769c16a322 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts@@ -11,6 +11,9 @@* 进程继续追加旧目录 jsonl 的分叉);'<pending>' 占位 id 不持久化不入集合但* 仍关 handle;空集 no-op、maker-core 抛错被吞并(移动主流程不受影响)。*/+import os from 'node:os';+import path from 'node:path';+import { beforeEach, describe, expect, it, vi } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';@@ -135,7 +138,7 @@ describe('relocateClaudeTranscriptsForSessionMove', () => {expect(out).toEqual({ persistedSdkSessionId: LIVE_ID });});- it('resolves projectsRoot from XDT_USER_DATA_DIR/claude-home in dev multi-instance runs', async () => {+ it('uses the CLI default ~/.claude projects root in dev multi-instance runs too', async () => {const prevUserData = process.env.XDT_USER_DATA_DIR;const prevConfigDir = process.env.CLAUDE_CONFIG_DIR;process.env.XDT_USER_DATA_DIR = '/tmp/xdt-instance-b';@@ -146,12 +149,10 @@ describe('relocateClaudeTranscriptsForSessionMove', () => {await relocateClaudeTranscriptsForSessionMove('s1', '/old/dir', '/new/dir');- // CLI 子进程被 auth-adapters 重定向到 <userData>/claude-home,迁移必须用同一根,- // 否则回退 ~/.claude 找不到源、也写不进 CLI 实际读取的目录。+ // dev 与正式版一样不再给 CLI 设 CLAUDE_CONFIG_DIR,迁移必须写进 CLI 实际读取的+ // 默认目录;旧版隔离目录 <userData>/claude-home 只作只读兜底。const args = h.relocate.mock.calls[0][0];- expect(args.projectsRoot?.split(/[\\/]/).slice(-3).join('/')).toBe(- 'xdt-instance-b/claude-home/projects',- );+ expect(args.projectsRoot).toBe(path.join(os.homedir(), '.claude', 'projects'));} finally {if (prevUserData === undefined) delete process.env.XDT_USER_DATA_DIR;else process.env.XDT_USER_DATA_DIR = prevUserData;diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 06df66b5b4..0a1640d06a 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -86,7 +86,8 @@ import {import { CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY, isAnthropicWireModel } from './claude-gateway-config.js';import { hasClaudeNativeLogin } from './claude-native-auth.js';import { disconnectClaudeNativeLogin, readClaudeNativeLogin } from './claude-native-connection.js';-import { claudeCliConfigDirOverride, claudeCliNetworkEnv } from './claude-native-cli.js';+import { claudeCliNetworkEnv } from './claude-native-cli.js';+import { ensureLegacyClaudeConfigMigrated } from './claude-legacy-config-migration.js';import { isAnthropicCompatProxyHandleReady } from './anthropic-compat-proxy-host.js';import { claudeUpstreamEndpoint } from './runtime-configs.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';@@ -748,14 +749,10 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {else env.ANTHROPIC_API_KEY = CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY;}}- // dev 多实例隔离:设了 XDT_USER_DATA_DIR(device-link 本地联调跑多实例)时,把- // Claude Code 的配置目录也切到 userData 下。否则多实例共用全局 ~/.claude- // (~/.claude.json / projects 下的 transcripts)会互相干扰,无法当作两台独立设备。- // 仅 dev(非 packaged)生效,生产忽略;auth 走 ANTHROPIC_API_KEY,重定向 config- // dir 不影响鉴权。process.env 路线行不通(CLAUDE_CONFIG_DIR 在 boot 期被- // stripSensitiveAnthropicEnv 清掉),故经 getAuthEnv 注入子进程 env(覆盖优先)。- const configDir = claudeCliConfigDirOverride();- if (configDir) env.CLAUDE_CONFIG_DIR = configDir;+ // 所有来源都用 CLI 默认配置目录(dev 多实例与正式版一致,不设 CLAUDE_CONFIG_DIR):+ // 订阅会话的凭证库按配置目录区分,隔离会看不到本机已有的 Claude Code 登录。+ // 旧版 dev 隔离在 <userData>/claude-home 的转录,拉起 CLI 前补拷到默认目录供 resume。+ await ensureLegacyClaudeConfigMigrated();return env;}diff --git a/apps/desktop/src/main/maker-host/claude-legacy-config-migration.ts b/apps/desktop/src/main/maker-host/claude-legacy-config-migration.tsnew file mode 100644index 0000000000..944cff12ea--- /dev/null+++ b/apps/desktop/src/main/maker-host/claude-legacy-config-migration.ts@@ -0,0 +1,219 @@+/**+ * claude-legacy-config-migration —— dev 多实例旧 Claude 配置目录的一次性补拷。+ *+ * 旧版 dev(设了 XDT_USER_DATA_DIR 的非 packaged 实例)把 Claude Code 的配置目录隔离在+ * `<userData>/claude-home`。Claude 订阅改由 CLI 自己登录后,凭证库按配置目录区分,+ * 隔离会让 dev 看不到本机已有的 Claude Code 登录;现在 dev 与正式版一样用默认 ~/.claude。+ *+ * 为了让旧 dev 任务还能 resume,把旧目录里按 sdk session id 存放的转录(projects)与+ * 文件检查点(file-history)补拷到默认目录:+ * - 只补缺,不覆盖已有文件;不删旧目录(旧 checkout 仍可能用它);+ * - 先写同目录临时文件再 hard link 到目标,中断不会留下半截 jsonl,也不会覆盖并发+ * 新建的同名文件;保留 mtime(转录归位按 mtime 比较新旧);+ * - 全部成功后写标记,之后不再扫描;有失败则下次启动重试。标记之后旧 checkout 再写进+ * 旧目录的转录不会补拷(过渡期限制,见 docs/dev-rules/desktop-development.md)。+ * 正式版恒不执行(从未使用 claude-home 存转录)。+ */++import { randomUUID } from 'node:crypto';+import fs, { promises as fsp } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { app } from 'electron';++import { createLogger } from '../logger.js';++const log = createLogger('claude-legacy-config-migration');++const LEGACY_DIR_NAME = 'claude-home';+const MIGRATED_SUBDIRS = ['projects', 'file-history'] as const;+const MARKER_FILE = '.cindy-migrated-to-default-config';+/** 拉起 CLI 前最多等这么久;超时不阻断会话,补拷继续在后台跑。 */+const SPAWN_WAIT_MS = 15_000;++interface CopyStats {+ copied: number;+ skipped: number;+ failed: number;+}++export interface LegacyClaudeConfigMigrationPaths {+ legacyDir: string;+ targetDir: string;+}++/**+ * 硬链接不可用时(部分文件系统 / Windows 权限)退回 COPYFILE_EXCL 直拷:仍绝不覆盖已有文件,+ * 代价是进程中途被杀可能留下半截目标文件(仅此兜底路径)。+ */+const LINK_UNSUPPORTED_CODES = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']);++let migration: Promise<void> | null = null;+let migrationSettled = false;+/** 首次等待已超时:之后的调用不再等,补拷在后台继续。 */+let spawnWaitExpired = false;++function legacyMigrationPaths(): LegacyClaudeConfigMigrationPaths | null {+ if (!process.env.XDT_USER_DATA_DIR || app.isPackaged) return null;+ return {+ legacyDir: path.join(app.getPath('userData'), LEGACY_DIR_NAME),+ targetDir: path.join(os.homedir(), '.claude'),+ };+}++function errorCode(err: unknown): string | undefined {+ return (err as NodeJS.ErrnoException | undefined)?.code;+}++async function pathExists(target: string): Promise<boolean> {+ try {+ await fsp.lstat(target);+ return true;+ } catch (err) {+ if (errorCode(err) === 'ENOENT') return false;+ throw err;+ }+}++async function copyFileIfMissing(from: string, to: string, stats: CopyStats): Promise<void> {+ if (await pathExists(to)) {+ stats.skipped += 1;+ return;+ }+ await fsp.mkdir(path.dirname(to), { recursive: true });+ // 临时名不以 .jsonl 结尾,残留也不会被 CLI 或转录扫描当成会话。+ const temp = `${to}.cindy-migrate-${process.pid}-${randomUUID()}.tmp`;+ try {+ await fsp.copyFile(from, temp, fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE);+ const source = await fsp.stat(from);+ await fsp.utimes(temp, source.atime, source.mtime);+ try {+ await fsp.link(temp, to);+ } catch (err) {+ if (!LINK_UNSUPPORTED_CODES.has(errorCode(err) ?? '')) throw err;+ await fsp.copyFile(temp, to, fs.constants.COPYFILE_EXCL);+ await fsp.utimes(to, source.atime, source.mtime);+ }+ stats.copied += 1;+ } catch (err) {+ if (errorCode(err) === 'EEXIST') {+ stats.skipped += 1;+ return;+ }+ throw err;+ } finally {+ // 清理失败(如杀软占用)不能盖掉已经成功的落位;残留临时名不会被当成会话。+ await fsp.rm(temp, { force: true }).catch(() => undefined);+ }+}++async function copyTreeIfMissing(from: string, to: string, stats: CopyStats): Promise<void> {+ let entries: fs.Dirent[];+ try {+ entries = await fsp.readdir(from, { withFileTypes: true });+ } catch (err) {+ if (errorCode(err) === 'ENOENT') return;+ throw err;+ }+ for (const entry of entries) {+ const source = path.join(from, entry.name);+ const target = path.join(to, entry.name);+ try {+ if (entry.isDirectory()) await copyTreeIfMissing(source, target, stats);+ // 只搬普通文件;符号链接等不跟随,避免把旧目录之外的内容带进来。+ else if (entry.isFile()) await copyFileIfMissing(source, target, stats);+ } catch (err) {+ stats.failed += 1;+ log.debug('legacy claude file copy failed', { code: errorCode(err) });+ }+ }+}++/** 导出供测试直接驱动;生产经 {@link ensureLegacyClaudeConfigMigrated}。 */+export async function migrateLegacyClaudeConfigDir(+ paths: LegacyClaudeConfigMigrationPaths,+): Promise<CopyStats | null> {+ const markerPath = path.join(paths.legacyDir, MARKER_FILE);+ if (await pathExists(markerPath)) return null;+ if (!(await pathExists(paths.legacyDir))) return null;+ const stats: CopyStats = { copied: 0, skipped: 0, failed: 0 };+ for (const subdir of MIGRATED_SUBDIRS) {+ await copyTreeIfMissing(+ path.join(paths.legacyDir, subdir),+ path.join(paths.targetDir, subdir),+ stats,+ );+ }+ if (stats.failed === 0) {+ await fsp.writeFile(+ markerPath,+ `${JSON.stringify({ migratedAt: new Date().toISOString() })}\n`,+ 'utf-8',+ );+ }+ return stats;+}++function startMigration(): Promise<void> | null {+ if (migration) return migration;+ let paths: LegacyClaudeConfigMigrationPaths | null;+ try {+ paths = legacyMigrationPaths();+ } catch (err) {+ log.warn('legacy dev claude config paths unavailable', {+ message: err instanceof Error ? err.message : String(err),+ });+ // 记住失败,本次运行不再重试(否则每次拉起 CLI 都重复告警)。+ migration = Promise.resolve();+ migrationSettled = true;+ return migration;+ }+ if (!paths) return null;+ migration = migrateLegacyClaudeConfigDir(paths)+ .then(+ (stats) => {+ if (stats) log.info('migrated legacy dev claude config dir', { ...stats });+ },+ (err: unknown) => {+ log.warn('legacy dev claude config migration failed', {+ message: err instanceof Error ? err.message : String(err),+ });+ },+ )+ .finally(() => {+ migrationSettled = true;+ });+ return migration;+}++/** 启动期后台触发(不等待),让会话移动 / fork 等在首次拉起 CLI 前也能读到补拷结果。 */+export function startLegacyClaudeConfigMigration(): void {+ void startMigration();+}++/**+ * 拉起 Claude CLI 前调用:补拷未完成时最多等待 {@link SPAWN_WAIT_MS}(只等一次,超时后+ * 后续调用不再等,补拷在后台继续)。best-effort,失败只记日志、从不抛出;非 dev 多实例+ * 直接返回。+ */+export async function ensureLegacyClaudeConfigMigrated(waitMs = SPAWN_WAIT_MS): Promise<void> {+ const pending = startMigration();+ if (!pending || migrationSettled || spawnWaitExpired) return;+ let timer: NodeJS.Timeout | undefined;+ const finished = await Promise.race([+ pending.then(() => true),+ new Promise<boolean>((resolve) => {+ timer = setTimeout(() => resolve(false), waitMs);+ timer.unref?.();+ }),+ ]);+ if (timer) clearTimeout(timer);+ if (!finished) spawnWaitExpired = true;+}++export function resetLegacyClaudeConfigMigrationForTest(): void {+ migration = null;+ migrationSettled = false;+ spawnWaitExpired = false;+}diff --git a/apps/desktop/src/main/maker-host/claude-native-cli.ts b/apps/desktop/src/main/maker-host/claude-native-cli.tsindex f74f9299a1..92368b6690 100644--- a/apps/desktop/src/main/maker-host/claude-native-cli.ts+++ b/apps/desktop/src/main/maker-host/claude-native-cli.ts@@ -15,9 +15,7 @@*/import { spawn, type ChildProcess } from 'node:child_process';-import path from 'node:path';-import { app } from 'electron';import { cleanProcessEnv } from '@cindy/maker-core';import { hasProxyEnvConfig, parseOutboundProxyUrl } from '@cindy/anthropic-compat-proxy';@@ -51,18 +49,6 @@ const STATUS_FAILURE_BACKOFF_MS = 30_000;const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;const ANTHROPIC_API_ORIGIN = 'https://api.anthropic.com';-/**- * dev 多实例(XDT_USER_DATA_DIR)把 Claude Code 的配置目录切到 userData 下,- * 否则多实例共用 ~/.claude 互相干扰。生产恒为 undefined(用 CLI 默认目录)。- * process.env 的 CLAUDE_CONFIG_DIR 在 boot 期已被剥离,只能经子进程 env 注入。- */-export function claudeCliConfigDirOverride(): string | undefined {- if (process.env.XDT_USER_DATA_DIR && !app.isPackaged && !process.env.CLAUDE_CONFIG_DIR) {- return path.join(app.getPath('userData'), 'claude-home');- }- return undefined;-}-const LOOPBACK_NO_PROXY = 'localhost,127.0.0.1,::1';/**@@ -106,12 +92,14 @@ function cliBinaryPath(): string | null {return getReadyBinaryPath('claude-code') ?? null;}+/**+ * 登录与登录态检查用 CLI 默认配置目录(dev 多实例也一样),凭证库因此与终端里的+ * `claude`、订阅会话共用同一份。process.env 的 CLAUDE_CONFIG_DIR 在 boot 期已被剥离。+ */async function cliEnv(options: { network: boolean }): Promise<NodeJS.ProcessEnv> {- const configDir = claudeCliConfigDirOverride();return {...cleanProcessEnv(),...(options.network ? await claudeCliNetworkEnv() : {}),- ...(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}),};}@@ -207,11 +195,13 @@ function statusFallback(): ClaudeCliLoginStatus {/*** 读 CLI 登录态(`claude auth status --json`,约 0.1–0.3s)。同一时刻只跑一个;- * 读失败(CLI 未就绪 / 超时 / 输出异常)时保留上一次结果,从未读到过则视为未登录,+ * 读失败(超时 / 输出异常 / 拉起失败)时保留上一次结果,从未读到过则视为未登录,* 并在 STATUS_FAILURE_BACKOFF_MS 内不再重试(force 除外,如用户主动登录)。+ * 内置 CLI 尚未就绪(启动期二进制还在准备)不算失败、不进退避:就绪后启动流程会再读一次。*/export function refreshClaudeCliLoginStatus(options?: { force?: boolean }): Promise<ClaudeCliLoginStatus> {if (statusInflight) return statusInflight;+ if (!cliBinaryPath()) return Promise.resolve(statusFallback());if (options?.force !== true &&lastStatusFailureAt !== null &&diff --git a/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts b/apps/desktop/src/main/maker-host/claude-transcript-relocation.tsindex 45076cc312..9aa078391a 100644--- a/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts+++ b/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts@@ -183,9 +183,10 @@ export async function relocateClaudeTranscriptsForSessionMove(log.debug('transcript relocation skipped: no sdk session ids', { sessionId });return { persistedSdkSessionId };}- // projectsRoot 必须与 CLI 子进程实际使用的配置目录一致:dev 多实例下- // auth-adapters 把 CLI 的 CLAUDE_CONFIG_DIR 重定向到 XDT_USER_DATA_DIR/claude-home,- // 主进程 env 里却没有该变量(boot 期被 strip),不能让 maker-core 回退 ~/.claude。+ // projectsRoot 必须与 CLI 子进程实际使用的配置目录一致(候选首项:显式+ // CLAUDE_CONFIG_DIR,否则默认 ~/.claude;dev 多实例也一样)。旧版 dev 隔离目录里+ // 尚未补拷的转录不在这里搬:下次拉起 CLI 前先补拷到默认目录,再由 resume 前的+ // 转录归位全局扫描放进新 cwd。const result = await relocateClaudeSessionTranscripts({sdkSessionIds,oldWorkingDir,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 59313589dc..fc1db14608 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12557,11 +12557,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)? await maker.listAgentRuntimeSkills(session.agentKind, {workingDir: session.workDir,sessionId: session.id,- runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || (- process.env.XDT_USER_DATA_DIR && !app.isPackaged- ? path.join(app.getPath('userData'), 'claude-home')- : path.join(os.homedir(), '.claude')- ),+ runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || path.join(os.homedir(), '.claude'),}): await maker.listAgentSkills(session.agentKind, {workingDir: session.workDir,diff --git a/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts b/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.tsindex 395fbb3ef5..64dce100b8 100644--- a/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts+++ b/apps/desktop/src/main/maker-orchestration/__tests__/claudeTranscriptAnchors.test.ts@@ -1,8 +1,9 @@import { mkdtemp, mkdir, rm, writeFile, unlink, realpath } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {+ defaultClaudeConfigDirCandidates,findClaudeSessionJsonl,__resetClaudeTranscriptPathCacheForTesting,} from '../claudeTranscriptAnchors';@@ -92,3 +93,38 @@ describe('Claude transcript path lookup cache', () => {await expect(findClaudeSessionJsonl('s0', undefined, root, () => now)).resolves.toBe(first);});});++describe('defaultClaudeConfigDirCandidates', () => {+ const originalConfigDir = process.env.CLAUDE_CONFIG_DIR;+ const originalUserDataDir = process.env.XDT_USER_DATA_DIR;++ afterEach(() => {+ vi.restoreAllMocks();+ if (originalConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;+ else process.env.CLAUDE_CONFIG_DIR = originalConfigDir;+ if (originalUserDataDir === undefined) delete process.env.XDT_USER_DATA_DIR;+ else process.env.XDT_USER_DATA_DIR = originalUserDataDir;+ });++ it('puts the CLI default dir first and keeps the legacy dev dir only as a read fallback', () => {+ vi.spyOn(os, 'homedir').mockReturnValue('/home/tester');+ delete process.env.CLAUDE_CONFIG_DIR;+ process.env.XDT_USER_DATA_DIR = '/data/dev-instance';++ expect(defaultClaudeConfigDirCandidates()).toEqual([+ path.join('/home/tester', '.claude'),+ path.join('/data/dev-instance', 'claude-home'),+ ]);+ });++ it('honors an explicit CLAUDE_CONFIG_DIR ahead of the default dir', () => {+ vi.spyOn(os, 'homedir').mockReturnValue('/home/tester');+ process.env.CLAUDE_CONFIG_DIR = '/custom/claude';+ delete process.env.XDT_USER_DATA_DIR;++ expect(defaultClaudeConfigDirCandidates()).toEqual([+ '/custom/claude',+ path.join('/home/tester', '.claude'),+ ]);+ });+});diff --git a/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts b/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.tsindex af62f4600e..ef9a63fc42 100644--- a/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts+++ b/apps/desktop/src/main/maker-orchestration/claudeTranscriptAnchors.ts@@ -149,18 +149,19 @@ function uniqueTruthy(values: Array<string | undefined>): string[] {}/**- * Claude CLI 配置目录候选(优先级序):显式 CLAUDE_CONFIG_DIR → dev 多实例的- * XDT_USER_DATA_DIR/claude-home(auth-adapters 给 CLI 子进程注入的同款重定向)- * → 默认 ~/.claude。desktop 侧读写 CLI 转录的模块应经此解析,不要各自硬编码- * ~/.claude(多实例下会找错根目录)。+ * Claude CLI 配置目录候选(优先级序):显式 CLAUDE_CONFIG_DIR → 默认 ~/.claude(CLI+ * 实际使用的目录)→ 旧版 dev 多实例的 XDT_USER_DATA_DIR/claude-home(只读兜底:+ * dev 曾把 CLI 配置目录隔离到这里,现已与正式版一样用默认目录,旧转录由+ * claude-legacy-config-migration 补拷过去)。首项即 CLI 当前的写入根;desktop 侧读写+ * CLI 转录的模块应经此解析,不要各自硬编码 ~/.claude。*/export function defaultClaudeConfigDirCandidates(): string[] {return uniqueTruthy([process.env.CLAUDE_CONFIG_DIR,+ path.join(os.homedir(), '.claude'),process.env.XDT_USER_DATA_DIR? path.join(process.env.XDT_USER_DATA_DIR, 'claude-home'): undefined,- path.join(os.homedir(), '.claude'),]);}diff --git a/apps/desktop/src/main/session-share/sessionShareExport.ts b/apps/desktop/src/main/session-share/sessionShareExport.tsindex 45be12a659..1bc7f0b816 100644--- a/apps/desktop/src/main/session-share/sessionShareExport.ts+++ b/apps/desktop/src/main/session-share/sessionShareExport.ts@@ -264,7 +264,7 @@ async function collectSessionPhaseA(sdkSessionIds = sdkSessionIds.filter((id) => allowed.has(id));}// 与 loadClaudeTranscriptAnchorIndex 同口径:遍历全部候选目录- // (CLAUDE_CONFIG_DIR → XDT_USER_DATA_DIR/claude-home → ~/.claude),+ // (CLAUDE_CONFIG_DIR → ~/.claude → 旧版 dev 的 XDT_USER_DATA_DIR/claude-home),// 只查第一个会把落在后续候选的 jsonl 误记缺失(review bot P1)。const projectsRoots = defaultClaudeConfigDirCandidates().map((dir) =>path.join(dir, 'projects'),diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 28c8d5b06b..f4e60f55e9 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -48,8 +48,10 @@ Anthropic 只允许用户用自己的订阅登录**未修改的 Claude Code**;Claude.ai 登录,也不得收集、存储或中转订阅凭证。Cindy 因此只做内置 CLI 的外壳:- 登录只拉起内置 CLI 的 `claude auth login --claudeai`,登录态只读- `claude auth status --json`。凭证留在 CLI 默认凭证库(macOS 钥匙串 / `~/.claude`,- dev 多实例为 userData 下的 `claude-home`),Cindy 不读取、不复制、不刷新它。+ `claude auth status --json`。凭证留在 CLI 默认凭证库(macOS 钥匙串 / `~/.claude`),+ Cindy 不读取、不复制、不刷新它。CLI 按配置目录区分凭证库,所以本机 CLI 的会话(任何来源)+ 与登录检查都不得设 `CLAUDE_CONFIG_DIR`(dev 多实例也用默认目录),否则会看不到本机已有的+ Claude Code 登录;SSH 远端的配置目录由远端 cc-manager 自己管理,不在此列。只有 Claude.ai 订阅账号的 OAuth 登录算「Claude 订阅」;CLI 用 Console 账号、API Key、apiKeyHelper、中转 token 或第三方云登录时按 `not_a_subscription` 处理,也不替用户改 CLI 的登录。- 登录态读取不得阻塞与订阅无关的路径:启动只在已连接时等待,列表类读取用缓存并后台刷新,diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.mdindex 428e170a43..10b225987f 100644--- a/docs/dev-rules/desktop-development.md+++ b/docs/dev-rules/desktop-development.md@@ -11,7 +11,14 @@ Agent 启动 Desktop 只使用仓库根的安全包装命令,并显式选择命令默认使用固定的 `dev` 命名隔离沙箱(等价于自动附加 `--isolated=dev`),不再默认共享 Cindy 账号登录态与业务数据。OpenAI 模型登录态是刻意保留的例外:普通 Dev 可只读复用同区域 Release/本机 Codex 已有登录态,能够调用模型,但不能在-Dev 内发起 OpenAI 登录或断开共享登录态:+Dev 内发起 OpenAI 登录或断开共享登录态。Claude Code 的配置目录同样不隔离:Dev 与正式版+一样使用 CLI 默认的 `~/.claude`(不设 `CLAUDE_CONFIG_DIR`),所以直接沿用本机 Claude Code+的订阅登录;在 Dev 里「使用 Claude Code 登录」等同于在终端运行 `claude auth login`,「断开」+只撤销本实例的使用许可。代价是多个 Dev 实例与安装版在同机共用 `~/.claude` 下的 Claude 转录+(按 sdk session id 区分;同机导入分享包时同 id 转录会复用同一份)。旧版 Dev 隔离在+`<userData>/claude-home` 的转录与文件检查点,会在启动时后台一次性补拷到默认目录(只补缺、+不覆盖、不删旧目录;拉起 Claude CLI 前最多等一次 15s);补拷完成后,旧 checkout 再写进旧目录的+转录不会再补拷:```bashpnpm restart:desktop:remote --region=global@@ -64,7 +71,7 @@ checkout 占用而中止,不要换命令绕过,应把 verdict 交给用户时使用;禁止与 `--isolated` 或环境里的 `XDT_ISOLATED=1` 组合。- `--isolated` / `--isolated=<名字>` / `--isolated=@worktree`:使用独立 userData 沙箱,数据库、Cindy 账号登录态、会话、定时任务与设备身份都与正式版彻底隔离(首次需重新登录 Cindy 账号);OpenAI 模型登录态按- 上述只读例外复用。命名沙箱每个名字一条独立沙箱,+ 上述只读例外复用,Claude Code 按上述约定使用默认 `~/.claude`。命名沙箱每个名字一条独立沙箱,名字限 `A-Za-z0-9_-`、≤32 字符。`@worktree` 是保留名,按当前 checkout 目录派生沙箱名。用户说「独立数据库/隔离数据/沙箱启动/不要动正式版数据」时用;Agent 把「启动开发版」也落在这条路径。**未合入主干的 migration 必须在 `--isolated` 沙箱里跑,不得连共享 userData**diff --git a/packages/maker-core/src/agents/claude-code/env-builder.ts b/packages/maker-core/src/agents/claude-code/env-builder.tsindex 06e98ae108..b5200cb1d5 100644--- a/packages/maker-core/src/agents/claude-code/env-builder.ts+++ b/packages/maker-core/src/agents/claude-code/env-builder.ts@@ -181,7 +181,7 @@ export const SENSITIVE_ANTHROPIC_ENV_KEYS = [* claude-code/index.ts startSession 远端分支)。** 刻意不复用 SENSITIVE_ANTHROPIC_ENV_KEYS:那是「继承残留清洗」超集,含 route 覆盖时- * 必须保留的字段(如 dev 多实例的 CLAUDE_CONFIG_DIR)。+ * 必须保留的字段(如 CLAUDE_CONFIG_DIR:远端由 cc-manager 自己决定)。*/export const REMOTE_ROUTE_OVERRIDE_ENV_KEYS = ['ANTHROPIC_API_KEY',@@ -489,8 +489,8 @@ export async function buildClaudeEnv(: undefined;const authEnv = { ...(await auth.getAuthEnv(authOptions)) };if (mode === 'remote') {- // CLAUDE_CONFIG_DIR is a host-local path. Desktop dev sandboxes inject a- // Windows/macOS userData path through the auth adapter; forwarding that+ // CLAUDE_CONFIG_DIR is a host-local path. If an auth adapter injects one+ // (older Desktop dev sandboxes used a userData path), forwarding that// literal path to a different POSIX host makes Claude resolve it relative// to the remote cwd and write configuration data into the repository.// The remote cc-manager owns this path and replaces it with its isolateddiff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex aff46650cf..d38e540c3e 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -1358,10 +1358,10 @@ export class ClaudeCodeAgent extends BaseAgent {// agent 的 `model:`。这里先扫一遍用户手写定义再决定:没人声明 model → 照旧设 env// (内置 agent 也吃到默认值);有人声明 → 不设 env,让那些声明生效。//- // 必须放在 buildClaudeEnv **之后**:dev 多实例把 cc 的配置目录重定向到- // `<userData>/claude-home`,而那个 CLAUDE_CONFIG_DIR 只存在于**子进程 env**里- // (boot 期已从 process.env 剥离)。拿 process.env 去扫会扫到 `~/.claude/agents`,- // 和 cc 实际读的目录不是同一个 → 判定失真,声明照旧被覆盖。+ // 必须放在 buildClaudeEnv **之后**:host 若经 auth adapter 重定向 cc 的配置目录+ // (旧版 dev 多实例曾用 `<userData>/claude-home`),那个 CLAUDE_CONFIG_DIR 只存在于+ // **子进程 env**里(boot 期已从 process.env 剥离)。拿 process.env 去扫会扫到+ // `~/.claude/agents`,和 cc 实际读的目录不是同一个 → 判定失真,声明照旧被覆盖。//// 只在会话启动时解析一次 —— env 要在 spawn 前定好,会话中途变动 tools/system 会破坏// prompt 缓存(见 docs/dev-rules/maker-core-and-agent-behavior.md §3.1)。diff --git a/packages/maker-core/src/agents/claude-code/subagent-definitions.ts b/packages/maker-core/src/agents/claude-code/subagent-definitions.tsindex 2c90472709..c7778b6712 100644--- a/packages/maker-core/src/agents/claude-code/subagent-definitions.ts+++ b/packages/maker-core/src/agents/claude-code/subagent-definitions.ts@@ -27,9 +27,9 @@* 的 `name`,与路径无关。** **必须传子进程 env**:`CLAUDE_CONFIG_DIR` 在 host boot 期就被 stripSensitiveAnthropicEnv- * 从 `process.env` 清掉了,dev 多实例隔离是由 auth adapter 只往**子进程 env** 注入的- * (apps/desktop/src/main/maker-host/auth-adapters.ts)。所以调用方要把最终交给 SDK 的那份- * env 传进来,否则这里扫的是 `~/.claude/agents`,而 cc 读的是 `<userData>/claude-home/agents`+ * 从 `process.env` 清掉了,host 要重定向配置目录只能由 auth adapter 往**子进程 env** 注入+ * (旧版 dev 多实例曾这样隔离到 `<userData>/claude-home`)。所以调用方要把最终交给 SDK 的+ * 那份 env 传进来,否则这里扫的是 `~/.claude/agents`,而 cc 读的是重定向后的 `agents`* ——判定与实际不符,声明照旧被覆盖。目录解析要同时看递入 env 与 host env,原因见* {@link userAgentsDir}(SDK spawn 是两份 env 合并)。*