Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 超时目录探测不再误报工作目录缺失 (#4705)

DavidShenXDc9b6fe28b460
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/helpers/workingDirectoryPreflightHarness.ts b/apps/desktop/src/main/maker-ipc/__tests__/helpers/workingDirectoryPreflightHarness.ts
new file mode 100644
index 0000000000..fc0af28965
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/helpers/workingDirectoryPreflightHarness.ts
@@ -0,0 +1,36 @@
+import path from 'node:path';
+import { vi } from 'vitest';
+import { createWorkingDirectoryRecovery } from '../../workingDirectoryRecovery';
+import { createWorkingDirectoryPreflight, type WorkingDirectoryPreflightDeps } from '../../workingDirectoryPreflight';
+
+/** Real preflight and recovery with in-memory filesystem and main-process adapters. */
+export function createPreflightHarness() {
+ const dir = path.resolve('/project');
+ const directoryStat = { isDirectory: () => true, dev: 7 };
+ const io = { stat: vi.fn(async (_dir: string) => directoryStat), mkdir: vi.fn(async () => {}) };
+ const recovery = createWorkingDirectoryRecovery(io);
+ const recover = vi.spyOn(recovery, 'recover');
+ const emitMissing = vi.fn();
+ const log = { debug: vi.fn(), warn: vi.fn() };
+ const readBoundWorkingDir = vi.fn(async (_id: string): Promise<string | null> => dir);
+ const deps: WorkingDirectoryPreflightDeps = {
+ workingDirectoryRecovery: recovery,
+ statWorkingDirectory: io.stat,
+ readBoundWorkingDir,
+ getUserDataPath: () => path.resolve('/user-data'),
+ isCindyMakeWorktreePath: vi.fn(() => false),
+ assertCindyMakeWorkspace: vi.fn(async () => {}),
+ getManagedWorktreeBasePath: vi.fn(() => null),
+ getManagedWorktreeReadinessForSession: vi.fn(async () => 'gone' as const),
+ findSimilarDirOnDisk: vi.fn(async () => null),
+ listActiveSessions: () => [],
+ emitWorkDirMissingError: emitMissing,
+ workdirLog: log,
+ log,
+ };
+ return { dir, directoryStat, io, recovery, recover, emitMissing, log, readBoundWorkingDir, deps, check: createWorkingDirectoryPreflight(deps) };
+}
+
+export function filesystemError(code: string) {
+ return Object.assign(new Error('filesystem operation failed'), { code });
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 36b8261455..5e72ed61f8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -28,6 +28,7 @@ import type { MakerSessionCreateOpts } from '../sessionRequest';
import { CredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';
import path from 'node:path';
import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
+import { createPreflightHarness, filesystemError } from './helpers/workingDirectoryPreflightHarness';
function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MakerSendTransactionSession {
return {
@@ -101,6 +102,41 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {
}
describe('maker SEND transaction', () => {
+ it('dispatches a bound lazy session after one timed-out probe without probing again at bootstrap', async () => {
+ const h = createPreflightHarness();
+ h.io.stat.mockRejectedValue(filesystemError('WORKDIR_PROBE_TIMEOUT'));
+ const lazySession = createSession({ id: 'lazy-timeout', workDir: h.dir });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => undefined),
+ checkWorkDirExists: h.check,
+ readSessionWorkingDirFromDb: h.readBoundWorkingDir,
+ bootstrapSession: vi.fn(async (opts) => {
+ await h.recovery.observe(opts.id!, h.recovery.resolve(opts.id!, opts.workingDir!));
+ return { session: lazySession, didInjectOrcaInstructions: false, didInjectProjectContext: false };
+ }),
+ });
+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('lazy-timeout', 'hello', {
+ id: 'lazy-timeout', agentKind: 'codex', model: 'gpt-5.4', workingDir: h.dir,
+ })).resolves.toMatchObject({ accepted: true, outcome: { kind: 'session-dispatch', dispatched: true } });
+ expect(h.io.stat).toHaveBeenCalledOnce();
+ expect(h.recover).toHaveBeenCalledWith('lazy-timeout', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ expect(h.log.warn).not.toHaveBeenCalled();
+ expect(lazySession.send).toHaveBeenCalledOnce();
+ });
+
+ it('keeps an unbound probe timeout as an error instead of a WORKDIR_MISSING send result', async () => {
+ const h = createPreflightHarness();
+ const timeout = filesystemError('WORKDIR_PROBE_TIMEOUT');
+ h.io.stat.mockRejectedValue(timeout);
+ h.readBoundWorkingDir.mockResolvedValue(null);
+ const { deps, session } = createDeps({ checkWorkDirExists: h.check });
+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello')).rejects.toBe(timeout);
+ expect(session.send).not.toHaveBeenCalled();
+ expect(h.recover).toHaveBeenCalledWith('session-1', session.workDir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ });
+
it('logs a slash-only DB fallback candidate without exposing the path or changing send behavior', async () => {
const workdirDiagnostics = { info: vi.fn(), warn: vi.fn() };
const { deps } = createDeps({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionWorkingDirectoryProbe.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionWorkingDirectoryProbe.test.ts
new file mode 100644
index 0000000000..0c7c62a5c6
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionWorkingDirectoryProbe.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from 'vitest';
+import { probeSessionWorkingDirectory } from '../sessionWorkingDirectoryProbe';
+
+describe('session working directory probe', () => {
+ it('returns the filesystem result without consulting the session binding', async () => {
+ const stat = { isDirectory: () => true, dev: 7 };
+ const readBoundWorkingDir = vi.fn(async () => 'C:/repo');
+
+ await expect(probeSessionWorkingDirectory('C:/repo', {
+ stat: vi.fn(async () => stat),
+ readBoundWorkingDir,
+ })).resolves.toEqual({ kind: 'stat', stat });
+ expect(readBoundWorkingDir).not.toHaveBeenCalled();
+ });
+
+ it('tolerates a timeout when it is the already-bound session directory', async () => {
+ const stat = vi.fn(async () => {
+ throw Object.assign(new Error('probe timed out'), { code: 'WORKDIR_PROBE_TIMEOUT' });
+ });
+
+ await expect(probeSessionWorkingDirectory('C:\\repo', {
+ stat,
+ readBoundWorkingDir: vi.fn(async () => 'C:/repo/'),
+ })).resolves.toEqual({ kind: 'bound-timeout' });
+ expect(stat).toHaveBeenCalledOnce();
+ });
+
+ it('tolerates a timeout when the persisted binding matches the probed directory', async () => {
+ const timeout = Object.assign(new Error('probe timed out'), { code: 'WORKDIR_PROBE_TIMEOUT' });
+
+ await expect(probeSessionWorkingDirectory('C:/repaired-repo', {
+ stat: vi.fn(async () => { throw timeout; }),
+ readBoundWorkingDir: vi.fn(async () => ['C:/old-live-repo', 'C:/repaired-repo']),
+ })).resolves.toEqual({ kind: 'bound-timeout' });
+ });
+
+ it('rethrows a timeout for an unbound directory instead of classifying it as missing', async () => {
+ const timeout = Object.assign(new Error('probe timed out'), { code: 'WORKDIR_PROBE_TIMEOUT' });
+
+ await expect(probeSessionWorkingDirectory('/stale/repo', {
+ stat: vi.fn(async () => { throw timeout; }),
+ readBoundWorkingDir: vi.fn(async () => '/current/repo'),
+ })).rejects.toBe(timeout);
+ });
+
+ it('preserves non-timeout filesystem errors', async () => {
+ const denied = Object.assign(new Error('access denied'), { code: 'EACCES' });
+
+ await expect(probeSessionWorkingDirectory('/repo', {
+ stat: vi.fn(async () => { throw denied; }),
+ readBoundWorkingDir: vi.fn(),
+ })).rejects.toBe(denied);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflight.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflight.test.ts
new file mode 100644
index 0000000000..77e5057ec9
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflight.test.ts
@@ -0,0 +1,112 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { createWorkingDirectoryPreflight } from '../workingDirectoryPreflight';
+import { createPreflightHarness, filesystemError } from './helpers/workingDirectoryPreflightHarness';
+
+describe('working directory send preflight', () => {
+ it('allows a bound timeout without missing, recovery, or a second bootstrap observation', async () => {
+ const h = createPreflightHarness();
+ h.io.stat.mockRejectedValue(filesystemError('WORKDIR_PROBE_TIMEOUT'));
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(true);
+ await h.recovery.observe('s', h.dir);
+ expect(h.io.stat).toHaveBeenCalledOnce();
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.io.mkdir).not.toHaveBeenCalled();
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ expect(h.log.warn).not.toHaveBeenCalled();
+ expect(h.recovery.resolve('s', h.dir)).toBe(h.dir);
+
+ // No cached permission to continue: the next send checks again.
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(true);
+ expect(h.io.stat).toHaveBeenCalledTimes(2);
+ h.io.stat.mockRejectedValue(filesystemError('ENOENT'));
+ h.recover.mockImplementation(async (_sessionId, _workingDir, _similar, _candidates, _mode, options) => options?.existingFallbackOnly === true);
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(false);
+ expect(h.recover).toHaveBeenCalledTimes(4);
+ expect(h.recover).toHaveBeenNthCalledWith(4, 's', h.dir, expect.any(Function), []);
+ expect(h.emitMissing).toHaveBeenCalledWith('s', h.dir, 'codex', 'not-exist', null);
+ });
+
+ it.each([null, path.resolve('/another-project')])('preserves an unbound timeout (%s) without recovery or missing', async (bound) => {
+ const h = createPreflightHarness();
+ const error = filesystemError('WORKDIR_PROBE_TIMEOUT');
+ h.io.stat.mockRejectedValue(error);
+ h.readBoundWorkingDir.mockResolvedValue(bound);
+ await expect(h.check('s', h.dir, 'codex')).rejects.toBe(error);
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ });
+
+ it.each(['EACCES', 'EIO', 'WORKDIR_PROBE_UNAVAILABLE'])('preserves %s instead of entering missing recovery', async (code) => {
+ const h = createPreflightHarness();
+ const error = filesystemError(code);
+ h.io.stat.mockRejectedValue(error);
+ await expect(h.check('s', h.dir, 'codex')).rejects.toBe(error);
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ expect(h.log.warn).toHaveBeenCalled();
+ });
+
+ it('recovers an explicitly absent ordinary directory without broadcasting missing', async () => {
+ const h = createPreflightHarness();
+ h.io.stat.mockRejectedValue(filesystemError('ENOENT'));
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(true);
+ expect(h.recover).toHaveBeenCalledTimes(2);
+ expect(h.recover).toHaveBeenNthCalledWith(2, 's', h.dir, expect.any(Function), []);
+ expect(h.io.mkdir).toHaveBeenCalledWith(h.dir, { recursive: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ });
+
+ it.each(['ENOENT', 'EACCES', 'WORKDIR_PROBE_TIMEOUT'])('keeps a suppressed %s quiet until the authoritative fallback is tried', async (code) => {
+ const h = createPreflightHarness();
+ h.readBoundWorkingDir.mockResolvedValue(null);
+ h.io.stat.mockRejectedValue(filesystemError(code));
+ await expect(h.check('s', h.dir, 'codex', null, { suppressMissingBroadcast: true })).resolves.toBe(false);
+ expect(h.log.warn).not.toHaveBeenCalled();
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ expect(h.emitMissing).not.toHaveBeenCalled();
+ });
+
+ it('still blocks an explicit non-directory result', async () => {
+ const h = createPreflightHarness();
+ h.io.stat.mockResolvedValue({ isDirectory: () => false, dev: 7 });
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(false);
+ expect(h.emitMissing).toHaveBeenCalledWith('s', h.dir, 'codex', 'not-dir');
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ });
+
+ it('treats ENOTDIR as a non-directory result without entering missing recovery', async () => {
+ const h = createPreflightHarness();
+ h.io.stat.mockRejectedValue(filesystemError('ENOTDIR'));
+ await expect(h.check('s', h.dir, 'codex')).resolves.toBe(false);
+ expect(h.emitMissing).toHaveBeenCalledWith('s', h.dir, 'codex', 'not-dir');
+ expect(h.recover).toHaveBeenCalledWith('s', h.dir, undefined, [], 'ordinary', { existingFallbackOnly: true });
+ });
+
+ it('checks managed worktree readiness before allowing a bound timeout', async () => {
+ const h = createPreflightHarness();
+ h.deps.getManagedWorktreeBasePath = vi.fn(() => h.dir);
+ h.deps.getManagedWorktreeReadinessForSession = vi.fn(async () => 'retry' as const);
+ h.io.stat.mockRejectedValue(filesystemError('WORKDIR_PROBE_TIMEOUT'));
+ const check = createWorkingDirectoryPreflight(h.deps);
+ await expect(check('s', h.dir, 'codex')).resolves.toBe(false);
+ expect(h.deps.getManagedWorktreeReadinessForSession).toHaveBeenCalledWith('s', h.dir);
+ expect(h.emitMissing).toHaveBeenCalledWith('s', h.dir, 'codex', 'not-exist');
+ expect(h.recovery.peek('s', h.dir)).toBeNull();
+ });
+
+ it('does not probe SSH paths on the local host', async () => {
+ const h = createPreflightHarness();
+ await expect(h.check('s', '/remote/repo', 'codex', 'ssh-host')).resolves.toBe(true);
+ expect(h.io.stat).not.toHaveBeenCalled();
+ });
+
+ it('keeps a present managed worktree blocked while restoration is incomplete', async () => {
+ const h = createPreflightHarness();
+ h.deps.getManagedWorktreeBasePath = () => h.dir;
+ h.deps.getManagedWorktreeReadinessForSession = async () => 'retry';
+ await expect(createWorkingDirectoryPreflight(h.deps)('s', h.dir, 'codex')).resolves.toBe(false);
+ expect(h.emitMissing).toHaveBeenCalled();
+ expect(h.io.mkdir).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflightRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflightRecovery.test.ts
index 5c7ab5d77d..41342230e9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflightRecovery.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryPreflightRecovery.test.ts
@@ -1,16 +1,7 @@
-import { readFileSync } from 'node:fs';
import path from 'node:path';
-import { ScriptTarget, transpileModule } from 'typescript';
import { describe, expect, it, vi } from 'vitest';
import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
-
-// Execute the production preflight with isolated IO, without booting Electron.
-const register = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
-const start = register.indexOf('async function checkWorkDirExists(');
-const end = register.indexOf('\n/**', start);
-const compiled = transpileModule(register.slice(start, end), {
- compilerOptions: { target: ScriptTarget.ES2022 },
-}).outputText;
+import { createWorkingDirectoryPreflight } from '../workingDirectoryPreflight';
function harness(originalState: 'EACCES' | 'file' | 'ENOENT' | 'ready', saved = true) {
const original = path.resolve('original-project');
@@ -28,31 +19,25 @@ function harness(originalState: 'EACCES' | 'file' | 'ENOENT' | 'ready', saved =
const allocate = vi.fn(async () => fallback);
const recovery = createWorkingDirectoryRecovery({ stat, mkdir, findFallback }, allocate);
const emit = vi.fn();
- const readiness = vi.fn(async () => 'ready');
+ const readiness = vi.fn(async (): Promise<'ready' | 'gone' | 'retry'> => 'ready');
const managedBase = vi.fn((_dir: string): string | null => null);
const isCindyMake = vi.fn(() => false);
const deps = {
- path,
- app: { getPath: () => path.resolve('test-profile') },
- isCindyMakeManagedWorktreePath: isCindyMake,
- assertCindyMakeWorkspace: vi.fn(async () => {}),
workingDirectoryRecovery: recovery,
statWorkingDirectory: stat,
+ readBoundWorkingDir: vi.fn(async () => original),
+ getUserDataPath: () => path.resolve('test-profile'),
+ isCindyMakeWorktreePath: isCindyMake,
+ assertCindyMakeWorkspace: vi.fn(async () => {}),
getManagedWorktreeBasePath: managedBase,
getManagedWorktreeReadinessForSession: readiness,
- workdirDiagnosticContext: () => ({}),
- workdirDiagnosticId: () => 'redacted',
- workdirDiagnosticErrorCode: (error: NodeJS.ErrnoException) => error.code,
- workdirLog: { warn: vi.fn(), info: vi.fn() },
- log: { warn: vi.fn(), info: vi.fn() },
- emitWorkDirMissingError: emit,
- isUnavailableFilesystemError: () => false,
findSimilarDirOnDisk: vi.fn(async () => null),
- getMaker: () => ({ listActiveSessions: () => [] }),
+ listActiveSessions: () => [],
+ workdirLog: { debug: vi.fn(), warn: vi.fn() },
+ log: { debug: vi.fn(), warn: vi.fn() },
+ emitWorkDirMissingError: emit,
};
- const check = new Function(...Object.keys(deps), compiled + '\nreturn checkWorkDirExists;')(
- ...Object.values(deps),
- ) as (id: string, dir: string, kind: string, remote?: string, opts?: { suppressMissingBroadcast: boolean }) => Promise<boolean>;
+ const check = createWorkingDirectoryPreflight(deps);
return { original, fallback, stat, mkdir, findFallback, allocate, recovery, emit, readiness, managedBase, isCindyMake, check };
}
@@ -74,19 +59,28 @@ describe('persistent ordinary recovery in workdir preflight', () => {
},
);
- it.each(['EACCES', 'file'] as const)('still blocks %s without a saved workspace', async (state) => {
- const h = harness(state, false);
- h.readiness.mockResolvedValue('not-managed');
+ it('preserves EACCES without a saved workspace instead of reporting missing', async () => {
+ const h = harness('EACCES', false);
+ h.readiness.mockResolvedValue('retry');
+ await expect(h.check('task', h.original, 'codex')).rejects.toMatchObject({ code: 'EACCES' });
+ expect(h.recovery.isFallback('task', h.original)).toBe(false);
+ expect(h.allocate).not.toHaveBeenCalled();
+ expect(h.mkdir).not.toHaveBeenCalled();
+ expect(h.emit).not.toHaveBeenCalled();
+ });
+
+ it('blocks a non-directory result without entering missing recovery', async () => {
+ const h = harness('file', false);
expect(await h.check('task', h.original, 'codex')).toBe(false);
expect(h.recovery.isFallback('task', h.original)).toBe(false);
expect(h.allocate).not.toHaveBeenCalled();
expect(h.mkdir).not.toHaveBeenCalled();
- expect(h.emit).toHaveBeenCalledOnce();
+ expect(h.emit).toHaveBeenCalledWith('task', h.original, 'codex', 'not-dir');
});
it('leaves a missing-path first probe to the caller with a DB repair candidate', async () => {
const h = harness('ENOENT', false);
- h.readiness.mockResolvedValue('not-managed');
+ h.readiness.mockResolvedValue('retry');
expect(await h.check('task', h.original, 'codex', undefined, { suppressMissingBroadcast: true })).toBe(false);
expect(h.mkdir).not.toHaveBeenCalled();
expect(h.allocate).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
index bbe853ed05..a6c1dd2e5f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
@@ -10,6 +10,37 @@ afterEach(async () => {
});
describe('working directory conversation recovery', () => {
+ it('accepts a later preflight stat after deferring bootstrap observation', async () => {
+ const io = {
+ stat: vi.fn(async () => ({ isDirectory: () => true, dev: 7 })),
+ mkdir: vi.fn(),
+ };
+ const recovery = createWorkingDirectoryRecovery(io);
+ recovery.deferObservationUntilNextProbe('s', '/repo');
+ await recovery.observe('s', '/repo');
+ expect(io.stat).not.toHaveBeenCalled();
+ await recovery.observe('s', '/repo', { isDirectory: () => true, dev: 7 });
+ await recovery.observe('s', '/repo');
+ expect(io.stat).not.toHaveBeenCalled();
+ });
+
+ it.each(['discard', 'clear', 'move', 'other-session'] as const)(
+ 'does not leak deferred observation across %s',
+ async (change) => {
+ const io = {
+ stat: vi.fn(async () => ({ isDirectory: () => true, dev: 7 })),
+ mkdir: vi.fn(),
+ };
+ const recovery = createWorkingDirectoryRecovery(io);
+ recovery.deferObservationUntilNextProbe('s', '/repo');
+ if (change === 'discard') recovery.discard('s');
+ if (change === 'clear') recovery.clear();
+ const dir = change === 'move' ? '/new-project' : '/repo';
+ await recovery.observe(change === 'other-session' ? 'other' : 's', dir);
+ expect(io.stat).toHaveBeenCalledExactlyOnceWith(dir);
+ },
+ );
+
it.each(['EACCES', 'EIO'])('does not abandon a saved recovery workspace when lookup fails with %s', async (code) => {
const io = {
stat: vi.fn(async () => ({ isDirectory: () => true })),
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bfdf9a4212..c0ae639b62 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -239,8 +239,9 @@ import {
} from '../localDb/client/current.js';
import { createBotRuntimeRestoreCoordinator } from './botRuntimeRestore.js';
import { createWorkingDirectoryRecovery, isUnavailableFilesystemError } from './workingDirectoryRecovery.js';
+import { createWorkingDirectoryPreflight } from './workingDirectoryPreflight.js';
import { allocateDialogueRecoveryWorkspace, findDialogueRecoveryWorkspace, requiredDialogueRecoveryRoot } from './dialogueRecoveryWorkspace.js';
-import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics.js';
+import { workdirDiagnosticContext, workdirDiagnosticErrorCode } from '../workdirDiagnostics.js';
import { statWorkingDirectory, mkdirWorkingDirectory, realpathWorkingDirectory, findSimilarWorkingDirectory } from '../workdir-probe-host/index.js';
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import {
@@ -18115,162 +18116,25 @@ async function materializeCodexImage(
* agentSource 为了让 reducer / 事件类型对齐,老 session 没法准确知道 source 时
* 走 'claude-code' 兜底;banner 不在乎 source,只显示 message。
*/
-async function checkWorkDirExists(
- sessionId: string,
- requestedWorkingDir: string | undefined | null,
- agentKind: AgentKind | undefined,
- remoteHostId?: string | null,
- opts?: { suppressMissingBroadcast?: boolean },
-): Promise<boolean> {
- // 远端 session: workdir 在远端机器上, 本地 fs.stat 必然 ENOENT 但完全没意义。
- // 这条 guard 当初是为本地 session 兜底 "用户在 Finder 把目录删了 / 改名了" 的
- // 场景, 远端走自己的 probe (StartRemoteSessionPanel 创建前 stat-remote-path,
- // 或者 agent 真跑起来时由远端 codex 自己报 ENOENT)。这里直接放行。
- if (remoteHostId) return true;
- if (!requestedWorkingDir?.trim()) return true;
- const cindyMakeWorkspace = isCindyMakeManagedWorktreePath(app.getPath('userData'), requestedWorkingDir);
- if (cindyMakeWorkspace) workingDirectoryRecovery.discard(sessionId);
- let workingDir = workingDirectoryRecovery.resolve(sessionId, requestedWorkingDir);
- const source: AgentKind = agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';
- // suppressMissingBroadcast: 调用方(SEND 事务)手里还有 DB 权威值可兜底时,
- // 首检失败只记日志不广播错误横幅——兜底成功的话用户不该看到假错误。
- const suppress = opts?.suppressMissingBroadcast === true;
- const startedAt = Date.now();
- const diagnosticContext = {
- ...workdirDiagnosticContext(sessionId, workingDir),
- suppressMissingBroadcast: suppress,
- usingFallback: workingDirectoryRecovery.isFallback(sessionId, workingDir),
- };
- try {
- if (cindyMakeWorkspace) await assertCindyMakeWorkspace(app.getPath('userData'), workingDir);
- // Resume the previously selected ordinary workspace before probing a path
- // that may now be inaccessible or a file. Do not allocate a new fallback here.
- if (!cindyMakeWorkspace &&
- !workingDirectoryRecovery.isFallback(sessionId, workingDir) &&
- getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) === null) {
- if (!await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'ordinary', { existingFallbackOnly: true })) {
- workdirLog.warn('workdir preflight rejected', { ...diagnosticContext, reason: 'saved-recovery-lookup-failed' });
- return false;
- }
- workingDir = workingDirectoryRecovery.resolve(sessionId, workingDir);
- }
- const stat = await statWorkingDirectory(workingDir);
- if (!stat.isDirectory()) {
- workdirLog.warn('workdir preflight rejected', { ...diagnosticContext, reason: 'not-directory' });
- if (suppress) {
- log.warn('send: workdir not a directory (broadcast suppressed, caller has fallback)', {
- sessionId,
- workingDir,
- });
- } else {
- emitWorkDirMissingError(sessionId, workingDir, source, 'not-dir');
- }
- return false;
- }
- // Managed worktrees need a stronger readiness check than directory existence: another send
- // may observe `git worktree add` before snapshot apply finishes, and a previous apply conflict
- // deliberately leaves the directory present while keeping the session blocked.
- const normalizedWorkingDir = path.resolve(workingDir).replace(/\\/g, '/');
- if (getManagedWorktreeBasePath(normalizedWorkingDir) !== null) {
- const ready = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
- if (ready !== 'ready') {
- if (ready === 'gone' && !suppress && await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')) return true;
- workdirLog.warn('workdir preflight rejected', { ...diagnosticContext, reason: 'managed-worktree-not-ready' });
- if (suppress) {
- log.warn('send: managed worktree not ready (broadcast suppressed, caller has fallback)', {
- sessionId,
- workingDir,
- });
- } else {
- emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist');
- }
- return false;
- }
- }
- if (!cindyMakeWorkspace && getManagedWorktreeBasePath(normalizedWorkingDir) === null) {
- if (!await workingDirectoryRecovery.recover(sessionId, workingDir)) {
- workdirLog.warn('workdir preflight rejected', { ...diagnosticContext, reason: 'recovery-failed-after-stat' });
- return false;
- }
- await workingDirectoryRecovery.observe(sessionId, workingDir);
- }
- workdirLog.info('workdir preflight ready', {
- ...diagnosticContext,
- usingFallback: workingDirectoryRecovery.isFallback(sessionId, workingDir),
- resolvedDirectoryRef: workdirDiagnosticId(workingDirectoryRecovery.resolve(sessionId, workingDir)),
- elapsedMs: Date.now() - startedAt,
- });
- return true;
- } catch (error) {
- workdirLog.warn('workdir preflight failed', {
- ...diagnosticContext, code: workdirDiagnosticErrorCode(error), elapsedMs: Date.now() - startedAt,
- });
- if (cindyMakeWorkspace) {
- if (!suppress) emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist');
- return false;
- }
- // Cindy 托管 worktree 被外部 PR cleanup / 手动 git 命令移除时,先按 DB 中
- // 的精确 worktree_path 从本地或 origin tracking 分支重建,保留原代码与快照。
- const restored = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
- if (restored === 'ready') {
- workdirLog.info('workdir preflight recovered', { ...diagnosticContext, action: 'managed-worktree-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;
- if (
- restored === 'gone' && !suppress &&
- ((error as NodeJS.ErrnoException).code === 'ENOENT' || unavailable) &&
- getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) !== null &&
- await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')
- ) return true;
- // 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 })))
- ) {
- const resolvedDir = workingDirectoryRecovery.resolve(sessionId, workingDir);
- workdirLog.info('workdir preflight recovered', {
- ...diagnosticContext, code: workdirDiagnosticErrorCode(error),
- resolvedDirectoryRef: workdirDiagnosticId(resolvedDir),
- usingFallback: workingDirectoryRecovery.isFallback(sessionId, workingDir),
- sameDirectory: path.resolve(workingDir) === path.resolve(resolvedDir),
- elapsedMs: Date.now() - startedAt,
- });
- log.info('send: working directory recovery completed', { sessionId, workingDir });
- return true;
- }
- if (suppress) {
- log.warn('send: workdir missing (broadcast suppressed, caller has fallback)', {
- sessionId,
- workingDir,
- });
- return false;
- }
- workdirLog.warn('workdir preflight blocked', {
- ...diagnosticContext, code: workdirDiagnosticErrorCode(error), reportedReason: 'not-exist',
- recoveryEligible: (error as NodeJS.ErrnoException).code === 'ENOENT' || unavailable,
- managedWorktree: getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) !== null,
- similarPathFound: !!similar, elapsedMs: Date.now() - startedAt,
- });
- emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist', similar);
- return false;
- }
-}
-
+const checkWorkDirExists = createWorkingDirectoryPreflight({
+ workingDirectoryRecovery,
+ statWorkingDirectory,
+ readBoundWorkingDir: async (sessionId) => {
+ const liveWorkingDir = getMakerIfReady()?.getSession(sessionId)?.workDir || null;
+ const persistedWorkingDir = await readSessionWorkingDirFromDb(sessionId).catch(() => null);
+ return [liveWorkingDir, persistedWorkingDir];
+ },
+ getUserDataPath: () => app.getPath('userData'),
+ isCindyMakeWorktreePath: isCindyMakeManagedWorktreePath,
+ assertCindyMakeWorkspace,
+ getManagedWorktreeBasePath,
+ getManagedWorktreeReadinessForSession,
+ findSimilarDirOnDisk,
+ listActiveSessions: () => getMaker().listActiveSessions(),
+ emitWorkDirMissingError,
+ workdirLog,
+ log,
+});
/**
* ENOENT 兜底:扫一下 parent 目录,找一个 trim/大小写 后等于目标 basename 的真实条目。
* 命中的最典型场景是 macOS Finder 里目录名末尾带了不可见空格,而 sessions.ts 写库时
diff --git a/apps/desktop/src/main/maker-ipc/sessionWorkingDirectoryProbe.ts b/apps/desktop/src/main/maker-ipc/sessionWorkingDirectoryProbe.ts
new file mode 100644
index 0000000000..b1413f7c6b
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionWorkingDirectoryProbe.ts
@@ -0,0 +1,54 @@
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
+
+export interface SessionWorkingDirectoryStat {
+ isDirectory(): boolean;
+ dev?: number;
+}
+
+export interface SessionWorkingDirectoryProbeDeps {
+ stat(workingDir: string): Promise<SessionWorkingDirectoryStat>;
+ readBoundWorkingDir(): Promise<string | null | readonly (string | null)[]>;
+}
+
+export type SessionWorkingDirectoryProbeResult =
+ | { kind: 'stat'; stat: SessionWorkingDirectoryStat }
+ | { kind: 'bound-timeout' };
+
+function matchesBoundWorkingDir(
+ boundWorkingDir: string | null | readonly (string | null)[],
+ workingDir: string,
+): boolean {
+ const candidates = Array.isArray(boundWorkingDir) ? boundWorkingDir : [boundWorkingDir];
+ const normalizedWorkingDir = normalizeWorkingDirForStorage(workingDir);
+ return candidates.some((candidate) => normalizeWorkingDirForStorage(candidate) === normalizedWorkingDir);
+}
+
+/**
+ * Probe a session cwd once. A timeout is usable evidence that the filesystem
+ * did not answer, but it is not evidence that a directory is missing. Existing
+ * sessions may continue with their already-bound cwd while the next operation
+ * reports the real filesystem error.
+ */
+export async function probeSessionWorkingDirectory(
+ workingDir: string,
+ deps: SessionWorkingDirectoryProbeDeps,
+): Promise<SessionWorkingDirectoryProbeResult> {
+ try {
+ return { kind: 'stat', stat: await deps.stat(workingDir) };
+ } catch (error) {
+ if (workdirErrorCode(error) !== 'WORKDIR_PROBE_TIMEOUT') throw error;
+
+ const boundWorkingDir = await deps.readBoundWorkingDir().catch(() => null);
+ if (matchesBoundWorkingDir(boundWorkingDir, workingDir)) {
+ return { kind: 'bound-timeout' };
+ }
+ throw error;
+ }
+}
+
+export function workdirErrorCode(error: unknown): string | undefined {
+ const code = error && typeof error === 'object'
+ ? (error as { code?: unknown }).code
+ : undefined;
+ return typeof code === 'string' ? code : undefined;
+}
diff --git a/apps/desktop/src/main/maker-ipc/workingDirectoryPreflight.ts b/apps/desktop/src/main/maker-ipc/workingDirectoryPreflight.ts
new file mode 100644
index 0000000000..16bcb2e04d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/workingDirectoryPreflight.ts
@@ -0,0 +1,246 @@
+import path from 'node:path';
+import type { AgentKind } from '@cindy/maker-core';
+import type { Logger } from '../logger.js';
+import type { createWorkingDirectoryRecovery } from './workingDirectoryRecovery.js';
+import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics.js';
+import { probeSessionWorkingDirectory, workdirErrorCode, type SessionWorkingDirectoryStat } from './sessionWorkingDirectoryProbe.js';
+
+/** Main-owned dependencies for the local send preflight; remote sessions bypass it. */
+export interface WorkingDirectoryPreflightDeps {
+ workingDirectoryRecovery: ReturnType<typeof createWorkingDirectoryRecovery>;
+ statWorkingDirectory(dir: string): Promise<SessionWorkingDirectoryStat>;
+ readBoundWorkingDir(sessionId: string): Promise<string | null | readonly (string | null)[]>;
+ getUserDataPath(): string;
+ isCindyMakeWorktreePath(userData: string, dir: string): boolean;
+ assertCindyMakeWorkspace(userData: string, dir: string): Promise<unknown>;
+ getManagedWorktreeBasePath(dir: string): string | null;
+ getManagedWorktreeReadinessForSession(sessionId: string, dir: string): Promise<'ready' | 'gone' | 'retry'>;
+ findSimilarDirOnDisk(dir: string): Promise<string | null>;
+ listActiveSessions(): { id: string; workDir: string; remoteHostId?: string | null }[];
+ emitWorkDirMissingError(sessionId: string, dir: string, source: AgentKind, reason: 'not-exist' | 'not-dir', similar?: string | null): void;
+ workdirLog: Pick<Logger, 'debug' | 'warn'>;
+ log: Pick<Logger, 'debug' | 'warn'>;
+}
+
+/** Timeout is uncertainty, not absence. Keep recovery and missing broadcasts behind evidence. */
+export function createWorkingDirectoryPreflight(deps: WorkingDirectoryPreflightDeps) {
+ const {
+ workingDirectoryRecovery, statWorkingDirectory, readBoundWorkingDir, getUserDataPath,
+ isCindyMakeWorktreePath, assertCindyMakeWorkspace, getManagedWorktreeBasePath,
+ getManagedWorktreeReadinessForSession, findSimilarDirOnDisk, listActiveSessions,
+ emitWorkDirMissingError, workdirLog, log,
+ } = deps;
+ return async function checkWorkDirExists(
+ sessionId: string,
+ requestedWorkingDir: string | undefined | null,
+ agentKind: AgentKind | undefined,
+ remoteHostId?: string | null,
+ opts?: { suppressMissingBroadcast?: boolean },
+ ): Promise<boolean> {
+ // 远端 session: workdir 在远端机器上, 本地 fs.stat 必然 ENOENT 但完全没意义。
+ // 这条 guard 当初是为本地 session 兜底 "用户在 Finder 把目录删了 / 改名了" 的
+ // 场景, 远端走自己的 probe (StartRemoteSessionPanel 创建前 stat-remote-path,
+ // 或者 agent 真跑起来时由远端 codex 自己报 ENOENT)。这里直接放行。
+ if (remoteHostId) return true;
+ if (!requestedWorkingDir?.trim()) return true;
+ const cindyMakeWorkspace = isCindyMakeWorktreePath(getUserDataPath(), requestedWorkingDir);
+ if (cindyMakeWorkspace) workingDirectoryRecovery.discard(sessionId);
+ let workingDir = workingDirectoryRecovery.resolve(sessionId, requestedWorkingDir);
+ const source: AgentKind = agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';
+ // suppressMissingBroadcast: 调用方(SEND 事务)手里还有 DB 权威值可兜底时,
+ // 首检失败只记日志不广播错误横幅——兜底成功的话用户不该看到假错误。
+ const suppress = opts?.suppressMissingBroadcast === true;
+ const startedAt = Date.now();
+ const diagnosticContext = {
+ ...workdirDiagnosticContext(sessionId, workingDir),
+ suppressMissingBroadcast: suppress,
+ usingFallback: workingDirectoryRecovery.isFallback(sessionId, workingDir),
+ };
+ try {
+ if (cindyMakeWorkspace) await assertCindyMakeWorkspace(getUserDataPath(), workingDir);
+ // Reuse a previously selected conversation-recovery directory before probing
+ // the original path. This lookup must not allocate a new directory.
+ if (!cindyMakeWorkspace &&
+ !workingDirectoryRecovery.isFallback(sessionId, workingDir) &&
+ getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) === null) {
+ if (!await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'ordinary', { existingFallbackOnly: true })) {
+ workdirLog.debug('workdir preflight rejected', { ...diagnosticContext, reason: 'saved-recovery-lookup-failed' });
+ return false;
+ }
+ workingDir = workingDirectoryRecovery.resolve(sessionId, workingDir);
+ }
+ const normalizedWorkingDir = path.resolve(workingDir).replace(/\\/g, '/');
+ const managedWorktree = getManagedWorktreeBasePath(normalizedWorkingDir) !== null;
+ const ensureManagedWorktreeReady = async (allowRecovery: boolean): Promise<boolean> => {
+ if (!managedWorktree) return true;
+ const ready = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
+ if (ready === 'ready') return true;
+ if (allowRecovery && ready === 'gone' && !suppress &&
+ await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')) return true;
+ (suppress ? workdirLog.debug : workdirLog.warn)('workdir preflight rejected', { ...diagnosticContext, reason: 'managed-worktree-not-ready' });
+ if (suppress) {
+ log.debug('send: managed worktree not ready (broadcast suppressed, caller has fallback)', {
+ sessionId,
+ workingDir,
+ });
+ } else {
+ emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist');
+ }
+ return false;
+ };
+ const probe = await probeSessionWorkingDirectory(workingDir, {
+ stat: statWorkingDirectory,
+ readBoundWorkingDir: async () => {
+ const boundWorkingDir = await readBoundWorkingDir(sessionId);
+ const resolveBoundWorkingDir = (dir: string | null) =>
+ dir ? workingDirectoryRecovery.resolve(sessionId, dir) : null;
+ if (typeof boundWorkingDir === 'string' || boundWorkingDir === null) {
+ return resolveBoundWorkingDir(boundWorkingDir);
+ }
+ return boundWorkingDir.map(resolveBoundWorkingDir);
+ },
+ });
+ if (probe.kind === 'bound-timeout') {
+ if (!await ensureManagedWorktreeReady(false)) return false;
+ workingDirectoryRecovery.deferObservationUntilNextProbe(sessionId, workingDir);
+ workdirLog.debug('workdir preflight timeout tolerated for bound session', {
+ ...diagnosticContext, code: 'WORKDIR_PROBE_TIMEOUT', reason: 'bound-directory',
+ elapsedMs: Date.now() - startedAt,
+ });
+ return true;
+ }
+ const stat = probe.stat;
+ if (!stat.isDirectory()) {
+ (suppress ? workdirLog.debug : workdirLog.warn)('workdir preflight rejected', { ...diagnosticContext, reason: 'not-directory' });
+ if (suppress) {
+ log.debug('send: workdir not a directory (broadcast suppressed, caller has fallback)', {
+ sessionId,
+ workingDir,
+ });
+ } else {
+ emitWorkDirMissingError(sessionId, workingDir, source, 'not-dir');
+ }
+ return false;
+ }
+ // Managed worktrees need a stronger readiness check than directory existence: another send
+ // may observe `git worktree add` before snapshot apply finishes, and a previous apply conflict
+ // deliberately leaves the directory present while keeping the session blocked.
+ if (!await ensureManagedWorktreeReady(true)) return false;
+ if (!cindyMakeWorkspace && getManagedWorktreeBasePath(normalizedWorkingDir) === null) {
+ if (!await workingDirectoryRecovery.recover(sessionId, workingDir)) {
+ (suppress ? workdirLog.debug : workdirLog.warn)('workdir preflight rejected', { ...diagnosticContext, reason: 'recovery-failed-after-stat' });
+ return false;
+ }
+ await workingDirectoryRecovery.observe(sessionId, workingDir, stat);
+ }
+ return true;
+ } catch (error) {
+ const errorCode = workdirErrorCode(error);
+ const reportProbeFailure = suppress || errorCode === 'WORKDIR_PROBE_TIMEOUT' ? workdirLog.debug : workdirLog.warn;
+ reportProbeFailure('workdir preflight failed', {
+ ...diagnosticContext, code: workdirDiagnosticErrorCode(error), elapsedMs: Date.now() - startedAt,
+ });
+ // A timeout means the filesystem did not answer before the safety deadline.
+ // It does not prove that the directory is gone, so never enter recovery or
+ // report WORKDIR_MISSING from this branch. A caller using a DB fallback may
+ // still probe that authoritative path after receiving false with suppression.
+ if (errorCode === 'WORKDIR_PROBE_TIMEOUT') {
+ if (suppress) {
+ log.debug('send: workdir probe timed out (broadcast suppressed, caller has fallback)', {
+ sessionId, workingDir,
+ });
+ return false;
+ }
+ throw error;
+ }
+ // ENOTDIR proves that a path component is not a directory, while other
+ // permission, I/O and transport failures must keep their original error.
+ if (errorCode === 'ENOTDIR') {
+ (suppress ? workdirLog.debug : workdirLog.warn)('workdir preflight rejected', { ...diagnosticContext, reason: 'not-directory' });
+ if (suppress) {
+ log.debug('send: workdir not a directory (broadcast suppressed, caller has fallback)', {
+ sessionId,
+ workingDir,
+ });
+ } else {
+ emitWorkDirMissingError(sessionId, workingDir, source, 'not-dir');
+ }
+ return false;
+ }
+ // Only ENOENT proves that a directory is absent. Permission, I/O and
+ // transport failures must keep their original error instead of becoming a
+ // misleading WORKDIR_MISSING report.
+ if (errorCode !== 'ENOENT') {
+ if (suppress) {
+ log.debug('send: workdir probe unavailable (broadcast suppressed, caller has fallback)', {
+ sessionId, workingDir, code: workdirDiagnosticErrorCode(error),
+ });
+ return false;
+ }
+ throw error;
+ }
+ if (cindyMakeWorkspace) {
+ if (!suppress) emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist');
+ return false;
+ }
+ // Cindy 托管 worktree 被外部 PR cleanup / 手动 git 命令移除时,先按 DB 中
+ // 的精确 worktree_path 从本地或 origin tracking 分支重建,保留原代码与快照。
+ const restored = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
+ if (restored === 'ready') {
+ workdirLog.debug('workdir preflight recovered', { ...diagnosticContext, action: 'managed-worktree-restored' });
+ log.debug('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.
+ let similar: string | null = null;
+ if (
+ restored === 'gone' && !suppress &&
+ errorCode === 'ENOENT' &&
+ getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) !== null &&
+ await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')
+ ) return true;
+ // 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 &&
+ errorCode === 'ENOENT' &&
+ getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) === null &&
+ await workingDirectoryRecovery.recover(sessionId, workingDir, async () => {
+ similar = await findSimilarDirOnDisk(workingDir!);
+ return similar;
+ },
+ listActiveSessions()
+ .filter((session) => !session.remoteHostId)
+ .map((session) => ({ id: session.id, workingDir: session.workDir })))
+ ) {
+ const resolvedDir = workingDirectoryRecovery.resolve(sessionId, workingDir);
+ workdirLog.debug('workdir preflight recovered', {
+ ...diagnosticContext, code: workdirDiagnosticErrorCode(error),
+ resolvedDirectoryRef: workdirDiagnosticId(resolvedDir),
+ usingFallback: workingDirectoryRecovery.isFallback(sessionId, workingDir),
+ sameDirectory: path.resolve(workingDir) === path.resolve(resolvedDir),
+ elapsedMs: Date.now() - startedAt,
+ });
+ log.debug('send: working directory recovery completed', { sessionId, workingDir });
+ return true;
+ }
+ if (suppress) {
+ log.debug('send: workdir missing (broadcast suppressed, caller has fallback)', {
+ sessionId,
+ workingDir,
+ });
+ return false;
+ }
+ workdirLog.warn('workdir preflight blocked', {
+ ...diagnosticContext, code: workdirDiagnosticErrorCode(error), reportedReason: 'not-exist',
+ recoveryEligible: errorCode === 'ENOENT',
+ managedWorktree: getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) !== null,
+ similarPathFound: !!similar, elapsedMs: Date.now() - startedAt,
+ });
+ emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist', similar);
+ return false;
+ }
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
index 87a59ae68a..ab9a3a5ac0 100644
--- a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
+++ b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
@@ -35,7 +35,7 @@ export function createWorkingDirectoryRecovery(io: {
requiredRoot?(dir: string): string | undefined;
findFallback?(sessionId: string, workingDir: string): Promise<string | undefined>;
} = fsp, allocateFallback?: (sessionId: string, workingDir: string, mode: 'ordinary' | 'unrestored-worktree') => Promise<string>, log?: WorkdirDiagnosticLogger) {
- const pending = new Map<string, { workingDir: string; note: string | null; device?: number; fallback?: string }>();
+ const pending = new Map<string, { workingDir: string; note: string | null; device?: number; fallback?: string; observationDeferred?: boolean }>();
function entryFor(sessionId: string, dir: string) {
const entry = pending.get(sessionId);
if (entry && entry.workingDir !== path.resolve(dir) && entry.fallback !== path.resolve(dir)) {
@@ -106,12 +106,24 @@ export function createWorkingDirectoryRecovery(io: {
}
}
return {
- async observe(sessionId: string, workingDir: string): Promise<void> {
+ // The send preflight already spent its deadline. Bootstrap must not probe
+ // again just to collect device metadata. A later successful preflight can
+ // supply its stat; this flag never bypasses the next send's existence check.
+ deferObservationUntilNextProbe(sessionId: string, workingDir: string): void {
+ const entry = entryFor(sessionId, workingDir) ?? { workingDir: path.resolve(workingDir), note: null };
+ pending.set(sessionId, { ...entry, observationDeferred: true });
+ },
+ async observe(
+ sessionId: string,
+ workingDir: string,
+ observedStat?: { isDirectory(): boolean; dev?: number },
+ ): Promise<void> {
const existing = entryFor(sessionId, workingDir);
if (existing?.device !== undefined || existing?.fallback) return;
+ if (existing?.observationDeferred && !observedStat) return;
const entry = existing ?? { workingDir: path.resolve(workingDir), note: null };
pending.set(sessionId, entry);
- const stat = await io.stat(workingDir);
+ const stat = observedStat ?? 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 });
diff --git a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
index 6164256e27..009a7d8c38 100644
--- a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
+++ b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
@@ -27,7 +27,7 @@ export interface WorkdirProbeChildLike {
}
export interface WorkdirProbeLoggerLike {
- info?(...args: unknown[]): void;
+ debug?(...args: unknown[]): void;
warn(...args: unknown[]): void;
}
@@ -206,7 +206,6 @@ export class WorkdirProbeHostClient {
const child = this.deps.fork();
const worker: ProbeWorker = { child, id: this.nextWorkerId++ };
this.workers.push(worker);
- this.deps.log.info?.('workdir probe worker created', { workerId: worker.id, ...this.poolDiagnostics() });
child.on('message', (message) => {
this.handleMessage(worker, message);
});
@@ -276,12 +275,12 @@ export class WorkdirProbeHostClient {
if (entry.probeTimer) clearTimeout(entry.probeTimer);
worker.active = undefined;
if (!message.result.ok) {
- this.deps.log.warn('workdir probe filesystem result', {
+ this.deps.log.debug?.('workdir probe filesystem result', {
...this.probeDiagnostics(entry), code: workdirDiagnosticErrorCode(message.result),
reason: 'filesystem-error',
});
} else if (entry.kind === 'probe' && !message.result.isDirectory) {
- this.deps.log.warn('workdir probe filesystem result', {
+ this.deps.log.debug?.('workdir probe filesystem result', {
...this.probeDiagnostics(entry), reason: 'not-directory',
});
}
@@ -297,8 +296,9 @@ export class WorkdirProbeHostClient {
worker.active = undefined;
if (entry?.probeTimer) clearTimeout(entry.probeTimer);
if (entry) this.rejectProbe(entry, error, reason);
- this.deps.log.warn('workdir probe worker termination requested', {
- workerId: worker.id, requestId: worker.lastRequestId, reason, ...this.poolDiagnostics(),
+ this.deps.log.debug?.('workdir probe worker termination requested', {
+ workerId: worker.id, requestId: worker.lastRequestId, reason,
+ ...this.poolDiagnostics(),
});
try {
if (!worker.child.kill()) {
@@ -325,7 +325,7 @@ export class WorkdirProbeHostClient {
if (entry) this.rejectProbe(entry,
new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host exited'), 'host-exited',
);
- this.deps.log.info?.('workdir probe worker exited', {
+ this.deps.log.debug?.('workdir probe worker exited', {
workerId: worker.id, requestId: worker.lastRequestId, exitCode: code,
terminationRequested: worker.terminating === true,
terminationWaitMs: worker.terminationRequestedAt === undefined ? null : Date.now() - worker.terminationRequestedAt,
@@ -360,7 +360,8 @@ export class WorkdirProbeHostClient {
}
private rejectProbe(entry: ProbeEntry, error: WorkdirProbeClientError, reason: string, cause?: unknown): void {
- this.deps.log.warn('workdir probe failed', {
+ const report = error.code === 'WORKDIR_PROBE_TIMEOUT' ? this.deps.log.debug : this.deps.log.warn;
+ report?.('workdir probe failed', {
...this.probeDiagnostics(entry), reason, code: workdirDiagnosticErrorCode(error),
...(cause === undefined ? {} : { causeCode: workdirDiagnosticErrorCode(cause) }),
});
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.ts
index 97f088a31e..abf2a42a2f 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
@@ -30,7 +30,7 @@ class FakeChild extends EventEmitter implements WorkdirProbeChildLike {
function createHarness(options: { maxWorkers?: number; maxQueued?: number } = {}) {
const children: FakeChild[] = [];
- const log = { info: vi.fn(), warn: vi.fn() };
+ const log = { debug: vi.fn(), warn: vi.fn() };
const client = new WorkdirProbeHostClient({
fork: () => {
const child = new FakeChild();
@@ -48,6 +48,17 @@ afterEach(() => {
});
describe('WorkdirProbeHostClient', () => {
+ it('keeps successful and non-directory polling results out of release warnings', async () => {
+ const { client, children, log } = createHarness();
+ for (let i = 0; i < 20; i++) {
+ const result = client.probe('/polled/dir', '/polled/dir', 1000);
+ children[0].respond(i % 2 === 0);
+ await expect(result).resolves.toEqual({ ok: true, isDirectory: i % 2 === 0 });
+ }
+ expect(log.warn).not.toHaveBeenCalled();
+ client.dispose();
+ });
+
it('identifies queue timeout before any request reaches the worker', async () => {
vi.useFakeTimers();
const { client, children, log } = createHarness({ maxWorkers: 1 });
@@ -56,7 +67,7 @@ describe('WorkdirProbeHostClient', () => {
await vi.advanceTimersByTimeAsync(50);
expect(await queued).toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });
expect(children[0].posted).toHaveLength(1);
- expect(log.warn).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({
+ expect(log.debug).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({
reason: 'queue-timeout', phase: 'before-dispatch', requestId: 2,
timeoutMs: 50, elapsedMs: 50, queueWaitMs: 50, responseWaitMs: null,
activeWorkers: 1, terminatingWorkers: 0,
@@ -75,11 +86,11 @@ describe('WorkdirProbeHostClient', () => {
children[0].emit('exit', 9);
await vi.advanceTimersByTimeAsync(50);
expect(await queued).toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });
- expect(log.warn).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({
+ expect(log.debug).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({
reason: 'response-timeout', phase: 'waiting-result', requestId: 2, workerId: 2,
elapsedMs: 150, queueWaitMs: 100, responseWaitMs: 50,
}));
- expect(log.info).toHaveBeenCalledWith('workdir probe worker exited', expect.objectContaining({
+ expect(log.debug).toHaveBeenCalledWith('workdir probe worker exited', expect.objectContaining({
workerId: 1, requestId: 1, exitCode: 9, terminationRequested: true,
}));
client.dispose();
@@ -97,7 +108,7 @@ describe('WorkdirProbeHostClient', () => {
if (reason === 'host-error') children[0].emit('error', 'private-type', 'private-location', 'private-report');
expect(await failure).toMatchObject({ code: 'WORKDIR_PROBE_UNAVAILABLE' });
expect(log.warn).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({ reason, requestId: 2 }));
- expect(JSON.stringify([...log.warn.mock.calls, ...log.info.mock.calls])).not.toContain('private');
+ expect(JSON.stringify([...log.warn.mock.calls, ...log.debug.mock.calls])).not.toContain('private');
client.dispose();
});
@@ -117,10 +128,11 @@ describe('WorkdirProbeHostClient', () => {
const result = client.probe('/private/dir', '/private/dir', 1000);
children[0].emit('message', { kind: 'result', id: 1, result: { ok: false, code } });
await expect(result).resolves.toEqual({ ok: false, code });
- expect(log.warn).toHaveBeenCalledWith('workdir probe filesystem result', expect.objectContaining({
+ expect(log.debug).toHaveBeenCalledWith('workdir probe filesystem result', expect.objectContaining({
reason: 'filesystem-error', code: code === 'PRIVATE_CREDENTIAL' ? 'UNKNOWN' : code, requestId: 1,
}));
- expect(JSON.stringify(log.warn.mock.calls)).not.toContain('PRIVATE_CREDENTIAL');
+ expect(log.warn).not.toHaveBeenCalled();
+ expect(JSON.stringify(log.debug.mock.calls)).not.toContain('PRIVATE_CREDENTIAL');
client.dispose();
});