dsh-delete-session 0.2.4 → 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/README.md CHANGED
@@ -72,6 +72,8 @@ dsh plugin --profile web add github:DDDMUC/dsh-delete-session
72
72
  | **同时删除子会话** | **关** | 开:删对话时把它派生的子代理会话一起删掉。关:弹窗列出子会话,由你勾选 |
73
73
  | 隔离夹保存位置 | 空(= `$DSH_HOME`) | 可手输、可点「选择文件夹…」调系统对话框、可点「打开」在资源管理器里定位 |
74
74
 
75
+ 产出文件的每一行右侧有两个按钮:**打开所在文件夹**(在资源管理器里定位)和**删除这个文件**(去向跟随「删除至回收站」开关,开则进回收站,关则直接删除)。删除只对本次扫描列出的路径有效,请求里写别的路径会被宿主拒绝。
76
+
75
77
  > 「选择文件夹…」用的是宿主自己的 `ctx.directoryPicker`:本地桌面弹系统对话框,远程/浏览式宿主自动退回页面内的目录列表。插件不再自带任何自绘或自编译的选择器。
76
78
 
77
79
  ### 删除之后文件在哪
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-delete-session",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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
@@ -113,6 +113,12 @@ window.__ModuleLoader__.load({
113
113
  pickerDefault: (path) => `默认路径:${path}`,
114
114
  rootSet: '保存位置已更新',
115
115
  artifactSection: '本对话产出的文件',
116
+ artifactOpenFolder: '打开所在文件夹',
117
+ artifactDeleteFile: '删除这个文件',
118
+ fileDeleted: '文件已删除',
119
+ fileRecycled: '文件已移入回收站',
120
+ fileDeleteFailed: '删除文件失败:',
121
+ revealFailed: '打开文件夹失败:',
116
122
  artifactLoading: '正在扫描…',
117
123
  artifactFailed: '扫描失败:',
118
124
  artifactNone: '没有需要处理的文件。',
@@ -209,6 +215,12 @@ window.__ModuleLoader__.load({
209
215
  pickerDefault: (path) => `Default path: ${path}`,
210
216
  rootSet: 'Location updated',
211
217
  artifactSection: 'Files this conversation produced',
218
+ artifactOpenFolder: 'Open containing folder',
219
+ artifactDeleteFile: 'Delete this file',
220
+ fileDeleted: 'File deleted',
221
+ fileRecycled: 'File moved to the recycle bin',
222
+ fileDeleteFailed: 'Could not delete the file: ',
223
+ revealFailed: 'Could not open the folder: ',
212
224
  artifactLoading: 'Scanning...',
213
225
  artifactFailed: 'Scan failed: ',
214
226
  artifactNone: 'Nothing to handle.',
@@ -593,6 +605,65 @@ window.__ModuleLoader__.load({
593
605
  })
594
606
  }
595
607
 
608
+ /** Drop one row from the dialog after its file left the disk. */
609
+ function forgetFile(sessionId, target) {
610
+ const dialog = state.dialog
611
+ if (dialog === null || dialog.sessionId !== sessionId) return
612
+ const artifacts = dialog.artifacts
613
+ if (artifacts === null || artifacts.plan === null) return
614
+ artifacts.selected.delete(target)
615
+ const keep = (row) => row.path !== target
616
+ artifacts.plan = {
617
+ ...artifacts.plan,
618
+ created: (artifacts.plan.created || []).filter(keep),
619
+ modified: (artifacts.plan.modified || []).filter(keep),
620
+ }
621
+ publish()
622
+ }
623
+
624
+ /** Delete one produced file, then drop its row. */
625
+ function deleteOneFile(sessionId, target) {
626
+ const recycle = recycleSession()
627
+ postDeleteFile(sessionId, target, recycle).then((data) => {
628
+ forgetFile(sessionId, target)
629
+ toast(t(data && data.recycled === true ? 'fileRecycled' : 'fileDeleted'))
630
+ }).catch((reason) => {
631
+ toast(t('fileDeleteFailed') + String((reason && reason.message) || reason), true)
632
+ })
633
+ }
634
+
635
+ /**
636
+ * Delete one produced file. The recycle choice is the same preference that
637
+ * governs a conversation delete, so the two never disagree.
638
+ */
639
+ function postDeleteFile(sessionId, target, recycle) {
640
+ return fetch('/dsh-delete-session/delete-file', {
641
+ method: 'POST',
642
+ headers: { 'content-type': 'application/json' },
643
+ body: JSON.stringify({ sessionId, path: target, recycle }),
644
+ }).then(async (res) => {
645
+ let data = {}
646
+ try { data = await res.json() } catch { /* keep {} */ }
647
+ if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
648
+ return data
649
+ })
650
+ }
651
+
652
+ /**
653
+ * Show one produced file's folder. The host validates that the path is a
654
+ * directory; the browser has no path module, so the parent is taken with a
655
+ * plain last-separator split — Windows separators included.
656
+ */
657
+ function revealParent(filePath) {
658
+ const text = String(filePath === null || filePath === undefined ? '' : filePath).replace(/[\\/]+$/, '')
659
+ const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
660
+ const parent = cut > 0 ? text.slice(0, cut) : text
661
+ if (parent === '') return
662
+ postReveal(parent).catch((reason) => {
663
+ toast(t('revealFailed') + String((reason && reason.message) || reason), true)
664
+ })
665
+ }
666
+
596
667
  /** Show the quarantine folder the current settings would write to. */
597
668
  function openQuarantineRoot(target) {
598
669
  if (typeof target !== 'string' || target === '') return
@@ -686,7 +757,9 @@ window.__ModuleLoader__.load({
686
757
  // host's `Modal`, so it brings no backdrop CSS of its own.
687
758
 
688
759
  const CSS = [
689
- '.dsdel-toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:2147483601;background:Canvas;color:CanvasText;border:1px solid color-mix(in srgb,CanvasText 25%,transparent);padding:9px 16px;border-radius:999px;font-size:12px;box-shadow:0 8px 24px rgba(0,0,0,.25);max-width:min(92vw,460px);cursor:pointer}',
760
+ '.dsdel-toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:2147483601;background:var(--dsw-alias-bg-overlay,var(--dsw-alias-bg-layer-1,#2b2b2b));color:var(--dsw-alias-label-primary,#fff);border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));padding:9px 16px;border-radius:10px;font-size:12.5px;line-height:18px;box-shadow:0 10px 28px rgba(0,0,0,.24);max-width:min(92vw,460px);cursor:pointer;animation:dsdel-toast-in .16s cubic-bezier(.2,.8,.3,1)}',
761
+ '@keyframes dsdel-toast-in{from{opacity:0;transform:translate(-50%,6px)}to{opacity:1;transform:translate(-50%,0)}}',
762
+ '@media (prefers-reduced-motion:reduce){.dsdel-toast{animation:none}.dsdel-field{transition:none}}',
690
763
  '.dsdel-check{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,rgba(128,128,128,.5));background:transparent;flex:none;margin-right:8px;box-sizing:border-box;cursor:pointer}',
691
764
  '.dsdel-check-on{background:var(--dsw-alias-state-business-primary,#4c6ef5);border-color:var(--dsw-alias-state-business-primary,#4c6ef5)}',
692
765
  '.dsdel-check-on::after{content:"";width:9px;height:5px;border-left:2px solid #fff;border-bottom:2px solid #fff;transform:rotate(-45deg) translateY(-1px)}',
@@ -709,10 +782,32 @@ window.__ModuleLoader__.load({
709
782
  '.dsdel-drop-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
710
783
  '.dsdel-bar-count{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary,inherit)}',
711
784
  '.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}',
785
+ '.dsdel-bar-btn:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
712
786
  '.dsdel-bar-btn:disabled{opacity:.5;cursor:default}',
713
787
  '.dsdel-bar-danger{border-color:var(--dsw-alias-state-error-primary,#e5484d);background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}',
788
+ // One token layer for every surface this plugin draws. Everything below
789
+ // reads these rather than repeating a fallback per rule: the host theme then
790
+ // reaches the whole plugin through one block, which is the point of exposing
791
+ // tokens at all.
792
+ '.dsdel-page,.dsdel-modal,.dsdel-bar{--dsdel-bg:var(--dsw-alias-fill-elevated,rgba(127,127,127,.06));--dsdel-bg-hover:var(--dsw-alias-fill-hover,rgba(127,127,127,.10));--dsdel-border:var(--dsw-alias-border-l2,rgba(127,127,127,.28));--dsdel-label:var(--dsw-alias-label-primary,inherit);--dsdel-label-dim:var(--dsw-alias-label-secondary,#666);--dsdel-label-faint:var(--dsw-alias-label-tertiary,#888);--dsdel-danger:var(--dsw-alias-state-error-primary,#e5484d);--dsdel-radius:10px;--dsdel-radius-sm:8px;--dsdel-ring:color-mix(in srgb,var(--dsw-alias-brand-primary,#4c8dff) 45%,transparent);--dsdel-shadow:0 1px 2px rgba(0,0,0,.04)}',
714
793
  '.dsdel-page{display:flex;flex-direction:column;gap:8px}',
715
- '.dsdel-page-hint{margin:0;color:var(--dsw-alias-label-tertiary,#888);font-size:13px;line-height:20px}',
794
+ // Each switch and its explanation read as one block, so a card with eight
795
+ // controls stops looking like one long column of tick boxes.
796
+ '.dsdel-field{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid var(--dsdel-border);border-radius:var(--dsdel-radius);background:var(--dsdel-bg);box-shadow:var(--dsdel-shadow);transition:background .12s ease,border-color .12s ease}',
797
+ '.dsdel-field:hover{background:var(--dsdel-bg-hover)}',
798
+ '.dsdel-field:focus-within{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
799
+ '.dsdel-page-hint{margin:0;color:var(--dsdel-label-faint);font-size:12.5px;line-height:19px;letter-spacing:.01em}',
800
+ // One produced file per row: tick on the left, path in the middle, a folder
801
+ // button on the right. The button sits outside the label so a click opens
802
+ // the folder instead of toggling the tick.
803
+ '.dsdel-file-row{display:flex;align-items:center;gap:8px;padding:4px 6px;border-radius:var(--dsdel-radius-sm);transition:background .12s ease}',
804
+ '.dsdel-file-row:hover{background:var(--dsdel-bg-hover)}',
805
+ '.dsdel-file-label{display:flex;align-items:center;gap:8px;flex:1;min-width:0;cursor:pointer}',
806
+ '.dsdel-file-path{flex:1;min-width:0;word-break:break-all;font-size:13px;line-height:20px;color:var(--dsdel-label)}',
807
+ '.dsdel-file-open{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;padding:0;border:1px solid transparent;border-radius:var(--dsdel-radius-sm);background:transparent;color:var(--dsdel-label-dim);cursor:pointer;transition:background .12s ease,color .12s ease,border-color .12s ease}',
808
+ '.dsdel-file-open:hover{background:var(--dsdel-bg);border-color:var(--dsdel-border);color:var(--dsdel-label)}',
809
+ '.dsdel-file-open:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
810
+ '.dsdel-file-remove:hover{background:color-mix(in srgb,var(--dsdel-danger) 12%,transparent);border-color:color-mix(in srgb,var(--dsdel-danger) 40%,transparent);color:var(--dsdel-danger)}',
716
811
  '.dsdel-star{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-tertiary,#8b93a1);padding:2px 2px 0;}',
717
812
  '.dsdel-star-link{color:var(--dsw-alias-brand-primary,#4d76e6);text-decoration:underline;}',
718
813
  '.dsdel-root-input{flex:1 1 220px;min-width:160px;min-height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-secondary,#d0d0d0);border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px}',
@@ -720,8 +815,11 @@ window.__ModuleLoader__.load({
720
815
  // A wider confirmation dialog: the class reaches it when `Modal` forwards
721
816
  // `className`, and the `:has()` rule catches the host-owned container when
722
817
  // it does not. Both are harmless if the other one is the one that applies.
723
- '.dsdel-dialog-wide{width:min(94vw,980px)!important;max-width:min(94vw,980px)!important}',
724
- '[role="dialog"]:has(.dsdel-modal-meta),[aria-modal="true"]:has(.dsdel-modal-meta){width:min(94vw,980px);max-width:min(94vw,980px)}',
818
+ '.dsdel-dialog-wide{width:min(46vw,860px)!important;max-width:min(46vw,860px)!important;min-height:min(240px,88vh)!important;max-height:88vh!important;display:flex;flex-direction:column;overflow:hidden}',
819
+ '.dsdel-dialog-wide > :first-child{flex:1 1 auto;min-height:0;overflow:auto}',
820
+ '.dsdel-dialog-wide > :last-child{flex:0 0 auto;margin-top:auto}',
821
+ '.dsdel-artifacts{overflow:auto;overscroll-behavior:contain;padding-right:2px}',
822
+ '[role="dialog"]:has(.dsdel-file-row),[aria-modal="true"]:has(.dsdel-file-row){width:min(46vw,860px);max-width:min(46vw,860px);min-height:min(240px,88vh);max-height:88vh}',
725
823
  '.dsdel-picker-list{display:flex;flex-direction:column;gap:2px;max-height:280px;overflow:auto;margin:0 0 8px}',
726
824
  '.dsdel-picker-row{appearance:none;text-align:left;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px;cursor:pointer}',
727
825
  '.dsdel-picker-row:hover{background:var(--dsw-alias-fill-secondary,rgba(127,127,127,0.12))}',
@@ -1528,6 +1626,8 @@ window.__ModuleLoader__.load({
1528
1626
 
1529
1627
  /** Inline glyphs for the two rows; the host exposes no matching pair. */
1530
1628
  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']
1629
+ /** A folder, for "show this file where it lives". */
1630
+ const FOLDER_PATHS = ['M3 6a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z']
1531
1631
  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']
1532
1632
 
1533
1633
  function glyph(paths) {
@@ -1661,21 +1761,55 @@ window.__ModuleLoader__.load({
1661
1761
  elements.push(h('p', { key: 'selected', className: 'dsdel-modal-meta' },
1662
1762
  translate('artifactSelected', artifacts.selected.size)))
1663
1763
  for (const row of rows.slice(0, ARTIFACT_ROWS_SHOWN)) {
1664
- elements.push(h('label', {
1764
+ elements.push(h('div', {
1665
1765
  key: `row:${row.path}`,
1666
- className: 'dsdel-modal-text',
1667
- style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '2px 0', cursor: 'pointer' },
1766
+ 'data-file-row': row.path,
1767
+ className: 'dsdel-file-row',
1668
1768
  },
1669
- h('input', {
1670
- type: 'checkbox',
1671
- checked: artifacts.selected.has(row.path),
1672
- onChange: (e) => {
1673
- if (e && e.target && e.target.checked) artifacts.selected.add(row.path)
1674
- else artifacts.selected.delete(row.path)
1675
- publish()
1769
+ h('label', {
1770
+ key: 'label',
1771
+ className: 'dsdel-file-label',
1772
+ },
1773
+ h('input', {
1774
+ type: 'checkbox',
1775
+ checked: artifacts.selected.has(row.path),
1776
+ onChange: (e) => {
1777
+ if (e && e.target && e.target.checked) artifacts.selected.add(row.path)
1778
+ else artifacts.selected.delete(row.path)
1779
+ publish()
1780
+ },
1781
+ }),
1782
+ h('span', { key: 'path', className: 'dsdel-file-path' }, row.displayPath || row.path),
1783
+ ),
1784
+ // Delete just this file. Same destination rule as the conversation
1785
+ // switch: the system trash when recycling is on, gone when it is not.
1786
+ h('button', {
1787
+ key: 'remove',
1788
+ type: 'button',
1789
+ className: 'dsdel-file-open dsdel-file-remove',
1790
+ title: translate('artifactDeleteFile'),
1791
+ 'aria-label': translate('artifactDeleteFile'),
1792
+ onClick: (event) => {
1793
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1794
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1795
+ deleteOneFile(state.dialog === null ? '' : state.dialog.sessionId, row.path)
1676
1796
  },
1677
- }),
1678
- h('span', { style: { wordBreak: 'break-all' } }, row.displayPath || row.path),
1797
+ }, glyph(TRASH_PATHS)),
1798
+ // One folder per row. What moves is the file, so the thing worth
1799
+ // looking at before deciding is where it lives. The button is a
1800
+ // SIBLING of the label: inside it, a click would toggle the tick box.
1801
+ h('button', {
1802
+ key: 'open',
1803
+ type: 'button',
1804
+ className: 'dsdel-file-open',
1805
+ title: translate('artifactOpenFolder'),
1806
+ 'aria-label': translate('artifactOpenFolder'),
1807
+ onClick: (event) => {
1808
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1809
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1810
+ revealParent(row.path)
1811
+ },
1812
+ }, glyph(FOLDER_PATHS)),
1679
1813
  ))
1680
1814
  }
1681
1815
  if (rows.length > ARTIFACT_ROWS_SHOWN) {
@@ -1691,7 +1825,7 @@ window.__ModuleLoader__.load({
1691
1825
  if (plan.truncated) {
1692
1826
  elements.push(h('p', { key: 'truncated', className: 'dsdel-modal-meta' }, translate('artifactTruncated')))
1693
1827
  }
1694
- return h('div', { key: 'artifacts' }, elements)
1828
+ return h('div', { key: 'artifacts', className: 'dsdel-artifacts' }, elements)
1695
1829
  }
1696
1830
 
1697
1831
  /** Folder picker overlay: walk directories, then commit one. */
@@ -1775,6 +1909,17 @@ window.__ModuleLoader__.load({
1775
1909
  const dialog = view.dialog
1776
1910
  if (dialog === null) return null
1777
1911
 
1912
+ // The file list sizes its own frame: a short list gets a short dialog, a
1913
+ // long one grows until the viewport cap and then scrolls. A forced ratio
1914
+ // cannot do that — it pins the height, so the empty band under two lines
1915
+ // of text simply moves around.
1916
+ const plan = dialog.artifacts !== null && dialog.artifacts !== undefined
1917
+ ? dialog.artifacts.plan
1918
+ : null
1919
+ const listed = plan === null || plan === undefined
1920
+ ? 0
1921
+ : (plan.created || []).length + (plan.modified || []).length
1922
+ const needsFrame = listed > 0 && dialog.artifacts.auto !== true
1778
1923
  const footer = h(
1779
1924
  Fragment,
1780
1925
  null,
@@ -1795,12 +1940,20 @@ window.__ModuleLoader__.load({
1795
1940
 
1796
1941
  return h(primitives.Modal, {
1797
1942
  open: true,
1798
- // The produced-file list needs more room than the default dialog gives.
1799
- // `Modal` does not document a width prop, so the class, the inline style
1800
- // and the `:has()` rule in the stylesheet all try, and whichever the host
1801
- // honours wins.
1802
- className: 'dsdel-dialog-wide',
1803
- style: { width: 'min(94vw, 980px)', maxWidth: 'min(94vw, 980px)' },
1943
+ // `Modal` documents no width prop, so the class, the inline style and the
1944
+ // `:has()` rule in the stylesheet all try; whichever the host honours wins.
1945
+ // 9:16: the file list reads as a column, so the shell is a phone-shaped
1946
+ // card. Width is derived from the height budget (94vh tall at most), which
1947
+ // keeps the ratio on every window size; the list scrolls inside it.
1948
+ ...(needsFrame ? { className: 'dsdel-dialog-wide' } : {}),
1949
+ ...(needsFrame ? {
1950
+ style: {
1951
+ width: 'min(46vw, 860px)',
1952
+ maxWidth: 'min(46vw, 860px)',
1953
+ minHeight: 'min(240px, 88vh)',
1954
+ maxHeight: '88vh',
1955
+ },
1956
+ } : {}),
1804
1957
  onClose: () => closeDeleteDialog(),
1805
1958
  closeLabel: translate('cancel'),
1806
1959
  title: translate('title'),
@@ -2041,7 +2194,36 @@ window.__ModuleLoader__.load({
2041
2194
  rel: 'noreferrer',
2042
2195
  }, translate('starCta'))))
2043
2196
 
2044
- return h('div', { className: 'dsdel-page' }, children)
2197
+ // Each control owns the nodes that explain it. Grouping them here keeps the
2198
+ // markup above flat (a switch and its hint are still two pushes) while the
2199
+ // page draws them as one block.
2200
+ const FIELD_KEYS = new Set(['ask', 'recycle', 'syncChildren', 'off', 'auto', 'scope', 'skipGit', 'root'])
2201
+ function groupFields(nodes) {
2202
+ const groups = []
2203
+ let current = null
2204
+ for (const node of nodes) {
2205
+ const key = node !== null && node !== undefined && node.props ? node.props.key : undefined
2206
+ if (FIELD_KEYS.has(key)) {
2207
+ current = { control: key, nodes: [node] }
2208
+ groups.push(current)
2209
+ continue
2210
+ }
2211
+ // The hint of a control is keyed `<control>Hint`; the root row keeps its
2212
+ // input, buttons and hint under the same prefix.
2213
+ if (current !== null && typeof key === 'string' && key !== 'star' && key !== 'cta'
2214
+ && key.startsWith(current.control)) {
2215
+ current.nodes.push(node)
2216
+ continue
2217
+ }
2218
+ current = null
2219
+ groups.push({ control: null, nodes: [node] })
2220
+ }
2221
+ return groups.map((group, index) => (group.control === null
2222
+ ? group.nodes[0]
2223
+ : h('div', { key: `field:${group.control}`, className: 'dsdel-field' }, ...group.nodes)))
2224
+ }
2225
+
2226
+ return h('div', { className: 'dsdel-page' }, groupFields(children))
2045
2227
  }
2046
2228
 
2047
2229
  // --- plugin ------------------------------------------------------------------
@@ -2118,7 +2300,17 @@ window.__ModuleLoader__.load({
2118
2300
  { name: 'shell.overlay', id: `${NS}-picker`, order: 1, locale: NS },
2119
2301
  QuarantinePicker,
2120
2302
  ))
2121
- // The plugin page card.
2303
+ // The plugin page card, on BOTH seats the manager offers.
2304
+ //
2305
+ // `plugins.bundle.config` renders on the package page, whose address is
2306
+ // `#/panel/plugins/<package>`. `plugins.row.config` renders on the row's
2307
+ // own page, `#/panel/plugins/<package>/<rowId>` — and this bundle's row id
2308
+ // is the package name, so that address repeated itself. The row seat keeps
2309
+ // only its `summary` face, which is the one line the rows list shows.
2310
+ slots.inject('plugins.bundle.config', () => slots.register(
2311
+ { name: 'plugins.bundle.config', key: NS },
2312
+ AskBeforeDeleteOption,
2313
+ ))
2122
2314
  slots.inject('plugins.row.config', () => slots.register(
2123
2315
  { name: 'plugins.row.config', key: `${NS}#${NS}` },
2124
2316
  AskBeforeDeleteOption,
package/src/index.js CHANGED
@@ -858,6 +858,13 @@ async function retireSessionFiles(sessionId, recycle) {
858
858
 
859
859
  const QUARANTINE_PREFIX = 'purge-quarantine'
860
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
861
868
  /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
862
869
  const RESOLVE_CONCURRENCY = 16
863
870
  /** How many directories the folder picker lists before saying there are more. */
@@ -1004,11 +1011,17 @@ async function collectSessionPaths(events, cwd, cache) {
1004
1011
  // names the same handful of files thousands of times, so awaiting per call
1005
1012
  // would buy one threadpool round trip per mention; this buys one per file.
1006
1013
  const named = new Set()
1014
+ let overflow = false
1007
1015
  for (const event of events) {
1008
1016
  const data = event && event.data
1009
1017
  if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1010
1018
  const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1011
- 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)
1012
1025
  }
1013
1026
  await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1014
1027
  await identityKey(absolute, memo)
@@ -1063,7 +1076,7 @@ async function collectSessionPaths(events, cwd, cache) {
1063
1076
  else read.add(call.identity)
1064
1077
  }
1065
1078
 
1066
- return { created, modified }
1079
+ return { named: named.size, overflow, created, modified }
1067
1080
  }
1068
1081
 
1069
1082
  /**
@@ -1207,7 +1220,8 @@ async function planArtifacts(ctx, sessionId, cache, options) {
1207
1220
  }
1208
1221
  const { events, warning } = await readSessionEvents(ctx, sessionId)
1209
1222
  if (warning !== undefined) warnings.push(warning)
1210
- const { created, modified } = await collectSessionPaths(events, cwd, cache)
1223
+ const scan = await collectSessionPaths(events, cwd, cache)
1224
+ const { created, modified } = scan
1211
1225
  const createdPlan = await classifyPaths(created, cwd, home, options)
1212
1226
  const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1213
1227
  const refused = [...createdPlan.refused, ...modifiedPlan.refused]
@@ -1219,7 +1233,8 @@ async function planArtifacts(ctx, sessionId, cache, options) {
1219
1233
  created: createdPlan.allowed.slice(0, MAX_LISTED),
1220
1234
  modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1221
1235
  refused: refused.slice(0, MAX_LISTED),
1222
- truncated: createdPlan.allowed.length > MAX_LISTED
1236
+ truncated: scan.overflow
1237
+ || createdPlan.allowed.length > MAX_LISTED
1223
1238
  || modifiedPlan.allowed.length > MAX_LISTED
1224
1239
  || refused.length > MAX_LISTED,
1225
1240
  warnings,
@@ -1352,6 +1367,72 @@ async function quarantineFiles(targets, cwd, home) {
1352
1367
  return { directory, moved, failed }
1353
1368
  }
1354
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
+
1355
1436
  /**
1356
1437
  * Quarantine the files one request selected. The candidate set is recomputed
1357
1438
  * here from the session log and the request's paths are intersected with it, so
@@ -1752,6 +1833,43 @@ export function apply(ctx) {
1752
1833
  },
1753
1834
  }))
1754
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
+
1755
1873
  // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1756
1874
  // hand a page a filesystem path, but this process is local, so it can.
1757
1875
  fiber.effect(() => webServer.register({
@@ -2007,9 +2125,13 @@ export function apply(ctx) {
2007
2125
  // else in the host reads this face.
2008
2126
  export const internals = {
2009
2127
  pickFolder,
2128
+ artifactCandidates,
2129
+ assertListedPath,
2130
+ removeOneFile,
2010
2131
  claimQuarantineDirectory,
2011
2132
  classifyPaths,
2012
2133
  collectSessionPaths,
2134
+ MAX_SCANNED,
2013
2135
  findSessionCaches,
2014
2136
  freeDestination,
2015
2137
  identityKey,
@@ -1310,3 +1310,146 @@ test('the native chooser is given a live abort signal', async () => {
1310
1310
  assert.equal(typeof seen.aborted, 'boolean', 'and it is an AbortSignal')
1311
1311
  assert.equal(seen.aborted, false, 'not already aborted')
1312
1312
  })
1313
+
1314
+ // --- both subagent creation modes are deletable, and only they -------------
1315
+
1316
+ /**
1317
+ * A subagent started in "fork" mode: it inherits a seeded prefix of the parent
1318
+ * log, so the header carries `isSeeded: true` — but `origin` is still `subagent`,
1319
+ * and the host writes it for both creation modes
1320
+ * (`childSessionMeta` in dsh-subagent sets `origin: "subagent"` unconditionally,
1321
+ * with `isSeeded` recording which mode was used).
1322
+ */
1323
+ const forkedSubagent = (id, parentSession) => ({
1324
+ id,
1325
+ parentSession,
1326
+ origin: 'subagent',
1327
+ isSeeded: true,
1328
+ delegationDepth: 1,
1329
+ })
1330
+
1331
+ test('a subagent started by fork is still a child of its parent', () => {
1332
+ const headers = [
1333
+ header('session-parent'),
1334
+ child('session-child-new', 'session-parent'),
1335
+ forkedSubagent('session-child-fork', 'session-parent'),
1336
+ ]
1337
+
1338
+ const found = internals.collectDescendants(headers, 'session-parent')
1339
+
1340
+ assert.deepEqual(
1341
+ found.map((h) => h.id),
1342
+ ['session-child-new', 'session-child-fork'],
1343
+ 'both creation modes are picked up',
1344
+ )
1345
+ })
1346
+
1347
+ test('a forked subagent can be deleted on its own', () => {
1348
+ const headers = [header('session-parent'), forkedSubagent('session-child-fork', 'session-parent')]
1349
+
1350
+ const picked = internals.selectChildDeletes(headers, 'session-parent', ['session-child-fork'])
1351
+
1352
+ assert.deepEqual(picked, ['session-child-fork'], 'deleting the parent may take the fork-mode child')
1353
+ })
1354
+
1355
+ test('the two modes are told apart from a user fork, which stays untouched', () => {
1356
+ const headers = [
1357
+ header('session-parent'),
1358
+ child('session-child-new', 'session-parent'),
1359
+ forkedSubagent('session-child-fork', 'session-parent'),
1360
+ fork('session-user-fork', 'session-parent'),
1361
+ ]
1362
+
1363
+ const found = internals.collectDescendants(headers, 'session-parent').map((h) => h.id)
1364
+
1365
+ assert.deepEqual(found, ['session-child-new', 'session-child-fork'], 'subagents only')
1366
+ assert.equal(found.includes('session-user-fork'), false, 'a conversation the user branched is not dragged along')
1367
+ })
1368
+ // --- deleting one produced file, with the same recycle choice ----------------
1369
+
1370
+ test('only the files the dialog listed may be deleted one by one', () => {
1371
+ const plan = {
1372
+ created: [{ path: 'C:/ws/new-a.md', ops: 1 }],
1373
+ modified: [{ path: 'C:/ws/old-c.md', ops: 2 }],
1374
+ }
1375
+
1376
+ const candidates = internals.artifactCandidates(plan)
1377
+
1378
+ assert.deepEqual(candidates.sort(), ['C:/ws/new-a.md', 'C:/ws/old-c.md'])
1379
+ // A path the plan never offered is refused by the route; this is the list it
1380
+ // checks against, so it has to cover both groups.
1381
+ assert.equal(candidates.includes('C:/ws/secret.md'), false)
1382
+ })
1383
+
1384
+ test('a permanent single-file delete really removes the file', async () => {
1385
+ const file = path.join(os.tmpdir(), `dsdel-one-${Date.now()}.md`)
1386
+ fs.writeFileSync(file, 'x')
1387
+
1388
+ const result = await internals.removeOneFile(file, false)
1389
+
1390
+ assert.equal(result.recycled, false)
1391
+ assert.equal(fs.existsSync(file), false, 'gone')
1392
+ })
1393
+
1394
+ test('a missing file is reported instead of throwing raw', async () => {
1395
+ const file = path.join(os.tmpdir(), `dsdel-one-missing-${Date.now()}.md`)
1396
+
1397
+ await assert.rejects(
1398
+ () => internals.removeOneFile(file, false),
1399
+ (error) => error instanceof Error,
1400
+ )
1401
+ })
1402
+
1403
+ test('a directory is refused: this button deletes files, not folders', async () => {
1404
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsdel-one-dir-'))
1405
+ try {
1406
+ await assert.rejects(
1407
+ () => internals.removeOneFile(dir, false),
1408
+ (error) => error && error.code === 'not-a-file',
1409
+ )
1410
+ } finally {
1411
+ fs.rmSync(dir, { recursive: true, force: true })
1412
+ }
1413
+ })
1414
+
1415
+ test('a path the plan never listed is refused', () => {
1416
+ const plan = { created: [{ path: 'C:/ws/listed.md' }], modified: [] }
1417
+
1418
+ assert.equal(internals.assertListedPath(plan, 'C:/ws/listed.md'), path.resolve('C:/ws/listed.md'))
1419
+ assert.throws(
1420
+ () => internals.assertListedPath(plan, 'C:/ws/secret.md'),
1421
+ (error) => error && error.code === 'not-listed',
1422
+ )
1423
+ })
1424
+ test('a session that names thousands of files is scanned up to a limit, not forever', async () => {
1425
+ // Every distinct path the log names costs a realpath. A runaway session (an
1426
+ // agent that walked a large tree) can name tens of thousands, and the dialog
1427
+ // would sit on "正在扫描…" while all of them are resolved. The cap bounds that
1428
+ // work; the plan reports `truncated`, which the dialog already shows.
1429
+ const events = []
1430
+ for (let i = 0; i < internals.MAX_SCANNED + 50; i += 1) {
1431
+ events.push({
1432
+ type: 'tool/call',
1433
+ data: {
1434
+ name: 'write',
1435
+ arguments: JSON.stringify({ path: `C:/ws/file-${i}.md` }),
1436
+ },
1437
+ })
1438
+ }
1439
+
1440
+ const result = await internals.collectSessionPaths(events, 'C:/ws', new Map())
1441
+
1442
+ assert.equal(result.overflow, true, 'the scan says it stopped early')
1443
+ assert.equal(result.named <= internals.MAX_SCANNED, true, 'and resolved no more than the cap')
1444
+ })
1445
+
1446
+ test('a small session is not flagged as truncated', async () => {
1447
+ const events = [
1448
+ { type: 'tool/call', data: { name: 'write', arguments: JSON.stringify({ path: 'C:/ws/a.md' }) } },
1449
+ { type: 'tool/call', data: { name: 'write', arguments: JSON.stringify({ path: 'C:/ws/b.md' }) } },
1450
+ ]
1451
+
1452
+ const result = await internals.collectSessionPaths(events, 'C:/ws', new Map())
1453
+
1454
+ assert.equal(result.overflow, false)
1455
+ })
@@ -333,6 +333,9 @@ async function loadPlugin(options = {}) {
333
333
  }
334
334
  // The native dialog route. `unsupported` models a platform without one, which
335
335
  // is what makes the client fall back to the in-page picker.
336
+ if (href.endsWith('/dsh-delete-session/delete-file')) {
337
+ return { ok: true, status: 200, json: async () => ({ ok: true, recycled: true }) }
338
+ }
336
339
  if (href.endsWith('/dsh-delete-session/pick')) {
337
340
  const pick = options.pick ?? { cancelled: true, path: null }
338
341
  if (pick.unsupported === true) {
@@ -1068,14 +1071,16 @@ const artifactSection = (harness) => {
1068
1071
  return kids.find((node) => node && node.props && node.props.key === 'artifacts') ?? null
1069
1072
  }
1070
1073
 
1071
- /** One rendered tick row per listed artifact. */
1074
+ /** One rendered row block per listed artifact. */
1072
1075
  const artifactRows = (harness) => {
1073
1076
  const section = artifactSection(harness)
1074
1077
  if (section === null) return []
1075
- return (section.props.children || []).filter((node) => node && node.type === 'label')
1078
+ return (section.props.children || []).filter((node) => node && node.props && node.props['data-file-row'] !== undefined)
1076
1079
  }
1077
1080
 
1078
- const artifactInputs = (harness) => artifactRows(harness).map((label) => label.props.children[0])
1081
+ /** The tick box of one row lives inside that row's label. */
1082
+ const rowLabel = (row) => (row.props.children || []).find((child) => child && child.type === 'label')
1083
+ const artifactInputs = (harness) => artifactRows(harness).map((row) => rowLabel(row).props.children[0])
1079
1084
 
1080
1085
  /** Open the dialog through the real menu row and let the scan settle. */
1081
1086
  async function openArtifactDialog(harness, session = SESSION_A) {
@@ -2503,3 +2508,284 @@ test('a fresh install deletes the children without listing them', async () => {
2503
2508
  'and the delete carries them',
2504
2509
  )
2505
2510
  })
2511
+ // --- visual layer: tokens, grouped fields, theme-true toast ----------------
2512
+
2513
+ test('the page card groups each switch with its hint in one field block', async () => {
2514
+ const harness = await loadPlugin()
2515
+ const card = pageCard(harness)
2516
+ const fields = (card.props.children ?? []).filter(
2517
+ (node) => node && node.props && node.props.className === 'dsdel-field',
2518
+ )
2519
+
2520
+ // Four switches at minimum: ask / recycle / syncChildren / artifacts-off.
2521
+ assert.ok(fields.length >= 4, 'each control became its own block, saw ' + fields.length)
2522
+ for (const field of fields) {
2523
+ const inner = (field.props.children ?? []).filter(Boolean)
2524
+ assert.ok(inner.length >= 1, 'the block holds the control')
2525
+ }
2526
+ })
2527
+
2528
+ test('the shared tokens are declared once and used by the blocks', async () => {
2529
+ const harness = await loadPlugin()
2530
+ const style = harness.document.head.querySelector('[data-dsh-delete-session="1"]')
2531
+ const css = String(style._text ?? '')
2532
+
2533
+ assert.match(css, /--dsdel-bg:/, 'a background token')
2534
+ assert.match(css, /--dsdel-border:/, 'a border token')
2535
+ assert.match(css, /--dsdel-ring:/, 'a focus ring token')
2536
+ assert.match(css, /\.dsdel-field\{[^}]*border-radius/, 'the block is rounded')
2537
+ assert.match(css, /\.dsdel-field:focus-within\{[^}]*outline/, 'and shows a focus ring')
2538
+ })
2539
+
2540
+ test('the toast follows the theme instead of the OS colour keywords', async () => {
2541
+ const harness = await loadPlugin()
2542
+ const style = harness.document.head.querySelector('[data-dsh-delete-session="1"]')
2543
+ const css = String(style._text ?? '')
2544
+
2545
+ // `Canvas`/`CanvasText` ignore the DSH theme entirely: in a dark app the toast
2546
+ // stayed a light system rectangle.
2547
+ assert.doesNotMatch(css, /background:Canvas/, 'no system background')
2548
+ assert.doesNotMatch(css, /color:CanvasText/, 'no system text colour')
2549
+ assert.match(css, /\.dsdel-toast\{[^}]*var\(--dsw-alias/, 'it reads the host theme tokens')
2550
+ })
2551
+ test('the card is registered on the package page, so its URL has one segment', async () => {
2552
+ const harness = await loadPlugin()
2553
+ const bundleEntry = harness.slotRegistrations.find(
2554
+ (entry) => entry.spec.name === 'plugins.bundle.config',
2555
+ )
2556
+
2557
+ // `plugins.row.config` renders on the row page, whose URL is
2558
+ // `#/panel/plugins/<package>/<rowId>` — with the row id equal to the package
2559
+ // name here, the address doubled. `plugins.bundle.config` renders on the
2560
+ // package page itself: `#/panel/plugins/<package>`.
2561
+ assert.ok(bundleEntry, 'the bundle-level slot is registered')
2562
+ assert.equal(bundleEntry.spec.key, NS, 'keyed by the package name')
2563
+
2564
+ const rendered = bundleEntry.Component({ view: 'page' })
2565
+ const fields = (rendered.props.children ?? []).filter(
2566
+ (node) => node && node.props && node.props.className === 'dsdel-field',
2567
+ )
2568
+ assert.ok(fields.length >= 4, 'and it carries the same switches')
2569
+ })
2570
+
2571
+ test('the row page keeps its one-line summary', async () => {
2572
+ const harness = await loadPlugin()
2573
+ const rowEntry = harness.slotRegistrations.find(
2574
+ (entry) => entry.spec.name === 'plugins.row.config',
2575
+ )
2576
+ assert.ok(rowEntry, 'the row summary is still registered')
2577
+
2578
+ const summary = rowEntry.Component({ view: 'summary' })
2579
+ assert.equal(typeof summary, 'string', 'the row list gets a sentence, not a card')
2580
+ })
2581
+ // --- each produced file can be opened where it lives ------------------------
2582
+
2583
+ /** The row block for one produced file inside the dialog. */
2584
+ function fileRow(harness, path) {
2585
+ const modal = dialogElement(harness)
2586
+ if (modal === null) return null
2587
+ const stack = [modal]
2588
+ while (stack.length > 0) {
2589
+ const node = stack.pop()
2590
+ if (node === null || node === undefined || typeof node !== 'object') continue
2591
+ if (node.props && node.props['data-file-row'] === path) return node
2592
+ const kids = node.props && node.props.children
2593
+ if (Array.isArray(kids)) stack.push(...kids)
2594
+ else if (kids) stack.push(kids)
2595
+ }
2596
+ return null
2597
+ }
2598
+
2599
+ test('every produced file offers a button that opens its folder', async () => {
2600
+ const harness = await loadPlugin({ plan: PLAN })
2601
+ localStorage.setItem(OFF_KEY, '0')
2602
+ mountRow(harness, SESSION_A)
2603
+ await openArtifactDialog(harness)
2604
+
2605
+ const target = PLAN.created[0].path
2606
+ const row = fileRow(harness, target)
2607
+ assert.ok(row, 'the file has its own row block')
2608
+
2609
+
2610
+ const button = findByKey(row.props.children ?? [], 'open')[0]
2611
+ assert.ok(button, 'the row carries an open button')
2612
+
2613
+ const before = harness.requests.filter((request) => request.url.endsWith('/dsh-delete-session/reveal')).length
2614
+ button.props.onClick({ preventDefault() {}, stopPropagation() {} })
2615
+ await tick()
2616
+ await tick()
2617
+
2618
+ const reveals = harness.requests.filter((request) => request.url.endsWith('/dsh-delete-session/reveal'))
2619
+ assert.equal(reveals.length, before + 1, 'the host is asked to reveal a folder')
2620
+ // The folder, not the file: the OS file manager highlights a file in its parent.
2621
+ assert.equal(JSON.parse(reveals.at(-1).init.body).path, 'C:/ws', 'the parent directory is passed')
2622
+ })
2623
+
2624
+ test('the open button does not disturb the selection', async () => {
2625
+ const harness = await loadPlugin({ plan: PLAN })
2626
+ localStorage.setItem(OFF_KEY, '0')
2627
+ mountRow(harness, SESSION_A)
2628
+ await openArtifactDialog(harness)
2629
+
2630
+ const target = PLAN.created[0].path
2631
+ const checkbox = rowLabel(fileRow(harness, target)).props.children[0]
2632
+ assert.equal(checkbox.props.checked, true, 'ticked by default')
2633
+
2634
+ const button = findByKey(fileRow(harness, target).props.children ?? [], 'open')[0]
2635
+ button.props.onClick({ preventDefault() {}, stopPropagation() {} })
2636
+ await tick()
2637
+
2638
+ const after = rowLabel(fileRow(harness, target)).props.children[0]
2639
+ assert.equal(after.props.checked, true, 'still ticked: opening a folder is not a toggle')
2640
+ })
2641
+ // --- the per-file delete button follows the recycle switch -----------------
2642
+
2643
+ const removeButton = (harness, target) =>
2644
+ findByKey(fileRow(harness, target).props.children ?? [], 'remove')[0]
2645
+
2646
+ const deleteFileCalls = (harness) =>
2647
+ harness.requests.filter((request) => request.url.endsWith('/dsh-delete-session/delete-file'))
2648
+
2649
+ test('deleting one file honours the recycle switch', async () => {
2650
+ const harness = await loadPlugin({ plan: PLAN })
2651
+ localStorage.setItem(OFF_KEY, '0')
2652
+ mountRow(harness, SESSION_A)
2653
+ await openArtifactDialog(harness)
2654
+
2655
+ const target = PLAN.created[0].path
2656
+ removeButton(harness, target).props.onClick({ preventDefault() {}, stopPropagation() {} })
2657
+ await tick()
2658
+ await tick()
2659
+
2660
+ const calls = deleteFileCalls(harness)
2661
+ assert.equal(calls.length, 1, 'one request')
2662
+ const body = JSON.parse(calls[0].init.body)
2663
+ assert.equal(body.path, target)
2664
+ assert.equal(body.recycle, true, 'recycling is on by default, same as a conversation')
2665
+ })
2666
+
2667
+ test('with recycling off the file is deleted outright', async () => {
2668
+ const harness = await loadPlugin({ plan: PLAN })
2669
+ localStorage.setItem(OFF_KEY, '0')
2670
+ localStorage.setItem(RECYCLE_KEY, '0')
2671
+ mountRow(harness, SESSION_A)
2672
+ await openArtifactDialog(harness)
2673
+
2674
+ const target = PLAN.created[0].path
2675
+ removeButton(harness, target).props.onClick({ preventDefault() {}, stopPropagation() {} })
2676
+ await tick()
2677
+ await tick()
2678
+
2679
+ const body = JSON.parse(deleteFileCalls(harness)[0].init.body)
2680
+ assert.equal(body.recycle, false, 'the switch decides, not the button')
2681
+ })
2682
+
2683
+ test('a deleted file leaves the list and the selection', async () => {
2684
+ const harness = await loadPlugin({ plan: PLAN })
2685
+ localStorage.setItem(OFF_KEY, '0')
2686
+ mountRow(harness, SESSION_A)
2687
+ await openArtifactDialog(harness)
2688
+
2689
+ const target = PLAN.created[0].path
2690
+ assert.ok(fileRow(harness, target), 'the row starts out there')
2691
+
2692
+ removeButton(harness, target).props.onClick({ preventDefault() {}, stopPropagation() {} })
2693
+ await tick()
2694
+ await tick()
2695
+
2696
+ assert.equal(fileRow(harness, target), null, 'the row is gone')
2697
+ assert.equal(artifactRows(harness).length, 1, 'the other file stays')
2698
+ })
2699
+ // --- only the file list earns the wide dialog ------------------------------
2700
+
2701
+ test('a plain confirmation keeps the host compact size', async () => {
2702
+ // No produced files here: the everyday "delete this conversation?" box. A
2703
+ // forced ratio would make it a screen-sized empty rectangle, because a
2704
+ // percentage of a wide monitor is simply a wide box.
2705
+ const harness = await loadPlugin()
2706
+ mountRow(harness, SESSION_A)
2707
+ const { element } = deleteRow(harness, SESSION_A)
2708
+ element.props.onSelect({ shiftKey: false })
2709
+ await flush()
2710
+
2711
+ const modal = dialogElement(harness)
2712
+ assert.ok(modal, 'the dialog opened')
2713
+ assert.equal(modal.props.className, undefined, 'no frame class')
2714
+ assert.equal(modal.props.style, undefined, 'and no forced size')
2715
+ })
2716
+
2717
+ test('the dialog widens when it actually lists files', async () => {
2718
+ const harness = await loadPlugin({ plan: PLAN })
2719
+ localStorage.setItem(OFF_KEY, '0')
2720
+ mountRow(harness, SESSION_A)
2721
+ await openArtifactDialog(harness)
2722
+
2723
+ const modal = dialogElement(harness)
2724
+ assert.equal(modal.props.className, 'dsdel-dialog-wide', 'the list needs the room')
2725
+ })
2726
+
2727
+ test('the stylesheet keys the wide rule on the file rows, not on any meta line', async () => {
2728
+ const harness = await loadPlugin()
2729
+ const style = harness.document.head.querySelector('[data-dsh-delete-session="1"]')
2730
+ const css = String(style._text ?? '')
2731
+
2732
+ // `:has(.dsdel-modal-meta)` matched every dialog this plugin draws — the meta
2733
+ // line is just "title · id" — and widened all of them.
2734
+ assert.doesNotMatch(css, /:has\(\.dsdel-modal-meta\)/, 'no widening on a meta line')
2735
+ assert.match(css, /:has\(\.dsdel-file-row\)/, 'the file rows are what earns the width')
2736
+ })
2737
+
2738
+ test('the dialog is a 16:9 landscape card', async () => {
2739
+ const harness = await loadPlugin({ plan: PLAN })
2740
+ localStorage.setItem(OFF_KEY, '0')
2741
+ mountRow(harness, SESSION_A)
2742
+ await openArtifactDialog(harness)
2743
+
2744
+ const modal = dialogElement(harness)
2745
+ const style = modal.props.style
2746
+ assert.match(String(style.width), /46vw/, 'the width budget is a share of the viewport')
2747
+ assert.match(String(style.width), /860px/, 'and it has a pixel ceiling for large monitors')
2748
+ assert.equal(style.maxHeight, '88vh', 'and never runs past the viewport')
2749
+
2750
+ // The list is the only part that grows, so it is the part that scrolls.
2751
+ const section = artifactSection(harness)
2752
+ assert.equal(section.props.className, 'dsdel-artifacts', 'the column is a scroll container')
2753
+ })
2754
+
2755
+ test('the stylesheet carries the same 16:9 geometry', async () => {
2756
+ const harness = await loadPlugin()
2757
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
2758
+
2759
+ assert.match(css, /\.dsdel-dialog-wide\{[^}]*max-width/, 'the class rule bounds the width')
2760
+ assert.match(css, /\.dsdel-artifacts\{[^}]*overflow:auto/, 'the column scrolls')
2761
+ })
2762
+
2763
+ test('the fixed-height frame keeps its buttons at the bottom', async () => {
2764
+ const harness = await loadPlugin()
2765
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
2766
+
2767
+ // The host renders the dialog as a flex column of [content, footer]. Keying on
2768
+ // OUR class plus first/last child survives a host restyle, which the hashed
2769
+ // module class names (`_content_14mp3_63`) would not.
2770
+ assert.match(css, /\.dsdel-dialog-wide\{[^}]*display:flex/, 'the frame is a flex column')
2771
+ assert.match(css, /\.dsdel-dialog-wide\{[^}]*flex-direction:column/, 'with the host\'s own direction')
2772
+ assert.match(css, /\.dsdel-dialog-wide > :first-child\{[^}]*flex:1/, 'the content takes the slack')
2773
+ assert.match(css, /\.dsdel-dialog-wide > :first-child\{[^}]*overflow:auto/, 'and scrolls instead of growing')
2774
+ assert.match(css, /\.dsdel-dialog-wide > :last-child\{[^}]*margin-top:auto/, 'the footer is pushed down')
2775
+ })
2776
+
2777
+ test('the frame sizes itself to the list', async () => {
2778
+ const harness = await loadPlugin({ plan: PLAN })
2779
+ localStorage.setItem(OFF_KEY, '0')
2780
+ mountRow(harness, SESSION_A)
2781
+ await openArtifactDialog(harness)
2782
+
2783
+ const style = dialogElement(harness).props.style
2784
+ // A ratio pins the height, which is what produced the empty band in the first
2785
+ // place: the box would keep a screen-ish height no matter how few rows it had.
2786
+ assert.equal(style.aspectRatio, undefined, 'no forced ratio')
2787
+ assert.equal(style.height, undefined, 'and no forced height')
2788
+ assert.equal(style.height, undefined, 'the height follows the list, not a ratio')
2789
+ assert.equal(style.maxHeight, '88vh', 'capped by the viewport')
2790
+ assert.match(String(style.minHeight), /240px/, 'and it never collapses')
2791
+ })