dsh-sessions-manager 3.4.0 → 3.4.1

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-sessions-manager",
3
3
  "description": "DSH 设置面板会话管理器:归档 / 恢复 / 彻底删除 / 移动到其他工作区,带工作区标签与会话日期;统一「会话管理」面板。Session manager for the DeepSeek Harness settings panel — archive / restore / permanently delete / move sessions across workspaces, with workspace tags & session dates in one unified panel.",
4
- "version": "3.4.0",
4
+ "version": "3.4.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -432,7 +432,9 @@ function SessionPanel({ workspacesSvc }) {
432
432
  setBusy(null)
433
433
  const n = it.title || it.sessionId
434
434
  showToast(action === 'archive' ? `已归档「${n}」` : `已恢复「${n}」`)
435
- refresh()
435
+ // 单条归档/恢复只是成员标记翻转:本地更新即可,不走整表 refresh
436
+ //(refresh 会清空多选状态;host 侧缓存已把列表成本压到 stat 级别)。
437
+ setSessions((s) => s && s.map((x) => (x.sessionId === it.sessionId ? { ...x, archived: action === 'archive' } : x)))
436
438
  })
437
439
  .catch((e) => { setBusy(null); setError(String((e && e.message) || e)) })
438
440
  }
@@ -445,8 +447,12 @@ function SessionPanel({ workspacesSvc }) {
445
447
  setBusy(null)
446
448
  const n = delTarget.title || delTarget.sessionId
447
449
  showToast(`已删除 ${n}(已移入回收站)`)
450
+ const sid = String(delTarget.sessionId)
448
451
  setDelTarget(null)
449
- refresh()
452
+ // 删除进入回收站:本地移除该行 + 单刷回收站,不整表 refresh。
453
+ setSessions((s) => s && s.filter((x) => String(x.sessionId) !== sid))
454
+ loadTrash()
455
+ dsmLoadTrashIds()
450
456
  })
451
457
  .catch((e) => { setBusy(null); setDelTarget(null); setError(String((e && e.message) || e)) })
452
458
  }
@@ -559,7 +565,10 @@ function SessionPanel({ workspacesSvc }) {
559
565
  setMoveMode('existing')
560
566
  setNewPath('')
561
567
  showToast(`已把「${it.title || it.sessionId}」移到 ${r.workspaceTitle || targetPath}`)
562
- refresh()
568
+ // 移动只改 workspacePath/workspaceTitle:本地替换该行,不整表 refresh。
569
+ setSessions((s) => s && s.map((x) => (x.sessionId === it.sessionId
570
+ ? { ...x, workspacePath: r.workspacePath || targetPath, workspaceTitle: r.workspaceTitle || targetPath }
571
+ : x)))
563
572
  })
564
573
  .catch((e) => { setBusy(null); setError(String((e && e.message) || e)) })
565
574
  }
@@ -1627,6 +1636,16 @@ function installSidebarWorkspaceDrag() {
1627
1636
  // native drag gesture for reordering sessions inside one group; only a real
1628
1637
  // workspace-heading target is intercepted here, so same-group sorting keeps
1629
1638
  // its official behavior.
1639
+ // 指针按下先于 dragstart 数十到数百毫秒,正好用来给「Map 里还没有的行」预热:
1640
+ // replace the 5s poll with a just-in-time fetch, so a brand-new session is
1641
+ // draggable on the first gesture without a background poll.
1642
+ document.addEventListener('pointerdown', (event) => {
1643
+ if (moving) return
1644
+ const row = eventRow(event)
1645
+ if (!row || sessionForRow(row)) return
1646
+ maybeRefresh()
1647
+ }, true)
1648
+
1630
1649
  document.addEventListener('dragstart', (event) => {
1631
1650
  const row = eventRow(event)
1632
1651
  const item = row && sessionForRow(row)
@@ -1682,7 +1701,31 @@ function installSidebarWorkspaceDrag() {
1682
1701
  refresh()
1683
1702
  const observer = new MutationObserver(scheduleDecorate)
1684
1703
  observer.observe(document.body, { childList: true, subtree: true })
1685
- setInterval(refresh, 5000)
1704
+ // 原先这里每 5s 无脑全表刷新一次。该接口在 host 侧要遍历全部会话,
1705
+ // 大库(issue #1: 49 会话 / 14 万帧)上每次都是一次重活,页面挂着就一直占宿主 CPU,
1706
+ // 连累 session.history 之类 RPC 超时。拖拽元数据根本不需要 5s 精度:
1707
+ // - 背景标签页完全不刷新
1708
+ // - 前台每 60s 兜底一次
1709
+ // - 标签页重新可见、或真正开始拖拽而 Map 里没有该行时,按需刷新
1710
+ let lastRefreshAt = Date.now()
1711
+ const maybeRefresh = () => {
1712
+ if (typeof document !== 'undefined' && document.hidden) return
1713
+ lastRefreshAt = Date.now()
1714
+ return refresh()
1715
+ }
1716
+ const REFRESH_MS = 60000
1717
+ setInterval(() => {
1718
+ if (typeof document !== 'undefined' && document.hidden) return
1719
+ if (Date.now() - lastRefreshAt < REFRESH_MS) return
1720
+ maybeRefresh()
1721
+ }, REFRESH_MS)
1722
+ if (typeof document !== 'undefined' && document.addEventListener) {
1723
+ document.addEventListener('visibilitychange', () => {
1724
+ if (document.hidden) return
1725
+ if (Date.now() - lastRefreshAt < 30000) return
1726
+ maybeRefresh()
1727
+ })
1728
+ }
1686
1729
  }
1687
1730
 
1688
1731
  export function apply(ctx) {
package/src/index.js CHANGED
@@ -16,6 +16,7 @@ import { renderSessionMarkdown } from './markdown.js'
16
16
  import { createStarIndex } from './star-index.js'
17
17
  import { aggregateStorage } from './storage-stats.js'
18
18
  import { createAutoArchiveStore, pickInactiveCandidates } from './auto-archive.js'
19
+ import { createSessionMetaCache } from './session-meta-cache.js'
19
20
 
20
21
 
21
22
  export const name = 'dsh-sessions-manager'
@@ -123,7 +124,29 @@ export function apply(ctx) {
123
124
  const sq = ctx.sessionQuery
124
125
  const dom = () => ctx.storageDomain.get('workspace')
125
126
  const authorityTitleCache = new Map()
126
- let authorityTitlesLoaded = false
127
+ // 会话原始元数据缓存(title / cwd / createdAt),按日志文件 (mtime, size) 指纹校验。
128
+ // 见 src/session-meta-cache.js 的说明:列表构建原本每条会话都要整本解压日志,
129
+ // 这个缓存让「日志没变」的会话直接跳过解码。
130
+ const metaCache = createSessionMetaCache()
131
+
132
+ // 从投影快照里抽出元数据;快照缺失/异常时返回零值 meta(调用方决定兜底)。
133
+ function metaFromSnapshot(o) {
134
+ let title = null, createdAt = null, cwd = null
135
+ if (o) {
136
+ if (o.title && o.title.title) title = String(o.title.title)
137
+ if (o.session) { cwd = o.session.cwd || null; createdAt = o.session.createdAt || null }
138
+ }
139
+ return { title, cwd, createdAt }
140
+ }
141
+
142
+ // 投影快照的两种返回形态都兼容:新版 runtime 返回 settled 结果
143
+ // ({ status: 'fulfilled', value }),老版本直接返回快照本身。
144
+ function unwrapSnapshot(result) {
145
+ if (!result) return null
146
+ if (result.status === 'fulfilled') return result.value || null
147
+ if (result.status === 'rejected') return null
148
+ return result
149
+ }
127
150
 
128
151
  async function archivedState() {
129
152
  const d = dom()
@@ -157,46 +180,68 @@ export function apply(ctx) {
157
180
 
158
181
  let wsByPath = {}
159
182
 
160
- async function resolveOne(id, usage) {
161
- let title = null, createdAt = null, cwd = null
162
- try {
163
- const o = await sq.readTitleSnapshot(id)
164
- if (o) {
165
- if (o.title && o.title.title) title = String(o.title.title)
166
- if (o.session) { cwd = o.session.cwd || null; createdAt = o.session.createdAt || null }
167
- }
168
- } catch (e) { /* fall back to raw log */ }
169
- if (!title || !cwd) {
170
- try {
171
- const r = await sp.readFrom(id, 0)
172
- if (r.meta) {
173
- if (!cwd) cwd = r.meta.cwd || null
174
- if (!createdAt) createdAt = r.meta.createdAt || null
175
- }
176
- if (!title && Array.isArray(r.events)) title = foldTitle(r.events)
177
- } catch (e2) { /* keep what we have */ }
178
- }
183
+ // 把原始元数据渲染成列表项。缓存命中与解码两条路径共用,保证输出一致。
184
+ function buildItem(key, meta, usage, exposeUsage) {
185
+ const cwd = meta.cwd || null
179
186
  const ws = cwd ? wsByPath[cwd] : undefined
180
- const workspaceGone = !!(cwd && !ws)
187
+ const title = meta.title || null
181
188
  const display = title ? (String(title).length > MAX_TITLE ? String(title).slice(0, MAX_TITLE) + '…' : String(title)) : null
182
189
  const base = {
183
- sessionId: id,
190
+ sessionId: key,
184
191
  title: display,
185
- createdAt: createdAt || null,
186
- workspacePath: cwd || null,
192
+ createdAt: meta.createdAt || null,
193
+ workspacePath: cwd,
187
194
  workspaceTitle: (ws && ws.title) ? ws.title : null,
188
- workspaceGone: workspaceGone ? true : false,
195
+ workspaceGone: !!(cwd && !ws),
189
196
  hasWorkspace: !!cwd,
190
197
  }
191
- // sizeBytes / updatedAt are opt-in: they cost one stat() per session, so
192
- // the high-frequency list routes stay exactly as cheap as before.
193
- if (usage) {
194
- if (usage.sizeById && usage.sizeById.has(id)) base.sizeBytes = usage.sizeById.get(id)
195
- if (usage.mtimeById && usage.mtimeById.has(id)) base.updatedAt = usage.mtimeById.get(id)
198
+ // sizeBytes / updatedAt 只在需要的路由(存储分析 / 自动归档)里带上:
199
+ // 它们本就来自 usage,附带输出对列表渲染无益。
200
+ if (exposeUsage && usage) {
201
+ if (usage.sizeById && usage.sizeById.has(key)) base.sizeBytes = usage.sizeById.get(key)
202
+ if (usage.mtimeById && usage.mtimeById.has(key)) base.updatedAt = usage.mtimeById.get(key)
196
203
  }
197
204
  return base
198
205
  }
199
206
 
207
+ // Resolve one session's display metadata.
208
+ //
209
+ // 成本模型(issue #1):下面的解码路径会把整本 .jsonl.zstd 逐帧解压、逐行
210
+ // JSON.parse,只为折叠出标题——大库上一次全表要几秒阻塞式 CPU。日志的
211
+ // (mtime, size) 没变就意味着内容没变,折叠结果也不可能变,所以命中缓存时
212
+ // 直接复用上次的元数据,跳过整本解码。
213
+ //
214
+ // opts.preloaded:批量投影(sq.readTitleSnapshots)已经拿到的快照;传了就不再
215
+ // 对同一条日志做第二次单例投影——issue 里「一条日志在单次列表里被解码两次」
216
+ // 正是这么来的。
217
+ async function resolveOne(id, usage, opts = {}) {
218
+ const key = String(id)
219
+ const statInfo = usage ? { mtimeMs: usage.mtimeById.get(key), size: usage.sizeById.get(key) } : null
220
+ const cached = metaCache.get(key, statInfo)
221
+ if (cached) return buildItem(key, cached, usage, opts.exposeUsage)
222
+
223
+ let meta = { title: null, cwd: null, createdAt: null }
224
+ if (opts.preloaded !== undefined) {
225
+ meta = metaFromSnapshot(unwrapSnapshot(opts.preloaded))
226
+ } else if (typeof sq.readTitleSnapshot === 'function') {
227
+ try { meta = metaFromSnapshot(await sq.readTitleSnapshot(id)) } catch (e) { /* fall back to raw log */ }
228
+ }
229
+ // 兜底:投影没给出标题或 cwd 时,才回退到整本解码(这条路径本身就贵,
230
+ // 且结果同样会进缓存,下一次列表就不会再走一遍)。
231
+ if (!meta.title || !meta.cwd) {
232
+ try {
233
+ const r = await sp.readFrom(id, 0)
234
+ if (r.meta) {
235
+ if (!meta.cwd) meta.cwd = r.meta.cwd || null
236
+ if (!meta.createdAt) meta.createdAt = r.meta.createdAt || null
237
+ }
238
+ if (!meta.title && Array.isArray(r.events)) meta.title = foldTitle(r.events)
239
+ } catch (e2) { /* keep what we have */ }
240
+ }
241
+ metaCache.set(key, statInfo, meta)
242
+ return buildItem(key, meta, usage, opts.exposeUsage)
243
+ }
244
+
200
245
  // Disk usage + last-write time for every session, in one pass.
201
246
  //
202
247
  // sp.locate(header) resolves the log file behind a session header; a single
@@ -205,11 +250,13 @@ export function apply(ctx) {
205
250
  // file's last write tracks the conversation's last turn. It errs safe: a log
206
251
  // we relocated (move) gets a fresh mtime and therefore looks *more* active
207
252
  // than it is, which can only delay an auto-archive, never cause a wrong one.
208
- async function collectUsage() {
253
+ // headers 可由调用方传入复用(列表构建里已经 sp.list() 过一次,避免重复列目录)。
254
+ async function collectUsage(preloadedHeaders) {
209
255
  const sizeById = new Map()
210
256
  const mtimeById = new Map()
211
- let headers = []
212
- try { headers = await sp.list() } catch (e) { headers = [] }
257
+ let headers = null
258
+ if (Array.isArray(preloadedHeaders)) headers = preloadedHeaders
259
+ else { try { headers = await sp.list() } catch (e) { headers = [] } }
213
260
  if (!Array.isArray(headers)) headers = []
214
261
  const CHUNK = 8
215
262
  for (let i = 0; i < headers.length; i += CHUNK) {
@@ -705,20 +752,43 @@ export function apply(ctx) {
705
752
  })
706
753
  }
707
754
 
708
- // opts.usage: fill sizeBytes + updatedAt (one stat() per session). Off by
709
- // default so the panel's list route keeps its original cost.
755
+ // 批量投影:一次调用把多条会话的标题/header 拿出来,避免逐条触发整本解码。
756
+ // 老 runtime 没有 readTitleSnapshots 时返回空 Map,调用方自然回退到逐条投影
757
+ // (功能不受影响,只是少了这层优化——插件不能假设对方的 runtime 版本)。
758
+ async function projectTitles(ids) {
759
+ const out = new Map()
760
+ if (!ids || !ids.length) return out
761
+ if (typeof sq.readTitleSnapshots !== 'function') return out
762
+ try {
763
+ const results = await sq.readTitleSnapshots(ids)
764
+ if (!Array.isArray(results)) return out
765
+ results.forEach((result, index) => {
766
+ const id = String(ids[index])
767
+ out.set(id, unwrapSnapshot(result))
768
+ })
769
+ } catch (e) { /* 批量失败:逐条回退 */ }
770
+ return out
771
+ }
772
+
773
+ // opts.usage: expose sizeBytes + updatedAt on each item (storage analysis and
774
+ // the auto-archive sweep need them; the panel list does not).
775
+ //
776
+ // 性能要点(issue #1):
777
+ // 1. sp.list() 只调一次(原先列了两遍目录)
778
+ // 2. 无条件做一遍 stat——一次 stat 是微秒级,而它算出的 (mtime, size) 指纹
779
+ // 是元数据缓存能否跳过整本解码的前提,收益远大于成本
780
+ // 3. 未命中缓存的会话走**一次**批量投影(sq.readTitleSnapshots),而不是逐条
710
781
  async function allSessionItems(opts = {}) {
711
- let materialized = new Set()
712
- let live = ctx.get('sessions')
782
+ let headers = []
713
783
  let headersOk = false
714
784
  try {
715
- const headers = await sp.list()
716
- materialized = new Set(headers.map((h) => String(h.id)))
717
- headersOk = true
718
- } catch (e) { /* best-effort */ }
719
- const ids = []
720
- try { for (const header of await sp.list()) ids.push(String(header.id)) } catch (e) { /* ignore */ }
721
- if (live) { try { live.list().forEach((s) => { if (!ids.includes(String(s.id))) ids.push(String(s.id)) }) } catch (e) { /* ignore */ } }
785
+ headers = await sp.list()
786
+ headersOk = Array.isArray(headers)
787
+ if (!headersOk) headers = []
788
+ } catch (e) { headers = [] }
789
+ let live = ctx.get('sessions')
790
+ const ids = headers.map((h) => String(h.id))
791
+ if (live) { try { live.list().forEach((s) => { const sid = String(s.id); if (!ids.includes(sid)) ids.push(sid) }) } catch (e) { /* ignore */ } }
722
792
  // Exclude sessions already moved to the recycle bin (软删除): they live in
723
793
  // 回收站, not in 会话管理, so the panel won't re-list them after a delete.
724
794
  let hiddenIds = new Set()
@@ -731,12 +801,19 @@ export function apply(ctx) {
731
801
  try { for (const ent of w.list()) wsByPath[ent.path] = ent } catch (e) { wsByPath = {} }
732
802
  const currentArchived = new Set((await archivedState().catch(() => ({ archivedSessionIds: [] }))).archivedSessionIds || [])
733
803
  const items = []
734
- const usage = (opts && opts.usage) ? await collectUsage() : null
804
+ const usage = await collectUsage(headers)
805
+ // 先按指纹把「缓存命中」与「需要解码」分开,只对后者做批量投影。
806
+ const statsById = new Map(visibleIds.map((id) => [id, { mtimeMs: usage.mtimeById.get(id), size: usage.sizeById.get(id) }]))
807
+ const { cached, missing } = metaCache.partition(visibleIds, statsById)
808
+ const snapshotById = await projectTitles(missing)
735
809
  const CHUNK = 6
736
810
  for (let i = 0; i < visibleIds.length; i += CHUNK) {
737
811
  // Arrow wrapper on purpose: Array#map passes (value, index, array), and
738
- // resolveOne's second argument is the usage map.
739
- const res2 = await Promise.all(visibleIds.slice(i, i + CHUNK).map((id) => resolveOne(id, usage)))
812
+ // resolveOne's second and third arguments are fixed here.
813
+ const res2 = await Promise.all(visibleIds.slice(i, i + CHUNK).map((id) => resolveOne(id, usage, {
814
+ exposeUsage: !!(opts && opts.usage),
815
+ preloaded: snapshotById.has(id) ? snapshotById.get(id) : undefined,
816
+ })))
740
817
  for (const it of res2) items.push({ ...it, archived: currentArchived.has(it.sessionId) })
741
818
  }
742
819
  // Annotate stars; GC only when we have a trustworthy id baseline, so a
@@ -794,28 +871,37 @@ export function apply(ctx) {
794
871
  return { ok: true, archived, candidates: candidates.length, failed, lastRunAt: now }
795
872
  }
796
873
 
874
+ // 侧栏权威数据:标题 + 回收站 id 集合。
875
+ //
876
+ // 标题原先「首次调用算一次就永久缓存」,日志之后再变也不会更新——标题会陈旧。
877
+ // 现在复用 metaCache:每次调用只 stat 一遍,日志没变直接取缓存,变了才重解码,
878
+ // 既不会陈旧也不会回到「每次全量解码」。
797
879
  async function sidebarAuthority() {
798
880
  const ids = []
799
- try { for (const header of await sp.list()) ids.push(String(header.id)) } catch (e) {}
881
+ let headers = []
882
+ try { headers = await sp.list() } catch (e) { headers = [] }
883
+ if (!Array.isArray(headers)) headers = []
884
+ for (const header of headers) ids.push(String(header.id))
800
885
  const sessions = ctx.get('sessions')
801
- try { if (sessions) sessions.list().forEach((session) => { if (!ids.includes(String(session.id))) ids.push(String(session.id)) }) } catch (e) {}
886
+ try { if (sessions) sessions.list().forEach((session) => { const sid = String(session.id); if (!ids.includes(sid)) ids.push(sid) }) } catch (e) {}
802
887
  const store = await readTrashStore()
803
- if (!authorityTitlesLoaded && ids.length && typeof sq.readTitleSnapshots === 'function') {
804
- const results = await sq.readTitleSnapshots(ids)
805
- results.forEach((result, index) => {
806
- if (result && result.status === 'fulfilled' && result.value && result.value.title && typeof result.value.title.title === 'string') {
807
- authorityTitleCache.set(ids[index], result.value.title.title)
888
+ if (ids.length) {
889
+ const usage = await collectUsage(headers)
890
+ const statsById = new Map(ids.map((id) => [id, { mtimeMs: usage.mtimeById.get(id), size: usage.sizeById.get(id) }]))
891
+ const { cached, missing } = metaCache.partition(ids, statsById)
892
+ const snapshotById = await projectTitles(missing)
893
+ for (const id of ids) {
894
+ let meta = cached.get(id) || null
895
+ if (!meta) {
896
+ const snapshot = snapshotById.has(id)
897
+ ? snapshotById.get(id)
898
+ : (typeof sq.readTitleSnapshot === 'function' ? await sq.readTitleSnapshot(id).catch(() => null) : null)
899
+ const next = metaFromSnapshot(snapshot)
900
+ metaCache.set(id, statsById.get(id), next)
901
+ meta = next
808
902
  }
809
- })
810
- authorityTitlesLoaded = true
811
- } else if (!authorityTitlesLoaded) {
812
- for (const sid of ids) {
813
- try {
814
- const snapshot = await sq.readTitleSnapshot(sid)
815
- if (snapshot && snapshot.title && typeof snapshot.title.title === 'string') authorityTitleCache.set(sid, snapshot.title.title)
816
- } catch (e) {}
903
+ if (meta && meta.title) authorityTitleCache.set(id, String(meta.title))
817
904
  }
818
- authorityTitlesLoaded = true
819
905
  }
820
906
  return {
821
907
  titles: Object.fromEntries(authorityTitleCache),
@@ -1031,7 +1117,11 @@ export function apply(ctx) {
1031
1117
  const body = await readJsonBody(req)
1032
1118
  const sid = body && typeof body.sessionId === 'string' ? body.sessionId : null
1033
1119
  if (!sid) return json(res, { ok: false, error: 'missing sessionId' }, 400)
1034
- json(res, await deleteOne(sid))
1120
+ const out = await deleteOne(sid)
1121
+ // 日志被搬进回收站(文件已不在原处):丢弃缓存条目,避免下次 stat 失败
1122
+ // 时残留旧元数据。
1123
+ metaCache.invalidate(sid)
1124
+ json(res, out)
1035
1125
  } catch (e) {
1036
1126
  json(res, { ok: false, error: String((e && e.message) || e) }, errorStatus(e))
1037
1127
  }
@@ -1048,7 +1138,7 @@ export function apply(ctx) {
1048
1138
  if (!ids || ids.length === 0) return json(res, { ok: false, error: 'missing sessionIds' }, 400)
1049
1139
  const results = []
1050
1140
  for (const sid of ids) {
1051
- try { results.push({ sessionId: sid, ok: true, ...(await deleteOne(sid)) }) }
1141
+ try { results.push({ sessionId: sid, ok: true, ...(await deleteOne(sid)) }); metaCache.invalidate(sid) }
1052
1142
  catch (e) { results.push({ sessionId: sid, ok: false, error: String((e && e.message) || e) }) }
1053
1143
  }
1054
1144
  json(res, { ok: true, deleted: results.filter((r) => r.ok).length, results })
@@ -1117,7 +1207,9 @@ export function apply(ctx) {
1117
1207
  const body = await readJsonBody(req)
1118
1208
  const sid = body && typeof body.sessionId === 'string' ? body.sessionId : null
1119
1209
  if (!sid) return json(res, { ok: false, error: 'missing sessionId' }, 400)
1120
- json(res, await restoreFromTrash(sid))
1210
+ const out = await restoreFromTrash(sid)
1211
+ metaCache.invalidate(sid)
1212
+ json(res, out)
1121
1213
  } catch (e) {
1122
1214
  json(res, { ok: false, error: String((e && e.message) || e) }, 500)
1123
1215
  }
@@ -1132,7 +1224,9 @@ export function apply(ctx) {
1132
1224
  const body = await readJsonBody(req)
1133
1225
  const sid = body && typeof body.sessionId === 'string' ? body.sessionId : null
1134
1226
  if (!sid) return json(res, { ok: false, error: 'missing sessionId' }, 400)
1135
- json(res, await purgeFromTrash(sid))
1227
+ const out = await purgeFromTrash(sid)
1228
+ metaCache.invalidate(sid)
1229
+ json(res, out)
1136
1230
  } catch (e) {
1137
1231
  json(res, { ok: false, error: String((e && e.message) || e) }, 500)
1138
1232
  }
@@ -1149,7 +1243,7 @@ export function apply(ctx) {
1149
1243
  if (!ids || ids.length === 0) return json(res, { ok: false, error: 'missing sessionIds' }, 400)
1150
1244
  const results = []
1151
1245
  for (const sid of ids) {
1152
- try { results.push({ sessionId: sid, ok: true, ...(await purgeFromTrash(sid)) }) }
1246
+ try { results.push({ sessionId: sid, ok: true, ...(await purgeFromTrash(sid)) }); metaCache.invalidate(sid) }
1153
1247
  catch (e) { results.push({ sessionId: sid, ok: false, error: String((e && e.message) || e) }) }
1154
1248
  }
1155
1249
  json(res, { ok: true, purged: results.filter((r) => r.ok).length, results })
@@ -1260,6 +1354,9 @@ export function apply(ctx) {
1260
1354
  if (!sid) return json(res, { ok: false, error: 'missing sessionId' }, 400)
1261
1355
  if (!target) return json(res, { ok: false, error: 'missing targetPath' }, 400)
1262
1356
  const moved = await moveOne(sid, target)
1357
+ // 移动会改写日志 frame0 的 cwd:元数据(cwd)已变,主动丢弃缓存条目,
1358
+ // 不等 mtime 指纹自然失效(Windows 上 mtime 精度较粗,指纹可能不变)。
1359
+ metaCache.invalidate(sid)
1263
1360
  // Reindex the host's in-memory sessionPath index so the sidebar
1264
1361
  // reflects the new grouping immediately (no DSH restart needed).
1265
1362
  // Do this before replying: drag/drop and menu clients treat a 2xx
@@ -0,0 +1,117 @@
1
+ // session-meta-cache.js — 会话「原始元数据」内存缓存(按日志文件指纹校验)。
2
+ //
3
+ // 背景(issue #1):列表构建原本对每条会话调用 readTitleSnapshot,而该调用会把
4
+ // 会话日志(.jsonl.zstd)的**所有 zstd 帧**逐帧解压、逐行 JSON.parse,只为折叠出
5
+ // 最新标题。大库(数十条会话、十万级帧)一次全表要几秒 CPU,且解码是同步块,
6
+ // 会阻塞宿主事件循环,连累 session.history 之类的 RPC 超时。
7
+ //
8
+ // 关键观察:解码得出的元数据(title / cwd / createdAt)只随**日志文件内容**变化,
9
+ // 而任何append/改名/移动都会更新日志文件的 mtime。所以只要记下当时的
10
+ // (mtimeMs, size),下次 stat 到相同指纹就可以直接复用缓存,跳过整本解码。
11
+ //
12
+ // 为什么自己实现而不用 runtime 的 prepared 缓存:插件不能假设对方的 runtime 版本
13
+ // (issue 报告者是 0.1.1-rc.2,本机是 0.1.2-rc.1),runtime 侧的缓存容量/命中策略
14
+ // 各版本不同。本模块只用 node 原生能力与插件已有的 sp.locate + stat,任何版本行为一致。
15
+ //
16
+ // 失效策略(三重保险):
17
+ // 1. 指纹校验:mtimeMs 或 size 任一变化即视为过期(append 改 mtime、移动改写 frame0 也改 mtime)
18
+ // 2. TTL:防止「mtime 精度/时钟回拨」导致的长期陈旧
19
+ // 3. 显式 invalidate:删除 / 移动 / 归档等宿主操作后主动丢弃对应条目
20
+ //
21
+ // 纯逻辑与副作用分离:isFresh / partitionByCache 都是纯函数,便于单测。
22
+
23
+ const DEFAULT_TTL_MS = 5 * 60 * 1000
24
+ const DEFAULT_MAX = 4000
25
+
26
+ // 文件指纹:只有同时拿到 mtime 与 size 才可信(两者都变才算内容变了)。
27
+ // 拿不到 stat 信息时返回 null——表示「无法校验」,调用方必须按未命中处理,
28
+ // 绝不能在有疑问时返回旧数据。
29
+ export function fingerprintOf(stat) {
30
+ if (!stat || typeof stat !== 'object') return null
31
+ const mtimeMs = stat.mtimeMs
32
+ const size = stat.size
33
+ if (typeof mtimeMs !== 'number' || !Number.isFinite(mtimeMs) || mtimeMs <= 0) return null
34
+ if (typeof size !== 'number' || !Number.isFinite(size) || size < 0) return null
35
+ return `${Math.floor(mtimeMs)}:${size}`
36
+ }
37
+
38
+ // 缓存条目是否仍然新鲜(纯函数)。
39
+ export function isFresh(entry, stat, now, ttlMs = DEFAULT_TTL_MS) {
40
+ if (!entry) return false
41
+ const fp = fingerprintOf(stat)
42
+ if (!fp) return false
43
+ if (entry.fingerprint !== fp) return false
44
+ if (typeof entry.at !== 'number') return false
45
+ return (now - entry.at) <= ttlMs
46
+ }
47
+
48
+ // 把一批 id 分成「命中缓存」与「需要解码」两组(纯函数,便于单测)。
49
+ // statsById: Map<id, {mtimeMs, size}>;cache: 与 SessionMetaCache 同构的 Map。
50
+ export function partitionByCache(ids, statsById, cache, now = Date.now(), ttlMs = DEFAULT_TTL_MS) {
51
+ const cached = new Map()
52
+ const missing = []
53
+ for (const id of ids) {
54
+ const entry = cache && cache.get(String(id))
55
+ const stat = statsById && statsById.get(String(id))
56
+ if (isFresh(entry, stat, now, ttlMs) && entry && entry.meta) {
57
+ cached.set(String(id), entry.meta)
58
+ } else {
59
+ missing.push(String(id))
60
+ }
61
+ }
62
+ return { cached, missing }
63
+ }
64
+
65
+ export function createSessionMetaCache(opts = {}) {
66
+ const ttlMs = Number.isFinite(opts.ttlMs) ? opts.ttlMs : DEFAULT_TTL_MS
67
+ const max = Number.isInteger(opts.max) && opts.max > 0 ? opts.max : DEFAULT_MAX
68
+ const map = new Map()
69
+ let hits = 0
70
+ let misses = 0
71
+
72
+ return {
73
+ // 命中返回 meta,未命中/无法校验返回 null。
74
+ get(id, stat) {
75
+ const key = String(id)
76
+ const entry = map.get(key)
77
+ if (isFresh(entry, stat, Date.now(), ttlMs)) {
78
+ hits++
79
+ // LRU:命中后移到末尾,容量满时优先淘汰最久未用。
80
+ map.delete(key)
81
+ map.set(key, entry)
82
+ return entry.meta
83
+ }
84
+ misses++
85
+ return null
86
+ },
87
+ set(id, stat, meta) {
88
+ if (!meta) return null
89
+ const fp = fingerprintOf(stat)
90
+ // 无法算出指纹(没 stat / stat 失败)时不写缓存:写进去就再也无法可靠失效。
91
+ if (!fp) return null
92
+ const key = String(id)
93
+ map.delete(key)
94
+ map.set(key, { fingerprint: fp, at: Date.now(), meta })
95
+ if (map.size > max) {
96
+ // 淘汰最久未用的一个(Map 保持插入顺序,首个即最旧)。
97
+ const oldest = map.keys().next().value
98
+ if (oldest !== undefined) map.delete(oldest)
99
+ }
100
+ return meta
101
+ },
102
+ // 批量判定:一次算出「命中缓存」与「需要解码」两组,供列表构建做批量投影。
103
+ partition(ids, statsById) {
104
+ return partitionByCache(ids, statsById, map, Date.now(), ttlMs)
105
+ },
106
+ invalidate(id) {
107
+ if (id == null) return false
108
+ const key = String(id)
109
+ const had = map.has(key)
110
+ map.delete(key)
111
+ return had
112
+ },
113
+ clear() { map.clear() },
114
+ get size() { return map.size },
115
+ stats() { return { size: map.size, hits, misses, ttlMs } },
116
+ }
117
+ }