Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 工作目录缺失时恢复目录并继续对话 (#4060)
Dash6678fd38388b
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.tsindex 4943560879..94c3b866d9 100644--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts@@ -218,7 +218,7 @@ describe('shouldPrependMobileClientPromptNote(内置命令旁路)', () => {},'claude-code',)).toBe(true);- expect(shouldPrependMobileClientPromptNote('/compact', 'pi')).toBe(true);+ expect(shouldPrependMobileClientPromptNote('/compact', 'pi')).toBe(false);expect(shouldPrependMobileClientPromptNote('/compact', 'codex')).toBe(true);});});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex be3c4adf4d..d4609790be 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -619,6 +619,7 @@ import {anySessionInTurn,applyCodexSpawnConfigChangeWithRestart,clearDeferredCodexRestartForOwnerBoundary,+ clearWorkingDirectoryRecoveryForOwnerBoundary,collectAgentInputQueueScanTexts,createAutomationUserTurnGitBaselineHooks,registerModelVisibilitySyncIpc,@@ -1749,6 +1750,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// 的 Maker 上兑现旧 owner 的记忆设置重启(shutdown 触发的会话关闭事件也会// 撞上它,先清再关)。clearDeferredCodexRestartForOwnerBoundary();+ clearWorkingDirectoryRecoveryForOwnerBoundary();// interrupted-turn-resume:shutdown 批量 close 会话会触发 close teardown 的// markSessionTurnEnded,把"边界时还在飞的 turn"伪装成正常收尾 —— 被切换打断的// 任务从此既无中断横幅也无红点,呈现为"卡住且无报错"(与 ⌘Q 的 quit freeze 同款diff --git a/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.tsindex 47b8d0a293..979db33986 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts@@ -43,6 +43,49 @@ function createOpts(}describe('prepareDirectoryGrantsForBootstrap', () => {+ it.each(['readonly', 'writable'])('does not grant writes when %s canonicalization times out during fallback', async (failed) => {+ const { workspace, specs, output } = makeGrantTree();+ const opts = createOpts(workspace, [specs], [output]);+ const persistExistingSession = vi.fn(async () => {});+ await prepareDirectoryGrantsForBootstrap(opts, {+ preservePersistedGrants: true,+ readPersistedWritableDirs: async () => [output],+ realpathDirectory: async (dir) => {+ if (dir === (failed === 'readonly' ? specs : output)) {+ throw Object.assign(new Error('timeout'), { code: 'WORKDIR_PROBE_TIMEOUT' });+ }+ return dir;+ },+ persistExistingSession,+ });+ expect(opts).toMatchObject({ extraDirs: [specs], writableDirs: [] });+ expect(persistExistingSession).not.toHaveBeenCalled();+ });++ it('keeps saved grants through fallback bootstrap while filtering unavailable runtime roots', async () => {+ const { workspace, specs, output, root } = makeGrantTree();+ const stored = { extraDirs: [specs], writableDirs: [output] };+ const persistExistingSession = vi.fn(async () => {});+ const statDirectory = vi.fn(async () => {+ throw Object.assign(new Error('share unavailable'), { code: 'WORKDIR_PROBE_TIMEOUT' });+ });+ const temporary = createOpts(workspace, stored.extraDirs, [root]);+ await prepareDirectoryGrantsForBootstrap(temporary, {+ preservePersistedGrants: true, statDirectory,+ readPersistedWritableDirs: async () => stored.writableDirs,+ persistExistingSession,+ });+ expect(temporary).toMatchObject({ extraDirs: [], writableDirs: [] });+ expect(statDirectory.mock.calls.flat()).not.toContain(root);+ expect(persistExistingSession).not.toHaveBeenCalled();+ const reconnected = createOpts(workspace, stored.extraDirs, [root]);+ await prepareDirectoryGrantsForBootstrap(reconnected, {+ readPersistedWritableDirs: async () => stored.writableDirs, persistExistingSession,+ });+ expect(reconnected).toMatchObject(stored);+ expect(persistExistingSession).not.toHaveBeenCalled();+ });+it('persists the complete applied subset when lazy bootstrap removes a nested writable grant', async () => {const { workspace, shared, specs, output } = makeGrantTree();const opts = createOpts(workspace, [specs], [shared, output]);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex e18dd1f1a3..f15f889693 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -47,6 +47,7 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {const deps: MakerSendTransactionDeps = {getSession: vi.fn((sessionId: string) => (sessionId === session.id ? session : undefined)),closeSession: vi.fn(async () => {}),+ preflightBotRuntimeResources: vi.fn(async () => {}),getSessionMeta: vi.fn(async () => ({ title: '现有会话' })),ensureRemoteReadyForSessionStart: vi.fn(async () => {}),checkWorkDirExists: vi.fn(async () => true),@@ -55,6 +56,9 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {synthesizeOrcaVendorOptionsFromDb: vi.fn(async () => false),readSessionExtraDirsFromDb: vi.fn(async () => []),readSessionWorkingDirFromDb: vi.fn(async () => null),+ readWorkingDirectoryRecoveryCreateOpts: vi.fn(async (): Promise<MakerSessionCreateOpts> => ({+ agentKind: 'codex', workingDir: 'C:\\repo', model: 'gpt-5.4',+ })),withRehydrateCloseSuppressed: vi.fn(async (_sessionId, fn) => await fn()),bootstrapSession: vi.fn(async (opts: MakerSessionCreateOpts) => ({session: createSession({@@ -1107,6 +1111,182 @@ describe('maker SEND transaction', () => {expect(session.send).not.toHaveBeenCalled();});+ it('recovers a live session from the repaired DB directory and resumes its native history', async () => {+ const recoveredSession = createSession({ workDir: '/repaired/project' });+ const { deps, session } = createDeps({+ readSessionWorkingDirFromDb: vi.fn(async () => '/repaired/project'),+ checkWorkDirExists: vi.fn(async (_id, dir) => dir === '/repaired/project'),+ reconcileCreateOptsWithDb: vi.fn(async (_id, opts) => {+ expect(deps.closeSession).not.toHaveBeenCalled();+ opts.resumeSessionId = 'native-history';+ opts.model = 'persisted-model';+ }),+ bootstrapSession: vi.fn(async () => ({+ session: recoveredSession,+ didInjectOrcaInstructions: false,+ didInjectProjectContext: false,+ })),+ });+ const transaction = createMakerSendTransaction(deps);++ await expect(transaction.sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'codex', workingDir: '/stale/caller', model: 'stale-model',+ })).resolves.toMatchObject({ accepted: true });++ expect(deps.checkWorkDirExists).toHaveBeenNthCalledWith(+ 1, 'session-1', session.workDir, 'codex', null, { suppressMissingBroadcast: true },+ );+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ id: 'session-1', workingDir: '/repaired/project', remoteHostId: undefined,+ resumeSessionId: 'native-history', model: 'persisted-model',+ }));+ expect(deps.closeSession).toHaveBeenCalledTimes(1);+ expect(session.send).not.toHaveBeenCalled();+ expect(recoveredSession.send).toHaveBeenCalledTimes(1);+ });++ it('keeps the live runtime when both its directory and the DB replacement are missing', async () => {+ const { deps, session } = createDeps({+ readSessionWorkingDirFromDb: vi.fn(async () => '/also/missing'),+ checkWorkDirExists: vi.fn(async () => false),+ reconcileCreateOptsWithDb: vi.fn(async () => {}),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'codex', workingDir: '/stale/caller',+ })).resolves.toMatchObject({ accepted: false, reason: 'WORKDIR_MISSING' });+ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(session.send).not.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,+ } });+ const recovered = createSession({ agentKind });+ const { deps } = createDeps({+ getSession: () => oldSession,+ readSessionWorkingDirFromDb: async () => oldSession.workDir,+ readWorkingDirectoryRecoveryCreateOpts: async () => ({+ agentKind, workingDir: oldSession.workDir, model: 'persisted-model',+ resumeSessionId: 'native-history', permissionMode: 'ask', planMode: true,+ }),+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated; original files remain missing',+ consumeWorkingDirectoryRecoveryNote: vi.fn(),+ bootstrapSession: vi.fn(async () => ({+ session: recovered, didInjectOrcaInstructions: false, didInjectProjectContext: false,+ })),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'continue'))+ .resolves.toMatchObject({ accepted: true });+ expect(deps.closeSession).toHaveBeenCalledOnce();+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ workingDir: oldSession.workDir, resumeSessionId: 'native-history',+ permissionMode: 'ask', planMode: true, userPrompt: 'Keep the caller preference',+ makerMemoryEnabled: true,+ }));+ expect(oldSession.send).not.toHaveBeenCalled();+ expect(recovered.send).toHaveBeenCalledWith(expect.stringContaining('original files remain missing'), expect.anything());+ expect(deps.consumeWorkingDirectoryRecoveryNote).toHaveBeenCalledOnce();+ });++ it.each([undefined, false, true])('preserves omitted startup preferences and respects an explicit memory setting of %s', async (makerMemoryEnabled) => {+ const session = createSession({ agentKind: 'pi', hostStartupPreferences: {+ userPrompt: 'Original preference', makerMemoryEnabled: true, displayReasoning: 'off',+ } });+ const { deps } = createDeps({+ getSession: () => session,+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated',+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'pi', makerMemoryEnabled,+ })).resolves.toMatchObject({ accepted: true });+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ userPrompt: 'Original preference', displayReasoning: 'off',+ makerMemoryEnabled: makerMemoryEnabled ?? true,+ }));+ });++ it.each(['codex', 'claude-code', 'pi'] as const)('restarts %s in the fallback workspace before dispatch', async (agentKind) => {+ const session = createSession({ agentKind });+ const recovered = createSession({ agentKind, workDir: '/conversation' });+ const { deps } = createDeps({+ getSession: () => session,+ resolveRecoveredWorkingDir: () => '/conversation',+ peekWorkingDirectoryRecoveryNote: () => 'Original filesystem unavailable; temporary conversation workspace',+ bootstrapSession: vi.fn(async () => ({ session: recovered, didInjectOrcaInstructions: false, didInjectProjectContext: false })),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'continue')).resolves.toMatchObject({ accepted: true });+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir: '/conversation' }));+ expect(session.send).not.toHaveBeenCalled();+ expect(recovered.send).toHaveBeenCalledWith(expect.stringContaining('Original filesystem unavailable'), expect.anything());+ });++ it('keeps the old runtime when Bot resource preflight fails, then resumes normally after repair', async () => {+ const session = createSession({ agentKind: 'pi' });+ const { deps } = createDeps({+ getSession: () => session,+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated',+ preflightBotRuntimeResources: vi.fn().mockRejectedValueOnce(new Error('Bot resource unavailable')).mockResolvedValue(undefined),+ });+ const transaction = createMakerSendTransaction(deps);+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).resolves.toMatchObject({ accepted: false });+ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ await transaction.sendToAgentAccepted('session-1', 'hello');+ expect(deps.closeSession).toHaveBeenCalledOnce();+ expect(vi.mocked(deps.preflightBotRuntimeResources).mock.invocationCallOrder[1])+ .toBeLessThan(vi.mocked(deps.closeSession).mock.invocationCallOrder[0]!);+ });++ it('uses persisted settings to recover a live session when send has no createOpts', async () => {+ const persisted: MakerSessionCreateOpts = {+ agentKind: 'codex', workingDir: '/repaired/project',+ model: 'persisted-model', resumeSessionId: 'native-history',+ permissionMode: 'ask', planMode: true, providerId: 'provider', fastMode: true,+ };+ const { deps, session } = createDeps({+ readSessionWorkingDirFromDb: vi.fn(async () => persisted.workingDir),+ readWorkingDirectoryRecoveryCreateOpts: vi.fn(async () => ({ ...persisted })),+ checkWorkDirExists: vi.fn(async (_id, dir) => dir === persisted.workingDir),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello'))+ .resolves.toMatchObject({ accepted: true });+ expect(deps.checkWorkDirExists).toHaveBeenNthCalledWith(+ 1, 'session-1', session.workDir, 'codex', null, { suppressMissingBroadcast: true },+ );+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining(persisted));+ expect(session.send).not.toHaveBeenCalled();+ });++ it('does not close the live runtime if native history reconciliation fails during directory recovery', async () => {+ const { deps, session } = createDeps({+ readSessionWorkingDirFromDb: vi.fn(async () => '/repaired/project'),+ checkWorkDirExists: vi.fn(async (_id, dir) => dir === '/repaired/project'),+ reconcileCreateOptsWithDb: vi.fn(async () => { throw new Error('DB unavailable'); }),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'codex', workingDir: '/stale/caller',+ })).resolves.toMatchObject({ accepted: false, reason: 'REHYDRATE_FAILED' });+ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(session.send).not.toHaveBeenCalled();+ });++ it('does not use local DB directory recovery for a live SSH session', async () => {+ const session = createSession({ remoteHostId: 'ssh-host' });+ const { deps } = createDeps({+ getSession: vi.fn(() => session),+ readSessionWorkingDirFromDb: vi.fn(async () => '/local/project'),+ reconcileCreateOptsWithDb: vi.fn(async () => {}),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', {+ agentKind: 'codex', workingDir: '/remote/project', remoteHostId: 'ssh-host',+ })).resolves.toMatchObject({ accepted: true });+ expect(deps.readSessionWorkingDirFromDb).not.toHaveBeenCalled();+ expect(deps.closeSession).not.toHaveBeenCalled();+ });+it('rebuilds an error session through lazy bootstrap before dispatch', async () => {const failedSession = createSession({getStatus: vi.fn(() => 'error' as const),@@ -1884,8 +2064,8 @@ describe('mobile client prompt note', () => {expect(session.send).toHaveBeenCalledWith('/compact focus on decisions', expect.anything());});- it('keeps the mobile note for /compact text sent to a non-Claude agent', async () => {- const session = createSession({ agentKind: 'pi' });+ it('keeps the mobile note for /compact text sent to Codex', async () => {+ const session = createSession({ agentKind: 'codex' });const { deps } = createDeps({getSession: vi.fn(() => session),isMobileClientInvoke: vi.fn(() => true),@@ -1921,6 +2101,83 @@ describe('mobile client prompt note', () => {});describe('session-agent-switch handoff injection', () => {+ it.each([+ '/skill:git',+ ' /extension-command argument',+ { type: 'user' as const, content: [{ type: 'text' as const, text: '/skill:git' }, { type: 'image' as const, url: 'https://example.invalid/image.png' }] },+ ])('keeps Pi command intact and retains recovery note: %j', async (command) => {+ const session = createSession({ agentKind: 'pi' });+ const consumeWorkingDirectoryRecoveryNote = vi.fn();+ const { deps } = createDeps({+ getSession: () => session,+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated',+ consumeWorkingDirectoryRecoveryNote,+ bootstrapSession: vi.fn(async () => ({ session, didInjectOrcaInstructions: false, didInjectProjectContext: false })),+ });+ const transaction = createMakerSendTransaction(deps);+ await transaction.sendToAgentAccepted('session-1', command);+ expect(session.send).toHaveBeenLastCalledWith(command, expect.anything());+ expect(consumeWorkingDirectoryRecoveryNote).not.toHaveBeenCalled();+ await transaction.sendToAgentAccepted('session-1', 'continue');+ expect(session.send).toHaveBeenLastCalledWith(expect.stringContaining('Directory recreated'), expect.anything());+ expect(consumeWorkingDirectoryRecoveryNote).toHaveBeenCalledOnce();+ });+ it.each([+ '/compact',+ { type: 'user' as const, content: '/compact focus on the bug' },+ { type: 'user' as const, content: [{ type: 'text' as const, text: '/compact' }] },+ ])('retains the recovery notice across a native compact command: %j', async (command) => {+ const session = createSession({ agentKind: 'claude-code' });+ const consumeWorkingDirectoryRecoveryNote = vi.fn();+ const { deps } = createDeps({+ getSession: () => session,+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated',+ consumeWorkingDirectoryRecoveryNote,+ bootstrapSession: vi.fn(async () => ({+ session, didInjectOrcaInstructions: false, didInjectProjectContext: false,+ })),+ });+ const transaction = createMakerSendTransaction(deps);+ await transaction.sendToAgentAccepted('session-1', command);+ expect(session.send).toHaveBeenLastCalledWith(command, expect.anything());+ expect(consumeWorkingDirectoryRecoveryNote).not.toHaveBeenCalled();+ await transaction.sendToAgentAccepted('session-1', 'continue');+ expect(session.send).toHaveBeenLastCalledWith(expect.stringContaining('Directory recreated'), expect.anything());+ expect(consumeWorkingDirectoryRecoveryNote).toHaveBeenCalledOnce();+ });++ it('tells the agent about recreated cwd without changing the displayed user message', async () => {+ const consumeWorkingDirectoryRecoveryNote = vi.fn();+ const { deps, session } = createDeps({+ peekWorkingDirectoryRecoveryNote: () => 'The directory was recreated; files are missing.',+ consumeWorkingDirectoryRecoveryNote,+ });+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello', undefined, {+ persistUserMessage: { clientId: 'input', content: 'hello' },+ });+ expect(session.send).toHaveBeenCalledWith(+ expect.stringContaining('The directory was recreated; files are missing.'), expect.anything(),+ );+ expect(vi.mocked(deps.createDbMessage).mock.calls[0]?.[1].content).toBe('hello');+ expect(consumeWorkingDirectoryRecoveryNote).toHaveBeenCalledWith(+ 'session-1', 'The directory was recreated; files are missing.',+ );+ });++ it('keeps the recovery notice when the provider has not accepted the message', async () => {+ const consumeWorkingDirectoryRecoveryNote = vi.fn();+ const session = createSession({+ send: vi.fn(async () => ({ accepted: false, reason: 'cancelled-before-dispatch' } satisfies SessionSendResult)),+ });+ const { deps } = createDeps({+ getSession: () => session,+ peekWorkingDirectoryRecoveryNote: () => 'Directory recreated',+ consumeWorkingDirectoryRecoveryNote,+ });+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello');+ expect(consumeWorkingDirectoryRecoveryNote).not.toHaveBeenCalled();+ });+it('pending 命中时 wire payload 前置交接段,落库内容保持用户原文,accepted 后 consume', async () => {const consumePendingHandoff = vi.fn();const { deps, session } = createDeps({diff --git a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.tsnew file mode 100644index 0000000000..bd9db51118--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts@@ -0,0 +1,320 @@+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => fsp.rm(root, { recursive: true, force: true })));+});++describe('working directory conversation recovery', () => {+ it.each(['WORKDIR_PROBE_TIMEOUT', 'EIO', 'EACCES'])('handles a share failing during mkdir: %s', async (code) => {+ const dir = path.resolve('/share/project');+ const fallback = path.resolve('/conversation');+ const allocate = vi.fn(async () => fallback);+ const mkdir = vi.fn(async () => { throw Object.assign(new Error('write failed'), { code }); });+ const recovery = createWorkingDirectoryRecovery({+ stat: async (target) => {+ if (target === dir) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return { isDirectory: () => true, dev: 1 };+ }, mkdir,+ }, allocate);+ const unavailable = code !== 'EACCES';+ expect(await recovery.recover('task', dir)).toBe(unavailable);+ expect(mkdir).toHaveBeenCalledOnce();+ expect(allocate).toHaveBeenCalledTimes(unavailable ? 1 : 0);+ expect(recovery.isFallback('task', dir)).toBe(unavailable);+ if (unavailable) {+ recovery.consume('task', recovery.peek('task')!);+ expect(recovery.isFallback('task', fallback)).toBe(true);+ expect(recovery.resolve('task', dir)).toBe(fallback);+ expect(recovery.isFallback('task', '/explicit-new-project')).toBe(false);+ }+ });++ it.runIf(process.platform === 'darwin')('distinguishes a bare /Volumes mount point from an alias to the system disk', async () => {+ const allocate = vi.fn(async () => '/conversation');+ const recovery = createWorkingDirectoryRecovery({+ stat: async () => ({ isDirectory: () => true, dev: 1 }), mkdir: vi.fn(),+ realpath: async (dir) => dir === '/Volumes/System' ? '/' : dir,+ }, allocate);+ expect(await recovery.recover('system', '/Volumes/System/project')).toBe(true);+ expect(allocate).not.toHaveBeenCalled();+ const diagnostic = vi.fn(async () => null);+ expect(await recovery.recover('external', '/Volumes/External/project', diagnostic)).toBe(true);+ expect(allocate).toHaveBeenCalledOnce();+ expect(diagnostic).not.toHaveBeenCalled();+ });++ it.each([false, true])('uses a conversation workspace after the observed volume disappears (shadow exists: %s)', async (shadowExists) => {+ const dir = path.resolve('/mounted/project');+ const fallback = path.resolve('/conversation');+ let mounted = true;+ const mkdir = vi.fn();+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async (target) => {+ if (!mounted && target === dir && !shadowExists) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return { isDirectory: () => true, dev: mounted ? 2 : 1 };+ }),+ mkdir,+ realpath: async (target) => target,+ }, async () => fallback);+ await recovery.observe('task', dir);+ mounted = false;+ expect(await recovery.recover('task', dir)).toBe(true);+ expect(mkdir).not.toHaveBeenCalled();+ expect(recovery.resolve('task', dir)).toBe(fallback);+ const note = recovery.peek('task', fallback)!;+ expect(note).toContain('not been restored or copied');+ expect(note).toContain(JSON.stringify(dir));+ recovery.consume('task', note);+ mounted = true;+ expect(await recovery.recover('task', dir)).toBe(true);+ expect(recovery.resolve('task', dir)).toBe(fallback);+ expect(recovery.peek('task', fallback)).toBeNull();+ expect(recovery.resolve('task', '/chosen-project')).toBe('/chosen-project');+ expect(recovery.resolve('task', dir)).toBe(dir);+ });++ it('recreates a deleted child on the same observed volume', async () => {+ const dir = path.resolve('/mounted/project');+ let missing = false;+ const mkdir = vi.fn();+ const allocate = vi.fn(async () => '/conversation');+ const recovery = createWorkingDirectoryRecovery({+ stat: async (target) => {+ if (missing && target === dir) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return { isDirectory: () => true, dev: 2 };+ }, mkdir,+ }, allocate);+ await recovery.observe('task', dir);+ missing = true;+ expect(await recovery.recover('task', dir)).toBe(true);+ expect(mkdir).toHaveBeenCalledWith(dir, { recursive: true });+ expect(allocate).not.toHaveBeenCalled();+ });++ it('recreates a deleted fallback without returning to the original mount', async () => {+ const mkdir = vi.fn();+ const recovery = createWorkingDirectoryRecovery({+ stat: async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }, mkdir,+ }, async () => '/conversation');+ expect(await recovery.recover('task', '/offline/project')).toBe(true);+ recovery.consume('task', recovery.peek('task')!);+ expect(await recovery.recover('task', '/conversation')).toBe(true);+ expect(mkdir).toHaveBeenCalledWith(path.resolve('/conversation'), { recursive: true });+ expect(recovery.resolve('task', '/offline/project')).toBe(path.resolve('/conversation'));+ expect(recovery.peek('task')).toContain('previous files have not been recovered');+ });++ it.each(['EIO', 'ENOTCONN', 'ENODEV', 'WORKDIR_PROBE_TIMEOUT'])('uses fallback for an unavailable filesystem probe: %s', async (code) => {+ const mkdir = vi.fn();+ const recovery = createWorkingDirectoryRecovery({+ stat: async () => { throw Object.assign(new Error('unavailable'), { code }); }, mkdir,+ }, async () => '/conversation');+ expect(await recovery.recover('task', '/network/project')).toBe(true);+ expect(mkdir).not.toHaveBeenCalled();+ expect(recovery.resolve('task', '/network/project')).toBe(path.resolve('/conversation'));+ });++ it('does not revive a fallback after cleanup during allocation', async () => {+ let finish!: (dir: string) => void;+ const allocate = vi.fn(() => new Promise<string>((resolve) => { finish = resolve; }));+ const recovery = createWorkingDirectoryRecovery({+ stat: async () => { throw Object.assign(new Error('missing drive'), { code: 'ENOENT' }); }, mkdir: vi.fn(),+ }, allocate);+ const recovering = recovery.recover('task', '/unavailable/project');+ await vi.waitFor(() => expect(allocate).toHaveBeenCalled());+ recovery.discard('task');+ finish('/conversation');+ expect(await recovering).toBe(false);+ expect(recovery.resolve('task', '/unavailable/project')).toBe('/unavailable/project');+ expect(recovery.peek('task')).toBeNull();+ });++ it('notifies physical aliases while preserving unrelated pending recovery', async () => {+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-cwd-alias-'));+ roots.push(root);+ const parent = path.join(root, 'parent');+ const alias = path.join(root, 'alias');+ await fsp.mkdir(parent);+ await fsp.symlink(parent, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const dir = path.join(parent, 'project');+ const aliasDir = path.join(alias, 'project');+ const other = path.join(root, 'other');+ const recovery = createWorkingDirectoryRecovery();+ await recovery.recover('other', other);+ const otherNote = recovery.peek('other', other);+ await recovery.recover('first', dir, null, [+ { id: 'alias', workingDir: aliasDir }, { id: 'other', workingDir: other },+ ]);+ expect(recovery.peek('alias', aliasDir)).toContain('previous files have not been recovered');+ expect(recovery.peek('other', other)).toBe(otherNote);+ recovery.consume('first', recovery.peek('first', dir)!);+ expect(recovery.peek('alias', aliasDir)).not.toBeNull();+ });++ it('does not revive an alias cleared while physical identity is being resolved', async () => {+ let finish!: (dir: string) => void;+ const realpath = vi.fn(() => new Promise<string>((resolve) => { finish = resolve; }));+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir: vi.fn(async () => {}),+ realpath,+ });+ const recovering = recovery.recover('first', '/project', null, [{ id: 'alias', workingDir: '/alias' }]);+ await vi.waitFor(() => expect(realpath).toHaveBeenCalledOnce());+ recovery.discard('alias');+ realpath.mockResolvedValue('/physical');+ finish('/physical');+ expect(await recovering).toBe(true);+ expect(recovery.peek('alias', '/alias')).toBeNull();+ expect(recovery.peek('first', '/project')).not.toBeNull();+ });++ it('keeps shared-directory notices independent and drops a notice after moving away', async () => {+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir: vi.fn(async () => {}),+ });+ await recovery.recover('first', '/project', null, ['second', 'third'].map((id) => ({ id, workingDir: '/project' })));+ const note = recovery.peek('first', '/project')!;+ recovery.consume('first', note);+ expect(recovery.peek('first', '/project')).toBeNull();+ expect(recovery.peek('second', '/project')).toBe(note);+ expect(recovery.peek('third', '/elsewhere')).toBeNull();+ expect(recovery.peek('third', '/project')).toBeNull();+ recovery.consume('second', note);+ expect(recovery.peek('second', '/project')).toBeNull();+ });++ it('does not revive sibling notices cleared or moved during shared-directory IO', async () => {+ let finish!: () => void;+ const mkdir = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir,+ });+ const recovering = recovery.recover('first', '/project', null, ['cleared', 'moved', 'remaining'].map((id) => ({ id, workingDir: '/project' })));+ await vi.waitFor(() => expect(mkdir).toHaveBeenCalled());+ recovery.discard('cleared');+ expect(recovery.peek('moved', '/elsewhere')).toBeNull();+ finish();+ expect(await recovering).toBe(true);+ expect(recovery.peek('cleared', '/project')).toBeNull();+ expect(recovery.peek('moved', '/project')).toBeNull();+ expect(recovery.peek('remaining', '/project')).toBe(recovery.peek('first', '/project'));+ expect(recovery.peek('remaining', '/project')).toContain('previous files have not been recovered');+ });++ it('passes the similar-path diagnostic to the agent while keeping the conversation available', async () => {+ const mkdir = vi.fn(async () => {});+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir,+ });+ expect(await recovery.recover('task', '/project', '/project ')).toBe(true);+ expect(mkdir).toHaveBeenCalledWith('/project', { recursive: true });+ expect(recovery.peek('task')).toContain(JSON.stringify('/project '));+ expect(recovery.peek('task')).toContain('Inspect this candidate before reading or creating project files');+ expect(recovery.peek('task')).toContain('previous files have not been recovered');+ });++ it('keeps the recovery note when another probe sees the directory before mkdir settles', async () => {+ let finish!: () => void;+ const mkdir = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn().mockRejectedValueOnce(Object.assign(new Error('missing'), { code: 'ENOENT' }))+ .mockResolvedValue({ isDirectory: () => true }),+ mkdir,+ });+ const first = recovery.recover('task', '/project');+ await vi.waitFor(() => expect(mkdir).toHaveBeenCalled());+ expect(await recovery.recover('task', '/project')).toBe(true);+ finish();+ expect(await first).toBe(true);+ expect(recovery.peek('task')).toContain('previous files have not been recovered');+ });++ it.each(['discard', 'clear'] as const)('does not restore a discarded note after late IO: %s', async (operation) => {+ let finish!: () => void;+ const mkdirDone = new Promise<void>((resolve) => { finish = resolve; });+ const mkdir = vi.fn(() => mkdirDone);+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir,+ });+ const recovering = recovery.recover('task', '/project');+ await vi.waitFor(() => expect(mkdir).toHaveBeenCalled());+ if (operation === 'discard') recovery.discard('task');+ else recovery.clear();+ finish();+ expect(await recovering).toBe(true);+ expect(recovery.peek('task')).toBeNull();+ });++ it('discards closed or cleared tasks and clears all notes at an owner boundary', async () => {+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir: vi.fn(async () => {}),+ });+ await recovery.recover('first', '/first');+ await recovery.recover('second', '/second');+ recovery.discard('first');+ expect(recovery.peek('first')).toBeNull();+ expect(recovery.peek('second')).not.toBeNull();+ recovery.clear();+ expect(recovery.peek('second')).toBeNull();+ });++ it('recreates the original directory and keeps its notice through repeated probes until acknowledged', async () => {+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-cwd-recovery-'));+ roots.push(root);+ const dir = path.join(root, 'removed-parent', 'project');+ const recovery = createWorkingDirectoryRecovery();+ expect(await recovery.recover('task', dir)).toBe(true);+ expect((await fsp.stat(dir)).isDirectory()).toBe(true);+ const note = recovery.peek('task');+ expect(note).toContain(JSON.stringify(dir));+ expect(note).toContain('previous files have not been recovered');+ expect(await recovery.recover('task', dir)).toBe(true);+ expect(recovery.peek('task')).toBe(note);+ recovery.consume('task', 'stale note');+ expect(recovery.peek('task')).toBe(note);+ recovery.consume('task', note!);+ expect(recovery.peek('task')).toBeNull();+ });++ it('does not replace an existing file or invent a recovery notice for an existing directory', async () => {+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-cwd-recovery-'));+ roots.push(root);+ const file = path.join(root, 'project');+ await fsp.writeFile(file, 'keep');+ const recovery = createWorkingDirectoryRecovery();+ expect(await recovery.recover('task', file)).toBe(false);+ expect(await fsp.readFile(file, 'utf8')).toBe('keep');+ expect(await recovery.recover('task', root)).toBe(true);+ expect(recovery.peek('task')).toBeNull();+ });++ it.each(['EACCES', 'ENOTDIR', 'EIO'])('does not recreate a path after %s', async (code) => {+ const mkdir = vi.fn();+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error(code), { code }); }), mkdir,+ });+ expect(await recovery.recover('task', '/unavailable')).toBe(false);+ expect(mkdir).not.toHaveBeenCalled();+ expect(recovery.peek('task')).toBeNull();+ });++ it('does not claim recovery if directory creation fails', async () => {+ const recovery = createWorkingDirectoryRecovery({+ stat: vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); }),+ mkdir: vi.fn(async () => { throw new Error('read-only volume'); }),+ });+ expect(await recovery.recover('task', '/unavailable')).toBe(false);+ expect(recovery.peek('task')).toBeNull();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts b/apps/desktop/src/main/maker-ipc/extraDirsValidator.tsindex 85e1ffc2a9..e5a651a0b7 100644--- a/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts+++ b/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts@@ -107,6 +107,7 @@ function isSelfOrSubdir(candidate: string, base: string): boolean {export async function validateExtraDirs(rawDirs: string[] | undefined | null,workingDir: string | undefined | null,+ statDirectory: (dir: string) => Promise<{ isDirectory(): boolean }> = fs.stat,): Promise<ValidateResult> {const valid: string[] = [];const rejected: ValidateResult['rejected'] = [];@@ -142,7 +143,7 @@ export async function validateExtraDirs(let stat;try {- stat = await fs.stat(root);+ stat = await statDirectory(root);} catch {rejected.push({ path: dir, reason: 'not-exist' });continue;@@ -192,15 +193,22 @@ async function canonicalDirectoryKey(dir: string): Promise<string> {export async function excludeDirectoryGrantConflicts(candidates: readonly string[],blocked: readonly string[],+ resolvePath?: (dir: string) => Promise<string>,): Promise<string[]> {if (candidates.length === 0) return [];- const blockedKeys = await Promise.all(blocked.map(canonicalDirectoryKey));+ // Bounded recovery probes must not treat a timed-out alias as a disjoint tree.+ const canonical = (dir: string) => resolvePath+ ? resolvePath(dir).catch(() => null)+ : canonicalDirectoryKey(dir);+ const blockedKeys = await Promise.all(blocked.map(canonical));+ if (blockedKeys.some((key) => key === null)) return [];const result: string[] = [];const acceptedKeys: string[] = [];for (const candidate of candidates) {- const candidateKey = await canonicalDirectoryKey(candidate);+ const candidateKey = await canonical(candidate);+ if (candidateKey === null) continue;const overlapsBlockedTree = blockedKeys.some((blockedKey) =>- isSelfOrSubdir(candidateKey, blockedKey) || isSelfOrSubdir(blockedKey, candidateKey));+ isSelfOrSubdir(candidateKey, blockedKey!) || isSelfOrSubdir(blockedKey!, candidateKey));const overlapsAcceptedTree = acceptedKeys.some((acceptedKey) =>isSelfOrSubdir(candidateKey, acceptedKey) || isSelfOrSubdir(acceptedKey, candidateKey));if (!overlapsBlockedTree && !overlapsAcceptedTree) {diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex e57cde8ee3..a7403d2b66 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -38,6 +38,10 @@ import type { MakerSessionCreateOpts } from './sessionRequest.js';type CreateOpts = MakerSessionCreateOpts;export interface BootstrapDirectoryGrantDeps {+ /** Host-only: a temporary workspace must not turn unavailable grants into revocations. */+ preservePersistedGrants?: boolean;+ statDirectory?: (dir: string) => Promise<{ isDirectory(): boolean }>;+ realpathDirectory?: (dir: string) => Promise<string>;readPersistedWritableDirs(sessionId: string): Promise<string[]>;persistExistingSession(sessionId: string,@@ -65,10 +69,10 @@ export async function prepareDirectoryGrantsForBootstrap(typeof opts.id === 'string' && opts.id? await deps.readPersistedWritableDirs(opts.id): [];- const extraValidation = await validateExtraDirs(requestedExtraDirs, opts.workingDir);- const writableValidation = await validateExtraDirs(requestedWritableDirs, opts.workingDir);+ const extraValidation = await validateExtraDirs(requestedExtraDirs, opts.workingDir, deps.statDirectory);+ const writableValidation = await validateExtraDirs(requestedWritableDirs, opts.workingDir, deps.statDirectory);const extraDirs = extraValidation.valid;- const writableDirs = await excludeDirectoryGrantConflicts(writableValidation.valid, extraDirs);+ const writableDirs = await excludeDirectoryGrantConflicts(writableValidation.valid, extraDirs, deps.realpathDirectory);if (opts.extraDirs !== undefined || extraDirs.length > 0) opts.extraDirs = extraDirs;if (opts.writableDirs !== undefined || writableDirs.length > 0) opts.writableDirs = writableDirs;@@ -76,7 +80,7 @@ export async function prepareDirectoryGrantsForBootstrap(const changed =!sameDirectoryList(requestedExtraDirs, extraDirs) ||!sameDirectoryList(requestedWritableDirs, writableDirs);- if (!changed || opts.remoteHostId || typeof opts.id !== 'string' || !opts.id) return;+ if (!changed || deps.preservePersistedGrants || opts.remoteHostId || typeof opts.id !== 'string' || !opts.id) return;await deps.persistExistingSession(opts.id, { extraDirs, writableDirs });}@@ -277,6 +281,7 @@ function extractIpcUserMessageText(message: IpcUserMessage): string {}export interface MakerSendTransactionSession {+ hostStartupPreferences?: CreateOpts['hostStartupPreferences'];id: string;agentKind: AgentKind;workDir: string;@@ -297,6 +302,7 @@ export interface MakerSendTransactionLog {export interface MakerSendTransactionDeps {getSession(sessionId: string): MakerSendTransactionSession | undefined | null;closeSession(sessionId: string): Promise<void>;+ preflightBotRuntimeResources(opts: CreateOpts): Promise<void>;getSessionMeta(sessionId: string): Promise<{ title?: string } | null>;ensureRemoteReadyForSessionStart(params: {session?: { agentKind: AgentKind; remoteHostId: string | null } | null;@@ -309,6 +315,7 @@ export interface MakerSendTransactionDeps {remoteHostId?: string | null,opts?: { suppressMissingBroadcast?: boolean },): Promise<boolean>;+ resolveRecoveredWorkingDir?(sessionId: string, workingDir: string): string;/*** 读 DB 里既有会话的权威 working_dir(行不存在 → null)。lazy-create /* rehydrate 在 caller 传入的 workingDir 校验失败时用它兜底——输入队列崩溃@@ -412,6 +419,9 @@ export interface MakerSendTransactionDeps {*/peekPendingHandoff?(sessionId: string): Promise<string | null>;consumePendingHandoff?(sessionId: string): void;+ peekWorkingDirectoryRecoveryNote?(sessionId: string, workingDir: string): string | null;+ readWorkingDirectoryRecoveryCreateOpts(sessionId: string): Promise<CreateOpts>;+ consumeWorkingDirectoryRecoveryNote?(sessionId: string, note: string): void;/*** 计划对账:会话里若有待处理计划,返回一段只进 wire payload 的指示文本。* sealedTurnId 只用于已完成计划的一次性保护,跨过 accepted 后才消费。@@ -569,7 +579,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeasync function loadExtraDirsIfNeeded(sessionId: string,opts: CreateOpts,- source: 'lazy-create' | 'active-orca-rehydrate',+ source: 'lazy-create' | 'active-session-rehydrate',): Promise<void> {if (opts.extraDirs === undefined) {try {@@ -624,7 +634,12 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakecreateOpts.agentKind,createOpts.remoteHostId,);- if (ok) return true;+ if (ok) {+ if (!createOpts.remoteHostId && createOpts.workingDir) {+ createOpts.workingDir = deps.resolveRecoveredWorkingDir?.(sessionId, createOpts.workingDir) ?? createOpts.workingDir;+ }+ return true;+ }if (!fallbackDir) return false;const okDb = await deps.checkWorkDirExists(sessionId,@@ -638,14 +653,16 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakestaleWorkingDir: createOpts.workingDir,workingDir: fallbackDir,});- createOpts.workingDir = fallbackDir;+ createOpts.workingDir = createOpts.remoteHostId ? fallbackDir :+ deps.resolveRecoveredWorkingDir?.(sessionId, fallbackDir) ?? fallbackDir;return true;}- async function rehydrateActiveOrcaSession(+ async function rehydrateActiveSession(sessionId: string,createOpts: CreateOpts,fromDeviceLinkClient: boolean,+ reason: 'orca' | 'workdir' = 'orca',): Promise<ResolveSessionResult> {const okRehydrate = await ensureWorkDirWithDbFallback(sessionId, createOpts);if (!okRehydrate) {@@ -659,14 +676,18 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make),};}- await loadExtraDirsIfNeeded(sessionId, createOpts, 'active-orca-rehydrate');+ await loadExtraDirsIfNeeded(sessionId, createOpts, 'active-session-rehydrate');try {+ if (reason === 'workdir') {+ await deps.synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);+ }// 关旧 runtime 前先按 DB 权威口径对账执行字段(与 lazy-create 同源):caller /// 队列的 createOpts 快照常不带 resumeSessionId(或带旧引擎的陈旧值),直接// close+bootstrap 会启动一个没有旧 transcript 的全新原生会话(#2882:Pi 会话// 中途 start_team 后丢失全部对话历史)。DB 读失败时 reconcile 抛错 → 落入下方// REHYDRATE_FAILED,此时尚未 closeSession,旧 runtime 不受损。await deps.reconcileCreateOptsWithDb?.(sessionId, createOpts);+ if (reason === 'workdir') await deps.preflightBotRuntimeResources(createOpts);// A newly created device-link Codex Lead has a real sdk_session_id as soon as// thread/start returns, but that id is not resumable until a provider turn// is accepted. The live Session is the only trustworthy local evidence at@@ -687,15 +708,16 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make}const session = await deps.withRehydrateCloseSuppressed(sessionId, async () => {await deps.closeSession(sessionId);- // close 后重新 bootstrap,避免旧 SDK handle 缺 Orca MCP vendorOptions。+ // Rebuild the SDK handle with the repaired cwd and current MCP options.const {session: newSess,didInjectOrcaInstructions,didInjectProjectContext,} = await deps.bootstrapSession(createOpts);await deps.markOrcaRoleIfNeeded(newSess.id, createOpts.orcaRole);- deps.log.info('send: rehydrate active Orca session with MCP vendorOptions', {+ deps.log.info('send: rehydrate active session', {sessionId,+ reason,agentKind: createOpts.agentKind,usedOrcaInstructions: didInjectOrcaInstructions,usedProjectContext: didInjectProjectContext,@@ -853,13 +875,52 @@ 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.+ const dbDir = !sess.remoteHostId+ ? await deps.readSessionWorkingDirFromDb(sessionId).catch(() => null)+ : null;+ const fallbackDir = dbDir && dbDir !== sess.workDir ? dbDir : null;const ok = await deps.checkWorkDirExists(sessionId,sess.workDir,sess.agentKind,sess.remoteHostId,+ ...(fallbackDir ? [{ suppressMissingBroadcast: true }] : []),);- if (!ok) {+ // 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 && (+ recoveredDir !== sess.workDir ||+ ((sess.agentKind === 'claude-code' || sess.agentKind === 'pi') &&+ !!deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir)));+ if ((!ok && fallbackDir) || needsCwdRefresh) {+ const supplied = (createOpts as CreateOpts | undefined) ??+ await deps.readWorkingDirectoryRecoveryCreateOpts(sessionId);+ const startupPreferences = sess.hostStartupPreferences ?? {};+ const preferences = Object.fromEntries(Object.entries(startupPreferences)+ .filter(([key]) => supplied[key as keyof typeof startupPreferences] === undefined));+ const co = deps.buildCreateOptsWithStderr({+ ...supplied,+ ...preferences,+ id: sessionId,+ workingDir: needsCwdRefresh ? recoveredDir : fallbackDir!,+ agentKind: sess.agentKind,+ remoteHostId: sess.remoteHostId ?? undefined,+ });+ const recovered = await rehydrateActiveSession(+ sessionId,+ co,+ requestedSendOpts.fromDeviceLinkClient === true,+ 'workdir',+ );+ if (recovered.kind === 'failure') return recovered.result;+ sess = recovered.session;+ } else if (!ok) {return toCompatibleMakerSendResult(createHostSendFailure('WORKDIR_MISSING',@@ -880,7 +941,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakesessionId,});} else {- const rehydrated = await rehydrateActiveOrcaSession(+ const rehydrated = await rehydrateActiveSession(sessionId,co,requestedSendOpts.fromDeviceLinkClient === true,@@ -988,6 +1049,12 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make}// session-agent-switch:切换后的首条消息把交接前缀拼进 wire payload。// 落库/显示内容(persistUserMessage.content)不含交接段——display 与 sent 分离。+ const workdirRecoveryNote = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)+ ? deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir) ?? null+ : null;+ if (workdirRecoveryNote) {+ normalized = prependNoteToWireUserMessage(normalized as HandoffWireMessage, workdirRecoveryNote);+ }const pendingHandoff = (await deps.peekPendingHandoff?.(sessionId)) ?? null;const withHandoff = pendingHandoff? prependHandoffToUserMessage(normalized as HandoffWireMessage, pendingHandoff)@@ -1345,6 +1412,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make// 只有跨过不可逆 dispatch 边界才消费;未派发保留 pending 下次重试。deps.consumePendingHandoff?.(sessionId);}+ if (workdirRecoveryNote && sendResult.accepted) {+ deps.consumeWorkingDirectoryRecoveryNote?.(sessionId, workdirRecoveryNote);+ }if (planReconcile?.sealedTurnId && sendResult.accepted) {try {await deps.consumeSealedPlanReconcileNote?.(sessionId, planReconcile.sealedTurnId);diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.tsindex 023351ac48..92dbf2ae14 100644--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts@@ -57,15 +57,24 @@ function singleTextContent(message: unknown): string | null {}/**- * Claude Code 内置命令必须位于消息开头;手机客户端说明不能抢占这个位置。- * 只放行已由 palette 明确暴露的 `/compact`,其它 slash 文本继续保留来源说明。+ * 原生命令必须位于消息开头;环境说明不能抢占这个位置。+ * Claude 旁路 /compact;Pi 的 slash 输入交由运行时自己的命令发现处理。*/export function shouldPrependMobileClientPromptNote(message: unknown,agentKind: string,): boolean {- if (agentKind !== 'claude-code') return true;const text = singleTextContent(message);+ // Pi owns command discovery. Leave slash inputs intact so its runtime can+ // execute installed commands (or treat unknown ones as literal text).+ if (agentKind === 'pi') {+ const content = message && typeof message === 'object'+ ? (message as { content?: unknown }).content : null;+ const parts = Array.isArray(content) ? content : [];+ const firstText = parts.find((part) => part?.type === 'text' && typeof part.text === 'string')?.text;+ return !(text ?? firstText ?? '').trimStart().startsWith('/');+ }+ if (agentKind !== 'claude-code') return true;return text === null || !/^\/compact(?:\s|$)/.test(text);}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4522dbd7b3..b43d70ddc0 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -210,6 +210,8 @@ import {isDbClientNotReadyError,} from '../localDb/client/current.js';import { createBotRuntimeRestoreCoordinator } from './botRuntimeRestore.js';+import { createWorkingDirectoryRecovery, isUnavailableFilesystemError } from './workingDirectoryRecovery.js';+import { statWorkingDirectory, mkdirWorkingDirectory, realpathWorkingDirectory, findSimilarWorkingDirectory } from '../workdir-probe-host/index.js';import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';import {awaitAgentInputQueueSnapshotPersistence,@@ -221,10 +223,7 @@ import {ensureDialogueWorkspaceDir,dialogueWorkspaceRootDir,} from '../localDb/dialogueWorkspace.js';-import {- healMissingDialogueWorkdir,- matchDialogueWorkspacePath,-} from '../localDb/dialogueWorkdirSelfHeal.js';+import { matchDialogueWorkspacePath } from '../localDb/dialogueWorkdirSelfHeal.js';import {broadcastMessageRow,broadcastMessageAgentMetaUpdate,@@ -1054,6 +1053,8 @@ import { handleSessionEvent, type SessionEventDependencies } from './sessionEvenimport { installSessionTurnObserver } from './sessionTurnObserver.js';const log = createLogger('maker-ipc');+const workingDirectoryRecovery = createWorkingDirectoryRecovery({ stat: statWorkingDirectory, mkdir: mkdirWorkingDirectory, realpath: realpathWorkingDirectory }, async (sessionId) =>+ ensureDialogueWorkspaceDir(sessionId, Date.now()));function localModelWindowSwitchErrorCode(code: IpcErrorCode): IpcErrorCode {return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;@@ -3317,6 +3318,10 @@ export function clearDeferredCodexRestartForOwnerBoundary(): void {deferredCodexRestartHolder?.clear();}+export function clearWorkingDirectoryRecoveryForOwnerBoundary(): void {+ workingDirectoryRecovery.clear();+}+/*** Goal / IM / scheduler 直发 `Session.send()` 的 deferred agent-switch 锁桥。*@@ -4592,6 +4597,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}),);setSessionRuntimeCleanup((sessionId) => {+ workingDirectoryRecovery.discard(sessionId);clearSessionRuntimeControlState(sessionId);clearSessionProvider(sessionId);setSessionEffort(sessionId, null);@@ -6244,6 +6250,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)didInjectOrcaInstructions: boolean;didInjectProjectContext: boolean;}> {+ if (o.id && o.workingDir && !o.remoteHostId) {+ o.workingDir = workingDirectoryRecovery.resolve(o.id, o.workingDir);+ await workingDirectoryRecovery.observe(o.id, o.workingDir).catch(() => undefined);+ }+ o.hostStartupPreferences = {+ userPrompt: o.userPrompt,+ makerMemoryEnabled: o.makerMemoryEnabled,+ displayReasoning: o.displayReasoning,+ };await options.waitForAccountProviderModelsReady();const runtimeOverride =typeof o.id === 'string' ? getSessionRuntimeControlSnapshot(o.id).effectiveOverride : null;@@ -6258,7 +6273,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const didInjectProjectContext =o.reviewMode === true ? false : await applyProjectContextInjection(o);+ const usingFallback = !!o.id && !!o.workingDir && !o.remoteHostId &&+ workingDirectoryRecovery.isFallback(o.id, o.workingDir);await prepareDirectoryGrantsForBootstrap(o, {+ statDirectory: usingFallback ? statWorkingDirectory : undefined,+ realpathDirectory: usingFallback ? realpathWorkingDirectory : undefined,+ preservePersistedGrants: usingFallback,readPersistedWritableDirs: readSessionWritableDirsFromDb,persistExistingSession: async (sessionId, patch) => {const [existing] = await getDbClient()@@ -11505,6 +11525,33 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await ensureRemoteReadyForSessionStart(params);},checkWorkDirExists,+ resolveRecoveredWorkingDir: (sessionId, dir) => workingDirectoryRecovery.resolve(sessionId, dir),+ preflightBotRuntimeResources: async (opts) => { await preflightBotRuntimeResources(opts); },+ readWorkingDirectoryRecoveryCreateOpts: async (sessionId) => {+ const [row] = await getDbClient().drizzle.select().from(sessions)+ .where(eq(sessions.id, sessionId)).limit(1);+ if (!row?.workingDir) throw new Error(`Session ${sessionId} has no working directory`);+ return {+ id: sessionId,+ agentKind: dbToMakerAgentKind(row.agentKind),+ workingDir: row.workingDir,+ workspaceKind: row.workspaceKind,+ model: row.model ?? undefined,+ providerId: row.providerId,+ effort: (row.effort ?? undefined) as CreateOpts['effort'],+ fastMode: !!row.fastMode,+ permissionMode: permissionModeOrAsk(row.permissionMode),+ planMode: !!row.planModeEnabled,+ title: row.title ?? undefined,+ resumeSessionId: row.sdkSessionId ?? undefined,+ remoteHostId: row.remoteHostId ?? undefined,+ orcaRole: row.orcaRole as CreateOpts['orcaRole'],+ codexHistoryHasProductPrompt: row.codexHistoryHasProductPrompt ?? undefined,+ };+ },+ peekWorkingDirectoryRecoveryNote: (sessionId, workingDir) => workingDirectoryRecovery.peek(sessionId, workingDir),+ consumeWorkingDirectoryRecoveryNote: (sessionId, note) =>+ workingDirectoryRecovery.consume(sessionId, note),isOrcaMcpHydrated,buildCreateOptsWithStderr,synthesizeOrcaVendorOptionsFromDb,@@ -14585,6 +14632,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)isRemoteInvoke: remoteInvoke,});const projection = inputCoordinator.clearSession(sid, clearBoundary);+ workingDirectoryRecovery.discard(sid);resetAutomaticRecoveryForExplicitStop(sid);// 丢弃缓存的待注入交接 / fork 来源标记:它们是按 clear 之前的历史算出来的,// DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后@@ -17250,12 +17298,13 @@ async function checkWorkDirExists(// 或者 agent 真跑起来时由远端 codex 自己报 ENOENT)。这里直接放行。if (remoteHostId) return true;if (!workingDir?.trim()) return true;+ workingDir = workingDirectoryRecovery.resolve(sessionId, workingDir);const source: AgentKind = agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';// suppressMissingBroadcast: 调用方(SEND 事务)手里还有 DB 权威值可兜底时,// 首检失败只记日志不广播错误横幅——兜底成功的话用户不该看到假错误。const suppress = opts?.suppressMissingBroadcast === true;try {- const stat = await fsp.stat(workingDir);+ const stat = await statWorkingDirectory(workingDir);if (!stat.isDirectory()) {if (suppress) {log.warn('send: workdir not a directory (broadcast suppressed, caller has fallback)', {@@ -17285,24 +17334,41 @@ async function checkWorkDirExists(return false;}}- return true;- } catch {- // app 托管的 dialogue 工作目录(<userData>/dialogues/<日期>/<id>)本来就是- // 空的一次性目录:丢了直接 mkdir 重建放行,不打扰用户(自愈详见- // dialogueWorkdirSelfHeal.ts;legacy userData 前缀由启动 sweep 先行改写)。- const healed = await healMissingDialogueWorkdir(workingDir, dialogueWorkspaceRootDir());- if (healed) {- log.info('send: recreated missing dialogue workdir', { sessionId, workingDir });- return true;+ if (getManagedWorktreeBasePath(normalizedWorkingDir) === null) {+ if (!await workingDirectoryRecovery.recover(sessionId, workingDir)) return false;+ await workingDirectoryRecovery.observe(sessionId, workingDir);}+ return true;+ } catch (error) {// Cindy 托管 worktree 被外部 PR cleanup / 手动 git 命令移除时,先按 DB 中- // 的精确 worktree_path 从本地或 origin tracking 分支重建。普通用户目录绝不- // 猜测 fallback;快照冲突也保持阻断,交给恢复横幅显式处理。+ // 的精确 worktree_path 从本地或 origin tracking 分支重建,保留原代码与快照。const restored = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);if (restored) {log.info('send: restored missing managed worktree', { sessionId, workingDir });return true;}+ // Preserve the existing sibling-path diagnostic before mkdir makes the probe pass.+ // A fuzzy match is a lead for the agent, not authority to switch project identity.+ const unavailable = isUnavailableFilesystemError(error);+ let similar: string | null = null;+ // A missing ordinary/dialogue cwd must not stop the conversation. Prefer a repaired+ // DB path when the caller has one; never turn a managed Git recovery into+ // an empty project, or treat permission/non-directory failures as ENOENT.+ if (+ !suppress &&+ ((error as NodeJS.ErrnoException).code === 'ENOENT' || unavailable) &&+ getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) === null &&+ await workingDirectoryRecovery.recover(sessionId, workingDir, async () => {+ similar = await findSimilarDirOnDisk(workingDir);+ return similar;+ },+ getMaker().listActiveSessions()+ .filter((session) => !session.remoteHostId)+ .map((session) => ({ id: session.id, workingDir: session.workDir })))+ ) {+ log.info('send: recreated missing working directory for conversation', { sessionId, workingDir });+ return true;+ }if (suppress) {log.warn('send: workdir missing (broadcast suppressed, caller has fallback)', {sessionId,@@ -17310,7 +17376,6 @@ async function checkWorkDirExists(});return false;}- const similar = await findSimilarDirOnDisk(workingDir);emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist', similar);return false;}@@ -17320,22 +17385,13 @@ async function checkWorkDirExists(* ENOENT 兜底:扫一下 parent 目录,找一个 trim/大小写 后等于目标 basename 的真实条目。* 命中的最典型场景是 macOS Finder 里目录名末尾带了不可见空格,而 sessions.ts 写库时* 做了 .trim() 把空格砍了 —— DB 里存的路径在磁盘上不存在,但同名带空格的目录是存在的。- * 失败一律返回 null,不要在错误兜底里再抛新错。+ * 普通诊断失败返回 null;文件系统不可用交给 recovery 的统一 fallback。*/async function findSimilarDirOnDisk(workingDir: string): Promise<string | null> {- try {- const parent = path.dirname(workingDir);- const target = path.basename(workingDir);- if (!parent || parent === workingDir || !target) return null;- const entries = await fsp.readdir(parent);- const trimMatch = entries.find((n) => n !== target && n.trim() === target.trim());- if (trimMatch) return path.join(parent, trimMatch);- const ciMatch = entries.find((n) => n !== target && n.toLowerCase() === target.toLowerCase());- if (ciMatch) return path.join(parent, ciMatch);+ return findSimilarWorkingDirectory(workingDir).catch((error) => {+ if (isUnavailableFilesystemError(error)) throw error;return null;- } catch {- return null;- }+ });}function emitWorkDirMissingError(diff --git a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.tsnew file mode 100644index 0000000000..f66977d255--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts@@ -0,0 +1,164 @@+import fsp from 'node:fs/promises';+import path from 'node:path';++export function isUnavailableFilesystemError(error: unknown): boolean {+ return ['EIO', 'ENOTCONN', 'ENODEV', 'ESTALE', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'WORKDIR_PROBE_TIMEOUT']+ .includes((error as NodeJS.ErrnoException | null)?.code ?? '');+}++/** Ordinary local directories only; managed Git worktrees keep their own restore path. */+export function createWorkingDirectoryRecovery(io: {+ stat(dir: string): Promise<{ isDirectory(): boolean; dev?: number }>;+ mkdir(dir: string, opts: { recursive: true }): Promise<unknown>;+ realpath?(dir: string): Promise<string>;+} = fsp, allocateFallback?: (sessionId: string) => Promise<string>) {+ const pending = new Map<string, { workingDir: string; note: string | null; device?: number; fallback?: string }>();+ function entryFor(sessionId: string, dir: string) {+ const entry = pending.get(sessionId);+ if (entry && entry.workingDir !== path.resolve(dir) && entry.fallback !== path.resolve(dir)) {+ pending.delete(sessionId);+ return undefined;+ }+ return entry;+ }+ async function mountUnavailable(dir: string, entry: { device?: number }) {+ const canonical = path.resolve(dir);+ if (process.platform === 'darwin' && canonical.startsWith('/Volumes/')) {+ const volume = canonical.split('/').slice(0, 3).join('/');+ try {+ const [mounted, parent] = await Promise.all([io.stat(volume), io.stat('/Volumes')]);+ // A bare mount-point directory is on the parent filesystem. Exclude+ // aliases such as /Volumes/Macintosh HD -> / before classifying it.+ if (mounted.dev !== undefined && mounted.dev === parent.dev &&+ await io.realpath?.(volume).catch(() => null) === volume) return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || isUnavailableFilesystemError(error)) return true;+ throw error;+ }+ }+ let ancestor = path.resolve(dir);+ while (true) {+ try {+ const current = await io.stat(ancestor);+ return entry.device !== undefined && current.dev !== undefined && current.dev !== entry.device;+ } catch (error) {+ if (isUnavailableFilesystemError(error)) return true;+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ const parent = path.dirname(ancestor);+ if (parent === ancestor) return true; // An unavailable drive/share root cannot be recreated.+ ancestor = parent;+ }+ }+ return {+ async observe(sessionId: string, workingDir: string): Promise<void> {+ const existing = entryFor(sessionId, workingDir);+ if (existing?.device !== undefined || existing?.fallback) return;+ const entry = existing ?? { workingDir: path.resolve(workingDir), note: null };+ pending.set(sessionId, entry);+ const stat = await io.stat(workingDir);+ // Do not revive a record cleared while observing the filesystem.+ if (pending.get(sessionId) !== entry) return;+ pending.set(sessionId, { workingDir: path.resolve(workingDir), note: existing?.note ?? null, device: stat.dev });+ },+ resolve(sessionId: string, workingDir: string): string {+ return entryFor(sessionId, workingDir)?.fallback ?? workingDir;+ },+ isFallback(sessionId: string, workingDir: string): boolean {+ return !!entryFor(sessionId, workingDir)?.fallback;+ },+ async recover(sessionId: string, workingDir: string, similarPath?: string | null | (() => Promise<string | null>), candidates: { id: string; workingDir: string }[] = []): Promise<boolean> {+ entryFor(sessionId, workingDir);+ const sessions = new Map(candidates.map((session) => [session.id, session.workingDir]));+ sessions.set(sessionId, workingDir);+ const entries = [...sessions].map(([id, dir]) => {+ const previous = pending.get(id);+ // Preserve unrelated recovery notes until physical identity is known.+ const entry = previous ?? { workingDir: path.resolve(dir), note: null };+ pending.set(id, entry);+ return { id, dir, entry };+ });+ const own = entryFor(sessionId, workingDir);+ const useFallback = async (): Promise<boolean> => {+ if (!own || !allocateFallback || pending.get(sessionId) !== own) return false;+ const fallback = path.resolve(await allocateFallback(sessionId));+ if (pending.get(sessionId) !== own) return false;+ pending.set(sessionId, { ...own, fallback, note: [+ '[Working directory recovery]',+ `The filesystem for ${JSON.stringify(workingDir)} is unavailable or has changed. Cindy is using ${JSON.stringify(fallback)} as a temporary conversation workspace.`,+ 'The original directory and files have not been restored or copied. Do not create a substitute directory at the original mount location. Files written here stay here when the disk reconnects; do not move them or switch back without discussing it with the user.',+ 'Continue responding. If the task needs the original files, investigate the disconnected disk or network share, or ask the user in this conversation. No folder-selection interface is required.',+ ].join('\n') });+ return true;+ };+ try {+ if (own?.fallback) {+ try { return (await io.stat(own.fallback)).isDirectory(); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false;+ }+ await io.mkdir(own.fallback, { recursive: true });+ if (pending.get(sessionId) !== own) return false;+ pending.set(sessionId, { ...own, note: [+ own.note ?? '[Working directory recovery]',+ `The temporary conversation directory ${JSON.stringify(own.fallback)} was also missing and has been recreated. Its previous files have not been recovered. The original workspace remains ${JSON.stringify(own.workingDir)}; do not create a substitute at that location.`,+ ].join('\n') });+ return true;+ }+ if (own && allocateFallback && await mountUnavailable(workingDir, own)) {+ return await useFallback();+ }+ // A stale probe must not mistake a file, permission error, or a directory+ // restored by someone else for a missing directory.+ try {+ const stat = await io.stat(workingDir);+ return stat.isDirectory();+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ const similar = typeof similarPath === 'function' ? await similarPath() : similarPath;+ await io.mkdir(workingDir, { recursive: true });+ const canonical = await io.realpath?.(workingDir).catch(() => null);+ // Cleanup may have removed this entry while filesystem IO was pending.+ // Do not repopulate it after a clear, archive, delete, or owner change.+ const note = [+ '[Working directory recovery]',+ `The working directory was missing. Cindy recreated the directory at ${JSON.stringify(workingDir)} so this conversation can continue.`,+ 'Only the directory was recreated; its previous files have not been recovered. Do not assume the original project contents are available.',+ ...(similar ? [+ `A similarly named filesystem entry exists at ${JSON.stringify(similar)} (possibly differing only in whitespace or case). Inspect this candidate before reading or creating project files in the recreated directory. It may contain the original project; verify its identity or ask the user before treating it as their workspace.`,+ ] : []),+ 'Continue responding to the user. If their task needs the missing files, investigate the location or recovery options, or ask the user through the conversation. Do not require a folder-selection interface just to continue chatting.',+ ].join('\n');+ await Promise.all(entries.map(async ({ id, dir, entry }) => {+ const matches = path.resolve(dir) === path.resolve(workingDir) ||+ (canonical != null && await io.realpath?.(dir).catch(() => null) === canonical);+ if (matches && pending.get(id) === entry) {+ pending.set(id, { ...entry, workingDir: path.resolve(dir), note });+ }+ }));+ return true;+ } catch (error) {+ // The share may disappear after stat, including during mkdir. Reuse the+ // same fallback transition; never retry a timed-out write on the share.+ if (!own?.fallback && isUnavailableFilesystemError(error)) {+ return useFallback().catch(() => false);+ }+ return false;+ }+ },+ peek(sessionId: string, workingDir?: string): string | null {+ const entry = workingDir === undefined ? pending.get(sessionId) : entryFor(sessionId, workingDir);+ return entry?.note ?? null;+ },+ consume(sessionId: string, expectedNote: string): void {+ const entry = pending.get(sessionId);+ if (entry?.note === expectedNote) pending.set(sessionId, { ...entry, note: null });+ },+ discard(sessionId: string): void {+ pending.delete(sessionId);+ },+ clear(): void {+ pending.clear();+ },+ };+}diff --git a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.tsindex b4f4de1729..27b0950a1b 100644--- a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts+++ b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts@@ -51,6 +51,7 @@ export class WorkdirProbeClientError extends Error {}interface ProbeEntry {+ kind: WorkdirProbeRequest['kind'];id: number;dir: string;key: string;@@ -84,7 +85,8 @@ export class WorkdirProbeHostClient {this.maxQueued = deps.maxQueued ?? DEFAULT_MAX_QUEUED;}- probe(dir: string, key: string, timeoutMs: number): Promise<WorkdirProbeResult> {+ probe(dir: string, key: string, timeoutMs: number, kind: WorkdirProbeRequest['kind'] = 'probe'): Promise<WorkdirProbeResult> {+ key = `${kind}:${key}`;if (this.disposed) {return Promise.reject(new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host is disposed'),@@ -101,6 +103,7 @@ export class WorkdirProbeHostClient {let entry!: ProbeEntry;const probe = new Promise<WorkdirProbeResult>((resolve, reject) => {entry = {+ kind,id: this.nextId++,dir,key,@@ -221,7 +224,7 @@ export class WorkdirProbeHostClient {entry.probeTimer.unref?.();const request: WorkdirProbeRequest = {- kind: 'probe',+ kind: entry.kind,id: entry.id,dir: entry.dir,};diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostClient.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostClient.test.tsindex acddd0aed6..b919824917 100644--- a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostClient.test.ts+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostClient.test.ts@@ -47,6 +47,25 @@ afterEach(() => {});describe('WorkdirProbeHostClient', () => {+ it.each(['mkdir', 'realpath', 'similar'] as const)('isolates %s from stat and ignores its late timeout response', async (kind) => {+ vi.useFakeTimers();+ const { client, children } = createHarness({ maxWorkers: 1 });+ const operation = client.probe('/share/a', '/share/a', 50, kind);+ const failure = operation.catch((error) => error);+ const stat = client.probe('/share/a', '/share/a', 150);+ expect(children[0].posted[0].kind).toBe(kind);+ await vi.advanceTimersByTimeAsync(50);+ await expect(failure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });+ expect(children[0].kill).toHaveBeenCalledOnce();+ children[0].respond();+ expect(children).toHaveLength(1);+ children[0].emit('exit', 0);+ expect(children[1].posted[0].kind).toBe('probe');+ children[1].respond();+ await expect(stat).resolves.toEqual({ ok: true, isDirectory: true });+ client.dispose();+ });+it('single-flights equivalent paths', async () => {const { client, children } = createHarness();diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.tsnew file mode 100644index 0000000000..3c8f6b46b6--- /dev/null+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.ts@@ -0,0 +1,22 @@+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { expect, it } from 'vitest';+import { runDirectoryOperation } from '../workdirProbeHostProcess.js';++it('creates only directories, resolves aliases and retains similar-path diagnostics inside the worker', async () => {+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-directory-worker-'));+ try {+ const dir = path.join(root, 'nested', 'project');+ expect(await runDirectoryOperation({ kind: 'mkdir', id: 1, dir })).toEqual({ ok: true, isDirectory: true });+ expect(await runDirectoryOperation({ kind: 'realpath', id: 2, dir })).toMatchObject({ ok: true, path: await fsp.realpath(dir) });+ expect(await runDirectoryOperation({ kind: 'probe', id: 3, dir })).toMatchObject({ ok: true, isDirectory: true });+ expect(await runDirectoryOperation({ kind: 'similar', id: 4, dir: `${dir} ` })).toMatchObject({ ok: true, path: dir });+ const file = path.join(root, 'file');+ await fsp.writeFile(file, 'keep');+ expect(await runDirectoryOperation({ kind: 'mkdir', id: 5, dir: file })).toMatchObject({ ok: false, code: 'EEXIST' });+ expect(await fsp.readFile(file, 'utf8')).toBe('keep');+ } finally {+ await fsp.rm(root, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/src/main/workdir-probe-host/index.ts b/apps/desktop/src/main/workdir-probe-host/index.tsindex fb2082f68e..0995082c31 100644--- a/apps/desktop/src/main/workdir-probe-host/index.ts+++ b/apps/desktop/src/main/workdir-probe-host/index.ts@@ -8,6 +8,7 @@ import { app, utilityProcess } from 'electron';import { createLogger } from '../logger.js';import { WorkdirProbeHostClient } from './WorkdirProbeHostClient.js';+import type { WorkdirProbeRequest } from './protocol.js';const log = createLogger('workdir-probe-host');@@ -39,6 +40,32 @@ export const workdirProbeHostClient = new WorkdirProbeHostClient({log,});+/** Bounded filesystem identity probe for local cwd recovery; never expose paths to a controller. */+async function directoryOperation(dir: string, kind: WorkdirProbeRequest['kind']) {+ const result = await workdirProbeHostClient.probe(dir, path.resolve(dir), 5_000, kind);+ if (!result.ok) throw Object.assign(new Error('Working directory probe failed'), { code: result.code });+ return result;+}++export async function statWorkingDirectory(dir: string): Promise<{ isDirectory(): boolean; dev?: number }> {+ const result = await directoryOperation(dir, 'probe');+ return { isDirectory: () => result.isDirectory, dev: result.device };+}++export async function mkdirWorkingDirectory(dir: string): Promise<void> {+ await directoryOperation(dir, 'mkdir');+}++export async function realpathWorkingDirectory(dir: string): Promise<string> {+ const result = await directoryOperation(dir, 'realpath');+ if (typeof result.path !== 'string') throw new Error('Invalid resolved directory');+ return result.path;+}++export async function findSimilarWorkingDirectory(dir: string): Promise<string | null> {+ return (await directoryOperation(dir, 'similar')).path ?? null;+}+// 真实 Electron app 一定有 once;条件注册让引用 guard 的纯 Node 单测仍可使用// 只覆盖自身所需字段的窄 electron stub,而不必为未执行的生命周期补整套假实现。if (typeof app.once === 'function') {diff --git a/apps/desktop/src/main/workdir-probe-host/protocol.ts b/apps/desktop/src/main/workdir-probe-host/protocol.tsindex 332df5a12a..ebad97e902 100644--- a/apps/desktop/src/main/workdir-probe-host/protocol.ts+++ b/apps/desktop/src/main/workdir-probe-host/protocol.ts@@ -1,19 +1,19 @@/*** workdir probe host wire format.*- * The utility process only returns a boolean or a stable filesystem error code.- * It never returns the probed path or the host error message to avoid leaking- * local filesystem details across the process boundary.+ * The utility process returns directory status/device identity or a stable filesystem error code.+ * Resolved paths are internal Main/utility data, never controller responses.+ * Host error messages are not returned.*/export interface WorkdirProbeRequest {- kind: 'probe';+ kind: 'probe' | 'mkdir' | 'realpath' | 'similar';id: number;dir: string;}export type WorkdirProbeResult =- | { ok: true; isDirectory: boolean }+ | { ok: true; isDirectory: boolean; device?: number; path?: string | null }| { ok: false; code: string };export interface WorkdirProbeResponse {diff --git a/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.ts b/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.tsindex f231b5a799..c801642d04 100644--- a/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.ts+++ b/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.ts@@ -6,7 +6,8 @@* uncancellable libuv work in Electron's main process.*/-import { stat } from 'node:fs/promises';+import { stat, mkdir, realpath, readdir } from 'node:fs/promises';+import path from 'node:path';import type {WorkdirProbeRequest,@@ -27,22 +28,43 @@ function filesystemErrorCode(error: unknown): string {: 'UNKNOWN';}+export async function runDirectoryOperation(request: WorkdirProbeRequest): Promise<WorkdirProbeResult> {+ try {+ if (request.kind === 'mkdir') {+ await mkdir(request.dir, { recursive: true });+ return { ok: true, isDirectory: true };+ }+ if (request.kind === 'realpath') {+ return { ok: true, isDirectory: true, path: await realpath(request.dir) };+ }+ if (request.kind === 'similar') {+ const parent = path.dirname(request.dir);+ const target = path.basename(request.dir);+ if (!target || parent === request.dir) return { ok: true, isDirectory: false, path: null };+ const entries = await readdir(parent);+ const match = entries.find((n) => n !== target && n.trim() === target.trim()) ??+ entries.find((n) => n !== target && n.toLowerCase() === target.toLowerCase());+ return { ok: true, isDirectory: false, path: match ? path.join(parent, match) : null };+ }+ const entry = await stat(request.dir);+ return { ok: true, isDirectory: entry.isDirectory(), device: entry.dev };+ } catch (error) {+ return { ok: false, code: filesystemErrorCode(error) };+ }+}+if (parentPort) {parentPort.on('message', (event) => {const request = event.data as Partial<WorkdirProbeRequest>;if (- request.kind !== 'probe' ||+ !['probe', 'mkdir', 'realpath', 'similar'].includes(request.kind ?? '') ||typeof request.id !== 'number' ||typeof request.dir !== 'string' ||request.dir.length === 0) {return;}- void stat(request.dir)- .then<WorkdirProbeResult, WorkdirProbeResult>(- (entry) => ({ ok: true, isDirectory: entry.isDirectory() }),- (error) => ({ ok: false, code: filesystemErrorCode(error) }),- )+ void runDirectoryOperation(request as WorkdirProbeRequest).then((result) => {const response: WorkdirProbeResponse = {kind: 'result',diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 39b5b64994..2217eff64e 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -471,6 +471,17 @@ describe('Maker local Pi package generation fence', () => {});describe('Maker session creation singleflight', () => {+ it('reports the effective runtime cwd when recovering an existing task elsewhere', async () => {+ const storage = createStorage();+ await storage.create({ id: 'recovered-cwd', agentKind: 'codex', workDir: '/original', title: 'Existing task', model: 'test-model' });+ const startSession = vi.fn(async () => createHandle({ id: 'recovered-native' }));+ const maker = new Maker({ agents: { codex: createAgent(startSession) }, storage, logger: createLogger() });+ const session = await maker.createSession({ id: 'recovered-cwd', agentKind: 'codex', workingDir: '/conversation', model: 'test-model' });+ expect(startSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir: '/conversation' }));+ expect(session.workDir).toBe('/conversation');+ expect((await storage.get('recovered-cwd'))?.workDir).toBe('/original');+ });+it('binds each rebuilt business session to a fresh runtime instance id', async () => {const seenInstanceIds: string[] = [];const startSession = vi.fn(async (opts: CreateSessionOptions) => {@@ -524,13 +535,18 @@ describe('Maker session creation singleflight', () => {resumeSessionId: 'thread-1',};- const first = maker.createSession(options);- const second = maker.createSession({ ...options });+ const preferences = { userPrompt: 'Original caller prompt', makerMemoryEnabled: true };+ const first = maker.createSession({ ...options, hostStartupPreferences: preferences });+ const second = maker.createSession({ ...options, hostStartupPreferences: { makerMemoryEnabled: false } });expect(startSession).toHaveBeenCalledTimes(1);resolveStart(createHandle({ id: 'thread-1' }));const [firstSession, secondSession] = await Promise.all([first, second]);+ expect(firstSession.hostStartupPreferences).toEqual(preferences);+ preferences.makerMemoryEnabled = false;+ const existingSession = await maker.createSession(options);+ expect(existingSession.hostStartupPreferences).toMatchObject({ userPrompt: 'Original caller prompt', makerMemoryEnabled: true });expect(secondSession).toBe(firstSession);expect(maker.listActiveSessions()).toEqual([firstSession]);expect(created).toHaveBeenCalledTimes(1);diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex ef19bf0d1c..42676c661e 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -37,7 +37,7 @@ import type {import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';import { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';-import { Session, generateSessionId } from './session.js';+import { Session, generateSessionId, type SessionStartupPreferences } from './session.js';import type {AgentSessionHandle,AgentSessionTeardownOptions,@@ -130,6 +130,8 @@ export interface MakerDeps {}export interface CreateSessionOptions extends StartSessionOptions {+ /** Host caller preferences before generated context; retained only by the live Session. */+ hostStartupPreferences?: SessionStartupPreferences;agentKind: AgentKind;/** 可选:UI 显示用 */title?: string;@@ -912,8 +914,9 @@ export class Maker {id: meta.id,sessionInstanceId,agentKind: meta.agentKind,- workDir: meta.workDir,+ workDir: startOpts.workingDir,handle,+ hostStartupPreferences: opts.hostStartupPreferences,capabilities: capabilitiesForSession(meta.agentKind, agent.capabilities, meta.remoteHostId),logger: this.logger,permissionMode: startOpts.permissionMode,diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 6686f929c0..6516f9d598 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -53,6 +53,7 @@ import type {AgentSessionTeardownOptions,BackgroundTaskSnapshot,SendOptions,+ StartSessionOptions,TurnContinuationState,} from './agents/base-agent.js';import {@@ -143,7 +144,12 @@ function parseTurnStallMs(raw: string | undefined): number {return Math.floor(n);}+/** Launch-only caller preferences. Live controls and grants have separate authorities. */+export type SessionStartupPreferences = Readonly<Pick<StartSessionOptions,+ 'userPrompt' | 'makerMemoryEnabled' | 'displayReasoning'>>;+export interface SessionOptions {+ hostStartupPreferences?: SessionStartupPreferences;id: string;/** 与 Agent MCP context 同源的本次内存实例代号;省略时由 Session 自铸。 */sessionInstanceId?: string;@@ -389,6 +395,8 @@ function createSendReservation(generation: number): SendReservation {}export class Session {+ /** Caller preferences before generated context; memory-only recovery input. */+ readonly hostStartupPreferences?: SessionStartupPreferences;readonly id: string;/** business id 可复用;instanceId 精确标识本次内存 Session incarnation。 */readonly instanceId: string;@@ -516,6 +524,8 @@ export class Session {private turnControlState: TurnControlState | null = null;constructor(opts: SessionOptions) {+ this.hostStartupPreferences = opts.hostStartupPreferences+ ? Object.freeze({ ...opts.hostStartupPreferences }) : undefined;this.id = opts.id;this.instanceId = opts.sessionInstanceId ?? generateSessionId();this.agentKind = opts.agentKind;