dsh-gallery 0.11.2 → 0.12.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/CHANGELOG.md +233 -0
- package/README.md +43 -10
- package/client.js +179 -52
- package/host/classify.js +70 -0
- package/host/constants.js +133 -0
- package/host/fsutil.js +136 -0
- package/host/groups.js +92 -0
- package/host/http.js +785 -0
- package/host/media.js +122 -0
- package/host/protocol.js +25 -0
- package/host/scan.js +531 -0
- package/host/session-index.js +187 -0
- package/host/session.js +192 -0
- package/host/settings.js +232 -0
- package/index.js +23 -1813
- package/package.json +8 -2
- package/session-index.js +7 -187
package/index.js
CHANGED
|
@@ -1,1823 +1,33 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 产出画廊 —— Host
|
|
2
|
+
* 产出画廊 · DSH 插件 —— Host 半入口。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* S1 拆分后本文件只做三件事:
|
|
5
|
+
* 1. 声明 inject
|
|
6
|
+
* 2. 把 config 交给各模块
|
|
7
|
+
* 3. 注册两条路由
|
|
8
8
|
*
|
|
9
|
-
*
|
|
9
|
+
* 实际逻辑分布在 host/ 下:
|
|
10
|
+
* constants.js 常量与默认值
|
|
11
|
+
* fsutil.js 路径/文件头/图片尺寸
|
|
12
|
+
* settings.js 设置读写 + 根目录探测 + 配置解析
|
|
13
|
+
* session.js 会话日志读取(zstd 多帧)
|
|
14
|
+
* classify.js 资产分类
|
|
15
|
+
* scan.js 扫描与分页
|
|
16
|
+
* groups.js 按对话分组
|
|
17
|
+
* media.js Range / 流式 / MIME
|
|
18
|
+
* http.js 路由注册
|
|
10
19
|
*/
|
|
11
|
-
import { promises as fsp, readFileSync, statSync, createReadStream } from 'node:fs'
|
|
12
|
-
import os from 'node:os'
|
|
13
|
-
import path from 'node:path'
|
|
14
|
-
import { Readable } from 'node:stream'
|
|
15
|
-
import { zstdDecompressSync } from 'node:zlib'
|
|
16
|
-
import { buildSessionIndex, clearSessionIndexCache } from './session-index.js'
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
export const ROUTE = '/api/dsh-gallery'
|
|
21
|
+
import { registerMediaRoute, registerOpsRoute } from './host/http.js'
|
|
20
22
|
|
|
21
|
-
/** 音视频直链(GET):给 <video>/<audio> 用,支持 Range。 */
|
|
22
|
-
export const MEDIA_ROUTE = '/api/dsh-gallery/media'
|
|
23
|
-
|
|
24
|
-
/** 媒体直链的分块阈值:小于它整块返回,大于它走 Range 分块(避免大视频读满内存)。 */
|
|
25
|
-
const STREAM_THRESHOLD = 8 * 1024 * 1024
|
|
26
|
-
|
|
27
|
-
/** DSH 主目录:优先环境变量,回退 ~/.dsh。 */
|
|
28
|
-
const DSH_HOME = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
29
|
-
|
|
30
|
-
/** 会话日志根目录(DSH 主目录下的 sessions)。 */
|
|
31
|
-
const DEFAULT_SESSIONS_DIR = path.join(DSH_HOME, 'sessions')
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* 运行时配置文件的默认位置。
|
|
35
|
-
* 用户可在面板内直接改产出根目录,改动写这里;
|
|
36
|
-
* 它的优先级高于 cordis.patch.yml,低于用户显式传入的 root。
|
|
37
|
-
*/
|
|
38
|
-
const DEFAULT_SETTINGS_FILE = path.join(DSH_HOME, 'dsh-gallery.json')
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 会话日志里,哪些工具调用的参数算「本对话的产出」。
|
|
42
|
-
*
|
|
43
|
-
* 分三类:
|
|
44
|
-
* 1. **直接写文件**:write / edit / present 等 —— 路径一定是产出。
|
|
45
|
-
* 2. **脚本产出**:Python/命令行脚本跑出来的图,不在 write 调用里,
|
|
46
|
-
* 但 Agent 一定会用 read_image 打开它看效果 —— 所以「看过的图」也算产出。
|
|
47
|
-
* 这是「过程中即时可见」的关键:不然脚本生成的中间图和成品图都看不见。
|
|
48
|
-
* 3. **不看文件**:read / grep / glob 等纯读取,不算产出(避免把别人的文件算进来)。
|
|
49
|
-
*/
|
|
50
|
-
const OUTPUT_TOOLS = new Set([
|
|
51
|
-
'write',
|
|
52
|
-
'edit',
|
|
53
|
-
'present',
|
|
54
|
-
'dsh_im_return_file',
|
|
55
|
-
'ops_write_file',
|
|
56
|
-
'ops_edit_file',
|
|
57
|
-
])
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* 「Agent 看过的图片」也算本对话产出。
|
|
61
|
-
* 只对图片生效(read_image 的参数就是图片路径),风险低:
|
|
62
|
-
* Agent 不会无缘无故打开一张与任务无关的图。
|
|
63
|
-
*/
|
|
64
|
-
const VIEW_TOOLS = new Set(['read_image'])
|
|
65
|
-
|
|
66
|
-
/** 只从 VIEW_TOOLS 里接受的图片扩展名。 */
|
|
67
|
-
const VIEW_IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.avif', '.tif', '.tiff'])
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* 命令执行类工具。它参数里的路径只作为「弱证据」:
|
|
71
|
-
* 出现在命令文本里 → 该文件是被处理过的,不算「纯输入」。
|
|
72
|
-
*/
|
|
73
|
-
const BASH_TOOLS = new Set(['ops_bash', 'pwsh', 'bash'])
|
|
74
|
-
|
|
75
|
-
/** zstd 帧起始魔数(小端 0x28B52FFD)。一个 .zstd 文件可能由多帧拼接而成。 */
|
|
76
|
-
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* 自动探测产出根目录(当用户既没配 root、也没有运行时配置时使用)。
|
|
80
|
-
*
|
|
81
|
-
* 策略:先找相对用户主目录的常见位置,再遍历可用盘符找 \DSH产出。
|
|
82
|
-
* 关键点:**代码里不出现任何写死的盘符**(是用循环遍历 A-Z 探测),
|
|
83
|
-
* 所以发布到别人机器上不会指向一个必然存在的错误路径,同时又能自动找到
|
|
84
|
-
* 装在其他盘上的产出目录。
|
|
85
|
-
*
|
|
86
|
-
* 探测结果会缓存 —— detectDefaultRoot 在每次请求的 resolveOptions 里都会被调用,
|
|
87
|
-
* 而遍历盘符涉及多次 stat,没必要每次都做。
|
|
88
|
-
*/
|
|
89
|
-
let defaultRootCache = null
|
|
90
|
-
|
|
91
|
-
function detectDefaultRoot() {
|
|
92
|
-
if (defaultRootCache !== null) return defaultRootCache
|
|
93
|
-
|
|
94
|
-
const home = os.homedir()
|
|
95
|
-
const candidates = [
|
|
96
|
-
// 1. 用户主目录下
|
|
97
|
-
path.join(home, 'DSH产出'),
|
|
98
|
-
path.join(home, 'DSH-outputs'),
|
|
99
|
-
// 2. 文档下
|
|
100
|
-
path.join(home, 'Documents', 'DSH产出'),
|
|
101
|
-
path.join(home, 'Documents', 'DSH-outputs'),
|
|
102
|
-
// 3. 桌面下
|
|
103
|
-
path.join(home, 'Desktop', 'DSH产出'),
|
|
104
|
-
// 4. 下载目录下
|
|
105
|
-
path.join(home, 'Downloads', 'DSH产出'),
|
|
106
|
-
]
|
|
107
|
-
|
|
108
|
-
// 5. 遍历可用盘符(Windows):C:\DSH产出、D:\DSH产出 …… 不写死任何字母
|
|
109
|
-
if (process.platform === 'win32') {
|
|
110
|
-
for (let code = 67; code <= 90; code += 1) { // C(67) → Z(90)
|
|
111
|
-
const drive = String.fromCharCode(code) + ':'
|
|
112
|
-
candidates.push(path.join(drive + path.sep, 'DSH产出'))
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
for (const candidate of candidates) {
|
|
117
|
-
try {
|
|
118
|
-
if (statSync(candidate).isDirectory()) {
|
|
119
|
-
defaultRootCache = candidate
|
|
120
|
-
return candidate
|
|
121
|
-
}
|
|
122
|
-
} catch {
|
|
123
|
-
// 不存在就试下一个
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// 全都不存在:返回第一个候选,让面板显示「目录不存在」并给出修改入口
|
|
128
|
-
defaultRootCache = candidates[0]
|
|
129
|
-
return defaultRootCache
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** 视频扩展名(与 DEFAULTS.mediaExtensions 里的音频部分相对)。 */
|
|
133
|
-
const VIDEO_EXTS = new Set([
|
|
134
|
-
'.mp4', '.webm', '.mov', '.m4v', '.mkv', '.avi', '.ogv',
|
|
135
|
-
])
|
|
136
|
-
|
|
137
|
-
const DEFAULTS = {
|
|
138
|
-
// 扫描时间窗口(小时)。默认一年:全局资产要能覆盖历史对话,
|
|
139
|
-
// 否则「按对话分组」看不到旧成果。24 小时会把历史全滤掉。
|
|
140
|
-
windowHours: 24 * 365,
|
|
141
|
-
maxItems: 60,
|
|
142
|
-
maxDepth: 3,
|
|
143
|
-
extensions: ['.png', '.jpg', '.jpeg', '.webp'],
|
|
144
|
-
/**
|
|
145
|
-
* 音视频画廊(v0.10.1):视频 + 音频,独立一个 kind。
|
|
146
|
-
* 用浏览器原生 <video>/<audio> 播放,不引入 ffmpeg 等后端转码,保持零依赖。
|
|
147
|
-
* 体积大的片子先不进列表(见 maxMediaBytes),避免一次性拉几十 MB 把面板卡死。
|
|
148
|
-
*/
|
|
149
|
-
mediaExtensions: [
|
|
150
|
-
// 视频
|
|
151
|
-
'.mp4', '.webm', '.mov', '.m4v', '.mkv', '.avi', '.ogv',
|
|
152
|
-
// 音频
|
|
153
|
-
'.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.oga', '.opus', '.wma',
|
|
154
|
-
],
|
|
155
|
-
/** 单个音视频文件的大小上限(字节)。超过就不列,避免加载卡顿。 */
|
|
156
|
-
maxMediaBytes: 200 * 1024 * 1024,
|
|
157
|
-
/**
|
|
158
|
-
* 文件画廊:只放「产出文件」——文档、代码、数据、压缩包、链接。
|
|
159
|
-
* 不收任何图片格式(图片归图片画廊),也不收音视频(音视频有独立画廊)。
|
|
160
|
-
*/
|
|
161
|
-
fileExtensions: [
|
|
162
|
-
'.md', '.markdown', '.txt', '.log',
|
|
163
|
-
'.json', '.jsonl', '.csv', '.tsv', '.yaml', '.yml', '.xml', '.toml',
|
|
164
|
-
'.pdf', '.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.rtf', '.odt',
|
|
165
|
-
'.html', '.htm', '.mht',
|
|
166
|
-
'.zip', '.7z', '.rar', '.tar', '.gz',
|
|
167
|
-
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx',
|
|
168
|
-
'.ps1', '.sh', '.bat', '.cmd', '.sql', '.ipynb',
|
|
169
|
-
'.url', '.lnk', '.webloc',
|
|
170
|
-
'.dxf', '.dwg', '.skp', '.3dm',
|
|
171
|
-
],
|
|
172
|
-
skipDirs: [
|
|
173
|
-
'library_merged',
|
|
174
|
-
'node_modules',
|
|
175
|
-
'.git',
|
|
176
|
-
'.svn',
|
|
177
|
-
'$RECYCLE.BIN',
|
|
178
|
-
'System Volume Information',
|
|
179
|
-
'__pycache__',
|
|
180
|
-
'.venv',
|
|
181
|
-
'venv',
|
|
182
|
-
'.cache',
|
|
183
|
-
],
|
|
184
|
-
maxDirectories: 4000,
|
|
185
|
-
maxEntries: 60000,
|
|
186
|
-
maxImageBytes: 64 * 1024 * 1024,
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** 读取运行时配置文件(<DSH_HOME>/dsh-gallery.json);不存在或损坏返回空对象。 */
|
|
190
|
-
function readSettingsFile(file) {
|
|
191
|
-
try {
|
|
192
|
-
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
193
|
-
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
|
|
194
|
-
} catch {
|
|
195
|
-
return {}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* 读取「已隐藏」的相对路径集合。
|
|
201
|
-
* 隐藏只记录路径,不移动/删除文件;列表扫描时按此过滤。
|
|
202
|
-
* @param settingsFile - 配置文件路径。
|
|
203
|
-
* @returns 规范化(正斜杠)后的相对路径数组。
|
|
204
|
-
*/
|
|
205
|
-
async function readHiddenList(settingsFile) {
|
|
206
|
-
const stored = readSettingsFile(settingsFile)
|
|
207
|
-
if (!Array.isArray(stored.hidden)) return []
|
|
208
|
-
return stored.hidden
|
|
209
|
-
.filter((p) => typeof p === 'string' && p !== '')
|
|
210
|
-
.map((p) => p.replace(/\\/g, '/'))
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* 解析最终配置。扫描目录(roots)的优先级(高 → 低):
|
|
215
|
-
* 1. 运行时配置文件的 roots 数组(面板内可加多个目录)
|
|
216
|
-
* 2. 运行时配置文件的 root(旧版单目录写法,兼容保留)
|
|
217
|
-
* 3. cordis.patch.yml 里配的 root / roots
|
|
218
|
-
* 4. 自动探测(detectDefaultRoot)
|
|
219
|
-
*
|
|
220
|
-
* 为什么支持多目录:DSH 一个会话一个 cwd,产出可能写在任意工作区下
|
|
221
|
-
* (例如 G:\DSH任务文件\xxx),不一定落在 G:\DSH产出。只配一个目录必然漏。
|
|
222
|
-
*/
|
|
223
|
-
function resolveOptions(config) {
|
|
224
|
-
const merged = { ...DEFAULTS, ...(config ?? {}) }
|
|
225
|
-
const settingsFile = String(merged.settingsFile ?? DEFAULT_SETTINGS_FILE)
|
|
226
|
-
const stored = readSettingsFile(settingsFile)
|
|
227
|
-
|
|
228
|
-
// 收集所有候选目录
|
|
229
|
-
const collected = []
|
|
230
|
-
const pushRoot = (value) => {
|
|
231
|
-
if (typeof value === 'string' && value.trim() !== '') collected.push(value.trim())
|
|
232
|
-
}
|
|
233
|
-
const pushList = (value) => {
|
|
234
|
-
if (Array.isArray(value)) for (const v of value) pushRoot(v)
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
pushList(stored.roots) // 1. 设置里的多目录
|
|
238
|
-
pushRoot(stored.root) // 2. 设置里的单目录(旧格式)
|
|
239
|
-
pushList(merged.roots) // 3. YAML 多目录
|
|
240
|
-
pushRoot(merged.root) // 4. YAML 单目录
|
|
241
|
-
|
|
242
|
-
// 去重(Windows 路径大小写不敏感)
|
|
243
|
-
const deduped = []
|
|
244
|
-
const seenRoots = new Set()
|
|
245
|
-
const candidates = collected.length > 0 ? collected : [detectDefaultRoot()]
|
|
246
|
-
for (const r of candidates) {
|
|
247
|
-
const abs = path.resolve(r)
|
|
248
|
-
const key = abs.toLowerCase()
|
|
249
|
-
if (seenRoots.has(key)) continue
|
|
250
|
-
seenRoots.add(key)
|
|
251
|
-
deduped.push(abs)
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
const resolvedRoots = deduped.length > 0 ? deduped : [path.resolve(detectDefaultRoot())]
|
|
255
|
-
const rootSource = collected.length === 0
|
|
256
|
-
? 'auto-detect'
|
|
257
|
-
: (typeof stored.root === 'string' || (Array.isArray(stored.roots) && stored.roots.length > 0) ? 'settings' : 'config')
|
|
258
|
-
|
|
259
|
-
return {
|
|
260
|
-
root: resolvedRoots[0],
|
|
261
|
-
roots: resolvedRoots,
|
|
262
|
-
rootSource,
|
|
263
|
-
settingsFile,
|
|
264
|
-
windowHours: numberOr(merged.windowHours, DEFAULTS.windowHours, 1, 24 * 366),
|
|
265
|
-
maxItems: numberOr(merged.maxItems, DEFAULTS.maxItems, 1, 500),
|
|
266
|
-
maxDepth: numberOr(merged.maxDepth, DEFAULTS.maxDepth, 0, 8),
|
|
267
|
-
extensions: arrayOfStrings(merged.extensions, DEFAULTS.extensions).map((e) => e.toLowerCase()),
|
|
268
|
-
fileExtensions: arrayOfStrings(merged.fileExtensions, DEFAULTS.fileExtensions).map((e) => e.toLowerCase()),
|
|
269
|
-
mediaExtensions: arrayOfStrings(merged.mediaExtensions, DEFAULTS.mediaExtensions).map((e) => e.toLowerCase()),
|
|
270
|
-
skipDirs: arrayOfStrings(merged.skipDirs, DEFAULTS.skipDirs).map((e) => e.toLowerCase()),
|
|
271
|
-
maxDirectories: numberOr(merged.maxDirectories, DEFAULTS.maxDirectories, 1, 200000),
|
|
272
|
-
maxEntries: numberOr(merged.maxEntries, DEFAULTS.maxEntries, 1, 1000000),
|
|
273
|
-
maxImageBytes: numberOr(merged.maxImageBytes, DEFAULTS.maxImageBytes, 1, 512 * 1024 * 1024),
|
|
274
|
-
maxMediaBytes: numberOr(merged.maxMediaBytes, DEFAULTS.maxMediaBytes, 1, 1024 * 1024 * 1024),
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
function numberOr(value, fallback, min, max) {
|
|
279
|
-
const n = typeof value === 'number' ? value : Number(value)
|
|
280
|
-
if (!Number.isFinite(n)) return fallback
|
|
281
|
-
return Math.min(Math.max(Math.trunc(n), min), max)
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
function arrayOfStrings(value, fallback) {
|
|
285
|
-
if (!Array.isArray(value)) return [...fallback]
|
|
286
|
-
const cleaned = value.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
|
|
287
|
-
return cleaned.length > 0 ? cleaned : [...fallback]
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/** Windows 路径比较统一小写;用于「必须在根目录内」的判定。 */
|
|
291
|
-
function isInside(root, target) {
|
|
292
|
-
const a = root.toLowerCase().replace(/[\\/]+$/, '')
|
|
293
|
-
const b = target.toLowerCase().replace(/[\\/]+$/, '')
|
|
294
|
-
return b === a || b.startsWith(a + '\\') || b.startsWith(a + '/')
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/** 只读图片头部若干字节,用于解析尺寸;失败返回 null。 */
|
|
298
|
-
async function readHead(fullPath, byteLimit) {
|
|
299
|
-
let handle
|
|
300
|
-
try {
|
|
301
|
-
handle = await fsp.open(fullPath, 'r')
|
|
302
|
-
const size = (await handle.stat()).size
|
|
303
|
-
const want = Math.min(byteLimit, size)
|
|
304
|
-
const buffer = Buffer.alloc(want)
|
|
305
|
-
const { bytesRead } = await handle.read(buffer, 0, want, 0)
|
|
306
|
-
return buffer.subarray(0, bytesRead)
|
|
307
|
-
} catch {
|
|
308
|
-
return null
|
|
309
|
-
} finally {
|
|
310
|
-
if (handle !== undefined) await handle.close().catch(() => {})
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/** PNG:IHDR 在固定偏移。 */
|
|
315
|
-
function pngSize(buf) {
|
|
316
|
-
if (buf.length < 24) return null
|
|
317
|
-
if (buf[0] !== 0x89 || buf[1] !== 0x50 || buf[2] !== 0x4e || buf[3] !== 0x47) return null
|
|
318
|
-
const width = buf.readUInt32BE(16)
|
|
319
|
-
const height = buf.readUInt32BE(20)
|
|
320
|
-
return width > 0 && height > 0 ? { width, height } : null
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/** JPEG:顺序找 SOF 段。 */
|
|
324
|
-
function jpegSize(buf) {
|
|
325
|
-
if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null
|
|
326
|
-
let p = 2
|
|
327
|
-
while (p + 9 < buf.length) {
|
|
328
|
-
if (buf[p] !== 0xff) {
|
|
329
|
-
p += 1
|
|
330
|
-
continue
|
|
331
|
-
}
|
|
332
|
-
let marker = buf[p + 1]
|
|
333
|
-
while (marker === 0xff && p + 1 < buf.length) {
|
|
334
|
-
p += 1
|
|
335
|
-
marker = buf[p + 1]
|
|
336
|
-
}
|
|
337
|
-
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
|
338
|
-
p += 2
|
|
339
|
-
continue
|
|
340
|
-
}
|
|
341
|
-
if (marker === 0xd9 || marker === 0xda) return null
|
|
342
|
-
const length = buf.readUInt16BE(p + 2)
|
|
343
|
-
if (length < 2) return null
|
|
344
|
-
const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
|
|
345
|
-
if (isSof) {
|
|
346
|
-
const height = buf.readUInt16BE(p + 5)
|
|
347
|
-
const width = buf.readUInt16BE(p + 7)
|
|
348
|
-
return width > 0 && height > 0 ? { width, height } : null
|
|
349
|
-
}
|
|
350
|
-
p += 2 + length
|
|
351
|
-
}
|
|
352
|
-
return null
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
/** WebP:RIFF 容器,VP8 / VP8L / VP8X 三种尺寸布局。 */
|
|
356
|
-
function webpSize(buf) {
|
|
357
|
-
if (buf.length < 32) return null
|
|
358
|
-
if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WEBP') return null
|
|
359
|
-
const chunk = buf.toString('ascii', 12, 16)
|
|
360
|
-
if (chunk === 'VP8 ') {
|
|
361
|
-
const width = buf.readUInt16LE(26) & 0x3fff
|
|
362
|
-
const height = buf.readUInt16LE(28) & 0x3fff
|
|
363
|
-
return width > 0 && height > 0 ? { width, height } : null
|
|
364
|
-
}
|
|
365
|
-
if (chunk === 'VP8L') {
|
|
366
|
-
const b0 = buf[21]
|
|
367
|
-
const b1 = buf[22]
|
|
368
|
-
const b2 = buf[23]
|
|
369
|
-
const b3 = buf[24]
|
|
370
|
-
const width = 1 + (((b0 & 0xff) | ((b1 & 0x3f) << 8)) & 0x3fff)
|
|
371
|
-
const height = 1 + ((((b1 & 0xc0) >> 6) | (b2 << 2) | ((b3 & 0x0f) << 10)) & 0x3fff)
|
|
372
|
-
return width > 0 && height > 0 ? { width, height } : null
|
|
373
|
-
}
|
|
374
|
-
if (chunk === 'VP8X') {
|
|
375
|
-
const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16))
|
|
376
|
-
const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16))
|
|
377
|
-
return width > 0 && height > 0 ? { width, height } : null
|
|
378
|
-
}
|
|
379
|
-
return null
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/** 按扩展名挑选解析器;返回 {width,height} 或 null。 */
|
|
383
|
-
function measureImage(buf, ext) {
|
|
384
|
-
try {
|
|
385
|
-
if (buf === null) return null
|
|
386
|
-
if (ext === '.png') return pngSize(buf)
|
|
387
|
-
if (ext === '.jpg' || ext === '.jpeg') return jpegSize(buf)
|
|
388
|
-
if (ext === '.webp') return webpSize(buf)
|
|
389
|
-
return pngSize(buf) ?? jpegSize(buf) ?? webpSize(buf)
|
|
390
|
-
} catch {
|
|
391
|
-
return null
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
/**
|
|
396
|
-
* 校验用户想设的产出根目录:必须是绝对路径、必须存在、必须是目录。
|
|
397
|
-
* @param candidate - 用户输入的路径。
|
|
398
|
-
* @returns { ok, root?, reason? } —— 通过时 root 是规范化后的绝对路径。
|
|
399
|
-
*/
|
|
400
|
-
export async function validateRootCandidate(candidate) {
|
|
401
|
-
if (typeof candidate !== 'string' || candidate.trim() === '') {
|
|
402
|
-
return { ok: false, reason: 'empty' }
|
|
403
|
-
}
|
|
404
|
-
const raw = candidate.trim()
|
|
405
|
-
// 只接受绝对路径(盘符或 UNC),相对路径无法确定含义
|
|
406
|
-
if (!path.isAbsolute(raw)) return { ok: false, reason: 'not-absolute' }
|
|
407
|
-
const resolved = path.resolve(raw)
|
|
408
|
-
try {
|
|
409
|
-
const st = await fsp.stat(resolved)
|
|
410
|
-
if (!st.isDirectory()) return { ok: false, reason: 'not-directory' }
|
|
411
|
-
} catch {
|
|
412
|
-
return { ok: false, reason: 'not-found' }
|
|
413
|
-
}
|
|
414
|
-
return { ok: true, root: resolved }
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/**
|
|
418
|
-
* 把设置写进运行时配置文件。
|
|
419
|
-
* 只覆盖传入的字段,其余保留——避免把 windowHours 之类顺手清掉。
|
|
420
|
-
* @param settingsFile - 配置文件路径。
|
|
421
|
-
* @param patch - 要合并进去的部分设置。
|
|
422
|
-
*/
|
|
423
|
-
export async function writeSettingsFile(settingsFile, patch) {
|
|
424
|
-
const current = readSettingsFile(settingsFile)
|
|
425
|
-
const next = { ...current, ...patch }
|
|
426
|
-
await fsp.mkdir(path.dirname(settingsFile), { recursive: true })
|
|
427
|
-
await fsp.writeFile(settingsFile, JSON.stringify(next, null, 2), 'utf8')
|
|
428
|
-
return next
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
/**
|
|
432
|
-
* 返回设置面板需要的全部信息。
|
|
433
|
-
* @param config - 插件配置。
|
|
434
|
-
*/
|
|
435
|
-
async function readSettingsPayload(config) {
|
|
436
|
-
const opts = resolveOptions(config)
|
|
437
|
-
// 逐个检查每个 root 是否存在
|
|
438
|
-
const rootsInfo = []
|
|
439
|
-
for (const r of opts.roots) {
|
|
440
|
-
let exists = false
|
|
441
|
-
try {
|
|
442
|
-
exists = (await fsp.stat(r)).isDirectory()
|
|
443
|
-
} catch {
|
|
444
|
-
exists = false
|
|
445
|
-
}
|
|
446
|
-
rootsInfo.push({ path: r, exists })
|
|
447
|
-
}
|
|
448
|
-
const exists = rootsInfo.length > 0 ? rootsInfo[0].exists : false
|
|
449
|
-
// 已隐藏条数:供设置面板显示「已隐藏 N 个 · 全部恢复」
|
|
450
|
-
const hidden = await readHiddenList(opts.settingsFile)
|
|
451
|
-
return {
|
|
452
|
-
root: opts.root,
|
|
453
|
-
roots: opts.roots,
|
|
454
|
-
rootsInfo,
|
|
455
|
-
rootSource: opts.rootSource,
|
|
456
|
-
rootExists: exists,
|
|
457
|
-
settingsFile: opts.settingsFile,
|
|
458
|
-
windowHours: opts.windowHours,
|
|
459
|
-
maxItems: opts.maxItems,
|
|
460
|
-
maxDepth: opts.maxDepth,
|
|
461
|
-
hiddenCount: hidden.length,
|
|
462
|
-
// 前若干条隐藏项,供面板预览(不返回全部,避免配置很大时拖慢)
|
|
463
|
-
hiddenSample: hidden.slice(0, 10),
|
|
464
|
-
defaults: {
|
|
465
|
-
// 给前端「恢复默认」用:自动探测的结果
|
|
466
|
-
root: path.resolve(detectDefaultRoot()),
|
|
467
|
-
},
|
|
468
|
-
home: os.homedir(),
|
|
469
|
-
platform: process.platform,
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/**
|
|
474
|
-
* 会话日志解压结果的缓存。
|
|
475
|
-
* 自动刷新每 5 秒一次,而一个活跃会话的日志解压后有 9MB 以上;
|
|
476
|
-
* 用「路径 + mtime + size」做键,日志没变就复用上次的解析结果。
|
|
477
|
-
*/
|
|
478
|
-
const sessionLogCache = new Map()
|
|
479
|
-
|
|
480
|
-
/**
|
|
481
|
-
* 解压一个会话日志。
|
|
482
|
-
* DSH 的 session.v4.jsonl.zstd 是「多帧 zstd 拼接」(每次追加写一帧),
|
|
483
|
-
* 单次 zstdDecompressSync 只能解第一帧,所以必须按魔数切开逐帧解。
|
|
484
|
-
* @param fullPath - 日志文件绝对路径。
|
|
485
|
-
* @returns 解压后的完整文本;失败返回空串。
|
|
486
|
-
*/
|
|
487
|
-
async function readSessionLogText(fullPath) {
|
|
488
|
-
let stat
|
|
489
|
-
let buf
|
|
490
|
-
try {
|
|
491
|
-
stat = await fsp.stat(fullPath)
|
|
492
|
-
const cacheKey = `${fullPath}|${stat.mtimeMs}|${stat.size}`
|
|
493
|
-
const cached = sessionLogCache.get(fullPath)
|
|
494
|
-
if (cached !== undefined && cached.key === cacheKey) return cached.text
|
|
495
|
-
buf = await fsp.readFile(fullPath)
|
|
496
|
-
} catch {
|
|
497
|
-
return ''
|
|
498
|
-
}
|
|
499
|
-
const offsets = []
|
|
500
|
-
let cursor = 0
|
|
501
|
-
while (cursor < buf.length) {
|
|
502
|
-
const hit = buf.indexOf(ZSTD_MAGIC, cursor)
|
|
503
|
-
if (hit < 0) break
|
|
504
|
-
offsets.push(hit)
|
|
505
|
-
cursor = hit + ZSTD_MAGIC.length
|
|
506
|
-
}
|
|
507
|
-
if (offsets.length === 0) return ''
|
|
508
|
-
const parts = []
|
|
509
|
-
for (const offset of offsets) {
|
|
510
|
-
try {
|
|
511
|
-
parts.push(zstdDecompressSync(buf.subarray(offset)))
|
|
512
|
-
} catch {
|
|
513
|
-
// 单帧损坏就跳过,不影响其余帧
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
const text = Buffer.concat(parts).toString('utf8')
|
|
517
|
-
sessionLogCache.set(fullPath, { key: `${fullPath}|${stat.mtimeMs}|${stat.size}`, text })
|
|
518
|
-
// 缓存只留最近若干条,避免长跑后堆积
|
|
519
|
-
if (sessionLogCache.size > 8) {
|
|
520
|
-
const oldest = sessionLogCache.keys().next().value
|
|
521
|
-
if (oldest !== undefined) sessionLogCache.delete(oldest)
|
|
522
|
-
}
|
|
523
|
-
return text
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
/** 在 ~/.dsh/sessions/<工作区分组>/<sessionId>/ 里定位某个会话目录。 */
|
|
527
|
-
async function locateSessionDir(sessionsDir, sessionId) {
|
|
528
|
-
if (typeof sessionId !== 'string' || sessionId === '') return null
|
|
529
|
-
// 防御:会话 id 只可能是 [A-Za-z0-9._-],不许出现路径分隔符
|
|
530
|
-
if (/[\\/]/.test(sessionId) || sessionId.includes('..')) return null
|
|
531
|
-
let groups
|
|
532
|
-
try {
|
|
533
|
-
groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
|
|
534
|
-
} catch {
|
|
535
|
-
return null
|
|
536
|
-
}
|
|
537
|
-
for (const group of groups) {
|
|
538
|
-
if (!group.isDirectory()) continue
|
|
539
|
-
const candidate = path.join(sessionsDir, String(group.name), sessionId)
|
|
540
|
-
try {
|
|
541
|
-
const stat = await fsp.stat(candidate)
|
|
542
|
-
if (stat.isDirectory()) return candidate
|
|
543
|
-
} catch {
|
|
544
|
-
// 继续找下一个分组
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
return null
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
/**
|
|
551
|
-
* 找出某个会话的全部**子会话**目录(子智能体)。
|
|
552
|
-
*
|
|
553
|
-
* 修法 C:DSH 里子智能体是独立会话,有自己的 session 日志目录,
|
|
554
|
-
* 它的 write/present 调用**不出现在主会话日志里**。
|
|
555
|
-
* 所以「当前对话」必须把子会话的产出也算进去。
|
|
556
|
-
*
|
|
557
|
-
* 判定依据:子会话日志首行的 `parentSession` 字段指向主会话 id。
|
|
558
|
-
*
|
|
559
|
-
* @param sessionsDir - 会话根目录。
|
|
560
|
-
* @param parentSessionId - 主会话 id。
|
|
561
|
-
* @returns 子会话日志的绝对路径数组。
|
|
562
|
-
*/
|
|
563
|
-
async function findSubSessionLogs(sessionsDir, parentSessionId) {
|
|
564
|
-
const result = []
|
|
565
|
-
if (typeof parentSessionId !== 'string' || parentSessionId === '') return result
|
|
566
|
-
let groups
|
|
567
|
-
try {
|
|
568
|
-
groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
|
|
569
|
-
} catch {
|
|
570
|
-
return result
|
|
571
|
-
}
|
|
572
|
-
for (const group of groups) {
|
|
573
|
-
if (!group.isDirectory()) continue
|
|
574
|
-
let sessions
|
|
575
|
-
try {
|
|
576
|
-
sessions = await fsp.readdir(path.join(sessionsDir, String(group.name)), { withFileTypes: true })
|
|
577
|
-
} catch {
|
|
578
|
-
continue
|
|
579
|
-
}
|
|
580
|
-
for (const s of sessions) {
|
|
581
|
-
if (!s.isDirectory()) continue
|
|
582
|
-
const logPath = path.join(sessionsDir, String(group.name), String(s.name), 'session.v4.jsonl.zstd')
|
|
583
|
-
try {
|
|
584
|
-
const st = await fsp.stat(logPath)
|
|
585
|
-
if (!st.isFile()) continue
|
|
586
|
-
} catch {
|
|
587
|
-
continue
|
|
588
|
-
}
|
|
589
|
-
// 读首行判断 parentSession;日志可能很大,只解第一帧就够(首行一定在第一帧)
|
|
590
|
-
const headText = await readSessionLogHead(logPath)
|
|
591
|
-
if (headText === '') continue
|
|
592
|
-
try {
|
|
593
|
-
const first = JSON.parse(headText.split('\n')[0])
|
|
594
|
-
if (first?.type === 'session' && first?.parentSession === parentSessionId) {
|
|
595
|
-
result.push(logPath)
|
|
596
|
-
}
|
|
597
|
-
} catch {
|
|
598
|
-
// 首行解析失败就跳过
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
return result
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/**
|
|
606
|
-
* 只解压会话日志的第一帧,取首行(判断 parentSession 用,避免读整个 9MB 日志)。
|
|
607
|
-
* @param fullPath - 日志路径。
|
|
608
|
-
* @returns 首帧解出的文本;失败返回空串。
|
|
609
|
-
*/
|
|
610
|
-
async function readSessionLogHead(fullPath) {
|
|
611
|
-
let buf
|
|
612
|
-
try {
|
|
613
|
-
buf = await fsp.readFile(fullPath)
|
|
614
|
-
} catch {
|
|
615
|
-
return ''
|
|
616
|
-
}
|
|
617
|
-
const hit = buf.indexOf(ZSTD_MAGIC, 0)
|
|
618
|
-
if (hit < 0) return ''
|
|
619
|
-
try {
|
|
620
|
-
return zstdDecompressSync(buf.subarray(hit)).toString('utf8')
|
|
621
|
-
} catch {
|
|
622
|
-
return ''
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
/** 递归收集 JSON 节点里所有以盘符开头的字符串(工具的 path 参数)。 */
|
|
627
|
-
function collectAbsolutePaths(node, sink) {
|
|
628
|
-
if (typeof node === 'string') {
|
|
629
|
-
if (/^[A-Za-z]:[\\/]/.test(node)) sink.push(node)
|
|
630
|
-
return
|
|
631
|
-
}
|
|
632
|
-
if (Array.isArray(node)) {
|
|
633
|
-
for (const entry of node) collectAbsolutePaths(entry, sink)
|
|
634
|
-
return
|
|
635
|
-
}
|
|
636
|
-
if (node !== null && typeof node === 'object') {
|
|
637
|
-
for (const key of Object.keys(node)) collectAbsolutePaths(node[key], sink)
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
/**
|
|
642
|
-
* 资产分类常量。
|
|
643
|
-
*
|
|
644
|
-
* 分类判据(按优先级,从高到低):
|
|
645
|
-
* 1. 被 `present` 声明过 → **最终资产**(正式交付物)
|
|
646
|
-
* 2. 只被 `read_image` 看过、从未被写入 → **输入资产**(用户给的参考图/资料)
|
|
647
|
-
* 3. 其余(write/edit/脚本产出/bash 提到) → **中间资产**
|
|
648
|
-
* 4. 会话日志里查不到任何记录 → **未归类**(历史文件,不能冒充「输入」)
|
|
649
|
-
*
|
|
650
|
-
* 为什么要有 UNKNOWN:早先版本把查不到归属的文件兜底成 input,
|
|
651
|
-
* 结果 4995 个历史文件全被标成「输入」,把真正的输入资产淹没了。
|
|
652
|
-
* 「不知道」就老老实实说不知道,不要瞎猜。
|
|
653
|
-
*/
|
|
654
|
-
const ASSET_CATEGORY = {
|
|
655
|
-
INPUT: 'input',
|
|
656
|
-
INTERMEDIATE: 'intermediate',
|
|
657
|
-
FINAL: 'final',
|
|
658
|
-
UNKNOWN: 'unknown',
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
/** 中文/英文标签映射(客户端也可自行翻译,这里只给分类值)。 */
|
|
662
|
-
const CATEGORY_ORDER = ['final', 'input', 'intermediate']
|
|
663
|
-
|
|
664
|
-
/**
|
|
665
|
-
* 从会话日志里读出「本对话产出过的绝对路径 + 分类」。
|
|
666
|
-
*
|
|
667
|
-
* 覆盖两类来源:
|
|
668
|
-
* 1. `write` / `edit` / `present` 等直接写文件的调用 —— 路径必是产出。
|
|
669
|
-
* 2. `read_image` 打开过的图片 —— 脚本(Python 等)生成的图不在 write 调用里,
|
|
670
|
-
* 但 Agent 一定会打开看效果。不纳入这一条,「过程中生成的图」在
|
|
671
|
-
* 「当前对话」里就完全看不见(只有全局资产能看到)。
|
|
672
|
-
*
|
|
673
|
-
* @param logText - 解压后的日志文本(每行一个 JSON)。
|
|
674
|
-
* @param sessionStartMs - 本会话开始时间(毫秒时间戳)。
|
|
675
|
-
* 用于区分「用户提供的素材」和「会话期间生成的产物」:
|
|
676
|
-
* 前者必定早于会话开始就存在。传 0 表示拿不到,此时不做输入判定。
|
|
677
|
-
* @returns Map<绝对路径, { category, presented, written, viewed, bashMentioned }>
|
|
678
|
-
*/
|
|
679
|
-
function extractAssetInfo(logText, sessionStartMs = 0) {
|
|
680
|
-
const assets = new Map()
|
|
681
|
-
if (typeof logText !== 'string' || logText === '') return assets
|
|
682
|
-
|
|
683
|
-
const ensure = (abs) => {
|
|
684
|
-
if (!assets.has(abs)) {
|
|
685
|
-
assets.set(abs, { presented: false, written: false, viewed: false, bashMentioned: false })
|
|
686
|
-
}
|
|
687
|
-
return assets.get(abs)
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
for (const line of logText.split('\n')) {
|
|
691
|
-
if (line === '') continue
|
|
692
|
-
// 快速预筛:只处理含 tool/call 的行,避免全量 JSON.parse
|
|
693
|
-
if (!line.includes('tool/call')) continue
|
|
694
|
-
let record
|
|
695
|
-
try {
|
|
696
|
-
record = JSON.parse(line)
|
|
697
|
-
} catch {
|
|
698
|
-
continue
|
|
699
|
-
}
|
|
700
|
-
if (record?.type !== 'tool/call') continue
|
|
701
|
-
const name = record?.data?.name
|
|
702
|
-
if (typeof name !== 'string') continue
|
|
703
|
-
|
|
704
|
-
const rawArgs = record?.data?.arguments
|
|
705
|
-
if (typeof rawArgs !== 'string') continue
|
|
706
|
-
let args
|
|
707
|
-
try {
|
|
708
|
-
args = JSON.parse(rawArgs)
|
|
709
|
-
} catch {
|
|
710
|
-
continue
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// ---- bash / pwsh:命令文本里提到的路径,只作为「非输入」的弱证据 ----
|
|
714
|
-
if (BASH_TOOLS.has(name)) {
|
|
715
|
-
const cmdText = `${args?.command ?? ''} ${args?.script_path ?? ''}`
|
|
716
|
-
const re = /[A-Za-z]:[\\/][^\s"'|&;<>()*?]+/g
|
|
717
|
-
for (const m of cmdText.matchAll(re)) {
|
|
718
|
-
const candidate = m[0].replace(/[\\/]+$/, '')
|
|
719
|
-
const ext = path.extname(candidate).toLowerCase()
|
|
720
|
-
// 只接受看起来像文件的路径(有扩展名)
|
|
721
|
-
if (ext === '') continue
|
|
722
|
-
try {
|
|
723
|
-
const info = ensure(path.resolve(candidate))
|
|
724
|
-
info.bashMentioned = true
|
|
725
|
-
} catch {
|
|
726
|
-
// 解析失败就跳过
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
continue
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
const isWriter = OUTPUT_TOOLS.has(name)
|
|
733
|
-
const isViewer = VIEW_TOOLS.has(name)
|
|
734
|
-
const isPresenter = name === 'present'
|
|
735
|
-
if (!isWriter && !isViewer && !isPresenter) continue
|
|
736
|
-
|
|
737
|
-
// present 的参数结构是 { files: [{ path, description }]}
|
|
738
|
-
let found = []
|
|
739
|
-
if (isPresenter && Array.isArray(args?.files)) {
|
|
740
|
-
found = args.files.map((f) => f?.path).filter((p) => typeof p === 'string')
|
|
741
|
-
} else {
|
|
742
|
-
collectAbsolutePaths(args, found)
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
for (const entry of found) {
|
|
746
|
-
if (isViewer) {
|
|
747
|
-
// 查看类工具只认图片:避免把 read_image 参数里偶尔出现的
|
|
748
|
-
// 目录、配置等非图片路径当成产出
|
|
749
|
-
const ext = path.extname(entry).toLowerCase()
|
|
750
|
-
if (!VIEW_IMAGE_EXTS.has(ext)) continue
|
|
751
|
-
}
|
|
752
|
-
const info = ensure(path.resolve(entry))
|
|
753
|
-
if (isPresenter) info.presented = true
|
|
754
|
-
else if (isViewer) info.viewed = true
|
|
755
|
-
else info.written = true
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
// ---- 归类 ----
|
|
760
|
-
for (const [abs, info] of assets) {
|
|
761
|
-
classifyAsset(abs, info, sessionStartMs)
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
return assets
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* 从会话日志首行解析会话开始时间(createdAt)。
|
|
769
|
-
* @param logText - 解压后的日志文本。
|
|
770
|
-
* @returns 毫秒时间戳;解析失败返回 0。
|
|
771
|
-
*/
|
|
772
|
-
function parseSessionStartMs(logText) {
|
|
773
|
-
if (typeof logText !== 'string' || logText === '') return 0
|
|
774
|
-
const firstLine = logText.split('\n')[0]
|
|
775
|
-
try {
|
|
776
|
-
const first = JSON.parse(firstLine)
|
|
777
|
-
return typeof first?.createdAt === 'number' ? first.createdAt : 0
|
|
778
|
-
} catch {
|
|
779
|
-
return 0
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
/**
|
|
784
|
-
* 给单个资产定分类。**唯一**的分类入口,别在别处复制这套判据。
|
|
785
|
-
*
|
|
786
|
-
* 规则(按优先级):
|
|
787
|
-
* 1. present 过 → 最终
|
|
788
|
-
* 2. 「只被 read_image 看过」是候选输入,但必须能证明它早于会话开始就存在:
|
|
789
|
-
* - mtime < 会话开始 → 输入(用户预先提供的素材)
|
|
790
|
-
* - mtime >= 会话开始 → 中间(会话期间生成的,脚本产出常见这种)
|
|
791
|
-
* 3. 其余 → 中间
|
|
792
|
-
*
|
|
793
|
-
* 为什么必须看时间:「被 read_image 看过」既可能是用户素材,也可能是脚本产出的图,
|
|
794
|
-
* Agent 两者都会打开看。实测反例:
|
|
795
|
-
* - architecture.png:write 写的是脚本,file_path 不是它,只在 read_image 出现
|
|
796
|
-
* - 缩略图尺寸对比.png:文件名写在 bash 的 python 代码里,不是绝对路径
|
|
797
|
-
* 这两类旧判据都会误判成「输入」。
|
|
798
|
-
*
|
|
799
|
-
* @param abs - 文件绝对路径。
|
|
800
|
-
* @param info - extractAssetInfo 收集到的动作标记(会被写入 category)。
|
|
801
|
-
* @param sessionStartMs - 会话开始时间;0 表示未知(此时不做输入判定)。
|
|
802
|
-
*/
|
|
803
|
-
function classifyAsset(abs, info, sessionStartMs) {
|
|
804
|
-
info.path = abs
|
|
805
|
-
|
|
806
|
-
if (info.presented) {
|
|
807
|
-
info.category = ASSET_CATEGORY.FINAL
|
|
808
|
-
return
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
const looksLikeInput = info.viewed === true && info.written !== true && info.bashMentioned !== true
|
|
812
|
-
if (!looksLikeInput) {
|
|
813
|
-
info.category = ASSET_CATEGORY.INTERMEDIATE
|
|
814
|
-
return
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
let mtimeMs = null
|
|
818
|
-
try {
|
|
819
|
-
mtimeMs = statSync(abs).mtimeMs
|
|
820
|
-
} catch {
|
|
821
|
-
mtimeMs = null
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
if (mtimeMs !== null && sessionStartMs > 0 && mtimeMs < sessionStartMs) {
|
|
825
|
-
info.category = ASSET_CATEGORY.INPUT
|
|
826
|
-
} else {
|
|
827
|
-
// 会话开始后才出现(或文件已不存在)→ 归中间,不冒充用户素材
|
|
828
|
-
info.category = ASSET_CATEGORY.INTERMEDIATE
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
/**
|
|
833
|
-
* 从会话日志里读出「本对话产出过的绝对路径」。
|
|
834
|
-
* @param logText - 解压后的日志文本(每行一个 JSON)。
|
|
835
|
-
* @returns 绝对路径的 Set。
|
|
836
|
-
*/
|
|
837
|
-
function extractOutputPaths(logText) {
|
|
838
|
-
return new Set(extractAssetInfo(logText).keys())
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
/**
|
|
842
|
-
* 算出「本对话」产出过的路径与任务目录。
|
|
843
|
-
*
|
|
844
|
-
* 支持多扫描目录(roots):逐个判断路径落在哪个 root 下。
|
|
845
|
-
* 修法 B:文件**直接躺在 root 根目录下**(没有子目录)时也要能匹配,
|
|
846
|
-
* 原实现只取「第一层目录」并要求至少两段,导致根目录文件全部判为 0。
|
|
847
|
-
*
|
|
848
|
-
* @param config - 用户配置。
|
|
849
|
-
* @param sessionId - 当前会话 id。
|
|
850
|
-
* @param allRoots - 已解析的扫描目录列表(不传则内部再解析一次)。
|
|
851
|
-
* @returns { ok, reason, taskDirs, paths, relPaths }
|
|
852
|
-
*/
|
|
853
|
-
async function resolveSessionScope(config, sessionId, allRoots) {
|
|
854
|
-
const opts = resolveOptions(config)
|
|
855
|
-
const roots = Array.isArray(allRoots) && allRoots.length > 0 ? allRoots : opts.roots
|
|
856
|
-
const sessionsDir = typeof config?.sessionsDir === 'string' && config.sessionsDir !== ''
|
|
857
|
-
? path.resolve(config.sessionsDir)
|
|
858
|
-
: DEFAULT_SESSIONS_DIR
|
|
859
|
-
const sessionDir = await locateSessionDir(sessionsDir, sessionId)
|
|
860
|
-
if (sessionDir === null) {
|
|
861
|
-
return { ok: false, reason: 'session-not-found', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
|
|
862
|
-
}
|
|
863
|
-
const logPath = path.join(sessionDir, 'session.v4.jsonl.zstd')
|
|
864
|
-
const logText = await readSessionLogText(logPath)
|
|
865
|
-
if (logText === '') {
|
|
866
|
-
return { ok: false, reason: 'log-empty', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
|
|
867
|
-
}
|
|
868
|
-
// 会话开始时间:用于区分「用户素材」与「会话期间产出」
|
|
869
|
-
const sessionStartMs = parseSessionStartMs(logText)
|
|
870
|
-
const allAssets = extractAssetInfo(logText, sessionStartMs)
|
|
871
|
-
|
|
872
|
-
// 修法 C:合并所有子会话(子智能体)的产出路径
|
|
873
|
-
const subLogs = await findSubSessionLogs(sessionsDir, sessionId)
|
|
874
|
-
for (const subLog of subLogs) {
|
|
875
|
-
const subText = await readSessionLogText(subLog)
|
|
876
|
-
if (subText === '') continue
|
|
877
|
-
for (const [abs, info] of extractAssetInfo(subText, sessionStartMs)) {
|
|
878
|
-
const existing = allAssets.get(abs)
|
|
879
|
-
if (existing) {
|
|
880
|
-
// 合并标记:任一处 present 就算最终
|
|
881
|
-
existing.presented = existing.presented || info.presented
|
|
882
|
-
existing.written = existing.written || info.written
|
|
883
|
-
existing.viewed = existing.viewed || info.viewed
|
|
884
|
-
existing.bashMentioned = existing.bashMentioned || info.bashMentioned
|
|
885
|
-
} else {
|
|
886
|
-
allAssets.set(abs, info)
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
// 合并后重新归类(因为 presented/written 可能变了)。
|
|
892
|
-
// 统一走 classifyAsset,避免两处判据分叉 —— v0.8.1 就是这里漏改导致分类不准。
|
|
893
|
-
for (const [abs, info] of allAssets) {
|
|
894
|
-
classifyAsset(abs, info, sessionStartMs)
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
const normalized = []
|
|
898
|
-
const relPaths = []
|
|
899
|
-
const taskDirs = new Set()
|
|
900
|
-
// relPath(小写) → 分类,供扫描时标注
|
|
901
|
-
const categoryByRel = new Map()
|
|
902
|
-
|
|
903
|
-
for (const [abs, info] of allAssets) {
|
|
904
|
-
const absolute = path.resolve(abs)
|
|
905
|
-
// 找出该路径属于哪个 root
|
|
906
|
-
let ownerRoot = null
|
|
907
|
-
for (const r of roots) {
|
|
908
|
-
if (isInside(r, absolute)) { ownerRoot = r; break }
|
|
909
|
-
}
|
|
910
|
-
if (ownerRoot === null) continue
|
|
911
|
-
normalized.push(absolute)
|
|
912
|
-
|
|
913
|
-
const rel = path.relative(ownerRoot, absolute)
|
|
914
|
-
const segs = rel.split(path.sep).filter((s) => s !== '')
|
|
915
|
-
const relPath = rel.split(path.sep).join('/')
|
|
916
|
-
relPaths.push(relPath)
|
|
917
|
-
categoryByRel.set(relPath.toLowerCase(), info.category)
|
|
918
|
-
// 修法 B:有子目录时取第一层;没有子目录(文件直接在 root 下)时,
|
|
919
|
-
// 用空字符串占位,表示「只在根目录层匹配」,不再直接丢弃
|
|
920
|
-
if (segs.length >= 2) taskDirs.add(segs[0])
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
return {
|
|
924
|
-
ok: true,
|
|
925
|
-
reason: 'ok',
|
|
926
|
-
taskDirs: [...taskDirs],
|
|
927
|
-
paths: normalized,
|
|
928
|
-
relPaths,
|
|
929
|
-
categoryByRel,
|
|
930
|
-
subSessions: subLogs.length,
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
/**
|
|
935
|
-
* 扫描画廊候选:广度优先、深度受限、跳过批量目录、有目录/条目预算。
|
|
936
|
-
* 结果按修改时间倒序,只回传 maxItems 条,另外给出 total 供「还有 N 张」。
|
|
937
|
-
*/
|
|
938
|
-
export async function scanGallery(config, kind = 'image', scope = 'global', sessionId = '', page = 1) {
|
|
939
|
-
const opts = resolveOptions(config)
|
|
940
|
-
const now = Date.now()
|
|
941
|
-
const cutoff = now - opts.windowHours * 3600_000
|
|
942
|
-
const isFile = kind === 'file'
|
|
943
|
-
const isMedia = kind === 'media'
|
|
944
|
-
const isSession = scope === 'session'
|
|
945
|
-
// 页码从 1 开始;非法值一律回到第 1 页
|
|
946
|
-
const currentPage = Math.max(1, Math.trunc(Number(page) || 1))
|
|
947
|
-
// 图片格式永远排除在文件画廊之外;防止用户配置误把图片塞进来
|
|
948
|
-
const extraImageEx = new Set(['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tif', '.tiff', '.heic', '.avif', '.ico'])
|
|
949
|
-
// 音视频同样不能混进文件画廊(v0.10.1):音视频有自己的画廊
|
|
950
|
-
const mediaEx = new Set(opts.mediaExtensions)
|
|
951
|
-
let rawExts
|
|
952
|
-
if (isFile) rawExts = opts.fileExtensions
|
|
953
|
-
else if (isMedia) rawExts = opts.mediaExtensions
|
|
954
|
-
else rawExts = opts.extensions
|
|
955
|
-
const extSet = new Set(rawExts.filter((e) => !(
|
|
956
|
-
(isFile && extraImageEx.has(e))
|
|
957
|
-
|| (isFile && mediaEx.has(e))
|
|
958
|
-
|| (isMedia && extraImageEx.has(e))
|
|
959
|
-
)))
|
|
960
|
-
const skipSet = new Set(opts.skipDirs)
|
|
961
|
-
|
|
962
|
-
// 当前对话范围:先解析会话日志(含子智能体会话),得到「本对话产出过的路径」
|
|
963
|
-
let scopeInfo = { ok: true, reason: 'global', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
|
|
964
|
-
let sessionRelSet = null
|
|
965
|
-
if (isSession) {
|
|
966
|
-
scopeInfo = await resolveSessionScope(config, sessionId, opts.roots)
|
|
967
|
-
// 修法 B:用「精确相对路径」集合判定,而不是只靠第一层目录名。
|
|
968
|
-
// 这样既能处理有子目录的情况,也能处理「文件直接躺在 root 根目录下」。
|
|
969
|
-
sessionRelSet = new Set((scopeInfo.relPaths ?? []).map((p) => p.toLowerCase()))
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
// 会话索引:建立「文件 → 所属对话 + 分类」的映射,供全局按对话分组用
|
|
973
|
-
const sessionsDir = typeof config?.sessionsDir === 'string' && config.sessionsDir !== ''
|
|
974
|
-
? path.resolve(config.sessionsDir)
|
|
975
|
-
: DEFAULT_SESSIONS_DIR
|
|
976
|
-
let sessionIndex = null
|
|
977
|
-
// 全局模式才需要索引(当前对话模式已有自己的 scopeInfo)
|
|
978
|
-
if (!isSession) {
|
|
979
|
-
sessionIndex = await buildSessionIndex(sessionsDir, opts, {
|
|
980
|
-
readSessionLogText,
|
|
981
|
-
extractAssetInfo,
|
|
982
|
-
})
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
// 文件绝对路径 → { sessionId, title, category }
|
|
986
|
-
const ownerByAbs = new Map()
|
|
987
|
-
if (sessionIndex !== null) {
|
|
988
|
-
for (const [sid, entry] of sessionIndex) {
|
|
989
|
-
for (const [abs, cat] of entry.files) {
|
|
990
|
-
// 同一个文件被多个对话产出时,取最近的那个对话
|
|
991
|
-
const prev = ownerByAbs.get(abs)
|
|
992
|
-
if (prev === undefined || entry.createdAt > prev.createdAt) {
|
|
993
|
-
ownerByAbs.set(abs, {
|
|
994
|
-
sessionId: sid,
|
|
995
|
-
title: entry.title || '',
|
|
996
|
-
createdAt: entry.createdAt,
|
|
997
|
-
category: cat,
|
|
998
|
-
})
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
// 已隐藏的路径:扫描时直接跳过(不移动文件,只从列表里拿掉)
|
|
1005
|
-
const hiddenSet = new Set(await readHiddenList(opts.settingsFile))
|
|
1006
|
-
|
|
1007
|
-
const matches = []
|
|
1008
|
-
let directories = 0
|
|
1009
|
-
let entries = 0
|
|
1010
|
-
let capped = false
|
|
1011
|
-
let anyRootExists = false
|
|
1012
|
-
const missingRoots = []
|
|
1013
|
-
|
|
1014
|
-
// 遍历所有扫描目录(多目录支持)
|
|
1015
|
-
for (const rootDir of opts.roots) {
|
|
1016
|
-
if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
|
|
1017
|
-
capped = true
|
|
1018
|
-
break
|
|
1019
|
-
}
|
|
1020
|
-
let rootOk = false
|
|
1021
|
-
try {
|
|
1022
|
-
const st = await fsp.stat(rootDir)
|
|
1023
|
-
rootOk = st.isDirectory()
|
|
1024
|
-
} catch {
|
|
1025
|
-
rootOk = false
|
|
1026
|
-
}
|
|
1027
|
-
if (!rootOk) {
|
|
1028
|
-
missingRoots.push(rootDir)
|
|
1029
|
-
continue
|
|
1030
|
-
}
|
|
1031
|
-
anyRootExists = true
|
|
1032
|
-
|
|
1033
|
-
const dirQueue = [{ dir: rootDir, depth: 0 }]
|
|
1034
|
-
while (dirQueue.length > 0) {
|
|
1035
|
-
if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
|
|
1036
|
-
capped = true
|
|
1037
|
-
break
|
|
1038
|
-
}
|
|
1039
|
-
const { dir, depth } = dirQueue.shift()
|
|
1040
|
-
directories += 1
|
|
1041
|
-
let dirents
|
|
1042
|
-
try {
|
|
1043
|
-
dirents = await fsp.readdir(dir, { withFileTypes: true })
|
|
1044
|
-
} catch {
|
|
1045
|
-
continue
|
|
1046
|
-
}
|
|
1047
|
-
for (const dirent of dirents) {
|
|
1048
|
-
entries += 1
|
|
1049
|
-
if (entries >= opts.maxEntries) {
|
|
1050
|
-
capped = true
|
|
1051
|
-
break
|
|
1052
|
-
}
|
|
1053
|
-
const entryName = String(dirent.name)
|
|
1054
|
-
const fullPath = path.join(dir, entryName)
|
|
1055
|
-
if (dirent.isDirectory()) {
|
|
1056
|
-
if (depth + 1 > opts.maxDepth) continue
|
|
1057
|
-
if (skipSet.has(entryName.toLowerCase())) continue
|
|
1058
|
-
dirQueue.push({ dir: fullPath, depth: depth + 1 })
|
|
1059
|
-
continue
|
|
1060
|
-
}
|
|
1061
|
-
if (!dirent.isFile()) continue
|
|
1062
|
-
const ext = path.extname(entryName).toLowerCase()
|
|
1063
|
-
if (!extSet.has(ext)) continue
|
|
1064
|
-
// 当前对话范围:按精确相对路径判定(支持根目录文件与多层子目录)
|
|
1065
|
-
const relPath = path.relative(rootDir, fullPath).split(path.sep).join('/')
|
|
1066
|
-
if (sessionRelSet !== null && !sessionRelSet.has(relPath.toLowerCase())) continue
|
|
1067
|
-
let stat
|
|
1068
|
-
try {
|
|
1069
|
-
stat = await fsp.stat(fullPath)
|
|
1070
|
-
} catch {
|
|
1071
|
-
continue
|
|
1072
|
-
}
|
|
1073
|
-
if (stat.size <= 0 || stat.mtimeMs < cutoff) continue
|
|
1074
|
-
// 音视频:超过体积上限的直接跳过(视频可能几百 MB,列出来点开就卡)
|
|
1075
|
-
if (isMedia && stat.size > opts.maxMediaBytes) continue
|
|
1076
|
-
// 被隐藏的直接跳过(隐藏只影响列表展示,文件仍在磁盘上)
|
|
1077
|
-
if (hiddenSet.has(relPath)) continue
|
|
1078
|
-
matches.push({
|
|
1079
|
-
relPath,
|
|
1080
|
-
relKey: `${opts.roots.indexOf(rootDir)}:${relPath}`,
|
|
1081
|
-
rootDir,
|
|
1082
|
-
rootIndex: opts.roots.indexOf(rootDir),
|
|
1083
|
-
name: entryName,
|
|
1084
|
-
size: stat.size,
|
|
1085
|
-
mtime: stat.mtimeMs,
|
|
1086
|
-
extension: ext,
|
|
1087
|
-
// 音视频区分「视频 / 音频」,客户端据此选 <video> 还是 <audio>
|
|
1088
|
-
...(isMedia ? { mediaType: VIDEO_EXTS.has(ext) ? 'video' : 'audio' } : {}),
|
|
1089
|
-
})
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
const rootMissing = !anyRootExists
|
|
1095
|
-
|
|
1096
|
-
// 给每个条目附加「分类」和「所属对话」
|
|
1097
|
-
for (const item of matches) {
|
|
1098
|
-
const abs = path.join(item.rootDir, ...item.relPath.split('/'))
|
|
1099
|
-
const owner = ownerByAbs.get(abs)
|
|
1100
|
-
item.absPath = abs
|
|
1101
|
-
if (isSession) {
|
|
1102
|
-
item.category = (scopeInfo.categoryByRel?.get(item.relPath.toLowerCase())) ?? null
|
|
1103
|
-
item.sessionId = sessionId
|
|
1104
|
-
} else if (owner !== undefined) {
|
|
1105
|
-
item.category = owner.category
|
|
1106
|
-
item.sessionId = owner.sessionId
|
|
1107
|
-
item.sessionTitle = owner.title
|
|
1108
|
-
item.sessionCreatedAt = owner.createdAt
|
|
1109
|
-
} else {
|
|
1110
|
-
// 不属于任何已知对话的文件:归到「历史资产」,分类记为**未归类**
|
|
1111
|
-
// 不能兜底成 input —— 那会把 4995 个历史文件全标成「输入」
|
|
1112
|
-
item.category = ASSET_CATEGORY.UNKNOWN
|
|
1113
|
-
item.sessionId = null
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
matches.sort((a, b) => b.mtime - a.mtime)
|
|
1118
|
-
const total = matches.length
|
|
1119
|
-
// 分页:每页 maxItems 条,保留 total 供页码条使用
|
|
1120
|
-
// 全局分组模式下不分页(客户端自己分组折叠),所有条目都返回摘要
|
|
1121
|
-
const pageCount = isSession
|
|
1122
|
-
? Math.max(1, Math.ceil(total / opts.maxItems))
|
|
1123
|
-
: Math.max(1, Math.ceil(total / opts.maxItems))
|
|
1124
|
-
const safePage = Math.min(currentPage, pageCount)
|
|
1125
|
-
const offset = (safePage - 1) * opts.maxItems
|
|
1126
|
-
const visible = matches.slice(offset, offset + opts.maxItems)
|
|
1127
|
-
|
|
1128
|
-
await Promise.all(visible.map(async (item) => {
|
|
1129
|
-
if (isFile || isMedia) {
|
|
1130
|
-
// 文件/音视频画廊不解析图片尺寸
|
|
1131
|
-
item.width = null
|
|
1132
|
-
item.height = null
|
|
1133
|
-
return
|
|
1134
|
-
}
|
|
1135
|
-
// 多目录:用该条目自己所属的 rootDir 拼绝对路径
|
|
1136
|
-
const measured = measureImage(
|
|
1137
|
-
await readHead(path.join(item.rootDir, ...item.relPath.split('/')), 65536),
|
|
1138
|
-
item.extension,
|
|
1139
|
-
)
|
|
1140
|
-
item.width = measured?.width ?? null
|
|
1141
|
-
item.height = measured?.height ?? null
|
|
1142
|
-
}))
|
|
1143
|
-
|
|
1144
|
-
// 全量统计:供「全局按对话分组」使用(不受分页限制)
|
|
1145
|
-
const allItemsSummary = []
|
|
1146
|
-
if (!isSession) {
|
|
1147
|
-
for (const item of matches) {
|
|
1148
|
-
allItemsSummary.push({
|
|
1149
|
-
absPath: item.absPath,
|
|
1150
|
-
relPath: item.relPath,
|
|
1151
|
-
sessionId: item.sessionId,
|
|
1152
|
-
sessionTitle: item.sessionTitle ?? '',
|
|
1153
|
-
sessionCreatedAt: item.sessionCreatedAt ?? 0,
|
|
1154
|
-
category: item.category,
|
|
1155
|
-
mtime: item.mtime,
|
|
1156
|
-
width: item.width ?? null,
|
|
1157
|
-
height: item.height ?? null,
|
|
1158
|
-
size: item.size,
|
|
1159
|
-
name: item.name,
|
|
1160
|
-
extension: item.extension,
|
|
1161
|
-
// 音视频类型(video / audio),客户端据此选 <video> 还是 <audio>
|
|
1162
|
-
...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
|
|
1163
|
-
})
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
return {
|
|
1168
|
-
kind,
|
|
1169
|
-
scope: isSession ? 'session' : 'global',
|
|
1170
|
-
scopeInfo: {
|
|
1171
|
-
ok: scopeInfo.ok,
|
|
1172
|
-
reason: scopeInfo.reason,
|
|
1173
|
-
taskDirs: scopeInfo.taskDirs.length,
|
|
1174
|
-
paths: scopeInfo.paths.length,
|
|
1175
|
-
relPaths: (scopeInfo.relPaths ?? []).length,
|
|
1176
|
-
// 子智能体会话数:> 0 表示已纳入它们的产出
|
|
1177
|
-
subSessions: scopeInfo.subSessions ?? 0,
|
|
1178
|
-
},
|
|
1179
|
-
root: opts.root,
|
|
1180
|
-
roots: opts.roots,
|
|
1181
|
-
rootSource: opts.rootSource,
|
|
1182
|
-
missingRoots,
|
|
1183
|
-
windowHours: opts.windowHours,
|
|
1184
|
-
maxItems: opts.maxItems,
|
|
1185
|
-
maxDepth: opts.maxDepth,
|
|
1186
|
-
generatedAt: now,
|
|
1187
|
-
items: visible,
|
|
1188
|
-
total,
|
|
1189
|
-
// 分页信息,客户端据此渲染页码条
|
|
1190
|
-
page: safePage,
|
|
1191
|
-
pageCount,
|
|
1192
|
-
pageSize: opts.maxItems,
|
|
1193
|
-
// 「还有 N 张」= 当前页之外的总数(不再只是「被截掉的」)
|
|
1194
|
-
hidden: Math.max(0, total - visible.length),
|
|
1195
|
-
rootMissing,
|
|
1196
|
-
scan: { directories, entries, capped },
|
|
1197
|
-
// 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)
|
|
1198
|
-
groups: isSession ? null : buildGroups(allItemsSummary, 120, sessionId),
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
/**
|
|
1203
|
-
* 把扁平的资产列表按「所属对话」分组。
|
|
1204
|
-
*
|
|
1205
|
-
* 分组规则:
|
|
1206
|
-
* - 属于某个已知对话的文件 → 归到该对话(标题用会话标题)
|
|
1207
|
-
* - 其余(日志里查不到归属的历史文件)→ 统一归到「历史资产」组
|
|
1208
|
-
*
|
|
1209
|
-
* 排序(v0.8.2 调整):
|
|
1210
|
-
* 1. **当前对话永远置顶** —— 用户打开「全局资产」最想先看自己这次做了什么,
|
|
1211
|
-
* 按时间倒序会把它压到中间(当前对话可能很早创建、但一直在用)。
|
|
1212
|
-
* 2. 其余对话按创建时间倒序。
|
|
1213
|
-
* 3. 「历史资产」永远最后。
|
|
1214
|
-
*
|
|
1215
|
-
* ⚠️ 体积控制:每组只返回前 maxPerGroup 条明细 + 完整总数。
|
|
1216
|
-
* 为什么必须截断:历史组有 4995 个文件,全量返回会让单次响应达到 1.3 MB,
|
|
1217
|
-
* 前端解析/渲染都会卡,面板看起来「只显示两组」。
|
|
1218
|
-
*
|
|
1219
|
-
* @param summary - 扁平资产摘要数组。
|
|
1220
|
-
* @param maxPerGroup - 每组最多返回多少条明细(默认 120)。
|
|
1221
|
-
* @param currentSessionId - 当前打开的会话 id;匹配到的组会标记 isCurrent 并置顶。
|
|
1222
|
-
* @returns 分组数组。
|
|
1223
|
-
*/
|
|
1224
|
-
function buildGroups(summary, maxPerGroup = 120, currentSessionId = '') {
|
|
1225
|
-
if (!Array.isArray(summary) || summary.length === 0) return []
|
|
1226
|
-
|
|
1227
|
-
const groups = new Map()
|
|
1228
|
-
for (const item of summary) {
|
|
1229
|
-
const key = item.sessionId ?? '__unassigned__'
|
|
1230
|
-
if (!groups.has(key)) {
|
|
1231
|
-
groups.set(key, {
|
|
1232
|
-
sessionId: item.sessionId,
|
|
1233
|
-
title: item.sessionId === null ? '' : (item.sessionTitle || item.sessionId.slice(0, 8)),
|
|
1234
|
-
createdAt: item.sessionCreatedAt || 0,
|
|
1235
|
-
files: [],
|
|
1236
|
-
})
|
|
1237
|
-
}
|
|
1238
|
-
const g = groups.get(key)
|
|
1239
|
-
g.files.push({
|
|
1240
|
-
absPath: item.absPath,
|
|
1241
|
-
relPath: item.relPath,
|
|
1242
|
-
category: item.category,
|
|
1243
|
-
mtime: item.mtime,
|
|
1244
|
-
width: item.width ?? null,
|
|
1245
|
-
height: item.height ?? null,
|
|
1246
|
-
size: item.size ?? 0,
|
|
1247
|
-
name: item.name ?? item.relPath.split('/').pop(),
|
|
1248
|
-
// 客户端卡片要靠这两个字段判断渲染类型(v0.10.1)
|
|
1249
|
-
extension: item.extension ?? ('.' + item.relPath.split('/').pop().split('.').pop().toLowerCase()),
|
|
1250
|
-
...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
|
|
1251
|
-
})
|
|
1252
|
-
if (item.sessionId === null && item.mtime > g.createdAt) g.createdAt = item.mtime
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
const out = []
|
|
1256
|
-
for (const g of groups.values()) {
|
|
1257
|
-
g.files.sort((a, b) => b.mtime - a.mtime)
|
|
1258
|
-
const counts = { final: 0, input: 0, intermediate: 0, unknown: 0 }
|
|
1259
|
-
for (const f of g.files) {
|
|
1260
|
-
if (counts[f.category] !== undefined) counts[f.category] += 1
|
|
1261
|
-
}
|
|
1262
|
-
// 只回传前 maxPerGroup 条明细(客户端滚动到底再按需请求)
|
|
1263
|
-
const returned = g.files.slice(0, maxPerGroup)
|
|
1264
|
-
out.push({
|
|
1265
|
-
sessionId: g.sessionId,
|
|
1266
|
-
isHistory: g.sessionId === null,
|
|
1267
|
-
// 当前打开的会话:客户端据此置顶并默认展开
|
|
1268
|
-
isCurrent: currentSessionId !== '' && g.sessionId === currentSessionId,
|
|
1269
|
-
title: g.title,
|
|
1270
|
-
createdAt: g.createdAt,
|
|
1271
|
-
fileCount: g.files.length,
|
|
1272
|
-
returnedCount: returned.length,
|
|
1273
|
-
truncated: g.files.length > returned.length,
|
|
1274
|
-
counts,
|
|
1275
|
-
files: returned,
|
|
1276
|
-
latestMtime: g.files.length > 0 ? g.files[0].mtime : 0,
|
|
1277
|
-
})
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
// 组排序:
|
|
1281
|
-
// 1. 当前对话永远第一(按时间倒序会把它压到中间)
|
|
1282
|
-
// 2. 其余对话按创建时间倒序
|
|
1283
|
-
// 3. 「历史资产」永远最后
|
|
1284
|
-
out.sort((a, b) => {
|
|
1285
|
-
if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1
|
|
1286
|
-
if (a.isHistory && !b.isHistory) return 1
|
|
1287
|
-
if (b.isHistory && !a.isHistory) return -1
|
|
1288
|
-
return b.createdAt - a.createdAt
|
|
1289
|
-
})
|
|
1290
|
-
|
|
1291
|
-
return out
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
/**
|
|
1295
|
-
* 把一个相对路径解析成根目录内的绝对路径;越界或不存在返回 null。
|
|
1296
|
-
* 多目录支持:第一个 root 找不到就逐个试其余 root。
|
|
1297
|
-
* @param roots - 扫描目录列表(或单个 root 字符串,兼容旧调用)。
|
|
1298
|
-
*/
|
|
1299
|
-
/**
|
|
1300
|
-
* 把「相对路径」解析成一个可读文件。
|
|
1301
|
-
*
|
|
1302
|
-
* @param roots - 允许的根目录。
|
|
1303
|
-
* @param relPath - 相对 root 的路径(用 / 分隔)。
|
|
1304
|
-
* @param opts - 配置。
|
|
1305
|
-
* @param byteCap - 体积上限(字节)。**图片和媒体上限不同**:
|
|
1306
|
-
* 图片用 maxImageBytes(默认 64MB),音视频用 maxMediaBytes(默认 200MB)。
|
|
1307
|
-
* 不传时退回 maxImageBytes。以前这里固定用 maxImageBytes,
|
|
1308
|
-
* 导致 127MB 的视频被判「不可读」→ 前端收到 404。
|
|
1309
|
-
*/
|
|
1310
|
-
async function resolveReadable(roots, relPath, opts, byteCap) {
|
|
1311
|
-
const list = Array.isArray(roots) ? roots : [roots]
|
|
1312
|
-
if (typeof relPath !== 'string' || relPath === '') return null
|
|
1313
|
-
const cap = typeof byteCap === 'number' && byteCap > 0 ? byteCap : opts.maxImageBytes
|
|
1314
|
-
const normalized = relPath.replace(/\\/g, '/')
|
|
1315
|
-
if (normalized.split('/').some((segment) => segment === '..' || segment === '')) return null
|
|
1316
|
-
for (const root of list) {
|
|
1317
|
-
const absolute = path.resolve(root, ...normalized.split('/'))
|
|
1318
|
-
if (!isInside(root, absolute)) continue
|
|
1319
|
-
try {
|
|
1320
|
-
const stat = await fsp.stat(absolute)
|
|
1321
|
-
if (!stat.isFile() || stat.size <= 0 || stat.size > cap) continue
|
|
1322
|
-
return { absolute, stat, root }
|
|
1323
|
-
} catch {
|
|
1324
|
-
// 换下一个 root
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
return null
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
/**
|
|
1331
|
-
* 解析 `Range: bytes=...` 头。
|
|
1332
|
-
* 支持:常规 (0-99)、开放 (100-)、后缀 (-50)、不可满足 (416)。
|
|
1333
|
-
* 多区间取第一个(HTTP 规范允许)。
|
|
1334
|
-
*/
|
|
1335
|
-
function parseMediaRange(raw, size) {
|
|
1336
|
-
if (raw === undefined) return null
|
|
1337
|
-
const m = /^bytes=(.+)$/i.exec(String(raw).trim())
|
|
1338
|
-
if (!m) return null
|
|
1339
|
-
const spec = m[1].split(',')[0].trim()
|
|
1340
|
-
if (spec === '') return null
|
|
1341
|
-
if (spec.startsWith('-')) {
|
|
1342
|
-
const suffix = Number(spec.slice(1))
|
|
1343
|
-
if (!Number.isFinite(suffix) || suffix <= 0) return null
|
|
1344
|
-
if (suffix >= size) return { start: 0, end: size - 1 }
|
|
1345
|
-
return { start: size - suffix, end: size - 1 }
|
|
1346
|
-
}
|
|
1347
|
-
const dash = spec.indexOf('-')
|
|
1348
|
-
if (dash === -1) return null
|
|
1349
|
-
const startText = spec.slice(0, dash)
|
|
1350
|
-
const endText = spec.slice(dash + 1)
|
|
1351
|
-
const start = startText === '' ? 0 : Number(startText)
|
|
1352
|
-
const end = endText === '' ? size - 1 : Number(endText)
|
|
1353
|
-
if (!Number.isInteger(start) || start < 0 || !Number.isInteger(end)) return null
|
|
1354
|
-
if (start >= size) return { unsatisfiable: true }
|
|
1355
|
-
return { start, end: Math.min(end, size - 1) }
|
|
1356
|
-
}
|
|
1357
|
-
|
|
1358
|
-
/**
|
|
1359
|
-
* 用 Node 原生 res 输出一个媒体文件,支持 HTTP Range。
|
|
1360
|
-
* 这是 206 能工作的关键:req/res 直写,不经过 DSH 的 fetch 网关。
|
|
1361
|
-
*/
|
|
1362
|
-
function serveMedia(req, res, filePath, size, type) {
|
|
1363
|
-
const headers = {
|
|
1364
|
-
'content-type': type,
|
|
1365
|
-
'accept-ranges': 'bytes',
|
|
1366
|
-
'cache-control': 'no-cache',
|
|
1367
|
-
'x-content-type-options': 'nosniff',
|
|
1368
|
-
}
|
|
1369
|
-
const range = parseMediaRange(req.headers.range, size)
|
|
1370
|
-
|
|
1371
|
-
if (range !== null && range.unsatisfiable === true) {
|
|
1372
|
-
res.writeHead(416, { ...headers, 'content-range': `bytes */${size}` })
|
|
1373
|
-
res.end()
|
|
1374
|
-
return
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
if (range !== null) {
|
|
1378
|
-
const { start, end } = range
|
|
1379
|
-
res.writeHead(206, {
|
|
1380
|
-
...headers,
|
|
1381
|
-
'content-range': `bytes ${start}-${end}/${size}`,
|
|
1382
|
-
'content-length': String(end - start + 1),
|
|
1383
|
-
})
|
|
1384
|
-
if (req.method === 'HEAD') { res.end(); return }
|
|
1385
|
-
const stream = createReadStream(filePath, { start, end })
|
|
1386
|
-
stream.on('error', () => res.destroy())
|
|
1387
|
-
stream.pipe(res)
|
|
1388
|
-
return
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
res.writeHead(200, { ...headers, 'content-length': String(size) })
|
|
1392
|
-
if (req.method === 'HEAD') { res.end(); return }
|
|
1393
|
-
const stream = createReadStream(filePath)
|
|
1394
|
-
stream.on('error', () => res.destroy())
|
|
1395
|
-
stream.pipe(res)
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
function contentTypeFor(ext) {
|
|
1399
|
-
if (ext === '.png') return 'image/png'
|
|
1400
|
-
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
|
|
1401
|
-
if (ext === '.webp') return 'image/webp'
|
|
1402
|
-
if (ext === '.gif') return 'image/gif'
|
|
1403
|
-
if (ext === '.bmp') return 'image/bmp'
|
|
1404
|
-
// 音视频(v0.10.1):让浏览器 <video>/<audio> 能直接解码
|
|
1405
|
-
if (ext === '.mp4' || ext === '.m4v') return 'video/mp4'
|
|
1406
|
-
if (ext === '.webm') return 'video/webm'
|
|
1407
|
-
if (ext === '.ogv') return 'video/ogg'
|
|
1408
|
-
if (ext === '.mov') return 'video/quicktime'
|
|
1409
|
-
if (ext === '.mkv') return 'video/x-matroska'
|
|
1410
|
-
if (ext === '.mp3') return 'audio/mpeg'
|
|
1411
|
-
if (ext === '.wav') return 'audio/wav'
|
|
1412
|
-
if (ext === '.m4a' || ext === '.aac') return 'audio/mp4'
|
|
1413
|
-
if (ext === '.flac') return 'audio/flac'
|
|
1414
|
-
if (ext === '.ogg' || ext === '.oga') return 'audio/ogg'
|
|
1415
|
-
if (ext === '.opus') return 'audio/opus'
|
|
1416
|
-
return 'application/octet-stream'
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
/** 统一 JSON 响应。 */
|
|
1420
|
-
function json(body, status) {
|
|
1421
|
-
return new Response(JSON.stringify(body), {
|
|
1422
|
-
status: status ?? 200,
|
|
1423
|
-
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
1424
|
-
})
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
/**
|
|
1428
|
-
* Host 插件入口。仅依赖 connection(exact Fetch 路由);缺失时插件不激活而不是抛错。
|
|
1429
|
-
*/
|
|
1430
23
|
export const inject = ['connection', 'webServer']
|
|
1431
24
|
|
|
1432
25
|
export function apply(ctx, config) {
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
* <video src> / <audio src> 需要一个浏览器能直接请求的 URL:
|
|
1436
|
-
* POST 路由不行(媒体元素不会发 POST),所以这里单独注册一个 GET 路径。
|
|
1437
|
-
* 支持 Range,浏览器才能拖进度条、边播边下。
|
|
1438
|
-
*/
|
|
1439
|
-
/**
|
|
1440
|
-
* 媒体直链(v0.11.0):用 ctx.webServer.register 注册 Node 原生路由。
|
|
1441
|
-
*
|
|
1442
|
-
* 为什么从 connection.fetch 换成 webServer?
|
|
1443
|
-
* - fetch 那套是 Web Fetch API(Request/Response),DSH 的网关层不透传 206,
|
|
1444
|
-
* <video src> 拿不到 Range,进度条拖不动(实测确认)。
|
|
1445
|
-
* - webServer 给的是 Node 原生 (req, res),可以 res.writeHead(206) + createReadStream,
|
|
1446
|
-
* 真正的分片流式下发。探针已实证:HEAD 200 / Range 206 / 中段 206 / 后缀 206 全部通过。
|
|
1447
|
-
*
|
|
1448
|
-
* 安全(三道防护,缺一不可):
|
|
1449
|
-
* 1. 路径必须落在扫描 roots 白名单内(isInside)—— 否则能读任意文件
|
|
1450
|
-
* 2. 跨站请求拒绝(sec-fetch-site / origin)
|
|
1451
|
-
* 3. 只允许 GET / HEAD
|
|
1452
|
-
*/
|
|
1453
|
-
ctx.effect(
|
|
1454
|
-
() => ctx.webServer.register({
|
|
1455
|
-
kind: 'prefix',
|
|
1456
|
-
path: MEDIA_ROUTE,
|
|
1457
|
-
handler: async (req, res) => {
|
|
1458
|
-
// ---- 防护 3:只读 ----
|
|
1459
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
1460
|
-
res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1461
|
-
res.end('method not allowed')
|
|
1462
|
-
return
|
|
1463
|
-
}
|
|
1464
|
-
// ---- 防护 2:拒绝跨站 ----
|
|
1465
|
-
const site = req.headers['sec-fetch-site']
|
|
1466
|
-
if (typeof site === 'string' && site === 'cross-site') {
|
|
1467
|
-
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1468
|
-
res.end('cross-site request refused')
|
|
1469
|
-
return
|
|
1470
|
-
}
|
|
1471
|
-
const origin = req.headers.origin
|
|
1472
|
-
if (typeof origin === 'string' && origin !== '') {
|
|
1473
|
-
let originHost = ''
|
|
1474
|
-
try { originHost = new URL(origin).host } catch { originHost = '' }
|
|
1475
|
-
const host = req.headers.host
|
|
1476
|
-
if (originHost !== '' && typeof host === 'string' && originHost !== host) {
|
|
1477
|
-
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1478
|
-
res.end('origin mismatch')
|
|
1479
|
-
return
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
try {
|
|
1484
|
-
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
1485
|
-
const relPath = url.searchParams.get('path') ?? ''
|
|
1486
|
-
if (relPath === '') {
|
|
1487
|
-
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1488
|
-
res.end('missing path')
|
|
1489
|
-
return
|
|
1490
|
-
}
|
|
1491
|
-
const resolved = resolveOptions(config)
|
|
1492
|
-
// ---- 防护 1:路径白名单 ----
|
|
1493
|
-
const found = await resolveReadable(resolved.roots, relPath, resolved, resolved.maxMediaBytes)
|
|
1494
|
-
if (found === null) {
|
|
1495
|
-
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1496
|
-
res.end('not found')
|
|
1497
|
-
return
|
|
1498
|
-
}
|
|
1499
|
-
let stat
|
|
1500
|
-
try {
|
|
1501
|
-
stat = await fsp.stat(found.absolute)
|
|
1502
|
-
} catch (error) {
|
|
1503
|
-
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1504
|
-
res.end(String(error?.message ?? error))
|
|
1505
|
-
return
|
|
1506
|
-
}
|
|
1507
|
-
const type = contentTypeFor(path.extname(found.absolute).toLowerCase())
|
|
1508
|
-
serveMedia(req, res, found.absolute, stat.size, type)
|
|
1509
|
-
} catch (error) {
|
|
1510
|
-
if (!res.headersSent) {
|
|
1511
|
-
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1512
|
-
res.end(String(error?.message ?? error))
|
|
1513
|
-
} else {
|
|
1514
|
-
res.destroy()
|
|
1515
|
-
}
|
|
1516
|
-
}
|
|
1517
|
-
},
|
|
1518
|
-
}),
|
|
1519
|
-
'dsh-gallery: media range route',
|
|
1520
|
-
)
|
|
1521
|
-
|
|
1522
|
-
ctx.effect(
|
|
1523
|
-
() =>
|
|
1524
|
-
ctx.connection.fetch.register({
|
|
1525
|
-
path: ROUTE,
|
|
1526
|
-
methods: ['POST'],
|
|
1527
|
-
requestBody: 'buffered',
|
|
1528
|
-
fetch: async (request) => {
|
|
1529
|
-
let body
|
|
1530
|
-
try {
|
|
1531
|
-
body = await request.json()
|
|
1532
|
-
} catch {
|
|
1533
|
-
body = {}
|
|
1534
|
-
}
|
|
1535
|
-
const op = typeof body?.op === 'string' ? body.op : ''
|
|
1536
|
-
// 每次请求都重新解析配置:这样用户在面板里改 root 后无需重启即生效
|
|
1537
|
-
const resolved = resolveOptions(config)
|
|
1538
|
-
|
|
1539
|
-
if (op === 'list') {
|
|
1540
|
-
try {
|
|
1541
|
-
// 三种画廊:图片 / 文件 / 音视频(v0.10.1)
|
|
1542
|
-
const kind = body?.kind === 'file' ? 'file'
|
|
1543
|
-
: body?.kind === 'media' ? 'media'
|
|
1544
|
-
: 'image'
|
|
1545
|
-
const scope = body?.scope === 'session' ? 'session' : 'global'
|
|
1546
|
-
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''
|
|
1547
|
-
return json(await scanGallery(config, kind, scope, sessionId, body?.page))
|
|
1548
|
-
} catch (error) {
|
|
1549
|
-
return json({ ok: false, error: { code: 'scan-failed', message: String(error?.message ?? error) } }, 500)
|
|
1550
|
-
}
|
|
1551
|
-
}
|
|
1552
|
-
|
|
1553
|
-
// 读取当前设置(含 root 来源、是否存在)
|
|
1554
|
-
if (op === 'settings') {
|
|
1555
|
-
try {
|
|
1556
|
-
return json({ ok: true, settings: await readSettingsPayload(config) })
|
|
1557
|
-
} catch (error) {
|
|
1558
|
-
return json({ ok: false, error: { code: 'settings-failed', message: String(error?.message ?? error) } }, 500)
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
// 修改产出根目录(单值,保留兼容):会覆盖 roots,只留这一个
|
|
1563
|
-
if (op === 'setRoot') {
|
|
1564
|
-
const candidate = body?.root
|
|
1565
|
-
const check = await validateRootCandidate(candidate)
|
|
1566
|
-
if (check.ok !== true) {
|
|
1567
|
-
const messages = {
|
|
1568
|
-
empty: '目录不能为空',
|
|
1569
|
-
'not-absolute': '必须是绝对路径,例如 /Users/you/outputs 或 D:\\产出',
|
|
1570
|
-
'not-directory': '该路径不是目录',
|
|
1571
|
-
'not-found': '目录不存在',
|
|
1572
|
-
}
|
|
1573
|
-
return json({
|
|
1574
|
-
ok: false,
|
|
1575
|
-
error: { code: check.reason, message: messages[check.reason] ?? '目录无效' },
|
|
1576
|
-
}, 400)
|
|
1577
|
-
}
|
|
1578
|
-
try {
|
|
1579
|
-
const opts = resolveOptions(config)
|
|
1580
|
-
// 写 roots 数组,并把旧的单值 root 清掉,避免重复
|
|
1581
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1582
|
-
delete current.root
|
|
1583
|
-
await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
|
|
1584
|
-
await fsp.writeFile(
|
|
1585
|
-
opts.settingsFile,
|
|
1586
|
-
JSON.stringify({ ...current, roots: [check.root] }, null, 2),
|
|
1587
|
-
'utf8',
|
|
1588
|
-
)
|
|
1589
|
-
return json({ ok: true, settings: await readSettingsPayload(config) })
|
|
1590
|
-
} catch (error) {
|
|
1591
|
-
return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
|
|
1595
|
-
// 追加一个扫描目录(多目录支持)
|
|
1596
|
-
if (op === 'addRoot') {
|
|
1597
|
-
const check = await validateRootCandidate(body?.root)
|
|
1598
|
-
if (check.ok !== true) {
|
|
1599
|
-
const messages = {
|
|
1600
|
-
empty: '目录不能为空',
|
|
1601
|
-
'not-absolute': '必须是绝对路径',
|
|
1602
|
-
'not-directory': '该路径不是目录',
|
|
1603
|
-
'not-found': '目录不存在',
|
|
1604
|
-
}
|
|
1605
|
-
return json({ ok: false, error: { code: check.reason, message: messages[check.reason] ?? '目录无效' } }, 400)
|
|
1606
|
-
}
|
|
1607
|
-
try {
|
|
1608
|
-
const opts = resolveOptions(config)
|
|
1609
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1610
|
-
const list = Array.isArray(current.roots) && current.roots.length > 0
|
|
1611
|
-
? current.roots.slice()
|
|
1612
|
-
: opts.roots.slice()
|
|
1613
|
-
// 去重(大小写不敏感)
|
|
1614
|
-
if (!list.some((r) => path.resolve(r).toLowerCase() === check.root.toLowerCase())) {
|
|
1615
|
-
list.push(check.root)
|
|
1616
|
-
}
|
|
1617
|
-
delete current.root
|
|
1618
|
-
await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
|
|
1619
|
-
await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, roots: list }, null, 2), 'utf8')
|
|
1620
|
-
return json({ ok: true, settings: await readSettingsPayload(config) })
|
|
1621
|
-
} catch (error) {
|
|
1622
|
-
return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
// 移除一个扫描目录
|
|
1627
|
-
if (op === 'removeRoot') {
|
|
1628
|
-
const target = typeof body?.root === 'string' ? body.root.trim() : ''
|
|
1629
|
-
if (target === '') {
|
|
1630
|
-
return json({ ok: false, error: { code: 'empty', message: '缺少要移除的目录' } }, 400)
|
|
1631
|
-
}
|
|
1632
|
-
try {
|
|
1633
|
-
const opts = resolveOptions(config)
|
|
1634
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1635
|
-
const list = (Array.isArray(current.roots) && current.roots.length > 0
|
|
1636
|
-
? current.roots.slice()
|
|
1637
|
-
: opts.roots.slice()
|
|
1638
|
-
).filter((r) => path.resolve(r).toLowerCase() !== path.resolve(target).toLowerCase())
|
|
1639
|
-
if (list.length === 0) {
|
|
1640
|
-
return json({ ok: false, error: { code: 'last-root', message: '至少要保留一个扫描目录' } }, 400)
|
|
1641
|
-
}
|
|
1642
|
-
delete current.root
|
|
1643
|
-
await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
|
|
1644
|
-
await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, roots: list }, null, 2), 'utf8')
|
|
1645
|
-
return json({ ok: true, settings: await readSettingsPayload(config) })
|
|
1646
|
-
} catch (error) {
|
|
1647
|
-
return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
if (op === 'raw') {
|
|
1652
|
-
const found = await resolveReadable(resolved.roots, body?.path, resolved)
|
|
1653
|
-
if (found === null) return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
|
|
1654
|
-
let bytes
|
|
1655
|
-
try {
|
|
1656
|
-
bytes = await fsp.readFile(found.absolute)
|
|
1657
|
-
} catch (error) {
|
|
1658
|
-
return json({ ok: false, error: { code: 'read-failed', message: String(error?.message ?? error) } }, 500)
|
|
1659
|
-
}
|
|
1660
|
-
return new Response(bytes, {
|
|
1661
|
-
status: 200,
|
|
1662
|
-
headers: {
|
|
1663
|
-
'content-type': contentTypeFor(path.extname(found.absolute).toLowerCase()),
|
|
1664
|
-
'content-length': String(bytes.byteLength),
|
|
1665
|
-
'cache-control': 'no-store',
|
|
1666
|
-
},
|
|
1667
|
-
})
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
// 在文件管理器中定位该文件(仅 Windows)
|
|
1671
|
-
if (op === 'reveal') {
|
|
1672
|
-
// reveal 要能定位大文件,所以用媒体上限(这里取两者较大值)
|
|
1673
|
-
const capForReveal = Math.max(resolved.maxImageBytes, resolved.maxMediaBytes)
|
|
1674
|
-
const found = await resolveReadable(resolved.roots, body?.path, resolved, capForReveal)
|
|
1675
|
-
if (found === null) {
|
|
1676
|
-
return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
|
|
1677
|
-
}
|
|
1678
|
-
// mode: 'select' 在文件夹里选中文件;'play' 尝试用默认程序打开(对媒体更直接)
|
|
1679
|
-
const mode = body?.mode === 'play' ? 'play' : 'select'
|
|
1680
|
-
try {
|
|
1681
|
-
const { spawn } = await import('node:child_process')
|
|
1682
|
-
let child
|
|
1683
|
-
if (process.platform === 'win32') {
|
|
1684
|
-
if (mode === 'play') {
|
|
1685
|
-
// cmd start:让 shell 按文件关联打开。空字符串是窗口标题占位,
|
|
1686
|
-
// 不占位的话中文路径会被当作窗口标题。
|
|
1687
|
-
child = spawn('cmd.exe', ['/c', 'start', '', found.absolute], {
|
|
1688
|
-
detached: true, stdio: 'ignore', windowsHide: true,
|
|
1689
|
-
})
|
|
1690
|
-
} else {
|
|
1691
|
-
// explorer /select 在直接 spawn 时对含中文的路径会以退出码 1 失败(已实测)。
|
|
1692
|
-
// 改走 cmd /c start "" explorer.exe /select,"<path>":让 cmd 负责引号与编码,
|
|
1693
|
-
// 这是 Windows 上打开并选中中文路径文件的稳定写法。
|
|
1694
|
-
child = spawn('cmd.exe', [
|
|
1695
|
-
'/c', 'start', '',
|
|
1696
|
-
'explorer.exe', `/select,"${found.absolute}"`,
|
|
1697
|
-
], {
|
|
1698
|
-
detached: true, stdio: 'ignore', windowsHide: true,
|
|
1699
|
-
})
|
|
1700
|
-
}
|
|
1701
|
-
} else {
|
|
1702
|
-
child = spawn('xdg-open', [mode === 'play' ? found.absolute : path.dirname(found.absolute)], {
|
|
1703
|
-
detached: true, stdio: 'ignore',
|
|
1704
|
-
})
|
|
1705
|
-
}
|
|
1706
|
-
// 不要 unref 立即丢:先观察 800ms 内的错误与退出码,异常时报给前端
|
|
1707
|
-
const outcome = await new Promise((resolve) => {
|
|
1708
|
-
let settled = false
|
|
1709
|
-
const done = (payload) => {
|
|
1710
|
-
if (settled) return
|
|
1711
|
-
settled = true
|
|
1712
|
-
resolve(payload)
|
|
1713
|
-
}
|
|
1714
|
-
child.on('error', (error) => done({
|
|
1715
|
-
ok: false, code: 'spawn-error', message: String(error?.message ?? error),
|
|
1716
|
-
}))
|
|
1717
|
-
child.on('exit', (code, signal) => {
|
|
1718
|
-
// explorer 成功时通常很快退出(它把活交给已有 explorer 进程)
|
|
1719
|
-
if (mode === 'play') {
|
|
1720
|
-
// cmd start 退出码 0 表示已交给关联程序
|
|
1721
|
-
done(code === 0 || code === null
|
|
1722
|
-
? { ok: true, exitCode: code, signal }
|
|
1723
|
-
: { ok: false, code: 'exit-nonzero', message: `exit ${code}`, exitCode: code })
|
|
1724
|
-
} else {
|
|
1725
|
-
// 现在 select 也走 cmd start,退出码 0 表示命令已被接受
|
|
1726
|
-
done(code === 0 || code === null
|
|
1727
|
-
? { ok: true, exitCode: code, signal }
|
|
1728
|
-
: { ok: false, code: 'select-exit-nonzero', message: `cmd start 退出码 ${code}`, exitCode: code })
|
|
1729
|
-
}
|
|
1730
|
-
})
|
|
1731
|
-
setTimeout(() => done({ ok: true, note: 'assumed-ok-after-800ms' }), 800)
|
|
1732
|
-
})
|
|
1733
|
-
if (child !== undefined && typeof child.unref === 'function' && outcome.ok) {
|
|
1734
|
-
try { child.unref() } catch {}
|
|
1735
|
-
}
|
|
1736
|
-
if (!outcome.ok) {
|
|
1737
|
-
return json({ ok: false, error: { code: outcome.code, message: outcome.message, mode }, detail: outcome }, 500)
|
|
1738
|
-
}
|
|
1739
|
-
return json({ ok: true, mode, detail: outcome })
|
|
1740
|
-
} catch (error) {
|
|
1741
|
-
return json({
|
|
1742
|
-
ok: false,
|
|
1743
|
-
error: { code: 'reveal-failed', message: String(error?.message ?? error), mode },
|
|
1744
|
-
}, 500)
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
|
|
1748
|
-
// ---------- 隐藏 / 取消隐藏 ----------
|
|
1749
|
-
// 隐藏只记路径,不动文件;列表扫描时过滤掉。
|
|
1750
|
-
if (op === 'hide' || op === 'unhide') {
|
|
1751
|
-
const rel = body?.path
|
|
1752
|
-
if (typeof rel !== 'string' || rel === '') {
|
|
1753
|
-
return json({ ok: false, error: { code: 'invalid-path', message: '缺少文件路径' } }, 400)
|
|
1754
|
-
}
|
|
1755
|
-
const normalized = rel.replace(/\\/g, '/')
|
|
1756
|
-
if (normalized.split('/').some((s) => s === '..' || s === '')) {
|
|
1757
|
-
return json({ ok: false, error: { code: 'invalid-path', message: '路径非法' } }, 400)
|
|
1758
|
-
}
|
|
1759
|
-
try {
|
|
1760
|
-
const opts = resolveOptions(config)
|
|
1761
|
-
const hidden = new Set(await readHiddenList(opts.settingsFile))
|
|
1762
|
-
if (op === 'hide') hidden.add(normalized)
|
|
1763
|
-
else hidden.delete(normalized)
|
|
1764
|
-
await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
|
|
1765
|
-
// 只改 hidden 字段,其余设置保留
|
|
1766
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1767
|
-
const next = { ...current, hidden: [...hidden] }
|
|
1768
|
-
await fsp.writeFile(opts.settingsFile, JSON.stringify(next, null, 2), 'utf8')
|
|
1769
|
-
return json({ ok: true, hidden: hidden.size })
|
|
1770
|
-
} catch (error) {
|
|
1771
|
-
return json({ ok: false, error: { code: 'hide-failed', message: String(error?.message ?? error) } }, 500)
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
|
|
1775
|
-
// ---------- 全部恢复(清空隐藏列表)----------
|
|
1776
|
-
if (op === 'clearHidden') {
|
|
1777
|
-
try {
|
|
1778
|
-
const opts = resolveOptions(config)
|
|
1779
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1780
|
-
const before = Array.isArray(current.hidden) ? current.hidden.length : 0
|
|
1781
|
-
await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
|
|
1782
|
-
await fsp.writeFile(
|
|
1783
|
-
opts.settingsFile,
|
|
1784
|
-
JSON.stringify({ ...current, hidden: [] }, null, 2),
|
|
1785
|
-
'utf8',
|
|
1786
|
-
)
|
|
1787
|
-
return json({ ok: true, cleared: before })
|
|
1788
|
-
} catch (error) {
|
|
1789
|
-
return json({ ok: false, error: { code: 'clear-failed', message: String(error?.message ?? error) } }, 500)
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
|
|
1793
|
-
// ---------- 删除文件(不可逆,前端必须二次确认)----------
|
|
1794
|
-
if (op === 'delete') {
|
|
1795
|
-
const found = await resolveReadable(resolved.roots, body?.path, resolved)
|
|
1796
|
-
if (found === null) return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
|
|
1797
|
-
// 双保险:前端未明确确认则拒绝执行
|
|
1798
|
-
if (body?.confirm !== true) {
|
|
1799
|
-
return json({ ok: false, error: { code: 'need-confirm', message: '需要确认后才能删除' } }, 400)
|
|
1800
|
-
}
|
|
1801
|
-
try {
|
|
1802
|
-
await fsp.rm(found.absolute, { force: true })
|
|
1803
|
-
// 删除后从隐藏列表里清掉,避免残留
|
|
1804
|
-
const opts = resolveOptions(config)
|
|
1805
|
-
const hidden = new Set(await readHiddenList(opts.settingsFile))
|
|
1806
|
-
const rel = body?.path.replace(/\\/g, '/')
|
|
1807
|
-
if (hidden.has(rel)) {
|
|
1808
|
-
hidden.delete(rel)
|
|
1809
|
-
const current = readSettingsFile(opts.settingsFile)
|
|
1810
|
-
await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, hidden: [...hidden] }, null, 2), 'utf8')
|
|
1811
|
-
}
|
|
1812
|
-
return json({ ok: true, deleted: found.absolute })
|
|
1813
|
-
} catch (error) {
|
|
1814
|
-
return json({ ok: false, error: { code: 'delete-failed', message: String(error?.message ?? error) } }, 500)
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
|
|
1818
|
-
return json({ ok: false, error: { code: 'unknown-op', message: `未知操作:${op}` } }, 400)
|
|
1819
|
-
},
|
|
1820
|
-
}),
|
|
1821
|
-
'dsh-gallery: api route',
|
|
1822
|
-
)
|
|
26
|
+
registerMediaRoute(ctx, config)
|
|
27
|
+
registerOpsRoute(ctx, config)
|
|
1823
28
|
}
|
|
29
|
+
|
|
30
|
+
// 对外再导出(保持与拆分前的公开接口一致)
|
|
31
|
+
export { ROUTE, MEDIA_ROUTE } from './host/constants.js'
|
|
32
|
+
export { scanGallery } from './host/scan.js'
|
|
33
|
+
export { validateRootCandidate, writeSettingsFile } from './host/settings.js'
|