dsh-gallery 0.17.0 → 1.0.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/protocol.js CHANGED
@@ -1,4 +1,4 @@
1
- // GENERATED from src/shared/protocol.js — 请勿手改
1
+ // GENERATED from src/shared/protocol.js — 请勿手改
2
2
  /**
3
3
  * 协议常量 —— Host 与 Client 的唯一真源。
4
4
  *
@@ -62,6 +62,37 @@ export function clamp01(v) {
62
62
  return n
63
63
  }
64
64
 
65
+ /** 把数夹到 [min, max] 闭区间内。 */
66
+ function clampNum(v, min, max) {
67
+ const n = Number(v)
68
+ if (!Number.isFinite(n)) return min
69
+ if (n < min) return min
70
+ if (n > max) return max
71
+ return n
72
+ }
73
+
74
+ /**
75
+ * v0.16.0 选段播放决策(纯函数,便于单测)。
76
+ *
77
+ * 老板 2026-11-13 11:56 反馈:播放必须跟选段走 —— **从入点起播、到出点结束**,
78
+ * 而不是播放器自己按整段播(截图里选段是 2:16–3:21,播放头却停在 0:29)。
79
+ * 拖动端点 / 点轨道时(scrubbing)不做钳制,否则播放头会被反复拽回,没法目视选帧。
80
+ *
81
+ * @returns {{ action: 'none' | 'stop' | 'seekIn', seekTo?: number }}
82
+ */
83
+ function trimPlaybackDecision(now, inPoint, outPoint, opts) {
84
+ const o = opts || {}
85
+ if (!Number.isFinite(now)) return { action: 'none' }
86
+ // 区间还没初始化(或过短)时不要干预原生播放
87
+ if (!(outPoint > inPoint + 0.05)) return { action: 'none' }
88
+ if (o.scrubbing === true) return { action: 'none' }
89
+ // 到出点:停住,不循环 —— 老板要的是「到出点结束」
90
+ if (now >= outPoint - 0.02) return { action: 'stop', seekTo: Math.min(now, outPoint) }
91
+ // 播放跑到入点之前(例如用原生进度条拖到了区间外)→ 拉回入点
92
+ if (now < inPoint - 0.25 && o.paused !== true) return { action: 'seekIn', seekTo: inPoint }
93
+ return { action: 'none' }
94
+ }
95
+
65
96
  /** 校验并规整一条批注;不合法返回 null。 */
66
97
  export function normalizeAnnotation(a) {
67
98
  if (a === null || typeof a !== "object") return null
@@ -80,3 +111,374 @@ export function normalizeAnnotation(a) {
80
111
  shape, x, y, w, h, note, frameMs,
81
112
  }
82
113
  }
114
+
115
+ /**
116
+ * 批注层几何(v0.14.4):SVG 与 <img> 共用同一布局盒、同一组 translate/scale。
117
+ * 图片按 object-fit:contain 居中后,实际显示盒往往小于预览容器;旧版 SVG 覆盖整个
118
+ * 容器且不带变换,1:1 就可能错位,放大后更彻底脱框。抽成纯函数便于离线钉死契约。
119
+ */
120
+ function annotationSvgStyle(imgBox, pan, zoom, transition) {
121
+ return {
122
+ position: 'absolute',
123
+ left: `${imgBox.left}px`,
124
+ top: `${imgBox.top}px`,
125
+ width: `${imgBox.width}px`,
126
+ height: `${imgBox.height}px`,
127
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
128
+ transformOrigin: '50% 50%',
129
+ transition,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * 标注态「按下要不要拦冒泡 / 交给谁」的判定(v0.14.4)。
135
+ * 查看器本身就支持中键拖拽平移;标注层过去对所有按键一律 stopPropagation,
136
+ * 把中键吞掉,导致标注时挪不动图。现在:中键放行给查看器平移,左键留给画框。
137
+ */
138
+ function annotationPointerRouting(active, button) {
139
+ // 未激活:不拦(图片 pointerEvents:none,事件本就落到查看器)
140
+ if (!active) return 'pass'
141
+ // 中键(1):放行给查看器的中键拖拽平移,框跟着图走(已画框与图共用 pan/zoom)
142
+ if (button === 1) return 'pan'
143
+ // 左键(0)及其余:拦住,交给标注层画框;顺带防止弹窗输入被查看器拖图抢走
144
+ return 'draw'
145
+ }
146
+
147
+ /** 标注层 SVG 的光标:中键平移进行中显示抓握,否则画框态为十字。 */
148
+ function annotationSvgCursor(active, dragging, zoom) {
149
+ if (!active) return 'default'
150
+ if (dragging && zoom > 1) return 'grabbing'
151
+ return 'crosshair'
152
+ }
153
+
154
+ /**
155
+ * 遮罩编码契约(v0.14.5 本机 MVP)—— 本机实证,不是推测:
156
+ * ComfyUI 官方 LoadImage 与本机孤海 LoadImageGoohai 的 MASK 输出都是 `1 - alpha/255`。
157
+ * 所以「框内 alpha=0、框外 alpha=255」的普通 RGBA PNG 直接就是可用遮罩,
158
+ * RGB 必须保留原图像素(LoadImage 的 IMAGE 输出仍拿它做局部重绘)。
159
+ * 这与 clipspace-painted-* 涂鸦遮罩等价,但不必复刻 ComfyUI 画布交互。
160
+ *
161
+ * 注意:遮罩是**新资产**(同视频截帧,落盘并登记到当前对话),不是批注;
162
+ * 批注依旧只存内存。导出的路径只进反馈草稿,零自动发送、插件零外部请求。
163
+ */
164
+
165
+ /** 原图像素上限:超过拒绝生成,避免超大图卡死前端(host 另有 24 MB 兜底)。 */
166
+ const MASK_MAX_PIXELS = 24000000
167
+
168
+ /** 归一化框选批注 → 原图像素矩形(clamp + 至少 1px,不越界)。 */
169
+ function maskPixelRect(annotation, width, height) {
170
+ const w = Math.max(1, Math.round(Number(width) || 0))
171
+ const h = Math.max(1, Math.round(Number(height) || 0))
172
+ const x = clamp01(annotation?.x)
173
+ const y = clamp01(annotation?.y)
174
+ let nw = clamp01(annotation?.w)
175
+ let nh = clamp01(annotation?.h)
176
+ if (nw > 0 && x + nw > 1) nw = 1 - x
177
+ if (nh > 0 && y + nh > 1) nh = 1 - y
178
+ const x0 = Math.min(w - 1, Math.max(0, Math.round(x * w)))
179
+ const y0 = Math.min(h - 1, Math.max(0, Math.round(y * h)))
180
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.round((x + nw) * w)))
181
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.round((y + nh) * h)))
182
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0, width: w, height: h }
183
+ }
184
+
185
+ /** 单像素 alpha:框内 0(mask=1 待重绘),框外 255(mask=0 保留)。 */
186
+ function maskAlphaAt(px, py, rect) {
187
+ const inside = px >= rect.x && px < rect.x + rect.w && py >= rect.y && py < rect.y + rect.h
188
+ return inside ? 0 : 255
189
+ }
190
+
191
+ /* ------------------------------------------------------------------ *
192
+ * v0.14.6 右键多点选区(老板 2026-11-12 拍板):
193
+ * 标记态下左键仍是矩形批注,右键逐点点击 4–20 个顶点,闭合成实心多边形。
194
+ * 实测口径(见验证报告第九节):必须是「实心、贴合目标外接框」的块,
195
+ * 描笔画的镂空线框 / 椭圆 / 大矩形都会出白底;多边形天然实心且面积可量。
196
+ * ------------------------------------------------------------------ */
197
+ const POLYGON_LIMITS = { min: 4, max: 20, closeRadius: 0.02, minArea: 0.0001 }
198
+
199
+ /* ------------------------------------------------------------------ *
200
+ * 选区纯色半透明填充(v0.14.7 引入;老板 2026-11-12 20:22 再定版):
201
+ * 填充 0.4 / 轮廓 0.7,界面选区与「填充预览图」共用红 / 绿 / 蓝三色;
202
+ * 导出的主 alpha 遮罩仍是「RGB 原图 + alpha 二值」,ComfyUI 链路一点不动。
203
+ * 轮廓视觉宽度统一 1.5px:界面 SVG 用 non-scaling-stroke 直接画 1.5px;
204
+ * 导出预览图按「DSH 缩到 200px 长边后仍留 1.5px」反推线宽 —— 固定 2px
205
+ * 描边缩完会消失,过宽的边线又会糊住选区,两端共用同一个基准常量。
206
+ * ------------------------------------------------------------------ */
207
+ const MASK_FILL_COLORS = Object.freeze({
208
+ green: { rgb: [94, 214, 150], label: '绿' },
209
+ red: { rgb: [239, 68, 68], label: '红' },
210
+ blue: { rgb: [59, 130, 246], label: '蓝' },
211
+ })
212
+ const MASK_FILL_KEYS = Object.keys(MASK_FILL_COLORS)
213
+ const MASK_FILL_ALPHA = 0.4
214
+ const MASK_STROKE_ALPHA = 0.7
215
+ /** 轮廓视觉宽度基准(px):界面直接画,导出预览图按缩略图比例反推。 */
216
+ const MASK_STROKE_PX = 1.5
217
+
218
+ /** 未知颜色一律回落绿色,避免脏值写进文件名 / 元数据。 */
219
+ function maskFillColor(key) {
220
+ return Object.prototype.hasOwnProperty.call(MASK_FILL_COLORS, key)
221
+ ? MASK_FILL_COLORS[key] : MASK_FILL_COLORS.green
222
+ }
223
+
224
+ function maskFillRgba(key, alpha = MASK_FILL_ALPHA) {
225
+ const [r, g, b] = maskFillColor(key).rgb
226
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`
227
+ }
228
+
229
+ /**
230
+ * 预览图轮廓线宽:以「DSH 缩略图长边 200px 时描边仍约 1.5px」反推,
231
+ * 夹在 6–40px,避免小图线条消失、超大图线条糊成一片。纯函数,测试跑真身。
232
+ */
233
+ function maskStrokeWidth(width, height) {
234
+ const w = Math.max(1, Number(width) || 0)
235
+ const h = Math.max(1, Number(height) || 0)
236
+ const scale = Math.max(w, h) / 200
237
+ return Math.max(6, Math.min(40, Math.round(MASK_STROKE_PX * scale)))
238
+ }
239
+
240
+ /** 预览层的填充 / 轮廓描述(纯函数,测试直接跑真身):多边形优先,矩形回落。 */
241
+ function maskOverlayPath(rect, polygonPx, colorKey) {
242
+ const hasPolygon = Array.isArray(polygonPx) && polygonPx.length >= 3
243
+ return {
244
+ key: Object.prototype.hasOwnProperty.call(MASK_FILL_COLORS, colorKey) ? colorKey : 'green',
245
+ label: maskFillColor(colorKey).label,
246
+ rgba: maskFillRgba(colorKey, MASK_FILL_ALPHA),
247
+ strokeRgba: maskFillRgba(colorKey, MASK_STROKE_ALPHA),
248
+ strokeWidth: maskStrokeWidth(rect?.width, rect?.height),
249
+ points: hasPolygon ? polygonPx : null,
250
+ rect: hasPolygon ? null : { x: rect.x, y: rect.y, w: rect.w, h: rect.h },
251
+ }
252
+ }
253
+
254
+ /** 顶点数组的归一外接框;points 既接受 [{x,y}] 也接受 [[x,y]]。 */
255
+ function polygonBBox(points) {
256
+ const xs = points.map((p) => clamp01(Array.isArray(p) ? p[0] : p?.x))
257
+ const ys = points.map((p) => clamp01(Array.isArray(p) ? p[1] : p?.y))
258
+ const x0 = Math.min(...xs)
259
+ const y0 = Math.min(...ys)
260
+ const x1 = Math.max(...xs)
261
+ const y1 = Math.max(...ys)
262
+ return { x: x0, y: y0, w: clamp01(x1 - x0), h: clamp01(y1 - y0) }
263
+ }
264
+
265
+ /** 鞋带公式:归一化面积,用来挡掉「点成一条线」的退化选区。 */
266
+ function polygonArea(points) {
267
+ let sum = 0
268
+ for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) {
269
+ const xi = Array.isArray(points[i]) ? points[i][0] : points[i].x
270
+ const yi = Array.isArray(points[i]) ? points[i][1] : points[i].y
271
+ const xj = Array.isArray(points[j]) ? points[j][0] : points[j].x
272
+ const yj = Array.isArray(points[j]) ? points[j][1] : points[j].y
273
+ sum += (xj * yi) - (xi * yj)
274
+ }
275
+ return Math.abs(sum) / 2
276
+ }
277
+
278
+ /** 射线法(无 canvas 环境兜底,也用于离线断言钉死「多边形内 alpha=0」)。 */
279
+ function pointInPolygon(px, py, points) {
280
+ let inside = false
281
+ for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) {
282
+ const xi = points[i][0]
283
+ const yi = points[i][1]
284
+ const xj = points[j][0]
285
+ const yj = points[j][1]
286
+ const hit = ((yi > py) !== (yj > py))
287
+ && (px < (((xj - xi) * (py - yi)) / (yj - yi)) + xi)
288
+ if (hit) inside = !inside
289
+ }
290
+ return inside
291
+ }
292
+
293
+ /** 归一化顶点 → 原图像素顶点;点不合法或数量越界一律返回 null。 */
294
+ function normalizePolygon(value, width, height) {
295
+ if (!Array.isArray(value) || value.length < POLYGON_LIMITS.min || value.length > POLYGON_LIMITS.max) return null
296
+ const w = Math.max(1, Math.round(Number(width) || 0))
297
+ const h = Math.max(1, Math.round(Number(height) || 0))
298
+ const pts = []
299
+ for (const p of value) {
300
+ const nx = Number(Array.isArray(p) ? p[0] : p?.x)
301
+ const ny = Number(Array.isArray(p) ? p[1] : p?.y)
302
+ if (!Number.isFinite(nx) || !Number.isFinite(ny)) return null
303
+ pts.push([clamp01(nx) * w, clamp01(ny) * h])
304
+ }
305
+ return pts
306
+ }
307
+
308
+ /**
309
+ * 多边形 → 全尺寸二值 alpha 层(0 = 待重绘,255 = 保留)。
310
+ * 优先用离屏 canvas 填充(浏览器自动处理自交、抗锯齿与非零环绕),
311
+ * 只在 bbox 子画布上读一次像素,避免全图再开一份 ImageData;
312
+ * 读回后按 >127 强制二值,保持与 ComfyUI `MASK = 1 - alpha/255` 的实证契约一致。
313
+ * Node / 无 canvas 环境退化为射线法,测试可直接跑真身。
314
+ */
315
+ function polygonAlphaLayer(points, width, height) {
316
+ const w = Math.max(1, Math.round(Number(width) || 0))
317
+ const h = Math.max(1, Math.round(Number(height) || 0))
318
+ const out = new Uint8Array(w * h).fill(255)
319
+ const xs = points.map((p) => p[0])
320
+ const ys = points.map((p) => p[1])
321
+ const x0 = Math.max(0, Math.min(w - 1, Math.floor(Math.min(...xs))))
322
+ const y0 = Math.max(0, Math.min(h - 1, Math.floor(Math.min(...ys))))
323
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.ceil(Math.max(...xs))))
324
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.ceil(Math.max(...ys))))
325
+ const bw = x1 - x0
326
+ const bh = y1 - y0
327
+ let ctx = null
328
+ try {
329
+ if (typeof OffscreenCanvas === 'function') {
330
+ const canvas = new OffscreenCanvas(bw, bh)
331
+ ctx = canvas.getContext('2d', { willReadFrequently: true })
332
+ } else if (typeof document !== 'undefined') {
333
+ const canvas = document.createElement('canvas')
334
+ canvas.width = bw
335
+ canvas.height = bh
336
+ ctx = canvas.getContext('2d', { willReadFrequently: true })
337
+ }
338
+ } catch { ctx = null }
339
+ if (ctx !== null) {
340
+ ctx.fillStyle = '#000'
341
+ ctx.fillRect(0, 0, bw, bh)
342
+ ctx.fillStyle = '#fff'
343
+ ctx.beginPath()
344
+ ctx.moveTo(points[0][0] - x0, points[0][1] - y0)
345
+ for (let i = 1; i < points.length; i += 1) ctx.lineTo(points[i][0] - x0, points[i][1] - y0)
346
+ ctx.closePath()
347
+ ctx.fill()
348
+ const sub = ctx.getImageData(0, 0, bw, bh).data
349
+ for (let py = 0; py < bh; py += 1) {
350
+ for (let px = 0; px < bw; px += 1) {
351
+ if (sub[((py * bw) + px) * 4] > 127) out[((py + y0) * w) + (px + x0)] = 0
352
+ }
353
+ }
354
+ } else {
355
+ for (let py = y0; py < y1; py += 1) {
356
+ for (let px = x0; px < x1; px += 1) {
357
+ if (pointInPolygon(px + 0.5, py + 0.5, points)) out[(py * w) + px] = 0
358
+ }
359
+ }
360
+ }
361
+ return out
362
+ }
363
+
364
+ /* ------------------------------------------------------------------ *
365
+ * RGBA 主遮罩 PNG 编码器(v0.14.9 修复 canvas 预乘 alpha 丢 RGB)
366
+ *
367
+ * 本机实证:canvas 内部是预乘 alpha 存储,putImageData → convertToBlob 往返后,
368
+ * alpha=0 的选区内 RGB 会被清零(区内均值差 147.39),而 ComfyUI
369
+ * #369 LoadImageGoohai 的 IMAGE 输出需要原图 RGB。主遮罩必须直接从
370
+ * 「RGB 原图 + 只改过 alpha」的 ImageData 编 PNG,一次也不回写 canvas。
371
+ * ------------------------------------------------------------------ */
372
+
373
+ /** CRC-32(IEEE 802.3),PNG chunk 校验用。 */
374
+ function pngCrc32(bytes) {
375
+ let c = 0xffffffff
376
+ for (let i = 0; i < bytes.length; i += 1) {
377
+ c ^= bytes[i]
378
+ for (let k = 0; k < 8; k += 1) c = (c >>> 1) ^ (0xedb88320 & -(c & 1))
379
+ }
380
+ return (c ^ 0xffffffff) >>> 0
381
+ }
382
+
383
+ /** 组装一个 PNG chunk:长度 + 类型 + 数据 + CRC。 */
384
+ function pngChunk(type, data) {
385
+ const out = new Uint8Array(12 + data.length)
386
+ const view = new DataView(out.buffer)
387
+ view.setUint32(0, data.length)
388
+ for (let i = 0; i < 4; i += 1) out[4 + i] = type.charCodeAt(i)
389
+ out.set(data, 8)
390
+ view.setUint32(8 + data.length, pngCrc32(out.subarray(4, 8 + data.length)))
391
+ return out
392
+ }
393
+
394
+ /** ImageData → PNG 扫描线:每行前置 filter=0,RGBA 四通道原样搬运。 */
395
+ function pngScanlines(imageData, width, height) {
396
+ const src = imageData.data
397
+ const stride = width * 4
398
+ const out = new Uint8Array((stride + 1) * height)
399
+ let p = 0
400
+ for (let y = 0; y < height; y += 1) {
401
+ out[p] = 0
402
+ p += 1
403
+ out.set(src.subarray(y * stride, (y + 1) * stride), p)
404
+ p += stride
405
+ }
406
+ return out
407
+ }
408
+
409
+ /** Adler-32,zlib 尾部校验。 */
410
+ function pngAdler32(bytes) {
411
+ let a = 1
412
+ let b = 0
413
+ for (let i = 0; i < bytes.length; i += 1) {
414
+ a = (a + bytes[i]) % 65521
415
+ b = (b + a) % 65521
416
+ }
417
+ return ((b << 16) | a) >>> 0
418
+ }
419
+
420
+ /** 拼接若干 Uint8Array。 */
421
+ function pngConcat(parts) {
422
+ const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0))
423
+ let p = 0
424
+ for (const part of parts) { out.set(part, p); p += part.length }
425
+ return out
426
+ }
427
+
428
+ /** zlib「stored」无压缩流,同步兜底(CompressionStream 不可用时)。 */
429
+ function pngZlibStored(bytes) {
430
+ const parts = [new Uint8Array([0x78, 0x01])]
431
+ let off = 0
432
+ while (off < bytes.length) {
433
+ const len = Math.min(65535, bytes.length - off)
434
+ const last = off + len >= bytes.length ? 1 : 0
435
+ const blk = new Uint8Array(5 + len)
436
+ blk[0] = last
437
+ blk[1] = len & 0xff
438
+ blk[2] = (len >> 8) & 0xff
439
+ blk[3] = (~len) & 0xff
440
+ blk[4] = ((~len) >> 8) & 0xff
441
+ blk.set(bytes.subarray(off, off + len), 5)
442
+ parts.push(blk)
443
+ off += len
444
+ }
445
+ const tail = new Uint8Array(4)
446
+ new DataView(tail.buffer).setUint32(0, pngAdler32(bytes))
447
+ parts.push(tail)
448
+ return pngConcat(parts)
449
+ }
450
+
451
+ /**
452
+ * ImageData → RGBA PNG 字节。优先 CompressionStream('deflate') 出标准 zlib 流,
453
+ * 不可用则退回同步 stored 流;两条路都不经过 canvas,RGB 一像素不丢。
454
+ */
455
+ async function encodeMaskPngBytes(imageData, width, height) {
456
+ const w = Math.max(1, Math.round(Number(width) || 0))
457
+ const h = Math.max(1, Math.round(Number(height) || 0))
458
+ const ihdr = new Uint8Array(13)
459
+ const iv = new DataView(ihdr.buffer)
460
+ iv.setUint32(0, w)
461
+ iv.setUint32(4, h)
462
+ ihdr[8] = 8
463
+ ihdr[9] = 6
464
+ const raw = pngScanlines(imageData, w, h)
465
+ let idat = null
466
+ if (typeof CompressionStream === 'function' && typeof Blob === 'function' && typeof Response === 'function') {
467
+ try {
468
+ const stream = new Blob([raw]).stream().pipeThrough(new CompressionStream('deflate'))
469
+ idat = new Uint8Array(await new Response(stream).arrayBuffer())
470
+ } catch {
471
+ idat = null
472
+ }
473
+ }
474
+ if (idat === null) idat = pngZlibStored(raw)
475
+ return pngConcat([
476
+ new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),
477
+ pngChunk('IHDR', ihdr),
478
+ pngChunk('IDAT', idat),
479
+ pngChunk('IEND', new Uint8Array(0)),
480
+ ])
481
+ }
482
+
483
+
484
+ /** tab 类型的身份;也是正文与标题在 keyed slot 里的 key。 */
package/host/scan.js CHANGED
@@ -26,6 +26,23 @@ 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
+
29
46
  export function categoryForSessionAsset(autoCategory, externalAsset) {
30
47
  return autoCategory ?? (externalAsset ? ASSET_CATEGORY.INPUT : null)
31
48
 
@@ -274,6 +291,8 @@ export async function resolveSessionScope(config, sessionId, allRoots) {
274
291
  return {
275
292
  ok: true,
276
293
  reason: 'ok',
294
+ // 2026-11-15:同目录放宽只收本对话开始之后新出现 / 改动的文件
295
+ sessionStartMs,
277
296
  taskDirs: [...taskDirs],
278
297
  paths: normalized,
279
298
  relPaths,
@@ -329,8 +348,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
329
348
  // v0.14.7:会话引用过的目录集合。同目录下的外部图片也纳入「当前对话」,
330
349
  // 但不在精确路径白名单里 —— 它们会被自动标为「素材」(input)。
331
350
  let sessionDirSet = null
351
+ let sessionStartMs = 0
332
352
  if (isSession) {
333
353
  scopeInfo = await resolveSessionScope(config, sessionId, opts.roots)
354
+ sessionStartMs = Number(scopeInfo.sessionStartMs) || 0
334
355
  // 修法 B:用「精确相对路径」集合判定,而不是只靠第一层目录名。
335
356
  // 这样既能处理有子目录的情况,也能处理「文件直接躺在 root 根目录下」。
336
357
  sessionRelSet = new Set((scopeInfo.relPaths ?? []).map((p) => p.toLowerCase()))
@@ -379,23 +400,36 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
379
400
  }
380
401
  }
381
402
 
382
- // v0.14.8:全局资产下「当前对话」组也要认出外部素材。
383
- // 旧逻辑只在 scope=session 算 sessionDirs;全局模式只认会话日志 / frames.json
384
- // 精确引用过的文件,同目录里外部放进来、没被引用过的图全掉进「历史资产」
385
- // 并标「未归类」——界面上就表现为「当前对话」组只有几张过程稿、素材数为 0。
386
- // 这里复用与「当前对话」视图完全相同的目录判定,把无归属的同目录图片
387
- // 挂回当前对话组并标 input(素材);其它对话 / 历史资产一律不动。
403
+ // 2026-11-15:全局资产下置顶的「当前对话」组,必须和「当前对话」视图用同一把尺子。
404
+ // 旧做法把归属交给全库会话索引、谁最近算谁的:本对话明明能看见的图,
405
+ // 会被更早引用过它的老对话抢走(老板实测:全局 2 张、当前对话视图 4 张)。
406
+ // 现在先解析本对话范围(精确路径 + 用过的目录),符合的资产一律归本对话组;
407
+ // 其余仍按会话索引 / 登记归属,历史资产口径不变。
388
408
  let globalCurrentDirs = null
389
409
  let globalCurrentMeta = null
410
+ let globalCurrentExactRels = null
411
+ let globalCurrentCategory = null
412
+ let globalCurrentStartMs = 0
390
413
  if (!isSession && sessionId !== '') {
391
414
  const current = await resolveSessionScope(config, sessionId, opts.roots)
392
415
  if (current.ok) {
416
+ globalCurrentStartMs = Number(current.sessionStartMs) || 0
393
417
  const dirs = new Set((current.sessionDirs ?? []).map((d) => String(d).toLowerCase()))
394
- // 本对话截帧 / 遮罩的登记目录也算(与 session 模式保持一致)
418
+ const exactRels = new Set((current.relPaths ?? []).map((p) => String(p).toLowerCase()))
419
+ const categoryByRel = new Map()
420
+ for (const [rel, cat] of (current.categoryByRel instanceof Map ? current.categoryByRel : new Map())) {
421
+ categoryByRel.set(String(rel).toLowerCase(), cat)
422
+ }
423
+ // 本对话截帧 / 遮罩的登记目录与精确路径也算(与 session 模式保持一致)
395
424
  for (const [rel, f] of frameByRel) {
396
- if (String(f.sessionId ?? '') === sessionId) dirs.add(parentDirOf(rel))
425
+ if (String(f.sessionId ?? '') !== sessionId) continue
426
+ dirs.add(parentDirOf(rel))
427
+ exactRels.add(String(rel).toLowerCase())
428
+ categoryByRel.set(String(rel).toLowerCase(), frameCategoryOf(f))
397
429
  }
398
430
  globalCurrentDirs = dirs
431
+ globalCurrentExactRels = exactRels
432
+ globalCurrentCategory = categoryByRel
399
433
  // 会话索引里可能没有该会话(日志里没有落在扫描目录内的产出),
400
434
  // 这时组名会退化成 sessionId 前 8 位。frames.json 的登记带会话标题,补上。
401
435
  const indexed = sessionIndex?.get(sessionId) ?? null
@@ -476,9 +510,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
476
510
  // 当前对话:精确路径白名单优先;不在白名单但落在「本对话用过的目录」里,
477
511
  // 视作外部放进来的素材放行(v0.14.7)。其它目录一律不进当前对话。
478
512
  let externalAsset = false
513
+ let looseDirHit = false
479
514
  if (sessionRelSet !== null && !sessionRelSet.has(relPath.toLowerCase())) {
480
515
  if (sessionDirSet === null || !sessionDirSet.has(parentDirOf(relPath))) continue
481
- externalAsset = true
516
+ looseDirHit = true
482
517
  }
483
518
  let stat
484
519
  try {
@@ -486,6 +521,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
486
521
  } catch {
487
522
  continue
488
523
  }
524
+ // 2026-11-15:同目录放宽只收本对话期间新出现 / 改动的图;
525
+ // 否则只读查一次图,就会把该目录里几百张历史图全算进这个新对话。
526
+ if (looseDirHit && !isFreshSince(stat, sessionStartMs)) continue
527
+ if (looseDirHit) externalAsset = true
489
528
  if (stat.size <= 0 || stat.mtimeMs < cutoff) continue
490
529
  // 音视频:超过体积上限的直接跳过(视频可能几百 MB,列出来点开就卡)
491
530
  if (isMedia && stat.size > opts.maxMediaBytes) continue
@@ -499,6 +538,9 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
499
538
  name: entryName,
500
539
  size: stat.size,
501
540
  mtime: stat.mtimeMs,
541
+ // 手工拷贝旧文件时 mtime 仍是老的,但创建时间是新的;
542
+ // 两个视图的同目录放宽判据都看它,不能只给 mtime 造成一边有一边没有。
543
+ birthtimeMs: stat.birthtimeMs,
502
544
  extension: ext,
503
545
  // v0.14.7:外部素材标记,扫描阶段据此给出「素材」标签
504
546
  ...(externalAsset ? { externalAsset: true } : {}),
@@ -572,20 +614,25 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
572
614
  // 手动改过的标签在下面仍然优先覆盖,刷新/重扫/重启都不回退。
573
615
  item.category = categoryForSessionAsset(autoCategory, item.externalAsset)
574
616
  item.sessionId = sessionId
617
+ } else if (globalCurrentExactRels !== null
618
+ && (globalCurrentExactRels.has(item.relPath.toLowerCase())
619
+ || (globalCurrentDirs !== null && globalCurrentDirs.has(parentDirOf(item.relPath))
620
+ && isFreshSince({ mtimeMs: item.mtime, birthtimeMs: item.birthtimeMs }, globalCurrentStartMs)))) {
621
+ // 2026-11-15:本对话日志精确引用过、或落在本对话用过的目录里的资产,
622
+ // 一律归到全局置顶的「当前对话」组;历史会话索引不能再把它抢走。
623
+ // 分类与「当前对话」视图完全一致:精确命中用日志判定,目录命中按外部素材标 input。
624
+ const relKey = item.relPath.toLowerCase()
625
+ const exact = globalCurrentExactRels.has(relKey)
626
+ item.category = categoryForSessionAsset(globalCurrentCategory?.get(relKey), !exact)
627
+ if (!exact) item.externalAsset = true
628
+ item.sessionId = sessionId
629
+ item.sessionTitle = globalCurrentMeta?.title ?? ''
630
+ item.sessionCreatedAt = globalCurrentMeta?.createdAt ?? 0
575
631
  } else if (owner !== undefined) {
576
632
  item.category = owner.category
577
633
  item.sessionId = owner.sessionId
578
634
  item.sessionTitle = owner.title
579
635
  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
636
  } else {
590
637
  // 不属于任何已知对话、也不在当前对话目录里的文件:归到「历史资产」,
591
638
  // 分类记为**未归类**。不能兜底成 input —— 那会把几千个历史文件全标成「输入」
@@ -650,6 +697,10 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
650
697
  size: item.size,
651
698
  name: item.name,
652
699
  extension: item.extension,
700
+ // 阶段 2:分组明细补齐遮罩关联与「手动改过标签」,
701
+ // 让 Agent 拿到的信息和人双击写进输入框拿到的完全一致。
702
+ ...(item.maskOf !== undefined ? { maskOf: item.maskOf } : {}),
703
+ categoryManual: item.categoryManual === true,
653
704
  // 音视频类型(video / audio),客户端据此选 <video> 还是 <audio>
654
705
  ...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
655
706
  // 截帧来源:反馈篮与草稿正文据此写清取自哪段视频的哪一帧
@@ -671,6 +722,8 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
671
722
  subSessions: scopeInfo.subSessions ?? 0,
672
723
  // v0.14.7:本对话用过的目录数 / 自动纳入的外部素材数(诊断用)
673
724
  // v0.14.8:全局模式另给一份目录数,两种视图口径是否一致一眼可查
725
+ sessionStartMs,
726
+ globalCurrentStartMs,
674
727
  externalDirs: sessionDirSet?.size ?? 0,
675
728
  globalExternalDirs: globalCurrentDirs?.size ?? 0,
676
729
  externalAssets: matches.reduce((n, i) => n + (i.externalAsset ? 1 : 0), 0),
@@ -685,6 +738,17 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
685
738
  generatedAt: now,
686
739
  items: visible,
687
740
  total,
741
+ // 2026-11-15:分类小数字按「本视图全部」算,不能只数第一页 60 张。
742
+ // 全局视图靠 groups[].counts,当前对话视图没有 groups,前端以前只能数 items,
743
+ // 结果与全局「当前对话」组的小标签对不上(老板 19:18 实测报的)。
744
+ counts: (() => {
745
+ const c = { final: 0, input: 0, intermediate: 0, unknown: 0 }
746
+ for (const m of matches) {
747
+ const k = String(m?.category ?? 'unknown')
748
+ if (Object.prototype.hasOwnProperty.call(c, k)) c[k] += 1
749
+ }
750
+ return c
751
+ })(),
688
752
  // 分页信息,客户端据此渲染页码条
689
753
  page: safePage,
690
754
  pageCount,
@@ -693,8 +757,11 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
693
757
  hidden: Math.max(0, total - visible.length),
694
758
  rootMissing,
695
759
  scan: { directories, entries, capped },
696
- // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)
697
- groups: isSession ? null : buildGroups(allItemsSummary, 120, sessionId, sessionStates),
760
+ // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)。
761
+ // 🔴 明细一次算全(全量留在服务端缓存),不再按 120 条截断:
762
+ // 历史组有 5000+ 张,截断后旧图永远翻不到。
763
+ // 响应由 host/http.js 瘦身成每组 60 张,前端点「再显示」再按需取下一批。
764
+ groups: isSession ? null : buildGroups(allItemsSummary, Number.MAX_SAFE_INTEGER, sessionId, sessionStates),
698
765
  }
699
766
  }
700
767
 
@@ -711,9 +778,9 @@ export async function scanGallery(config, kind = 'image', scope = 'global', sess
711
778
  * 2. 其余对话按创建时间倒序。
712
779
  * 3. 「历史资产」永远最后。
713
780
  *
714
- * ⚠️ 体积控制:每组只返回前 maxPerGroup 条明细 + 完整总数。
715
- * 为什么必须截断:历史组有 4995 个文件,全量返回会让单次响应达到 1.3 MB,
716
- * 前端解析/渲染都会卡,面板看起来「只显示两组」。
781
+ * ⚠️ 明细一次给全(调用方传极大 maxPerGroup):历史组有 5000+ 个文件,
782
+ * 以前每组截断到 120 条,旧图永远翻不到。现在由前端渐进渲染控制画面里的
783
+ * 卡片数量;单次响应约 1.5 MB,解析开销远小于「几千张卡同时进画面」。
717
784
  *
718
785
  * @param summary - 扁平资产摘要数组。
719
786
  * @param maxPerGroup - 每组最多返回多少条明细(默认 120)。