dsh-gallery 0.17.0 → 1.1.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/host/scan.js CHANGED
@@ -26,6 +26,52 @@ export function parentDirOf(relPath) {
26
26
  }
27
27
 
28
28
  /** v0.14.7:当前对话分类。日志/登记里没有的、同目录外部图片自动标「素材」(input)。 */
29
+ /**
30
+ * 2026-11-15:同目录放宽的「新鲜度」门槛。
31
+ *
32
+ * 老规则:只要本对话提到过某个目录里的任意一张图,该目录下所有图片都算
33
+ * 这个对话的素材。只读查一次图(助手回答里带了几条历史路径)就会把几百张
34
+ * 老图抢进新对话(真实实测:3 张相关 → 217 张,其中 207 张标成素材)。
35
+ * 现在只放行「本对话开始之后新出现或新改动」的文件:插件粘贴 / 裁剪会
36
+ * 把 mtime 刷成当前时间,仍看得见;手工拷贝旧文件时 birthtime 也是新的。
37
+ * 拿不到会话开始时间时一律不放宽,宁可少显示也不误抢。
38
+ */
39
+ export function isFreshSince(stat, sessionStartMs) {
40
+ const since = Number(sessionStartMs) || 0
41
+ if (since <= 0 || stat == null) return false
42
+ const newest = Math.max(Number(stat.mtimeMs) || 0, Number(stat.birthtimeMs) || 0)
43
+ return newest >= since
44
+ }
45
+
46
+ /**
47
+ * 2026-11-16 第一档:限流并发执行。
48
+ * scan 阶段每个文件都要读一次 stat,串行时五千多个文件要 7 秒左右;
49
+ * 这里用固定数量的「工人」同时干,结果按下标回填,顺序与串行完全一致。
50
+ */
51
+ export async function mapPool(items, limit, fn) {
52
+ const list = Array.isArray(items) ? items : []
53
+ const out = new Array(list.length)
54
+ if (list.length === 0) return out
55
+ const width = Math.max(1, Math.min(Math.trunc(Number(limit) || 1), list.length))
56
+ let cursor = 0
57
+ const workers = []
58
+ for (let w = 0; w < width; w += 1) {
59
+ workers.push((async () => {
60
+ for (;;) {
61
+ const i = cursor
62
+ cursor += 1
63
+ if (i >= list.length) return
64
+ out[i] = await fn(list[i], i)
65
+ }
66
+ })())
67
+ }
68
+ await Promise.all(workers)
69
+ return out
70
+ }
71
+
72
+ /** 并发读 stat 的路数:本地盘 32 路收益已接近上限,再高只增加抢占。 */
73
+ export const SCAN_CONCURRENCY = 32
74
+
29
75
  export function categoryForSessionAsset(autoCategory, externalAsset) {
30
76
  return autoCategory ?? (externalAsset ? ASSET_CATEGORY.INPUT : null)
31
77
 
@@ -274,6 +320,8 @@ export async function resolveSessionScope(config, sessionId, allRoots) {
274
320
  return {
275
321
  ok: true,
276
322
  reason: 'ok',
323
+ // 2026-11-15:同目录放宽只收本对话开始之后新出现 / 改动的文件
324
+ sessionStartMs,
277
325
  taskDirs: [...taskDirs],
278
326
  paths: normalized,
279
327
  relPaths,
@@ -329,8 +377,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
329
377
  // v0.14.7:会话引用过的目录集合。同目录下的外部图片也纳入「当前对话」,
330
378
  // 但不在精确路径白名单里 —— 它们会被自动标为「素材」(input)。
331
379
  let sessionDirSet = null
380
+ let sessionStartMs = 0
332
381
  if (isSession) {
333
382
  scopeInfo = await resolveSessionScope(config, sessionId, opts.roots)
383
+ sessionStartMs = Number(scopeInfo.sessionStartMs) || 0
334
384
  // 修法 B:用「精确相对路径」集合判定,而不是只靠第一层目录名。
335
385
  // 这样既能处理有子目录的情况,也能处理「文件直接躺在 root 根目录下」。
336
386
  sessionRelSet = new Set((scopeInfo.relPaths ?? []).map((p) => p.toLowerCase()))
@@ -379,23 +429,36 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
379
429
  }
380
430
  }
381
431
 
382
- // v0.14.8:全局资产下「当前对话」组也要认出外部素材。
383
- // 旧逻辑只在 scope=session 算 sessionDirs;全局模式只认会话日志 / frames.json
384
- // 精确引用过的文件,同目录里外部放进来、没被引用过的图全掉进「历史资产」
385
- // 并标「未归类」——界面上就表现为「当前对话」组只有几张过程稿、素材数为 0。
386
- // 这里复用与「当前对话」视图完全相同的目录判定,把无归属的同目录图片
387
- // 挂回当前对话组并标 input(素材);其它对话 / 历史资产一律不动。
432
+ // 2026-11-15:全局资产下置顶的「当前对话」组,必须和「当前对话」视图用同一把尺子。
433
+ // 旧做法把归属交给全库会话索引、谁最近算谁的:本对话明明能看见的图,
434
+ // 会被更早引用过它的老对话抢走(老板实测:全局 2 张、当前对话视图 4 张)。
435
+ // 现在先解析本对话范围(精确路径 + 用过的目录),符合的资产一律归本对话组;
436
+ // 其余仍按会话索引 / 登记归属,历史资产口径不变。
388
437
  let globalCurrentDirs = null
389
438
  let globalCurrentMeta = null
439
+ let globalCurrentExactRels = null
440
+ let globalCurrentCategory = null
441
+ let globalCurrentStartMs = 0
390
442
  if (!isSession && sessionId !== '') {
391
443
  const current = await resolveSessionScope(config, sessionId, opts.roots)
392
444
  if (current.ok) {
445
+ globalCurrentStartMs = Number(current.sessionStartMs) || 0
393
446
  const dirs = new Set((current.sessionDirs ?? []).map((d) => String(d).toLowerCase()))
394
- // 本对话截帧 / 遮罩的登记目录也算(与 session 模式保持一致)
447
+ const exactRels = new Set((current.relPaths ?? []).map((p) => String(p).toLowerCase()))
448
+ const categoryByRel = new Map()
449
+ for (const [rel, cat] of (current.categoryByRel instanceof Map ? current.categoryByRel : new Map())) {
450
+ categoryByRel.set(String(rel).toLowerCase(), cat)
451
+ }
452
+ // 本对话截帧 / 遮罩的登记目录与精确路径也算(与 session 模式保持一致)
395
453
  for (const [rel, f] of frameByRel) {
396
- if (String(f.sessionId ?? '') === sessionId) dirs.add(parentDirOf(rel))
454
+ if (String(f.sessionId ?? '') !== sessionId) continue
455
+ dirs.add(parentDirOf(rel))
456
+ exactRels.add(String(rel).toLowerCase())
457
+ categoryByRel.set(String(rel).toLowerCase(), frameCategoryOf(f))
397
458
  }
398
459
  globalCurrentDirs = dirs
460
+ globalCurrentExactRels = exactRels
461
+ globalCurrentCategory = categoryByRel
399
462
  // 会话索引里可能没有该会话(日志里没有落在扫描目录内的产出),
400
463
  // 这时组名会退化成 sessionId 前 8 位。frames.json 的登记带会话标题,补上。
401
464
  const indexed = sessionIndex?.get(sessionId) ?? null
@@ -415,6 +478,8 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
415
478
  const hiddenSet = new Set(await readHiddenList(opts.settingsFile))
416
479
 
417
480
  const matches = []
481
+ // 2026-11-16 第一档:两阶段扫描的候选路径暂存(先收集、再并发 stat)
482
+ const candidates = []
418
483
  let directories = 0
419
484
  let entries = 0
420
485
  let capped = false
@@ -475,40 +540,66 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
475
540
  const relPath = path.relative(rootDir, fullPath).split(path.sep).join('/')
476
541
  // 当前对话:精确路径白名单优先;不在白名单但落在「本对话用过的目录」里,
477
542
  // 视作外部放进来的素材放行(v0.14.7)。其它目录一律不进当前对话。
478
- let externalAsset = false
543
+ let looseDirHit = false
479
544
  if (sessionRelSet !== null && !sessionRelSet.has(relPath.toLowerCase())) {
480
545
  if (sessionDirSet === null || !sessionDirSet.has(parentDirOf(relPath))) continue
481
- externalAsset = true
546
+ looseDirHit = true
482
547
  }
483
- let stat
484
- try {
485
- stat = await fsp.stat(fullPath)
486
- } catch {
487
- continue
488
- }
489
- if (stat.size <= 0 || stat.mtimeMs < cutoff) continue
490
- // 音视频:超过体积上限的直接跳过(视频可能几百 MB,列出来点开就卡)
491
- if (isMedia && stat.size > opts.maxMediaBytes) continue
492
548
  // 被隐藏的直接跳过(隐藏只影响列表展示,文件仍在磁盘上)
493
549
  if (hiddenSet.has(relPath)) continue
494
- matches.push({
550
+ // 第一阶段只登记路径,stat 留到全部收集完再统一并发读(第一档性能优化)
551
+ candidates.push({
552
+ fullPath,
495
553
  relPath,
496
- relKey: `${opts.roots.indexOf(rootDir)}:${relPath}`,
554
+ entryName,
497
555
  rootDir,
498
556
  rootIndex: opts.roots.indexOf(rootDir),
499
- name: entryName,
500
- size: stat.size,
501
- mtime: stat.mtimeMs,
502
557
  extension: ext,
503
- // v0.14.7:外部素材标记,扫描阶段据此给出「素材」标签
504
- ...(externalAsset ? { externalAsset: true } : {}),
505
- // 音视频区分「视频 / 音频」,客户端据此选 <video> 还是 <audio>
506
- ...(isMedia ? { mediaType: VIDEO_EXTS.includes(ext) ? 'video' : 'audio' } : {}),
558
+ looseDirHit,
507
559
  })
508
560
  }
509
561
  }
510
562
  }
511
563
 
564
+ // 2026-11-16 第一档:第二阶段限流并发读 stat。
565
+ // 全库五千多个文件逐个 await 要 7 秒左右,几十路并发能压到 1 秒内;
566
+ // 过滤条件(时间窗口 / 体积 / 隐藏 / 同目录新鲜度)与串行时完全一致,
567
+ // 只是把「等待」叠起来做,不改变任何一条判定。
568
+ const statted = await mapPool(candidates, SCAN_CONCURRENCY, async (c) => {
569
+ let stat
570
+ try {
571
+ stat = await fsp.stat(c.fullPath)
572
+ } catch {
573
+ return null
574
+ }
575
+ // 2026-11-15:同目录放宽只收本对话期间新出现 / 改动的图;
576
+ // 否则只读查一次图,就会把该目录里几百张历史图全算进这个新对话。
577
+ if (c.looseDirHit && !isFreshSince(stat, sessionStartMs)) return null
578
+ if (stat.size <= 0 || stat.mtimeMs < cutoff) return null
579
+ // 音视频:超过体积上限的直接跳过(视频可能几百 MB,列出来点开就卡)
580
+ if (isMedia && stat.size > opts.maxMediaBytes) return null
581
+ return {
582
+ relPath: c.relPath,
583
+ relKey: `${c.rootIndex}:${c.relPath}`,
584
+ rootDir: c.rootDir,
585
+ rootIndex: c.rootIndex,
586
+ name: c.entryName,
587
+ size: stat.size,
588
+ mtime: stat.mtimeMs,
589
+ // 手工拷贝旧文件时 mtime 仍是老的,但创建时间是新的;
590
+ // 两个视图的同目录放宽判据都看它,不能只给 mtime 造成一边有一边没有。
591
+ birthtimeMs: stat.birthtimeMs,
592
+ extension: c.extension,
593
+ // v0.14.7:外部素材标记,扫描阶段据此给出「素材」标签
594
+ ...(c.looseDirHit ? { externalAsset: true } : {}),
595
+ // 音视频区分「视频 / 音频」,客户端据此选 <video> 还是 <audio>
596
+ ...(isMedia ? { mediaType: VIDEO_EXTS.includes(c.extension) ? 'video' : 'audio' } : {}),
597
+ }
598
+ })
599
+ for (const item of statted) {
600
+ if (item !== null) matches.push(item)
601
+ }
602
+
512
603
  const rootMissing = !anyRootExists
513
604
 
514
605
  // v0.14.2:手动标签覆写优先于机器预判的产出状态。
@@ -572,20 +663,25 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
572
663
  // 手动改过的标签在下面仍然优先覆盖,刷新/重扫/重启都不回退。
573
664
  item.category = categoryForSessionAsset(autoCategory, item.externalAsset)
574
665
  item.sessionId = sessionId
666
+ } else if (globalCurrentExactRels !== null
667
+ && (globalCurrentExactRels.has(item.relPath.toLowerCase())
668
+ || (globalCurrentDirs !== null && globalCurrentDirs.has(parentDirOf(item.relPath))
669
+ && isFreshSince({ mtimeMs: item.mtime, birthtimeMs: item.birthtimeMs }, globalCurrentStartMs)))) {
670
+ // 2026-11-15:本对话日志精确引用过、或落在本对话用过的目录里的资产,
671
+ // 一律归到全局置顶的「当前对话」组;历史会话索引不能再把它抢走。
672
+ // 分类与「当前对话」视图完全一致:精确命中用日志判定,目录命中按外部素材标 input。
673
+ const relKey = item.relPath.toLowerCase()
674
+ const exact = globalCurrentExactRels.has(relKey)
675
+ item.category = categoryForSessionAsset(globalCurrentCategory?.get(relKey), !exact)
676
+ if (!exact) item.externalAsset = true
677
+ item.sessionId = sessionId
678
+ item.sessionTitle = globalCurrentMeta?.title ?? ''
679
+ item.sessionCreatedAt = globalCurrentMeta?.createdAt ?? 0
575
680
  } else if (owner !== undefined) {
576
681
  item.category = owner.category
577
682
  item.sessionId = owner.sessionId
578
683
  item.sessionTitle = owner.title
579
684
  item.sessionCreatedAt = owner.createdAt
580
- } else if (globalCurrentDirs !== null && globalCurrentDirs.has(parentDirOf(item.relPath))) {
581
- // v0.14.8 全局模式:外部放进本对话目录、日志与登记都没引用的图片。
582
- // 与「当前对话」视图同一口径:挂回当前对话组 + 自动标「素材」(input)。
583
- // 只对「不属于任何已知对话」的条目生效,绝不抢别的对话已引用的文件。
584
- item.category = ASSET_CATEGORY.INPUT
585
- item.externalAsset = true
586
- item.sessionId = sessionId
587
- item.sessionTitle = globalCurrentMeta?.title ?? ''
588
- item.sessionCreatedAt = globalCurrentMeta?.createdAt ?? 0
589
685
  } else {
590
686
  // 不属于任何已知对话、也不在当前对话目录里的文件:归到「历史资产」,
591
687
  // 分类记为**未归类**。不能兜底成 input —— 那会把几千个历史文件全标成「输入」
@@ -650,6 +746,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
650
746
  size: item.size,
651
747
  name: item.name,
652
748
  extension: item.extension,
749
+ // 阶段 2:分组明细补齐遮罩关联与「手动改过标签」,
750
+ // 让 Agent 拿到的信息和人双击写进输入框拿到的完全一致。
751
+ ...(item.maskOf !== undefined ? { maskOf: item.maskOf } : {}),
752
+ categoryManual: item.categoryManual === true,
653
753
  // 音视频类型(video / audio),客户端据此选 <video> 还是 <audio>
654
754
  ...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
655
755
  // 截帧来源:反馈篮与草稿正文据此写清取自哪段视频的哪一帧
@@ -671,6 +771,8 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
671
771
  subSessions: scopeInfo.subSessions ?? 0,
672
772
  // v0.14.7:本对话用过的目录数 / 自动纳入的外部素材数(诊断用)
673
773
  // v0.14.8:全局模式另给一份目录数,两种视图口径是否一致一眼可查
774
+ sessionStartMs,
775
+ globalCurrentStartMs,
674
776
  externalDirs: sessionDirSet?.size ?? 0,
675
777
  globalExternalDirs: globalCurrentDirs?.size ?? 0,
676
778
  externalAssets: matches.reduce((n, i) => n + (i.externalAsset ? 1 : 0), 0),
@@ -685,6 +787,17 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
685
787
  generatedAt: now,
686
788
  items: visible,
687
789
  total,
790
+ // 2026-11-15:分类小数字按「本视图全部」算,不能只数第一页 60 张。
791
+ // 全局视图靠 groups[].counts,当前对话视图没有 groups,前端以前只能数 items,
792
+ // 结果与全局「当前对话」组的小标签对不上(老板 19:18 实测报的)。
793
+ counts: (() => {
794
+ const c = { final: 0, input: 0, intermediate: 0, unknown: 0 }
795
+ for (const m of matches) {
796
+ const k = String(m?.category ?? 'unknown')
797
+ if (Object.prototype.hasOwnProperty.call(c, k)) c[k] += 1
798
+ }
799
+ return c
800
+ })(),
688
801
  // 分页信息,客户端据此渲染页码条
689
802
  page: safePage,
690
803
  pageCount,
@@ -693,8 +806,11 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
693
806
  hidden: Math.max(0, total - visible.length),
694
807
  rootMissing,
695
808
  scan: { directories, entries, capped },
696
- // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)
697
- groups: isSession ? null : buildGroups(allItemsSummary, 120, sessionId, sessionStates),
809
+ // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)。
810
+ // 🔴 明细一次算全(全量留在服务端缓存),不再按 120 条截断:
811
+ // 历史组有 5000+ 张,截断后旧图永远翻不到。
812
+ // 响应由 host/http.js 瘦身成每组 60 张,前端点「再显示」再按需取下一批。
813
+ groups: isSession ? null : buildGroups(allItemsSummary, Number.MAX_SAFE_INTEGER, sessionId, sessionStates),
698
814
  }
699
815
  }
700
816
 
@@ -711,9 +827,9 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
711
827
  * 2. 其余对话按创建时间倒序。
712
828
  * 3. 「历史资产」永远最后。
713
829
  *
714
- * ⚠️ 体积控制:每组只返回前 maxPerGroup 条明细 + 完整总数。
715
- * 为什么必须截断:历史组有 4995 个文件,全量返回会让单次响应达到 1.3 MB,
716
- * 前端解析/渲染都会卡,面板看起来「只显示两组」。
830
+ * ⚠️ 明细一次给全(调用方传极大 maxPerGroup):历史组有 5000+ 个文件,
831
+ * 以前每组截断到 120 条,旧图永远翻不到。现在由前端渐进渲染控制画面里的
832
+ * 卡片数量;单次响应约 1.5 MB,解析开销远小于「几千张卡同时进画面」。
717
833
  *
718
834
  * @param summary - 扁平资产摘要数组。
719
835
  * @param maxPerGroup - 每组最多返回多少条明细(默认 120)。