Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 将共用工作目录探测改为主进程异步执行 (#4718)
DavidShenXD1d20fd2b3dd2
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjsindex 5fc095c592..ec57839e6a 100644--- a/apps/desktop/eslint.config.mjs+++ b/apps/desktop/eslint.config.mjs@@ -11,13 +11,12 @@ export default tseslint.config(},{files: ['src/main/**/*.{ts,tsx}'],- // watcher-host、workdir-probe-host、Review PDF、Ghost Node broker 与 Pi Subagent+ // watcher-host、Review PDF、Ghost Node broker 与 Pi Subagent// 后台宿主是受测的 utilityProcess 基建,和 localDb 一样属于“进程边界基建”,// 只对精确入口豁免导入限制。ignores: ['src/main/localDb/**/*.{ts,tsx}','src/main/watcher-host/**/*.{ts,tsx}',- 'src/main/workdir-probe-host/**/*.{ts,tsx}','src/main/mcp-integrations/forgeIconConversionHost.ts','src/main/reviewer/reviewPdfProcess.ts','src/main/cindy-brain/nodeRuntimeBroker.ts',diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 8c70dc8593..ae5937bdf1 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -2101,13 +2101,6 @@ const config: ForgeConfig = {// SDK 缺失或原生崩溃都不能影响 Electron main。target: 'preload',},- {- entry: 'src/main/workdir-probe-host/workdirProbeHostProcess.ts',- config: 'vite.preload.config.ts',- // UNC/SMB stat 不可取消;独立 utility process 超时后可直接终止,- // 避免把挂死 I/O 留在 Electron main 的 libuv 线程池。- target: 'preload',- },{entry: 'src/main/cindy-brain/piSubagentRunnerProcess.ts',config: 'vite.preload.config.ts',diff --git a/apps/desktop/src/main/device-link/remote-workdir-guard.ts b/apps/desktop/src/main/device-link/remote-workdir-guard.tsindex 5ddaeba9e8..819caf588a 100644--- a/apps/desktop/src/main/device-link/remote-workdir-guard.ts+++ b/apps/desktop/src/main/device-link/remote-workdir-guard.ts@@ -60,9 +60,9 @@ function classifyStatError(err: unknown): RemoteWorkingDirRejectionReason {}/**- * 生产探测在有界 utility-process 池中执行。`fs.stat` 不支持 AbortSignal,- * 因此超时会终止对应 host,释放其 libuv 状态并让等待请求获得槽位。- * `options.stat` 仅为单元测试注入,同样保留业务超时语义。+ * 生产探测在主进程的有限异步池中执行。`fs.promises` 保持事件循环可运行,+ * 每次请求仍有端到端 deadline;底层 I/O 不可取消时会继续占用有限槽位,避免+ * 超时重试把未完成的文件系统请求无限堆积。`options.stat` 仅为单元测试注入。*/export async function probeRemoteDirectory(dir: string,diff --git a/apps/desktop/src/main/workdir-probe-host/MainProcessWorkdirProbeClient.ts b/apps/desktop/src/main/workdir-probe-host/MainProcessWorkdirProbeClient.tsnew file mode 100644index 0000000000..44ade96dd8--- /dev/null+++ b/apps/desktop/src/main/workdir-probe-host/MainProcessWorkdirProbeClient.ts@@ -0,0 +1,336 @@+/**+ * Main-process async directory probes.+ *+ * Electron utility processes are deliberately not used here: on affected+ * Windows machines the utility process can be started successfully but never+ * deliver its first message. The fs/promises calls stay asynchronous and are+ * bounded by a small in-flight pool plus an end-to-end deadline. A timed-out+ * operation keeps its slot until the underlying I/O settles because Node does+ * not expose cancellation for fs promises.+ */++import { mkdir, realpath, readdir, stat } from 'node:fs/promises';+import path from 'node:path';++import type { WorkdirProbeRequest, WorkdirProbeResult } from './protocol';+import { workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics';++export interface MainProcessWorkdirProbeLogger {+ info?(...args: unknown[]): void;+ warn(...args: unknown[]): void;+}++export interface MainProcessWorkdirProbeFs {+ stat(dir: string): Promise<{ isDirectory(): boolean; dev?: number }>;+ mkdir(dir: string): Promise<void>;+ realpath(dir: string): Promise<string>;+ readdir(dir: string): Promise<string[]>;+}++export interface MainProcessWorkdirProbeClientDeps {+ log: MainProcessWorkdirProbeLogger;+ fs?: MainProcessWorkdirProbeFs;+ maxInFlight?: number;+ maxQueued?: number;+}++export type MainProcessWorkdirProbeErrorCode =+ 'WORKDIR_PROBE_TIMEOUT' | 'WORKDIR_PROBE_UNAVAILABLE';++export class MainProcessWorkdirProbeError extends Error {+ constructor(+ readonly code: MainProcessWorkdirProbeErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'MainProcessWorkdirProbeError';+ }+}++interface ProbeEntry {+ kind: WorkdirProbeRequest['kind'];+ id: number;+ dir: string;+ key: string;+ deadline: number;+ enqueuedAt: number;+ startedAt?: number;+ resolve: (result: WorkdirProbeResult) => void;+ reject: (error: Error) => void;+ queueTimer?: ReturnType<typeof setTimeout>;+ probeTimer?: ReturnType<typeof setTimeout>;+ inFlightPromise?: Promise<WorkdirProbeResult>;+ settled?: boolean;+}++const DEFAULT_MAX_IN_FLIGHT = 2;+const DEFAULT_MAX_QUEUED = 32;++const defaultFs: MainProcessWorkdirProbeFs = {+ stat: async (dir) => stat(dir),+ mkdir: async (dir) => {+ await mkdir(dir, { recursive: true });+ },+ realpath: (dir) => realpath(dir),+ readdir: async (dir) => readdir(dir),+};++export class MainProcessWorkdirProbeClient {+ private readonly maxInFlight: number;+ private readonly maxQueued: number;+ private readonly fs: MainProcessWorkdirProbeFs;+ private readonly queue: ProbeEntry[] = [];+ private readonly activeEntries = new Set<ProbeEntry>();+ private readonly inFlightByPath = new Map<string, Promise<WorkdirProbeResult>>();+ private active = 0;+ private nextId = 1;+ private disposed = false;++ constructor(private readonly deps: MainProcessWorkdirProbeClientDeps) {+ this.maxInFlight = deps.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT;+ this.maxQueued = deps.maxQueued ?? DEFAULT_MAX_QUEUED;+ this.fs = deps.fs ?? defaultFs;+ }++ probe(+ dir: string,+ key: string,+ timeoutMs: number,+ kind: WorkdirProbeRequest['kind'] = 'probe',+ ): Promise<WorkdirProbeResult> {+ if (this.disposed) {+ return Promise.reject(this.unavailable('probe host is disposed', dir, kind, 'disposed'));+ }+ const dedupeKey = `${kind}:${key}`;+ const existing = this.inFlightByPath.get(dedupeKey);+ if (existing) return existing;+ if (this.queue.length >= this.maxQueued) {+ return Promise.reject(this.unavailable('probe queue is full', dir, kind, 'queue-full'));+ }++ let entry!: ProbeEntry;+ const promise = new Promise<WorkdirProbeResult>((resolve, reject) => {+ const enqueuedAt = Date.now();+ entry = {+ kind,+ id: this.nextId++,+ dir,+ key: dedupeKey,+ deadline: enqueuedAt + timeoutMs,+ enqueuedAt,+ resolve,+ reject,+ };+ this.queue.push(entry);+ this.armQueueTimer(entry);+ this.drain();+ });+ entry.inFlightPromise = promise;+ this.inFlightByPath.set(dedupeKey, promise);+ return promise;+ }++ dispose(): void {+ if (this.disposed) return;+ this.disposed = true;+ const error = this.unavailable('probe host is disposed', '', 'probe', 'disposed');+ for (const entry of this.queue.splice(0)) {+ if (entry.queueTimer) clearTimeout(entry.queueTimer);+ this.rejectEntry(entry, error, 'disposed');+ }+ for (const entry of this.activeEntries) {+ this.rejectEntry(entry, error, 'disposed');+ }+ }++ private drain(): void {+ if (this.disposed) return;+ while (this.active < this.maxInFlight && this.queue.length > 0) {+ const entry = this.queue.shift()!;+ if (entry.queueTimer) clearTimeout(entry.queueTimer);+ if (this.remainingMs(entry) <= 0) {+ this.rejectEntry(+ entry,+ this.timeout('directory probe deadline elapsed'),+ 'deadline-before-dispatch',+ );+ continue;+ }+ this.start(entry);+ }+ }++ private armQueueTimer(entry: ProbeEntry): void {+ entry.queueTimer = setTimeout(() => {+ const index = this.queue.indexOf(entry);+ if (index < 0) return;+ this.queue.splice(index, 1);+ this.rejectEntry(entry, this.timeout('timed out waiting for a probe slot'), 'queue-timeout');+ }, this.remainingMs(entry));+ entry.queueTimer.unref?.();+ }++ private start(entry: ProbeEntry): void {+ this.active += 1;+ this.activeEntries.add(entry);+ entry.startedAt = Date.now();+ const remainingMs = this.remainingMs(entry);+ entry.probeTimer = setTimeout(() => {+ if (entry.settled) return;+ this.rejectEntry(entry, this.timeout('directory probe timed out'), 'response-timeout');+ }, remainingMs);+ entry.probeTimer.unref?.();++ void this.execute(entry.kind, entry.dir).then(+ (result) => {+ if (!entry.settled) {+ this.clearProbeTimer(entry);+ if (!result.ok) {+ this.deps.log.warn('workdir probe filesystem result', {+ ...this.diagnostics(entry),+ reason: 'filesystem-error',+ code: workdirDiagnosticErrorCode({ code: result.code }),+ });+ }+ entry.settled = true;+ entry.resolve(result);+ }+ this.finishActive(entry);+ },+ (error) => {+ if (!entry.settled) {+ this.clearProbeTimer(entry);+ this.rejectEntry(+ entry,+ this.unavailable(+ 'probe filesystem operation failed',+ entry.dir,+ entry.kind,+ 'filesystem-failure',+ error,+ ),+ 'filesystem-failure',+ );+ }+ this.finishActive(entry);+ },+ );+ }++ private finishActive(entry: ProbeEntry): void {+ this.activeEntries.delete(entry);+ if (entry.inFlightPromise && this.inFlightByPath.get(entry.key) === entry.inFlightPromise) {+ this.inFlightByPath.delete(entry.key);+ }+ this.release();+ }++ private async execute(+ kind: WorkdirProbeRequest['kind'],+ dir: string,+ ): Promise<WorkdirProbeResult> {+ try {+ if (kind === 'mkdir') {+ await this.fs.mkdir(dir);+ return { ok: true, isDirectory: true };+ }+ if (kind === 'realpath') {+ return { ok: true, isDirectory: true, path: await this.fs.realpath(dir) };+ }+ if (kind === 'similar') {+ const parent = path.dirname(dir);+ const target = path.basename(dir);+ if (!target || parent === dir) return { ok: true, isDirectory: false, path: null };+ const entries = await this.fs.readdir(parent);+ const match =+ entries.find((name) => name !== target && name.trim() === target.trim()) ??+ entries.find((name) => name !== target && name.toLowerCase() === target.toLowerCase());+ return { ok: true, isDirectory: false, path: match ? path.join(parent, match) : null };+ }+ const entry = await this.fs.stat(dir);+ return { ok: true, isDirectory: entry.isDirectory(), device: entry.dev };+ } catch (error) {+ return { ok: false, code: filesystemErrorCode(error) };+ }+ }++ private release(): void {+ this.active = Math.max(0, this.active - 1);+ this.drain();+ }++ private clearProbeTimer(entry: ProbeEntry): void {+ if (entry.probeTimer) {+ clearTimeout(entry.probeTimer);+ entry.probeTimer = undefined;+ }+ }++ private rejectEntry(entry: ProbeEntry, error: Error, reason: string): void {+ if (entry.settled) return;+ this.clearProbeTimer(entry);+ entry.settled = true;+ this.deps.log.warn('workdir probe failed', {+ ...this.diagnostics(entry),+ reason,+ code: workdirDiagnosticErrorCode(error),+ });+ entry.reject(error);+ if (!this.activeEntries.has(entry) && entry.inFlightPromise) {+ if (this.inFlightByPath.get(entry.key) === entry.inFlightPromise) {+ this.inFlightByPath.delete(entry.key);+ }+ }+ }++ private diagnostics(entry: ProbeEntry) {+ const now = Date.now();+ return {+ requestId: entry.id,+ 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,+ active: this.active,+ queued: this.queue.length,+ maxInFlight: this.maxInFlight,+ maxQueued: this.maxQueued,+ };+ }++ private remainingMs(entry: ProbeEntry): number {+ return Math.max(0, entry.deadline - Date.now());+ }++ private timeout(message: string): MainProcessWorkdirProbeError {+ return new MainProcessWorkdirProbeError('WORKDIR_PROBE_TIMEOUT', message);+ }++ private unavailable(+ message: string,+ dir: string,+ kind: WorkdirProbeRequest['kind'],+ reason: string,+ cause?: unknown,+ ): MainProcessWorkdirProbeError {+ const error = new MainProcessWorkdirProbeError('WORKDIR_PROBE_UNAVAILABLE', message);+ this.deps.log.warn('workdir probe unavailable', {+ ...(dir ? { operation: kind, directoryRef: workdirDiagnosticId(dir) } : {}),+ reason,+ code: workdirDiagnosticErrorCode(error),+ ...(cause === undefined ? {} : { causeCode: workdirDiagnosticErrorCode(cause) }),+ });+ return error;+ }+}++function filesystemErrorCode(error: unknown): string {+ return error &&+ typeof error === 'object' &&+ typeof (error as { code?: unknown }).code === 'string'+ ? (error as { code: string }).code+ : 'UNKNOWN';+}diff --git a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts b/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.tsdeleted file mode 100644index 009a7d8c38..0000000000--- a/apps/desktop/src/main/workdir-probe-host/WorkdirProbeHostClient.ts+++ /dev/null@@ -1,418 +0,0 @@-/**- * Main-process proxy for bounded, cancellable directory probes.- *- * Node's fs.stat cannot cancel a wedged UNC/SMB request. Each probe therefore- * runs in one of a small number of Electron utility processes. A timed-out- * probe kills only its worker, releasing the slot and the worker's libuv state.- * Queued probes wait for a slot within the same end-to-end deadline instead of- * being rejected immediately merely because other shares are slow.- */--import type {- WorkdirProbeRequest,- WorkdirProbeResponse,- WorkdirProbeResult,-} from './protocol';-import { workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics';--export interface WorkdirProbeChildLike {- postMessage(message: unknown): void;- on(event: 'message', listener: (message: unknown) => void): void;- on(event: 'exit', listener: (code: number) => void): void;- on(- event: 'error',- listener: (type: string, location: string, report: string) => void,- ): void;- kill(): boolean;-}--export interface WorkdirProbeLoggerLike {- debug?(...args: unknown[]): void;- warn(...args: unknown[]): void;-}--export interface WorkdirProbeHostClientDeps {- fork: () => WorkdirProbeChildLike;- log: WorkdirProbeLoggerLike;- maxWorkers?: number;- maxQueued?: number;-}--export type WorkdirProbeClientErrorCode =- | 'WORKDIR_PROBE_TIMEOUT'- | 'WORKDIR_PROBE_UNAVAILABLE';--export class WorkdirProbeClientError extends Error {- constructor(- readonly code: WorkdirProbeClientErrorCode,- message: string,- ) {- super(message);- this.name = 'WorkdirProbeClientError';- }-}--interface ProbeEntry {- kind: WorkdirProbeRequest['kind'];- id: number;- dir: string;- key: string;- deadline: number;- enqueuedAt: number;- startedAt?: number;- workerId?: number;- resolve: (result: WorkdirProbeResult) => void;- reject: (error: Error) => void;- queueTimer?: ReturnType<typeof setTimeout>;- probeTimer?: ReturnType<typeof setTimeout>;-}--interface ProbeWorker {- id: number;- child: WorkdirProbeChildLike;- active?: ProbeEntry;- terminating?: boolean;- terminationRequestedAt?: number;- lastRequestId?: number;-}--const DEFAULT_MAX_WORKERS = 2;-const DEFAULT_MAX_QUEUED = 32;--export class WorkdirProbeHostClient {- private readonly maxWorkers: number;- private readonly maxQueued: number;- private readonly workers: ProbeWorker[] = [];- 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) {- this.maxWorkers = deps.maxWorkers ?? DEFAULT_MAX_WORKERS;- this.maxQueued = deps.maxQueued ?? DEFAULT_MAX_QUEUED;- }-- 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'),- );- }- 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'),- );- }-- let entry!: ProbeEntry;- const probe = new Promise<WorkdirProbeResult>((resolve, reject) => {- const enqueuedAt = Date.now();- entry = {- kind,- id: this.nextId++,- dir,- key,- deadline: enqueuedAt + timeoutMs,- enqueuedAt,- resolve,- reject,- };- this.schedule(entry);- }).finally(() => {- if (this.inFlightByPath.get(key) === probe) {- this.inFlightByPath.delete(key);- }- });- this.inFlightByPath.set(key, probe);- return probe;- }-- dispose(): void {- if (this.disposed) return;- this.disposed = true;- const error = new WorkdirProbeClientError(- 'WORKDIR_PROBE_UNAVAILABLE',- 'probe host is disposed',- );- for (const queued of this.queue.splice(0)) {- if (queued.queueTimer) clearTimeout(queued.queueTimer);- this.rejectProbe(queued, error, 'disposed');- }- for (const worker of this.workers.splice(0)) {- if (worker.active?.probeTimer) clearTimeout(worker.active.probeTimer);- if (worker.active) this.rejectProbe(worker.active, error, 'disposed');- worker.active = undefined;- try {- worker.child.kill();- } catch {- // The utility process may already have exited.- }- }- }-- private schedule(entry: ProbeEntry): void {- const idle = this.workers.find((worker) => !worker.active && !worker.terminating);- if (idle) {- this.startProbe(idle, entry);- return;- }- if (this.workers.length < this.maxWorkers) {- try {- this.startProbe(this.createWorker(), entry);- } catch (error) {- this.rejectProbe(entry,- new WorkdirProbeClientError(- 'WORKDIR_PROBE_UNAVAILABLE',- `failed to start probe host: ${String(error)}`,- ),- 'host-start-failed',- error,- );- }- return;- }-- this.queue.push(entry);- const remainingMs = this.remainingMs(entry);- entry.queueTimer = setTimeout(() => {- const index = this.queue.indexOf(entry);- if (index < 0) return;- this.queue.splice(index, 1);- this.rejectProbe(entry,- new WorkdirProbeClientError(- 'WORKDIR_PROBE_TIMEOUT',- 'timed out waiting for a probe slot',- ),- 'queue-timeout',- );- }, remainingMs);- entry.queueTimer.unref?.();- }-- private createWorker(): ProbeWorker {- const child = this.deps.fork();- const worker: ProbeWorker = { child, id: this.nextWorkerId++ };- this.workers.push(worker);- child.on('message', (message) => {- this.handleMessage(worker, message);- });- child.on('exit', (code) => {- this.handleWorkerExit(worker, code);- });- child.on('error', () => {- this.beginWorkerTermination(- worker,- new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host failed'),- 'host-error',- );- });- return worker;- }-- private startProbe(worker: ProbeWorker, entry: ProbeEntry): void {- if (entry.queueTimer) {- clearTimeout(entry.queueTimer);- entry.queueTimer = undefined;- }- const remainingMs = this.remainingMs(entry);- if (remainingMs <= 0) {- 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?.();-- const request: WorkdirProbeRequest = {- kind: entry.kind,- id: entry.id,- dir: entry.dir,- };- try {- worker.child.postMessage(request);- } catch (error) {- this.beginWorkerTermination(- worker,- new WorkdirProbeClientError(- 'WORKDIR_PROBE_UNAVAILABLE',- `probe host postMessage failed: ${String(error)}`,- ),- 'dispatch-failed',- );- }- }-- private handleMessage(worker: ProbeWorker, message: unknown): void {- const entry = worker.active;- 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.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.debug?.('workdir probe filesystem result', {- ...this.probeDiagnostics(entry), reason: 'not-directory',- });- }- entry.resolve(message.result);- this.drainQueue();- }-- 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);- if (entry) this.rejectProbe(entry, error, reason);- this.deps.log.debug?.('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', {- workerId: worker.id, requestId: worker.lastRequestId, ...this.poolDiagnostics(),- });- }- } catch (killError) {- this.deps.log.warn('failed to request workdir probe host termination; waiting for exit', {- workerId: worker.id, requestId: worker.lastRequestId,- code: workdirDiagnosticErrorCode(killError), ...this.poolDiagnostics(),- });- }- // The worker remains in this.workers and therefore counts against- // maxWorkers until Electron confirms exit. This is fail-closed: a process- // that refuses to exit can reduce availability, but cannot multiply.- }-- 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);- if (entry) this.rejectProbe(entry,- new WorkdirProbeClientError('WORKDIR_PROBE_UNAVAILABLE', 'probe host exited'), 'host-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,- ...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 {- 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) }),- });- entry.reject(error);- }-- private removeWorker(worker: ProbeWorker): boolean {- const index = this.workers.indexOf(worker);- if (index < 0) return false;- this.workers.splice(index, 1);- return true;- }-- private remainingMs(entry: ProbeEntry): number {- return Math.max(0, entry.deadline - Date.now());- }-- private drainQueue(): void {- if (this.disposed) return;- while (this.queue.length > 0) {- const idle = this.workers.find((worker) => !worker.active && !worker.terminating);- if (idle) {- this.startProbe(idle, this.queue.shift()!);- continue;- }- if (this.workers.length >= this.maxWorkers) return;- const entry = this.queue.shift()!;- try {- this.startProbe(this.createWorker(), entry);- } catch (error) {- if (entry.queueTimer) clearTimeout(entry.queueTimer);- this.rejectProbe(entry,- new WorkdirProbeClientError(- 'WORKDIR_PROBE_UNAVAILABLE',- `failed to restart probe host: ${String(error)}`,- ),- 'host-restart-failed',- error,- );- }- }- }-}--function isProbeResponse(message: unknown): message is WorkdirProbeResponse {- if (!message || typeof message !== 'object') return false;- const candidate = message as Partial<WorkdirProbeResponse>;- if (candidate.kind !== 'result' || typeof candidate.id !== 'number') return false;- const result = candidate.result as Partial<WorkdirProbeResult> | undefined;- if (!result || typeof result.ok !== 'boolean') return false;- return result.ok- ? typeof (result as { isDirectory?: unknown }).isDirectory === 'boolean'- : typeof (result as { code?: unknown }).code === 'string';-}diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/MainProcessWorkdirProbeClient.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/MainProcessWorkdirProbeClient.test.tsnew file mode 100644index 0000000000..57b1da4084--- /dev/null+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/MainProcessWorkdirProbeClient.test.ts@@ -0,0 +1,147 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ MainProcessWorkdirProbeClient,+ type MainProcessWorkdirProbeFs,+} from '../MainProcessWorkdirProbeClient.js';++const log = { info: vi.fn(), warn: vi.fn() };++afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe('MainProcessWorkdirProbeClient', () => {+ it('performs directory operations asynchronously in the main process', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-main-probe-'));+ const client = new MainProcessWorkdirProbeClient({ log });+ try {+ await expect(client.probe(root, root, 1_000)).resolves.toMatchObject({+ ok: true,+ isDirectory: true,+ });+ await expect(+ client.probe(path.join(root, 'created'), `${root}/created`, 1_000, 'mkdir'),+ ).resolves.toEqual({ ok: true, isDirectory: true });+ await expect(+ client.probe(path.join(root, 'created'), `${root}/created`, 1_000, 'realpath'),+ ).resolves.toMatchObject({ ok: true, path: await fs.realpath(path.join(root, 'created')) });+ await expect(+ client.probe(path.join(root, 'created '), `${root}/created `, 1_000, 'similar'),+ ).resolves.toMatchObject({ ok: true, path: path.join(root, 'created') });+ await expect(+ client.probe(path.join(root, 'missing'), `${root}/missing`, 1_000),+ ).resolves.toEqual({ ok: false, code: 'ENOENT' });+ } finally {+ client.dispose();+ await fs.rm(root, { recursive: true, force: true });+ }+ });++ it('fails closed at the deadline while keeping in-flight I/O bounded', async () => {+ vi.useFakeTimers();+ let resolveSlow!: (value: { isDirectory(): boolean }) => void;+ let active = 0;+ let maxActive = 0;+ const slow = new Promise<{ isDirectory(): boolean }>((resolve) => {+ resolveSlow = resolve;+ });+ const fsMock: MainProcessWorkdirProbeFs = {+ stat: async () => {+ active += 1;+ maxActive = Math.max(maxActive, active);+ try {+ return await slow;+ } finally {+ active -= 1;+ }+ },+ mkdir: async () => undefined,+ realpath: async (dir) => dir,+ readdir: async () => [],+ };+ const client = new MainProcessWorkdirProbeClient({ log, fs: fsMock, maxInFlight: 1 });+ const first = client.probe('/slow/a', '/slow/a', 20).catch((error) => error);+ const second = client.probe('/slow/b', '/slow/b', 100).catch((error) => error);++ await vi.advanceTimersByTimeAsync(20);+ await expect(first).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });+ expect(maxActive).toBe(1);+ await vi.advanceTimersByTimeAsync(80);+ await expect(second).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });++ resolveSlow({ isDirectory: () => true });+ await vi.runAllTimersAsync();+ expect(maxActive).toBe(1);+ client.dispose();+ });++ it('keeps a timed-out path single-flighted until its filesystem operation settles', async () => {+ vi.useFakeTimers();+ let resolveSlow!: (value: { isDirectory(): boolean }) => void;+ let calls = 0;+ const slow = new Promise<{ isDirectory(): boolean }>((resolve) => {+ resolveSlow = resolve;+ });+ const fsMock: MainProcessWorkdirProbeFs = {+ stat: async () => {+ calls += 1;+ return slow;+ },+ mkdir: async () => undefined,+ realpath: async (dir) => dir,+ readdir: async () => [],+ };+ const client = new MainProcessWorkdirProbeClient({ log, fs: fsMock });+ const first = client.probe('/slow', '/slow', 20);+ const firstError = first.catch((error) => error);++ await vi.advanceTimersByTimeAsync(20);+ await expect(firstError).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });+ const retryWhileIoPending = client.probe('/slow', '/slow', 100);+ const retryWhileIoPendingError = retryWhileIoPending.catch((error) => error);+ expect(retryWhileIoPending).toBe(first);+ expect(calls).toBe(1);+ await expect(retryWhileIoPendingError).resolves.toMatchObject({+ code: 'WORKDIR_PROBE_TIMEOUT',+ });++ resolveSlow({ isDirectory: () => true });+ await vi.runAllTimersAsync();+ const retryAfterIoSettles = client.probe('/slow', '/slow', 100);+ expect(retryAfterIoSettles).not.toBe(first);+ expect(calls).toBe(2);+ await expect(retryAfterIoSettles).resolves.toMatchObject({ ok: true, isDirectory: true });+ client.dispose();+ });++ it('rejects active probes immediately when disposed while letting I/O settle', async () => {+ let resolveSlow!: (value: { isDirectory(): boolean }) => void;+ const slow = new Promise<{ isDirectory(): boolean }>((resolve) => {+ resolveSlow = resolve;+ });+ const fsMock: MainProcessWorkdirProbeFs = {+ stat: async () => slow,+ mkdir: async () => undefined,+ realpath: async (dir) => dir,+ readdir: async () => [],+ };+ const client = new MainProcessWorkdirProbeClient({ log, fs: fsMock });+ const probe = client.probe('/slow', '/slow', 5_000).catch((error) => error);++ await Promise.resolve();+ client.dispose();+ await expect(probe).resolves.toMatchObject({ code: 'WORKDIR_PROBE_UNAVAILABLE' });+ await expect(client.probe('/slow', '/slow', 5_000)).rejects.toMatchObject({+ code: 'WORKDIR_PROBE_UNAVAILABLE',+ });++ resolveSlow({ isDirectory: () => true });+ await Promise.resolve();+ });+});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.tsdeleted file mode 100644index abf2a42a2f..0000000000--- a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostClient.test.ts+++ /dev/null@@ -1,286 +0,0 @@-import { EventEmitter } from 'node:events';--import { afterEach, describe, expect, it, vi } from 'vitest';--import {- WorkdirProbeHostClient,- type WorkdirProbeChildLike,-} from '../WorkdirProbeHostClient.js';-import type { WorkdirProbeRequest, WorkdirProbeResponse } from '../protocol.js';--class FakeChild extends EventEmitter implements WorkdirProbeChildLike {- readonly posted: WorkdirProbeRequest[] = [];- killResult = true;- kill = vi.fn(() => this.killResult);-- postMessage(message: unknown): void {- this.posted.push(message as WorkdirProbeRequest);- }-- respond(isDirectory = true): void {- const request = this.posted.at(-1)!;- const response: WorkdirProbeResponse = {- kind: 'result',- id: request.id,- result: { ok: true, isDirectory },- };- this.emit('message', response);- }-}--function createHarness(options: { maxWorkers?: number; maxQueued?: number } = {}) {- const children: FakeChild[] = [];- const log = { debug: vi.fn(), warn: vi.fn() };- const client = new WorkdirProbeHostClient({- fork: () => {- const child = new FakeChild();- children.push(child);- return child;- },- log,- ...options,- });- return { client, children, log };-}--afterEach(() => {- vi.useRealTimers();-});--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 });- 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.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,- }));- 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.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.debug).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.debug.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.debug).toHaveBeenCalledWith('workdir probe filesystem result', expect.objectContaining({- reason: 'filesystem-error', code: code === 'PRIVATE_CREDENTIAL' ? 'UNKNOWN' : code, requestId: 1,- }));- expect(log.warn).not.toHaveBeenCalled();- expect(JSON.stringify(log.debug.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 });- const operation = client.probe('/share/a', '/share/a', 50, kind);- const failure = operation.catch((error) => error);- const stat = client.probe('/share/a', '/share/a', 150);- expect(children[0].posted[0].kind).toBe(kind);- await vi.advanceTimersByTimeAsync(50);- await expect(failure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });- expect(children[0].kill).toHaveBeenCalledOnce();- children[0].respond();- expect(children).toHaveLength(1);- children[0].emit('exit', 0);- expect(children[1].posted[0].kind).toBe('probe');- children[1].respond();- await expect(stat).resolves.toEqual({ ok: true, isDirectory: true });- client.dispose();- });-- it('single-flights equivalent paths', async () => {- const { client, children } = createHarness();-- const first = client.probe('/share/a', '/share/a', 1_000);- const second = client.probe('/share/a/', '/share/a', 1_000);-- expect(children).toHaveLength(1);- expect(children[0].posted).toHaveLength(1);- children[0].respond();- await expect(Promise.all([first, second])).resolves.toEqual([- { ok: true, isDirectory: true },- { ok: true, isDirectory: true },- ]);- client.dispose();- });-- it('kills timed-out hosts, releases slots, and runs a queued healthy probe', async () => {- vi.useFakeTimers();- const { client, children } = createHarness({ maxWorkers: 2 });-- const first = client.probe('/share/a', '/share/a', 100);- const second = client.probe('/share/b', '/share/b', 100);- const healthy = client.probe('/local/healthy', '/local/healthy', 200);- const failures = Promise.allSettled([first, second]);-- expect(children).toHaveLength(2);- expect(children[0].posted[0].dir).toBe('/share/a');- expect(children[1].posted[0].dir).toBe('/share/b');-- await vi.advanceTimersByTimeAsync(100);-- expect(children[0].kill).toHaveBeenCalledOnce();- expect(children[1].kill).toHaveBeenCalledOnce();- expect(children).toHaveLength(2);- children[0].emit('exit', 0);- children[1].emit('exit', 0);- expect(children).toHaveLength(3);- expect(children[2].posted[0].dir).toBe('/local/healthy');- children[2].respond();-- await expect(healthy).resolves.toEqual({ ok: true, isDirectory: true });- await expect(failures).resolves.toEqual([- expect.objectContaining({ status: 'rejected' }),- expect.objectContaining({ status: 'rejected' }),- ]);- client.dispose();- });-- it('allows the same path to retry on a fresh host after timeout', async () => {- vi.useFakeTimers();- const { client, children } = createHarness({ maxWorkers: 1 });-- const first = client.probe('/share/a', '/share/a', 50);- const firstFailure = first.catch((error) => error);- await vi.advanceTimersByTimeAsync(50);- await expect(firstFailure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });- children[0].emit('exit', 0);-- const retry = client.probe('/share/a', '/share/a', 50);- expect(children).toHaveLength(2);- children[1].respond();- await expect(retry).resolves.toEqual({ ok: true, isDirectory: true });- client.dispose();- });-- it('waits for a busy slot but bounds the queue', async () => {- vi.useFakeTimers();- const { client } = createHarness({ maxWorkers: 1, maxQueued: 1 });-- const active = client.probe('/share/a', '/share/a', 100);- const queued = client.probe('/share/b', '/share/b', 100);- const overflow = client.probe('/share/c', '/share/c', 100);- const settled = Promise.allSettled([active, queued]);-- await expect(overflow).rejects.toMatchObject({ code: 'WORKDIR_PROBE_UNAVAILABLE' });- await vi.advanceTimersByTimeAsync(100);- await expect(settled).resolves.toEqual([- expect.objectContaining({ status: 'rejected' }),- expect.objectContaining({ status: 'rejected' }),- ]);- client.dispose();- });-- it('does not replace a timed-out host until exit is confirmed, even when kill returns false', async () => {- vi.useFakeTimers();- const { client, children } = createHarness({ maxWorkers: 1 });-- const first = client.probe('/share/a', '/share/a', 50);- children[0].killResult = false;- const firstFailure = first.catch((error) => error);- await vi.advanceTimersByTimeAsync(50);- await expect(firstFailure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });-- const second = client.probe('/local/healthy', '/local/healthy', 100);- expect(children).toHaveLength(1);- expect(children[0].kill).toHaveReturnedWith(false);-- children[0].emit('exit', 0);- expect(children).toHaveLength(2);- children[1].respond();- await expect(second).resolves.toEqual({ ok: true, isDirectory: true });- client.dispose();- });-- it('shares one end-to-end deadline between queue wait and active probing', async () => {- vi.useFakeTimers();- const { client, children } = createHarness({ maxWorkers: 1 });-- const blocker = client.probe('/share/a', '/share/a', 100);- const blockerFailure = blocker.catch((error) => error);- const queued = client.probe('/share/b', '/share/b', 150);- let queuedSettled = false;- const queuedFailure = queued.catch((error) => {- queuedSettled = true;- return error;- });-- await vi.advanceTimersByTimeAsync(100);- await expect(blockerFailure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });- children[0].emit('exit', 0);- expect(children[1].posted[0].dir).toBe('/share/b');-- await vi.advanceTimersByTimeAsync(49);- expect(queuedSettled).toBe(false);- await vi.advanceTimersByTimeAsync(1);- await expect(queuedFailure).resolves.toMatchObject({ code: 'WORKDIR_PROBE_TIMEOUT' });- client.dispose();- });-});diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.tsindex 0adf75c1af..4324d701d9 100644--- a/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/WorkdirProbeHostPackaging.test.ts@@ -1,36 +1,28 @@-/** workdirProbeHostPackaging.test — 目录探测隔离进程的打包与权限边界契约。 */-+/** Directory probing stays asynchronous inside Electron main. */import fs from 'node:fs';import path from 'node:path';-import { describe, expect, it } from 'vitest';const desktopRoot = path.resolve(process.cwd());-describe('workdir probe host packaging contract', () => {- it('将 utility-process 入口打成独立 CJS bundle', () => {+describe('workdir probe packaging contract', () => {+ it('does not package a utility-process probe host', () => {const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');const wiring = fs.readFileSync(path.join(desktopRoot, 'src/main/workdir-probe-host/index.ts'),'utf8',);-- expect(forge).toContain("entry: 'src/main/workdir-probe-host/workdirProbeHostProcess.ts'");- expect(forge).toContain("config: 'vite.preload.config.ts'");- expect(forge).toContain("target: 'preload'");- expect(wiring).toContain("path.join(__dirname, 'workdirProbeHostProcess.js')");- expect(wiring).toContain('utilityProcess.fork');- expect(wiring).toContain("app.once('before-quit'");+ expect(forge).not.toContain('workdir-probe-host/workdirProbeHostProcess.ts');+ expect(wiring).not.toContain('utilityProcess');+ expect(wiring).toContain('MainProcessWorkdirProbeClient');});- it('不向探测进程继承完整环境或宿主 cwd', () => {+ it('keeps the probe deadline and quit cleanup in the main process', () => {const wiring = fs.readFileSync(path.join(desktopRoot, 'src/main/workdir-probe-host/index.ts'),'utf8',);-- expect(wiring).toContain('const env: NodeJS.ProcessEnv = {}');- expect(wiring).not.toContain('...process.env');- expect(wiring).toContain('cwd: os.tmpdir()');+ expect(wiring).toContain('5_000');+ expect(wiring).toContain("app.once('before-quit'");});});diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.tsdeleted file mode 100644index 3c8f6b46b6..0000000000--- a/apps/desktop/src/main/workdir-probe-host/__tests__/directoryOperations.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import fsp from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import { expect, it } from 'vitest';-import { runDirectoryOperation } from '../workdirProbeHostProcess.js';--it('creates only directories, resolves aliases and retains similar-path diagnostics inside the worker', async () => {- const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-directory-worker-'));- try {- const dir = path.join(root, 'nested', 'project');- expect(await runDirectoryOperation({ kind: 'mkdir', id: 1, dir })).toEqual({ ok: true, isDirectory: true });- expect(await runDirectoryOperation({ kind: 'realpath', id: 2, dir })).toMatchObject({ ok: true, path: await fsp.realpath(dir) });- expect(await runDirectoryOperation({ kind: 'probe', id: 3, dir })).toMatchObject({ ok: true, isDirectory: true });- expect(await runDirectoryOperation({ kind: 'similar', id: 4, dir: `${dir} ` })).toMatchObject({ ok: true, path: dir });- const file = path.join(root, 'file');- await fsp.writeFile(file, 'keep');- expect(await runDirectoryOperation({ kind: 'mkdir', id: 5, dir: file })).toMatchObject({ ok: false, code: 'EEXIST' });- expect(await fsp.readFile(file, 'utf8')).toBe('keep');- } finally {- await fsp.rm(root, { recursive: true, force: true });- }-});diff --git a/apps/desktop/src/main/workdir-probe-host/__tests__/index.test.ts b/apps/desktop/src/main/workdir-probe-host/__tests__/index.test.tsnew file mode 100644index 0000000000..e7c84a9663--- /dev/null+++ b/apps/desktop/src/main/workdir-probe-host/__tests__/index.test.ts@@ -0,0 +1,39 @@+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ dispose: vi.fn(),+ probe: vi.fn(),+}));++vi.mock('electron', () => ({+ app: { once: vi.fn() },+}));++vi.mock('../../logger.js', () => ({+ createLogger: vi.fn(() => ({ warn: vi.fn() })),+}));++vi.mock('../MainProcessWorkdirProbeClient.js', () => ({+ MainProcessWorkdirProbeClient: vi.fn(() => mocks),+}));++import { statWorkingDirectory } from '../index.js';++describe('workdir probe wiring', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.probe.mockResolvedValue({ ok: true, isDirectory: true });+ });++ it('normalizes equivalent paths before single-flight deduplication', async () => {+ const dir = path.join('relative', '..', 'workspace');++ await expect(statWorkingDirectory(dir)).resolves.toMatchObject({+ isDirectory: expect.any(Function),+ });++ expect(mocks.probe).toHaveBeenCalledWith(dir, path.resolve(dir), 5_000, 'probe');+ });+});diff --git a/apps/desktop/src/main/workdir-probe-host/index.ts b/apps/desktop/src/main/workdir-probe-host/index.tsindex bd9b4deefb..4033ec84d1 100644--- a/apps/desktop/src/main/workdir-probe-host/index.ts+++ b/apps/desktop/src/main/workdir-probe-host/index.ts@@ -1,53 +1,27 @@-/**- * Electron wiring for the bounded workdir probe utility-process pool.- */+/** Electron wiring for bounded asynchronous main-process directory probes. */-import os from 'node:os';+import { app } from 'electron';import path from 'node:path';-import { app, utilityProcess } from 'electron';import { createLogger } from '../logger.js';-import { WorkdirProbeHostClient } from './WorkdirProbeHostClient.js';+import { MainProcessWorkdirProbeClient } from './MainProcessWorkdirProbeClient.js';import type { WorkdirProbeRequest } from './protocol.js';const log = createLogger('workdir-diagnostics');-function forkProbeHost(): ReturnType<typeof utilityProcess.fork> {- const env: NodeJS.ProcessEnv = {};- for (const key of [- 'PATH',- 'SystemRoot',- 'WINDIR',- 'TMPDIR',- 'TEMP',- 'TMP',- 'LANG',- 'LC_ALL',- ] as const) {- if (process.env[key] !== undefined) env[key] = process.env[key];- }- return utilityProcess.fork(path.join(__dirname, 'workdirProbeHostProcess.js'), [], {- serviceName: 'xdt-workdir-probe-host',- // 避免继承 token/API key;只保留进程启动和本地化所需的系统变量。- env,- // 不继承可能恰好位于断线网络盘上的宿主 cwd。- cwd: os.tmpdir(),- });-}--export const workdirProbeHostClient = new WorkdirProbeHostClient({- fork: forkProbeHost,- log,-});+export const workdirProbeHostClient = new MainProcessWorkdirProbeClient({ log });/** Bounded filesystem identity probe for local cwd recovery; never expose paths to a controller. */async function directoryOperation(dir: string, kind: WorkdirProbeRequest['kind']) {const result = await workdirProbeHostClient.probe(dir, path.resolve(dir), 5_000, kind);- if (!result.ok) throw Object.assign(new Error('Working directory probe failed'), { code: result.code });+ if (!result.ok)+ throw Object.assign(new Error('Working directory probe failed'), { code: result.code });return result;}-export async function statWorkingDirectory(dir: string): Promise<{ isDirectory(): boolean; dev?: number }> {+export async function statWorkingDirectory(+ dir: string,+): Promise<{ isDirectory(): boolean; dev?: number }> {const result = await directoryOperation(dir, 'probe');return { isDirectory: () => result.isDirectory, dev: result.device };}@@ -66,8 +40,6 @@ export async function findSimilarWorkingDirectory(dir: string): Promise<string |return (await directoryOperation(dir, 'similar')).path ?? null;}-// 真实 Electron app 一定有 once;条件注册让引用 guard 的纯 Node 单测仍可使用-// 只覆盖自身所需字段的窄 electron stub,而不必为未执行的生命周期补整套假实现。if (typeof app.once === 'function') {app.once('before-quit', () => {workdirProbeHostClient.dispose();diff --git a/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.ts b/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.tsdeleted file mode 100644index c801642d04..0000000000--- a/apps/desktop/src/main/workdir-probe-host/workdirProbeHostProcess.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * Dedicated Electron utility-process entry for directory probes.- *- * The main process assigns at most one request at a time to each host. A stuck- * UNC/SMB stat is cancelled by terminating this process, never by accumulating- * uncancellable libuv work in Electron's main process.- */--import { stat, mkdir, realpath, readdir } from 'node:fs/promises';-import path from 'node:path';--import type {- WorkdirProbeRequest,- WorkdirProbeResponse,- WorkdirProbeResult,-} from './protocol';--interface ParentPortLike {- postMessage(message: unknown): void;- on(event: 'message', listener: (event: { data: unknown }) => void): void;-}--const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;--function filesystemErrorCode(error: unknown): string {- return error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'- ? (error as { code: string }).code- : 'UNKNOWN';-}--export async function runDirectoryOperation(request: WorkdirProbeRequest): Promise<WorkdirProbeResult> {- try {- if (request.kind === 'mkdir') {- await mkdir(request.dir, { recursive: true });- return { ok: true, isDirectory: true };- }- if (request.kind === 'realpath') {- return { ok: true, isDirectory: true, path: await realpath(request.dir) };- }- if (request.kind === 'similar') {- const parent = path.dirname(request.dir);- const target = path.basename(request.dir);- if (!target || parent === request.dir) return { ok: true, isDirectory: false, path: null };- const entries = await readdir(parent);- const match = entries.find((n) => n !== target && n.trim() === target.trim()) ??- entries.find((n) => n !== target && n.toLowerCase() === target.toLowerCase());- return { ok: true, isDirectory: false, path: match ? path.join(parent, match) : null };- }- const entry = await stat(request.dir);- return { ok: true, isDirectory: entry.isDirectory(), device: entry.dev };- } catch (error) {- return { ok: false, code: filesystemErrorCode(error) };- }-}--if (parentPort) {- parentPort.on('message', (event) => {- const request = event.data as Partial<WorkdirProbeRequest>;- if (- !['probe', 'mkdir', 'realpath', 'similar'].includes(request.kind ?? '') ||- typeof request.id !== 'number' ||- typeof request.dir !== 'string' ||- request.dir.length === 0- ) {- return;- }- void runDirectoryOperation(request as WorkdirProbeRequest)- .then((result) => {- const response: WorkdirProbeResponse = {- kind: 'result',- id: request.id!,- result,- };- parentPort.postMessage(response);- });- });-}