dsh-gallery 1.5.0 → 1.6.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/host/scan.js CHANGED
@@ -9,12 +9,12 @@ import path from 'node:path'
9
9
  import { ASSET_CATEGORY, classifyAsset } from './classify.js'
10
10
  import { BASH_TOOLS, DEFAULT_SESSIONS_DIR, DSH_HOME, OUTPUT_TOOLS, VIDEO_EXTS, VIEW_IMAGE_EXTS, VIEW_TOOLS } from './constants.js'
11
11
  import { isInside, measureImage, readHead } from './fsutil.js'
12
- import { buildGroups } from './groups.js'
12
+ import { buildGroups, buildRootSessionResolver } from './groups.js'
13
13
  import { collectAbsolutePaths, findSubSessionLogs, locateSessionDir, readSessionLogText } from './session.js'
14
- import { readHiddenList, resolveOptions } from './settings.js'
14
+ import { readHiddenList, readHiddenSessions, resolveOptions } from './settings.js'
15
15
  import { readLabels, LABEL_CATEGORIES } from './labels.js'
16
16
  import { readFrames } from './frames.js'
17
- import { buildSessionIndex, readSessionStates } from './session-index.js'
17
+ import { buildSessionIndex, readSessionStates, sessionIndexCacheFileFor } from './session-index.js'
18
18
 
19
19
  /**
20
20
  * v0.14.7:相对路径的父目录(统一小写;空串表示文件直接躺在 root 下)。
@@ -25,6 +25,12 @@ export function parentDirOf(relPath) {
25
25
  return p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : ''
26
26
  }
27
27
 
28
+ /**
29
+ * 分类的「确定性」排序。同一对话多次引用同一张图(父会话 + 子智能体会话)时,
30
+ * 取更确定的那个 —— 不能因为子会话只看了一眼就把定稿降级成素材。
31
+ */
32
+ const CATEGORY_RANK = { final: 3, intermediate: 2, input: 1, unknown: 0 }
33
+
28
34
  /** v0.14.7:当前对话分类。日志/登记里没有的、同目录外部图片自动标「素材」(input)。 */
29
35
  /**
30
36
  * 2026-11-15:同目录放宽的「新鲜度」门槛。
@@ -697,28 +703,122 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
697
703
  sessionIndex = await buildSessionIndex(sessionsDir, opts, {
698
704
  readSessionLogText,
699
705
  extractAssetInfo,
706
+ // v1.6.5:重启后复用上次的日志解析结果,避免每次开面板都全量解压 zstd。
707
+ cacheFile: sessionIndexCacheFileFor(opts.settingsFile),
700
708
  })
701
709
  }
702
710
 
703
- // 文件绝对路径 → { sessionId, title, category }
711
+ // 文件绝对路径 → [{ sessionId, title, createdAt, category }](**多值**)
712
+ //
713
+ // 2026-11-25:子智能体会话(parentSession 指向父会话)的产出并进**根父会话**。
714
+ // 「当前对话」视图本来就把子会话资产合并(见 resolveSessionScope 的「修法 C」),
715
+ // 但全局按对话分组时子会话是按 owner 单独成组的 —— 两套尺子不一致,实测就是
716
+ // 「全局里这个对话只有 5 张,点进对话却有 35 张」,看着像资产丢了。
717
+ //
718
+ // 同日再改:改成**多值**。原先「一个文件只归一个对话,谁最近引用算谁的」,
719
+ // 结果只要另一个对话贴过这张图,原对话的组里就少一张(老板实测:打开有 21 张、
720
+ // 全局只剩 5 张)。现在凡是在日志里引用过它的对话都记下来,分组时各入各的组,
721
+ // 两个视图才对得上账。实测全库 3527 个被引用的文件里 1523 个被多个对话引用。
722
+ const rootSessionOf = buildRootSessionResolver(sessionIndex)
704
723
  const ownerByAbs = new Map()
705
724
  if (sessionIndex !== null) {
706
725
  for (const [sid, entry] of sessionIndex) {
726
+ const rootId = rootSessionOf(sid)
727
+ const rootEntry = rootId === sid ? entry : sessionIndex.get(rootId)
728
+ const groupTitle = String(rootEntry?.title ?? entry.title ?? '')
729
+ const groupCreatedAt = Number(rootEntry?.createdAt) || Number(entry.createdAt) || 0
707
730
  for (const [abs, cat] of entry.files) {
708
- // 同一个文件被多个对话产出时,取最近的那个对话
709
- const prev = ownerByAbs.get(abs)
710
- if (prev === undefined || entry.createdAt > prev.createdAt) {
711
- ownerByAbs.set(abs, {
712
- sessionId: sid,
713
- title: entry.title || '',
714
- createdAt: entry.createdAt,
731
+ let list = ownerByAbs.get(abs)
732
+ if (list === undefined) {
733
+ list = []
734
+ ownerByAbs.set(abs, list)
735
+ }
736
+ const exist = list.find((x) => x.sessionId === rootId)
737
+ if (exist === undefined) {
738
+ list.push({
739
+ sessionId: rootId,
740
+ title: groupTitle,
741
+ createdAt: groupCreatedAt,
715
742
  category: cat,
743
+ // 原始产出会话:子会话时与 sessionId 不同,供诊断用
744
+ ...(rootId === sid ? {} : { ownerSessionId: sid }),
716
745
  })
746
+ } else if (CATEGORY_RANK[cat] > CATEGORY_RANK[exist.category]) {
747
+ // 同一对话多次引用(父 + 子会话)时取更确定的那一档:final > intermediate > input
748
+ exist.category = cat
717
749
  }
718
750
  }
719
751
  }
720
752
  }
721
753
 
754
+ // 2026-11-25:全局分组的「产出者」索引 —— 靠「用过的目录 + 时间窗口」判定谁产出的。
755
+ //
756
+ // 起因(老板两次报):全局里「DSH辅助漫剧制作流程」只剩 2 张,切进该对话却有 13 张。
757
+ // 那 11 张在 11-24 13:25 产出,却被 11-24 20:21 才开张的同名对话 (1)「引用」走了 ——
758
+ // 文件比它开张还早一个多小时。原规则「谁最近引用算谁的」把**看过**当成了**产出**。
759
+ //
760
+ // 三条约束,缺一不可:
761
+ // ① 目录必须是有子目录的层(根直属层在 session-index 里已排除,太宽);
762
+ // ② 文件必须晚于该会话开始(isFreshSince 同一把关),老图不会被新对话吸走;
763
+ // ③ 同目录被多个会话用过时取「开始得最晚」的那个。
764
+ // 优先级见下面 item 归属链:当前对话 > 截帧登记 > 本索引 > 日志精确引用。
765
+ const dirOwnerIndex = new Map()
766
+ if (sessionIndex !== null) {
767
+ for (const [sid, entry] of sessionIndex) {
768
+ const dirs = entry.dirs
769
+ if (!(dirs instanceof Set) || dirs.size === 0) continue
770
+ const rootId = rootSessionOf(sid)
771
+ const rootEntry = rootId === sid ? entry : sessionIndex.get(rootId)
772
+ const startMs = Number(entry.startMs) || Number(entry.createdAt) || 0
773
+ if (startMs <= 0) continue
774
+ const cand = {
775
+ sessionId: rootId,
776
+ title: String(rootEntry?.title ?? entry.title ?? ''),
777
+ createdAt: Number(rootEntry?.createdAt) || Number(entry.createdAt) || 0,
778
+ startMs,
779
+ }
780
+ for (const dir of dirs) {
781
+ const item = dir === '' ? { ...cand, rootLevel: true } : cand
782
+ const list = dirOwnerIndex.get(dir)
783
+ if (list === undefined) dirOwnerIndex.set(dir, [item])
784
+ else list.push(item)
785
+ }
786
+ }
787
+ }
788
+ /**
789
+ * 目录 + 时间判定:返回**所有**命中的候选会话(开始时间从新到旧)。
790
+ *
791
+ * 为什么返回数组而不是只挑一个:老板对账的标准是「打开这个对话看到几张,
792
+ * 全局这个组就该有几张」。实测 a912 与 94d7 两个对话的活跃期重叠,
793
+ * 同一批图两边都说得通 —— 单选必然让一边少几张,看着就像资产丢了。
794
+ * 允许「一张图同时属于用它产出过的每个对话」,两个视图就永远对得上账。
795
+ * 实测代价:全库 6944 条里仅 266 条(3.8%)会进多个组,可接受。
796
+ */
797
+ const matchDirOwners = (item) => {
798
+ if (dirOwnerIndex.size === 0) return []
799
+ const list = dirOwnerIndex.get(parentDirOf(item.relPath))
800
+ if (list === undefined) return []
801
+ // 🔴 只认 mtime(最后写出时间),**不看 birthtime**。
802
+ // 实测踩过:图卡 mtime 是产出时间,但 birthtime 因跨盘复制变成了更晚的时刻,
803
+ // 于是被判定「更晚开张的对话也算新鲜」,归属被抢走。
804
+ const mtime = Number(item.mtime) || 0
805
+ if (mtime <= 0) return []
806
+ const hits = []
807
+ const seen = new Set()
808
+ for (const cand of list) {
809
+ if (mtime < cand.startMs) continue
810
+ if (seen.has(cand.sessionId)) continue
811
+ seen.add(cand.sessionId)
812
+ hits.push(cand)
813
+ }
814
+ hits.sort((a, b) => {
815
+ // 根直属层的最低优先:有具体子目录的判定永远排在前面
816
+ if ((a.rootLevel === true) !== (b.rootLevel === true)) return a.rootLevel === true ? 1 : -1
817
+ return b.startMs - a.startMs
818
+ })
819
+ return hits
820
+ }
821
+
722
822
  // 2026-11-15:全局资产下置顶的「当前对话」组,必须和「当前对话」视图用同一把尺子。
723
823
  // 旧做法把归属交给全库会话索引、谁最近算谁的:本对话明明能看见的图,
724
824
  // 会被更早引用过它的老对话抢走(老板实测:全局 2 张、当前对话视图 4 张)。
@@ -799,6 +899,16 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
799
899
  }
800
900
  }
801
901
 
902
+ // 2026-11-25:当前对话本身若是子智能体会话,「当前对话组」也按根父会话算 ——
903
+ // 否则同一个子会话的文件会在两个组里分家(目录兜底进父组、精确命中的自成一组)。
904
+ const currentRootSid = sessionId === '' ? sessionId : rootSessionOf(sessionId)
905
+ const currentRootMeta = currentRootSid === sessionId
906
+ ? globalCurrentMeta
907
+ : {
908
+ title: String(sessionIndex?.get(currentRootSid)?.title ?? globalCurrentMeta?.title ?? ''),
909
+ createdAt: Number(sessionIndex?.get(currentRootSid)?.createdAt) || globalCurrentMeta?.createdAt || 0,
910
+ }
911
+
802
912
  // 已隐藏的路径:扫描时直接跳过(不移动文件,只从列表里拿掉)
803
913
  const hiddenSet = new Set(await readHiddenList(opts.settingsFile))
804
914
 
@@ -1021,16 +1131,71 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1021
1131
  // 登记不在会话日志里:ownerByAbs 查不到时,用登记里的会话信息补一个虚拟归属。
1022
1132
  // 日志里已有归属的文件(例如视频本身)一律沿用原归属,不受影响。
1023
1133
  const frameSid = String(frame?.sessionId ?? '')
1134
+ // 子会话截的帧同样并进根父会话(与 ownerByAbs 归一同一口径)
1135
+ const frameRootSid = frameSid === '' ? '' : rootSessionOf(frameSid)
1024
1136
  const virtualOwner = frame !== undefined && frameSid !== ''
1025
1137
  ? {
1026
- sessionId: frameSid,
1027
- title: String(frame.sessionTitle ?? '') || sessionIndex?.get(frameSid)?.title || '',
1028
- createdAt: Number(frame.sessionCreatedAt) || sessionIndex?.get(frameSid)?.createdAt || 0,
1138
+ sessionId: frameRootSid,
1139
+ title: String(frame.sessionTitle ?? '') || sessionIndex?.get(frameRootSid)?.title || '',
1140
+ createdAt: Number(frame.sessionCreatedAt) || sessionIndex?.get(frameRootSid)?.createdAt || 0,
1029
1141
  // 截帧 = 过程稿;粘贴 / 裁剪 = 素材(登记里带着 category,缺省回落过程稿)
1030
1142
  category: frameCategoryOf(frame),
1031
1143
  }
1032
1144
  : undefined
1033
- const owner = ownerByAbs.get(abs) ?? virtualOwner
1145
+ const indexedList = ownerByAbs.get(abs) ?? []
1146
+ // 主归属:日志里「最近引用」它的那个对话(沿用原排序,保证历史行为不变)
1147
+ const indexedOwner = indexedList.length === 0
1148
+ ? undefined
1149
+ : indexedList.reduce((a, b) => (b.createdAt > a.createdAt ? b : a))
1150
+ // 2026-11-25:**产出者判定优先于「谁最近引用算谁的」**。
1151
+ //
1152
+ // 实测反例(老板 11-25 报):a912「DSH辅助漫剧制作流程」(11-23 19:24)产出的
1153
+ // 11 张图卡,被 11-24 20:21 才开张的同名对话 94d7「引用」走了 —— 于是 a912 在
1154
+ // 全局只剩 2 张,而切进该对话能看见 13 张。两个视图用了两套尺子。
1155
+ //
1156
+ // 优先级:当前对话 > 截帧登记 > 目录 + 时间(产出者)> 日志精确引用。
1157
+ // 但**归属不止一个**:凡是认得这张图的对话,分组时各入各的组(见下面 refs)。
1158
+ const dirOwners = virtualOwner === undefined
1159
+ ? matchDirOwners({
1160
+ relPath: item.relPath,
1161
+ mtime: item.mtime,
1162
+ })
1163
+ : []
1164
+ const dirOwner = dirOwners.length > 0 ? dirOwners[0] : null
1165
+ /**
1166
+ * 这张图「属于」的对话清单(多值)。
1167
+ *
1168
+ * 老板的对账标准很朴素:**打开这个对话看到几张,全局这个组就该有几张**。
1169
+ * 原先一个文件只归一个对话,只要别的对话贴过同一张图,原对话的组就少一张
1170
+ * (实测「产线测试快速反馈」打开 21 张、全局只剩 5 张)。现在改成多归属。
1171
+ */
1172
+ const refs = []
1173
+ const refSids = new Set()
1174
+ const pushRef = (sessionId, title, createdAt, category) => {
1175
+ const sid = String(sessionId ?? '')
1176
+ if (sid === '' || refSids.has(sid)) return
1177
+ refSids.add(sid)
1178
+ refs.push({
1179
+ sessionId: sid,
1180
+ title: title ?? '',
1181
+ createdAt: Number(createdAt) || 0,
1182
+ category,
1183
+ })
1184
+ }
1185
+ // ① 日志里精确引用过它的对话 —— 最硬的证据,排最前
1186
+ for (const own of indexedList) pushRef(own.sessionId, own.title, own.createdAt, own.category)
1187
+ // ② 目录 + 时间窗:判定为产出者(分类用该对话自己的判定,没有则素材)。
1188
+ // 根直属层同样参与 —— 早年试过「有更具体归属就跳过根层」,结果 Chief 系列
1189
+ // 对话的组里各少 12 张素材(打开对话有、全局没有),对账失败。
1190
+ for (const cand of dirOwners) {
1191
+ const own = sessionIndex?.get(cand.sessionId)?.files?.get(abs)
1192
+ pushRef(cand.sessionId, cand.title, cand.createdAt,
1193
+ typeof own === 'string' ? own : ASSET_CATEGORY.INPUT)
1194
+ }
1195
+ // ③ 截帧 / 粘贴登记
1196
+ if (virtualOwner !== undefined) {
1197
+ pushRef(virtualOwner.sessionId, virtualOwner.title, virtualOwner.createdAt, virtualOwner.category)
1198
+ }
1034
1199
  item.absPath = abs
1035
1200
  if (isSession) {
1036
1201
  const autoCategory = scopeInfo.categoryByRel?.get(item.relPath.toLowerCase())
@@ -1051,9 +1216,9 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1051
1216
  const exact = globalCurrentExactRels.has(relKey)
1052
1217
  item.category = categoryForSessionAsset(globalCurrentCategory?.get(relKey), !exact)
1053
1218
  if (!exact) item.externalAsset = true
1054
- item.sessionId = sessionId
1055
- item.sessionTitle = globalCurrentMeta?.title ?? ''
1056
- item.sessionCreatedAt = globalCurrentMeta?.createdAt ?? 0
1219
+ item.sessionId = currentRootSid
1220
+ item.sessionTitle = currentRootMeta?.title ?? ''
1221
+ item.sessionCreatedAt = currentRootMeta?.createdAt ?? 0
1057
1222
  // 2026-11-24:全局「当前对话」组里的共享文件同样加共享标记
1058
1223
  if (globalCurrentSharedAbsSet !== null && globalCurrentSharedAbsSet.has(abs.toLowerCase())) {
1059
1224
  item.shared = true
@@ -1062,11 +1227,31 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1062
1227
  if (globalCurrentInheritedAbsSet !== null && globalCurrentInheritedAbsSet.has(abs.toLowerCase())) {
1063
1228
  item.inherited = true
1064
1229
  }
1065
- } else if (owner !== undefined) {
1066
- item.category = owner.category
1067
- item.sessionId = owner.sessionId
1068
- item.sessionTitle = owner.title
1069
- item.sessionCreatedAt = owner.createdAt
1230
+ } else if (virtualOwner !== undefined) {
1231
+ // 截帧 / 粘贴登记:本会话当场产出的硬证据,优先级最高
1232
+ item.category = virtualOwner.category
1233
+ item.sessionId = virtualOwner.sessionId
1234
+ item.sessionTitle = virtualOwner.title
1235
+ item.sessionCreatedAt = virtualOwner.createdAt
1236
+ } else if (dirOwner !== null) {
1237
+ // 2026-11-25:目录 + 时间窗口命中 —— 文件落在本会话用过的目录里,且晚于会话开始。
1238
+ // 分类:若该文件也被这个会话在日志里精确引用过,沿用日志分类(与「当前对话」
1239
+ // 视图同源判据),否则按外部素材标 input。
1240
+ const sameOwner = indexedList.find((x) => x.sessionId === dirOwner.sessionId)
1241
+ item.category = categoryForSessionAsset(sameOwner?.category, sameOwner === undefined)
1242
+ if (sameOwner === undefined) item.externalAsset = true
1243
+ item.sessionId = dirOwner.sessionId
1244
+ item.sessionTitle = dirOwner.title
1245
+ item.sessionCreatedAt = dirOwner.createdAt
1246
+ // 供诊断:这条是靠目录 + 时间判定的产出,不是日志精确记录
1247
+ item.dirOwner = true
1248
+ } else if (indexedOwner !== undefined) {
1249
+ item.category = indexedOwner.category
1250
+ item.sessionId = indexedOwner.sessionId
1251
+ item.sessionTitle = indexedOwner.title
1252
+ item.sessionCreatedAt = indexedOwner.createdAt
1253
+ // 子智能体产出:分组并进父会话,但保留原始产出会话,诊断时能分清是谁做的
1254
+ if (indexedOwner.ownerSessionId !== undefined) item.ownerSessionId = indexedOwner.ownerSessionId
1070
1255
  } else {
1071
1256
  // 不属于任何已知对话、也不在当前对话目录里的文件:归到「历史资产」,
1072
1257
  // 分类记为**未归类**。不能兜底成 input —— 那会把几千个历史文件全标成「输入」
@@ -1074,11 +1259,26 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1074
1259
  item.sessionId = null
1075
1260
  }
1076
1261
 
1262
+ // 2026-11-25:多归属表 —— 只有真的被多个对话认得才建(绝大多数条目只有一项)。
1263
+ // 主归属那条用「本分支判出来的分类」覆盖,保证置顶的当前对话组与视图完全一致。
1264
+ if (refs.length > 1) {
1265
+ const self = item.sessionId === null || item.sessionId === undefined
1266
+ ? undefined
1267
+ : refs.find((r) => r.sessionId === item.sessionId)
1268
+ if (self !== undefined) self.category = item.category
1269
+ item.sessionRefs = refs
1270
+ }
1271
+
1077
1272
  // 手动改过的标签覆盖机器预判,且刷新 / 重扫 / 重启都不会回退。
1078
1273
  const manual = manualLabels[item.relPath]
1079
1274
  if (manual !== undefined && LABEL_CATEGORIES.includes(manual?.category)) {
1080
1275
  item.category = manual.category
1081
1276
  item.categoryManual = true
1277
+ // 2026-11-25:多归属的副本同样要跟着手动标签走,否则同一张图
1278
+ // 在「打开这个对话」里是定稿、在全局同组里却是素材(实测量过 1 张差异)。
1279
+ if (Array.isArray(item.sessionRefs)) {
1280
+ for (const ref of item.sessionRefs) ref.category = manual.category
1281
+ }
1082
1282
  } else {
1083
1283
  item.categoryManual = false
1084
1284
  }
@@ -1114,6 +1314,11 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1114
1314
  // 会话状态只读判定:只给分组加标注,不改排序、不改显示范围(0.14.1 原样)
1115
1315
  const sessionStates = isSession ? null : await readSessionStates(DSH_HOME)
1116
1316
 
1317
+ // v1.6.5:已隐藏的对话(全局资产底部的「已隐藏对话」合集)。
1318
+ // 只下发 id 列表,不在后端过滤 —— 前端拿去分区,右键一点就立即生效,
1319
+ // 不必为了一次隐藏把整个扫描(全库约 6 秒)重跑一遍。
1320
+ const hiddenSessions = isSession ? [] : await readHiddenSessions(opts.settingsFile)
1321
+
1117
1322
  // 全量统计:供「全局按对话分组」使用(不受分页限制)
1118
1323
  const allItemsSummary = []
1119
1324
  if (!isSession) {
@@ -1142,6 +1347,9 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1142
1347
  // 2026-11-25:来源标记必须透传给全局分组,否则资产台卡片看不到角标
1143
1348
  ...(item.inherited ? { inherited: true } : {}),
1144
1349
  ...(item.shared ? { shared: true } : {}),
1350
+ // 2026-11-25:一张图可能同时属于用它产出过的多个对话 —— 这张副归属表
1351
+ // 必须带到分组里,否则只有主归属那组有它(全局就比对话里少几张)。
1352
+ ...(Array.isArray(item.sessionRefs) ? { sessionRefs: item.sessionRefs } : {}),
1145
1353
  })
1146
1354
  }
1147
1355
  }
@@ -1196,13 +1404,15 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
1196
1404
  pageSize: opts.maxItems,
1197
1405
  // 「还有 N 张」= 当前页之外的总数(不再只是「被截掉的」)
1198
1406
  hidden: Math.max(0, total - visible.length),
1407
+ // v1.6.5:全局视图下发「已隐藏对话」清单,前端据此把对应分组收进合集
1408
+ hiddenSessions,
1199
1409
  rootMissing,
1200
1410
  scan: { directories, entries, capped },
1201
1411
  // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)。
1202
1412
  // 🔴 明细一次算全(全量留在服务端缓存),不再按 120 条截断:
1203
1413
  // 历史组有 5000+ 张,截断后旧图永远翻不到。
1204
1414
  // 响应由 host/http.js 瘦身成每组 60 张,前端点「再显示」再按需取下一批。
1205
- groups: isSession ? null : buildGroups(allItemsSummary, Number.MAX_SAFE_INTEGER, sessionId, sessionStates),
1415
+ groups: isSession ? null : buildGroups(allItemsSummary, Number.MAX_SAFE_INTEGER, currentRootSid, sessionStates),
1206
1416
  }
1207
1417
  }
1208
1418
 
@@ -8,9 +8,12 @@
8
8
  * 而画廊每 5 秒刷新一次 → 不可能每次都全量解压。
9
9
  * 用「目录 mtime + 会话数」做键,没事就不重扫。
10
10
  *
11
- * 为什么用目录 mtime 而不是逐个文件:
12
- * 108 个文件各 stat 一次也有开销;会话目录增多或日志追加时,
13
- * 目录 mtime 会变,足够触发重扫。
11
+ * 为什么用「逐条日志 mtime|size」而不是整表时间戳:
12
+ * 只要当前对话还在写日志,整表键每次都变,会把 100 MB 日志全量重解压。
13
+ * 逐条缓存后,活跃会话只重解它自己那一个日志(几十毫秒)。
14
+ *
15
+ * v1.6.5:这份缓存还会落盘(见下方 DISK_CACHE_VERSION),重启后直接复用,
16
+ * 不再每次重开面板都付一遍 7 秒的解压费。
14
17
  */
15
18
 
16
19
  import { promises as fsp } from 'node:fs'
@@ -27,6 +30,134 @@ const sessionEntryCache = new Map()
27
30
  /** 当前缓存对应的扫描目录指纹;用户改了根目录就整体失效。 */
28
31
  let indexRootsKey = ''
29
32
 
33
+ /**
34
+ * v1.6.5 卡顿根治:会话日志「解析结果」的磁盘缓存。
35
+ *
36
+ * 实测(本机 115 份日志 / 6940 张资产):冷启动全库扫描 7189 ms,
37
+ * 同进程热缓存只要 136 ms —— 差的 7 秒全在反复解压 zstd 日志并重跑
38
+ * extractAssetInfo / extractSessionTitle。进程内 sessionEntryCache 重启必丢,
39
+ * 所以每次重开面板都要再付一次。
40
+ *
41
+ * 这里把解析结果按 logPath + (mtime|size) 落到 <settings 同目录>,
42
+ * 重启后直接读回来:日志没变就绝不解压、绝不重解析;日志一变只重算那一份。
43
+ * 判据仍是 mtime(与全项目一致),没有「快照陈旧」问题。
44
+ *
45
+ * - 只在生产链路启用:scan.js 通过 deps.cacheFile 传入;测试直调不传,
46
+ * 行为与旧版逐字一致,不会往测试环境写文件。
47
+ * - 缓存文件绝不放扫描根内,否则下次刷新会把它自己扫成资产。
48
+ */
49
+ const DISK_CACHE_VERSION = 1
50
+
51
+ /** 缓存文件路径:设置文件同目录(DSH_HOME 下)。 */
52
+ export function sessionIndexCacheFileFor(settingsFile) {
53
+ return path.join(path.dirname(String(settingsFile)), 'gallery-session-index.json')
54
+ }
55
+
56
+ let diskLoaded = false
57
+ let diskRootsKey = ''
58
+ let diskLoadPromise = null
59
+ /** clearSessionIndexCache() 之后别把刚清掉的旧盘又灌回来,等这轮重算重写。 */
60
+ let skipNextDiskLoad = false
61
+
62
+ /** Map/Set 转成可 JSON 化结构。 */
63
+ function packEntry(entry) {
64
+ if (entry === null || entry === undefined) return null
65
+ return {
66
+ sessionId: entry.sessionId,
67
+ title: entry.title,
68
+ createdAt: entry.createdAt,
69
+ startMs: entry.startMs,
70
+ cwd: entry.cwd,
71
+ parentSession: entry.parentSession,
72
+ files: entry.files instanceof Map ? [...entry.files] : [],
73
+ dirs: entry.dirs instanceof Set ? [...entry.dirs] : [],
74
+ maxMtime: entry.maxMtime,
75
+ logMtime: entry.logMtime,
76
+ }
77
+ }
78
+
79
+ /** 反解;结构坏了返回 undefined,让那一条重新解析(不整表作废)。 */
80
+ function unpackEntry(raw) {
81
+ if (raw === null || raw === undefined) return null
82
+ if (typeof raw !== 'object') return undefined
83
+ if (!Array.isArray(raw.files) || !Array.isArray(raw.dirs)) return undefined
84
+ const files = new Map()
85
+ for (const pair of raw.files) {
86
+ if (Array.isArray(pair) && typeof pair[0] === 'string') {
87
+ files.set(pair[0], typeof pair[1] === 'string' ? pair[1] : 'unknown')
88
+ }
89
+ }
90
+ return {
91
+ sessionId: String(raw.sessionId ?? ''),
92
+ title: String(raw.title ?? ''),
93
+ createdAt: Number(raw.createdAt) || 0,
94
+ startMs: Number(raw.startMs) || 0,
95
+ cwd: String(raw.cwd ?? ''),
96
+ parentSession: String(raw.parentSession ?? ''),
97
+ files,
98
+ dirs: new Set(raw.dirs.filter((d) => typeof d === 'string')),
99
+ maxMtime: Number(raw.maxMtime) || 0,
100
+ logMtime: Number(raw.logMtime) || 0,
101
+ }
102
+ }
103
+
104
+ /** tmp + rename 原子写;失败只吞,缓存是加速器,绝不拖垮扫描。 */
105
+ async function flushDiskCache(file, rootsKey) {
106
+ let tmp = ''
107
+ try {
108
+ const body = JSON.stringify({
109
+ v: DISK_CACHE_VERSION,
110
+ at: Date.now(),
111
+ rootsKey,
112
+ entries: [...sessionEntryCache.entries()].map(([p, c]) => [
113
+ p, { key: c.key, entry: packEntry(c.entry) },
114
+ ]),
115
+ })
116
+ await fsp.mkdir(path.dirname(file), { recursive: true })
117
+ tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`
118
+ await fsp.writeFile(tmp, body, 'utf8')
119
+ await fsp.rename(tmp, file)
120
+ tmp = ''
121
+ } catch {
122
+ if (tmp !== '') { try { await fsp.unlink(tmp) } catch { /* 忽略 */ } }
123
+ }
124
+ }
125
+
126
+ /** 重启后把上次解析结果读回内存;版本 / roots 不符一律整表作废。 */
127
+ async function loadDiskCache(file, rootsKey) {
128
+ let raw
129
+ try { raw = JSON.parse(await fsp.readFile(file, 'utf8')) } catch { return }
130
+ if (raw === null || typeof raw !== 'object') return
131
+ if (raw.v !== DISK_CACHE_VERSION || raw.rootsKey !== rootsKey) return
132
+ if (!Array.isArray(raw.entries)) return
133
+ for (const pair of raw.entries) {
134
+ if (!Array.isArray(pair) || typeof pair[0] !== 'string') continue
135
+ const c = pair[1]
136
+ if (c === null || typeof c !== 'object' || typeof c.key !== 'string') continue
137
+ const entry = unpackEntry(c.entry)
138
+ if (entry === undefined) continue
139
+ sessionEntryCache.set(pair[0], { key: c.key, entry })
140
+ }
141
+ }
142
+
143
+ /** 懒加载一次;并发调用共用同一个 Promise,避免重复读盘。 */
144
+ async function ensureDiskLoaded(file, rootsKey) {
145
+ if (diskLoaded && diskRootsKey === rootsKey) return
146
+ if (diskLoadPromise !== null) { await diskLoadPromise; return }
147
+ diskLoadPromise = (async () => {
148
+ if (diskLoaded && diskRootsKey !== rootsKey) {
149
+ // roots 变了:旧缓存的 files/dirs 按旧 root 算,必须全部重算
150
+ sessionEntryCache.clear()
151
+ } else if (!skipNextDiskLoad) {
152
+ await loadDiskCache(file, rootsKey)
153
+ }
154
+ diskLoaded = true
155
+ diskRootsKey = rootsKey
156
+ skipNextDiskLoad = false
157
+ })()
158
+ try { await diskLoadPromise } finally { diskLoadPromise = null }
159
+ }
160
+
30
161
  /**
31
162
  * 扫出一个会话目录里的全部会话(含子会话)。
32
163
  * @param sessionsDir - 会话根目录。
@@ -153,17 +284,24 @@ function extractSessionMeta(logText) {
153
284
  */
154
285
  export async function buildSessionIndex(sessionsDir, opts, deps) {
155
286
  const { readSessionLogText, extractAssetInfo } = deps
287
+ // 只有生产链路(scan.js)传 cacheFile;测试直调不传 → 行为与旧版完全一致。
288
+ const cacheFile = typeof deps?.cacheFile === 'string' && deps.cacheFile !== ''
289
+ ? deps.cacheFile : ''
156
290
  try {
157
291
  // 列目录 + stat 115 个日志文件很便宜(约 10 ms),每次都做;
158
292
  // 贵的「解压 + 逐行解析」只发生在 mtime/size 变了的那些日志上。
159
293
  const allDirs = await listSessionDirs(sessionsDir)
160
294
  // 扫描目录变了(面板里改 root)→ 旧缓存里的文件归属是按旧目录算的,必须全部重算
161
295
  const rootsKey = (opts.roots ?? []).map((r) => path.resolve(r).toLowerCase()).join('|')
162
- if (rootsKey !== indexRootsKey) {
296
+ if (cacheFile !== '') {
297
+ await ensureDiskLoaded(cacheFile, rootsKey)
298
+ } else if (rootsKey !== indexRootsKey) {
163
299
  sessionEntryCache.clear()
164
300
  indexRootsKey = rootsKey
165
301
  }
166
302
  const index = new Map()
303
+ // 有新的解析结果 / 删掉过期条目时才回写盘,热扫描一次磁盘写入都不做
304
+ let dirty = false
167
305
  const livePaths = new Set()
168
306
 
169
307
  for (const d of allDirs) {
@@ -178,6 +316,7 @@ export async function buildSessionIndex(sessionsDir, opts, deps) {
178
316
  const logText = await readSessionLogText(d.logPath)
179
317
  if (logText === '') {
180
318
  sessionEntryCache.set(d.logPath, { key, entry: null })
319
+ dirty = true
181
320
  continue
182
321
  }
183
322
 
@@ -188,6 +327,16 @@ export async function buildSessionIndex(sessionsDir, opts, deps) {
188
327
 
189
328
  // 只看落在扫描目录内的路径
190
329
  const files = new Map()
330
+ // 2026-11-25:本对话「用过的目录」(相对扫描根、小写),供全局分组做目录兜底。
331
+ //
332
+ // 起因:老板在全局资产里看到「DSH辅助漫剧制作流程」只剩 2 张,切进该对话却是 12 张。
333
+ // 那 10 张日志里没有精确路径,只有「当前对话」视图靠「目录 + 时间窗口」兜得住;
334
+ // 全局分组只认精确路径,它们就掉进「历史资产」了。这里把目录也记进索引。
335
+ //
336
+ // 只收有子目录的层 + 根直属层(空串)—— 后者单列,由 scan 侧当作**最低优先**的
337
+ // 兜底:一个会话只要在根层产过文件,就会认得根层之后的所有新图,很容易过度归属,
338
+ // 所以它只在「没有任何更具体的归属」时才生效(实测「新项目调研」缺的 5 张就在根层)。
339
+ const dirs = new Set()
191
340
  let maxMtime = meta.createdAt
192
341
  for (const [abs, info] of assets) {
193
342
  let ownerRoot = null
@@ -196,6 +345,9 @@ export async function buildSessionIndex(sessionsDir, opts, deps) {
196
345
  }
197
346
  if (ownerRoot === null) continue
198
347
  files.set(abs, info.category)
348
+ const relDir = path.relative(ownerRoot, path.dirname(path.resolve(abs)))
349
+ .split(path.sep).join('/')
350
+ if (!relDir.startsWith('..')) dirs.add(relDir.toLowerCase())
199
351
  try {
200
352
  const st = await fsp.stat(abs)
201
353
  if (st.mtimeMs > maxMtime) maxMtime = st.mtimeMs
@@ -204,29 +356,36 @@ export async function buildSessionIndex(sessionsDir, opts, deps) {
204
356
  }
205
357
  }
206
358
 
207
- if (files.size === 0) {
208
- sessionEntryCache.set(d.logPath, { key, entry: null })
209
- continue
210
- }
359
+ // 2026-11-25:files 为空也**不再丢弃**这条记录。
360
+ // 原因:子会话可能只把产出落在扫描根外(日志里没路径),父会话条目却是
361
+ // 子会话归并的依据 —— 丢掉它,buildRootSessionResolver 就找不到父链,
362
+ // 子会话会单独成组,父组永远少几张(实测「尺间空间IP品牌重塑」少 59 张)。
363
+ // 空条目对 ownerByAbs / dirOwnerIndex 都是空循环,不产生副作用。
211
364
 
212
365
  const entry = {
213
366
  sessionId: d.sessionId,
214
367
  title,
215
368
  createdAt: meta.createdAt,
369
+ // 目录兜底的时间门槛:文件必须「晚于本对话开始」才算它的产出,
370
+ // 与 resolveSessionScope 的 isFreshSince 同一把关,避免把老图抢进新对话。
371
+ startMs: meta.createdAt,
216
372
  cwd: meta.cwd,
217
373
  parentSession: meta.parentSession,
218
374
  files,
375
+ dirs,
219
376
  maxMtime,
220
377
  logMtime: d.logMtime,
221
378
  }
222
379
  index.set(d.sessionId, entry)
223
380
  sessionEntryCache.set(d.logPath, { key, entry })
381
+ dirty = true
224
382
  }
225
383
 
226
384
  // 日志目录被删掉时把对应缓存也清掉,避免常驻进程里无限堆积
227
385
  for (const p of sessionEntryCache.keys()) {
228
- if (!livePaths.has(p)) sessionEntryCache.delete(p)
386
+ if (!livePaths.has(p)) { sessionEntryCache.delete(p); dirty = true }
229
387
  }
388
+ if (cacheFile !== '' && dirty) await flushDiskCache(cacheFile, rootsKey)
230
389
  return index
231
390
  } catch {
232
391
  return new Map()
@@ -247,6 +406,8 @@ function isInsidePath(root, abs) {
247
406
  export function clearSessionIndexCache() {
248
407
  sessionEntryCache.clear()
249
408
  indexRootsKey = ''
409
+ diskLoaded = false
410
+ skipNextDiskLoad = true
250
411
  }
251
412
 
252
413
  /**