my-dsh-message-search 0.2.1 → 0.3.8

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.
Files changed (3) hide show
  1. package/client.js +390 -24
  2. package/host.js +296 -2
  3. package/package.json +1 -1
package/client.js CHANGED
@@ -16,11 +16,28 @@ window.__ModuleLoader__.load({
16
16
  const h = React.createElement
17
17
  const NS = 'messageSearch'
18
18
  const ROUTE = 'api/message-search'
19
- const UI_REVISION = '2026-11-18.1'
19
+ const UI_REVISION = '2026-11-18.10'
20
20
 
21
21
  const zh = {
22
22
  title: '检索消息',
23
23
  placeholder: '检索消息正文…',
24
+ placeholderAttach: '按文件名筛选,留空则列出全部',
25
+ modeLabel: '检索对象',
26
+ modeText: '文本',
27
+ modeFile: '附件',
28
+ modeImage: '图片',
29
+ foundFiles: '共 {count} 个附件',
30
+ foundImages: '共 {count} 张图片',
31
+ noFiles: '没有匹配的附件',
32
+ noImages: '没有匹配的图片',
33
+ originUser: '用户上传',
34
+ originMention: '用户引用',
35
+ originAgent: 'Agent 生成',
36
+ openFolder: '打开文件夹',
37
+ locateAttachment: '定位到所在消息',
38
+ jumpFailed: '已打开会话,但没能定位到该消息所在位置',
39
+ jumpTopOnly: '已打开会话并回到顶部(该会话没有轮次导航)',
40
+ missingFile: '文件缺失',
24
41
  scopeCurrent: '当前会话',
25
42
  scopeWorkspace: '工作区',
26
43
  scopeAll: '全部会话',
@@ -34,12 +51,15 @@ window.__ModuleLoader__.load({
34
51
  needWorkspace: '先选择一个工作区。',
35
52
  error: '检索失败:{message}',
36
53
  corpus: '范围:{sessions} 个会话 · {messages} 条消息',
54
+ corpusSessions: '范围:{sessions} 个会话',
55
+ foundItems: '共 {count} 项',
37
56
  elapsed: '{seconds}',
38
57
  truncated: '结果较多,只显示前 {max} 条。',
39
58
  skipped: '{count} 个会话日志无法解析,已跳过。',
40
59
  emptyNoSession: '当前没有打开的会话;可切到「工作区」或「全部会话」。',
41
60
  hint: '↑↓ 选择 · Enter 打开 · Esc 关闭',
42
61
  close: '关闭检索',
62
+ clear: '清空',
43
63
  untitled: '未命名会话',
44
64
  ungrouped: '未分组',
45
65
  roleUser: '我',
@@ -50,6 +70,23 @@ window.__ModuleLoader__.load({
50
70
  const en = {
51
71
  title: 'Search messages',
52
72
  placeholder: 'Search message text…',
73
+ placeholderAttach: 'Filter by file name; leave empty to list all',
74
+ modeLabel: 'Search target',
75
+ modeText: 'Text',
76
+ modeFile: 'Files',
77
+ modeImage: 'Images',
78
+ foundFiles: '{count} files',
79
+ foundImages: '{count} images',
80
+ noFiles: 'No matching files',
81
+ noImages: 'No matching images',
82
+ originUser: 'Uploaded',
83
+ originMention: 'Mentioned',
84
+ originAgent: 'Agent',
85
+ openFolder: 'Open folder',
86
+ locateAttachment: 'Jump to the message',
87
+ jumpFailed: 'Opened the session but could not locate the message',
88
+ jumpTopOnly: 'Opened the session and scrolled to the top (no turn navigation here)',
89
+ missingFile: 'file missing',
53
90
  scopeCurrent: 'This session',
54
91
  scopeWorkspace: 'Workspace',
55
92
  scopeAll: 'All sessions',
@@ -63,12 +100,15 @@ window.__ModuleLoader__.load({
63
100
  needWorkspace: 'Choose a workspace first.',
64
101
  error: 'Search failed: {message}',
65
102
  corpus: 'Scope: {sessions} sessions · {messages} messages',
103
+ corpusSessions: 'Scope: {sessions} sessions',
104
+ foundItems: '{count} items',
66
105
  elapsed: '{seconds}',
67
106
  truncated: 'Showing the first {max} results.',
68
107
  skipped: '{count} session logs could not be parsed and were skipped.',
69
108
  emptyNoSession: 'No session is open; switch to Workspace or All sessions.',
70
109
  hint: '↑↓ select · Enter open · Esc close',
71
110
  close: 'Close search',
111
+ clear: 'Clear',
72
112
  untitled: 'Untitled session',
73
113
  ungrouped: 'No workspace',
74
114
  roleUser: 'You',
@@ -146,6 +186,8 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
146
186
  .msn-bar{display:flex;align-items:center;gap:6px;margin:12px 24px 0;height:40px;box-sizing:border-box;padding:0 6px 0 14px;border:0.5px solid var(--dsw-alias-border-l4);border-radius:12px;background:transparent}
147
187
  .msn-bar:focus-within{border-color:var(--dsw-alias-label-caption)}
148
188
  .msn-input{flex:1 1 auto;min-width:0;height:100%;border:0;background:transparent;color:var(--dsw-alias-label-primary);font-size:13px;padding:0;outline:none}
189
+ .msn-clear{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--dsw-alias-label-caption);cursor:pointer}
190
+ .msn-clear:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
149
191
  .msn-input::placeholder{color:var(--dsw-alias-label-caption)}
150
192
  .msn-scopes{position:relative;display:flex;align-items:center;gap:2px;flex:none}
151
193
  .msn-scope{display:inline-flex;align-items:center;gap:4px;border:0;background:transparent;color:var(--dsw-alias-label-caption);font-size:12.5px;line-height:20px;padding:5px 9px;border-radius:8px;cursor:pointer;white-space:nowrap;max-width:170px}
@@ -163,6 +205,50 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
163
205
  .msn-menu-empty{padding:8px 10px;font-size:12.5px;color:var(--dsw-alias-label-caption)}
164
206
  .msn-status{display:flex;align-items:center;gap:10px;padding:10px 24px 6px;font-size:12.5px;color:var(--dsw-alias-label-caption);min-height:28px}
165
207
  .msn-status-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
208
+ .msn-modes{display:inline-flex;align-items:center;gap:2px;flex:none;padding:2px;border-radius:9px;background:var(--dsw-alias-bg-module-platform)}
209
+ .msn-mode{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-caption);font:inherit;font-size:12px;line-height:18px;padding:2px 8px;border-radius:7px;cursor:pointer}
210
+ .msn-mode:hover{color:var(--dsw-alias-label-primary)}
211
+ .msn-mode[aria-pressed='true']{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.08)}
212
+ .msn-attach{display:flex;align-items:stretch;gap:6px;border-radius:12px;padding:2px}
213
+ .msn-attach:hover,.msn-attach[data-active='true']{background:var(--dsw-alias-interactive-bg-hover)}
214
+ .msn-attach-main{flex:1;min-width:0;display:flex;align-items:center;gap:10px;padding:8px 10px;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
215
+ .msn-ext{flex:none;width:38px;height:44px;border-radius:10px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;border:0.5px solid currentColor}
216
+ .msn-ext-label{font-size:8.5px;font-weight:600;letter-spacing:.02em;line-height:1;max-width:34px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
217
+ .msn-ext-doc{color:#2f5bd7;background:rgba(47,91,215,.10)}
218
+ .msn-ext-sheet{color:#137a4a;background:rgba(19,122,74,.10)}
219
+ .msn-ext-slides{color:#b4531a;background:rgba(180,83,26,.10)}
220
+ .msn-ext-pdf{color:#c02b2b;background:rgba(192,43,43,.10)}
221
+ .msn-ext-archive{color:#8a6512;background:rgba(138,101,18,.12)}
222
+ .msn-ext-text{color:#556069;background:rgba(85,96,105,.10)}
223
+ .msn-ext-code{color:#6b46c1;background:rgba(107,70,193,.10)}
224
+ .msn-ext-image{color:#0d7c86;background:rgba(13,124,134,.10)}
225
+ .msn-ext-other{color:#6b7280;background:rgba(107,114,128,.10)}
226
+ .msn-attach-body{flex:1;min-width:0;display:block}
227
+ .msn-attach-l1{display:flex;align-items:baseline;gap:8px;min-width:0}
228
+ .msn-attach-name{font-size:13px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:none;max-width:52%}
229
+ .msn-attach-name[data-gone='true']{text-decoration:line-through;text-decoration-thickness:1px;color:var(--dsw-alias-label-caption)}
230
+ .msn-attach-title{font-size:12px;color:var(--dsw-alias-label-caption);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
231
+ .msn-attach-l2{display:flex;align-items:center;gap:8px;margin-top:3px;font-size:12px;color:var(--dsw-alias-label-caption)}
232
+ .msn-attach-time,.msn-attach-size{font-variant-numeric:tabular-nums}
233
+ .msn-attach-open{flex:none;align-self:center;margin-right:6px;appearance:none;border:0.5px solid var(--dsw-alias-border-l4);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;padding:3px 10px;border-radius:999px;cursor:pointer}
234
+ .msn-attach-open:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-caption)}
235
+ .msn-thumb{flex:none;width:44px;height:44px;border-radius:8px;object-fit:cover;background:var(--dsw-alias-bg-module-platform)}
236
+ .msn-gallery{flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;display:grid;grid-template-columns:repeat(auto-fill,minmax(136px,1fr));grid-auto-rows:min-content;gap:10px;padding:6px 14px 12px;align-content:start}
237
+ .msn-tile{position:relative;border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-module-platform);border:0.5px solid var(--dsw-alias-border-l4)}
238
+ .msn-tile[data-active='true']{border-color:var(--dsw-alias-label-caption);box-shadow:0 0 0 1px var(--dsw-alias-label-caption)}
239
+ .msn-tile-hit{display:block;width:100%;padding:0;border:0;background:transparent;cursor:pointer}
240
+ .msn-tile-img{display:block;width:100%;height:104px;object-fit:cover;background:var(--dsw-alias-bg-module-platform)}
241
+ .msn-tile-empty{display:block;width:100%;height:104px;background:var(--dsw-alias-interactive-bg-hover)}
242
+ .msn-tile-meta{display:flex;align-items:center;gap:6px;padding:5px 8px 6px;font-size:11px;color:var(--dsw-alias-label-caption)}
243
+ .msn-tile-time{margin-left:auto;font-variant-numeric:tabular-nums}
244
+ .msn-tile-open:disabled{opacity:.4;cursor:default}
245
+ .msn-tile-gone{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.45);color:#fff;font-size:12px;pointer-events:none}
246
+ .msn-attach-open:disabled{opacity:.45;cursor:default}
247
+ .msn-tile-open{position:absolute;top:6px;right:6px;opacity:0;transition:opacity .15s ease;appearance:none;border:0.5px solid rgba(255,255,255,.35);background:rgba(0,0,0,.55);color:#fff;font:inherit;font-size:11px;line-height:16px;padding:2px 8px;border-radius:999px;cursor:pointer}
248
+ .msn-tile:hover .msn-tile-open,.msn-tile[data-active='true'] .msn-tile-open{opacity:1}
249
+ .msn-thumb-empty{display:inline-block}
250
+ .msn-missing{color:var(--dsw-alias-state-error-primary)}
251
+ .msn-note-warn{color:var(--dsw-alias-state-error-primary)}
166
252
  .msn-status-error{color:var(--dsw-alias-state-error-primary)}
167
253
  .msn-note{padding:0 24px 8px;font-size:12px;color:var(--dsw-alias-label-caption)}
168
254
  .msn-list{flex:1;margin:0;padding:6px 14px 10px;list-style:none;overflow:auto;border-top:0.5px solid var(--dsw-alias-border-l4);min-height:0}
@@ -567,6 +653,56 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
567
653
  }
568
654
 
569
655
  /** 检索面板。 */
656
+ /** 按扩展名判断文件类型(决定图标底色与角标文字)。 */
657
+ const FILE_KINDS = {
658
+ docx: ['DOCX', 'doc'], doc: ['DOC', 'doc'], rtf: ['RTF', 'doc'],
659
+ xlsx: ['XLSX', 'sheet'], xls: ['XLS', 'sheet'], csv: ['CSV', 'sheet'],
660
+ pptx: ['PPTX', 'slides'], ppt: ['PPT', 'slides'],
661
+ pdf: ['PDF', 'pdf'],
662
+ zip: ['ZIP', 'archive'], rar: ['RAR', 'archive'], '7z': ['7Z', 'archive'], gz: ['GZ', 'archive'],
663
+ md: ['MD', 'text'], markdown: ['MD', 'text'], txt: ['TXT', 'text'], log: ['LOG', 'text'],
664
+ json: ['JSON', 'code'], js: ['JS', 'code'], mjs: ['JS', 'code'], cjs: ['JS', 'code'],
665
+ ts: ['TS', 'code'], py: ['PY', 'code'], ps1: ['PS1', 'code'], sh: ['SH', 'code'],
666
+ png: ['PNG', 'image'], jpg: ['JPG', 'image'], jpeg: ['JPG', 'image'], gif: ['GIF', 'image'],
667
+ webp: ['WEBP', 'image'], svg: ['SVG', 'image'], bmp: ['BMP', 'image'],
668
+ }
669
+
670
+ /**
671
+ * 文件类型角标:圆角方块 + 文档轮廓 + 扩展名。
672
+ * @param {{name: string}} props - 文件名。
673
+ * @returns {object} React 元素。
674
+ */
675
+ function FileGlyph({ name }) {
676
+ const ext = (/.([A-Za-z0-9]+)$/.exec(String(name ?? ''))?.[1] ?? '').toLowerCase()
677
+ const [label, tone] = FILE_KINDS[ext] ?? [(ext === '' ? 'FILE' : ext.slice(0, 4).toUpperCase()), 'other']
678
+ return h('span', { className: 'msn-ext msn-ext-' + tone, 'aria-hidden': 'true' }, [
679
+ h('svg', {
680
+ key: 'i', viewBox: '0 0 24 24', width: 12, height: 12, fill: 'none', stroke: 'currentColor',
681
+ strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round',
682
+ }, [
683
+ h('path', { key: 'a', d: 'M7 3.5h7l4 4V20a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1Z' }),
684
+ h('path', { key: 'b', d: 'M14 3.5V8h4' }),
685
+ ]),
686
+ h('span', { key: 'l', className: 'msn-ext-label' }, label),
687
+ ])
688
+ }
689
+
690
+ /** 图片缩略图:按需向 Host 取 data URL。 */
691
+ function AttachmentThumb({ item, request, enabled, variant }) {
692
+ const [url, setUrl] = React.useState(null)
693
+ React.useEffect(() => {
694
+ if (!enabled) return undefined
695
+ let alive = true
696
+ Promise.resolve(request('attachment-blob', { id: item.id, mediaType: item.mediaType }))
697
+ .then((value) => { if (alive) setUrl(value?.dataUrl ?? null) })
698
+ .catch(() => { if (alive) setUrl(null) })
699
+ return () => { alive = false }
700
+ }, [enabled, item.id, item.mediaType, request])
701
+ const mediaClass = variant === 'tile' ? 'msn-tile-img' : 'msn-thumb'
702
+ if (!enabled || url === null) return h('span', { className: (variant === 'tile' ? 'msn-tile-empty' : 'msn-thumb msn-thumb-empty') })
703
+ return h('img', { className: mediaClass, src: url, alt: item.name, loading: 'lazy' })
704
+ }
705
+
570
706
  function SearchPanel(props) {
571
707
  const tr = props.translate
572
708
  const request = props.request
@@ -586,7 +722,9 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
586
722
  // 结果对应的检索签名:query|scope|workspace。签名变化就清空旧结果,
587
723
  // 免得"改了范围还按 Enter"时打开的是上一次的命中。
588
724
  const [searchedFor, setSearchedFor] = React.useState('')
589
- const signature = `${query.trim()}|${scope}|${workspaceId}`
725
+ // 检索模式:文本 / 附件 / 图片。附件与图片允许空关键词(=列出全部)。
726
+ const [mode, setMode] = React.useState('text')
727
+ const signature = `${mode}|${query.trim()}|${scope}|${workspaceId}`
590
728
  const stale = searchedFor !== signature
591
729
 
592
730
  const requestRef = React.useRef(request)
@@ -639,7 +777,7 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
639
777
  React.useEffect(() => {
640
778
  // 只在"关 → 开"的那一次给默认范围:有当前会话就搜当前会话,否则搜全部。
641
779
  // 不能依赖 sessionId 变化,否则探针晚到会把用户手动选的范围冲掉。
642
- if (isOpen && !wasOpenRef.current) { setScope(sessionId === undefined ? 'all' : 'current'); setMenuOpen(false) }
780
+ if (isOpen && !wasOpenRef.current) { setScope(sessionId === undefined ? 'all' : 'current'); setMenuOpen(false); setNotice(null) }
643
781
  if (!isOpen) setMenuOpen(false)
644
782
  wasOpenRef.current = isOpen
645
783
  }, [isOpen, sessionId])
@@ -664,7 +802,8 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
664
802
 
665
803
  const run = React.useCallback(async () => {
666
804
  const keyword = query.trim()
667
- if (keyword === '') { setPhase('idle'); setResult(null); setFailure(null); return }
805
+ const listing = mode !== 'text'
806
+ if (!listing && keyword === '') { setPhase('idle'); setResult(null); setFailure(null); return }
668
807
  if (scope === 'workspace' && workspaceId === '') { setPhase('idle'); setResult(null); setFailure(null); return }
669
808
  const sig = signatureRef.current
670
809
  abortRef.current?.abort()
@@ -675,12 +814,20 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
675
814
  setFailure(null)
676
815
  setElapsed(0)
677
816
  try {
678
- const value = await requestRef.current('search', {
679
- query: keyword,
680
- scope,
681
- sessionId: scope === 'current' ? sessionId : undefined,
682
- workspaceId: scope === 'workspace' ? workspaceId : undefined,
683
- })
817
+ const value = listing
818
+ ? await requestRef.current('attachments', {
819
+ query: keyword,
820
+ kind: mode,
821
+ scope,
822
+ sessionId: scope === 'current' ? sessionId : undefined,
823
+ workspaceId: scope === 'workspace' ? workspaceId : undefined,
824
+ })
825
+ : await requestRef.current('search', {
826
+ query: keyword,
827
+ scope,
828
+ sessionId: scope === 'current' ? sessionId : undefined,
829
+ workspaceId: scope === 'workspace' ? workspaceId : undefined,
830
+ })
684
831
  if (controller.signal.aborted || signatureRef.current !== sig) return
685
832
  setResult(value)
686
833
  setSearchedFor(sig)
@@ -694,9 +841,10 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
694
841
  setPhase('error')
695
842
  setElapsed(performance.now() - startedRef.current)
696
843
  }
697
- }, [query, scope, sessionId, workspaceId])
844
+ }, [query, scope, sessionId, workspaceId, mode])
698
845
 
699
846
  const hits = stale ? [] : (result?.hits ?? [])
847
+ const attachments = stale ? [] : (result?.items ?? [])
700
848
  React.useEffect(() => { setActiveIndex(0) }, [result])
701
849
 
702
850
  React.useEffect(() => {
@@ -708,6 +856,96 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
708
856
  setFailure(null)
709
857
  }, [signature])
710
858
 
859
+ /** 点轮次导航按钮跳到第 N 轮(会话自己负责滚动)。 */
860
+ const jumpToTurn = (turn) => {
861
+ if (!Number.isFinite(turn) || turn <= 0) return false
862
+ const labels = ['跳转到第 ' + String(turn) + ' 轮', '加载并跳转到第 ' + String(turn) + ' 轮']
863
+ const target = [...document.querySelectorAll('[aria-label]')]
864
+ .find(el => labels.includes(el.getAttribute('aria-label') ?? ''))
865
+ if (target === undefined) return false
866
+ target.click()
867
+ return true
868
+ }
869
+
870
+ const [notice, setNotice] = React.useState(null)
871
+
872
+ /** 打开附件所在文件夹(资源管理器定位到文件)。 */
873
+ const openFolder = async (item) => {
874
+ try {
875
+ await requestRef.current('attachment-open', { id: item.id, kind: item.kind, path: item.path })
876
+ setNotice(null)
877
+ } catch (error) {
878
+ setNotice(error instanceof Error ? error.message : String(error))
879
+ }
880
+ }
881
+
882
+ /**
883
+ * 跳到某一轮后,尽量把图片本身滚进视口:会话把图片渲染成 data URL,
884
+ * 其长度约为字节数的 4/3,用这个特征在正文里认出同一张图。
885
+ */
886
+ const focusImage = (item) => {
887
+ if (item.kind !== 'image' || !item.exists || item.bytes <= 0) return false
888
+ const expected = item.bytes * 4 / 3
889
+ const images = [...document.querySelectorAll('img')]
890
+ .filter(el => typeof el.src === 'string' && el.src.startsWith('data:image/'))
891
+ const match = images.find(el => Math.abs(el.src.length - expected) / expected < 0.06)
892
+ if (match === undefined) return false
893
+ match.scrollIntoView({ block: 'center', behavior: 'smooth' })
894
+ match.style.outline = '2px solid rgba(255,205,0,.95)'
895
+ match.style.outlineOffset = '2px'
896
+ window.setTimeout(() => {
897
+ match.style.outline = ''
898
+ match.style.outlineOffset = ''
899
+ }, 2600)
900
+ return true
901
+ }
902
+
903
+ /** 轻提示:浮在窗口底部,3 秒消失(不占检索面板版面)。 */
904
+ const toast = (message) => {
905
+ const node = document.createElement('div')
906
+ node.textContent = message
907
+ node.style.cssText = 'position:fixed;left:50%;bottom:36px;transform:translateX(-50%);z-index:1300;padding:8px 14px;border-radius:10px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border:0.5px solid var(--dsw-alias-border-l4);box-shadow:0 8px 24px rgba(0,0,0,.18);font-size:12.5px'
908
+ document.body.append(node)
909
+ window.setTimeout(() => node.remove(), 3000)
910
+ }
911
+
912
+ /** 会话没有轮次导航时的兜底:滚到正文顶部。 */
913
+ const scrollTranscriptTop = () => {
914
+ const chat = document.querySelector('[data-conversation-region="chat"]')
915
+ if (chat === null) return false
916
+ const list = []
917
+ if (chat.scrollHeight > chat.clientHeight + 20) list.push(chat)
918
+ for (const el of chat.querySelectorAll('*')) {
919
+ if (el.clientHeight > 120 && el.scrollHeight > el.clientHeight + 20) list.push(el)
920
+ }
921
+ const scroller = list.sort((a, b) => b.scrollTop - a.scrollTop)[0]
922
+ if (scroller === undefined) return false
923
+ scroller.scrollTop = 0
924
+ return true
925
+ }
926
+
927
+ /** 附件条目:打开会话并跳到它所在的那一轮。 */
928
+ const openAttachmentItem = (item) => {
929
+ setOpen(false)
930
+ props.openSession(item.sessionId)
931
+ const started = performance.now()
932
+ const attempt = () => {
933
+ if (jumpToTurn(item.turn)) {
934
+ setNotice(null)
935
+ window.setTimeout(() => { focusImage(item) }, 700)
936
+ return
937
+ }
938
+ if (performance.now() - started > 4000) {
939
+ // 会话没有轮次导航(例如只有一轮):滚到正文顶部,并用浮层提示,不再占用检索面板
940
+ const scrolled = item.turn <= 1 && scrollTranscriptTop()
941
+ toast(scrolled ? tr('jumpTopOnly') : tr('jumpFailed'))
942
+ return
943
+ }
944
+ window.setTimeout(attempt, 300)
945
+ }
946
+ window.setTimeout(attempt, 300)
947
+ }
948
+
711
949
  const openSession = (id, hit) => {
712
950
  setOpen(false)
713
951
  props.openSession(id)
@@ -719,7 +957,8 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
719
957
  React.useEffect(() => {
720
958
  if (!isOpen) return undefined
721
959
  const keyword = query.trim()
722
- if (keyword === '' || (scope === 'workspace' && workspaceId === '')) {
960
+ const listing = mode !== 'text'
961
+ if ((!listing && keyword === '') || (scope === 'workspace' && workspaceId === '')) {
723
962
  setPhase('idle')
724
963
  setResult(null)
725
964
  setFailure(null)
@@ -731,7 +970,7 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
731
970
  window.clearTimeout(autoRef.current)
732
971
  autoRef.current = window.setTimeout(() => { void run() }, 250)
733
972
  return () => window.clearTimeout(autoRef.current)
734
- }, [isOpen, signature, stale, run])
973
+ }, [isOpen, signature, stale, run, mode])
735
974
  React.useEffect(() => () => window.clearTimeout(autoRef.current), [])
736
975
 
737
976
  const onKeyDown = (event) => {
@@ -741,9 +980,10 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
741
980
  setOpen(false)
742
981
  return
743
982
  }
983
+ const listLength = mode === 'text' ? hits.length : attachments.length
744
984
  if (event.key === 'ArrowDown') {
745
985
  event.preventDefault()
746
- setActiveIndex(index => Math.min(index + 1, Math.max(hits.length - 1, 0)))
986
+ setActiveIndex(index => Math.min(index + 1, Math.max(listLength - 1, 0)))
747
987
  return
748
988
  }
749
989
  if (event.key === 'ArrowUp') {
@@ -753,10 +993,13 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
753
993
  }
754
994
  if (event.key === 'Enter') {
755
995
  if (event.isComposing) return
756
- const ready = !stale && phase === 'done' && hits.length > 0 && hits[activeIndex] !== undefined
996
+ const listing = mode !== 'text'
997
+ const items = listing ? attachments : hits
998
+ const ready = !stale && phase === 'done' && items.length > 0 && items[activeIndex] !== undefined
757
999
  if (ready) {
758
1000
  event.preventDefault()
759
- openSession(hits[activeIndex].sessionId, hits[activeIndex])
1001
+ if (listing) openAttachmentItem(items[activeIndex])
1002
+ else openSession(items[activeIndex].sessionId, items[activeIndex])
760
1003
  } else {
761
1004
  // 还没搜出这次的结果:立刻搜,不等防抖
762
1005
  event.preventDefault()
@@ -771,17 +1014,103 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
771
1014
  const workspaceReady = scope !== 'workspace' || workspaceId !== ''
772
1015
  // 状态行只放"结果/错误/提示",检索中与无结果交给中间占位区显示一次,
773
1016
  // 避免同一句话在上下两处重复。
1017
+ const listing = mode !== 'text'
774
1018
  const statusText = phase === 'error'
775
1019
  ? tr('error', { message: failure ?? '' })
776
1020
  : phase === 'done'
777
- ? (hits.length === 0 ? '' : tr('found', { count: String(hits.length) }))
1021
+ ? (listing
1022
+ ? tr(mode === 'image' ? 'foundImages' : 'foundFiles', { count: String(attachments.length) })
1023
+ : (hits.length === 0 ? '' : tr('found', { count: String(hits.length) })))
778
1024
  : phase === 'searching'
779
1025
  ? ''
780
1026
  : scope === 'workspace' && workspaceId === ''
781
1027
  ? tr('needWorkspace')
782
1028
  : scope === 'current' && sessionId === undefined
783
1029
  ? tr('emptyNoSession')
784
- : (query.trim() === '' ? tr('idle') : '')
1030
+ : (query.trim() === '' && !listing ? tr('idle') : '')
1031
+
1032
+ const attachmentRows = attachments.map((item, index) => {
1033
+ const where = item.workspaceTitle !== '' ? item.workspaceTitle : tr('ungrouped')
1034
+ const title = item.title !== '' ? item.title : tr('untitled')
1035
+ const size = item.bytes >= 1024 * 1024
1036
+ ? (item.bytes / 1024 / 1024).toFixed(1) + ' MB'
1037
+ : Math.max(1, Math.round(item.bytes / 1024)) + ' KB'
1038
+ return h('li', { key: item.sessionId + '-' + String(item.seq) + '-' + item.id + '-' + String(index) },
1039
+ h('div', {
1040
+ className: 'msn-attach',
1041
+ 'data-active': index === activeIndex ? 'true' : undefined,
1042
+ onMouseEnter: () => setActiveIndex(index),
1043
+ }, [
1044
+ h('button', {
1045
+ key: 'main', type: 'button', className: 'msn-attach-main',
1046
+ onClick: () => openAttachmentItem(item),
1047
+ title: tr('locateAttachment'),
1048
+ }, [
1049
+ h(FileGlyph, { key: 'glyph', name: item.name !== '' ? item.name : item.id }),
1050
+ h('span', { key: 'body', className: 'msn-attach-body' }, [
1051
+ h('span', { key: 'l1', className: 'msn-attach-l1' }, [
1052
+ h('span', {
1053
+ key: 'n',
1054
+ className: 'msn-attach-name',
1055
+ 'data-gone': item.exists ? undefined : 'true',
1056
+ }, item.name !== '' ? item.name : item.id.slice(0, 16)),
1057
+ h('span', { key: 'w', className: 'msn-row-where' }, where),
1058
+ h('span', { key: 't', className: 'msn-attach-title' }, title),
1059
+ ]),
1060
+ h('span', { key: 'l2', className: 'msn-attach-l2' }, [
1061
+ h('span', {
1062
+ key: 'origin',
1063
+ className: 'msn-badge',
1064
+ 'data-origin': item.origin,
1065
+ }, item.source === 'mention'
1066
+ ? tr('originMention')
1067
+ : (item.origin === 'agent' ? tr('originAgent') : tr('originUser'))),
1068
+ h('span', { key: 'time', className: 'msn-attach-time' }, timeText(item.time)),
1069
+ h('span', { key: 's', className: 'msn-attach-size' }, size),
1070
+ item.exists ? null : h('span', { key: 'm', className: 'msn-missing' }, tr('missingFile')),
1071
+ ]),
1072
+ ]),
1073
+ ]),
1074
+ h('button', {
1075
+ key: 'open', type: 'button', className: 'msn-attach-open',
1076
+ disabled: !item.exists,
1077
+ onClick: (event) => { event.stopPropagation(); if (item.exists) void openFolder(item) },
1078
+ title: item.exists ? tr('openFolder') : tr('missingFile'),
1079
+ }, tr('openFolder')),
1080
+ ]))
1081
+ })
1082
+
1083
+ const galleryTiles = attachments.map((item, index) => {
1084
+ const size = item.bytes >= 1024 * 1024
1085
+ ? (item.bytes / 1024 / 1024).toFixed(1) + ' MB'
1086
+ : Math.max(1, Math.round(item.bytes / 1024)) + ' KB'
1087
+ return h('div', {
1088
+ key: item.sessionId + '-' + String(item.seq) + '-' + item.id + '-' + String(index),
1089
+ className: 'msn-tile',
1090
+ 'data-active': index === activeIndex ? 'true' : undefined,
1091
+ onMouseEnter: () => setActiveIndex(index),
1092
+ title: (item.name !== '' ? item.name : item.id) + ' · ' + size,
1093
+ }, [
1094
+ h('button', {
1095
+ key: 'hit', type: 'button', className: 'msn-tile-hit',
1096
+ onClick: () => openAttachmentItem(item),
1097
+ 'aria-label': tr('locateAttachment'),
1098
+ }, h(AttachmentThumb, { key: 'img', item, request: requestRef.current, enabled: index < 48, variant: 'tile' })),
1099
+ h('div', { key: 'meta', className: 'msn-tile-meta' }, [
1100
+ h('span', { key: 'o', className: 'msn-badge', 'data-origin': item.origin },
1101
+ item.origin === 'agent' ? tr('originAgent') : tr('originUser')),
1102
+ item.exists ? null : h('span', { key: 'm', className: 'msn-missing' }, tr('missingFile')),
1103
+ h('span', { key: 't', className: 'msn-tile-time' }, timeText(item.time)),
1104
+ ]),
1105
+ h('button', {
1106
+ key: 'open', type: 'button', className: 'msn-tile-open',
1107
+ disabled: !item.exists,
1108
+ onClick: (event) => { event.stopPropagation(); if (item.exists) void openFolder(item) },
1109
+ title: item.exists ? tr('openFolder') : tr('missingFile'),
1110
+ }, tr('openFolder')),
1111
+ item.exists ? null : h('span', { key: 'gone', className: 'msn-tile-gone' }, tr('missingFile')),
1112
+ ])
1113
+ })
785
1114
 
786
1115
  const rows = hits.map((hit, index) => {
787
1116
  const where = hit.workspaceTitle !== '' ? hit.workspaceTitle : tr('ungrouped')
@@ -807,7 +1136,9 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
807
1136
 
808
1137
  const footLeft = result === null
809
1138
  ? ''
810
- : `${tr('corpus', { sessions: String(result.scannedSessions), messages: String(result.scannedMessages) })}${result.skipped?.length ? ` · ${tr('skipped', { count: String(result.skipped.length) })}` : ''}`
1139
+ : listing
1140
+ ? `${tr('corpusSessions', { sessions: String(result.scannedSessions) })} · ${tr('foundItems', { count: String(result.total ?? attachments.length) })}${result.skipped?.length ? ` · ${tr('skipped', { count: String(result.skipped.length) })}` : ''}`
1141
+ : `${tr('corpus', { sessions: String(result.scannedSessions), messages: String(result.scannedMessages) })}${result.skipped?.length ? ` · ${tr('skipped', { count: String(result.skipped.length) })}` : ''}`
811
1142
 
812
1143
  return h('div', {
813
1144
  className: 'msn-layer',
@@ -842,11 +1173,28 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
842
1173
  className: 'msn-input',
843
1174
  type: 'text',
844
1175
  value: query,
845
- placeholder: tr('placeholder'),
1176
+ placeholder: mode === 'text' ? tr('placeholder') : tr('placeholderAttach'),
846
1177
  'aria-label': tr('placeholder'),
847
1178
  onChange: (event) => setQuery(event.target.value),
848
1179
  onKeyDown,
849
1180
  }),
1181
+ query === ''
1182
+ ? null
1183
+ : h('button', {
1184
+ key: 'clear',
1185
+ type: 'button',
1186
+ className: 'msn-clear',
1187
+ 'aria-label': tr('clear'),
1188
+ title: tr('clear'),
1189
+ onMouseDown: (event) => event.preventDefault(),
1190
+ onClick: () => {
1191
+ setQuery('')
1192
+ inputRef.current?.focus()
1193
+ },
1194
+ }, h('svg', {
1195
+ width: 12, height: 12, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1196
+ strokeWidth: 2, strokeLinecap: 'round',
1197
+ }, [h('path', { key: 'a', d: 'M6 6l12 12' }), h('path', { key: 'b', d: 'M18 6L6 18' })])),
850
1198
  h('div', { key: 'scopes', className: 'msn-scopes' }, [
851
1199
  h('button', {
852
1200
  key: 'current', type: 'button', className: 'msn-scope',
@@ -913,13 +1261,31 @@ body[data-ds-dark-theme] .msn-layer{background:rgba(0,0,0,.55)}
913
1261
  ]),
914
1262
  h('div', { key: 'status', className: `msn-status ${phase === 'error' ? 'msn-status-error' : ''}`, 'aria-live': 'polite' }, [
915
1263
  h('span', { key: 'txt', className: 'msn-status-text' }, statusText),
1264
+ h('div', { key: 'modes', className: 'msn-modes', role: 'group', 'aria-label': tr('modeLabel') }, [
1265
+ ['text', 'modeText'], ['file', 'modeFile'], ['image', 'modeImage'],
1266
+ ].map(([value, key]) => h('button', {
1267
+ key: value,
1268
+ type: 'button',
1269
+ className: 'msn-mode',
1270
+ 'aria-pressed': mode === value ? 'true' : 'false',
1271
+ title: tr(key),
1272
+ onClick: () => { setMode(value); setNotice(null) },
1273
+ }, tr(key)))),
916
1274
  ]),
1275
+ notice === null ? null : h('div', { key: 'notice', className: 'msn-note msn-note-warn' }, notice),
917
1276
  result !== null && result.truncated ? h('div', { key: 'trunc', className: 'msn-note' }, tr('truncated', { max: String(result.maxHits) })) : null,
918
1277
  h('div', { key: 'body', className: 'msn-body' },
919
- hits.length > 0
920
- ? h('ul', { key: 'list', className: 'msn-list' }, rows)
921
- : h('div', { key: 'empty', className: 'msn-body-empty' },
922
- phase === 'done' ? tr('noMatch') : (phase === 'searching' ? tr('searching') : ''))),
1278
+ listing
1279
+ ? (attachments.length > 0
1280
+ ? (mode === 'image'
1281
+ ? h('div', { key: 'gallery', className: 'msn-gallery' }, galleryTiles)
1282
+ : h('ul', { key: 'list', className: 'msn-list' }, attachmentRows))
1283
+ : h('div', { key: 'empty', className: 'msn-body-empty' },
1284
+ phase === 'done' ? tr(mode === 'image' ? 'noImages' : 'noFiles') : (phase === 'searching' ? tr('searching') : '')))
1285
+ : (hits.length > 0
1286
+ ? h('ul', { key: 'list', className: 'msn-list' }, rows)
1287
+ : h('div', { key: 'empty', className: 'msn-body-empty' },
1288
+ phase === 'done' ? tr('noMatch') : (phase === 'searching' ? tr('searching') : '')))),
923
1289
  h('div', { key: 'foot', className: 'msn-foot' }, [
924
1290
  h('span', { key: 'hint' }, tr('hint')),
925
1291
  h('span', { key: 'corpus' }, footLeft),
package/host.js CHANGED
@@ -17,14 +17,16 @@ import fs from 'node:fs'
17
17
  import os from 'node:os'
18
18
  import path from 'node:path'
19
19
  import zlib from 'node:zlib'
20
+ import { spawn } from 'node:child_process'
20
21
 
21
22
  export const name = 'message-search'
22
23
 
23
24
  /** Client 页面读取的私有路由。 */
24
25
  const HTTP_PATH = '/api/message-search'
25
26
  /** Host 构建标记。 */
26
- const HOST_REVISION = '2026-11-18.1'
27
+ const HOST_REVISION = '2026-11-18.10'
27
28
  /** 一次检索最多返回多少条命中。 */
29
+ const MAX_BLOB_BYTES = 12 * 1024 * 1024
28
30
  const DEFAULT_MAX_HITS = 200
29
31
  /** 片段前后各取多少字符。 */
30
32
  const SNIPPET_PAD = 80
@@ -74,6 +76,7 @@ function start(ctx, config) {
74
76
  ? process.env.DSH_HOME
75
77
  : path.join(os.homedir(), '.dsh')
76
78
  const sessionsRoot = path.join(home, 'sessions')
79
+ const attachmentsRoot = path.join(home, 'attachments', 'v1')
77
80
  const workspaceFile = path.join(home, 'storages', 'workspace.json')
78
81
  const maxHits = Number.isFinite(Number(config?.maxHits)) && Number(config?.maxHits) > 0
79
82
  ? Math.min(Math.floor(Number(config.maxHits)), 1000)
@@ -116,6 +119,9 @@ function start(ctx, config) {
116
119
  if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached
117
120
  const text = decodeFrames(fs.readFileSync(file))
118
121
  const messages = []
122
+ const attachments = []
123
+ const writes = []
124
+ const mentions = []
119
125
  let title = ''
120
126
  let turn = 0
121
127
  for (const line of text.split('\n')) {
@@ -134,8 +140,74 @@ function start(ctx, config) {
134
140
  turn += 1
135
141
  continue
136
142
  }
143
+ // 附件(图片 / 文件)出现在三类事件里:用户上传、待发输入、工具产出
144
+ const collectAttachments = (content, origin, meta, source) => {
145
+ if (!Array.isArray(content)) return
146
+ for (const part of content) {
147
+ const ref = part?.attachment
148
+ if (ref === undefined || (part.type !== 'image' && part.type !== 'file')) continue
149
+ attachments.push({
150
+ kind: part.type,
151
+ id: String(ref.attachmentId ?? ''),
152
+ name: String(ref.name ?? ''),
153
+ mediaType: String(ref.mediaType ?? ''),
154
+ bytes: Number(ref.bytes ?? 0),
155
+ width: Number(ref.width ?? 0),
156
+ height: Number(ref.height ?? 0),
157
+ origin,
158
+ source,
159
+ turn: meta.turn,
160
+ seq: meta.seq,
161
+ time: meta.time,
162
+ })
163
+ }
164
+ }
165
+ if (event.type === 'agent/inbox/spliced') {
166
+ for (const entry of Array.isArray(event.data?.inserted) ? event.data.inserted : []) {
167
+ collectAttachments(entry?.content, 'user', { turn, seq: Number(event.seq ?? 0), time: Number(event.time ?? 0) }, 'inbox')
168
+ }
169
+ continue
170
+ }
171
+ if (event.type === 'tool/result') {
172
+ collectAttachments(event.data?.message?.content, 'agent', { turn, seq: Number(event.seq ?? 0), time: Number(event.time ?? 0) }, 'tool')
173
+ continue
174
+ }
175
+ // Agent 写出的文件:write / edit 工具的 path 参数(这两个工具是落盘的)
176
+ if (event.type === 'tool/call') {
177
+ const toolName = String(event.data?.name ?? '')
178
+ if (toolName === 'write' || toolName === 'edit') {
179
+ let args = {}
180
+ try { args = JSON.parse(String(event.data?.arguments ?? '{}')) } catch { args = {} }
181
+ const target = typeof args?.file_path === 'string'
182
+ ? args.file_path
183
+ : (typeof args?.path === 'string' ? args.path : '')
184
+ if (target !== '') {
185
+ writes.push({ path: target, turn, seq: Number(event.seq ?? 0), time: Number(event.time ?? 0) })
186
+ }
187
+ }
188
+ continue
189
+ }
137
190
  if (event.type === 'user/message') {
191
+ collectAttachments(event.data?.content, 'user', { turn, seq: Number(event.seq ?? 0), time: Number(event.time ?? 0) }, 'message')
138
192
  const content = textOf(event.data?.content)
193
+ // "@C:\path\file.docx" 只是文本引用,不进附件库;照样能在"附件"里查到
194
+ for (const match of content.matchAll(/@([A-Za-z]:[\\/][^\n@]*)/g)) {
195
+ // 不能按空格切:编辑器插入的 chip 后面经常紧跟正文
196
+ // ("@C:\\…\\报告.docx总结一下内容"),只能从长到短试前缀,能 stat 到文件的就是路径。
197
+ const raw = match[1].trim()
198
+ const limit = Math.min(raw.length, 400)
199
+ for (let length = limit; length >= 4; length -= 1) {
200
+ const candidate = raw.slice(0, length).trim().replace(/[,。;、))】》"'`]+$/, '')
201
+ if (candidate.length < 4) continue
202
+ try {
203
+ if (!fs.statSync(candidate).isFile()) continue
204
+ } catch {
205
+ continue
206
+ }
207
+ mentions.push({ path: candidate, turn, seq: Number(event.seq ?? 0), time: Number(event.time ?? 0) })
208
+ break
209
+ }
210
+ }
139
211
  if (content.trim() !== '') {
140
212
  messages.push({ role: 'user', text: content, time: Number(event.time ?? 0), seq: Number(event.seq ?? 0), turn })
141
213
  }
@@ -150,7 +222,7 @@ function start(ctx, config) {
150
222
  }
151
223
  }
152
224
  if (title === '' && messages.length > 0) title = messages[0].text.slice(0, 40)
153
- const parsed = { mtimeMs: stat.mtimeMs, size: stat.size, title, messages }
225
+ const parsed = { mtimeMs: stat.mtimeMs, size: stat.size, title, messages, attachments, writes, mentions }
154
226
  cache.set(file, parsed)
155
227
  return parsed
156
228
  }
@@ -322,6 +394,225 @@ function start(ctx, config) {
322
394
  }
323
395
  }
324
396
 
397
+ /** sha256 去掉前缀。 */
398
+ const shaOf = (id) => String(id ?? '').replace(/^sha256:/i, '')
399
+
400
+ /**
401
+ * 附件在磁盘上的路径。
402
+ * 图片归一化后存在 objects/,上传文件原样存在 file-objects/。
403
+ * @param {{kind: string, id: string}} item - 附件条目。
404
+ * @returns {string|null} 绝对路径;id 非法时为 null。
405
+ */
406
+ const attachmentPathOf = (item) => {
407
+ const sha = shaOf(item.id)
408
+ if (!/^[0-9a-f]{64}$/i.test(sha)) return null
409
+ const bucket = item.kind === 'image' ? 'objects' : 'file-objects'
410
+ return path.join(attachmentsRoot, bucket, sha.slice(0, 2), sha)
411
+ }
412
+
413
+ /** 会话 + 作用域过滤,附件检索与文本检索共用。 */
414
+ const scopeItems = (payload) => {
415
+ const scope = payload?.scope === 'workspace' ? 'workspace' : payload?.scope === 'current' ? 'current' : 'all'
416
+ const { bySession } = workspaceIndex()
417
+ const all = listSessions()
418
+ if (scope === 'current') {
419
+ const wanted = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
420
+ return { scope, bySession, items: all.filter(item => item.sessionId === wanted), sessionId: wanted }
421
+ }
422
+ if (scope === 'workspace') {
423
+ const wantedWorkspace = typeof payload?.workspaceId === 'string' ? payload.workspaceId : ''
424
+ const ids = new Set()
425
+ for (const [sessionId, owner] of bySession) if (owner.id === wantedWorkspace) ids.add(sessionId)
426
+ return { scope, bySession, items: all.filter(item => ids.has(item.sessionId)), workspaceId: wantedWorkspace }
427
+ }
428
+ return { scope, bySession, items: all }
429
+ }
430
+
431
+ /**
432
+ * 附件检索:按文件名匹配(空关键词 = 全部),区分用户上传与 Agent 生成。
433
+ * @param {object} payload - { query, scope, sessionId, workspaceId, kind }。
434
+ * @returns {object} 结果。
435
+ */
436
+ const listAttachments = (payload) => {
437
+ const started = Date.now()
438
+ const kind = payload?.kind === 'image' ? 'image' : 'file'
439
+ const query = typeof payload?.query === 'string' ? payload.query.trim().toLowerCase() : ''
440
+ const { scope, bySession, items: scopeSessions } = scopeItems(payload)
441
+ const items = []
442
+ const skipped = []
443
+ let scanned = 0
444
+ for (const session of scopeSessions) {
445
+ let parsed
446
+ try {
447
+ parsed = parseSession(session.file)
448
+ } catch (error) {
449
+ skipped.push({ sessionId: session.sessionId, reason: describe(error) })
450
+ continue
451
+ }
452
+ const owner = bySession.get(session.sessionId)
453
+ const title = parsed.title !== '' ? parsed.title : session.sessionId
454
+ // 同一张图会同时出现在 agent/inbox/spliced、user/message、tool/result 里,
455
+ // 按 (sessionId, attachmentId) 去重,保留第一次出现的位置。
456
+ // 同一条附件会在 inbox / user message / tool result 里重复出现,
457
+ // 用"最可信的事件"决定它属于哪一轮:user/message > tool/result > inbox。
458
+ const priorityOf = (source) => (source === 'message' ? 3 : source === 'tool' ? 2 : 1)
459
+ const seen = new Map()
460
+ if (kind === 'file') {
461
+ // 用户在消息里 @ 引用的本地文件(不在附件库,只有路径)
462
+ for (const mention of parsed.mentions ?? []) {
463
+ const name = path.basename(mention.path)
464
+ if (query !== '' && !name.toLowerCase().includes(query)) continue
465
+ const key = session.sessionId + '|mention|' + mention.path
466
+ if (seen.has(key)) continue
467
+ seen.set(key, { source: 'mention', seq: mention.seq, turn: mention.turn })
468
+ scanned += 1
469
+ let exists = false
470
+ let bytes = 0
471
+ try {
472
+ const stat = fs.statSync(mention.path)
473
+ exists = stat.isFile()
474
+ bytes = exists ? stat.size : 0
475
+ } catch { exists = false }
476
+ items.push({
477
+ kind: 'file',
478
+ id: '',
479
+ name,
480
+ mediaType: '',
481
+ bytes,
482
+ width: 0,
483
+ height: 0,
484
+ origin: 'user',
485
+ source: 'mention',
486
+ turn: mention.turn,
487
+ seq: mention.seq,
488
+ time: mention.time,
489
+ sessionId: session.sessionId,
490
+ title,
491
+ workspaceId: owner?.id ?? '',
492
+ workspaceTitle: owner?.title ?? '',
493
+ path: mention.path,
494
+ exists,
495
+ })
496
+ }
497
+ // Agent 写出的工作区文件:同一会话里同一路径只保留最后一次写入
498
+ const lastWrite = new Map()
499
+ for (const write of parsed.writes ?? []) lastWrite.set(write.path, write)
500
+ for (const [writePath, write] of lastWrite) {
501
+ const name = path.basename(writePath)
502
+ if (query !== '' && !name.toLowerCase().includes(query)) continue
503
+ const key = session.sessionId + '|file|' + writePath
504
+ if (seen.has(key)) continue
505
+ seen.set(key, { source: 'tool', seq: write.seq, turn: write.turn })
506
+ scanned += 1
507
+ let exists = false
508
+ let bytes = 0
509
+ try {
510
+ const stat = fs.statSync(writePath)
511
+ exists = stat.isFile()
512
+ bytes = exists ? stat.size : 0
513
+ } catch { exists = false }
514
+ items.push({
515
+ kind: 'file',
516
+ id: '',
517
+ name,
518
+ mediaType: '',
519
+ bytes,
520
+ width: 0,
521
+ height: 0,
522
+ origin: 'agent',
523
+ turn: write.turn,
524
+ seq: write.seq,
525
+ time: write.time,
526
+ sessionId: session.sessionId,
527
+ title,
528
+ workspaceId: owner?.id ?? '',
529
+ workspaceTitle: owner?.title ?? '',
530
+ path: writePath,
531
+ exists,
532
+ })
533
+ }
534
+ }
535
+ for (const attachment of parsed.attachments) {
536
+ if (attachment.kind !== kind) continue
537
+ if (query !== '' && !attachment.name.toLowerCase().includes(query)) continue
538
+ const key = session.sessionId + '|' + attachment.id
539
+ const known = seen.get(key)
540
+ if (known !== undefined) {
541
+ // 已有一条更可信(或更靠后)的记录:替换掉它,保证 turn 指向真正的消息
542
+ if (priorityOf(attachment.source) < priorityOf(known.source)) continue
543
+ if (priorityOf(attachment.source) === priorityOf(known.source) && attachment.seq <= known.seq) continue
544
+ const index = items.indexOf(known)
545
+ if (index >= 0) items.splice(index, 1)
546
+ }
547
+ seen.set(key, attachment)
548
+ scanned += 1
549
+ const filePath = attachmentPathOf(attachment)
550
+ let exists = false
551
+ if (filePath !== null) {
552
+ try { exists = fs.statSync(filePath).isFile() } catch { exists = false }
553
+ }
554
+ items.push({
555
+ ...attachment,
556
+ sessionId: session.sessionId,
557
+ title,
558
+ workspaceId: owner?.id ?? '',
559
+ workspaceTitle: owner?.title ?? '',
560
+ path: filePath,
561
+ exists,
562
+ })
563
+ }
564
+ }
565
+ items.sort((a, b) => b.time - a.time)
566
+ return {
567
+ kind,
568
+ query,
569
+ scope,
570
+ items: items.slice(0, maxHits),
571
+ truncated: items.length > maxHits,
572
+ total: items.length,
573
+ scannedSessions: scopeSessions.length,
574
+ elapsedMs: Date.now() - started,
575
+ skipped,
576
+ maxHits,
577
+ }
578
+ }
579
+
580
+ /**
581
+ * 打开附件所在文件夹(Windows 用资源管理器选中该文件)。
582
+ * @param {object} payload - { id, kind }。
583
+ * @returns {{ok: boolean, path: string}} 结果。
584
+ */
585
+ const openAttachment = (payload) => {
586
+ // 工作区文件(Agent 写出)没有 attachment id,直接用绝对路径;
587
+ // 附件则从 id 推导路径,并限制在附件根目录内。
588
+ const direct = typeof payload?.path === 'string' && payload.path !== '' ? path.resolve(payload.path) : null
589
+ const derived = attachmentPathOf({ kind: payload?.kind === 'image' ? 'image' : 'file', id: payload?.id })
590
+ const resolved = direct ?? (derived === null ? null : path.resolve(derived))
591
+ if (resolved === null) throw new Error('附件标识无效')
592
+ if (direct === null) {
593
+ const root = path.resolve(attachmentsRoot)
594
+ if (!resolved.startsWith(root + path.sep)) throw new Error('附件路径越界')
595
+ }
596
+ try {
597
+ if (!fs.statSync(resolved).isFile()) throw new Error('不是文件')
598
+ } catch {
599
+ throw new Error('文件不存在(可能已被移动或清理)')
600
+ }
601
+ const child = spawn('cmd', ['/c', 'explorer', '/select,', resolved], { detached: true, stdio: 'ignore', windowsHide: true })
602
+ child.unref()
603
+ return { ok: true, path: resolved }
604
+ }
605
+
606
+ /** 读取图片字节,返回 data URL(供列表缩略预览)。 */
607
+ const attachmentBlob = (payload) => {
608
+ const filePath = attachmentPathOf({ kind: 'image', id: payload?.id })
609
+ if (filePath === null) throw new Error('附件标识无效')
610
+ const bytes = fs.statSync(filePath).size
611
+ if (bytes > MAX_BLOB_BYTES) throw new Error('图片过大,无法内联预览')
612
+ const data = fs.readFileSync(filePath).toString('base64')
613
+ return { dataUrl: 'data:' + (typeof payload?.mediaType === 'string' && payload.mediaType !== '' ? payload.mediaType : 'image/png') + ';base64,' + data }
614
+ }
615
+
325
616
  const handleHttp = async (request) => {
326
617
  if (request.method !== 'POST') return new Response(null, { status: 405, headers: { allow: 'POST' } })
327
618
  let body
@@ -335,6 +626,9 @@ function start(ctx, config) {
335
626
  try {
336
627
  if (op === 'status') return Response.json({ ok: true, value: status() }, { headers: { 'cache-control': 'no-store' } })
337
628
  if (op === 'search') return Response.json({ ok: true, value: search(payload) }, { headers: { 'cache-control': 'no-store' } })
629
+ if (op === 'attachments') return Response.json({ ok: true, value: listAttachments(payload) }, { headers: { 'cache-control': 'no-store' } })
630
+ if (op === 'attachment-open') return Response.json({ ok: true, value: openAttachment(payload) }, { headers: { 'cache-control': 'no-store' } })
631
+ if (op === 'attachment-blob') return Response.json({ ok: true, value: attachmentBlob(payload) }, { headers: { 'cache-control': 'no-store' } })
338
632
  return Response.json({ ok: false, error: { code: 'message-search/unknown-op', message: `未知操作 "${op}"` } }, { status: 400 })
339
633
  } catch (error) {
340
634
  return Response.json({ ok: false, error: { code: 'message-search/failed', message: describe(error) } }, { status: 400 })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-dsh-message-search",
3
- "version": "0.2.1",
3
+ "version": "0.3.8",
4
4
  "license": "MIT",
5
5
  "description": "跨会话消息检索:Ctrl+F 打开,按当前会话 / 工作区 / 全部会话检索消息正文",
6
6
  "repository": {