dsh-delete-session 0.2.3 → 0.2.4

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/README.md CHANGED
@@ -1,4 +1,5 @@
1
1
  # dsh-delete-session
2
+ - **拖到页脚删除** —— 把侧边栏里的对话直接拖到页脚那一条,整条变红并显示「松手删除「标题」」,松手即按「删除时询问」的设置走:开着就弹确认框,关着就直接删;多选模式下拖动仍是宿主的行排序,不会被接管
2
3
 
3
4
  **DeepSeek Harness 会话删除插件 —— 在侧边栏会话菜单里直接删除会话。**
4
5
 
@@ -71,6 +72,8 @@ dsh plugin --profile web add github:DDDMUC/dsh-delete-session
71
72
  | **同时删除子会话** | **关** | 开:删对话时把它派生的子代理会话一起删掉。关:弹窗列出子会话,由你勾选 |
72
73
  | 隔离夹保存位置 | 空(= `$DSH_HOME`) | 可手输、可点「选择文件夹…」调系统对话框、可点「打开」在资源管理器里定位 |
73
74
 
75
+ > 「选择文件夹…」用的是宿主自己的 `ctx.directoryPicker`:本地桌面弹系统对话框,远程/浏览式宿主自动退回页面内的目录列表。插件不再自带任何自绘或自编译的选择器。
76
+
74
77
  ### 删除之后文件在哪
75
78
 
76
79
  | 平台 | 去处 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-delete-session",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Delete sessions from the DSH Web sidebar: adds a Delete action to the session row menu with a risk-consent dialog, sends the session log, workspace accounting and live session state to the system trash (or removes them outright), and, when opted in, quarantines the files the conversation produced.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/client.js CHANGED
@@ -61,6 +61,9 @@ window.__ModuleLoader__.load({
61
61
  pageAsk: '删除时询问',
62
62
  pageRecycle: '删除至回收站',
63
63
  pageSyncChildren: '同时删除子会话',
64
+ dropHint: '拖到这里删除',
65
+ dropRelease: '松手删除「{name}」',
66
+ dropFallback: '这个对话',
64
67
  starAsk: '⭐ 顺手留颗 Star,作者能高兴一整天',
65
68
  starCta: '行,给你一颗 Star',
66
69
  pageSyncChildrenOn: '删除对话时,把它派生的子代理会话一起删掉。',
@@ -98,6 +101,7 @@ window.__ModuleLoader__.load({
98
101
  rootOpened: '已在文件管理器中打开',
99
102
  rootOpenFailed: '打开失败:',
100
103
  pickerOpening: '已打开系统文件夹对话框,请在弹出的窗口里选择',
104
+ pickerFailed: '选择文件夹失败:',
101
105
  pageRootReset: '用默认',
102
106
  pageRootDefaultHint: (path) => `当前使用默认路径:${path}`,
103
107
  pageRootCustomHint: '隔离夹会建在这个目录下,每次删除生成一个带时间戳的子目录',
@@ -155,6 +159,9 @@ window.__ModuleLoader__.load({
155
159
  pageAsk: 'Ask before deleting',
156
160
  pageRecycle: 'Delete to the Recycle Bin',
157
161
  pageSyncChildren: 'Delete child sessions too',
162
+ dropHint: 'Drop here to delete',
163
+ dropRelease: 'Release to delete \'{name}\'',
164
+ dropFallback: 'this conversation',
158
165
  starAsk: '⭐ A star would make the author\'s day',
159
166
  starCta: 'Fine — have one',
160
167
  pageSyncChildrenOn: 'A delete also removes the subagent sessions it spawned.',
@@ -190,6 +197,7 @@ window.__ModuleLoader__.load({
190
197
  rootOpened: 'Opened in the file manager',
191
198
  rootOpenFailed: 'Could not open: ',
192
199
  pickerOpening: 'The system folder dialog is open; pick a folder in that window',
200
+ pickerFailed: 'Could not open the folder picker: ',
193
201
  pageRootReset: 'Use default',
194
202
  pageRootDefaultHint: (path) => `Using the default path: ${path}`,
195
203
  pageRootCustomHint: 'The quarantine folder is created here, one timestamped subfolder per delete',
@@ -309,6 +317,11 @@ window.__ModuleLoader__.load({
309
317
  picker: null,
310
318
  /** The host's default quarantine root, fetched once so the card can name it. */
311
319
  defaultRoot: null,
320
+ /**
321
+ * The session being dragged over the footer, or null. `over` arms the drop:
322
+ * the bar only says "松手删除" once the pointer is actually on it.
323
+ */
324
+ drag: null,
312
325
  }
313
326
 
314
327
  const listeners = new Set()
@@ -322,6 +335,7 @@ window.__ModuleLoader__.load({
322
335
  batch: state.batch,
323
336
  picker: state.picker,
324
337
  defaultRoot: state.defaultRoot,
338
+ drag: state.drag,
325
339
  selectedCount: state.selected.size,
326
340
  }
327
341
  }
@@ -492,11 +506,13 @@ window.__ModuleLoader__.load({
492
506
  * a conversation of its own, so it is offered rather than swept up.
493
507
  */
494
508
  function syncChildren() {
495
- return readPref(SYNC_CHILDREN_KEY, '0') === '1'
509
+ return readPref(SYNC_CHILDREN_KEY, '1') !== '0'
496
510
  }
497
511
 
498
512
  function setSyncChildren(on) {
499
- writePref(SYNC_CHILDREN_KEY, on ? '1' : null)
513
+ // "Off" is written as '0' rather than cleared: the default is now on, so a
514
+ // removed key would read back as on again.
515
+ writePref(SYNC_CHILDREN_KEY, on ? '1' : '0')
500
516
  }
501
517
 
502
518
  /** The chosen quarantine root, or '' for "use the host default". */
@@ -687,6 +703,10 @@ window.__ModuleLoader__.load({
687
703
  // exclusion rule silently hid the bar together with its Cancel button.
688
704
  'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [data-dsh-plugin]{display:none}',
689
705
  'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [class*="_entryRow"]{display:none}',
706
+ '.dsdel-drop{border:1px dashed var(--dsw-alias-border-l2,rgba(128,128,128,.4));border-radius:8px;color:var(--dsw-alias-label-secondary,inherit)}',
707
+ '.dsdel-drop-over{border-color:var(--dsw-alias-state-error-primary,#e5484d);border-style:solid;background:rgba(229,72,77,.10);color:var(--dsw-alias-state-error-primary,#e5484d)}',
708
+ '.dsdel-drop-icon{display:inline-flex;flex:0 0 auto;align-items:center}',
709
+ '.dsdel-drop-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
690
710
  '.dsdel-bar-count{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary,inherit)}',
691
711
  '.dsdel-bar-btn{flex:0 0 auto;white-space:nowrap;appearance:none;min-height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.4));background:var(--dsw-alias-fill-elevated,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,inherit);border-radius:8px;font-size:13px;cursor:pointer}',
692
712
  '.dsdel-bar-btn:disabled{opacity:.5;cursor:default}',
@@ -774,6 +794,56 @@ window.__ModuleLoader__.load({
774
794
  return id === '' ? null : id
775
795
  }
776
796
 
797
+ // --- drag a session onto the footer to delete it ---------------------------
798
+ //
799
+ // The id comes from the host's own `data-row-key`, never from `dataTransfer`:
800
+ // the official drag only reorders, and a dragover payload is unreadable anyway.
801
+ // The gesture ends in the same place as the menu row - the confirmation dialog
802
+ // unless the user turned asking off - so there is exactly one delete policy.
803
+
804
+ /** The row under the pointer, with the title the drop target can name. */
805
+ function draggedSession(event) {
806
+ const target = event === null || event === undefined ? null : event.target
807
+ const row = target && typeof target.closest === 'function'
808
+ ? target.closest('[role="treeitem"]')
809
+ : null
810
+ const sessionId = sessionIdFromRow(row)
811
+ if (sessionId === null) return null
812
+ const text = row !== null && typeof row.textContent === 'string' ? row.textContent.trim() : ''
813
+ const title = text === '' ? null : text.slice(0, 40)
814
+ return { sessionId, title }
815
+ }
816
+
817
+ function onDragStartCapture(event) {
818
+ // Inside multi-select a drag is the host reordering rows; deleting on drop
819
+ // would make the mode quietly destructive.
820
+ if (state.selecting) return
821
+ const info = draggedSession(event)
822
+ if (info === null) return
823
+ state.drag = { sessionId: info.sessionId, title: info.title, over: false }
824
+ syncFooterMode()
825
+ publish()
826
+ }
827
+
828
+ function onDragEndCapture() {
829
+ if (state.drag === null) return
830
+ state.drag = null
831
+ syncFooterMode()
832
+ publish()
833
+ }
834
+
835
+ /** Drop on the bar: same policy as the menu row. */
836
+ function dropToDelete() {
837
+ const drag = state.drag
838
+ if (drag === null) return
839
+ state.drag = null
840
+ syncFooterMode()
841
+ publish()
842
+ const needsDialog = !artifactsOff() && !artifactsAuto()
843
+ if (skipConfirm() && !needsDialog) deleteNow({ sessionId: drag.sessionId })
844
+ else openDeleteDialog(drag.sessionId, drag.title)
845
+ }
846
+
777
847
  function decorateRows() {
778
848
  if (typeof document === 'undefined') return
779
849
  const rows = document.querySelectorAll('[role="treeitem"]')
@@ -782,14 +852,22 @@ window.__ModuleLoader__.load({
782
852
  if (!id) return
783
853
  // Checkboxes belong to multi-select only: a single delete (or any other
784
854
  // decorate pass outside the mode) must not plant them on every row.
855
+ // The checkbox is always the row's first element child, so it is read
856
+ // through the pointer. `querySelector` here ran twice per row per frame,
857
+ // which is the pass's dominant cost once the list is long.
858
+ const first = row.firstElementChild
859
+ const existing = first !== null && first !== undefined
860
+ && first.classList
861
+ && first.classList.contains(DEL_CHECK)
862
+ ? first
863
+ : null
785
864
  if (!state.selecting) {
786
- const stray = row.querySelector(':scope > .dsdel-check')
787
- if (stray) stray.remove()
865
+ if (existing !== null) existing.remove()
788
866
  } else {
789
- let check = row.querySelector(':scope > .dsdel-check')
867
+ let check = existing
790
868
  if (!check) {
791
869
  check = document.createElement('span')
792
- check.className = 'dsdel-check'
870
+ check.className = DEL_CHECK
793
871
  check.setAttribute('data-dsh-delete-session', 'check')
794
872
  row.insertBefore(check, row.firstChild)
795
873
  }
@@ -801,6 +879,24 @@ window.__ModuleLoader__.load({
801
879
  document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
802
880
  }
803
881
  }
882
+ /**
883
+ * A mutation batch only matters when a node came or went. Text streaming
884
+ * inside the transcript produces characterData records forever; scheduling a
885
+ * full row scan for those would burn a frame's budget on every token.
886
+ */
887
+ function onRowMutations(records) {
888
+ if (records === undefined || records === null) return scheduleDecorate()
889
+ for (const record of records) {
890
+ const added = record === null || record === undefined ? null : record.addedNodes
891
+ const removed = record === null || record === undefined ? null : record.removedNodes
892
+ if ((added !== null && added !== undefined && added.length > 0)
893
+ || (removed !== null && removed !== undefined && removed.length > 0)) {
894
+ scheduleDecorate()
895
+ return
896
+ }
897
+ }
898
+ }
899
+
804
900
  function scheduleDecorate() {
805
901
  if (typeof requestAnimationFrame !== 'function') return
806
902
  if (decorateRaf !== null) return
@@ -834,6 +930,42 @@ window.__ModuleLoader__.load({
834
930
  function BulkBar({ t: injected }) {
835
931
  const translate = localizedTranslator(injected)
836
932
  const view = useSnapshot()
933
+ // A session dragged over the sidebar turns the footer into a drop target.
934
+ if (view.drag !== null && view.drag !== undefined) {
935
+ const armed = view.drag.over === true
936
+ const name = view.drag.title === null || view.drag.title === undefined
937
+ ? translate('dropFallback')
938
+ : view.drag.title
939
+ return h('div', {
940
+ className: armed ? 'dsdel-bar dsdel-drop dsdel-drop-over' : 'dsdel-bar dsdel-drop',
941
+ role: 'toolbar',
942
+ onDragOver: (event) => {
943
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
944
+ if (event && event.dataTransfer) {
945
+ try { event.dataTransfer.dropEffect = 'move' } catch { /* read-only */ }
946
+ }
947
+ if (state.drag !== null && state.drag.over !== true) {
948
+ state.drag.over = true
949
+ publish()
950
+ }
951
+ },
952
+ onDragLeave: () => {
953
+ if (state.drag !== null && state.drag.over !== false) {
954
+ state.drag.over = false
955
+ publish()
956
+ }
957
+ },
958
+ onDrop: (event) => {
959
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
960
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
961
+ dropToDelete()
962
+ },
963
+ },
964
+ h('span', { key: 'icon', className: 'dsdel-drop-icon' }, glyph(TRASH_PATHS)),
965
+ h('span', { key: 'text', className: 'dsdel-drop-text' },
966
+ armed ? translate('dropRelease', name) : translate('dropHint', name)),
967
+ )
968
+ }
837
969
  // Outside selection mode the footer keeps its normal face.
838
970
  if (!view.selecting) return null
839
971
  const busy = view.batch !== null
@@ -918,17 +1050,30 @@ window.__ModuleLoader__.load({
918
1050
  else classes.remove('dsdel-selecting')
919
1051
  }
920
1052
 
1053
+ /** The footer is ours while selecting or while a session is dragged over it. */
1054
+ function syncFooterMode() {
1055
+ markSelecting(state.selecting || state.drag !== null)
1056
+ }
1057
+
921
1058
  function enterSelection() {
922
1059
  if (state.selecting) return
923
1060
  state.selecting = true
924
1061
  state.selected.clear()
925
1062
  ensureStyle()
926
- markSelecting(true)
1063
+ syncFooterMode()
927
1064
  document.addEventListener('click', onSelectClickCapture, true)
928
1065
  document.addEventListener('keydown', onSelectKeydown, true)
929
1066
  if (typeof MutationObserver === 'function') {
930
- rowObserver = new MutationObserver(scheduleDecorate)
931
- rowObserver.observe(document.body, { childList: true, subtree: true })
1067
+ rowObserver = new MutationObserver(onRowMutations)
1068
+ // Observation root is the list, not the document: the transcript below
1069
+ // streams tokens continuously and would otherwise wake this on every one.
1070
+ const list = typeof document.querySelector === 'function'
1071
+ ? document.querySelector(LIST_SELECTOR)
1072
+ : null
1073
+ rowObserver.observe(list !== null && list !== undefined ? list : document.body, {
1074
+ childList: true,
1075
+ subtree: true,
1076
+ })
932
1077
  }
933
1078
  publish()
934
1079
  }
@@ -943,7 +1088,7 @@ window.__ModuleLoader__.load({
943
1088
  state.pending.clear()
944
1089
  document.querySelectorAll('.dsdel-row-pending').forEach((el) => el.classList.remove('dsdel-row-pending'))
945
1090
  }
946
- markSelecting(false)
1091
+ syncFooterMode()
947
1092
  document.removeEventListener('click', onSelectClickCapture, true)
948
1093
  document.removeEventListener('keydown', onSelectKeydown, true)
949
1094
  if (rowObserver) { rowObserver.disconnect(); rowObserver = null }
@@ -1293,11 +1438,16 @@ window.__ModuleLoader__.load({
1293
1438
  toast(t('rootSet'))
1294
1439
  })
1295
1440
  .catch((reason) => {
1296
- if (reason && reason.code === 'unsupported') {
1441
+ // Two host answers mean "use the page picker instead": `unsupported`
1442
+ // (no directoryPicker service at all) and `browse` (the service exists
1443
+ // but serves listings, which is what a remote client gets). Neither is
1444
+ // a failure, so neither may surface as a toast.
1445
+ if (reason && (reason.code === 'unsupported' || reason.code === 'browse')) {
1297
1446
  openPicker()
1298
1447
  return
1299
1448
  }
1300
- toast(t('failed') + String((reason && reason.message) || reason), true)
1449
+ // Nothing was deleted here, so the delete wording would mislead.
1450
+ toast(t('pickerFailed') + String((reason && reason.message) || reason), true)
1301
1451
  })
1302
1452
  .finally(() => {
1303
1453
  folderDialogOpen = false
@@ -1371,6 +1521,11 @@ window.__ModuleLoader__.load({
1371
1521
 
1372
1522
  // --- menu rows (slot: sidebar.workspaces.session.menu.item) ----------------
1373
1523
 
1524
+ /** The sidebar list container; hashed class name, matched by its suffix. */
1525
+ const LIST_SELECTOR = '[class*="_regionArea"]'
1526
+ /** Marks a row checkbox this plugin planted. */
1527
+ const DEL_CHECK = 'dsdel-check'
1528
+
1374
1529
  /** Inline glyphs for the two rows; the host exposes no matching pair. */
1375
1530
  const TRASH_PATHS = ['M4 7h16', 'M10 11v6', 'M14 11v6', 'M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13', 'M9 7V4h6v3']
1376
1531
  const SELECT_PATHS = ['M5 7m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M5 17m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M11 7h9', 'M11 17h9']
@@ -1936,6 +2091,12 @@ window.__ModuleLoader__.load({
1936
2091
  }
1937
2092
 
1938
2093
  const install = (slots) => {
2094
+ // The drag gesture is document-wide (the row is not ours), so these are
2095
+ // plain capture listeners rather than slot handlers.
2096
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
2097
+ document.addEventListener('dragstart', onDragStartCapture, true)
2098
+ document.addEventListener('dragend', onDragEndCapture, true)
2099
+ }
1939
2100
  // Session menu rows. A package-namespaced id keeps them beside the
1940
2101
  // shipped pin(100)/rename(200)/fork(300)/archive(400)/session-id(450).
1941
2102
  slots.inject('sidebar.workspaces.session.menu.item', () => slots.register(
@@ -1971,6 +2132,12 @@ window.__ModuleLoader__.load({
1971
2132
 
1972
2133
  // Leaving the mode disconnects the row observer and strips the checkboxes.
1973
2134
  return () => {
2135
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
2136
+ document.removeEventListener('dragstart', onDragStartCapture, true)
2137
+ document.removeEventListener('dragend', onDragEndCapture, true)
2138
+ }
2139
+ state.drag = null
2140
+ syncFooterMode()
1974
2141
  exitSelection()
1975
2142
  }
1976
2143
  }
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
@@ -849,234 +862,10 @@ const MAX_LISTED = 500
849
862
  const RESOLVE_CONCURRENCY = 16
850
863
  /** How many directories the folder picker lists before saying there are more. */
851
864
  const MAX_BROWSE_ENTRIES = 500
852
- /** How long a native folder dialog may stay open before the request gives up. */
865
+ /** How long the OS chooser may stay open before the request gives up on it. */
853
866
  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
- }
867
+ /** How long a shell helper (the recycle-bin script) may run before giving up. */
868
+ const SHELL_TIMEOUT_MS = 5 * 60 * 1000
1080
869
 
1081
870
  /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
1082
871
  function runExecutable(program, args, timeoutMs) {
@@ -1785,55 +1574,58 @@ function revealDirectory(directory) {
1785
1574
  ? { program: 'open', args: [directory] }
1786
1575
  : { program: 'xdg-open', args: [directory] }
1787
1576
  const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1577
+ // Without this listener a failed spawn (explorer missing, blocked by security
1578
+ // software) surfaces as an unhandled `error` event and takes the host down.
1579
+ child.on('error', () => {})
1788
1580
  child.unref()
1789
1581
  }
1790
1582
 
1791
1583
  /**
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.
1584
+ * Ask the host for a directory.
1585
+ *
1586
+ * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1587
+ * whose capability names the interaction this deployment supports: a native
1588
+ * deployment opens one OS chooser, a browse deployment serves a listing the page
1589
+ * draws itself. Consumers are meant to switch on `capability().kind`.
1590
+ *
1591
+ * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1592
+ * was a reimplementation of something the host already ships, it could not follow a
1593
+ * remote deployment, and it needed a compiler on the machine at first use.
1594
+ *
1595
+ * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1596
+ * `{ unsupported: true }` so the page falls back to its own picker.
1795
1597
  */
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)
1598
+ async function pickFolder(ctx) {
1599
+ const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1600
+ ? ctx.get('directoryPicker')
1601
+ : undefined
1602
+ if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1603
+ return { unsupported: true }
1604
+ }
1605
+ let capability
1800
1606
  try {
1801
- return await runPowershell(
1802
- ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
1803
- PICK_TIMEOUT_MS,
1804
- )
1607
+ capability = picker.capability()
1608
+ } catch {
1609
+ return { unsupported: true }
1610
+ }
1611
+ if (capability === null || capability === undefined) return { unsupported: true }
1612
+ if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1613
+ // `pick(signal)` is mandatory: the host implementation begins with
1614
+ // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1615
+ // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1616
+ // the one the previous PowerShell dialog used: a dialog nobody answers must not
1617
+ // hold the request forever.
1618
+ const controller = new AbortController()
1619
+ const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1620
+ let picked
1621
+ try {
1622
+ picked = await capability.pick(controller.signal)
1805
1623
  } finally {
1806
- try { await fsp.rm(scriptPath, { force: true }) } catch { /* best effort */ }
1624
+ clearTimeout(timer)
1807
1625
  }
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,请改用浏览…')
1818
- }
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)
1626
+ const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1627
+ if (chosen === null) return { cancelled: true, path: null }
1628
+ const resolved = path.resolve(chosen)
1837
1629
  let info
1838
1630
  try {
1839
1631
  info = await fsp.stat(resolved)
@@ -1844,6 +1636,7 @@ async function pickFolderNative() {
1844
1636
  return { cancelled: false, path: resolved }
1845
1637
  }
1846
1638
 
1639
+
1847
1640
  // --- http --------------------------------------------------------------------
1848
1641
 
1849
1642
  function isLoopbackAddress(address) {
@@ -1971,7 +1764,15 @@ export function apply(ctx) {
1971
1764
  return
1972
1765
  }
1973
1766
  try {
1974
- const picked = await pickFolderNative()
1767
+ const picked = await pickFolder(ctx)
1768
+ if (picked.unsupported === true) {
1769
+ sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
1770
+ return
1771
+ }
1772
+ if (picked.browse === true) {
1773
+ sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
1774
+ return
1775
+ }
1975
1776
  sendJson(res, 200, { ok: true, ...picked })
1976
1777
  } catch (error) {
1977
1778
  const status = error instanceof HttpError ? error.status : 500
@@ -2205,7 +2006,7 @@ export function apply(ctx) {
2205
2006
  // quarantine against a scratch tree and a stubbed persistence service. Nothing
2206
2007
  // else in the host reads this face.
2207
2008
  export const internals = {
2208
- ensurePickerExe,
2009
+ pickFolder,
2209
2010
  claimQuarantineDirectory,
2210
2011
  classifyPaths,
2211
2012
  collectSessionPaths,
@@ -1215,3 +1215,98 @@ test('a child that is still open is left alone and reported as skipped', async (
1215
1215
  assert.equal(fs.existsSync(child.dir), true, 'a busy child is not deleted under its writer')
1216
1216
  assert.equal(result.children[0].skipped, 'busy', 'and the report says why')
1217
1217
  })
1218
+
1219
+ // --- the folder picker belongs to the host, not to this plugin ---------------
1220
+
1221
+ /**
1222
+ * The host mounts `@deepseek-ai/dsh-host-directory-picker-auto` as
1223
+ * `ctx.directoryPicker`; its capability says which interaction the deployment
1224
+ * supports. Native deployments open one OS chooser, browse deployments serve a
1225
+ * listing the page renders itself.
1226
+ */
1227
+ const pickerContext = (capability) => ({
1228
+ get: (name) => (name === 'directoryPicker' ? { capability: () => capability } : undefined),
1229
+ })
1230
+
1231
+ test('a native host capability answers with the chosen directory', async () => {
1232
+ // A real directory: the plugin still validates what the chooser hands back, so
1233
+ // a path that vanished between the click and the answer is not accepted.
1234
+ const chosen = fs.mkdtempSync(path.join(os.tmpdir(), 'dsdel-pick-'))
1235
+ const ctx = pickerContext({ kind: 'native', pick: async () => chosen })
1236
+
1237
+ const result = await internals.pickFolder(ctx)
1238
+
1239
+ assert.deepEqual(result, { cancelled: false, path: path.resolve(chosen) })
1240
+ fs.rmSync(chosen, { recursive: true, force: true })
1241
+ })
1242
+
1243
+ test('a cancelled native chooser is reported, not thrown', async () => {
1244
+ const ctx = pickerContext({ kind: 'native', pick: async () => null })
1245
+
1246
+ const result = await internals.pickFolder(ctx)
1247
+
1248
+ assert.deepEqual(result, { cancelled: true, path: null })
1249
+ })
1250
+
1251
+ test('a browse-only host asks the page to render its own picker', async () => {
1252
+ const ctx = pickerContext({ kind: 'browse', list: async () => [] })
1253
+
1254
+ const result = await internals.pickFolder(ctx)
1255
+
1256
+ assert.equal(result.browse, true, 'the in-page picker takes over')
1257
+ })
1258
+
1259
+ test('a host without the service is reported as unsupported', async () => {
1260
+ for (const ctx of [{ get: () => undefined }, {}, null]) {
1261
+ const result = await internals.pickFolder(ctx)
1262
+ assert.equal(result.unsupported, true)
1263
+ }
1264
+ })
1265
+
1266
+ test('a capability that throws does not take the request down', async () => {
1267
+ const ctx = { get: () => ({ capability: () => { throw new Error('boom') } }) }
1268
+
1269
+ const result = await internals.pickFolder(ctx)
1270
+
1271
+ assert.equal(result.unsupported, true)
1272
+ })
1273
+
1274
+ test('this plugin no longer compiles or shells out a picker of its own', () => {
1275
+ // The C# source, the compiler probe and the PowerShell fallback all existed
1276
+ // only because the host's own chooser was not being used.
1277
+ const source = fs.readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
1278
+ // `findCsc` stays: the recycle-bin helper still compiles a C# program. Only the
1279
+ // picker-specific machinery is gone.
1280
+ for (const gone of ['PICK_CSHARP', 'PICK_EXE_SOURCE', 'PICK_SCRIPT', 'ensurePickerExe', 'pickFolderWithPowershell', 'pickFolderNative']) {
1281
+ assert.equal(source.includes(gone), false, gone + ' should be gone')
1282
+ }
1283
+ })
1284
+
1285
+ // --- the picker call must hand the host a real signal ------------------------
1286
+
1287
+ test('the native chooser is given a live abort signal', async () => {
1288
+ // The host implementation starts with `if (signal.aborted) throw …`, so calling
1289
+ // `pick()` with no argument throws "Cannot read properties of undefined
1290
+ // (reading 'aborted')" — which surfaced as a bogus delete failure.
1291
+ let seen
1292
+ const ctx = {
1293
+ get: (name) =>
1294
+ name === 'directoryPicker'
1295
+ ? {
1296
+ capability: () => ({
1297
+ kind: 'native',
1298
+ pick: async (signal) => {
1299
+ seen = signal
1300
+ return null
1301
+ },
1302
+ }),
1303
+ }
1304
+ : undefined,
1305
+ }
1306
+
1307
+ await internals.pickFolder(ctx)
1308
+
1309
+ assert.ok(seen, 'a signal was passed')
1310
+ assert.equal(typeof seen.aborted, 'boolean', 'and it is an AbortSignal')
1311
+ assert.equal(seen.aborted, false, 'not already aborted')
1312
+ })
@@ -282,9 +282,14 @@ async function loadPlugin(options = {}) {
282
282
  writable: true,
283
283
  })
284
284
  globalThis.MutationObserver = class {
285
- constructor(callback) { this.callback = callback; observers.push(this) }
286
- observe() {}
287
- disconnect() {}
285
+ constructor(callback) {
286
+ this.callback = callback
287
+ this.target = null
288
+ this.options = null
289
+ observers.push(this)
290
+ }
291
+ observe(target, options) { this.target = target === undefined ? null : target; this.options = options === undefined ? null : options }
292
+ disconnect() { this.target = null }
288
293
  }
289
294
  // The plugin coalesces decorate passes through rAF. Run the callback on a real
290
295
  // microtask-free tick rather than synchronously: `scheduleDecorate` assigns the
@@ -331,7 +336,12 @@ async function loadPlugin(options = {}) {
331
336
  if (href.endsWith('/dsh-delete-session/pick')) {
332
337
  const pick = options.pick ?? { cancelled: true, path: null }
333
338
  if (pick.unsupported === true) {
334
- return { ok: false, status: 501, json: async () => ({ ok: false, code: 'unsupported', error: '系统文件夹对话框只支持 Windows' }) }
339
+ return { ok: false, status: 200, json: async () => ({ ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' }) }
340
+ }
341
+ // A browse deployment: the host has no OS chooser to raise, so it tells the
342
+ // page to draw its own picker. Normal for a remote client.
343
+ if (pick.browse === true) {
344
+ return { ok: false, status: 200, json: async () => ({ ok: false, code: 'browse', error: '浏览式宿主' }) }
335
345
  }
336
346
  return { ok: true, status: 200, json: async () => ({ ok: true, ...pick }) }
337
347
  }
@@ -442,12 +452,20 @@ function makeStorage() {
442
452
  * from `data-row-key`, not from a React fiber; without this the plugin finds no
443
453
  * id and skips the row, which would make every assertion below pass vacuously.
444
454
  */
445
- function mountRow(harness, session = SESSION_A) {
455
+ /** The host wraps the session rows in this container; the plugin watches it. */
456
+ function mountList(harness) {
457
+ const list = harness.document.createElement('div')
458
+ list.className = 'hHd-Xa_regionArea'
459
+ harness.document.body.appendChild(list)
460
+ return list
461
+ }
462
+
463
+ function mountRow(harness, session = SESSION_A, parent = null) {
446
464
  const row = harness.document.createElement('div')
447
465
  row.className = 'session_row'
448
466
  row.setAttribute('role', 'treeitem')
449
467
  row.setAttribute('data-row-key', `session:${session.id}`)
450
- harness.document.body.appendChild(row)
468
+ ;(parent ?? harness.document.body).appendChild(row)
451
469
  harness.rows.push(row)
452
470
  return row
453
471
  }
@@ -1906,12 +1924,12 @@ const childChecks = (harness) => {
1906
1924
  return section === undefined ? [] : collectChecks([section], harness)
1907
1925
  }
1908
1926
 
1909
- test('the page offers to take child sessions with their parent, off by default', async () => {
1927
+ test('the page offers to take child sessions with their parent, on by default', async () => {
1910
1928
  const harness = await loadPlugin()
1911
1929
  const box = pageCheck(harness, 'syncChildren')
1912
1930
 
1913
1931
  assert.ok(box, 'the switch renders with the other delete controls')
1914
- assert.equal(box.props.checked, false, 'asking is the default')
1932
+ assert.equal(box.props.checked, true, 'taking them along is the default')
1915
1933
  assert.equal(box.props.label, '同时删除子会话')
1916
1934
 
1917
1935
  box.props.onChange(true)
@@ -1920,6 +1938,7 @@ test('the page offers to take child sessions with their parent, off by default',
1920
1938
 
1921
1939
  test('with the switch off the dialog lists the children, ticked, for you to narrow', async () => {
1922
1940
  const harness = await loadPlugin({ children: CHILDREN })
1941
+ localStorage.setItem(SYNC_CHILDREN_KEY, '0')
1923
1942
  mountRow(harness, SESSION_A)
1924
1943
 
1925
1944
  const { element } = deleteRow(harness, SESSION_A)
@@ -1933,6 +1952,7 @@ test('with the switch off the dialog lists the children, ticked, for you to narr
1933
1952
 
1934
1953
  test('unticking a child keeps it out of the delete', async () => {
1935
1954
  const harness = await loadPlugin({ children: CHILDREN })
1955
+ localStorage.setItem(SYNC_CHILDREN_KEY, '0')
1936
1956
  mountRow(harness, SESSION_A)
1937
1957
 
1938
1958
  const { element } = deleteRow(harness, SESSION_A)
@@ -2176,6 +2196,7 @@ test('an interpolating host translator never receives our function entries', asy
2176
2196
 
2177
2197
  test('a placeholder string is interpolated locally, not by the host', async () => {
2178
2198
  const harness = await loadPlugin({ children: CHILDREN })
2199
+ localStorage.setItem(SYNC_CHILDREN_KEY, '0')
2179
2200
  const dict = harness.locales[NS].zh
2180
2201
  const strict = (key, params) => {
2181
2202
  const value = dict[key]
@@ -2213,3 +2234,272 @@ test('the bar buttons keep their width instead of wrapping', async () => {
2213
2234
  assert.match(css, /\.dsdel-bar-btn\{[^}]*white-space:nowrap/, 'and never wrap their label')
2214
2235
  assert.match(css, /\.dsdel-bar-count\{[^}]*text-overflow:ellipsis/, 'the count gives way instead')
2215
2236
  })
2237
+
2238
+ // --- drag a session onto the footer bar to delete it ------------------------
2239
+
2240
+ /** Drag one mounted row the way the host starts a session drag. */
2241
+ const startRowDrag = (harness, row) => harness.document.dispatchToDocument('dragstart', {
2242
+ target: row,
2243
+ preventDefault() {},
2244
+ stopPropagation() {},
2245
+ })
2246
+
2247
+ const dropEvent = () => ({ preventDefault() {}, stopPropagation() {}, dataTransfer: { dropEffect: '' } })
2248
+
2249
+ test('dragging a session row turns the footer into a drop target', async () => {
2250
+ const harness = await loadPlugin()
2251
+ const row = mountRow(harness, SESSION_A)
2252
+
2253
+ assert.equal(bar(harness), null, 'the footer is untouched before the drag')
2254
+
2255
+ startRowDrag(harness, row)
2256
+ await flush()
2257
+
2258
+ const node = bar(harness)
2259
+ assert.ok(node, 'the bar appears while a session is being dragged')
2260
+ assert.match(String(node.props.className), /\bdsdel-drop\b/, 'as a drop target, not the selection bar')
2261
+ assert.equal(harness.document.body._classes.has('dsdel-selecting'), true, 'and the account row steps aside')
2262
+ })
2263
+
2264
+ test('hovering the bar shows that releasing will delete', async () => {
2265
+ const harness = await loadPlugin()
2266
+ const row = mountRow(harness, SESSION_A)
2267
+
2268
+ startRowDrag(harness, row)
2269
+ await flush()
2270
+ assert.doesNotMatch(String(bar(harness).props.className), /dsdel-drop-over/, 'not armed yet')
2271
+
2272
+ bar(harness).props.onDragOver(dropEvent())
2273
+ await flush()
2274
+
2275
+ const node = bar(harness)
2276
+ assert.match(String(node.props.className), /dsdel-drop-over/, 'armed once the pointer is over it')
2277
+ const text = JSON.stringify(node.props.children)
2278
+ assert.match(text, /松手删除/, 'and the line says so')
2279
+ })
2280
+
2281
+ test('leaving the bar disarms it again', async () => {
2282
+ const harness = await loadPlugin()
2283
+ const row = mountRow(harness, SESSION_A)
2284
+
2285
+ startRowDrag(harness, row)
2286
+ await flush()
2287
+ bar(harness).props.onDragOver(dropEvent())
2288
+ await flush()
2289
+ bar(harness).props.onDragLeave(dropEvent())
2290
+ await flush()
2291
+
2292
+ assert.doesNotMatch(String(bar(harness).props.className), /dsdel-drop-over/)
2293
+ })
2294
+
2295
+ test('dropping asks first unless the user turned asking off', async () => {
2296
+ const harness = await loadPlugin()
2297
+ const row = mountRow(harness, SESSION_A)
2298
+
2299
+ startRowDrag(harness, row)
2300
+ await flush()
2301
+ bar(harness).props.onDrop(dropEvent())
2302
+ await flush()
2303
+
2304
+ assert.ok(dialogParts(harness), 'the confirmation dialog opens — the same rule as the menu row')
2305
+ assert.equal(deleteCalls(harness), 0, 'and nothing is deleted yet')
2306
+ })
2307
+
2308
+ test('dropping deletes straight away when asking is off', async () => {
2309
+ const harness = await loadPlugin()
2310
+ localStorage.setItem(SKIP_KEY, '1')
2311
+ const row = mountRow(harness, SESSION_A)
2312
+
2313
+ startRowDrag(harness, row)
2314
+ await flush()
2315
+ bar(harness).props.onDrop(dropEvent())
2316
+ await flush()
2317
+
2318
+ assert.equal(deleteCalls(harness), 1, 'one delete goes out')
2319
+ assert.equal(dialogParts(harness), null, 'with no dialog')
2320
+ })
2321
+
2322
+ test('ending the drag without dropping puts the footer back', async () => {
2323
+ const harness = await loadPlugin()
2324
+ const row = mountRow(harness, SESSION_A)
2325
+
2326
+ startRowDrag(harness, row)
2327
+ await flush()
2328
+ harness.document.dispatchToDocument('dragend', { target: row, preventDefault() {}, stopPropagation() {} })
2329
+ await flush()
2330
+
2331
+ assert.equal(bar(harness), null, 'the footer is empty again')
2332
+ assert.equal(harness.document.body._classes.has('dsdel-selecting'), false, 'and the account row is back')
2333
+ })
2334
+
2335
+ test('a drag started during multi-select is left alone', async () => {
2336
+ const harness = await loadPlugin()
2337
+ mountRow(harness, SESSION_A)
2338
+ selectRow(harness).element.props.onSelect()
2339
+ await flush()
2340
+
2341
+ const barBefore = bar(harness)
2342
+ assert.match(String(barBefore.props.className), /\bdsdel-bar\b/)
2343
+
2344
+ startRowDrag(harness, harness.rows[0])
2345
+ await flush()
2346
+
2347
+ assert.doesNotMatch(String(bar(harness).props.className), /\bdsdel-drop\b/, 'reordering inside the mode is not a delete')
2348
+ })
2349
+
2350
+ // --- performance: the decorate pass must stay cheap --------------------------
2351
+
2352
+ test('the row observer watches the session list, not the whole document', async () => {
2353
+ const harness = await loadPlugin()
2354
+ const list = mountList(harness)
2355
+ mountRow(harness, SESSION_A, list)
2356
+ selectRow(harness).element.props.onSelect()
2357
+ await flush()
2358
+
2359
+ const observer = harness.observers[0]
2360
+ assert.ok(observer, 'multi-select installs one observer')
2361
+ // Observing `document.body` means every streamed token in the transcript wakes
2362
+ // this callback. The list is the only subtree that can gain or lose rows.
2363
+ assert.equal(
2364
+ observer.target,
2365
+ list,
2366
+ 'the list container is the observation root',
2367
+ )
2368
+ })
2369
+
2370
+ test('a mutation with no added or removed nodes schedules no pass', async () => {
2371
+ const harness = await loadPlugin()
2372
+ mountRow(harness, SESSION_A)
2373
+ selectRow(harness).element.props.onSelect()
2374
+ await flush()
2375
+
2376
+ const observer = harness.observers[0]
2377
+ let scanned = 0
2378
+ const realQuery = harness.document.querySelectorAll.bind(harness.document)
2379
+ harness.document.querySelectorAll = (selector) => {
2380
+ if (selector === '[role="treeitem"]') scanned += 1
2381
+ return realQuery(selector)
2382
+ }
2383
+
2384
+ // A character-data mutation: text streaming, nothing structural.
2385
+ observer.callback([{ type: 'characterData', addedNodes: [], removedNodes: [] }])
2386
+ await flush()
2387
+ assert.equal(scanned, 0, 'no row scan for a text-only mutation')
2388
+
2389
+ // A structural one still has to run.
2390
+ observer.callback([{ type: 'childList', addedNodes: [harness.rows[0]], removedNodes: [] }])
2391
+ await flush()
2392
+ assert.equal(scanned, 1, 'one scan when a row arrives')
2393
+ })
2394
+
2395
+ test('the decorate pass does not run a selector engine over every row', async () => {
2396
+ const harness = await loadPlugin()
2397
+ mountRow(harness, SESSION_A)
2398
+ selectRow(harness).element.props.onSelect()
2399
+ await flush()
2400
+
2401
+ const row = harness.rows[0]
2402
+ let rowSelectors = 0
2403
+ const realQuery = row.querySelector.bind(row)
2404
+ row.querySelector = (selector) => { rowSelectors += 1; return realQuery(selector) }
2405
+
2406
+ harness.observers[0].callback([{ type: 'childList', addedNodes: [row], removedNodes: [] }])
2407
+ await flush()
2408
+
2409
+ // The checkbox is always the first element child; a per-row selector call per
2410
+ // frame is the pass's dominant cost with a long list.
2411
+ assert.equal(rowSelectors, 0, 'the checkbox is found without querying')
2412
+ })
2413
+
2414
+ test('a browse-only host falls back to the in-page picker too', async () => {
2415
+ // The host answered `browse`: it has a listing API but no OS chooser to raise.
2416
+ // That is the normal shape for a remote client, so it must not read as an error.
2417
+ const listing = { path: 'C:/ws', parent: 'C:/', entries: [], roots: ['C:/'], truncated: false, defaultRoot: 'C:/home' }
2418
+ const harness = await loadPlugin({ browse: listing, pick: { browse: true } })
2419
+ localStorage.setItem(OFF_KEY, '0')
2420
+ localStorage.setItem(ROOT_KEY, 'C:/ws')
2421
+
2422
+ pageRootBrowse(harness).props.onClick()
2423
+ await tick()
2424
+ await tick()
2425
+
2426
+ assert.ok(pickerElement(harness), 'the in-page picker opened')
2427
+ assert.ok(browseRequests(harness).length > 0, 'and it asked the host for a listing')
2428
+ })
2429
+
2430
+ test('a failing folder dialog says so instead of blaming the delete', async () => {
2431
+ const harness = await loadPlugin()
2432
+ localStorage.setItem(OFF_KEY, '0')
2433
+ const originalFetch = globalThis.fetch
2434
+ globalThis.fetch = async (url, init) => {
2435
+ if (String(url).endsWith('/dsh-delete-session/pick')) {
2436
+ harness.requests.push({ url: String(url), init })
2437
+ return {
2438
+ ok: false,
2439
+ status: 500,
2440
+ json: async () => ({ ok: false, code: 'shell', error: "Cannot read properties of undefined (reading 'aborted')" }),
2441
+ }
2442
+ }
2443
+ return originalFetch(url, init)
2444
+ }
2445
+
2446
+ pageRootBrowse(harness).props.onClick()
2447
+ await tick()
2448
+ await tick()
2449
+
2450
+ const last = toasts(harness).at(-1)
2451
+ assert.match(last, /选择文件夹失败/, 'the picker is named')
2452
+ assert.doesNotMatch(last, /删除失败/, 'and deleting is not blamed for it')
2453
+ assert.match(last, /aborted/, 'the host message is still carried through')
2454
+ })
2455
+
2456
+ // --- first install: the four defaults --------------------------------------
2457
+
2458
+ test('a fresh install ticks all four delete switches', async () => {
2459
+ // No storage at all: this is what a new user sees on the plugin page.
2460
+ const harness = await loadPlugin()
2461
+
2462
+ const expected = [
2463
+ ['ask', '删除时询问', 'ask first'],
2464
+ ['recycle', '删除至回收站', 'recycle bin'],
2465
+ ['syncChildren', '同时删除子会话', 'take the subagent sessions along'],
2466
+ ['off', '不处理产出文件(保持当前行为)', 'leave produced files alone'],
2467
+ ]
2468
+
2469
+ for (const [key, label, why] of expected) {
2470
+ const box = pageCheck(harness, key)
2471
+ assert.ok(box, key + ' renders')
2472
+ assert.equal(box.props.label, label)
2473
+ assert.equal(box.props.checked, true, why)
2474
+ }
2475
+ })
2476
+
2477
+ test('unticking "take the child sessions along" is remembered', async () => {
2478
+ const harness = await loadPlugin()
2479
+ const box = pageCheck(harness, 'syncChildren')
2480
+ assert.equal(box.props.checked, true, 'on by default')
2481
+
2482
+ box.props.onChange(false)
2483
+ // The default is now "on", so the off choice has to be written explicitly:
2484
+ // deleting the key would read back as on again.
2485
+ assert.equal(localStorage.getItem(SYNC_CHILDREN_KEY), '0', 'off is written, not cleared')
2486
+ })
2487
+
2488
+ test('a fresh install deletes the children without listing them', async () => {
2489
+ const harness = await loadPlugin({ children: CHILDREN })
2490
+ mountRow(harness, SESSION_A)
2491
+
2492
+ const { element } = deleteRow(harness, SESSION_A)
2493
+ element.props.onSelect({ shiftKey: false })
2494
+ await flush()
2495
+
2496
+ assert.deepEqual(childChecks(harness), [], 'no per-child ticks to narrow, because they all go')
2497
+ dialogParts(harness).confirm.props.onClick()
2498
+ await flush()
2499
+
2500
+ assert.deepEqual(
2501
+ deleteBody(harness).childSessionIds,
2502
+ ['session-child-one', 'session-child-two'],
2503
+ 'and the delete carries them',
2504
+ )
2505
+ })