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。

feat(diagnostics): add privacy-safe working directory tracing

Lizid1a2b323bce3
diff --git a/apps/desktop/src/main/__tests__/workdirDiagnostics.test.ts b/apps/desktop/src/main/__tests__/workdirDiagnostics.test.ts
new file mode 100644
index 0000000000..323c5e5ad9
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/workdirDiagnostics.test.ts
@@ -0,0 +1,33 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics';
+
+describe('working directory diagnostic privacy', () => {
+ it('correlates normalized paths without exposing directories or session contents', () => {
+ const dir = path.resolve('private-project');
+ const context = workdirDiagnosticContext('private-session', dir);
+ expect(context.directoryRef).toBe(workdirDiagnosticId(path.join(dir, '.')));
+ expect(context.directoryRef).not.toBe(workdirDiagnosticId(path.join(dir, 'other')));
+ expect(context.sessionRef).not.toBe(workdirDiagnosticContext('other-session', dir).sessionRef);
+ expect(context.sessionRef).toMatch(/^[a-f0-9]{16}$/);
+ expect(context.directoryRef).toMatch(/^[a-f0-9]{16}$/);
+ expect(JSON.stringify(context)).not.toContain('private');
+ });
+
+ it('does not reuse directory references across module lifetimes', async () => {
+ const dir = path.resolve('private-project');
+ const before = workdirDiagnosticId(dir);
+ vi.resetModules();
+ const fresh = await import('../workdirDiagnostics');
+ expect(fresh.workdirDiagnosticId(dir)).not.toBe(before);
+ });
+
+ it.each(['ENOENT', 'EACCES', 'EIO', 'WORKDIR_PROBE_TIMEOUT', 'WORKDIR_PROBE_UNAVAILABLE'])('retains only known error codes: %s', (code) => {
+ const error = Object.assign(new Error('private path and credentials'), { code });
+ expect(workdirDiagnosticErrorCode(error)).toBe(code);
+ });
+
+ it.each([null, undefined, {}, { code: 42 }, { code: 'PRIVATE_CREDENTIAL' }, new Error('private-project')])('does not copy arbitrary error details: %j', (error) => {
+ expect(workdirDiagnosticErrorCode(error)).toBe('UNKNOWN');
+ });
+});
diff --git a/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts b/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
index 850b93b748..8767cc67de 100644
--- a/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
+++ b/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
@@ -11,6 +11,15 @@ import { describe, expect, it } from 'vitest';
import { isAllowedScope, __testing } from '../sourceAllowlist';
+describe('working directory diagnostics scope', () => {
+ it('allows only the path-free exact scope, not content-bearing roots or future children', () => {
+ expect(isAllowedScope('workdir-diagnostics')).toBe(true);
+ for (const scope of ['workdir-diagnostics/paths', 'workdir-diagnostics:paths', 'r:workdir-diagnostics', 'maker-ipc', 'workdir-probe-host']) {
+ expect(isAllowedScope(scope)).toBe(false);
+ }
+ });
+});
+
describe('放行:基础设施来源', () => {
it.each([
['lifecycle', '退出编排与 render-process-gone'],
diff --git a/apps/desktop/src/main/log-upload/sourceAllowlist.ts b/apps/desktop/src/main/log-upload/sourceAllowlist.ts
index 2e6e747430..ddebb7bab1 100644
--- a/apps/desktop/src/main/log-upload/sourceAllowlist.ts
+++ b/apps/desktop/src/main/log-upload/sourceAllowlist.ts
@@ -112,6 +112,7 @@ const ALLOWED_ROOT_SCOPES: readonly string[] = [
* 不要把一个混着路径的 scope 整体放行。
*/
const ALLOWED_EXACT_SCOPES: readonly string[] = [
+ 'workdir-diagnostics',
'device-link', // 服务初始化、relay 连接/断开/重连、心跳
'device-link:cross-process-lock', // 跨进程锁的获取与释放(只有锁状态,无路径)
// 主库打开 / migration / schema 漂移 / 完整性 / fatal —— bare `localDb` 只打这些基础设施
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 4205ece9b2..b033ba93e3 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -99,6 +99,21 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {
}
describe('maker SEND transaction', () => {
+ 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({
+ workdirDiagnostics,
+ readSessionWorkingDirFromDb: vi.fn(async () => 'C:/repo'),
+ });
+ const transaction = createMakerSendTransaction(deps);
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).resolves.toMatchObject({ accepted: true });
+ expect(workdirDiagnostics.info).toHaveBeenCalledWith('workdir DB fallback candidate', expect.objectContaining({
+ source: 'live', sameNormalizedDirectory: true,
+ }));
+ expect(JSON.stringify(workdirDiagnostics.info.mock.calls)).not.toContain('repo');
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ });
+
it('stamps device-link provenance at the enqueue boundary and rejects forged local values', () => {
const item = { clientId: 'input-1', text: 'hello' } as unknown as AgentInputQueuedMessage;
expect(stampTrustedDeviceLinkQueuedOrigin(item, true)).toMatchObject({
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 bd9db51118..e23eaa4464 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,82 @@ afterEach(async () => {
});
describe('working directory conversation recovery', () => {
+ it('records same-directory fallback and a later failed fallback probe without changing recovery behavior', async () => {
+ const dir = path.resolve('/private/dialogue');
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const recovery = createWorkingDirectoryRecovery({
+ stat: async () => { throw Object.assign(new Error('private-project'), { code: 'WORKDIR_PROBE_TIMEOUT' }); },
+ mkdir: vi.fn(),
+ }, async () => dir, log);
+ expect(await recovery.recover('private-session', dir)).toBe(true);
+ expect(log.info).toHaveBeenCalledWith('workdir recovery completed', expect.objectContaining({
+ action: 'fallback-selected', sameDirectory: true,
+ }));
+ expect(log.warn).toHaveBeenCalledWith('workdir recovery unavailable', expect.objectContaining({
+ reason: 'ancestor-probe-failed', code: 'WORKDIR_PROBE_TIMEOUT',
+ }));
+ expect(await recovery.recover('private-session', dir)).toBe(false);
+ expect(log.warn).toHaveBeenCalledWith('workdir recovery attempt failed', expect.objectContaining({
+ stage: 'fallback-stat', code: 'WORKDIR_PROBE_TIMEOUT', usingFallback: true,
+ }));
+ expect(JSON.stringify([...log.info.mock.calls, ...log.warn.mock.calls])).not.toContain('private');
+ });
+
+ it('logs original directory creation separately from fallback allocation', async () => {
+ const dir = path.resolve('/private/project');
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const recovery = createWorkingDirectoryRecovery({
+ stat: async (target) => {
+ if (target === dir) throw Object.assign(new Error('private missing directory'), { code: 'ENOENT' });
+ return { isDirectory: () => true, dev: 1 };
+ }, mkdir: vi.fn(),
+ }, async () => path.resolve('/private/fallback'), log);
+ expect(await recovery.recover('private-session', dir, '/private/similar')).toBe(true);
+ expect(log.info).toHaveBeenCalledExactlyOnceWith('workdir recovery directory created', expect.objectContaining({
+ action: 'directory-recreated', code: 'ENOENT', similarPathFound: true,
+ }));
+ expect(JSON.stringify(log.info.mock.calls)).not.toContain('private');
+ });
+
+ it('records changed device identity before selecting fallback', async () => {
+ const log = { info: vi.fn(), warn: vi.fn() };
+ let device = 1;
+ const recovery = createWorkingDirectoryRecovery({
+ stat: async () => ({ isDirectory: () => true, dev: device }), mkdir: vi.fn(),
+ }, async () => path.resolve('/private/fallback'), log);
+ const dir = path.resolve('/private/project');
+ await recovery.observe('private-session', dir);
+ device = 2;
+ expect(await recovery.recover('private-session', dir)).toBe(true);
+ expect(log.warn).toHaveBeenCalledWith('workdir recovery unavailable', expect.objectContaining({
+ reason: 'device-changed', expectedDevice: 1, actualDevice: 2,
+ }));
+ expect(log.info).toHaveBeenCalledWith('workdir recovery completed', expect.objectContaining({ action: 'fallback-selected', sameDirectory: false }));
+ });
+
+ it.each(['EACCES', 'ENOSPC'])('records the stage and code of failed original directory creation: %s', async (code) => {
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const dir = path.resolve('/private/project');
+ const recovery = createWorkingDirectoryRecovery({
+ stat: async (target) => {
+ if (target === dir) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return { isDirectory: () => true, dev: 1 };
+ },
+ mkdir: async () => { throw Object.assign(new Error('private details'), { code }); },
+ }, async () => path.resolve('/private/fallback'), log);
+ expect(await recovery.recover('private-session', dir)).toBe(false);
+ expect(log.warn).toHaveBeenCalledWith('workdir recovery attempt failed', expect.objectContaining({ stage: 'original-mkdir', code }));
+ expect(log.info).not.toHaveBeenCalled();
+ });
+
+ it('does not emit recovery messages for healthy checks', async () => {
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const recovery = createWorkingDirectoryRecovery({ stat: async () => ({ isDirectory: () => true, dev: 1 }), mkdir: vi.fn() }, undefined, log);
+ expect(await recovery.recover('private-session', path.resolve('/private/project'))).toBe(true);
+ expect(log.info).not.toHaveBeenCalled();
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
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');
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index f3c9a697b1..b0648a35e2 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -13,6 +13,8 @@ import {
} from '@cindy/maker-core';
import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
+import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId, type WorkdirDiagnosticLogger } from '../workdirDiagnostics.js';
import {
createHostSendFailure,
@@ -475,6 +477,7 @@ export interface MakerSendTransactionDeps {
*/
isCindyMakeSession?(sessionId: string): Promise<boolean>;
log: MakerSendTransactionLog;
+ workdirDiagnostics?: WorkdirDiagnosticLogger;
}
export interface MakerSendTransaction {
@@ -649,8 +652,19 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
sessionId: string,
createOpts: CreateOpts,
): Promise<boolean> {
- const dbDir = await deps.readSessionWorkingDirFromDb(sessionId).catch(() => null);
+ const dbDir = await deps.readSessionWorkingDirFromDb(sessionId).catch((error) => {
+ deps.workdirDiagnostics?.warn('workdir DB lookup failed', {
+ ...workdirDiagnosticContext(sessionId, createOpts.workingDir), source: 'bootstrap',
+ code: workdirDiagnosticErrorCode(error),
+ });
+ return null;
+ });
const fallbackDir = dbDir && dbDir !== createOpts.workingDir ? dbDir : null;
+ if (fallbackDir) deps.workdirDiagnostics?.info('workdir DB fallback candidate', {
+ ...workdirDiagnosticContext(sessionId, createOpts.workingDir), source: 'bootstrap',
+ dbDirectoryRef: workdirDiagnosticId(fallbackDir),
+ sameNormalizedDirectory: normalizeWorkingDirForStorage(fallbackDir) === normalizeWorkingDirForStorage(createOpts.workingDir),
+ });
const ok = fallbackDir
? await deps.checkWorkDirExists(
sessionId,
@@ -910,9 +924,20 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
// 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)
+ ? await deps.readSessionWorkingDirFromDb(sessionId).catch((error) => {
+ deps.workdirDiagnostics?.warn('workdir DB lookup failed', {
+ ...workdirDiagnosticContext(sessionId, sess!.workDir), source: 'live',
+ code: workdirDiagnosticErrorCode(error),
+ });
+ return null;
+ })
: null;
const fallbackDir = dbDir && dbDir !== sess.workDir ? dbDir : null;
+ if (fallbackDir) deps.workdirDiagnostics?.info('workdir DB fallback candidate', {
+ ...workdirDiagnosticContext(sessionId, sess.workDir), source: 'live',
+ dbDirectoryRef: workdirDiagnosticId(fallbackDir),
+ sameNormalizedDirectory: normalizeWorkingDirForStorage(fallbackDir) === normalizeWorkingDirForStorage(sess.workDir),
+ });
const ok = await deps.checkWorkDirExists(
sessionId,
sess.workDir,
@@ -930,6 +955,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
((sess.agentKind === 'claude-code' || sess.agentKind === 'pi') &&
!!deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir)));
if ((!ok && fallbackDir) || needsCwdRefresh) {
+ deps.workdirDiagnostics?.info('workdir runtime refresh requested', {
+ ...workdirDiagnosticContext(sessionId, sess.workDir),
+ reason: needsCwdRefresh ? 'recovered-directory' : 'db-fallback',
+ targetDirectoryRef: workdirDiagnosticId(needsCwdRefresh ? recoveredDir : fallbackDir!),
+ });
const supplied = (createOpts as CreateOpts | undefined) ??
await deps.readWorkingDirectoryRecoveryCreateOpts(sessionId);
const startupPreferences = sess.hostStartupPreferences ?? {};
@@ -949,6 +979,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
requestedSendOpts.fromDeviceLinkClient === true,
'workdir',
);
+ deps.workdirDiagnostics?.info('workdir runtime refresh completed', {
+ ...workdirDiagnosticContext(sessionId, co.workingDir), outcome: recovered.kind,
+ });
if (recovered.kind === 'failure') return recovered.result;
sess = recovered.session;
} else if (!ok) {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 8f158e402e..2c758a0342 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -232,6 +232,7 @@ import {
} from '../localDb/client/current.js';
import { createBotRuntimeRestoreCoordinator } from './botRuntimeRestore.js';
import { createWorkingDirectoryRecovery, isUnavailableFilesystemError } from './workingDirectoryRecovery.js';
+import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics.js';
import { statWorkingDirectory, mkdirWorkingDirectory, realpathWorkingDirectory, findSimilarWorkingDirectory } from '../workdir-probe-host/index.js';
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import {
@@ -1098,8 +1099,9 @@ import { handleSessionEvent, type SessionEventDependencies } from './sessionEven
import { installSessionTurnObserver } from './sessionTurnObserver.js';
const log = createLogger('maker-ipc');
+const workdirLog = createLogger('workdir-diagnostics');
const workingDirectoryRecovery = createWorkingDirectoryRecovery({ stat: statWorkingDirectory, mkdir: mkdirWorkingDirectory, realpath: realpathWorkingDirectory }, async (sessionId) =>
- ensureDialogueWorkspaceDir(sessionId, Date.now()));
+ ensureDialogueWorkspaceDir(sessionId, Date.now()), workdirLog);
function localModelWindowSwitchErrorCode(code: IpcErrorCode): IpcErrorCode {
return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;
@@ -6543,7 +6545,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}> {
if (o.id && o.workingDir && !o.remoteHostId) {
o.workingDir = workingDirectoryRecovery.resolve(o.id, o.workingDir);
- await workingDirectoryRecovery.observe(o.id, o.workingDir).catch(() => undefined);
+ await workingDirectoryRecovery.observe(o.id, o.workingDir).catch((error) => {
+ workdirLog.warn('workdir bootstrap observation failed', {
+ ...workdirDiagnosticContext(o.id!, o.workingDir), code: workdirDiagnosticErrorCode(error),
+ });
+ });
}
o.hostStartupPreferences = {
userPrompt: o.userPrompt,
@@ -12252,6 +12258,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId),
prepareUnhealthySession: (sessionId) =>
contextOverflowRolloverHolder?.prepareUnhealthySession(sessionId) ?? Promise.resolve(false),
+ workdirDiagnostics: workdirLog,
log,
});
@@ -18016,9 +18023,16 @@ async function checkWorkDirExists(
// 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 {
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,
@@ -18036,6 +18050,7 @@ async function checkWorkDirExists(
if (getManagedWorktreeBasePath(normalizedWorkingDir) !== null) {
const ready = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);
if (!ready) {
+ 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,
@@ -18048,15 +18063,28 @@ async function checkWorkDirExists(
}
}
if (getManagedWorktreeBasePath(normalizedWorkingDir) === null) {
- if (!await workingDirectoryRecovery.recover(sessionId, workingDir)) return false;
+ 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,
+ });
// Cindy 托管 worktree 被外部 PR cleanup / 手动 git 命令移除时,先按 DB 中
// 的精确 worktree_path 从本地或 origin tracking 分支重建,保留原代码与快照。
const restored = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);
if (restored) {
+ workdirLog.info('workdir preflight recovered', { ...diagnosticContext, action: 'managed-worktree-restored' });
log.info('send: restored missing managed worktree', { sessionId, workingDir });
return true;
}
@@ -18079,7 +18107,15 @@ async function checkWorkDirExists(
.filter((session) => !session.remoteHostId)
.map((session) => ({ id: session.id, workingDir: session.workDir })))
) {
- log.info('send: recreated missing working directory for conversation', { sessionId, workingDir });
+ 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) {
@@ -18089,6 +18125,12 @@ async function checkWorkDirExists(
});
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;
}
diff --git a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
index f66977d255..a992ab63a1 100644
--- a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
+++ b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
@@ -1,5 +1,9 @@
import fsp from 'node:fs/promises';
import path from 'node:path';
+import {
+ workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId,
+ type WorkdirDiagnosticLogger,
+} from '../workdirDiagnostics';
export function isUnavailableFilesystemError(error: unknown): boolean {
return ['EIO', 'ENOTCONN', 'ENODEV', 'ESTALE', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'WORKDIR_PROBE_TIMEOUT']
@@ -11,7 +15,7 @@ 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>) {
+} = fsp, allocateFallback?: (sessionId: string) => Promise<string>, log?: WorkdirDiagnosticLogger) {
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);
@@ -21,7 +25,7 @@ export function createWorkingDirectoryRecovery(io: {
}
return entry;
}
- async function mountUnavailable(dir: string, entry: { device?: number }) {
+ async function mountUnavailable(dir: string, entry: { device?: number }, report: (details: Record<string, unknown>) => void) {
const canonical = path.resolve(dir);
if (process.platform === 'darwin' && canonical.startsWith('/Volumes/')) {
const volume = canonical.split('/').slice(0, 3).join('/');
@@ -30,9 +34,15 @@ export function createWorkingDirectoryRecovery(io: {
// 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;
+ await io.realpath?.(volume).catch(() => null) === volume) {
+ report({ reason: 'bare-mount-point', probedDirectoryRef: workdirDiagnosticId(volume) });
+ return true;
+ }
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT' || isUnavailableFilesystemError(error)) return true;
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || isUnavailableFilesystemError(error)) {
+ report({ reason: 'mount-probe-failed', code: workdirDiagnosticErrorCode(error), probedDirectoryRef: workdirDiagnosticId(volume) });
+ return true;
+ }
throw error;
}
}
@@ -40,13 +50,24 @@ export function createWorkingDirectoryRecovery(io: {
while (true) {
try {
const current = await io.stat(ancestor);
- return entry.device !== undefined && current.dev !== undefined && current.dev !== entry.device;
+ const changed = entry.device !== undefined && current.dev !== undefined && current.dev !== entry.device;
+ if (changed) report({
+ reason: 'device-changed', expectedDevice: entry.device, actualDevice: current.dev,
+ probedDirectoryRef: workdirDiagnosticId(ancestor),
+ });
+ return changed;
} catch (error) {
- if (isUnavailableFilesystemError(error)) return true;
+ if (isUnavailableFilesystemError(error)) {
+ report({ reason: 'ancestor-probe-failed', code: workdirDiagnosticErrorCode(error), probedDirectoryRef: workdirDiagnosticId(ancestor) });
+ 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.
+ if (parent === ancestor) {
+ report({ reason: 'root-missing', code: 'ENOENT', probedDirectoryRef: workdirDiagnosticId(ancestor) });
+ return true;
+ }
ancestor = parent;
}
}
@@ -79,8 +100,21 @@ export function createWorkingDirectoryRecovery(io: {
return { id, dir, entry };
});
const own = entryFor(sessionId, workingDir);
+ const startedAt = Date.now();
+ const context = workdirDiagnosticContext(sessionId, workingDir);
+ let stage = 'mount-check';
+ const reportFailure = (error: unknown) => log?.warn('workdir recovery attempt failed', {
+ ...context, stage, code: workdirDiagnosticErrorCode(error),
+ usingFallback: !!own?.fallback, elapsedMs: Date.now() - startedAt,
+ });
const useFallback = async (): Promise<boolean> => {
- if (!own || !allocateFallback || pending.get(sessionId) !== own) return false;
+ stage = 'fallback-allocation';
+ if (!own || !allocateFallback || pending.get(sessionId) !== own) {
+ log?.warn('workdir recovery fallback skipped', {
+ ...context, reason: !allocateFallback ? 'allocator-missing' : 'stale-recovery',
+ });
+ return false;
+ }
const fallback = path.resolve(await allocateFallback(sessionId));
if (pending.get(sessionId) !== own) return false;
pending.set(sessionId, { ...own, fallback, note: [
@@ -89,34 +123,63 @@ export function createWorkingDirectoryRecovery(io: {
'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') });
+ log?.info('workdir recovery completed', {
+ ...context, action: 'fallback-selected', fallbackRef: workdirDiagnosticId(fallback),
+ sameDirectory: path.resolve(workingDir) === fallback, elapsedMs: Date.now() - startedAt,
+ });
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;
+ stage = 'fallback-stat';
+ try {
+ const valid = (await io.stat(own.fallback)).isDirectory();
+ if (!valid) log?.warn('workdir recovery rejected', { ...context, stage, reason: 'not-directory' });
+ return valid;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ reportFailure(error);
+ return false;
+ }
}
+ stage = 'fallback-mkdir';
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') });
+ log?.info('workdir recovery completed', {
+ ...context, action: 'fallback-recreated', code: 'ENOENT',
+ fallbackRef: workdirDiagnosticId(own.fallback), elapsedMs: Date.now() - startedAt,
+ });
return true;
}
- if (own && allocateFallback && await mountUnavailable(workingDir, own)) {
+ if (own && allocateFallback && await mountUnavailable(workingDir, own, (details) => {
+ log?.warn('workdir recovery unavailable', { ...context, ...details });
+ })) {
return await useFallback();
}
// A stale probe must not mistake a file, permission error, or a directory
// restored by someone else for a missing directory.
+ stage = 'original-stat';
try {
const stat = await io.stat(workingDir);
- return stat.isDirectory();
+ const valid = stat.isDirectory();
+ if (!valid) log?.warn('workdir recovery rejected', { ...context, stage, reason: 'not-directory' });
+ return valid;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
+ stage = 'similar-path';
const similar = typeof similarPath === 'function' ? await similarPath() : similarPath;
+ stage = 'original-mkdir';
await io.mkdir(workingDir, { recursive: true });
+ log?.info('workdir recovery directory created', {
+ ...context, action: 'directory-recreated', code: 'ENOENT',
+ similarPathFound: !!similar, elapsedMs: Date.now() - startedAt,
+ });
+ stage = 'alias-resolution';
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.
@@ -138,10 +201,14 @@ export function createWorkingDirectoryRecovery(io: {
}));
return true;
} catch (error) {
+ reportFailure(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 useFallback().catch((fallbackError) => {
+ reportFailure(fallbackError);
+ return false;
+ });
}
return false;
}
diff --git a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
index 27b0950a1b..6164256e27 100644
--- a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
+++ b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts
@@ -13,6 +13,7 @@ import type {
WorkdirProbeResponse,
WorkdirProbeResult,
} from './protocol';
+import { workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics';
export interface WorkdirProbeChildLike {
postMessage(message: unknown): void;
@@ -26,6 +27,7 @@ export interface WorkdirProbeChildLike {
}
export interface WorkdirProbeLoggerLike {
+ info?(...args: unknown[]): void;
warn(...args: unknown[]): void;
}
@@ -56,6 +58,9 @@ interface ProbeEntry {
dir: string;
key: string;
deadline: number;
+ enqueuedAt: number;
+ startedAt?: number;
+ workerId?: number;
resolve: (result: WorkdirProbeResult) => void;
reject: (error: Error) => void;
queueTimer?: ReturnType<typeof setTimeout>;
@@ -63,9 +68,12 @@ interface ProbeEntry {
}
interface ProbeWorker {
+ id: number;
child: WorkdirProbeChildLike;
active?: ProbeEntry;
terminating?: boolean;
+ terminationRequestedAt?: number;
+ lastRequestId?: number;
}
const DEFAULT_MAX_WORKERS = 2;
@@ -78,6 +86,7 @@ export class WorkdirProbeHostClient {
private readonly queue: ProbeEntry[] = [];
private readonly inFlightByPath = new Map<string, Promise<WorkdirProbeResult>>();
private nextId = 1;
+ private nextWorkerId = 1;
private disposed = false;
constructor(private readonly deps: WorkdirProbeHostClientDeps) {
@@ -88,6 +97,10 @@ export class WorkdirProbeHostClient {
probe(dir: string, key: string, timeoutMs: number, kind: WorkdirProbeRequest['kind'] = 'probe'): Promise<WorkdirProbeResult> {
key = `${kind}:${key}`;
if (this.disposed) {
+ this.deps.log.warn('workdir probe rejected', {
+ reason: 'disposed', code: 'WORKDIR_PROBE_UNAVAILABLE',
+ operation: kind, directoryRef: workdirDiagnosticId(dir), ...this.poolDiagnostics(),
+ });
return Promise.reject(
new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host is disposed'),
);
@@ -95,6 +108,10 @@ export class WorkdirProbeHostClient {
const existing = this.inFlightByPath.get(key);
if (existing) return existing;
if (this.queue.length >= this.maxQueued) {
+ this.deps.log.warn('workdir probe rejected', {
+ reason: 'queue-full', code: 'WORKDIR_PROBE_UNAVAILABLE',
+ operation: kind, directoryRef: workdirDiagnosticId(dir), ...this.poolDiagnostics(),
+ });
return Promise.reject(
new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe queue is full'),
);
@@ -102,12 +119,14 @@ export class WorkdirProbeHostClient {
let entry!: ProbeEntry;
const probe = new Promise<WorkdirProbeResult>((resolve, reject) => {
+ const enqueuedAt = Date.now();
entry = {
kind,
id: this.nextId++,
dir,
key,
- deadline: Date.now() + timeoutMs,
+ deadline: enqueuedAt + timeoutMs,
+ enqueuedAt,
resolve,
reject,
};
@@ -130,11 +149,11 @@ export class WorkdirProbeHostClient {
);
for (const queued of this.queue.splice(0)) {
if (queued.queueTimer) clearTimeout(queued.queueTimer);
- queued.reject(error);
+ this.rejectProbe(queued, error, 'disposed');
}
for (const worker of this.workers.splice(0)) {
if (worker.active?.probeTimer) clearTimeout(worker.active.probeTimer);
- worker.active?.reject(error);
+ if (worker.active) this.rejectProbe(worker.active, error, 'disposed');
worker.active = undefined;
try {
worker.child.kill();
@@ -154,11 +173,13 @@ export class WorkdirProbeHostClient {
try {
this.startProbe(this.createWorker(), entry);
} catch (error) {
- entry.reject(
+ this.rejectProbe(entry,
new WorkdirProbeClientError(
'WORKDIR_PROBE_UNAVAILABLE',
`failed to start probe host: ${String(error)}`,
),
+ 'host-start-failed',
+ error,
);
}
return;
@@ -170,11 +191,12 @@ export class WorkdirProbeHostClient {
const index = this.queue.indexOf(entry);
if (index < 0) return;
this.queue.splice(index, 1);
- entry.reject(
+ this.rejectProbe(entry,
new WorkdirProbeClientError(
'WORKDIR_PROBE_TIMEOUT',
'timed out waiting for a probe slot',
),
+ 'queue-timeout',
);
}, remainingMs);
entry.queueTimer.unref?.();
@@ -182,19 +204,20 @@ export class WorkdirProbeHostClient {
private createWorker(): ProbeWorker {
const child = this.deps.fork();
- const worker: ProbeWorker = { child };
+ 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);
});
- child.on('exit', () => {
- this.handleWorkerExit(worker);
+ child.on('exit', (code) => {
+ this.handleWorkerExit(worker, code);
});
- child.on('error', (type, location) => {
- this.deps.log.warn('workdir probe host error', { type, location });
+ child.on('error', () => {
this.beginWorkerTermination(
worker,
new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host failed'),
+ 'host-error',
);
});
return worker;
@@ -207,18 +230,23 @@ export class WorkdirProbeHostClient {
}
const remainingMs = this.remainingMs(entry);
if (remainingMs <= 0) {
- entry.reject(
+ this.rejectProbe(entry,
new WorkdirProbeClientError('WORKDIR_PROBE_TIMEOUT', 'directory probe deadline elapsed'),
+ 'deadline-before-dispatch',
);
this.drainQueue();
return;
}
worker.active = entry;
+ entry.startedAt = Date.now();
+ entry.workerId = worker.id;
+ worker.lastRequestId = entry.id;
entry.probeTimer = setTimeout(() => {
if (worker.active !== entry) return;
this.beginWorkerTermination(
worker,
new WorkdirProbeClientError('WORKDIR_PROBE_TIMEOUT', 'directory probe timed out'),
+ 'response-timeout',
);
}, remainingMs);
entry.probeTimer.unref?.();
@@ -237,6 +265,7 @@ export class WorkdirProbeHostClient {
'WORKDIR_PROBE_UNAVAILABLE',
`probe host postMessage failed: ${String(error)}`,
),
+ 'dispatch-failed',
);
}
}
@@ -246,24 +275,41 @@ export class WorkdirProbeHostClient {
if (!entry || !isProbeResponse(message) || message.id !== entry.id) return;
if (entry.probeTimer) clearTimeout(entry.probeTimer);
worker.active = undefined;
+ if (!message.result.ok) {
+ this.deps.log.warn('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.probeDiagnostics(entry), reason: 'not-directory',
+ });
+ }
entry.resolve(message.result);
this.drainQueue();
}
- private beginWorkerTermination(worker: ProbeWorker, error: WorkdirProbeClientError): void {
+ private beginWorkerTermination(worker: ProbeWorker, error: WorkdirProbeClientError, reason: string): void {
if (worker.terminating) return;
worker.terminating = true;
+ worker.terminationRequestedAt = Date.now();
const entry = worker.active;
worker.active = undefined;
if (entry?.probeTimer) clearTimeout(entry.probeTimer);
- entry?.reject(error);
+ 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(),
+ });
try {
if (!worker.child.kill()) {
- this.deps.log.warn('workdir probe host kill was not acknowledged; waiting for exit');
+ this.deps.log.warn('workdir probe host kill was not acknowledged; waiting for exit', {
+ workerId: worker.id, requestId: worker.lastRequestId, ...this.poolDiagnostics(),
+ });
}
} catch (killError) {
this.deps.log.warn('failed to request workdir probe host termination; waiting for exit', {
- error: String(killError),
+ workerId: worker.id, requestId: worker.lastRequestId,
+ code: workdirDiagnosticErrorCode(killError), ...this.poolDiagnostics(),
});
}
// The worker remains in this.workers and therefore counts against
@@ -271,17 +317,56 @@ export class WorkdirProbeHostClient {
// that refuses to exit can reduce availability, but cannot multiply.
}
- private handleWorkerExit(worker: ProbeWorker): void {
+ private handleWorkerExit(worker: ProbeWorker, code: number): void {
if (!this.removeWorker(worker)) return;
const entry = worker.active;
worker.active = undefined;
if (entry?.probeTimer) clearTimeout(entry.probeTimer);
- entry?.reject(
- new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host exited'),
+ if (entry) this.rejectProbe(entry,
+ new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host exited'), 'host-exited',
);
+ this.deps.log.info?.('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,
+ ...this.poolDiagnostics(),
+ });
this.drainQueue();
}
+ private poolDiagnostics() {
+ return {
+ workers: this.workers.length,
+ activeWorkers: this.workers.filter((worker) => worker.active).length,
+ terminatingWorkers: this.workers.filter((worker) => worker.terminating).length,
+ queued: this.queue.length,
+ maxWorkers: this.maxWorkers,
+ maxQueued: this.maxQueued,
+ };
+ }
+
+ private probeDiagnostics(entry: ProbeEntry) {
+ const now = Date.now();
+ return {
+ requestId: entry.id, workerId: entry.workerId, operation: entry.kind,
+ directoryRef: workdirDiagnosticId(entry.dir),
+ phase: entry.startedAt === undefined ? 'before-dispatch' : 'waiting-result',
+ timeoutMs: entry.deadline - entry.enqueuedAt,
+ elapsedMs: now - entry.enqueuedAt,
+ queueWaitMs: (entry.startedAt ?? now) - entry.enqueuedAt,
+ responseWaitMs: entry.startedAt === undefined ? null : now - entry.startedAt,
+ ...this.poolDiagnostics(),
+ };
+ }
+
+ private rejectProbe(entry: ProbeEntry, error: WorkdirProbeClientError, reason: string, cause?: unknown): void {
+ this.deps.log.warn('workdir probe failed', {
+ ...this.probeDiagnostics(entry), reason, code: workdirDiagnosticErrorCode(error),
+ ...(cause === undefined ? {} : { causeCode: workdirDiagnosticErrorCode(cause) }),
+ });
+ entry.reject(error);
+ }
+
private removeWorker(worker: ProbeWorker): boolean {
const index = this.workers.indexOf(worker);
if (index < 0) return false;
@@ -307,11 +392,13 @@ export class WorkdirProbeHostClient {
this.startProbe(this.createWorker(), entry);
} catch (error) {
if (entry.queueTimer) clearTimeout(entry.queueTimer);
- entry.reject(
+ this.rejectProbe(entry,
new WorkdirProbeClientError(
'WORKDIR_PROBE_UNAVAILABLE',
`failed to restart probe host: ${String(error)}`,
),
+ 'host-restart-failed',
+ error,
);
}
}
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 b919824917..97f088a31e 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,16 +30,17 @@ 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 client = new WorkdirProbeHostClient({
fork: () => {
const child = new FakeChild();
children.push(child);
return child;
},
- log: { warn: vi.fn() },
+ log,
...options,
});
- return { client, children };
+ return { client, children, log };
}
afterEach(() => {
@@ -47,6 +48,82 @@ afterEach(() => {
});
describe('WorkdirProbeHostClient', () => {
+ it('identifies queue timeout before any request reaches the worker', async () => {
+ vi.useFakeTimers();
+ const { client, children, log } = createHarness({ maxWorkers: 1 });
+ const blocked = client.probe('/private/blocker', '/private/blocker', 1000).catch((error) => error);
+ const queued = client.probe('/private/queued', '/private/queued', 50).catch((error) => error);
+ 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({
+ reason: 'queue-timeout', phase: 'before-dispatch', requestId: 2,
+ timeoutMs: 50, elapsedMs: 50, queueWaitMs: 50, responseWaitMs: null,
+ activeWorkers: 1, terminatingWorkers: 0,
+ }));
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain('private');
+ client.dispose();
+ await blocked;
+ });
+
+ it('reports queue and response wait separately and confirms worker exit', async () => {
+ vi.useFakeTimers();
+ const { client, children, log } = createHarness({ maxWorkers: 1 });
+ const blocked = client.probe('/private/blocker', '/private/blocker', 100).catch((error) => error);
+ const queued = client.probe('/private/queued', '/private/queued', 150).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(100);
+ 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({
+ 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({
+ workerId: 1, requestId: 1, exitCode: 9, terminationRequested: true,
+ }));
+ client.dispose();
+ await blocked;
+ });
+
+ it.each(['host-exited', 'host-error', 'dispatch-failed'] as const)('reports a process failure without filesystem or error contents: %s', async (reason) => {
+ const { client, children, log } = createHarness({ maxWorkers: 1 });
+ const first = client.probe('/private/first', '/private/first', 1000);
+ children[0].respond();
+ await first;
+ if (reason === 'dispatch-failed') vi.spyOn(children[0], 'postMessage').mockImplementation(() => { throw new Error('private credentials'); });
+ const failure = client.probe('/private/second', '/private/second', 1000).catch((error) => error);
+ if (reason === 'host-exited') children[0].emit('exit', 1);
+ 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');
+ client.dispose();
+ });
+
+ it('reports a spawn failure without logging its raw exception', async () => {
+ const log = { warn: vi.fn() };
+ const client = new WorkdirProbeHostClient({
+ fork: () => { throw new Error('private executable path'); }, log,
+ });
+ await expect(client.probe('/private/dir', '/private/dir', 100)).rejects.toMatchObject({ code: 'WORKDIR_PROBE_UNAVAILABLE' });
+ expect(log.warn).toHaveBeenCalledWith('workdir probe failed', expect.objectContaining({ reason: 'host-start-failed', phase: 'before-dispatch' }));
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain('private');
+ client.dispose();
+ });
+
+ it.each(['ENOENT', 'EACCES', 'EIO', 'PRIVATE_CREDENTIAL'])('distinguishes a returned filesystem error from probe failures: %s', async (code) => {
+ const { client, children, log } = createHarness();
+ 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({
+ reason: 'filesystem-error', code: code === 'PRIVATE_CREDENTIAL' ? 'UNKNOWN' : code, requestId: 1,
+ }));
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain('PRIVATE_CREDENTIAL');
+ client.dispose();
+ });
+
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 });
diff --git a/apps/desktop/src/main/workdir-probe-host/index.ts b/apps/desktop/src/main/workdir-probe-host/index.ts
index 0995082c31..bd9b4deefb 100644
--- a/apps/desktop/src/main/workdir-probe-host/index.ts
+++ b/apps/desktop/src/main/workdir-probe-host/index.ts
@@ -10,7 +10,7 @@ import { createLogger } from '../logger.js';
import { WorkdirProbeHostClient } from './WorkdirProbeHostClient.js';
import type { WorkdirProbeRequest } from './protocol.js';
-const log = createLogger('workdir-probe-host');
+const log = createLogger('workdir-diagnostics');
function forkProbeHost(): ReturnType<typeof utilityProcess.fork> {
const env: NodeJS.ProcessEnv = {};
diff --git a/apps/desktop/src/main/workdirDiagnostics.ts b/apps/desktop/src/main/workdirDiagnostics.ts
new file mode 100644
index 0000000000..13e793f26c
--- /dev/null
+++ b/apps/desktop/src/main/workdirDiagnostics.ts
@@ -0,0 +1,36 @@
+import { createHmac, randomBytes } from 'node:crypto';
+import path from 'node:path';
+import { getSystemErrorMap } from 'node:util';
+
+const diagnosticKey = randomBytes(32);
+const errorCodes = new Set([
+ ...[...getSystemErrorMap().values()].map(([code]) => code),
+ 'WORKDIR_PROBE_TIMEOUT',
+ 'WORKDIR_PROBE_UNAVAILABLE',
+]);
+
+export interface WorkdirDiagnosticLogger {
+ info(...args: unknown[]): void;
+ warn(...args: unknown[]): void;
+}
+
+function diagnosticId(kind: 'directory' | 'session', value: string): string {
+ return createHmac('sha256', diagnosticKey).update(kind).update('\0').update(value).digest('hex').slice(0, 16);
+}
+
+export function workdirDiagnosticId(dir: string): string {
+ return diagnosticId('directory', path.resolve(dir));
+}
+
+export function workdirDiagnosticContext(sessionId: string, dir: string) {
+ return { sessionRef: diagnosticId('session', sessionId), directoryRef: workdirDiagnosticId(dir) };
+}
+
+export function workdirDiagnosticErrorCode(error: unknown): string {
+ try {
+ const code = (error as NodeJS.ErrnoException | null)?.code;
+ return typeof code === 'string' && errorCodes.has(code) ? code : 'UNKNOWN';
+ } catch {
+ return 'UNKNOWN';
+ }
+}
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index ed62e5edfd..8cfb554556 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -161,6 +161,9 @@ localStorage 按 **origin + userData 目录** 分家——dev 的 renderer 从
## 分层验证
+工作目录误报缺失或切到备用目录时,参见[工作目录异常日志判读](../working-directory-diagnostics.md),
+按探测阶段、恢复结果与匿名关联标识区分原因,不要仅凭超时推断掉盘。
+
本节指导**开发过程中的增量验证**;提交(commit/PR)前的强制门禁以
`development-workflow.md` 的「提交前测试门禁」为准(仓库根 `pnpm test:unit:related` 与相关
package 的 typecheck 全部通过;CI 仍跑完整 `pnpm test:unit`)。开发过程中根据实际改动选择最小但充分的检查:
diff --git a/docs/working-directory-diagnostics.md b/docs/working-directory-diagnostics.md
new file mode 100644
index 0000000000..dcdf5fcc43
--- /dev/null
+++ b/docs/working-directory-diagnostics.md
@@ -0,0 +1,67 @@
+# 工作目录异常:日志判读
+
+本次诊断只增加可观测性,不修改目录探测的超时预算、恢复判据、目录授权或 Agent 行为。
+它不会修复原目录,也不会主动搬动用户文件。
+
+## 收集
+
+问题出现后记下发生时间和客户端版本,通过现有“上传日志”入口提供诊断日志。
+本机也可以在当前实例的日志目录中搜索当天的 main 日志,筛选 scope
+`workdir-diagnostics`。默认 info 等级即可记录,不需要打开 debug;自定义日志等级仍然生效。
+这些日志需要运行包含本次改动的客户端版本,旧版本无法补录。
+
+## 关联字段
+
+| 字段 | 用途 |
+| --- | --- |
+| `directoryRef` / `probedDirectoryRef` | 关联目标目录与恢复过程中实际检查的祖先目录 |
+| `sessionRef` | 关联同一个任务的检查、恢复和运行时重建 |
+| `requestId` / `workerId` | 关联一次探测请求与承载它的进程 |
+| `elapsedMs` / `queueWaitMs` / `responseWaitMs` | 总耗时、排队耗时、派发后的结果等待耗时 |
+| `activeWorkers` / `terminatingWorkers` / `queued` | 判断是否忙于处理其他请求,或等待旧进程退出 |
+| `code` / `causeCode` | 已知错误码;不认识的错误码统一为 `UNKNOWN`,不输出原始异常 |
+
+目录和任务关联标识采用进程内随机密钥的 HMAC;同一次运行可关联,重启后改变。
+它们不是目录原文,也不是可用来还原路径的普通路径哈希。符号链接等不同路径拼法不保证标识相同。
+
+## 探测阶段
+
+| 日志中的 `reason` | 能确认的事实 |
+| --- | --- |
+| `queue-full` | 等候队列达到上限,本请求没有派发 |
+| `queue-timeout` | 等待进程空位耗尽预算,没有开始检查目标目录 |
+| `deadline-before-dispatch` | 准备派发时总预算已耗尽 |
+| `host-start-failed` / `host-restart-failed` | 创建探测进程失败;有底层已知错误时看 `causeCode` |
+| `dispatch-failed` | 向探测进程发送请求失败 |
+| `host-error` / `host-exited` | 探测进程异常或未返回结果就退出 |
+| `response-timeout` | 请求已经派发,但未在预算内收到结果 |
+| `filesystem-error` | 探测进程返回文件操作错误;看 `code` 区分 `ENOENT`、`EACCES`、`EIO` 等 |
+| `not-directory` | 文件操作返回目标不是目录 |
+| `disposed` | 探测池已关闭或正在关闭,不能把它当作目录缺失 |
+
+**`response-timeout` 不能单独证明硬盘损坏或掉盘。** 当前内部协议没有文件操作开始回执,
+它仍可能包含进程启动、文件操作或进程间通信等待;日志不会把未知原因伪装成确定的磁盘故障。
+进程的创建、终止请求、kill 未获确认和最终退出都有独立日志,退出记录带 `exitCode`
+与 `terminationRequested`,可判断是超时后主动终止,还是意外退出。
+
+## 恢复与发送阶段
+
+- `workdir recovery unavailable`:看 `reason` 区分祖先探测错误、盘根缺失、裸挂载点和 `device-changed`;设备变化附预期与实际设备号。
+- `workdir recovery directory created`:真正执行了原地 mkdir;`similarPathFound` 表示发现相似目录线索,不记录其名字。
+- `workdir recovery completed`:`action=fallback-selected` 是选用备用目录,`action=fallback-recreated` 是重建备用目录,不能混同原目录被恢复。
+- `sameDirectory=true`:备用目录与输入目录相同,是“回退到自身”的直接诊断证据;本次仅记录,不修改该行为。
+- `workdir recovery attempt failed`:`stage` 指明失败在挂载检查、备用目录 stat/mkdir、相似目录检查、原目录 mkdir 还是别名解析。随后仍可能成功回退,不能只看这一条判断最终失败。
+- `workdir preflight ready/recovered/blocked/rejected`:表示发送前检查的最终走向;`blocked` 同时记录真实错误码与实际报出的 `reportedReason`,可识别“探测器故障却报目录不存在”。
+- `workdir DB lookup failed`:读 DB 路径失败;`workdir DB fallback candidate` 记录存在 DB 候选,`sameNormalizedDirectory=true` 表示只是规范化后的路径拼法相同,本次不改变比较或发送逻辑。
+- `workdir runtime refresh requested/completed`:表示因目录问题请求重建运行时及其结果;结合前面的目录检查日志判断重建为何成功或被阻断。
+
+按发生时间先找 `preflight failed/blocked`,用 `sessionRef` 和 `directoryRef` 关联恢复记录,
+再用目录标识找到对应探测的 `reason`、请求编号、耗时和进程状态。后续的 `preflight ready`
+可以确认检查恢复正常,避免误判为只能重启客户端才能恢复。
+
+## 上报边界
+
+`workdir-diagnostics` 只按精确 scope 加入日志上传白名单。新增理由是该来源只包含
+固定事件名、已知错误码、数值、布尔值和匿名关联标识,不包含目录、文件名、任务标题、
+消息、凭证或原始异常。其子 scope、Renderer 转发及原有 `maker-ipc` / `workdir-probe-host`
+不会因此获得上传权限;现有授权、记录边界与脱敏规则保持不变。