dsh-gallery 0.12.1 → 0.13.7

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.
@@ -0,0 +1,193 @@
1
+ // GENERATED from src/shared/feedback-text.js — 请勿手改
2
+ /**
3
+ * 反馈契约 v1 —— 纯函数,Host 与 Client 双端复用。
4
+ *
5
+ * 由 scripts/build.mjs 沿用 protocol.js 的做法:
6
+ * · 剥掉 export 注入 client bundle
7
+ * · 生成 host/feedback-text.js 供 Host 侧 import
8
+ *
9
+ * 设计原则(调研结论,见 docs/migration.md 与调研报告):
10
+ * 1. 反馈是**契约**不是自由文本:带锚点(relPath)、动作类型、理由、目标会话。
11
+ * 2. **攒批 + 一次发送**:多条标记合成一条消息,不逐条发。
12
+ * 3. **人确认闸门**:本模块只负责「产出草稿文本」,发送由用户在 composer 里点。
13
+ * 4. **显式 changeOnly / keep**:生成类工作流实证「只改 X、其余锁死」远好于「再改改」。
14
+ * 5. 逐条用 `Annotation N:` 编号,便于模型逐条回应(参考 dsh-quote-annotate-pro 契约)。
15
+ */
16
+
17
+ /** 首版 6 个动作。值即契约里的 action 字符串,不要随意改(已写进 marks 文件)。 */
18
+ export const ACTIONS = [
19
+ 'approve',
20
+ 'reject',
21
+ 'finalize',
22
+ 'redo-one-dim',
23
+ 'regenerate-selected',
24
+ 'set-reference',
25
+ ]
26
+
27
+ /** 动作 → 中文动词(生成草稿正文用)。 */
28
+ export const ACTION_LABELS_ZH = {
29
+ approve: '通过',
30
+ reject: '不要这张',
31
+ finalize: '定为最终版',
32
+ 'redo-one-dim': '单维重做',
33
+ 'regenerate-selected': '选择性重生成',
34
+ 'set-reference': '设为参照',
35
+ }
36
+
37
+ /** 动作 → 英文动词。 */
38
+ export const ACTION_LABELS_EN = {
39
+ approve: 'approve',
40
+ reject: 'reject',
41
+ finalize: 'finalize',
42
+ 'redo-one-dim': 'redo one dimension',
43
+ 'regenerate-selected': 'regenerate',
44
+ 'set-reference': 'set as reference',
45
+ }
46
+
47
+ /** 契约版本。检查项会核对。 */
48
+ export const SCHEMA = 1
49
+
50
+ /** 来源标识。 */
51
+ export const SOURCE = 'dsh-gallery'
52
+
53
+ /** 常用「只改」维度候选(给 UI 做快捷输入,不是强制枚举)。 */
54
+ export const CHANGE_CANDIDATES = [
55
+ '色调', '亮度', '材质', '构图', '透视', '比例', '文字', '光线', '风格', '细节',
56
+ ]
57
+
58
+ /** 常用的「锁死」项候选。 */
59
+ export const KEEP_CANDIDATES = [
60
+ '构图', '人物位置', '主体比例', '透视角度', '文字内容', '整体风格', '配色基调',
61
+ ]
62
+
63
+ /**
64
+ * 构造一条反馈项。
65
+ * @param item - { relPath, category, action, reason?, changeOnly?, keep?, preserve?, region?, params? }
66
+ * @returns 规范化后的 feedback item
67
+ */
68
+ export function makeItem(item) {
69
+ const out = {
70
+ relPath: String(item?.relPath ?? ''),
71
+ category: String(item?.category ?? 'unknown'),
72
+ action: ACTIONS.includes(item?.action) ? item.action : 'approve',
73
+ }
74
+ if (typeof item?.reason === 'string' && item.reason.trim() !== '') out.reason = item.reason.trim()
75
+ if (Array.isArray(item?.changeOnly) && item.changeOnly.length > 0) {
76
+ out.changeOnly = item.changeOnly.map((x) => String(x)).filter((x) => x !== '')
77
+ }
78
+ if (Array.isArray(item?.keep) && item.keep.length > 0) {
79
+ out.keep = item.keep.map((x) => String(x)).filter((x) => x !== '')
80
+ }
81
+ if (Array.isArray(item?.preserve) && item.preserve.length > 0) {
82
+ out.preserve = item.preserve.map((x) => String(x)).filter((x) => x !== '')
83
+ }
84
+ if (item?.region !== undefined && item.region !== null) out.region = item.region
85
+ if (item?.params !== undefined && item.params !== null) out.params = item.params
86
+ return out
87
+ }
88
+
89
+ /**
90
+ * 构造一份反馈草稿(契约对象)。
91
+ * @param args - { sessionId, items, status? }
92
+ */
93
+ export function makeFeedback(args) {
94
+ return {
95
+ schema: SCHEMA,
96
+ source: SOURCE,
97
+ sessionId: String(args?.sessionId ?? ''),
98
+ status: args?.status === 'sent' ? 'sent' : 'draft',
99
+ items: (Array.isArray(args?.items) ? args.items : []).map(makeItem),
100
+ createdAt: typeof args?.createdAt === 'number' ? args.createdAt : Date.now(),
101
+ }
102
+ }
103
+
104
+ /** 文件名取路径末段。 */
105
+ function baseName(relPath) {
106
+ const s = String(relPath ?? '')
107
+ const i = s.lastIndexOf('/')
108
+ return i >= 0 ? s.slice(i + 1) : s
109
+ }
110
+
111
+ /**
112
+ * 把契约渲染成**人类与模型都能读的草稿正文**。
113
+ *
114
+ * 关键要求(调研结论 4):每条必须同时写「只改 X」与「其余锁死」,
115
+ * 否则模型容易把整张重画。
116
+ *
117
+ * @param feedback - makeFeedback() 的产物
118
+ * @param options - { locale?: 'zh'|'en', targetSessionTitle?: string }
119
+ * @returns 纯文本(可直接 setDraft 进 composer)
120
+ */
121
+ export function renderFeedbackText(feedback, options) {
122
+ const locale = options?.locale === 'en' ? 'en' : 'zh'
123
+ const labels = locale === 'en' ? ACTION_LABELS_EN : ACTION_LABELS_ZH
124
+ const items = Array.isArray(feedback?.items) ? feedback.items : []
125
+
126
+ if (items.length === 0) {
127
+ return locale === 'en'
128
+ ? '(No items in the feedback basket.)'
129
+ : '(反馈篮里还没有条目。)'
130
+ }
131
+
132
+ const lines = []
133
+ if (locale === 'en') {
134
+ lines.push(`[Feedback from dsh-gallery · ${items.length} item(s)]`)
135
+ lines.push('')
136
+ lines.push('Reply item by item using the `Annotation N:` prefix, so each decision maps to one annotation.')
137
+ lines.push('')
138
+ } else {
139
+ lines.push(`【产出画廊反馈 · 共 ${items.length} 条】`)
140
+ lines.push('')
141
+ lines.push('请按 `Annotation 1:`、`Annotation 2:` … 逐条回应,让每条决定都对应到一个批注。')
142
+ lines.push('')
143
+ }
144
+
145
+ items.forEach((item, idx) => {
146
+ const n = idx + 1
147
+ const name = baseName(item.relPath)
148
+ const verb = labels[item.action] ?? item.action
149
+ lines.push(`Annotation ${n}:${verb} —— ${name}`)
150
+ lines.push(`${locale === 'en' ? 'Path' : '路径'}:${item.relPath}`)
151
+ if (item.reason !== undefined) {
152
+ lines.push(`${locale === 'en' ? 'Reason' : '理由'}:${item.reason}`)
153
+ }
154
+ if (Array.isArray(item.changeOnly) && item.changeOnly.length > 0) {
155
+ lines.push(locale === 'en'
156
+ ? `changeOnly: ${item.changeOnly.join(' / ')}`
157
+ : `只改:${item.changeOnly.join(' / ')}`)
158
+ }
159
+ if (Array.isArray(item.keep) && item.keep.length > 0) {
160
+ lines.push(locale === 'en'
161
+ ? `keep locked: ${item.keep.join(' / ')}`
162
+ : `锁死(其余不动):${item.keep.join(' / ')}`)
163
+ }
164
+ if (Array.isArray(item.preserve) && item.preserve.length > 0) {
165
+ lines.push(locale === 'en'
166
+ ? `preserve: ${item.preserve.join(' / ')}`
167
+ : `保留:${item.preserve.join(' / ')}`)
168
+ }
169
+ if (item.region !== undefined && item.region !== null) {
170
+ lines.push(`${locale === 'en' ? 'Region' : '区域'}:${JSON.stringify(item.region)}`)
171
+ }
172
+ if (item.params !== undefined && item.params !== null) {
173
+ lines.push(`${locale === 'en' ? 'Params' : '参数'}:${JSON.stringify(item.params)}`)
174
+ }
175
+ lines.push('')
176
+ })
177
+
178
+ // 收口指令:把「锁死」原则再强调一次(防模型整张重画)
179
+ if (locale === 'en') {
180
+ lines.push('Unless an annotation says otherwise, keep everything else unchanged — do not regenerate wholesale.')
181
+ } else {
182
+ lines.push('除上述明确要改的部分外,其余全部保持原样,不要整张重做。')
183
+ }
184
+
185
+ return lines.join('\n')
186
+ }
187
+
188
+ /**
189
+ * 把契约序列化成 JSON(导出 / 落盘 / 审计用,与渲染同一个 shape)。
190
+ */
191
+ export function serializeFeedback(feedback) {
192
+ return JSON.stringify(feedback, null, 2)
193
+ }
package/host/http.js CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { promises as fsp } from 'node:fs'
12
+ import { createHash } from 'node:crypto'
12
13
  import path from 'node:path'
13
14
 
14
15
  import { ROUTE, MEDIA_ROUTE } from './constants.js'
@@ -19,6 +20,29 @@ import {
19
20
  } from './settings.js'
20
21
  import { scanGallery } from './scan.js'
21
22
  import { resolveReadable, serveMedia, contentTypeFor } from './media.js'
23
+ import { MARK_ACTIONS, readMarks, writeMarks, setMark, setMarksBatch, marksFilePath } from './marks.js'
24
+
25
+ /** reveal 相关的排查日志(失败/异常时便于定位,不影响功能)。 */
26
+ /**
27
+ * 把相对路径解析到 roots 内的绝对路径(v0.13.7,删除闸门用)。
28
+ * 解析不出 / 越界返回 null。
29
+ */
30
+ function resolveUnderRoots(roots, relPath) {
31
+ if (!Array.isArray(roots) || roots.length === 0) return null
32
+ for (const root of roots) {
33
+ if (typeof root !== "string" || root === "") continue
34
+ const abs = path.resolve(root, relPath)
35
+ if (!isInside(root, abs)) continue
36
+ return abs
37
+ }
38
+ return null
39
+ }
40
+
41
+ function LOG_RESOLVE(label, detail) {
42
+ if (process.env.DSH_GALLERY_DEBUG === '1') {
43
+ try { console.info('dsh-gallery ' + label, JSON.stringify(detail)) } catch { /* 忽略 */ }
44
+ }
45
+ }
22
46
 
23
47
  /** 统一 JSON 响应。 */
24
48
  function json(body, status) {
@@ -479,156 +503,341 @@ export function registerOpsRoute(ctx, config) {
479
503
 
480
504
  // 在文件管理器中定位该文件(仅 Windows)
481
505
 
482
- if (op === 'reveal') {
506
+ // ---- 标记(S3-a)----
507
+ if (op === 'getMarks') {
508
+ const settingsFile = resolveOptions(config).settingsFile
509
+ const stored = await readMarks(settingsFile)
510
+ return json({ ok: true, marks: stored.marks })
511
+ }
483
512
 
484
- // reveal 要能定位大文件,所以用媒体上限(这里取两者较大值)
513
+ if (op === 'marks') {
514
+ const relPath = String(body?.path ?? '')
515
+ if (relPath === '') {
516
+ return json({ ok: false, error: { code: 'bad-request', message: '缺少 path' } }, 400)
517
+ }
518
+ // mark 为 null 表示清除;否则校验 action 合法性
519
+ const mark = body?.mark
520
+ if (mark !== null && mark !== undefined) {
521
+ if (typeof mark !== 'object' || !MARK_ACTIONS.includes(mark.action)) {
522
+ return json({ ok: false, error: { code: 'bad-request', message: 'action 不合法' } }, 400)
523
+ }
524
+ }
525
+ try {
526
+ const settingsFile = resolveOptions(config).settingsFile
527
+ const next = await setMark(settingsFile, relPath, mark === undefined ? null : mark)
528
+ return json({ ok: true, marks: next })
529
+ } catch (error) {
530
+ return json({ ok: false, error: { code: 'marks-write-failed', message: String(error?.message ?? error) } }, 500)
531
+ }
532
+ }
485
533
 
486
- const capForReveal = Math.max(resolved.maxImageBytes, resolved.maxMediaBytes)
534
+ if (op === 'marksBatch') {
535
+ /**
536
+ * 批量设 / 清标记(v0.13.7)。
537
+ *
538
+ * 一次写入搞定多个卡片,避免「批量确认 20 张 → 20 次读改写」。
539
+ * 仍然是**只改标记文件、绝不改写自动分类**(数据边界)。
540
+ *
541
+ * body: { updates: [{ path, mark }] } mark 为 null 表示清除
542
+ */
543
+ const updates = Array.isArray(body?.updates) ? body.updates : null
544
+ if (updates === null) {
545
+ return json({ ok: false, error: { code: 'bad-request', message: '缺少 updates 数组' } }, 400)
546
+ }
547
+ if (updates.length > 200) {
548
+ return json({ ok: false, error: { code: 'too-many', message: '单次最多 200 条' } }, 400)
549
+ }
550
+ for (const u of updates) {
551
+ if (typeof u?.path !== 'string' || u.path === '') {
552
+ return json({ ok: false, error: { code: 'bad-request', message: 'updates 里有非法 path' } }, 400)
553
+ }
554
+ const m = u.mark
555
+ if (m !== null && m !== undefined) {
556
+ if (typeof m !== 'object' || !MARK_ACTIONS.includes(m.action)) {
557
+ return json({ ok: false, error: { code: 'bad-request', message: 'action 不合法:' + String(m?.action) } }, 400)
558
+ }
559
+ }
560
+ }
561
+ try {
562
+ const settingsFile = resolveOptions(config).settingsFile
563
+ const next = await setMarksBatch(settingsFile, updates)
564
+ return json({ ok: true, marks: next, applied: updates.length })
565
+ } catch (error) {
566
+ return json({ ok: false, error: { code: 'marks-write-failed', message: String(error?.message ?? error) } }, 500)
567
+ }
568
+ }
487
569
 
488
- const found = await resolveReadable(resolved.roots, body?.path, resolved, capForReveal)
570
+ if (op === 'deleteDiscarded') {
571
+ /**
572
+ * 清掉废稿(v0.13.7)—— **永久删除、不进回收站、不可逆**。
573
+ *
574
+ * 安全闸门(缺一不可):
575
+ * 1. 两阶段:先 dryRun 拿清单,人看完再 confirm 真删
576
+ * 2. 清单一致性:真删时用 digest 校验「删的就是刚才看过的那批」
577
+ * 3. 每批上限 10 个(超过由前端分批,服务端再兜一层)
578
+ * 4. 只删 roots 内的普通文件
579
+ * 5. 绝不删插件自己的数据文件(settings / marks)
580
+ * 6. 删完同步清掉对应 marks,并返回被清的路径供前端清反馈篮
581
+ *
582
+ * body: { paths: string[], dryRun?: boolean, confirm?: boolean, digest?: string }
583
+ */
584
+ const paths = Array.isArray(body?.paths) ? body.paths : null
585
+ if (paths === null || paths.length === 0) {
586
+ return json({ ok: false, error: { code: 'bad-request', message: '缺少 paths 数组' } }, 400)
587
+ }
588
+ if (paths.length > 10) {
589
+ return json({
590
+ ok: false,
591
+ error: { code: 'batch-too-large', message: '单批最多 10 个,请分批处理', count: paths.length },
592
+ }, 400)
593
+ }
489
594
 
490
- if (found === null) {
595
+ const opts = resolveOptions(config)
596
+ const settingsFile = opts.settingsFile
597
+ const marksFile = marksFilePath(settingsFile)
598
+ const forbidden = new Set([settingsFile, marksFile, settingsFile + '.tmp', marksFile + '.tmp'])
599
+
600
+ // ---- 逐个解析并校验 ----
601
+ const entries = []
602
+ const rejected = []
603
+ for (const p of paths) {
604
+ const relPath = String(p ?? '')
605
+ if (relPath === '') { rejected.push({ path: relPath, reason: 'empty-path' }); continue }
606
+ let abs
607
+ try {
608
+ abs = path.isAbsolute(relPath) ? relPath : resolveUnderRoots(opts.roots, relPath)
609
+ } catch {
610
+ rejected.push({ path: relPath, reason: 'outside-roots' }); continue
611
+ }
612
+ if (abs === null || abs === undefined) {
613
+ rejected.push({ path: relPath, reason: 'outside-roots' }); continue
614
+ }
615
+ // 插件自身数据文件一律拒绝
616
+ if (forbidden.has(abs)) {
617
+ rejected.push({ path: relPath, reason: 'plugin-data-file' }); continue
618
+ }
619
+ let st
620
+ try {
621
+ st = await fsp.stat(abs)
622
+ } catch {
623
+ rejected.push({ path: relPath, reason: 'not-found' }); continue
624
+ }
625
+ if (!st.isFile()) {
626
+ rejected.push({ path: relPath, reason: 'not-a-file' }); continue
627
+ }
628
+ entries.push({ relPath, absolute: abs, size: st.size })
629
+ }
491
630
 
492
- return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
631
+ // 清单指纹:路径排序后 hash,确保「确认的就是看过的」
632
+ const digestOf = (list) => {
633
+ const h = createHash('sha1')
634
+ for (const e of [...list].map((x) => x.absolute).sort()) h.update(e)
635
+ return h.digest('hex')
636
+ }
637
+ const digest = digestOf(entries)
638
+
639
+ // ---- dryRun:只列清单,不动磁盘 ----
640
+ if (body?.dryRun === true) {
641
+ return json({
642
+ ok: true,
643
+ dryRun: true,
644
+ count: entries.length,
645
+ digest,
646
+ files: entries.map((e) => ({ path: e.relPath, absolute: e.absolute, size: e.size })),
647
+ rejected,
648
+ })
649
+ }
650
+
651
+ // ---- 真删:必须显式 confirm + digest 一致 ----
652
+ if (body?.confirm !== true) {
653
+ return json({ ok: false, error: { code: 'confirm-required', message: '缺少 confirm 标记' } }, 400)
654
+ }
655
+ if (typeof body?.digest !== 'string' || body.digest !== digest) {
656
+ return json({
657
+ ok: false,
658
+ error: { code: 'digest-mismatch', message: '文件清单已变化(可能被重新扫描或改动),请重新确认' },
659
+ }, 409)
660
+ }
661
+
662
+ // ---- 执行删除(任一批失败立即停,不自动重试)----
663
+ const deleted = []
664
+ const failed = []
665
+ for (const e of entries) {
666
+ try {
667
+ await fsp.unlink(e.absolute)
668
+ deleted.push(e.relPath)
669
+ } catch (error) {
670
+ failed.push({ path: e.relPath, reason: String(error?.message ?? error) })
671
+ }
672
+ }
493
673
 
674
+ // ---- 同步清掉这些路径的 marks ----
675
+ let marksLeft = {}
676
+ if (deleted.length > 0) {
677
+ try {
678
+ const cur = await readMarks(settingsFile)
679
+ const next = { ...cur.marks }
680
+ for (const rp of deleted) delete next[rp]
681
+ await writeMarks(settingsFile, next)
682
+ marksLeft = next
683
+ } catch (error) {
684
+ return json({
685
+ ok: false,
686
+ error: {
687
+ code: 'marks-cleanup-failed',
688
+ message: '文件已删但标记清理失败:' + String(error?.message ?? error),
689
+ deleted,
690
+ },
691
+ }, 500)
692
+ }
494
693
  }
495
694
 
496
- // mode: 'select' 在文件夹里选中文件;'play' 尝试用默认程序打开(对媒体更直接)
695
+ return json({
696
+ ok: failed.length === 0,
697
+ deleted,
698
+ failed,
699
+ rejected,
700
+ marks: marksLeft,
701
+ note: `永久删除 ${deleted.length} 个文件(不进回收站)`,
702
+ })
703
+ }
704
+
705
+ if (op === 'reveal') {
706
+ /**
707
+ * 在资源管理器里定位 / 用系统程序打开。
708
+ *
709
+ * ⚠️ 历史坑(v0.13.5 及以前,「打开所在文件夹」一律打开「文档」):
710
+ * 旧实现 spawn('cmd.exe', ['/c','start','','explorer.exe', `/select,"${abs}"`])
711
+ * 手写的双引号经 Node spawn 的自动 quoting + cmd start 两层转义后
712
+ * **残留在路径里**,explorer 实际收到 `/select,"G:\...png"` —— 引号成了字面字符,
713
+ * 解析失败 → 回退打开默认位置「文档」。与文件名/类型/空格无关,三类资产全中。
714
+ *
715
+ * 修法:**不再手工加引号、不经 cmd 中转**,直接 spawn 目标程序,
716
+ * 让 Node 自己处理空格与中文的 quoting(实测 argv 干净)。
717
+ *
718
+ * 另:不再用退出码当「已定位到」的证据 ——
719
+ * explorer 参数无效时 cmd 照样退出 0,那是**假成功**。
720
+ * 现在语义是「命令已发出」,返回体带 absolute / via / platform 供排查。
721
+ */
722
+ LOG_RESOLVE('reveal: 开始', { path: body?.path, mode: body?.mode })
723
+
724
+ // 定位文件不该受大小限制 —— 只校验存在 + 是否文件 + 路径越界。
725
+ // 传 Infinity 让 resolveReadable 的 size 检查失效(它只跳过 size > cap 的项)。
726
+ const found = await resolveReadable(resolved.roots, body?.path, resolved, Number.MAX_SAFE_INTEGER)
727
+ if (found === null) {
728
+ return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
729
+ }
497
730
 
731
+ // mode: 'select' 在文件夹里选中文件;'play' 用默认程序打开(对媒体更直接)
498
732
  const mode = body?.mode === 'play' ? 'play' : 'select'
733
+ const absolute = found.absolute
499
734
 
500
735
  try {
501
-
502
736
  const { spawn } = await import('node:child_process')
503
-
504
737
  let child
738
+ let via
739
+ let command
505
740
 
506
741
  if (process.platform === 'win32') {
507
-
508
742
  if (mode === 'play') {
509
-
510
- // cmd start:让 shell 按文件关联打开。空字符串是窗口标题占位,
511
-
512
- // 不占位的话中文路径会被当作窗口标题。
513
-
514
- child = spawn('cmd.exe', ['/c', 'start', '', found.absolute], {
515
-
516
- detached: true, stdio: 'ignore', windowsHide: true,
517
-
743
+ // 直接 spawn 文件本身,由 shell 按文件关联打开 —— 不经 cmd start。
744
+ // detached:true 让宿主不等待;shell 会交给关联程序。
745
+ via = 'win32-file-association'
746
+ command = absolute
747
+ // 同样不要 windowsHide(否则播放器窗口也可能不显示)
748
+ child = spawn(absolute, [], {
749
+ detached: true, stdio: 'ignore',
518
750
  })
519
-
520
751
  } else {
521
-
522
- // explorer /select 在直接 spawn 时对含中文的路径会以退出码 1 失败(已实测)。
523
-
524
- // 改走 cmd /c start "" explorer.exe /select,"<path>":让 cmd 负责引号与编码,
525
-
526
- // 这是 Windows 上打开并选中中文路径文件的稳定写法。
527
-
528
- child = spawn('cmd.exe', [
529
-
530
- '/c', 'start', '',
531
-
532
- 'explorer.exe', `/select,"${found.absolute}"`,
533
-
534
- ], {
535
-
536
- detached: true, stdio: 'ignore', windowsHide: true,
537
-
752
+ // explorer /select:**路径不加引号**,交给 Node 的 spawn 自动 quoting。
753
+ // argv 实测为 `/select,G:\DSH产出\...\x.png`(干净,无字面引号)。
754
+ via = 'win32-explorer-select'
755
+ command = `explorer.exe /select,${absolute}`
756
+ // ⚠️ **不要加 windowsHide**:实测它会抑制 explorer 的窗口显示
757
+ // (变量隔离:windowsHide:true → 窗口 0→0 不开;false/不设 → 0→1 正常)。
758
+ // reveal 的目的就是让用户看见窗口,隐藏它等于没做。
759
+ child = spawn('explorer.exe', [`/select,${absolute}`], {
760
+ detached: true, stdio: 'ignore',
538
761
  })
539
-
540
762
  }
541
-
763
+ } else if (process.platform === 'darwin') {
764
+ if (mode === 'play') {
765
+ via = 'darwin-open'
766
+ command = `open ${absolute}`
767
+ child = spawn('open', [absolute], { detached: true, stdio: 'ignore' })
768
+ } else {
769
+ // macOS 用 -R 才能真正在 Finder 里选中文件(xdg/open 目录做不到选中)
770
+ via = 'darwin-open-reveal'
771
+ command = `open -R ${absolute}`
772
+ child = spawn('open', ['-R', absolute], { detached: true, stdio: 'ignore' })
773
+ }
542
774
  } else {
543
-
544
- child = spawn('xdg-open', [mode === 'play' ? found.absolute : path.dirname(found.absolute)], {
545
-
546
- detached: true, stdio: 'ignore',
547
-
548
- })
549
-
775
+ // Linux: 没有通用的「选中文件」协议,只能打开所在目录
776
+ via = mode === 'play' ? 'linux-xdg-open-file' : 'linux-xdg-open-dir'
777
+ const target = mode === 'play' ? absolute : path.dirname(absolute)
778
+ command = `xdg-open ${target}`
779
+ child = spawn('xdg-open', [target], { detached: true, stdio: 'ignore' })
550
780
  }
551
781
 
552
- // 不要 unref 立即丢:先观察 800ms 内的错误与退出码,异常时报给前端
553
-
782
+ // 观察 800ms 内的 spawn 错误;**不拿退出码当成功证据**
554
783
  const outcome = await new Promise((resolve) => {
555
-
556
784
  let settled = false
557
-
558
785
  const done = (payload) => {
559
-
560
786
  if (settled) return
561
-
562
787
  settled = true
563
-
564
788
  resolve(payload)
565
-
566
789
  }
567
-
568
790
  child.on('error', (error) => done({
569
-
570
- ok: false, code: 'spawn-error', message: String(error?.message ?? error),
571
-
791
+ ok: false,
792
+ code: 'spawn-error',
793
+ message: String(error?.message ?? error),
572
794
  }))
573
-
574
795
  child.on('exit', (code, signal) => {
575
-
576
- // explorer 成功时通常很快退出(它把活交给已有 explorer 进程)
577
-
578
- if (mode === 'play') {
579
-
580
- // cmd start 退出码 0 表示已交给关联程序
581
-
582
- done(code === 0 || code === null
583
-
584
- ? { ok: true, exitCode: code, signal }
585
-
586
- : { ok: false, code: 'exit-nonzero', message: `exit ${code}`, exitCode: code })
587
-
588
- } else {
589
-
590
- // 现在 select 也走 cmd start,退出码 0 表示命令已被接受
591
-
592
- done(code === 0 || code === null
593
-
594
- ? { ok: true, exitCode: code, signal }
595
-
596
- : { ok: false, code: 'select-exit-nonzero', message: `cmd start 退出码 ${code}`, exitCode: code })
597
-
598
- }
599
-
796
+ // 退出码只作为附加信息回报;explorer/cmd/open 都会把活交出去后立即退出,
797
+ // 退出码并不能证明「已定位到文件」。真正的验证由真机做(看窗口)。
798
+ done({ ok: true, exitCode: code, signal })
600
799
  })
601
-
602
- setTimeout(() => done({ ok: true, note: 'assumed-ok-after-800ms' }), 800)
603
-
800
+ setTimeout(() => done({ ok: true, note: 'assumed-dispatched-after-800ms' }), 800)
604
801
  })
605
802
 
606
- if (child !== undefined && typeof child.unref === 'function' && outcome.ok) {
607
-
608
- try { child.unref() } catch {}
609
-
803
+ if (child !== undefined && typeof child.unref === 'function') {
804
+ try { child.unref() } catch { /* 忽略 */ }
610
805
  }
611
806
 
612
807
  if (!outcome.ok) {
613
-
614
- return json({ ok: false, error: { code: outcome.code, message: outcome.message, mode }, detail: outcome }, 500)
615
-
808
+ return json({
809
+ ok: false,
810
+ error: {
811
+ code: outcome.code ?? 'reveal-failed',
812
+ message: outcome.message ?? '命令未发出',
813
+ mode, via, command, absolute,
814
+ },
815
+ }, 500)
616
816
  }
617
817
 
618
- return json({ ok: true, mode, detail: outcome })
619
-
818
+ // 成功语义 = 命令已发出;把 absolute / via / command 一并返回便于排查
819
+ return json({
820
+ ok: true,
821
+ mode,
822
+ via,
823
+ platform: process.platform,
824
+ absolute,
825
+ basename: path.basename(absolute),
826
+ dirname: path.dirname(absolute),
827
+ command,
828
+ detail: outcome,
829
+ })
620
830
  } catch (error) {
621
-
622
831
  return json({
623
-
624
832
  ok: false,
625
-
626
- error: { code: 'reveal-failed', message: String(error?.message ?? error), mode },
627
-
833
+ error: {
834
+ code: 'reveal-failed',
835
+ message: String(error?.message ?? error),
836
+ mode,
837
+ },
838
+ absolute,
628
839
  }, 500)
629
-
630
840
  }
631
-
632
841
  }
633
842
 
634
843