Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 活 runtime 的 cwd 与 DB 漂移时按 DB 目录重建
Zhang Yunjin5cb4f35106dc
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex afb34f525d..7837a8595c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -56,6 +56,8 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {getSessionMeta: vi.fn(async () => ({ title: '现有会话' })),ensureRemoteReadyForSessionStart: vi.fn(async () => {}),checkWorkDirExists: vi.fn(async () => true),+ // 默认"DB 目录不可用":不命中移动漂移重建,既有用例保持原语义。+ statDirectory: vi.fn(async () => ({ isDirectory: () => false })),isOrcaMcpHydrated: vi.fn(() => true),buildCreateOptsWithStderr: vi.fn((opts: MakerSessionCreateOpts) => opts),synthesizeOrcaVendorOptionsFromDb: vi.fn(async () => false),@@ -1165,6 +1167,79 @@ describe('maker SEND transaction', () => {expect(session.send).not.toHaveBeenCalled();});+ it('rebuilds a live runtime in the persisted directory when the runtime cwd drifted', async () => {+ // 会话移动后旧 runtime 可能仍活着(cc 转录迁移 close 是 best-effort),且旧目录+ // 通常还在:DB 目录真实存在时必须关旧 runtime 并按 DB 目录重建,否则下一轮消息+ // 仍在旧 cwd 执行(2026-09-13 实报)。+ const movedSession = createSession({ workDir: '/data/old-project' });+ const rebuiltSession = createSession({ workDir: '/data/new-project' });+ const { deps } = createDeps({+ getSession: () => movedSession,+ readSessionWorkingDirFromDb: vi.fn(async () => '/data/new-project'),+ statDirectory: vi.fn(async () => ({ isDirectory: () => true })),+ bootstrapSession: vi.fn(async () => ({+ session: rebuiltSession,+ didInjectOrcaInstructions: false,+ didInjectProjectContext: false,+ })),+ });++ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'claude-code', workingDir: '/data/old-project',+ })).resolves.toMatchObject({ accepted: true });++ expect(deps.checkWorkDirExists).toHaveBeenNthCalledWith(+ 1, 'session-1', '/data/old-project', 'codex', null, { suppressMissingBroadcast: true },+ );+ expect(deps.statDirectory).toHaveBeenCalledWith('/data/new-project');+ expect(deps.closeSession).toHaveBeenCalledOnce();+ expect(deps.bootstrapSession).toHaveBeenCalledWith(+ expect.objectContaining({ workingDir: '/data/new-project' }),+ );+ expect(movedSession.send).not.toHaveBeenCalled();+ expect(rebuiltSession.send).toHaveBeenCalled();+ });++ it('keeps the live runtime when the persisted directory is not actually on disk', async () => {+ // 只有 DB 目录真实存在才迁移:不存在时不能走 recovery/mkdir 把不存在的项目+ // "恢复"成空文件夹,也不能丢掉活 runtime 的上下文。+ const movedSession = createSession({ workDir: '/data/old-project' });+ const { deps } = createDeps({+ getSession: () => movedSession,+ readSessionWorkingDirFromDb: vi.fn(async () => '/data/new-project'),+ statDirectory: vi.fn(async () => ({ isDirectory: () => false })),+ });++ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'claude-code', workingDir: '/data/old-project',+ })).resolves.toMatchObject({ accepted: true });++ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(movedSession.send).toHaveBeenCalled();+ });++ it('keeps the recovery fallback instead of switching a live runtime to the raw persisted path', async () => {+ // DB 目录已被 workingDirectoryRecovery 接管(resolve 返回 fallback):文件在+ // fallback 里,不能因为原路径"存在"就把 session 拉回去。+ const movedSession = createSession({ workDir: '/data/old-project' });+ const { deps } = createDeps({+ getSession: () => movedSession,+ readSessionWorkingDirFromDb: vi.fn(async () => '/mnt/disk/project'),+ resolveRecoveredWorkingDir: (_id, dir) =>+ (dir === '/mnt/disk/project' ? '/userData/fallback' : dir),+ statDirectory: vi.fn(async () => ({ isDirectory: () => true })),+ });++ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'codex', workingDir: '/data/old-project',+ })).resolves.toMatchObject({ accepted: true });++ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(movedSession.send).toHaveBeenCalled();+ });+it.each(['claude-code', 'pi'] as const)('refreshes a live %s process after same-path recovery and preserves its note', async (agentKind) => {const oldSession = createSession({ agentKind, hostStartupPreferences: {userPrompt: 'Keep the caller preference', makerMemoryEnabled: true,diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 605750b39d..0b69c19bfa 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -337,6 +337,12 @@ export interface MakerSendTransactionDeps {opts?: { suppressMissingBroadcast?: boolean },): Promise<boolean>;resolveRecoveredWorkingDir?(sessionId: string, workingDir: string): string;+ /**+ * 纯文件系统探测(不做 recovery / mkdir / 广播)。判断 DB 里的 working_dir 是否+ * **真实存在** —— 会话移动后 runtime cwd 与 DB 漂移时,只有确认 DB 目录真实存在+ * 才重建 runtime,不能把不存在的目录"恢复"成空文件夹。+ */+ statDirectory(dir: string): Promise<{ isDirectory(): boolean }>;/*** 读 DB 里既有会话的权威 working_dir(行不存在 → null)。lazy-create 把它当唯一* 真源直接采纳;rehydrate 只在 caller 传入的 workingDir 校验失败时用它兜底——@@ -705,6 +711,24 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makereturn true;}+ /**+ * 持久化 working_dir 是否真实可用:纯 stat,不做 recovery / mkdir / 广播。+ * 已被 workingDirectoryRecovery 接管的目录(resolve 返回 fallback)不算 ——+ * session 的文件在 fallback 里,继续留在那里才符合恢复语义。+ */+ async function isUsablePersistedWorkingDir(+ sessionId: string,+ workingDir: string,+ ): Promise<boolean> {+ const resolved = deps.resolveRecoveredWorkingDir?.(sessionId, workingDir) ?? workingDir;+ if (resolved !== workingDir) return false;+ try {+ return (await deps.statDirectory(workingDir)).isDirectory();+ } catch {+ return false;+ }+ }+async function rehydrateActiveSession(sessionId: string,createOpts: CreateOpts,@@ -924,9 +948,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeawait deps.ensureRemoteReadyForSessionStart({ session: sess, createOpts });if (sess) {- // Startup migration or a directory relocation may repair SQLite while a- // live SDK still owns the old cwd. Only use that persisted replacement;- // recreating an arbitrary project as an empty folder would lose its context.+ // SQLite 里的 working_dir 才是持久真源(启动迁移 / 目录重定位 / 用户移动+ // 会话都会改写它),而活 SDK 可能仍占着旧 cwd。漂移时按下面的规则切到持久+ // 目录:它必须**真实存在**(纯 stat,绝不为它 mkdir 空文件夹 —— 那会丢掉活+ // runtime 的上下文),且不被 workingDirectoryRecovery 的 fallback 接管。const dbDir = !sess.remoteHostId? await deps.readSessionWorkingDirFromDb(sessionId).catch(() => null): null;@@ -938,15 +963,27 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makesess.remoteHostId,...(fallbackDir ? [{ suppressMissingBroadcast: true }] : []),);+ // 会话移动(移动到项目 / worktree 变更)后旧 runtime 可能仍然活着 —— cc 的+ // 转录迁移 close 是 best-effort,close 失败时移动照常完成。此时 DB 的+ // working_dir 才是任务现在的目录:它**真实存在**且与 runtime cwd 不一致时,+ // 关闭旧 runtime 并按 DB 目录重建;不能等旧目录消失 —— 旧目录通常还在+ // (2026-09-13 实报:移动后消息仍在旧目录执行)。+ const persistedDirReady = ok && fallbackDir+ ? await isUsablePersistedWorkingDir(sessionId, fallbackDir)+ : false;// Claude/Pi keep a process whose cwd can still reference the deleted inode.// The pending note also covers recovery performed by an earlier preflight.const recoveredDir = !sess.remoteHostId? deps.resolveRecoveredWorkingDir?.(sessionId, sess.workDir) ?? sess.workDir: sess.workDir;- const needsCwdRefresh = ok && !sess.remoteHostId && (+ // recovery 语义优先:live 目录已被 fallback 接管(或带 note)时按 fallback+ // 重建,不做 DB 迁移 —— 那批文件在 fallback 里,不能把 session 拉回 DB 路径。+ const liveDirNeedsRecovery =recoveredDir !== sess.workDir ||((sess.agentKind === 'claude-code' || sess.agentKind === 'pi') &&- !!deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir)));+ !!deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir));+ const needsCwdRefresh = ok && !sess.remoteHostId &&+ (liveDirNeedsRecovery || persistedDirReady);if ((!ok && fallbackDir) || needsCwdRefresh) {const supplied = (createOpts as CreateOpts | undefined) ??await deps.readWorkingDirectoryRecoveryCreateOpts(sessionId);@@ -957,7 +994,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make...supplied,...preferences,id: sessionId,- workingDir: needsCwdRefresh ? recoveredDir : fallbackDir!,+ workingDir: needsCwdRefresh+ ? (liveDirNeedsRecovery ? recoveredDir : fallbackDir!)+ : fallbackDir!,agentKind: sess.agentKind,remoteHostId: sess.remoteHostId ?? undefined,});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 10c528df93..3fe711fcba 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12106,6 +12106,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},checkWorkDirExists,resolveRecoveredWorkingDir: (sessionId, dir) => workingDirectoryRecovery.resolve(sessionId, dir),+ statDirectory: (dir) => statWorkingDirectory(dir),preflightBotRuntimeResources: async (opts) => { await preflightBotRuntimeResources(opts); },readWorkingDirectoryRecoveryCreateOpts: async (sessionId) => {const [row] = await getDbClient().drizzle.select().from(sessions)