ai-helper-agent 2.4.6 → 2.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,65 +1,320 @@
1
- // agent/src/directory-picker.js - 系统原生目录选择框
2
- // 供扩展端"切换工作目录"弹窗的浏览按钮调用:仅本机代理(loopback)有意义,
3
- // 远端机器可能无桌面环境,弹窗用户也看不到(由 server.js 的来源 IP 门控兜底)。
1
+ // agent/src/directory-picker.js - 系统原生目录选择框(多后端兜底 + 完整诊断)
2
+ //
3
+ // 供扩展端「切换工作目录」弹窗的「浏览…」按钮调用,仅本机代理(loopback)才有意义:
4
+ // 工作目录本就是代理端机器上的路径,远端弹窗用户也看不到(server.js 另有来源 IP 门控)。
5
+ //
6
+ // Windows 企业环境里「点了没窗口」的常见成因:
7
+ // 1) Defender ASR「Block execution of potentially obfuscated scripts」拦截 -EncodedCommand
8
+ // 2) Constrained Language Mode / AppLocker 拦截 Add-Type 加载 .NET 程序集
9
+ // 3) 从 Git Bash 等非原生终端启动时 PATH / 环境变量被改写,PATH 查找不到 powershell.exe
10
+ // 因此按「内联 -Command(绝对路径)→ EncodedCommand → cscript + WSH」顺序兜底,
11
+ // 每个后端的失败原因都记录在 attempts 里;全部失败时把摘要回传给扩展端,避免“不知道怎么回事”。
12
+ //
13
+ // 稳定性约束(任何一条都不允许打破,否则会拖垮常驻的 agent 进程):
14
+ // - 本模块对外只 resolve 结果对象,绝不 reject / 绝不抛异常
15
+ // - 子进程有超时强杀 + 强杀后兜底 settle,保证请求不会永久悬挂
16
+ // - 子进程输出有长度上限,防止异常命令刷爆内存
17
+ // - 同一时刻只允许一个选择框,连点不会拉起多个窗口
4
18
  import { spawn } from 'child_process';
19
+ import fs from 'fs';
20
+ import os from 'os';
21
+ import path from 'path';
5
22
 
6
23
  // 选择框悬挂超时:用户长时间不选视为放弃,避免子进程常驻
7
24
  const PICK_TIMEOUT_MS = 120 * 1000;
25
+ // 强杀后等待 close 的兜底时长:某些后端被杀后不触发 close,不能因此让请求挂着
26
+ const KILL_SETTLE_MS = 2000;
27
+ // 单个子进程输出上限(字符)
28
+ const MAX_STREAM_CHARS = 64 * 1024;
29
+ // 回传给扩展端的错误摘要上限(toast 能展示的长度)
30
+ const MAX_ERROR_CHARS = 300;
31
+ const DEFAULT_TITLE = 'Select folder';
32
+
33
+ /** 清理标题:去掉会破坏脚本/参数的字符(各后端都把标题拼进脚本或参数) */
34
+ function sanitizeTitle(title) {
35
+ return String(title || '')
36
+ .replace(/["'\\`\r\n\t]/g, ' ')
37
+ .replace(/\s+/g, ' ')
38
+ .trim()
39
+ .slice(0, 120) || DEFAULT_TITLE;
40
+ }
41
+
42
+ function toBase64Utf8(text) {
43
+ return Buffer.from(String(text), 'utf8').toString('base64');
44
+ }
45
+
46
+ /**
47
+ * 解析 Windows 可执行文件的绝对路径
48
+ * 优先用 %SystemRoot% 拼绝对路径,彻底摆脱 Git Bash/MSYS 对 PATH 与环境变量的改写;
49
+ * 取不到 SystemRoot 时退回裸命令名,交由 PATH 查找。
50
+ */
51
+ function resolveWindowsExe(name, env) {
52
+ const root = (env && (env.SystemRoot || env.windir || env.WINDIR)) || '';
53
+ if (root) {
54
+ if (name === 'powershell') {
55
+ return path.win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
56
+ }
57
+ if (name === 'cscript') {
58
+ return path.win32.join(root, 'System32', 'cscript.exe');
59
+ }
60
+ }
61
+ return `${name}.exe`;
62
+ }
63
+
64
+ /**
65
+ * 解析可用于落临时文件的目录
66
+ * Windows 下优先 %LOCALAPPDATA%\Temp:从 Git Bash 等 MSYS 终端启动时 TEMP/TMP 可能被改写成
67
+ * POSIX 形式(/tmp),直接用 os.tmpdir() 会落到不可写的盘根,导致 VBS 兜底后端静默失效。
68
+ */
69
+ export function resolveTmpDir(platform, env = process.env) {
70
+ if (platform === 'win32') {
71
+ const local = env.LOCALAPPDATA || env.LocalAppData;
72
+ if (local) return path.win32.join(local, 'Temp');
73
+ const tmp = env.TEMP || env.TMP;
74
+ // 只接受驱动器绝对路径,避开 MSYS 风格的 /tmp
75
+ if (tmp && /^[A-Za-z]:[\\/]/.test(tmp)) return tmp;
76
+ }
77
+ return os.tmpdir();
78
+ }
79
+
80
+ /**
81
+ * Windows PowerShell 脚本主体(共享给 -Command / -EncodedCommand 两个后端)
82
+ * - 标题以 base64 传入并在脚本内解码:内联调用时命令行可保持纯 ASCII,避开代码页乱码
83
+ * - 选中路径以 UTF-8 base64 写 stdout:避开中文 Windows 控制台 GBK 输出被按 UTF-8 解码的乱码
84
+ * - 退出码约定:0=选中 / 2=用户取消 / 1=异常(异常信息写 stderr)
85
+ */
86
+ function buildPowerShellScript(title) {
87
+ const titleB64 = toBase64Utf8(sanitizeTitle(title));
88
+ return [
89
+ '$ErrorActionPreference = \'Stop\'',
90
+ `$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${titleB64}'))`,
91
+ 'try {',
92
+ 'Add-Type -AssemblyName System.Windows.Forms',
93
+ '$f = New-Object System.Windows.Forms.FolderBrowserDialog',
94
+ '$f.Description = $t',
95
+ '$owner = New-Object System.Windows.Forms.Form',
96
+ '$owner.TopMost = $true',
97
+ '$null = $owner.Handle',
98
+ 'if ($f.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($f.SelectedPath))); exit 0 }',
99
+ 'exit 2',
100
+ '} catch {',
101
+ '[Console]::Error.Write($_.Exception.GetType().Name + \': \' + $_.Exception.Message)',
102
+ 'exit 1',
103
+ '}',
104
+ ].join('; ');
105
+ }
8
106
 
9
107
  /**
10
- * 构造各平台的目录选择命令
108
+ * VBScript 兜底后端:走 WSH + Shell.Application.BrowseForFolder
109
+ * 与 PowerShell 完全不同的执行通道(不受 PowerShell 执行策略/语言模式影响),
110
+ * 是 -Command 与 -EncodedCommand 双双被拦时的第三通路。
111
+ * 脚本本身保持纯 ASCII(英文标题),避免 .vbs 文件编码解析问题;
112
+ * 选中路径写入临时文件(FSO Unicode = UTF-16LE),读回时不依赖控制台代码页。
113
+ */
114
+ function buildVbsScript(outputFile) {
115
+ const safeOut = String(outputFile).replace(/"/g, '""');
116
+ return [
117
+ 'Option Explicit',
118
+ 'On Error Resume Next',
119
+ 'Dim sh, folder, picked, fso, ts',
120
+ 'picked = ""',
121
+ 'Set sh = CreateObject("Shell.Application")',
122
+ 'If Err.Number <> 0 Then WScript.Quit 1',
123
+ 'Err.Clear',
124
+ 'Set folder = sh.BrowseForFolder(0, "Select working directory", 65, 0)',
125
+ 'If Err.Number <> 0 Then WScript.Quit 1',
126
+ 'Err.Clear',
127
+ 'If Not folder Is Nothing Then',
128
+ ' If Not folder.Self Is Nothing Then picked = folder.Self.Path',
129
+ 'End If',
130
+ 'Set fso = CreateObject("Scripting.FileSystemObject")',
131
+ 'If Err.Number <> 0 Then WScript.Quit 1',
132
+ 'Err.Clear',
133
+ `Set ts = fso.OpenTextFile("${safeOut}", 2, True, -1)`,
134
+ 'If Err.Number <> 0 Then WScript.Quit 1',
135
+ 'ts.Write picked',
136
+ 'ts.Close',
137
+ 'WScript.Quit 0',
138
+ '',
139
+ ].join('\r\n');
140
+ }
141
+
142
+ /** 规整选中路径:去首尾空白与尾部分隔符(根目录 "/" 与 "C:\\" 除外) */
143
+ export function normalizePickedPath(raw) {
144
+ let p = String(raw || '').trim();
145
+ while (p.length > 3 && /[\\/]$/.test(p)) p = p.slice(0, -1);
146
+ if (/^[A-Za-z]:$/.test(p)) p += '\\';
147
+ return p;
148
+ }
149
+
150
+ /** 路径合理性校验:排除乱码与控制字符(base64 误解码时会出现) */
151
+ function looksLikePath(value) {
152
+ const s = String(value || '').trim();
153
+ if (!s || s.length > 4096) return false;
154
+ if (/[\u0000-\u001f\ufffd]/.test(s)) return false;
155
+ return /[\\/]/.test(s);
156
+ }
157
+
158
+ /** PowerShell 后端:stdout 为 UTF-8 base64 编码的路径 */
159
+ function decodePowerShellOutput(stdout) {
160
+ const raw = String(stdout || '').trim();
161
+ if (!raw) return '';
162
+ // 只取最后一行非空内容(防止任何前缀噪声)
163
+ const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
164
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
165
+ const line = lines[i];
166
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(line) || line.length < 8) continue;
167
+ try {
168
+ const decoded = Buffer.from(line, 'base64').toString('utf8').trim();
169
+ if (looksLikePath(decoded)) return normalizePickedPath(decoded);
170
+ } catch { /* 非法 base64:继续找下一行 */ }
171
+ }
172
+ return '';
173
+ }
174
+
175
+ /** VBS 后端:路径写在临时文件里(FSO 以 UTF-16LE 写入,可能带 BOM) */
176
+ function readPickedFile(file) {
177
+ try {
178
+ if (!fs.existsSync(file)) return '';
179
+ let text = fs.readFileSync(file, 'utf16le');
180
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
181
+ const trimmed = text.trim();
182
+ return looksLikePath(trimmed) ? normalizePickedPath(trimmed) : '';
183
+ } catch {
184
+ return '';
185
+ }
186
+ }
187
+
188
+ /**
189
+ * 构造各平台的目录选择执行计划(按顺序尝试)
190
+ * 每个条目:{ backend, kind, command, args?, prepare? }
191
+ * - prepare() 用于需要落临时文件的后端,返回 { args, decode, cleanup, meta } 或 null(准备失败)
192
+ * - 无 prepare 的条目直接用 args + decode
11
193
  * @param {string} title - 选择框提示文案
12
194
  * @param {string} [platform] - 平台标识(默认 process.platform,测试可注入)
13
- * @returns {{command: string, args: string[], fallback?: {command: string, args: string[]}}}
195
+ * @param {object} [options] - { env, tmpDir }
196
+ * @returns {Array<object>}
14
197
  */
15
- export function buildPickCommand(title, platform = process.platform) {
16
- // 各命令均以参数数组形式传入(不经 shell),这里仅清理标题中的引号防止脚本注入
17
- const safeTitle = String(title || '').replace(/["'\\`]/g, '').trim() || 'Select folder';
198
+ export function buildPickPlan(title, platform = process.platform, options = {}) {
199
+ const env = options.env || process.env;
200
+ const tmpDir = options.tmpDir || resolveTmpDir(platform, env);
201
+ const safeTitle = sanitizeTitle(title);
18
202
 
19
203
  if (platform === 'darwin') {
20
- return {
204
+ return [{
205
+ backend: 'osascript',
206
+ kind: 'posix',
21
207
  command: 'osascript',
22
208
  args: ['-e', `POSIX path of (choose folder with prompt "${safeTitle}")`],
23
- };
209
+ decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
210
+ }];
24
211
  }
25
212
 
26
213
  if (platform === 'win32') {
27
- // FolderBrowserDialog 需要 STA 线程;TopMost owner 防止对话框被主窗口遮挡
28
- const script = [
29
- "Add-Type -AssemblyName System.Windows.Forms",
30
- "$f = New-Object System.Windows.Forms.FolderBrowserDialog",
31
- `$f.Description = '${safeTitle}'`,
32
- "$owner = New-Object System.Windows.Forms.Form -Property @{TopMost = $true}",
33
- "if ($f.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($f.SelectedPath) }",
34
- ].join('; ');
35
- // EncodedCommand(base64 UTF-16LE)避免命令行转义问题
36
- const encoded = Buffer.from(script, 'utf16le').toString('base64');
37
- return {
38
- command: 'powershell.exe',
39
- args: ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded],
40
- };
214
+ const psExe = resolveWindowsExe('powershell', env);
215
+ const cscriptExe = resolveWindowsExe('cscript', env);
216
+ const psScript = buildPowerShellScript(title);
217
+ const psCommon = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-STA'];
218
+
219
+ return [
220
+ {
221
+ // 后端 1:内联 -Command。脚本刻意不含双引号,避免 Node 参数转义与 PowerShell 解析冲突;
222
+ // 同时不经过 -EncodedCommand,绕开 ASR「可疑混淆脚本」规则的拦截。
223
+ backend: 'powershell-inline',
224
+ kind: 'powershell',
225
+ command: psExe,
226
+ args: [...psCommon, '-Command', psScript],
227
+ decode: (r) => decodePowerShellOutput(r.stdout),
228
+ },
229
+ {
230
+ // 后端 2:-EncodedCommand(base64 UTF-16LE),兼容极端转义场景,但可能被安全策略拦
231
+ backend: 'powershell-encoded',
232
+ kind: 'powershell',
233
+ command: psExe,
234
+ args: [...psCommon, '-EncodedCommand', Buffer.from(psScript, 'utf16le').toString('base64')],
235
+ decode: (r) => decodePowerShellOutput(r.stdout),
236
+ },
237
+ {
238
+ // 后端 3:cscript + WSH。完全独立的执行通道,用来覆盖 PowerShell 被策略整体封杀的情况
239
+ backend: 'cscript-vbs',
240
+ kind: 'vbs',
241
+ command: cscriptExe,
242
+ prepare() {
243
+ try {
244
+ const dir = fs.mkdtempSync(path.join(tmpDir, 'ai-helper-pick-'));
245
+ const scriptFile = path.join(dir, 'pick.vbs');
246
+ const outputFile = path.join(dir, 'picked.txt');
247
+ fs.writeFileSync(scriptFile, buildVbsScript(outputFile), 'utf8');
248
+ return {
249
+ args: ['//nologo', '//B', scriptFile],
250
+ decode: () => readPickedFile(outputFile),
251
+ cleanup() {
252
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 目录已被清理 */ }
253
+ },
254
+ meta: { scriptFile, outputFile },
255
+ };
256
+ } catch {
257
+ // 临时目录不可写(只读环境/权限受限):跳过该后端,不影响其它后端
258
+ return null;
259
+ }
260
+ },
261
+ },
262
+ ];
41
263
  }
42
264
 
43
265
  // Linux / 其他:zenity 优先,kdialog 回退
44
- return {
45
- command: 'zenity',
46
- args: ['--file-selection', '--directory', `--title=${safeTitle}`],
47
- fallback: {
266
+ return [
267
+ {
268
+ backend: 'zenity',
269
+ kind: 'posix',
270
+ command: 'zenity',
271
+ args: ['--file-selection', '--directory', `--title=${safeTitle}`],
272
+ decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
273
+ },
274
+ {
275
+ backend: 'kdialog',
276
+ kind: 'posix',
48
277
  command: 'kdialog',
49
278
  args: ['--getexistingdirectory', '~', '--title', safeTitle],
279
+ decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
50
280
  },
51
- };
281
+ ];
52
282
  }
53
283
 
54
- /** 规整选中路径:去首尾空白与 osascript POSIX path 的尾斜杠(根目录 "/" 除外) */
55
- function normalizePickedPath(raw) {
56
- let p = String(raw || '').trim();
57
- while (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1);
58
- return p;
284
+ /** 兼容旧调用:返回首选后端 */
285
+ export function buildPickCommand(title, platform = process.platform, options = {}) {
286
+ return buildPickPlan(title, platform, options)[0];
287
+ }
288
+
289
+ /** 子进程退出语义 → 统一结果:严格区分「用户取消」与「失败原因」,失败时携带诊断信息 */
290
+ function classifyPickResult(runResult, item) {
291
+ const picked = item.decode ? item.decode(runResult) : '';
292
+ if (picked) return { success: true, path: picked, available: true };
293
+
294
+ const code = runResult.code;
295
+ const errText = String(runResult.stderr || '').trim();
296
+
297
+ if (item.kind === 'powershell' || item.kind === 'vbs') {
298
+ // 退出码是我们自己脚本约定的:2=取消;0=对话框正常关闭但没选
299
+ if (code === 2 || code === 0) return { success: true, path: null, available: true };
300
+ return {
301
+ success: false,
302
+ path: null,
303
+ available: true,
304
+ exitCode: code ?? null,
305
+ error: `exit ${code === null || code === undefined ? 'unknown' : code}${errText ? `: ${errText}` : '(无 stderr,可能被安全策略拦截)'}`,
306
+ };
307
+ }
308
+
309
+ // POSIX:无 stderr 的非零退出、或 stderr 明确是取消 → 视为用户取消
310
+ if (!errText) return { success: true, path: null, available: true };
311
+ if (/cancel|取消|-128/i.test(errText)) return { success: true, path: null, available: true };
312
+ return { success: false, path: null, available: true, exitCode: code ?? null, error: errText };
59
313
  }
60
314
 
61
315
  /**
62
- * 运行单个选择命令,收集 stdout;spawn 失败(ENOENT 等)与超时均以结果对象返回,不抛异常
316
+ * 运行单个选择命令,收集 stdout/stderr
317
+ * spawn 失败(ENOENT 等)、超时、被信号杀死等一律以结果对象返回,不抛异常
63
318
  */
64
319
  function runPickOnce(command, args, timeoutMs, spawnImpl) {
65
320
  return new Promise((resolve) => {
@@ -71,64 +326,176 @@ function runPickOnce(command, args, timeoutMs, spawnImpl) {
71
326
  return;
72
327
  }
73
328
  let stdout = '';
329
+ let stderr = '';
74
330
  let timedOut = false;
75
331
  let settled = false;
332
+ let timer = null;
76
333
  const finish = (result) => {
77
334
  if (settled) return;
78
335
  settled = true;
79
- clearTimeout(timer);
336
+ if (timer) clearTimeout(timer);
80
337
  resolve(result);
81
338
  };
82
- const timer = setTimeout(() => {
339
+ timer = setTimeout(() => {
83
340
  timedOut = true;
84
- try { child.kill(); } catch { /* 进程已退出 */ }
341
+ try { child.kill(); } catch { /* 进程可能已退出 */ }
342
+ // 兜底 settle:被杀进程若始终不触发 close,也不能让 HTTP 请求挂着
343
+ setTimeout(() => finish({ code: null, stdout, stderr, timedOut: true }), KILL_SETTLE_MS);
85
344
  }, timeoutMs);
86
- child.stdout?.on?.('data', (d) => { stdout += d; });
87
- child.stderr?.on?.('data', () => {});
345
+ // 管道自身的 error(EPIPE/ECONNRESET,进程被杀或管道先行关闭时可能出现)必须监听:
346
+ // EventEmitter 的 'error' 事件若无监听者会被抛成 uncaughtException
347
+ child.stdout?.on?.('error', () => {});
348
+ child.stderr?.on?.('error', () => {});
349
+ child.stdout?.on?.('data', (chunk) => {
350
+ if (stdout.length < MAX_STREAM_CHARS) stdout += chunk.toString();
351
+ });
352
+ child.stderr?.on?.('data', (chunk) => {
353
+ if (stderr.length < MAX_STREAM_CHARS) stderr += chunk.toString();
354
+ });
88
355
  // spawn 失败(命令不存在等)以异步 error 事件呈现
89
356
  child.on?.('error', (err) => finish({ spawnError: true, stderr: String(err?.message || err) }));
90
- child.on?.('close', (code) => finish({ code, stdout, stderr: '', timedOut }));
357
+ child.on?.('close', (code) => finish({ code, stdout, stderr, timedOut }));
91
358
  });
92
359
  }
93
360
 
94
- /**
95
- * 弹出系统原生目录选择框
96
- * @param {string} [title] - 选择框提示文案
97
- * @param {object} [options] - spawnImpl(测试注入)/ timeoutMs / platform(测试注入)/ hasDisplay(测试注入,Linux 无图形会话判定)
98
- * @returns {Promise<{success: boolean, path: string|null, available: boolean, error?: string}>}
99
- * - 选中:{ success: true, path, available: true }
100
- * - 用户取消:{ success: true, path: null, available: true }
101
- * - 环境不支持(命令不存在/无图形会话):{ success: false, path: null, available: false }
102
- * - 超时等其他错误:{ success: false, path: null, available: true, error }
103
- */
104
- export async function pickDirectoryNative(title = '', options = {}) {
361
+ /** 把各后端失败原因压缩成一行摘要,供 toast 与日志使用 */
362
+ function summarizeAttempts(attempts) {
363
+ const text = attempts
364
+ .filter((a) => a && a.error)
365
+ .map((a) => `${a.backend}: ${a.error}`)
366
+ .join(' | ');
367
+ return text.length > MAX_ERROR_CHARS ? `${text.slice(0, MAX_ERROR_CHARS)}…` : text;
368
+ }
369
+
370
+ /** 进行中的选择:同一时刻只允许一个窗口,避免连点拉起多个弹窗把 agent 拖住 */
371
+ let inFlight = null;
372
+
373
+ async function doPickDirectory(title, options) {
374
+ const platform = options.platform ?? process.platform;
375
+ const env = options.env || process.env;
105
376
  const spawnImpl = options.spawnImpl || spawn;
106
377
  const timeoutMs = options.timeoutMs ?? PICK_TIMEOUT_MS;
107
- const platform = options.platform ?? process.platform;
108
- const hasDisplay = options.hasDisplay ?? Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
109
378
 
110
379
  // 无图形会话的 Linux 直接降级(zenity/kdialog 起不来,只会白白报错)
111
- if (platform === 'linux' && !hasDisplay) {
112
- return { success: false, path: null, available: false, error: 'no-display' };
380
+ if (platform === 'linux') {
381
+ const hasDisplay = options.hasDisplay ?? Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
382
+ if (!hasDisplay) {
383
+ return { success: false, path: null, available: false, error: 'no-display', attempts: [] };
384
+ }
113
385
  }
114
386
 
115
- const plan = buildPickCommand(title, platform);
116
- const attempts = plan.fallback ? [plan, plan.fallback] : [plan];
387
+ const plan = buildPickPlan(title, platform, { env, tmpDir: options.tmpDir });
117
388
 
118
- for (const { command, args } of attempts) {
119
- const r = await runPickOnce(command, args, timeoutMs, spawnImpl);
120
- if (r.spawnError) continue; // 该命令不可用,尝试回退
121
- if (r.timedOut) {
122
- return { success: false, path: null, available: true, error: 'timeout' };
389
+ const attempts = [];
390
+ let lastTimeout = null;
391
+
392
+ for (const item of plan) {
393
+ let prepared = null;
394
+ try {
395
+ prepared = item.prepare
396
+ ? item.prepare()
397
+ : { args: item.args, decode: item.decode, cleanup: null, meta: null };
398
+ } catch (err) {
399
+ attempts.push({ backend: item.backend, error: `prepare-failed: ${err?.message || err}` });
400
+ continue;
123
401
  }
124
- const path = normalizePickedPath(r.stdout);
125
- if (path) {
126
- return { success: true, path, available: true };
402
+ if (!prepared) {
403
+ attempts.push({ backend: item.backend, error: 'prepare-failed: 临时文件不可写' });
404
+ continue;
127
405
  }
128
- // 空输出(无论退出码):用户取消选择
129
- return { success: true, path: null, available: true };
406
+
407
+ try {
408
+ const r = await runPickOnce(item.command, prepared.args, timeoutMs, spawnImpl);
409
+ if (r.spawnError) {
410
+ // 该命令不可用(未安装/路径不对/无法执行),记录原因后尝试下一个后端
411
+ attempts.push({ backend: item.backend, error: `spawn-failed: ${String(r.stderr || '').slice(0, 160)}` });
412
+ continue;
413
+ }
414
+ if (r.timedOut) {
415
+ // 进程起来了却没有结果:多见于「窗口被策略挡住/不可见」或用户一直没选
416
+ lastTimeout = {
417
+ backend: item.backend,
418
+ detail: String(r.stderr || '').trim().slice(0, 160),
419
+ };
420
+ attempts.push({ backend: item.backend, error: `timeout${lastTimeout.detail ? `: ${lastTimeout.detail}` : '(窗口未在时限内返回,可能被安全策略拦截或不可见)'}` });
421
+ // 超时意味着窗口可能真的弹出来了,不再继续拉第二个窗口
422
+ break;
423
+ }
424
+ const result = classifyPickResult(r, { kind: item.kind, decode: prepared.decode });
425
+ if (result.success) {
426
+ return { ...result, backend: item.backend, attempts };
427
+ }
428
+ attempts.push({ backend: item.backend, exitCode: r.code ?? null, error: result.error });
429
+ } catch (err) {
430
+ // 单个后端内的任何意外都不能中断整体流程,更不能冒泡到 HTTP 层
431
+ attempts.push({ backend: item.backend, error: `unexpected: ${err?.message || err}` });
432
+ } finally {
433
+ try { prepared.cleanup?.(); } catch { /* 清理失败不影响结果 */ }
434
+ }
435
+ }
436
+
437
+ const summary = summarizeAttempts(attempts);
438
+ if (lastTimeout) {
439
+ return {
440
+ success: false,
441
+ path: null,
442
+ available: true,
443
+ error: 'timeout',
444
+ backend: lastTimeout.backend,
445
+ detail: lastTimeout.detail || '',
446
+ attempts,
447
+ diagnostics: summary,
448
+ };
130
449
  }
450
+ // 全部后端都没能弹出窗口:区分「根本没有可用工具」与「工具在但执行失败」
451
+ const noTool = plan.length > 0 && attempts.length === plan.length
452
+ && attempts.every((a) => String(a.error || '').startsWith('spawn-failed'));
453
+ return {
454
+ success: false,
455
+ path: null,
456
+ available: false,
457
+ error: noTool ? `no-dialog-tool: ${summary}` : `all-backends-failed: ${summary}`,
458
+ attempts,
459
+ diagnostics: summary,
460
+ };
461
+ }
462
+
463
+ /**
464
+ * 弹出系统原生目录选择框
465
+ * @param {string} [title] - 选择框提示文案
466
+ * @param {object} [options] - spawnImpl / timeoutMs / platform / env / tmpDir / hasDisplay(均为可注入,便于测试)
467
+ * @returns {Promise<{success: boolean, path: string|null, available: boolean, backend?: string,
468
+ * error?: string, attempts?: Array<object>, diagnostics?: string}>}
469
+ * - 选中:{ success: true, path, available: true, backend }
470
+ * - 用户取消:{ success: true, path: null, available: true }
471
+ * - 环境不支持:{ success: false, path: null, available: false, error: 'no-dialog-tool: …' | 'no-display' }
472
+ * - 后端都失败:{ success: false, path: null, available: false, error: 'all-backends-failed: …', attempts }
473
+ * - 超时:{ success: false, path: null, available: true, error: 'timeout', attempts }
474
+ * - 已有窗口在等待:{ success: false, path: null, available: true, error: 'busy' }
475
+ * 本函数永不 reject。
476
+ */
477
+ export async function pickDirectoryNative(title = '', options = {}) {
478
+ if (inFlight) {
479
+ return { success: false, path: null, available: true, error: 'busy', attempts: [] };
480
+ }
481
+ inFlight = doPickDirectory(title, options || {});
482
+ try {
483
+ return await inFlight;
484
+ } catch (err) {
485
+ // 极限兜底:任何漏网异常都转成结果对象,绝不让 HTTP 层 500 或进程崩溃
486
+ return {
487
+ success: false,
488
+ path: null,
489
+ available: true,
490
+ error: `internal: ${err?.message || err}`,
491
+ attempts: [],
492
+ };
493
+ } finally {
494
+ inFlight = null;
495
+ }
496
+ }
131
497
 
132
- // 所有候选命令均不可用
133
- return { success: false, path: null, available: false, error: 'no-dialog-tool' };
498
+ /** 测试用:查询是否有选择框正在等待 */
499
+ export function isPickInFlight() {
500
+ return Boolean(inFlight);
134
501
  }
package/src/server.js CHANGED
@@ -995,15 +995,42 @@ export function startServer() {
995
995
  logSecurity('pick_directory_remote_blocked', { remote: remoteIp, extId });
996
996
  return jsonResponse(res, 200, { success: false, path: null, available: false, error: 'remote-source' });
997
997
  }
998
+ // 这是全服务里唯一可能耗时数分钟的端点(等用户选目录):客户端很可能在此期间
999
+ // 关闭侧边栏/断开。向已销毁的 res 写入会触发流错误,因此统一走安全响应。
1000
+ const respond = (payload) => {
1001
+ if (res.writableEnded || res.destroyed) return;
1002
+ try {
1003
+ jsonResponse(res, 200, payload);
1004
+ } catch (err) {
1005
+ try { logError('config', 'pick_directory_respond_failed', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
1006
+ }
1007
+ };
998
1008
  try {
999
- const result = await pickDirectoryNative(typeof body.title === 'string' ? body.title : '');
1009
+ const title = typeof body.title === 'string' ? body.title.slice(0, 120) : '';
1010
+ // pickDirectoryNative 内部已做多后端兜底、超时强杀与异常吸收,此处只会拿到结果对象
1011
+ const result = await pickDirectoryNative(title);
1000
1012
  if (result.success && result.path) {
1001
- logSystem('directory_picked', { path: result.path, extId });
1013
+ logSystem('directory_picked', { path: result.path, backend: result.backend || '', extId });
1014
+ } else if (!result.success && result.error !== 'busy') {
1015
+ // busy 是并发保护的正常分支(已有窗口在等),不算失败
1016
+ // 其余记录各后端真实失败原因(无桌面会话 / 被安全策略拦截 / 超时等),
1017
+ // 用户端只看得到摘要,完整 attempts 落到日志里备查
1018
+ logError('config', 'pick_directory_failed', {
1019
+ error: result.error,
1020
+ backend: result.backend || '',
1021
+ exitCode: result.exitCode,
1022
+ available: result.available,
1023
+ attempts: Array.isArray(result.attempts) ? result.attempts : [],
1024
+ extId,
1025
+ });
1002
1026
  }
1003
- return jsonResponse(res, 200, result);
1027
+ respond(result);
1028
+ return;
1004
1029
  } catch (err) {
1005
- logError('config', 'pick_directory_error', { error: err.message });
1006
- return jsonResponse(res, 500, { success: false, path: null, available: true, error: err.message });
1030
+ // 兜底:即便 picker 自身出意外,也只返回结构化错误,不影响 agent 其它接口
1031
+ try { logError('config', 'pick_directory_error', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
1032
+ respond({ success: false, path: null, available: true, error: err.message });
1033
+ return;
1007
1034
  }
1008
1035
  }
1009
1036