dsh-sweeper 1.4.4 → 1.5.0

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
@@ -85,6 +85,16 @@ publishing → Add publisher → GitHub Actions**,填
85
85
  - 一周内**被工具用过**的,不进列表(只在顶部「保护」里计数)。
86
86
  - 清理 = `rename` 进 `DSH_HOME/plugin-data/dsh-sweeper/trash/<批次>/`,并写 `manifest.json`;不调用 `unlink` 删用户文件。
87
87
 
88
+ ## 扫描在后台继续(v1.5)
89
+
90
+ 一次扫描要读几十上百段会话日志(本机约 10–20 秒)。它**属于宿主进程,不属于这个页面**:切到别的设置页、关掉侧边栏、去干活,扫描都不会停,读完后照样把报告发出来。
91
+
92
+ 重新打开时先问 `GET /status`,如果一遍正在跑,就按 `第 1/2 遍 · 12 / 46 个会话` 继续显示进度,而不是从 0 重来;页面每 900 ms 拉一次进度,扫描结束后自动把新报告渲染出来。横幅上写着一句话:「可以离开这个页面,扫描会在后台继续;回来时接着显示进度,不会从头再来。」
93
+
94
+ 具体实现只有三处:`lib/scan.js` 在每段会话上报 `onProgress({pass, done, total})`;`lib/index.js` 把它写进 `state.scanJob` 并由 `/status` 暴露;`lib/client.js` 在挂载时先读 `/status`、再决定是显示横幅还是直接读报告。`/report` 本身仍然阻塞到扫描结束(这样它的响应一定是完整的),所以页面必须并行去问 `/status`——否则刷新时只会看到一句「正在读取会话日志」。
95
+
96
+ `test/browser/check.mjs` 用 `?scanning=1` 让回放服务的 `/status` 一直返回「进行中」,断言横幅、计数(`31 / 46`)和那句离开提示都在;`test/harness.js` 另有两个静态状态(`scanning`、`scanningSecondPass`)。
97
+
88
98
  ## 路由
89
99
 
90
100
  | 方法 | 路径 | 说明 |
@@ -98,6 +108,7 @@ publishing → Add publisher → GitHub Actions**,填
98
108
  | POST | `/plugins/dsh-sweeper/deep/start` | `{token, consent:true}`,启动深度分析(最多 4 段并发),立即返回 `jobId`;未带 `consent` 返回 400 |
99
109
  | GET | `/plugins/dsh-sweeper/deep/status` | 当前任务进度与已收集结果(客户端每 900ms 拉一次) |
100
110
  | POST | `/plugins/dsh-sweeper/deep/cancel` | `{jobId}`,停止派发新的对话,已返回的结果保留 |
111
+ | GET | `/plugins/dsh-sweeper/status` | 正在跑的扫描:`{scanning, job:{pass,done,total,startedAt,finishedAt}, hasReport, ageMs}`;页面靠它显示后台进度 |
101
112
  | GET | `/plugins/dsh-sweeper/health` | 扫描状态 |
102
113
 
103
114
  POST 必须带 `x-dsh-sweeper: 1` 头(跨站请求无法携带自定义头,借此挡掉 CSRF);`token` 与最近一次扫描绑定,过期或重扫后失效;选中「不确定」项时必须 `acknowledge: true`。
package/lib/client.js CHANGED
@@ -989,12 +989,16 @@ window.__ModuleLoader__.load({
989
989
  const [deepConsent, setDeepConsent] = useState(false)
990
990
  const [deepErr, setDeepErr] = useState(null)
991
991
  const [deepSel, setDeepSel] = useState(() => new Set())
992
+ // A pass belongs to the host, not to this page: leaving the settings
993
+ // screen does not stop it. This is the one already running when the page
994
+ // opened, so the panel can show its progress instead of a blank skeleton.
995
+ const [bgScan, setBgScan] = useState(null)
992
996
  const scanStart = useRef(Date.now())
993
997
  const reviewStart = useRef(0)
994
998
  const loadSeq = useRef(0)
995
999
  const startingRef = useRef(false)
996
1000
 
997
- const scanning = status === 'loading' || status === 'refreshing'
1001
+ const scanning = status === 'loading' || status === 'refreshing' || !!bgScan
998
1002
 
999
1003
  const load = useCallback((force, keepReview) => {
1000
1004
  // Two quick clicks used to race: the slower response could land last and
@@ -1004,6 +1008,16 @@ window.__ModuleLoader__.load({
1004
1008
  scanStart.current = Date.now()
1005
1009
  setStatus((s) => (s === 'loading' ? 'loading' : 'refreshing'))
1006
1010
  setError(null)
1011
+ // /report blocks until the pass finishes, so ask for its progress in
1012
+ // parallel; without this a refresh triggered from the page would show
1013
+ // a bare skeleton for the whole ten seconds.
1014
+ getJSON('/status')
1015
+ .then((d) => {
1016
+ if (seq !== loadSeq.current || !d || !d.scanning) return
1017
+ scanStart.current = (d.job && d.job.startedAt) || Date.now()
1018
+ setBgScan(d.job || { pass: 1, done: 0, total: 0, startedAt: Date.now() })
1019
+ })
1020
+ .catch(() => {})
1007
1021
  getJSON('/report' + (force ? '?refresh=1' : ''))
1008
1022
  .then((data) => {
1009
1023
  if (seq !== loadSeq.current) return
@@ -1048,7 +1062,47 @@ window.__ModuleLoader__.load({
1048
1062
  .finally(() => { planningRef.current = false; setDeepPlanning(false) })
1049
1063
  }, [])
1050
1064
 
1051
- useEffect(() => { load(false); loadTrash() }, [load, loadTrash])
1065
+ // Ask the host whether a pass is already in flight before asking for a
1066
+ // report: /report waits for the running scan, so calling it first would
1067
+ // look like "nothing happens" for the whole duration.
1068
+ const bgKey = bgScan ? bgScan.startedAt + ':' + bgScan.pass : ''
1069
+ useEffect(() => {
1070
+ let stop = false
1071
+ getJSON('/status')
1072
+ .then((d) => {
1073
+ if (stop) return
1074
+ if (d && d.scanning) {
1075
+ scanStart.current = (d.job && d.job.startedAt) || Date.now()
1076
+ setBgScan(d.job || { pass: 1, done: 0, total: 0, startedAt: Date.now() })
1077
+ setStatus('loading')
1078
+ } else {
1079
+ load(false)
1080
+ }
1081
+ })
1082
+ .catch(() => { if (!stop) load(false) })
1083
+ return () => { stop = true }
1084
+ }, [load])
1085
+
1086
+ useEffect(() => { loadTrash() }, [loadTrash])
1087
+
1088
+ // Follow the background pass until it settles, then read the report it
1089
+ // published. 900 ms is slow enough to be invisible, fast enough that the
1090
+ // counter moves while the user watches it.
1091
+ useEffect(() => {
1092
+ if (!bgScan) return
1093
+ let stop = false
1094
+ const tick = () => {
1095
+ getJSON('/status')
1096
+ .then((d) => {
1097
+ if (stop) return
1098
+ if (!d || !d.scanning) { setBgScan(null); load(false); return }
1099
+ setBgScan(d.job || null)
1100
+ })
1101
+ .catch(() => { /* keep the last known progress; the next tick retries */ })
1102
+ }
1103
+ const id = setInterval(tick, 900)
1104
+ return () => { stop = true; clearInterval(id) }
1105
+ }, [bgKey, load])
1052
1106
  useEffect(() => {
1053
1107
  if (!toast) return
1054
1108
  const id = setTimeout(() => setToast(null), 4200)
@@ -1483,8 +1537,30 @@ window.__ModuleLoader__.load({
1483
1537
  report && report.truncated ? h('span', { style: { fontSize: 11, color: T.warn } }, '结果超过 2000 条,只列出最大的部分') : null,
1484
1538
  ),
1485
1539
 
1540
+ bgScan ? h('div', { className: 'sw-card', style: { marginTop: 12, padding: '12px 14px' } },
1541
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
1542
+ h('div', { className: 'sw-spin' }),
1543
+ h('div', { style: { fontSize: 12.5, fontWeight: 600 } }, '正在扫描'),
1544
+ h('span', { className: 'sw-num', style: { fontSize: 11.5, color: T.dim } },
1545
+ '第 ' + (bgScan.pass || 1) + '/2 遍 · ' + (bgScan.total
1546
+ ? fmtNum(bgScan.done || 0) + ' / ' + fmtNum(bgScan.total) + ' 个会话'
1547
+ : '正在读取会话列表')),
1548
+ h('div', { style: { flex: 1 } }),
1549
+ h('span', { className: 'sw-num', style: { fontSize: 11, color: T.faint } },
1550
+ h(Timer, { start: scanStart.current, running: true }))),
1551
+ h('div', { className: 'sw-progress', style: { marginTop: 8 } },
1552
+ h('div', {
1553
+ className: 'sw-progress-fill',
1554
+ style: { width: Math.max(4, Math.min(100, bgScan.total ? Math.round((bgScan.done / bgScan.total) * 100) : 6)) + '%' },
1555
+ })),
1556
+ h('div', { style: { fontSize: 11, color: T.faint, marginTop: 6 } },
1557
+ '可以离开这个页面,扫描会在后台继续;回来时接着显示进度,不会从头再来。'),
1558
+ ) : null,
1559
+
1486
1560
  tab === 'report' ? h(ReportPanel, {
1487
- report, status, error, selected, setSelected,
1561
+ // The banner above already explains a running pass; letting the panel
1562
+ // show its own "reading logs" skeleton too reads like two scans.
1563
+ report, status: bgScan ? 'ready' : status, error, selected, setSelected,
1488
1564
  onScan: () => load(true),
1489
1565
  onDelete: askDelete,
1490
1566
  onExport: exportJSON,
package/lib/index.js CHANGED
@@ -91,6 +91,9 @@ export function apply(ctx, config = {}) {
91
91
  token: null,
92
92
  byKey: new Map(),
93
93
  running: null,
94
+ // The last scan pass, kept after it settles so a page opened mid-scan (or
95
+ // right after one) can show how far it got instead of a blank skeleton.
96
+ scanJob: null,
94
97
  reviewing: false,
95
98
  lastError: null,
96
99
  // Bumped whenever something moved on disk (delete/restore). A scan that was
@@ -273,23 +276,32 @@ export function apply(ctx, config = {}) {
273
276
  // which left a window where a second caller saw no running pass and started
274
277
  // its own full scan on top of the one that had just finished.
275
278
  if (state.running) return state.running
279
+ const job = { startedAt: Date.now(), pass: 1, done: 0, total: 0, finishedAt: 0 }
280
+ state.scanJob = job
276
281
  state.running = (async () => {
277
282
  try {
278
283
  let epoch = state.epoch
279
284
  let report = null
280
285
  for (let i = 0; i < 3; i++) {
281
286
  state.passes += 1
282
- report = await scan(ctx, { week: weekDays * DAY })
287
+ report = await scan(ctx, {
288
+ week: weekDays * DAY,
289
+ // A pass restarts from the first conversation; the page says which
290
+ // pass it is looking at rather than pretending the count reset.
291
+ onProgress: (p) => { job.pass = p.pass; job.done = p.done; job.total = p.total },
292
+ })
283
293
  if (state.epoch === epoch) break
284
294
  epoch = state.epoch
285
295
  }
286
296
  state.lastError = null
297
+ job.done = job.total
287
298
  return publish(report)
288
299
  } catch (err) {
289
300
  state.lastError = (err && err.message) || String(err)
290
301
  try { ctx.logger && ctx.logger.warn && ctx.logger.warn('[dsh-sweeper] scan failed: %s', state.lastError) } catch { /* ignore */ }
291
302
  throw err
292
303
  } finally {
304
+ job.finishedAt = Date.now()
293
305
  state.running = null
294
306
  }
295
307
  })()
@@ -749,6 +761,27 @@ export function apply(ctx, config = {}) {
749
761
  sendJSON(res, 200, gone)
750
762
  })
751
763
 
764
+ // Closing the settings page does not stop a pass; this is how a reopened
765
+ // page finds the one already running instead of starting a second one.
766
+ route(BASE + '/status', async (req, res) => {
767
+ const job = state.scanJob
768
+ const r = state.report
769
+ sendJSON(res, 200, {
770
+ scanning: !!state.running,
771
+ job: job ? {
772
+ pass: job.pass,
773
+ done: job.done,
774
+ total: job.total,
775
+ startedAt: job.startedAt,
776
+ finishedAt: job.finishedAt || 0,
777
+ ms: (job.finishedAt || Date.now()) - job.startedAt,
778
+ } : null,
779
+ hasReport: !!r,
780
+ ageMs: r ? Date.now() - state.publishedAt : null,
781
+ lastError: state.lastError,
782
+ })
783
+ })
784
+
752
785
  route(BASE + '/health', async (req, res) => {
753
786
  const r = state.report
754
787
  sendJSON(res, 200, {
@@ -842,6 +875,28 @@ export function applySelfTest(ctx) {
842
875
  const report = JSON.parse(scanOut.body)
843
876
  out.scanPasses = ctx.__sweeperState ? ctx.__sweeperState.passes : null
844
877
  out.steps.push({ step: 'scan', status: scanOut.status, items: (report.items || []).length, tiers: report.tiers, protected: report.protected, unreadable: (report.unreadable || []).length, truncated: !!report.truncated, scanMs: report.durationMs })
878
+ // The panel shows a pass that is already running, which it learns from
879
+ // /status. Check the bookkeeping: a finished pass must report done ==
880
+ // total and a finish time, otherwise the banner would never clear.
881
+ const idle = JSON.parse((await call('GET', '/plugins/dsh-sweeper/status')).body)
882
+ out.steps.push({
883
+ step: 'status-idle', scanning: !!idle.scanning, hasReport: !!idle.hasReport,
884
+ done: idle.job && idle.job.done, total: idle.job && idle.job.total,
885
+ finished: !!(idle.job && idle.job.finishedAt),
886
+ })
887
+ // Fire a refresh without waiting for it, then look for scanning:true.
888
+ // The pass is short enough to finish first; a miss is reported, not failed.
889
+ const pending = call('GET', '/plugins/dsh-sweeper/report?refresh=1')
890
+ let observed = false
891
+ let total = 0
892
+ for (let i = 0; i < 15 && !observed; i++) {
893
+ await new Promise((r) => setTimeout(r, 100))
894
+ const s = JSON.parse((await call('GET', '/plugins/dsh-sweeper/status')).body)
895
+ if (s.scanning) { observed = true; total = (s.job && s.job.total) || 0 }
896
+ }
897
+ await pending
898
+ out.steps.push({ step: 'status-running', observed, total })
899
+
845
900
  const planOut = await call('GET', '/plugins/dsh-sweeper/deep/plan?refresh=1')
846
901
  const plan = JSON.parse(planOut.body)
847
902
  out.steps.push({ step: 'plan', status: planOut.status, sessions: (plan.sessions || []).length, estTokens: plan.estTokens, concurrency: plan.concurrency })
package/lib/scan.js CHANGED
@@ -250,6 +250,15 @@ export async function scan(ctx, opts = {}) {
250
250
  const unreadable = []
251
251
  const stats = { sessions: 0, events: 0, toolCalls: 0, errors: 0, openJobs: 0 }
252
252
 
253
+ const onProgress = typeof opts.onProgress === 'function' ? opts.onProgress : null
254
+ const total = list.length
255
+ // Reporting a pass is best effort: a throwing listener must never abort a
256
+ // scan, and a slow one must never be awaited.
257
+ const tick = (pass, done) => {
258
+ if (!onProgress) return
259
+ try { onProgress({ pass, done, total }) } catch { /* progress is cosmetic */ }
260
+ }
261
+
253
262
  const titleOf = new Map()
254
263
  const addArtifact = (raw, producer) => {
255
264
  const key = normKey(raw)
@@ -273,7 +282,10 @@ export async function scan(ctx, opts = {}) {
273
282
  }
274
283
 
275
284
  // ── pass 1: producers, spill paths, job bookkeeping ─────────────────────
285
+ let passOne = 0
276
286
  for (const snap of list) {
287
+ tick(1, passOne++)
288
+
277
289
  const id = idOf(snap)
278
290
  if (!id) continue
279
291
  let handle
@@ -343,7 +355,10 @@ export async function scan(ctx, opts = {}) {
343
355
  }
344
356
 
345
357
  // ── pass 2: references (any later text that names a known path) ─────────
358
+ let passTwo = 0
346
359
  for (const snap of list) {
360
+ tick(2, passTwo++)
361
+
347
362
  const id = idOf(snap)
348
363
  if (!id || unreadable.includes(String(id))) continue
349
364
  let handle
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sweeper",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "description": "清理对话留下的临时文件与垃圾,释放磁盘空间;只报告,清理进回收站可恢复 (cleanup junk files conversations leave on disk, free up space)",
6
6
  "keywords": [