dsh-delete-session 0.2.3 → 0.2.5

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.
package/src/index.js CHANGED
@@ -258,6 +258,20 @@ public static class Program {
258
258
  const RECYCLE_EXE_VERSION = 1
259
259
  const RECYCLE_TIMEOUT_MS = 60 * 1000
260
260
 
261
+ /** The C# compiler that ships with .NET Framework, if this machine has it. */
262
+ function findCsc() {
263
+ const windir = process.env.WINDIR || 'C:\\Windows'
264
+ for (const flavor of ['Framework64', 'Framework']) {
265
+ const candidate = path.join(windir, 'Microsoft.NET', flavor, 'v4.0.30319', 'csc.exe')
266
+ try {
267
+ if (fs.statSync(candidate).isFile()) return candidate
268
+ } catch {
269
+ // try the next flavour
270
+ }
271
+ }
272
+ return null
273
+ }
274
+
261
275
  /** Compile the recycle helper once into the DSH cache; null when it cannot. */
262
276
  async function ensureRecycleExe() {
263
277
  if (process.platform !== 'win32') return null
@@ -300,7 +314,6 @@ async function ensureRecycleExe() {
300
314
  function warmCompiledHelpers() {
301
315
  if (process.platform !== 'win32') return
302
316
  const warm = async () => {
303
- try { await ensurePickerExe() } catch { /* the fallback covers it */ }
304
317
  try { await ensureRecycleExe() } catch { /* the fallback covers it */ }
305
318
  }
306
319
  void warm()
@@ -393,7 +406,7 @@ async function sendToRecycleBin(targets) {
393
406
  await fsp.writeFile(scriptPath, bytes)
394
407
  output = await runPowershell(
395
408
  ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
396
- PICK_TIMEOUT_MS,
409
+ SHELL_TIMEOUT_MS,
397
410
  )
398
411
  } catch {
399
412
  return false
@@ -845,238 +858,21 @@ async function retireSessionFiles(sessionId, recycle) {
845
858
 
846
859
  const QUARANTINE_PREFIX = 'purge-quarantine'
847
860
  const MAX_LISTED = 500
861
+ /**
862
+ * How many distinct paths one scan will resolve. Every path costs a realpath,
863
+ * and a session that walked a large tree can name tens of thousands of them;
864
+ * the dialog would sit on "scanning" for as long as they take. Past this the
865
+ * plan reports `truncated`, which the dialog already surfaces.
866
+ */
867
+ const MAX_SCANNED = 2000
848
868
  /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
849
869
  const RESOLVE_CONCURRENCY = 16
850
870
  /** How many directories the folder picker lists before saying there are more. */
851
871
  const MAX_BROWSE_ENTRIES = 500
852
- /** How long a native folder dialog may stay open before the request gives up. */
872
+ /** How long the OS chooser may stay open before the request gives up on it. */
853
873
  const PICK_TIMEOUT_MS = 5 * 60 * 1000
854
-
855
- /**
856
- * The folder picker.
857
- *
858
- * Windows offers its modern chooser through COM (`IFileOpenDialog` +
859
- * `FOS_PICKFOLDERS`), and the interesting part is not the dialog but the wait
860
- * before it. Measured on the target machine:
861
- *
862
- * PowerShell startup ......... ~520 ms
863
- * + Windows.Forms assembly .... ~950 ms (left over from the old
864
- * `FolderBrowserDialog` version)
865
- * compiled .exe, no console ... ~120 ms
866
- *
867
- * So the picker is a tiny executable: compiled once into the DSH home, spawned
868
- * directly afterwards. The PowerShell script below stays as the fallback for a
869
- * machine without `csc.exe`.
870
- *
871
- * The executable runs with `windowsHide`, which hides the first window it shows,
872
- * so a background thread calls `ShowWindow(SW_SHOW)` and raises it. That thread
873
- * also centres the dialog and retries, because the window reports no final size
874
- * on the first tick.
875
- */
876
- const PICK_CSHARP = `
877
- using System;
878
- using System.Text;
879
- using System.Threading;
880
- using System.Runtime.InteropServices;
881
-
882
- public static class DshFolderPick {
883
- [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd);
884
- [DllImport("user32.dll")] static extern IntPtr SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
885
- [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr h);
886
- [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l);
887
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
888
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
889
- [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r);
890
- [DllImport("user32.dll")] static extern bool SystemParametersInfoW(uint action, uint param, out RECT rect, uint winIni);
891
- [DllImport("kernel32.dll")] static extern uint GetCurrentProcessId();
892
- delegate bool EnumProc(IntPtr h, IntPtr l);
893
-
894
- [StructLayout(LayoutKind.Sequential)]
895
- struct RECT { public int Left, Top, Right, Bottom; }
896
-
897
- static IntPtr FindDialog() {
898
- uint me = GetCurrentProcessId();
899
- IntPtr found = IntPtr.Zero;
900
- EnumWindows((h, l) => {
901
- uint pid;
902
- GetWindowThreadProcessId(h, out pid);
903
- if (pid == me) {
904
- var cls = new StringBuilder(128, 128);
905
- GetClassNameW(h, cls, 128);
906
- if (cls.ToString().StartsWith("#32770") && found == IntPtr.Zero) found = h;
907
- }
908
- return true;
909
- }, IntPtr.Zero);
910
- return found;
911
- }
912
-
913
- static void Raise() {
914
- bool centered = false;
915
- for (int i = 0; i < 80; i++) {
916
- Thread.Sleep(150);
917
- IntPtr h = FindDialog();
918
- if (h == IntPtr.Zero) continue;
919
- ShowWindow(h, 5);
920
- if (!centered) {
921
- RECT work, box;
922
- if (SystemParametersInfoW(0x0030, 0, out work, 0) && GetWindowRect(h, out box)) {
923
- int w = box.Right - box.Left;
924
- int ht = box.Bottom - box.Top;
925
- int availW = work.Right - work.Left;
926
- int availH = work.Bottom - work.Top;
927
- // A half-built rect would park the window off screen, so only a
928
- // believable size that actually fits is allowed to move it.
929
- if (w > 600 && ht > 300 && w < availW && ht < availH) {
930
- int x = work.Left + (availW - w) / 2;
931
- int y = work.Top + (availH - ht) / 2;
932
- SetWindowPos(h, (IntPtr)(-1), x, y, 0, 0, 0x0001);
933
- centered = true;
934
- }
935
- }
936
- }
937
- SetWindowPos(h, (IntPtr)(-1), 0, 0, 0, 0, 0x0003);
938
- BringWindowToTop(h);
939
- }
940
- }
941
-
942
- [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
943
- interface IFileOpenDialog {
944
- [PreserveSig] int Show(IntPtr parent);
945
- void SetFileTypes(uint c, IntPtr f);
946
- void SetFileTypeIndex(uint i);
947
- void GetFileTypeIndex(out uint i);
948
- void Advise(IntPtr p, out uint c);
949
- void Unadvise(uint c);
950
- void SetOptions(uint fos);
951
- void GetOptions(out uint fos);
952
- void SetDefaultFolder(IShellItem i);
953
- void SetFolder(IShellItem i);
954
- void GetFolder(out IShellItem i);
955
- void GetCurrentSelection(out IShellItem i);
956
- void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string n);
957
- void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string n);
958
- void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string t);
959
- void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string t);
960
- void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string t);
961
- void GetResult(out IShellItem i);
962
- void AddPlace(IShellItem i, uint f);
963
- void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string e);
964
- void Close(int hr);
965
- void SetClientGuid(ref Guid g);
966
- void ClearClientData();
967
- void SetFilter(IntPtr f);
968
- }
969
-
970
- [ComImport, Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
971
- interface IShellItem {
972
- void BindToHandler(IntPtr pbc, ref Guid bhid, ref Guid riid, out IntPtr ppv);
973
- void GetParent(out IShellItem ppsi);
974
- void GetDisplayName(uint sigdn, out IntPtr name);
975
- void GetAttributes(uint mask, out uint attrs);
976
- void Compare(IShellItem psi, uint hint, out int order);
977
- }
978
-
979
- [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
980
- class FileOpenDialog { }
981
-
982
- public static string Show(string title, string okLabel) {
983
- var raiser = new Thread(Raise);
984
- raiser.IsBackground = true;
985
- raiser.Start();
986
-
987
- var dialog = (IFileOpenDialog)new FileOpenDialog();
988
- uint options;
989
- dialog.GetOptions(out options);
990
- dialog.SetOptions(options | 0x20u | 0x40u | 0x800u);
991
- if (title != null) dialog.SetTitle(title);
992
- if (okLabel != null) dialog.SetOkButtonLabel(okLabel);
993
-
994
- int hr = dialog.Show(IntPtr.Zero);
995
- if (hr != 0) return null;
996
-
997
- IShellItem item;
998
- dialog.GetResult(out item);
999
- IntPtr name;
1000
- item.GetDisplayName(0x80058000u, out name);
1001
- string path = Marshal.PtrToStringUni(name);
1002
- Marshal.FreeCoTaskMem(name);
1003
- return path;
1004
- }
1005
- }`
1006
-
1007
- /** The compiled form: the class above plus an entry point that prints one path. */
1008
- const PICK_EXE_SOURCE = PICK_CSHARP + `
1009
-
1010
- public static class Program {
1011
- public static int Main(string[] args) {
1012
- string picked = DshFolderPick.Show(args.Length > 0 ? args[0] : null, args.Length > 1 ? args[1] : null);
1013
- if (picked == null) return 1;
1014
- // Written as UTF-8 bytes rather than through Console.Out: its encoding
1015
- // depends on a console this process does not own, and paths are not ASCII.
1016
- byte[] bytes = System.Text.Encoding.UTF8.GetBytes(picked);
1017
- using (System.IO.Stream stdout = Console.OpenStandardOutput()) {
1018
- stdout.Write(bytes, 0, bytes.Length);
1019
- stdout.Flush();
1020
- }
1021
- return 0;
1022
- }
1023
- }`
1024
-
1025
- /** The fallback for a host without `csc.exe`: the same class through PowerShell. */
1026
- const PICK_SCRIPT = `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
1027
- $source = @'
1028
- ${PICK_CSHARP}
1029
- '@
1030
- Add-Type -TypeDefinition $source
1031
- $picked = [DshFolderPick]::Show('选择隔离夹保存位置', '选择此文件夹')
1032
- if ($picked) { [Console]::Out.Write($picked) }
1033
- `
1034
-
1035
- /** Bump when `PICK_EXE_SOURCE` changes, so a cached build is not reused. */
1036
- const PICK_EXE_VERSION = 1
1037
- /** Compiling once is slow; it happens on the first ever pick only. */
1038
- const PICK_COMPILE_TIMEOUT_MS = 60 * 1000
1039
-
1040
- /** The C# compiler that ships with .NET Framework, if this machine has it. */
1041
- function findCsc() {
1042
- const windir = process.env.WINDIR || 'C:\\Windows'
1043
- for (const flavor of ['Framework64', 'Framework']) {
1044
- const candidate = path.join(windir, 'Microsoft.NET', flavor, 'v4.0.30319', 'csc.exe')
1045
- try {
1046
- if (fs.statSync(candidate).isFile()) return candidate
1047
- } catch {
1048
- // try the next flavour
1049
- }
1050
- }
1051
- return null
1052
- }
1053
-
1054
- /**
1055
- * Compile the picker once into `$DSH_HOME/cache/dsh-delete-session`, then reuse
1056
- * it. Returns null when this machine cannot compile, so the caller falls back to
1057
- * the PowerShell path rather than failing the pick.
1058
- */
1059
- async function ensurePickerExe() {
1060
- if (process.platform !== 'win32') return null
1061
- const dir = path.join(dshHome(), 'cache', 'dsh-delete-session', `v${PICK_EXE_VERSION}`)
1062
- const exe = path.join(dir, 'dsh-folder-pick.exe')
1063
- if (await pathExists(exe)) return exe
1064
- const csc = findCsc()
1065
- if (csc === null) return null
1066
- try {
1067
- await fsp.mkdir(dir, { recursive: true })
1068
- const source = path.join(dir, 'picker.cs')
1069
- await fsp.writeFile(source, PICK_EXE_SOURCE, 'utf8')
1070
- const built = await runExecutable(csc, ['-nologo', '-target:exe', `-out:${exe}`, '-r:System.dll', source], PICK_COMPILE_TIMEOUT_MS)
1071
- try { await fsp.rm(source, { force: true }) } catch { /* best effort */ }
1072
- if (built.code === 0) {
1073
- if (await pathExists(exe)) return exe
1074
- }
1075
- } catch {
1076
- // fall through to the PowerShell path
1077
- }
1078
- return null
1079
- }
874
+ /** How long a shell helper (the recycle-bin script) may run before giving up. */
875
+ const SHELL_TIMEOUT_MS = 5 * 60 * 1000
1080
876
 
1081
877
  /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
1082
878
  function runExecutable(program, args, timeoutMs) {
@@ -1215,11 +1011,17 @@ async function collectSessionPaths(events, cwd, cache) {
1215
1011
  // names the same handful of files thousands of times, so awaiting per call
1216
1012
  // would buy one threadpool round trip per mention; this buys one per file.
1217
1013
  const named = new Set()
1014
+ let overflow = false
1218
1015
  for (const event of events) {
1219
1016
  const data = event && event.data
1220
1017
  if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1221
1018
  const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1222
- if (target !== undefined) named.add(target.path)
1019
+ if (target === undefined) continue
1020
+ if (named.size >= MAX_SCANNED && !named.has(target.path)) {
1021
+ overflow = true
1022
+ break
1023
+ }
1024
+ named.add(target.path)
1223
1025
  }
1224
1026
  await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1225
1027
  await identityKey(absolute, memo)
@@ -1274,7 +1076,7 @@ async function collectSessionPaths(events, cwd, cache) {
1274
1076
  else read.add(call.identity)
1275
1077
  }
1276
1078
 
1277
- return { created, modified }
1079
+ return { named: named.size, overflow, created, modified }
1278
1080
  }
1279
1081
 
1280
1082
  /**
@@ -1418,7 +1220,8 @@ async function planArtifacts(ctx, sessionId, cache, options) {
1418
1220
  }
1419
1221
  const { events, warning } = await readSessionEvents(ctx, sessionId)
1420
1222
  if (warning !== undefined) warnings.push(warning)
1421
- const { created, modified } = await collectSessionPaths(events, cwd, cache)
1223
+ const scan = await collectSessionPaths(events, cwd, cache)
1224
+ const { created, modified } = scan
1422
1225
  const createdPlan = await classifyPaths(created, cwd, home, options)
1423
1226
  const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1424
1227
  const refused = [...createdPlan.refused, ...modifiedPlan.refused]
@@ -1430,7 +1233,8 @@ async function planArtifacts(ctx, sessionId, cache, options) {
1430
1233
  created: createdPlan.allowed.slice(0, MAX_LISTED),
1431
1234
  modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1432
1235
  refused: refused.slice(0, MAX_LISTED),
1433
- truncated: createdPlan.allowed.length > MAX_LISTED
1236
+ truncated: scan.overflow
1237
+ || createdPlan.allowed.length > MAX_LISTED
1434
1238
  || modifiedPlan.allowed.length > MAX_LISTED
1435
1239
  || refused.length > MAX_LISTED,
1436
1240
  warnings,
@@ -1563,6 +1367,72 @@ async function quarantineFiles(targets, cwd, home) {
1563
1367
  return { directory, moved, failed }
1564
1368
  }
1565
1369
 
1370
+ /**
1371
+ * The files one plan actually offered. The per-file delete button sends back a
1372
+ * path from this list, and the route refuses anything else: a request cannot
1373
+ * name a file the user was never shown.
1374
+ *
1375
+ * @param plan - the artifact plan this plugin produced for a session.
1376
+ * @returns every listed path, created and modified alike.
1377
+ */
1378
+ function artifactCandidates(plan) {
1379
+ const out = []
1380
+ for (const group of [plan.created, plan.modified]) {
1381
+ if (!Array.isArray(group)) continue
1382
+ for (const row of group) {
1383
+ if (row !== null && row !== undefined && typeof row.path === 'string') out.push(row.path)
1384
+ }
1385
+ }
1386
+ return out
1387
+ }
1388
+
1389
+ /**
1390
+ * The path a per-file delete may touch: one the plan listed, nothing else.
1391
+ * Without this the button would be a general-purpose delete primitive reachable
1392
+ * from the page.
1393
+ *
1394
+ * @param plan - the artifact plan for the session.
1395
+ * @param target - the path the page asked for.
1396
+ * @returns the resolved path, ready to unlink.
1397
+ */
1398
+ function assertListedPath(plan, target) {
1399
+ const resolved = path.resolve(target)
1400
+ const listed = artifactCandidates(plan).some((candidate) => path.resolve(candidate) === resolved)
1401
+ if (!listed) throw new HttpError(403, 'not-listed', '该文件不在本对话的产出清单里')
1402
+ return resolved
1403
+ }
1404
+
1405
+ /**
1406
+ * Delete one produced file. The destination is the user's call, and the dialog
1407
+ * passes the same preference that governs a conversation delete: to the system
1408
+ * trash, or outright.
1409
+ *
1410
+ * @param target - absolute path of the file.
1411
+ * @param recycle - true to send it to the system recycle bin.
1412
+ * @returns `{ recycled }` describing where it went.
1413
+ */
1414
+ async function removeOneFile(target, recycle) {
1415
+ const resolved = path.resolve(target)
1416
+ let info
1417
+ try {
1418
+ info = await fsp.lstat(resolved)
1419
+ } catch (error) {
1420
+ throw new HttpError(404, 'missing', `文件已不存在:${String((error && error.message) || error)}`)
1421
+ }
1422
+ if (!info.isFile()) throw new HttpError(400, 'not-a-file', '只能删除普通文件')
1423
+ if (recycle === true) {
1424
+ const ok = await sendToRecycleBin([resolved])
1425
+ if (!ok) throw new HttpError(500, 'recycle', '移入回收站失败')
1426
+ return { recycled: true }
1427
+ }
1428
+ try {
1429
+ await fsp.unlink(resolved)
1430
+ } catch (error) {
1431
+ throw new HttpError(500, 'unlink', `删除失败:${String((error && error.message) || error)}`)
1432
+ }
1433
+ return { recycled: false }
1434
+ }
1435
+
1566
1436
  /**
1567
1437
  * Quarantine the files one request selected. The candidate set is recomputed
1568
1438
  * here from the session log and the request's paths are intersected with it, so
@@ -1785,55 +1655,58 @@ function revealDirectory(directory) {
1785
1655
  ? { program: 'open', args: [directory] }
1786
1656
  : { program: 'xdg-open', args: [directory] }
1787
1657
  const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1658
+ // Without this listener a failed spawn (explorer missing, blocked by security
1659
+ // software) surfaces as an unhandled `error` event and takes the host down.
1660
+ child.on('error', () => {})
1788
1661
  child.unref()
1789
1662
  }
1790
1663
 
1791
1664
  /**
1792
- * The slow path: the same dialog through PowerShell. Windows PowerShell 5.1
1793
- * reads a script file as UTF-8 only when it carries a BOM, and without one the
1794
- * Chinese labels corrupt the run into a silent exit.
1665
+ * Ask the host for a directory.
1666
+ *
1667
+ * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1668
+ * whose capability names the interaction this deployment supports: a native
1669
+ * deployment opens one OS chooser, a browse deployment serves a listing the page
1670
+ * draws itself. Consumers are meant to switch on `capability().kind`.
1671
+ *
1672
+ * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1673
+ * was a reimplementation of something the host already ships, it could not follow a
1674
+ * remote deployment, and it needed a compiler on the machine at first use.
1675
+ *
1676
+ * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1677
+ * `{ unsupported: true }` so the page falls back to its own picker.
1795
1678
  */
1796
- async function pickFolderWithPowershell() {
1797
- const scriptPath = path.join(os.tmpdir(), `dsh-delete-session-pick-${process.pid}-${Date.now()}.ps1`)
1798
- const bytes = Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), Buffer.from(PICK_SCRIPT, 'utf8')])
1799
- await fsp.writeFile(scriptPath, bytes)
1679
+ async function pickFolder(ctx) {
1680
+ const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1681
+ ? ctx.get('directoryPicker')
1682
+ : undefined
1683
+ if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1684
+ return { unsupported: true }
1685
+ }
1686
+ let capability
1800
1687
  try {
1801
- return await runPowershell(
1802
- ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
1803
- PICK_TIMEOUT_MS,
1804
- )
1688
+ capability = picker.capability()
1689
+ } catch {
1690
+ return { unsupported: true }
1691
+ }
1692
+ if (capability === null || capability === undefined) return { unsupported: true }
1693
+ if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1694
+ // `pick(signal)` is mandatory: the host implementation begins with
1695
+ // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1696
+ // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1697
+ // the one the previous PowerShell dialog used: a dialog nobody answers must not
1698
+ // hold the request forever.
1699
+ const controller = new AbortController()
1700
+ const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1701
+ let picked
1702
+ try {
1703
+ picked = await capability.pick(controller.signal)
1805
1704
  } finally {
1806
- try { await fsp.rm(scriptPath, { force: true }) } catch { /* best effort */ }
1807
- }
1808
- }
1809
-
1810
- /**
1811
- * Raise the real Windows folder picker and return what the user chose. The
1812
- * browser cannot hand a page a filesystem path, but this process can ask the OS.
1813
- * @returns `{ cancelled, path }`.
1814
- */
1815
- async function pickFolderNative() {
1816
- if (process.platform !== 'win32') {
1817
- throw new HttpError(501, 'unsupported', '系统文件夹对话框只支持 Windows,请改用浏览…')
1705
+ clearTimeout(timer)
1818
1706
  }
1819
-
1820
- // The compiled picker answers in ~120 ms; the PowerShell fallback costs a
1821
- // second before the dialog even appears, so it is only the second choice.
1822
- let picked = ''
1823
- const exe = await ensurePickerExe()
1824
- if (exe !== null) {
1825
- const run = await runExecutable(exe, ['选择隔离夹保存位置', '选择此文件夹'], PICK_TIMEOUT_MS)
1826
- // Exit 1 is a cancelled dialog; anything else means it never opened.
1827
- if (run.code !== 0 && run.code !== 1) {
1828
- throw new HttpError(500, 'shell', `系统对话框异常退出(${run.code})`)
1829
- }
1830
- picked = run.code === 0 ? run.stdout : ''
1831
- } else {
1832
- picked = await pickFolderWithPowershell()
1833
- }
1834
- if (picked === '') return { cancelled: true, path: null }
1835
-
1836
- const resolved = path.resolve(picked)
1707
+ const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1708
+ if (chosen === null) return { cancelled: true, path: null }
1709
+ const resolved = path.resolve(chosen)
1837
1710
  let info
1838
1711
  try {
1839
1712
  info = await fsp.stat(resolved)
@@ -1844,6 +1717,7 @@ async function pickFolderNative() {
1844
1717
  return { cancelled: false, path: resolved }
1845
1718
  }
1846
1719
 
1720
+
1847
1721
  // --- http --------------------------------------------------------------------
1848
1722
 
1849
1723
  function isLoopbackAddress(address) {
@@ -1959,6 +1833,43 @@ export function apply(ctx) {
1959
1833
  },
1960
1834
  }))
1961
1835
 
1836
+ // Delete ONE produced file from the dialog. The path must be one the scan
1837
+ // listed, so this cannot become a general-purpose delete primitive.
1838
+ fiber.effect(() => webServer.register({
1839
+ kind: 'exact',
1840
+ path: `${ROUTE_PREFIX}/delete-file`,
1841
+ handler: async (req, res) => {
1842
+ if (!guard(req, res)) return
1843
+ if (req.method !== 'POST') {
1844
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1845
+ return
1846
+ }
1847
+ let body = {}
1848
+ try {
1849
+ const raw = await readBody(req)
1850
+ if (raw) body = JSON.parse(raw)
1851
+ } catch {
1852
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1853
+ return
1854
+ }
1855
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1856
+ const target = typeof body.path === 'string' ? body.path.trim() : ''
1857
+ try {
1858
+ if (sessionId === '') throw new HttpError(400, 'invalid', 'sessionId required')
1859
+ if (target === '') throw new HttpError(400, 'invalid', 'path required')
1860
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1861
+ const plan = await planArtifacts(ctx, sessionId, undefined, {})
1862
+ const resolved = assertListedPath(plan, target)
1863
+ const result = await removeOneFile(resolved, body.recycle === true)
1864
+ sendJson(res, 200, { ok: true, ...result })
1865
+ } catch (error) {
1866
+ const status = error instanceof HttpError ? error.status : 500
1867
+ const code = error instanceof HttpError ? error.code : 'internal'
1868
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1869
+ }
1870
+ },
1871
+ }))
1872
+
1962
1873
  // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1963
1874
  // hand a page a filesystem path, but this process is local, so it can.
1964
1875
  fiber.effect(() => webServer.register({
@@ -1971,7 +1882,15 @@ export function apply(ctx) {
1971
1882
  return
1972
1883
  }
1973
1884
  try {
1974
- const picked = await pickFolderNative()
1885
+ const picked = await pickFolder(ctx)
1886
+ if (picked.unsupported === true) {
1887
+ sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
1888
+ return
1889
+ }
1890
+ if (picked.browse === true) {
1891
+ sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
1892
+ return
1893
+ }
1975
1894
  sendJson(res, 200, { ok: true, ...picked })
1976
1895
  } catch (error) {
1977
1896
  const status = error instanceof HttpError ? error.status : 500
@@ -2205,10 +2124,14 @@ export function apply(ctx) {
2205
2124
  // quarantine against a scratch tree and a stubbed persistence service. Nothing
2206
2125
  // else in the host reads this face.
2207
2126
  export const internals = {
2208
- ensurePickerExe,
2127
+ pickFolder,
2128
+ artifactCandidates,
2129
+ assertListedPath,
2130
+ removeOneFile,
2209
2131
  claimQuarantineDirectory,
2210
2132
  classifyPaths,
2211
2133
  collectSessionPaths,
2134
+ MAX_SCANNED,
2212
2135
  findSessionCaches,
2213
2136
  freeDestination,
2214
2137
  identityKey,