@lizimin/dsh-session-search 0.0.0-stage → 1.3.6

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/client.js ADDED
@@ -0,0 +1,1013 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@lizimin/dsh-session-search',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const PANEL = 'local-session-search';
7
+ const NS = 'local-session-search';
8
+ const en = {
9
+ title: 'Session Search', intro: 'Find text in your conversation history.', all: 'All sessions', scope: 'Search scope',
10
+ placeholder: 'Search conversation text…', search: 'Search', clear: 'Clear', close: 'Back to conversation',
11
+ settings: 'Settings', openSettings: 'Open Session Search settings', settingsUnavailable: 'Plugin settings navigation is unavailable. Open Plugins → Session Search instead.',
12
+ loading: 'Searching…', empty: 'No matches found. Try different text or broaden your scope.',
13
+ start: 'Search all sessions, or choose one session to find individual messages.',
14
+ grouped: 'Every matching reply/event across conversations.',
15
+ events: 'Matching events in the selected session.', more: 'Load more results', open: 'Open conversation',
16
+ pending: 'No matches in this batch. Load more to search the remaining sessions.', partial: 'Some sessions could not be read. Results may be incomplete.',
17
+ within: 'Search this session', retry: 'Retry', catalogError: 'Could not load the session list.',
18
+ results: 'Results', sessionFilter: 'Filter session names or IDs…', choose: 'Choose a session',
19
+ shortcut: 'Ctrl+F / ⌘F', event: 'Event', stale: 'If history changed, search again to refresh the results.',
20
+ sessions: 'sessions', loadingSessions: 'Loading sessions…', unavailable: 'Selected session',
21
+ matching: 'Choose literal, case-sensitive, whole-word or regular-expression matching.',
22
+ includeSubagents: 'Include subagent conversations', subagent: 'Subagent', conversations: 'Conversations', subagents: 'Subagent conversations',
23
+ pickerHint: 'One entry per conversation, shown by its session title. Forked conversations stay separate.'
24
+ };
25
+ const zh = {
26
+ title: '会话搜索', intro: '在历史对话中查找文本。', all: '所有会话', scope: '搜索范围',
27
+ placeholder: '搜索对话文本…', search: '搜索', clear: '清空', close: '返回对话',
28
+ settings: '设置', openSettings: '打开会话搜索设置', settingsUnavailable: '暂时无法打开插件设置,请从“插件 → 会话搜索”进入。',
29
+ loading: '正在搜索…', empty: '没有匹配结果。请尝试其他文本或扩大搜索范围。',
30
+ start: '搜索所有会话,或选择指定会话来查找各条消息。',
31
+ grouped: '显示所有对话中的全部匹配回复或事件。',
32
+ events: '所选会话中的匹配事件。', more: '加载更多结果', open: '打开对话',
33
+ pending: '本批会话中没有匹配。请加载更多以搜索其余会话。', partial: '部分会话无法读取,结果可能不完整。',
34
+ within: '搜索此会话', retry: '重试', catalogError: '无法加载会话列表。',
35
+ results: '结果', sessionFilter: '筛选会话名称或 ID…', choose: '选择会话',
36
+ shortcut: 'Ctrl+F / ⌘F', event: '事件', stale: '如果历史记录已变化,请重新搜索以刷新结果。',
37
+ sessions: '个会话', loadingSessions: '正在加载会话…', unavailable: '所选会话',
38
+ matching: '支持字面文本、区分大小写、全字和正则表达式匹配。',
39
+ includeSubagents: '包含子代理对话', subagent: '子代理', conversations: '对话', subagents: '子代理对话',
40
+ pickerHint: '每个条目代表一个完整对话,以会话标题显示。分叉对话单独列出。'
41
+ };
42
+ Object.assign(en, {
43
+ grouped: 'Every matching reply/event across eligible conversations, ordered by message date.',
44
+ matching: 'One result per matching reply/event, not per text occurrence. Final replies exclude reasoning, tools and intermediate messages.',
45
+ matchCase: 'Match Case', wholeWord: 'Match Whole Word', useRegex: 'Use Regular Expression', searchModes: 'Search modes',
46
+ regexHint: 'Regular expressions use JavaScript Unicode syntax, without / delimiters. Complex patterns may time out.',
47
+ fuzzy: 'Text matching', fuzzyOff: 'Exact', fuzzyTypo: 'Typo-tolerant', fuzzySubsequence: 'Subsequence',
48
+ fuzzyOnly: 'No exact matches found. Below are the fuzzy matches.',
49
+ fuzzyOffHint: 'Exact text by default. Select a fuzzy mode for spelling mistakes or abbreviations. Regex and fuzzy modes are mutually exclusive.',
50
+ fuzzyTypoHint: 'Match complete words with small spelling mistakes, including swapped letters: wrokspace → workspace. Words of 1–3 characters require an exact match; 4–7 allow 1 edit; 8+ allow 2. Max 128 characters / 16 words.',
51
+ fuzzySubsequenceHint: 'Match ordered letters inside each word: wrkspc → workspace. Words must stay together in query order; matches cannot span unrelated text. Candidate words are limited to 4× query-word length + 8. Max 128 characters / 16 words.',
52
+ pickerHint: 'Whole conversations, latest user activity first. Empty/internal-only sessions are omitted; untitled conversations remain available.',
53
+ includeArchived: 'Include archived sessions', archived: 'Archived', finalOnly: 'Final model replies only',
54
+ finalHint: 'Turn this off to include user inputs, intermediate replies, tools and stored reasoning.',
55
+ sort: 'Result order', newest: 'Newest first', oldest: 'Oldest first', untitled: 'Untitled conversation',
56
+ refresh: 'Refresh sessions', archivedHint: 'Archived conversations must be restored from the sidebar/archive manager before opening.',
57
+ workspace: 'Workspace', allWorkspaces: 'All workspaces', ungroupedWorkspace: 'Ungrouped / no workspace',
58
+ workspaceHint: 'The session list and search are restricted to the selected workspace. Changing workspace clears the selected session.',
59
+ view: 'Result view', timeline: 'Timeline', bySession: 'By session', matches: 'matching messages',
60
+ treeHint: 'Conversations ordered by their newest matching message (oldest when reversed). Expand a conversation to see its matches.',
61
+ moreSessions: 'Load more sessions', loadedMatches: 'Loaded matches', groupChanged: 'History changed since the session counts were loaded. Search again to refresh.'
62
+ });
63
+ Object.assign(zh, {
64
+ grouped: '显示所有符合范围的对话中的全部匹配回复或事件,按消息时间排序。',
65
+ matching: '每条匹配回复或事件显示一个结果,不按文本出现次数计数。最终回复不包含推理、工具和中间消息。',
66
+ matchCase: '区分大小写', wholeWord: '全字匹配', useRegex: '使用正则表达式', searchModes: '匹配模式',
67
+ regexHint: '正则表达式采用 JavaScript Unicode 语法,不需要 / 分隔符。复杂表达式可能超时。',
68
+ fuzzy: '文本匹配', fuzzyOff: '精确', fuzzyTypo: '拼写容错', fuzzySubsequence: '子序列',
69
+ fuzzyOnly: '未找到精确匹配。以下为模糊匹配结果。',
70
+ fuzzyOffHint: '默认精确匹配。选择模糊模式可容忍拼写错误或使用缩写。正则表达式与模糊模式互斥。',
71
+ fuzzyTypoHint: '匹配有少量拼写错误的完整词,包括相邻字母交换:wrokspace → workspace。1–3 字符的词需精确匹配,4–7 字符允许 1 次编辑,8 字符以上允许 2 次。查询最多 128 字符 / 16 个词。',
72
+ fuzzySubsequenceHint: '在每个词内依序匹配字符:wrkspc → workspace。各词必须按查询顺序连续出现,不跨无关文本匹配。候选词长度不超过查询词长度的 4 倍加 8。查询最多 128 字符 / 16 个词。',
73
+ pickerHint: '每项代表完整对话,按最近用户活动排序。空会话和内部会话不显示;未命名对话仍可搜索。',
74
+ includeArchived: '包含已归档会话', archived: '已归档', finalOnly: '仅搜索模型最终回复',
75
+ finalHint: '取消勾选以包含用户输入、中间回复、工具和存储的推理文本。',
76
+ sort: '结果排序', newest: '最新优先', oldest: '最早优先', untitled: '未命名对话',
77
+ refresh: '刷新会话', archivedHint: '请先在侧边栏或归档管理中恢复已归档会话,再打开对话。',
78
+ workspace: '工作区', allWorkspaces: '所有工作区', ungroupedWorkspace: '未分组 / 无工作区',
79
+ workspaceHint: '会话列表和搜索仅限所选工作区。切换工作区会清除已选会话。',
80
+ view: '结果视图', timeline: '时间线', bySession: '按会话', matches: '条匹配消息',
81
+ treeHint: '按各会话最新匹配消息排序(最早优先时反向)。展开会话以查看匹配消息。',
82
+ moreSessions: '加载更多会话', loadedMatches: '已加载消息', groupChanged: '会话计数加载后历史记录已变化,请重新搜索以刷新。'
83
+ });
84
+ Object.assign(en, {filters: 'Search filters', tips: 'Search tips & matching rules', session: 'Session', readyTitle: 'Your conversations, within reach', emptyTitle: 'No matches yet', pendingTitle: 'More history to search', resultsHint: 'Matching messages', filterNames: 'Filter session list', navigation: 'Search navigation', typoExample: 'wrokspace → workspace', subsequenceExample: 'wrkspc → workspace'});
85
+ Object.assign(zh, {filters: '搜索筛选', tips: '搜索提示与匹配规则', session: '会话', readyTitle: '轻松找回对话中的细节', emptyTitle: '暂未找到匹配', pendingTitle: '还有历史记录待搜索', resultsHint: '匹配消息', filterNames: '筛选会话列表', navigation: '搜索导航', typoExample: 'wrokspace → workspace', subsequenceExample: 'wrkspc → workspace'});
86
+ Object.assign(en, {
87
+ searchMode: 'When to search', liveMode: 'Real-time (300 ms debounce)', submitMode: 'Only on Enter / Search',
88
+ modeHint: 'Applies to this profile. In Enter / Search mode, query and filter edits wait for submission.',
89
+ save: 'Save', saving: 'Saving…', saved: 'Saved', settingsLoading: 'Loading search settings…', settingsError: 'Could not load search settings.',
90
+ pendingChanges: 'Changes pending — press Enter or Search to apply the entire query and filters.',
91
+ selectAll: 'Select all listed', clearSelection: 'Clear selection (all)', selectedCount: 'selected', filterOptions: 'Filter names or IDs…', noOptions: 'No options found.',
92
+ workspaceHint: 'Choose one or more workspaces; an empty selection means all. Changing workspaces clears selected sessions.',
93
+ timeRange: 'Message time', allTime: 'All time', today: 'Today', last24h: 'Last 24 hours', last7d: 'Last 7 days', thisMonth: 'This month', custom: 'Custom',
94
+ startDate: 'Start date', endDate: 'End date', timeHint: 'Uses message timestamps, not session activity. Dates use your browser’s local timezone; the end date includes the entire local day. Relative ranges are fixed when searching and stay fixed while loading more.',
95
+ timeError: 'Choose valid dates with the start date on or before the end date.',
96
+ submitReady: 'Press Enter or Search to search with these filters.',
97
+ sessionLimit: 'Select at most 1,000 sessions, or clear the selection to search all sessions.',
98
+ workspaceLimit: 'Select at most 200 workspaces, or clear the selection to search all workspaces.'
99
+ });
100
+ Object.assign(zh, {
101
+ searchMode: '搜索触发方式', liveMode: '实时搜索(防抖 300 毫秒)', submitMode: '仅按回车 / 点击搜索时',
102
+ modeHint: '保存到当前配置档。回车 / 搜索模式下,文本与筛选修改将在提交后生效。',
103
+ save: '保存', saving: '正在保存…', saved: '已保存', settingsLoading: '正在加载搜索设置…', settingsError: '无法加载搜索设置。',
104
+ pendingChanges: '有待应用的修改 — 按回车或点击搜索以应用完整文本与筛选条件。',
105
+ selectAll: '全选当前列表', clearSelection: '清除选择(全部)', selectedCount: '项已选', filterOptions: '筛选名称或 ID…', noOptions: '没有符合条件的选项。',
106
+ workspaceHint: '可选择多个工作区;未选择表示全部。更改工作区将清除已选会话。',
107
+ timeRange: '消息时间', allTime: '所有时间', today: '今天', last24h: '最近 24 小时', last7d: '最近 7 天', thisMonth: '本月', custom: '自定义',
108
+ startDate: '开始日期', endDate: '结束日期', timeHint: '按消息时间戳筛选,而非会话活动时间。日期采用浏览器本地时区;结束日期包含当地整天。相对时间在搜索时固定,加载更多时不会移动。',
109
+ timeError: '请选择有效日期,且开始日期不得晚于结束日期。', submitReady: '按回车或点击搜索,使用这些筛选条件开始搜索。',
110
+ sessionLimit: '最多选择 1,000 个会话,或清除选择以搜索所有会话。',
111
+ workspaceLimit: '最多选择 200 个工作区,或清除选择以搜索所有工作区。'
112
+ });
113
+ Object.assign(en, {conversationHighlights: 'Search highlights', clearHighlights: 'Clear highlights (Esc)', highlighting: 'Highlighting loaded conversation text…', highlightReady: 'Matching text is highlighted. Press Esc to clear.', highlightEmpty: 'No matches in the currently displayed text. Load older messages or expand collapsed content to highlight more.', highlightLimited: 'Highlight limit reached; only part of the displayed text is highlighted.', highlightZeroWidth: 'Nonempty matches are highlighted; zero-width regex matches have no text to paint.', highlightUnavailable: 'This browser does not support conversation highlights.', highlightFailed: 'Could not highlight conversation text.'});
114
+ Object.assign(en, {
115
+ highlightLimited: 'Display highlighting is capped (200,000 characters / 500 blocks / 2,048 marks). The selected message is prioritized; search results are not reduced.',
116
+ highlightTargetHidden: 'The selected event is loaded, but its text is collapsed or not shown in Chat. Expand the relevant turn, reasoning or tool result.',
117
+ highlightJumpFailed: 'Could not load the selected message. Return to search and try again.'
118
+ });
119
+ Object.assign(zh, {conversationHighlights: '搜索高亮', clearHighlights: '清除高亮(Esc)', highlighting: '正在高亮已加载的对话文本…', highlightReady: '匹配文本已高亮。按 Esc 清除。', highlightEmpty: '当前显示的文本中没有匹配。加载更早消息或展开折叠内容可继续高亮。', highlightLimited: '已达到高亮上限,仅高亮部分显示文本。', highlightZeroWidth: '已高亮非空匹配;零宽正则匹配没有可标黄文本。', highlightUnavailable: '当前浏览器不支持对话高亮。', highlightFailed: '无法高亮对话文本。'});
120
+ Object.assign(zh, {
121
+ highlightLimited: '显示高亮已达上限(20 万字符 / 500 文本块 / 2,048 处标记)。优先处理所选消息;搜索结果并未减少。',
122
+ highlightTargetHidden: '所选事件已加载,但文本处于折叠状态或未在聊天视图中显示。请展开对应轮次、推理或工具结果。',
123
+ highlightJumpFailed: '无法加载所选消息。请返回搜索后重试。'
124
+ });
125
+ const css = `
126
+ .dss-page{box-sizing:border-box;display:flex;flex-direction:column;height:100%;min-height:0;width:100%;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-size:14px;line-height:1.5;container-type:inline-size}
127
+ .dss-page *{box-sizing:border-box}.dss-page [hidden]{display:none!important}.dss-page p{margin:0}.dss-muted{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.65}
128
+ .dss-head{padding:22px 28px;display:flex;justify-content:space-between;gap:16px;align-items:center;border-bottom:1px solid var(--dsw-alias-border-l1)}.dss-brand{display:flex;align-items:center;gap:13px;min-width:0}.dss-emblem{display:grid;place-items:center;width:42px;height:42px;flex-shrink:0;border-radius:13px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-brand-primary)}.dss-page h1{font-size:20px;line-height:1.35;letter-spacing:-.4px;margin:0 0 3px;font-weight:650}.dss-head-actions{display:flex;align-items:center;gap:12px;flex-shrink:0}
129
+ .dss-body{overflow:auto;min-height:0;flex:1;padding:28px 28px 40px;scrollbar-gutter:stable}.dss-inner{max-width:1040px;margin:0 auto}.dss-controls{padding:20px;border:1px solid var(--dsw-alias-border-l1);border-radius:16px;background:var(--dsw-alias-bg-layer-1)}
130
+ .dss-page input,.dss-page select{font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:9px 11px;min-width:0;min-height:38px;max-width:100%}.dss-page input::placeholder{color:var(--dsw-alias-label-secondary)}.dss-page button{font:inherit;font-size:13px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:7px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);padding:8px 12px;line-height:1.5;transition:background .15s,border-color .15s}.dss-page button:hover{background:var(--dsw-alias-bg-layer-2)}.dss-page button:disabled{opacity:.5;cursor:default}.dss-page button:focus-visible,.dss-page input:focus-visible,.dss-page select:focus-visible,.dss-page summary:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:3px}
131
+ .dss-form{display:flex;gap:10px;margin:0 0 18px;align-items:stretch}.dss-searchbox{display:flex;align-items:center;flex:1;min-width:0;border:1px solid var(--dsw-alias-border-l2);border-radius:11px;background:var(--dsw-alias-bg-base);padding:4px 7px 4px 13px;gap:6px}.dss-searchbox>svg{flex-shrink:0;color:var(--dsw-alias-label-secondary)}.dss-page .dss-query{flex:1;width:100%;min-width:50px;font-size:15px;border:0;background:transparent;padding:10px 6px;box-shadow:none}.dss-searchbox:focus-within{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}.dss-page .dss-query:focus-visible{outline:none}.dss-modes{display:flex;gap:2px;flex-shrink:0}.dss-page .dss-mode{font-family:monospace;font-size:13px;min-width:29px;min-height:29px;padding:3px 4px;border-radius:6px;border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary)}.dss-page .dss-mode[aria-pressed="true"]{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-bg-layer-2)}.dss-mode-word{text-decoration:underline;text-underline-offset:3px}
132
+ .dss-page .dss-primary{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);font-weight:600;background:var(--dsw-alias-bg-layer-2)}.dss-page .dss-submit{padding:10px 20px;border-radius:11px}.dss-page .dss-icon-button{width:32px;height:32px;padding:0;flex-shrink:0;border-color:transparent;background:transparent;font-size:21px;color:var(--dsw-alias-label-secondary)}.dss-page .dss-clear{font-size:18px;width:26px;height:28px}.dss-shortcut{white-space:nowrap;font-family:inherit;font-size:11px;border:1px solid var(--dsw-alias-border-l2);border-bottom-width:2px;border-radius:6px;padding:3px 7px;color:var(--dsw-alias-label-secondary)}
133
+ .dss-filter-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) minmax(0,1fr);gap:14px}.dss-field{display:flex;flex-direction:column;gap:6px;min-width:0}.dss-field>label,.dss-field-label{font-size:11px;font-weight:600;letter-spacing:.3px;color:var(--dsw-alias-label-secondary)}.dss-field select{width:100%}.dss-session-field{grid-column:2 / 4}.dss-session-controls{display:grid;grid-template-columns:minmax(90px,.65fr) minmax(0,1fr);gap:8px}.dss-session-controls input,.dss-session-controls select{width:100%}.dss-match-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:14px}.dss-match-row>label{font-size:12px;color:var(--dsw-alias-label-secondary)}.dss-match-row select{padding:5px 10px;min-height:32px}
134
+ .dss-options{display:flex;gap:10px 18px;flex-wrap:wrap;align-items:center;padding-top:16px;margin-top:16px;border-top:1px solid var(--dsw-alias-border-l1)}.dss-check{display:inline-flex;align-items:center;gap:7px;cursor:pointer;font-size:12px;line-height:1.5}.dss-check input{width:15px;height:15px;min-height:0;padding:0;margin:0;accent-color:var(--dsw-alias-brand-primary)}.dss-page .dss-refresh{margin-left:auto;padding:4px 6px;font-size:12px;border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary)}
135
+ .dss-tips{margin-top:13px;font-size:12px;color:var(--dsw-alias-label-secondary)}.dss-tips summary{cursor:pointer;display:list-item;width:fit-content;max-width:100%;padding:3px 0;user-select:none}.dss-tips[open] summary{margin-bottom:10px;color:var(--dsw-alias-label-primary)}.dss-tip-body{display:grid;gap:8px;padding:12px 14px;background:var(--dsw-alias-bg-base);border-radius:9px;line-height:1.7}.dss-tip-body strong{font-weight:600;color:var(--dsw-alias-label-primary)}
136
+ .dss-divider{border:0;border-top:1px solid var(--dsw-alias-border-l1);margin:26px 0 20px;width:100%}.dss-results-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:14px}.dss-results-title{font-size:14px;font-weight:600;margin:0}.dss-display-options{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.dss-page select option{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}.dss-views{display:inline-flex;gap:2px;padding:3px;background:var(--dsw-alias-bg-layer-2);border-radius:8px}.dss-page .dss-view{font-size:12px;border-color:transparent;padding:3px 10px;background:transparent;border-radius:5px;color:var(--dsw-alias-label-secondary)}.dss-page .dss-view[aria-pressed="true"]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l1);font-weight:600}
137
+ .dss-note{margin:0 0 16px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap}.dss-result-count{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}.dss-message{padding:48px 22px;text-align:center;border:1px solid var(--dsw-alias-border-l1);border-radius:14px;background:var(--dsw-alias-bg-layer-1);line-height:1.8;color:var(--dsw-alias-label-secondary);font-size:13px}.dss-message>svg{display:block;margin:0 auto 16px;padding:12px;box-sizing:content-box;border-radius:16px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-brand-primary)}.dss-message h3{font-size:16px;font-weight:600;color:var(--dsw-alias-label-primary);margin:0 0 7px}.dss-page .dss-fuzzy-notice{padding:12px 15px;margin:0 0 16px;border-left:3px solid var(--dsw-alias-brand-primary);border-radius:0 8px 8px 0;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.65}.dss-error{color:var(--dsw-alias-state-error-primary);padding:14px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;margin:14px 0;font-size:13px;overflow-wrap:anywhere}
138
+ .dss-hit{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);border-radius:13px;margin-bottom:12px;padding:18px 20px;transition:border-color .15s}.dss-hit:hover{border-color:var(--dsw-alias-border-l2)}.dss-hit h2{font-size:15px;line-height:1.5;margin:0;font-weight:600;overflow-wrap:anywhere}.dss-hit-heading{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.dss-meta{display:flex;align-items:center;gap:6px 12px;flex-wrap:wrap;margin:8px 0 12px;font-size:11px}.dss-event-type{font-weight:500;color:var(--dsw-alias-label-primary)}.dss-id{font-family:monospace;overflow-wrap:anywhere;font-size:10px}.dss-meta .dss-id{margin-left:auto}.dss-badge{display:inline-flex;gap:4px;align-items:center;min-width:0;max-width:100%;font-size:10px;line-height:1.7;font-weight:500;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:5px;padding:1px 6px;vertical-align:middle;overflow-wrap:anywhere}.dss-badge svg{flex-shrink:0}.dss-workspace-badge{max-width:100%}
139
+ .dss-snippet{white-space:pre-wrap;overflow-wrap:anywhere;font-family:inherit;font-size:13px;line-height:1.85;margin:0 0 14px;padding:12px 14px;background:var(--dsw-alias-bg-base);border-radius:8px;max-height:260px;overflow:auto}.dss-snippet mark{background:var(--dsw-alias-state-warn-primary);color:var(--dss-mark-ink,var(--dsw-alias-bg-base));font-weight:650;border-radius:3px;padding:0 1px;box-shadow:0 0 0 1px var(--dsw-alias-state-warn-primary);text-decoration:none}.dss-actions{display:flex;gap:12px;flex-wrap:wrap}.dss-page .dss-actions button{padding:3px 0;font-size:12px;border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary)}.dss-page .dss-actions .dss-primary{color:var(--dsw-alias-brand-primary);font-weight:500}.dss-page .dss-actions button:hover{color:var(--dsw-alias-brand-primary);text-decoration:underline}.dss-page .dss-more{display:flex;margin:22px auto;padding:9px 20px;border-radius:9px}
140
+ .dss-group{border:1px solid var(--dsw-alias-border-l1);border-radius:13px;margin:0 0 12px;background:var(--dsw-alias-bg-layer-1);overflow:hidden}.dss-group h2{font-size:14px;margin:0}.dss-page .dss-group-toggle{display:flex;align-items:center;text-align:left;gap:11px;width:100%;border:0;border-radius:0;padding:17px 20px 10px;background:transparent}.dss-group-title{flex:1;min-width:0;overflow-wrap:anywhere;font-weight:600}.dss-chevron{flex-shrink:0;color:var(--dsw-alias-label-secondary);transition:transform .15s}.dss-group-toggle[aria-expanded="true"] .dss-chevron{transform:rotate(90deg)}.dss-group-count{font-size:11px;font-weight:500;color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-bg-layer-2);border-radius:6px;padding:3px 8px;text-align:right}.dss-group-meta{padding:0 20px 15px 45px;display:flex;gap:8px;flex-wrap:wrap;font-size:11px}.dss-group-body{margin:0 18px 18px 26px;padding-left:14px;border-left:2px solid var(--dsw-alias-border-l2)}.dss-group-body .dss-hit{background:var(--dsw-alias-bg-base);padding:12px 14px}.dss-group-body .dss-snippet{background:var(--dsw-alias-bg-layer-1)}.dss-group-body .dss-meta{margin-top:0}.dss-group-body .dss-message{padding:18px}.dss-group-progress{padding:8px 0;font-size:11px}.dss-group .dss-more{margin:12px auto}.dss-zero{display:inline-block;width:2px;min-height:1em;vertical-align:text-bottom;background:var(--dsw-alias-brand-primary)}
141
+ @container(max-width:720px){.dss-head{padding:18px 20px}.dss-body{padding:20px}.dss-controls{padding:16px}.dss-filter-grid{grid-template-columns:1fr 1fr}.dss-session-field{grid-column:1 / -1}.dss-field:first-child{grid-column:1 / -1}.dss-shortcut{display:none}.dss-page .dss-refresh{margin-left:0}}
142
+ @container(max-width:480px){.dss-head{padding:16px}.dss-head .dss-muted{font-size:11px}.dss-emblem{width:34px;height:34px;border-radius:10px}.dss-brand{gap:10px}.dss-page h1{font-size:18px}.dss-body{padding:16px 12px 28px}.dss-form{flex-wrap:wrap;gap:8px}.dss-searchbox{flex-basis:100%}.dss-page .dss-submit{width:100%;padding:8px}.dss-session-controls{grid-template-columns:1fr}.dss-options{align-items:flex-start;gap:12px;flex-direction:column}.dss-hit{padding:14px}.dss-meta .dss-id{margin-left:0}.dss-results-toolbar{align-items:flex-start}.dss-group-toggle .dss-group-count{max-width:105px}.dss-group-body{margin-left:12px;padding-left:10px}.dss-group-meta{padding-left:20px}}
143
+ .dss-picker{position:relative;min-width:0}.dss-page .dss-picker-trigger{width:100%;justify-content:space-between;text-align:left;min-height:38px}.dss-picker-panel{position:absolute;z-index:20;top:calc(100% + 5px);left:0;width:100%;min-width:min(280px,80vw);max-width:85vw;padding:10px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-base)}.dss-picker-panel>input{width:100%}.dss-picker-tools{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}.dss-page .dss-picker-tools button{font-size:11px;padding:3px 6px}.dss-picker-list{max-height:240px;overflow:auto;overscroll-behavior:contain}.dss-picker-option{display:flex;align-items:flex-start;gap:8px;padding:8px;border-radius:6px;overflow-wrap:anywhere;font-size:12px;cursor:pointer}.dss-picker-option:hover{background:var(--dsw-alias-bg-layer-2)}.dss-picker-option input{flex-shrink:0;width:15px;height:15px;min-height:0;padding:0;margin:3px 0;accent-color:var(--dsw-alias-brand-primary)}.dss-time-grid{margin-top:14px}.dss-pending{margin:12px 0;color:var(--dsw-alias-state-warn-primary);font-size:12px}.dss-settings{height:auto;display:block;padding:16px;border-radius:12px;border:1px solid var(--dsw-alias-border-l1)}.dss-settings .dss-field{margin-bottom:12px}.dss-settings .dss-save-row{display:flex;align-items:center;gap:12px}.dss-zero{background:var(--dsw-alias-state-warn-primary)!important}
144
+ @media(prefers-reduced-motion:reduce){.dss-page *{transition:none!important}}
145
+ `;
146
+ function Icon({size = 20}) {
147
+ return h('svg', {width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, 'aria-hidden': true},
148
+ h('circle', {cx: 10.5, cy: 10.5, r: 6.8}), h('path', {d: 'm16 16 5 5'}));
149
+ }
150
+ function Glyph({kind, size = 15}) {
151
+ const paths = {refresh: 'M20 7v5h-5 M4 17v-5h5 M6.1 7a7 7 0 0 1 11.5-2L20 8 M4 16l2.4 3A7 7 0 0 0 18 17', arrow: 'M5 12h14 M13 6l6 6-6 6', timeline: 'M8 5h12 M8 12h12 M8 19h12 M3 5h.01 M3 12h.01 M3 19h.01', folder: 'M3 7h6l2-3h5l2 3h3v13H3z', back: 'M19 12H5 M11 6l-6 6 6 6', settings: 'M4 7h16 M4 17h16 M8 4v6 M16 14v6'};
152
+ return h('svg', {width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true}, h('path', {d: paths[kind] || paths.arrow}));
153
+ }
154
+ function BranchIcon() {
155
+ return h('svg', {width: 12, height: 12, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, 'aria-hidden': true},
156
+ h('circle', {cx: 4, cy: 3, r: 1.5}), h('circle', {cx: 12, cy: 4, r: 1.5}), h('circle', {cx: 4, cy: 13, r: 1.5}), h('path', {d: 'M4 4.5v7M4 9h3a5 5 0 0 0 5-3.5'}));
157
+ }
158
+ const shortId = id => id.replace(/^session-/, '').slice(0, 8);
159
+ // Only render Host-computed ranges: executing a user regex here could freeze the UI.
160
+ // All session text remains React text nodes, never HTML.
161
+ function Highlight({text, ranges}) {
162
+ const source = String(text || '');
163
+ if (!Array.isArray(ranges) || !ranges.length) return source;
164
+ const parts = [];
165
+ let start = 0;
166
+ for (const [index, range] of ranges.slice(0, 100).entries()) {
167
+ if (!Number.isInteger(range.start) || !Number.isInteger(range.end) || range.start < start || range.end < range.start || range.end > source.length) continue;
168
+ parts.push(source.slice(start, range.start), h('mark', {key: index, className: range.start === range.end ? 'dss-zero' : undefined}, source.slice(range.start, range.end)));
169
+ start = range.end;
170
+ }
171
+ parts.push(source.slice(start));
172
+ return h(React.Fragment, null, ...parts);
173
+ }
174
+ // Resolve at click time so a temporarily unavailable manager never blanks Search.
175
+ function openPluginSettings(ctx) {
176
+ const navigation = ctx.get('pluginNavigation');
177
+ if (typeof navigation?.openBundle !== 'function') return false;
178
+ navigation.openBundle('@lizimin/dsh-session-search');
179
+ return true;
180
+ }
181
+ // Parse date inputs as browser-local calendar dates, never UTC date-only strings.
182
+ function localDay(value) {
183
+ if (!value) return undefined;
184
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
185
+ if (!match) return NaN;
186
+ const [, year, month, day] = match.map(Number);
187
+ const date = new Date(0); date.setFullYear(year, month - 1, day); date.setHours(0, 0, 0, 0);
188
+ return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day ? date.getTime() : NaN;
189
+ }
190
+ function timeBounds(preset, start, end, now) {
191
+ if (preset === 'all') return {};
192
+ if (preset === 'custom') {
193
+ const after = localDay(start), endDay = localDay(end);
194
+ if ((after !== undefined && !Number.isFinite(after)) || (endDay !== undefined && !Number.isFinite(endDay)) || (after !== undefined && endDay !== undefined && after > endDay)) return null;
195
+ const date = endDay === undefined ? null : new Date(endDay);
196
+ if (date) date.setDate(date.getDate() + 1);
197
+ return {after, before: date?.getTime()};
198
+ }
199
+ if (preset === '24h' || preset === '7d') return {after: now - (preset === '24h' ? 1 : 7) * 86400000, before: now};
200
+ const date = new Date(now); date.setHours(0, 0, 0, 0);
201
+ if (preset === 'month') date.setDate(1);
202
+ return {after: date.getTime(), before: now};
203
+ }
204
+ // Exact event identities only. Chat anchors can precede assistant settlement;
205
+ // never navigate to the numerically nearest row (that could be another reply).
206
+ function selectedChatNodeKeys(chat, seq) {
207
+ if (!Number.isSafeInteger(seq) || !chat?.order || !chat.nodes?.get) return [];
208
+ return chat.order.filter(key => {
209
+ const node = chat.nodes.get(key);
210
+ return node && [node.anchorSeq, node.data?.seq, node.data?.finalNode?.seq, node.data?.root?.seq].includes(seq);
211
+ });
212
+ }
213
+ async function loadSelectedMessage(reference, intent, isCurrent) {
214
+ await reference.ready;
215
+ if (!isCurrent()) return false;
216
+ if (Number.isSafeInteger(intent.seq)) await reference.binding.session.loadThrough(intent.seq);
217
+ return isCurrent();
218
+ }
219
+ return {
220
+ inject: ['slots', 'layout', 'locale', 'uiWorkspace', 'sessions'],
221
+ apply(ctx) {
222
+ ctx.effect(() => ctx.locale.register(NS, 'en', en));
223
+ ctx.effect(() => ctx.locale.register(NS, 'zh', zh));
224
+ const t = ctx.locale.bind(NS);
225
+ const stored = {query: '', sessionIds: [], workspaceIds: [], includeSubagents: false, includeArchived: false, finalOnly: true, order: 'newest', matchCase: false, wholeWord: false, useRegex: false, fuzzy: 'off', view: 'timeline', timePreset: 'all', startDate: '', endDate: ''};
226
+ const settingListeners = new Set();
227
+ let settingsEpoch = 0;
228
+ async function settingsApi(method = 'GET', searchMode, signal) {
229
+ const response = await fetch(new URL('api/local-session-search-settings', document.baseURI), {
230
+ method, credentials: 'same-origin', cache: 'no-store', signal,
231
+ ...(method === 'POST' ? {headers: {'Content-Type': 'application/json'}, body: JSON.stringify({searchMode})} : {})
232
+ });
233
+ const value = await response.json();
234
+ if (!response.ok) throw new Error(value.error || `HTTP ${response.status}`);
235
+ if (!['live', 'submit'].includes(value.searchMode)) throw new Error(t('settingsError'));
236
+ return value;
237
+ }
238
+ function SettingsForm({view}) {
239
+ React.useSyncExternalStore(fn => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
240
+ const [mode, setMode] = React.useState('live');
241
+ const [loaded, setLoaded] = React.useState(false);
242
+ const [busy, setBusy] = React.useState(false);
243
+ const [error, setError] = React.useState('');
244
+ const [saved, setSaved] = React.useState(false);
245
+ const [retry, setRetry] = React.useState(0);
246
+ const control = React.useRef(null);
247
+ const id = React.useId();
248
+ React.useEffect(() => {
249
+ const controller = new AbortController(); control.current = controller;
250
+ setLoaded(false); setError('');
251
+ settingsApi('GET', undefined, controller.signal).then(value => {
252
+ if (!controller.signal.aborted) {setMode(value.searchMode); setLoaded(true);}
253
+ }).catch(err => {if (!controller.signal.aborted) setError(err.message);});
254
+ return () => {controller.abort(); control.current?.abort();};
255
+ }, [retry]);
256
+ if (view === 'summary') return h('p', null, t('modeHint'));
257
+ const save = async event => {
258
+ event.preventDefault(); if (!loaded || busy) return;
259
+ const controller = new AbortController(); control.current = controller;
260
+ setBusy(true); setError(''); setSaved(false);
261
+ try {
262
+ const value = await settingsApi('POST', mode, controller.signal);
263
+ if (controller.signal.aborted) return;
264
+ settingsEpoch++; for (const listener of settingListeners) listener(value.searchMode);
265
+ setMode(value.searchMode); setSaved(true);
266
+ } catch (err) {if (!controller.signal.aborted) setError(err.message);}
267
+ finally {if (!controller.signal.aborted) setBusy(false);}
268
+ };
269
+ return h('form', {className: 'dss-page dss-settings', onSubmit: save, 'aria-busy': !loaded && !error || busy}, h('style', null, css),
270
+ h('div', {className: 'dss-field'}, h('label', {htmlFor: id}, t('searchMode')),
271
+ h('select', {id, value: mode, disabled: !loaded || busy, onChange: e => {setMode(e.target.value); setSaved(false);}},
272
+ h('option', {value: 'live'}, t('liveMode')), h('option', {value: 'submit'}, t('submitMode'))), h('p', {className: 'dss-muted'}, t('modeHint'))),
273
+ !loaded && !error && h('p', {role: 'status'}, t('settingsLoading')),
274
+ error && h('div', {className: 'dss-error', role: 'alert'}, error, !loaded && h('button', {type: 'button', onClick: () => setRetry(v => v + 1)}, t('retry'))),
275
+ h('div', {className: 'dss-save-row'}, h('button', {type: 'submit', className: 'dss-primary', disabled: !loaded || busy}, t(busy ? 'saving' : 'save')),
276
+ saved && h('span', {role: 'status'}, t('saved'))));
277
+ }
278
+ function MultiPicker({label, allLabel, values, options, onChange, disabled, hint}) {
279
+ const [open, setOpen] = React.useState(false);
280
+ const [filter, setFilter] = React.useState('');
281
+ const root = React.useRef(null), trigger = React.useRef(null), field = React.useRef(null);
282
+ const id = React.useId();
283
+ React.useEffect(() => {if (disabled) setOpen(false);}, [disabled]);
284
+ React.useEffect(() => {
285
+ if (!open) return;
286
+ field.current?.focus();
287
+ const outside = event => {if (!root.current?.contains(event.target)) setOpen(false);};
288
+ document.addEventListener('pointerdown', outside);
289
+ return () => document.removeEventListener('pointerdown', outside);
290
+ }, [open]);
291
+ const known = new Set(options.map(option => option.id));
292
+ const entries = [...options, ...values.filter(value => !known.has(value)).map(value => ({id: value, label: value}))];
293
+ const visible = entries.filter(option => `${option.label} ${option.id}`.toLowerCase().includes(filter.toLowerCase()));
294
+ const selected = new Set(values);
295
+ return h('div', {className: 'dss-picker', ref: root, onBlur: event => {
296
+ // Row text/padding is not focusable: allow the label's native click to
297
+ // reach its checkbox before dismissing. Outside pointers and Escape
298
+ // already close the picker; only definite outside focus closes here.
299
+ if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget)) setOpen(false);
300
+ }, onKeyDown: event => {
301
+ if (event.key === 'Escape' && open) {event.preventDefault(); event.stopPropagation(); setOpen(false); trigger.current?.focus();}
302
+ }}, h('button', {ref: trigger, type: 'button', className: 'dss-picker-trigger', disabled, title: hint, 'aria-label': label, 'aria-expanded': open, 'aria-controls': id, 'aria-haspopup': 'dialog', onClick: () => setOpen(value => !value)},
303
+ values.length ? `${values.length} ${t('selectedCount')}` : allLabel, h('span', {'aria-hidden': true}, '▾')),
304
+ open && h('div', {id, className: 'dss-picker-panel', role: 'dialog', 'aria-label': label},
305
+ h('input', {ref: field, type: 'search', value: filter, placeholder: t('filterOptions'), 'aria-label': `${label}: ${t('filterNames')}`, onChange: e => setFilter(e.target.value)}),
306
+ h('div', {className: 'dss-picker-tools'},
307
+ h('button', {type: 'button', onClick: () => onChange([...new Set([...values, ...visible.map(option => option.id)])])}, t('selectAll')),
308
+ h('button', {type: 'button', onClick: () => onChange([])}, t('clearSelection'))),
309
+ h('div', {className: 'dss-picker-list', role: 'group', 'aria-label': label}, visible.length ? visible.map(option => h('label', {key: option.id, className: 'dss-picker-option', title: option.title || option.id},
310
+ h('input', {type: 'checkbox', checked: selected.has(option.id), onChange: e => onChange(e.target.checked ? [...values, option.id] : values.filter(value => value !== option.id))}), h('span', null, option.label))) : h('p', {className: 'dss-muted'}, t('noOptions')))));
311
+ }
312
+ // Opaque warn fill remains yellow in both palettes. Pick a contrasting ink
313
+ // from existing semantic surfaces, recalculating when the palette changes.
314
+ function useHighlightContrast() {
315
+ const root = React.useRef(null);
316
+ React.useEffect(() => {
317
+ const node = root.current; if (!node) return;
318
+ const probe = document.createElement('span'); probe.hidden = true; node.append(probe);
319
+ const luminance = color => {
320
+ const rgb = color.match(/[\d.]+/g)?.slice(0, 3).map(Number);
321
+ if (!rgb || rgb.length !== 3) return null;
322
+ return rgb.map(value => {const v = value / 255; return v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4;}).reduce((sum, value, index) => sum + value * [.2126, .7152, .0722][index], 0);
323
+ };
324
+ const update = () => {
325
+ const readColor = token => {probe.style.color = `var(${token})`; return luminance(getComputedStyle(probe).color);};
326
+ const yellow = readColor('--dsw-alias-state-warn-primary');
327
+ if (yellow === null) return;
328
+ let best = '', score = 0;
329
+ for (const token of ['--dsw-alias-label-primary', '--dsw-alias-bg-base']) {
330
+ const ink = readColor(token); if (ink === null) continue;
331
+ const contrast = (Math.max(ink, yellow) + .05) / (Math.min(ink, yellow) + .05);
332
+ if (contrast > score) {score = contrast; best = token;}
333
+ }
334
+ if (best) node.style.setProperty('--dss-mark-ink', `var(${best})`);
335
+ };
336
+ update();
337
+ const observer = new MutationObserver(update);
338
+ observer.observe(document.body, {attributes: true, attributeFilter: ['style', 'class', 'data-ds-dark-theme']});
339
+ observer.observe(document.documentElement, {attributes: true, attributeFilter: ['style', 'class']});
340
+ return () => {observer.disconnect(); probe.remove();};
341
+ }, []);
342
+ return root;
343
+ }
344
+ const focusListeners = new Set();
345
+ const focus = () => {for (const fn of focusListeners) fn();};
346
+ ctx.effect(() => {
347
+ const keydown = event => {
348
+ if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== 'f' || event.isComposing || event.repeat) return;
349
+ try {ctx.layout.selectPanel(PANEL);} catch {return;}
350
+ event.preventDefault();
351
+ focus();
352
+ };
353
+ window.addEventListener('keydown', keydown);
354
+ return () => window.removeEventListener('keydown', keydown);
355
+ });
356
+ async function api(input, signal) {
357
+ const params = new URLSearchParams();
358
+ for (const [key, value] of Object.entries(input)) if (value !== undefined && value !== '') params.set(key, Array.isArray(value) ? JSON.stringify(value) : value);
359
+ // Relative to the mounted application URL; signed same-origin cookie only.
360
+ const response = await fetch(new URL(`api/local-session-search?${params}`, document.baseURI), {credentials: 'same-origin', cache: 'no-store', signal});
361
+ const value = await response.json();
362
+ if (!response.ok) throw new Error(value.error || `HTTP ${response.status}`);
363
+ return value;
364
+ }
365
+ // View-only intent: never saved to session events, storage, or the URL.
366
+ let highlightIntent = null;
367
+ let highlightPanelMounted = false;
368
+ let releaseHighlightShell;
369
+ let observedHighlightIntent = null;
370
+ const highlightListeners = new Set();
371
+ const setHighlightIntent = value => {
372
+ if (value !== highlightIntent) observedHighlightIntent = null;
373
+ highlightIntent = value;
374
+ // Keep the native main key and its selected-Session surface. Only the
375
+ // shell is temporarily shadowed; its declarations remain owner-managed.
376
+ if (value && !releaseHighlightShell) {
377
+ try {
378
+ releaseHighlightShell = ctx.slots.inject('main.conversation', function* () {
379
+ yield ctx.slots.register({name: 'main.conversation', priority: -10,
380
+ children: {'session-search.highlight.body': {kind: 'single', scope: 'session'}}}, HighlightedConversation);
381
+ yield ctx.slots.register({name: 'session-search.highlight.body'}, HighlightedConversationBody);
382
+ });
383
+ } catch (error) {highlightIntent = null; throw error;}
384
+ } else if (!value && releaseHighlightShell) {
385
+ const release = releaseHighlightShell; releaseHighlightShell = undefined; release();
386
+ }
387
+ for (const listener of highlightListeners) listener();
388
+ };
389
+ const clearHighlights = () => {
390
+ const wasMounted = highlightPanelMounted;
391
+ setHighlightIntent(null);
392
+ // null is native Conversation mode; the string 'conversation' is a
393
+ // custom panel and does NOT mount sidebarRight's Session surface.
394
+ if (wasMounted) ctx.layout.selectPanel(null);
395
+ };
396
+ ctx.effect(() => {
397
+ const escape = event => {
398
+ if (event.key !== 'Escape' || event.isComposing || !highlightIntent) return;
399
+ event.preventDefault(); event.stopPropagation(); clearHighlights();
400
+ };
401
+ window.addEventListener('keydown', escape, true);
402
+ return () => {window.removeEventListener('keydown', escape, true); setHighlightIntent(null); window.CSS?.highlights?.delete('dss-conversation-match');};
403
+ });
404
+ const HighlightRoot = React.createContext(null);
405
+ const highlightCss = `
406
+ .dss-conversation-root{display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;height:100%;position:relative}
407
+ .dss-conversation-root *::highlight(dss-conversation-match){background:var(--dsw-alias-state-warn-primary);color:var(--dss-mark-ink,var(--dsw-alias-bg-base));text-decoration:none}
408
+ .dss-highlight-header{display:flex;align-items:center;gap:12px;flex-wrap:wrap;flex-shrink:0;padding:12px 18px;border-bottom:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
409
+ .dss-highlight-header>strong{flex:1;min-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
410
+ .dss-highlight-header>button{font:inherit;cursor:pointer;padding:5px 9px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}
411
+ .dss-highlight-header>button:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
412
+ .dss-conversation-highlight-control{display:inline-flex;align-items:center;gap:6px;max-width:640px;min-width:0;color:var(--dsw-alias-label-secondary);font-size:11px}
413
+ .dss-conversation-highlight-control span{white-space:normal;overflow-wrap:anywhere;line-height:1.5}
414
+ .dss-conversation-highlight-control button{font:inherit;cursor:pointer;padding:3px 7px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}
415
+ .dss-conversation-highlight-control button:hover{background:var(--dsw-alias-bg-layer-2)}
416
+ .dss-conversation-highlight-control button:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
417
+ `;
418
+ // A temporary native Conversation shell owns only its unique child.
419
+ // Retain history through the selected event and release on exit.
420
+ function HighlightedConversation({sessionId, renderSlot, SessionProvider}) {
421
+ React.useSyncExternalStore(fn => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
422
+ const intent = React.useSyncExternalStore(fn => {highlightListeners.add(fn); return () => highlightListeners.delete(fn);}, () => highlightIntent);
423
+ const [opened, setOpened] = React.useState(null);
424
+ const [error, setError] = React.useState('');
425
+ React.useEffect(() => {
426
+ // Ignore the old selection during asynchronous openSession. Once the
427
+ // requested Session has appeared, navigating away restores the shell
428
+ // even if the renderer remounts this component for another Session.
429
+ if (!intent || intent !== highlightIntent) return;
430
+ if (sessionId === intent.sessionId) observedHighlightIntent = intent;
431
+ else if (observedHighlightIntent === intent) setHighlightIntent(null);
432
+ }, [sessionId, intent]);
433
+ React.useEffect(() => {
434
+ highlightPanelMounted = true;
435
+ return () => {highlightPanelMounted = false;};
436
+ }, []);
437
+ React.useEffect(() => {
438
+ setOpened(null); setError('');
439
+ if (!intent) return;
440
+ let cancelled = false, reference;
441
+ try {
442
+ reference = ctx.sessions.retain(intent.sessionId, {source: 'gateway'});
443
+ // Chat's latest page alone may not contain the selected event.
444
+ loadSelectedMessage(reference, intent, () => !cancelled && highlightIntent === intent).then(current => {
445
+ if (current) setOpened({intent, reference});
446
+ }).catch(failure => {if (!cancelled && highlightIntent === intent) setError(`${t('highlightJumpFailed')} ${failure.message}`);});
447
+ } catch (failure) {setError(failure.message);}
448
+ return () => {cancelled = true; reference?.release();};
449
+ }, [intent]);
450
+ return opened?.intent === intent && intent?.sessionId === sessionId ? h(SessionProvider, {session: opened.reference}, renderSlot('session-search.highlight.body', {})) :
451
+ h('div', {className: 'dss-page'}, h('style', null, css),
452
+ h('p', {role: error ? 'alert' : 'status'}, error || t('highlighting')),
453
+ h('button', {type: 'button', onClick: clearHighlights}, t('close')));
454
+ }
455
+ function HighlightedConversationBody({sessionId, renderFactorySlot, useSessions, useChat}) {
456
+ const root = useHighlightContrast();
457
+ const title = useSessions(snapshot => snapshot.byId[sessionId]?.title);
458
+ return h(HighlightRoot.Provider, {value: root}, h('div', {ref: root, className: 'dss-conversation-root'},
459
+ h('style', null, highlightCss),
460
+ h('header', {className: 'dss-highlight-header', 'data-dss-highlight-ui': ''},
461
+ h('strong', {title: title || sessionId}, title || t('untitled')),
462
+ h(ConversationHighlights, {sessionId, useChat}),
463
+ h('button', {type: 'button', onClick: clearHighlights}, t('close'))),
464
+ renderFactorySlot('conversation.content', {variant: 'embedded', phase: 'active', hero: false})));
465
+ }
466
+ // Read only our owned subtree; CSS Custom Highlights paint DOM Ranges
467
+ // without inserting mark tags into React's tree or changing saved text.
468
+ function collectHighlightBlocks(root, priorityRoots = []) {
469
+ const excluded = 'script,style,textarea,input,select,button,header,nav,form,[contenteditable]:not([contenteditable="false"]),[role="textbox"],[role="dialog"],[data-dss-highlight-ui]';
470
+ const groups = [], seen = new Set();
471
+ let total = 0, visited = 0, truncated = false;
472
+ // Spend the bounded budget on the clicked message before earlier history.
473
+ for (const scope of [...priorityRoots, root]) {
474
+ if (truncated) break;
475
+ const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
476
+ let node, previousBlock;
477
+ while ((node = walker.nextNode())) {
478
+ if (++visited > 20000) {truncated = true; break;}
479
+ if (node.nodeType === Node.ELEMENT_NODE) {
480
+ if (node.tagName === 'BR' || node.matches(excluded)) previousBlock = null;
481
+ continue;
482
+ }
483
+ if (seen.has(node)) {previousBlock = null; continue;}
484
+ seen.add(node);
485
+ const parent = node.parentElement;
486
+ if (!parent || parent.closest(excluded) || !node.data.length || !parent.getClientRects().length) {previousBlock = null; continue;}
487
+ const style = getComputedStyle(parent);
488
+ if (style.visibility === 'hidden' || style.visibility === 'collapse') {previousBlock = null; continue;}
489
+ const block = parent.closest('p,pre,li,td,th,h1,h2,h3,h4,h5,h6,div,section,article') || parent;
490
+ if (!root.contains(block)) continue;
491
+ if ((previousBlock !== block && groups.length >= 500) || total + node.data.length > 200000) {truncated = true; break;}
492
+ if (previousBlock !== block) {groups.push({text: '', nodes: []}); previousBlock = block;}
493
+ const group = groups[groups.length - 1];
494
+ group.nodes.push({node, start: group.text.length, text: node.data});
495
+ group.text += node.data; total += node.data.length;
496
+ }
497
+ }
498
+ return {blocks: groups, truncated};
499
+ }
500
+ function domHighlightRange(block, start, end, root) {
501
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > block.text.length) return null;
502
+ const first = block.nodes.find(part => part.start + part.text.length > start || start === block.text.length && part.start + part.text.length === start);
503
+ const last = block.nodes.find(part => part.start + part.text.length >= end);
504
+ if (!first || !last || !root.contains(first.node) || !root.contains(last.node)) return null;
505
+ const range = document.createRange();
506
+ range.setStart(first.node, start - first.start); range.setEnd(last.node, end - last.start);
507
+ return range;
508
+ }
509
+ function ConversationHighlights({sessionId, useChat}) {
510
+ const chat = useChat(snapshot => snapshot);
511
+ const chatRef = React.useRef(chat); chatRef.current = chat;
512
+ React.useSyncExternalStore(fn => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
513
+ const root = React.useContext(HighlightRoot);
514
+ const intent = React.useSyncExternalStore(fn => {highlightListeners.add(fn); return () => highlightListeners.delete(fn);}, () => highlightIntent);
515
+ const active = intent?.sessionId === sessionId ? intent : null;
516
+ const [status, setStatus] = React.useState({intent: null, key: 'highlighting'});
517
+ React.useEffect(() => {
518
+ if (!active || !root?.current) return;
519
+ const registry = window.CSS?.highlights;
520
+ if (!registry || typeof window.Highlight !== 'function') {setStatus({intent: active, key: 'highlightUnavailable'}); return;}
521
+ const container = root.current;
522
+ let timer, controller, disposed = false, generation = 0, landed = false, rowLocated = false, userMoved = false;
523
+ const stopJump = () => {userMoved = true;};
524
+ const stopKeyJump = event => {if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(event.key)) stopJump();};
525
+ container.addEventListener('wheel', stopJump, {passive: true});
526
+ container.addEventListener('touchstart', stopJump, {passive: true});
527
+ container.addEventListener('pointerdown', stopJump);
528
+ container.addEventListener('keydown', stopKeyJump);
529
+ const targetRows = () => {
530
+ const keys = new Set(selectedChatNodeKeys(chatRef.current, active.seq));
531
+ // Compatibility adapter, scoped to our own embedded occurrence.
532
+ // Data attributes are not a public navigation API: missing/changed
533
+ // markup degrades to an explicit unavailable/hidden notice, never a
534
+ // guess at a different message.
535
+ return [...container.querySelectorAll('[data-chat-node-key]')].filter(row => keys.has(row.getAttribute('data-chat-node-key')));
536
+ };
537
+ const scrollRange = range => {
538
+ if (landed || userMoved || !range.getClientRects().length) return;
539
+ let viewport = range.startContainer.parentElement, scrolled = false;
540
+ while (viewport && viewport !== container) {
541
+ const style = getComputedStyle(viewport);
542
+ if (/(auto|scroll)/.test(style.overflowY) && viewport.scrollHeight > viewport.clientHeight) {
543
+ // Tool/process bodies can scroll inside the main transcript.
544
+ // Re-read the range rectangle after each inner adjustment.
545
+ const rect = range.getBoundingClientRect(), box = viewport.getBoundingClientRect();
546
+ viewport.scrollTo({top: Math.max(0, viewport.scrollTop + rect.top - box.top - viewport.clientHeight * .35), behavior: 'instant'});
547
+ scrolled = true;
548
+ }
549
+ viewport = viewport.parentElement;
550
+ }
551
+ if (scrolled) landed = true;
552
+ };
553
+ const clearPaint = () => registry.delete('dss-conversation-match');
554
+ // Throttle, rather than trailing debounce: streaming must not postpone
555
+ // painting the settled messages forever. Keep old valid ranges meantime.
556
+ const schedule = () => {
557
+ if (timer || disposed) return;
558
+ timer = setTimeout(() => {timer = null; scan();}, 250);
559
+ };
560
+ async function scan() {
561
+ const current = ++generation;
562
+ controller?.abort(); controller = new AbortController();
563
+ const signal = controller.signal;
564
+ setStatus({intent: active, key: 'highlighting'});
565
+ try {
566
+ const rows = targetRows();
567
+ const visibleRows = rows.filter(row => row.getClientRects().length && getComputedStyle(row).visibility !== 'hidden');
568
+ if (!landed && !userMoved && !rowLocated && visibleRows.length) {
569
+ visibleRows[0].scrollIntoView({block: 'center', behavior: 'instant'});
570
+ rowLocated = true;
571
+ // Let viewport-bound Chat content reveal after the row scroll.
572
+ schedule();
573
+ }
574
+ const snapshot = collectHighlightBlocks(container, visibleRows);
575
+ const response = await fetch(new URL('api/local-session-search-highlight', document.baseURI), {
576
+ method: 'POST', credentials: 'same-origin', cache: 'no-store', signal,
577
+ headers: {'Content-Type': 'application/json'},
578
+ body: JSON.stringify({...active.spec, texts: snapshot.blocks.map(block => block.text)})
579
+ });
580
+ const value = await response.json();
581
+ if (!response.ok) throw new Error(value.error || `HTTP ${response.status}`);
582
+ if (disposed || signal.aborted || current !== generation || highlightIntent !== active) return;
583
+ // A streaming block must not prevent stable messages being painted.
584
+ const valid = snapshot.blocks.map(block => block.nodes.every(part => container.contains(part.node) && part.node.data === part.text));
585
+ if (valid.some(value => !value)) schedule();
586
+ const highlight = new window.Highlight();
587
+ let count = 0, zeroWidth = false, selectedRange = null;
588
+ for (const item of value.items || []) {
589
+ const block = snapshot.blocks[item.index]; if (!block || !valid[item.index]) continue;
590
+ for (const selected of item.ranges || []) {
591
+ if (selected.start === selected.end) {zeroWidth = true; continue;}
592
+ if (count >= 2048) break;
593
+ const range = domHighlightRange(block, selected.start, selected.end, container);
594
+ if (range) {
595
+ highlight.add(range); count++;
596
+ if (!selectedRange && rows.some(row => row.contains(range.startContainer))) selectedRange = range;
597
+ }
598
+ }
599
+ }
600
+ registry.set('dss-conversation-match', highlight);
601
+ if (selectedRange) scrollRange(selectedRange);
602
+ const limited = snapshot.truncated || value.truncated || count >= 2048 || value.items?.some(item => item.rangesTruncated);
603
+ setStatus({intent: active, key: Number.isSafeInteger(active.seq) && !selectedRange && !landed ? 'highlightTargetHidden' : limited ? 'highlightLimited' : zeroWidth ? 'highlightZeroWidth' : count ? 'highlightReady' : 'highlightEmpty', limited});
604
+ } catch (error) {
605
+ if (!disposed && !signal.aborted && current === generation) {clearPaint(); setStatus({intent: active, key: 'highlightFailed', error: error.message});}
606
+ }
607
+ }
608
+ const observer = new MutationObserver(changes => {
609
+ if (changes.some(change => {
610
+ const target = change.target.nodeType === Node.TEXT_NODE ? change.target.parentElement : change.target;
611
+ return target && !target.closest('[data-dss-highlight-ui],style,header,nav,form,button,[contenteditable]:not([contenteditable="false"])');
612
+ })) schedule();
613
+ });
614
+ observer.observe(container, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['hidden', 'open', 'class', 'style']});
615
+ schedule();
616
+ return () => {
617
+ disposed = true; generation++; clearTimeout(timer); controller?.abort(); observer.disconnect(); clearPaint();
618
+ container.removeEventListener('wheel', stopJump); container.removeEventListener('touchstart', stopJump);
619
+ container.removeEventListener('pointerdown', stopJump); container.removeEventListener('keydown', stopKeyJump);
620
+ };
621
+ }, [active, root, sessionId]);
622
+ if (!active) return null;
623
+ const message = status.intent === active ? `${t(status.key)}${status.limited && status.key !== 'highlightLimited' ? ` ${t('highlightLimited')}` : ''}` : t('highlighting');
624
+ return h('div', {'data-dss-highlight-ui': '', className: 'dss-conversation-highlight-control', role: 'status', title: `${message}${status.error ? ` ${status.error}` : ''}`},
625
+ h('span', null, `${t('conversationHighlights')}: ${active.spec.query} — ${message}${status.intent === active && status.error ? ` ${status.error}` : ''}`),
626
+ h('button', {type: 'button', title: t('clearHighlights'), 'aria-label': t('clearHighlights'), onClick: clearHighlights}, '×'));
627
+ }
628
+ function openHighlightedConversation(hit, request) {
629
+ const spec = {query: request.query, matchCase: request.matchCase, wholeWord: request.wholeWord, useRegex: request.useRegex, fuzzy: request.fuzzy};
630
+ const previous = highlightIntent;
631
+ setHighlightIntent({sessionId: hit.sessionId, seq: hit.seq, spec});
632
+ try {ctx.uiWorkspace.openSession(hit.sessionId); ctx.layout.selectPanel(null);} catch (error) {setHighlightIntent(previous); throw error;}
633
+ }
634
+ // Keep pages mounted across view switches; a switch is presentation only.
635
+ // Request keys isolate query/filter changes, and abort/generation guards
636
+ // prevent late replies or pagination from overwriting a newer search.
637
+ function usePaged(request, enabled, revision, delay = 300) {
638
+ const key = JSON.stringify([request, revision]);
639
+ const active = React.useRef({key, enabled}); active.current = {key, enabled};
640
+ const [state, setState] = React.useState({key, page: null, busy: false, error: ''});
641
+ const [retry, setRetry] = React.useState(0);
642
+ const cache = React.useRef(null);
643
+ const current = React.useRef(null);
644
+ const moreControl = React.useRef(null);
645
+ const requestRef = React.useRef(request); requestRef.current = request;
646
+ React.useEffect(() => {
647
+ const controller = new AbortController();
648
+ current.current = controller; moreControl.current?.abort();
649
+ if (cache.current?.key !== key) cache.current = null;
650
+ const cached = cache.current?.page ?? null;
651
+ setState({key, page: cached, busy: enabled && !cached, error: ''});
652
+ if (enabled && !cached) {
653
+ const timer = setTimeout(() => {
654
+ if (controller.signal.aborted || active.current.key !== key || !active.current.enabled) return;
655
+ api(requestRef.current, controller.signal).then(page => {
656
+ if (controller.signal.aborted || active.current.key !== key || !active.current.enabled) return;
657
+ cache.current = {key, page}; setState({key, page, busy: false, error: ''});
658
+ }).catch(err => {
659
+ if (!controller.signal.aborted && active.current.key === key && active.current.enabled) setState({key, page: null, busy: false, error: err.message});
660
+ });
661
+ }, delay);
662
+ return () => {clearTimeout(timer); controller.abort(); moreControl.current?.abort();};
663
+ }
664
+ return () => {controller.abort(); moreControl.current?.abort();};
665
+ }, [key, enabled, retry, delay]);
666
+ const value = enabled && state.key === key ? state : {page: null, busy: enabled, error: ''};
667
+ async function more() {
668
+ if (!enabled || active.current.key !== key || !active.current.enabled || value.busy || moreControl.current && !moreControl.current.signal.aborted || !value.page?.nextCursor) return;
669
+ const controller = new AbortController(); moreControl.current = controller;
670
+ const owner = current.current;
671
+ setState(old => ({...old, busy: true, error: ''}));
672
+ try {
673
+ const next = await api({...request, cursor: value.page.nextCursor}, controller.signal);
674
+ if (controller.signal.aborted || owner !== current.current || active.current.key !== key || !active.current.enabled) return;
675
+ const identity = item => `${item.sessionId}:${item.seq ?? 'group'}`;
676
+ const seen = new Set(value.page.items.map(identity));
677
+ const page = {...next, items: [...value.page.items, ...next.items.filter(item => !seen.has(identity(item)))]};
678
+ cache.current = {key, page}; setState({key, page, busy: false, error: ''});
679
+ } catch (err) {
680
+ if (!controller.signal.aborted && owner === current.current && active.current.key === key && active.current.enabled) setState(old => ({...old, busy: false, error: `${err.message} — ${t('stale')}`}));
681
+ } finally {if (moreControl.current === controller) moreControl.current = null;}
682
+ }
683
+ return {...value, more, refresh: () => {cache.current = null; setRetry(v => v + 1);}};
684
+ }
685
+ function FuzzyNotice({page, busy, error}) {
686
+ // This is scope-wide Host metadata, not a guess from the loaded snippets.
687
+ // Never claim absence while loading, on failure, or with unreadable sessions.
688
+ if (busy || error || !page || !['typo', 'subsequence'].includes(page.fuzzy) ||
689
+ page.hasExactMatches !== false || !page.items.length || page.warnings?.length) return null;
690
+ return h('p', {className: 'dss-fuzzy-notice', role: 'status'}, t('fuzzyOnly'));
691
+ }
692
+ function WorkspaceLabel({hit}) {
693
+ const name = hit.workspaceId === '__ungrouped__' ? t('ungroupedWorkspace') : hit.workspaceTitle || hit.workspacePath || hit.workspaceId || t('ungroupedWorkspace');
694
+ return h('span', {className: 'dss-badge dss-workspace-badge', title: `${t('workspace')}: ${hit.workspacePath || name}`}, h(Glyph, {kind: 'folder', size: 11}), name);
695
+ }
696
+ function Badges({hit}) {
697
+ return h(React.Fragment, null,
698
+ hit.subagent && h('span', {className: 'dss-badge'}, h(BranchIcon), t('subagent')),
699
+ hit.archived && h('span', {className: 'dss-badge'}, t('archived')));
700
+ }
701
+ function EmptyState({empty = false, pending = false}) {
702
+ return h('div', {className: 'dss-message'}, h(Icon, {size: 25}),
703
+ h('h3', null, t(pending ? 'pendingTitle' : empty ? 'emptyTitle' : 'readyTitle')),
704
+ h('p', null, t(pending ? 'pending' : empty ? 'empty' : 'start')));
705
+ }
706
+ function ResultCard({hit, request, within, grouped = false, showWorkspace = false, fallbackTitle}) {
707
+ return h('article', {className: 'dss-hit'},
708
+ !grouped && h('div', {className: 'dss-hit-heading'}, h('h2', null, hit.title || fallbackTitle || t('untitled')),
709
+ showWorkspace && h(WorkspaceLabel, {hit}), h(Badges, {hit})),
710
+ h('div', {className: 'dss-meta dss-muted'}, h('span', {className: 'dss-event-type'}, hit.type), h('span', null, `${t('event')} #${hit.seq}`),
711
+ hit.time !== undefined && h('time', {dateTime: new Date(hit.time).toISOString()}, new Date(hit.time).toLocaleString()),
712
+ !grouped && h('span', {className: 'dss-id', title: hit.sessionId}, shortId(hit.sessionId))),
713
+ h('pre', {className: 'dss-snippet'}, h(Highlight, {text: hit.snippet, ranges: hit.ranges})),
714
+ h('div', {className: 'dss-actions'},
715
+ h('button', {type: 'button', disabled: hit.archived, title: hit.archived ? t('archivedHint') : t('open'), onClick: () => openHighlightedConversation(hit, request)}, t('open'), h(Glyph, {kind: 'arrow', size: 13})),
716
+ within && h('button', {type: 'button', className: 'dss-primary', onClick: () => within(hit.sessionId)}, t('within'))));
717
+ }
718
+ function SessionGroup({group, request, enabled, revision, within, delay}) {
719
+ const [expanded, setExpanded] = React.useState(false);
720
+ const bodyId = React.useId();
721
+ // Narrow with the same plural scope contract, preserving frozen time bounds.
722
+ const result = usePaged({...request, action: 'search', sessionIds: [group.sessionId]}, enabled && expanded, revision, delay);
723
+ const changed = result.page && result.page.total !== group.count;
724
+ return h('section', {className: 'dss-group'},
725
+ h('h2', null, h('button', {type: 'button', className: 'dss-group-toggle', 'aria-expanded': expanded, 'aria-controls': bodyId, onClick: () => setExpanded(v => !v)},
726
+ h('svg', {className: 'dss-chevron', width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true}, h('path', {d: 'm6 3 5 5-5 5'})),
727
+ h('span', {className: 'dss-group-title'}, group.title || t('untitled')),
728
+ h('span', {className: 'dss-group-count'}, `${group.count} · ${t('matches')}`))),
729
+ h('div', {className: 'dss-group-meta dss-muted'}, request.workspaceIds.length !== 1 && h(WorkspaceLabel, {hit: group}), h(Badges, {hit: group}),
730
+ h('span', {className: 'dss-id', title: group.sessionId}, shortId(group.sessionId)),
731
+ group.time !== undefined && h('time', {dateTime: new Date(group.time).toISOString()}, new Date(group.time).toLocaleString())),
732
+ h('div', {id: bodyId, hidden: !expanded, className: 'dss-group-body', 'aria-busy': result.busy},
733
+ result.error && h('div', {className: 'dss-error', role: 'alert'}, result.error, ' ', h('button', {type: 'button', onClick: result.refresh}, t('retry'))),
734
+ changed && h('div', {className: 'dss-error', role: 'status'}, t('groupChanged')),
735
+ result.page?.warnings?.length > 0 && h('p', {className: 'dss-error', role: 'status'}, t('partial')),
736
+ result.busy && !result.page && h('p', {className: 'dss-message', role: 'status'}, t('loading')),
737
+ result.page?.items.map(hit => h(ResultCard, {key: `${hit.sessionId}:${hit.seq}`, hit, request, within, grouped: true})),
738
+ result.page && h('p', {className: 'dss-muted dss-group-progress'}, `${t('loadedMatches')}: ${result.page.items.length} / ${result.page.total}`),
739
+ result.page?.nextCursor && h('button', {type: 'button', className: 'dss-more', disabled: result.busy, onClick: result.more}, result.busy ? t('loading') : t('more'))));
740
+ }
741
+ function SessionGroups({request, enabled, revision, within, delay}) {
742
+ const result = usePaged({...request, action: 'groups'}, enabled && Boolean(request.query.trim()), revision, delay);
743
+ const key = JSON.stringify([request, revision]);
744
+ return h('div', {hidden: !enabled},
745
+ h('div', {className: 'dss-note dss-muted'}, h('span', {title: t('treeHint')}, t('bySession')),
746
+ result.page && h('span', {className: 'dss-result-count'}, `${result.page.items.length} / ${result.page.total} ${t('sessions')} · ${result.page.totalMatches} ${t('matches')}`)),
747
+ result.error && h('div', {className: 'dss-error', role: 'alert'}, result.error, ' ', h('button', {type: 'button', onClick: result.refresh}, t('retry'))),
748
+ result.page?.warnings?.length > 0 && h('p', {className: 'dss-error', role: 'status'}, `${t('partial')} (${result.page.warnings.length})`),
749
+ h('div', {'aria-live': 'polite', 'aria-busy': result.busy},
750
+ !request.query.trim() ? h(EmptyState) : result.busy && !result.page ? h('div', {className: 'dss-message', role: 'status'}, t('loading')) : result.page?.items.length === 0 ? h(EmptyState, {empty: true}) : null,
751
+ h(FuzzyNotice, result),
752
+ result.page?.items.map(group => h(SessionGroup, {key: `${key}:${group.sessionId}`, group, request, enabled, revision, within, delay})),
753
+ result.page?.nextCursor && h('button', {type: 'button', className: 'dss-more', disabled: result.busy, onClick: result.more}, result.busy ? t('loading') : t('moreSessions'))));
754
+ }
755
+ function SearchPage() {
756
+ React.useSyncExternalStore(fn => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
757
+ const [query, setQuery] = React.useState(stored.query);
758
+ const [sessionIds, setSessionIds] = React.useState(stored.sessionIds);
759
+ const [workspaceIds, setWorkspaceIds] = React.useState(stored.workspaceIds);
760
+ const [workspaces, setWorkspaces] = React.useState([]);
761
+ const [includeSubagents, setIncludeSubagents] = React.useState(stored.includeSubagents);
762
+ const [includeArchived, setIncludeArchived] = React.useState(stored.includeArchived);
763
+ const [finalOnly, setFinalOnly] = React.useState(stored.finalOnly);
764
+ const [order, setOrder] = React.useState(stored.order);
765
+ const [matchCase, setMatchCase] = React.useState(stored.matchCase);
766
+ const [wholeWord, setWholeWord] = React.useState(stored.wholeWord);
767
+ const [useRegex, setUseRegex] = React.useState(stored.useRegex);
768
+ const [fuzzy, setFuzzy] = React.useState(stored.fuzzy);
769
+ const [view, setView] = React.useState(stored.view);
770
+ const tree = sessionIds.length !== 1 && view === 'session';
771
+ const content = finalOnly ? 'final' : 'all';
772
+ const [timePreset, setTimePreset] = React.useState(stored.timePreset);
773
+ const [startDate, setStartDate] = React.useState(stored.startDate);
774
+ const [endDate, setEndDate] = React.useState(stored.endDate);
775
+ const [settings, setSettings] = React.useState({mode: null, error: '', revision: 0});
776
+ const [settingsRetry, setSettingsRetry] = React.useState(0);
777
+ const [submitted, setSubmitted] = React.useState(null);
778
+ const markRoot = useHighlightContrast();
779
+ const [catalog, setCatalog] = React.useState([]);
780
+ const [catalogState, setCatalogState] = React.useState('loading');
781
+ const [loadedCatalogScope, setLoadedCatalogScope] = React.useState(null);
782
+ const [catalogError, setCatalogError] = React.useState('');
783
+ const [selectionError, setSelectionError] = React.useState('');
784
+ const [catalogVersion, setCatalogVersion] = React.useState(0);
785
+ const [version, setVersion] = React.useState(0);
786
+ // Refreshing choices alone must not disable/restart a submitted search.
787
+ // A genuinely different scope still waits for catalog reconciliation.
788
+ const catalogScopeKey = JSON.stringify([workspaceIds, includeSubagents, includeArchived]);
789
+ const catalogReady = loadedCatalogScope === catalogScopeKey;
790
+ const draft = {query, workspaceIds, sessionIds, includeSubagents, includeArchived, content, order, matchCase, wholeWord, useRegex, fuzzy, timePreset, startDate, endDate};
791
+ const draftKey = JSON.stringify(draft);
792
+ // Clock reads occur only when the draft changes or an explicit search is
793
+ // submitted. Pagination and presentation-only renders reuse this value.
794
+ const resolved = React.useMemo(() => timeBounds(timePreset, startDate, endDate, Date.now()), [draftKey, version, settings.revision]);
795
+ const makeRequest = bounds => ({query, workspaceIds: [...workspaceIds], sessionIds: [...sessionIds], includeSubagents, includeArchived, content, order, matchCase, wholeWord, useRegex, fuzzy, ...bounds});
796
+ const liveRequest = React.useMemo(() => makeRequest(resolved || {}), [draftKey, resolved]);
797
+ // Once a draft is edited, returning to old text must not silently run
798
+ // that old submission again; only Enter/Search re-arms submit mode.
799
+ React.useEffect(() => {setSubmitted(old => old?.draftKey === draftKey ? old : null);}, [draftKey]);
800
+ const currentSubmission = submitted?.draftKey === draftKey && submitted?.settingsRevision === settings.revision;
801
+ const request = currentSubmission ? submitted.request : liveRequest;
802
+ const pendingChanges = settings.mode === 'submit' && Boolean(query.trim()) && !currentSubmission;
803
+ const enabled = Boolean(settings.mode && !settings.error && resolved && query.trim() && catalogReady && !selectionError && (settings.mode === 'live' || currentSubmission));
804
+ const revision = `${settings.revision}:${version}`;
805
+ const delay = settings.mode === 'live' ? 300 : 0;
806
+ const timeline = usePaged(request, enabled && !tree, revision, delay);
807
+ const {page, error, busy, more} = timeline;
808
+ const input = React.useRef(null);
809
+ const [navigationError, setNavigationError] = React.useState(false);
810
+ const openSettings = () => {
811
+ try {setNavigationError(!openPluginSettings(ctx));}
812
+ catch {setNavigationError(true);}
813
+ };
814
+ const setText = value => {stored.query = value; setQuery(value); if (!value.trim()) {setSubmitted(null); setSelectionError(''); setVersion(v => v + 1);}};
815
+ const setTarget = values => {
816
+ // Validate the raw selection; never silently truncate Select all.
817
+ if (values.length > 1000) {setSelectionError('sessionLimit'); return;}
818
+ setSelectionError(''); stored.sessionIds = values; setSessionIds(values);
819
+ };
820
+ const submit = () => {
821
+ if (!settings.mode || settings.error || selectionError || !catalogReady || !query.trim()) return;
822
+ const bounds = timeBounds(timePreset, startDate, endDate, Date.now());
823
+ if (!bounds) return;
824
+ setSubmitted({draftKey, settingsRevision: settings.revision, request: makeRequest(bounds)});
825
+ setVersion(v => v + 1);
826
+ };
827
+ React.useEffect(() => {
828
+ let controller;
829
+ let active = true;
830
+ const adopt = mode => {
831
+ if (!active) return;
832
+ // An unchanged focus revalidation must preserve the submitted
833
+ // snapshot, relative-time bounds and pagination cache.
834
+ setSettings(old => old.mode === mode && !old.error ? old : {mode, error: '', revision: old.mode === mode ? old.revision : old.revision + 1});
835
+ };
836
+ const revalidate = () => {
837
+ controller?.abort(); controller = new AbortController();
838
+ const owner = controller, epoch = settingsEpoch;
839
+ settingsApi('GET', undefined, owner.signal).then(value => {
840
+ if (active && !owner.signal.aborted && settingsEpoch === epoch) adopt(value.searchMode);
841
+ }).catch(err => {
842
+ if (active && !owner.signal.aborted && settingsEpoch === epoch) setSettings(old => ({...old, error: err.message}));
843
+ });
844
+ };
845
+ const localChange = mode => {
846
+ controller?.abort();
847
+ setSubmitted(null);
848
+ setSettings(old => ({mode, error: '', revision: old.revision + 1}));
849
+ };
850
+ settingListeners.add(localChange);
851
+ window.addEventListener('focus', revalidate);
852
+ revalidate();
853
+ return () => {active = false; controller?.abort(); settingListeners.delete(localChange); window.removeEventListener('focus', revalidate);};
854
+ }, [settingsRetry]);
855
+ const setFuzzyMode = value => {
856
+ stored.fuzzy = value; setFuzzy(value);
857
+ if (value !== 'off') {stored.useRegex = false; setUseRegex(false);}
858
+ };
859
+ const setRegexMode = enabled => {
860
+ stored.useRegex = enabled; setUseRegex(enabled);
861
+ if (enabled) {stored.fuzzy = 'off'; setFuzzy('off');}
862
+ };
863
+ const setWorkspace = values => {
864
+ if (values.length > 200) {setSelectionError('workspaceLimit'); return;}
865
+ if (JSON.stringify(values) === JSON.stringify(workspaceIds)) {setSelectionError(''); return;}
866
+ stored.workspaceIds = values; setWorkspaceIds(values);
867
+ setTarget([]); setCatalog([]); setCatalogState('loading');
868
+ };
869
+ const setSubagents = enabled => {
870
+ stored.includeSubagents = enabled; setIncludeSubagents(enabled);
871
+ // Turning the scope off must not leave a hidden subagent selected.
872
+ if (!enabled) setTarget(sessionIds.filter(id => catalog.some(item => item.sessionId === id && !item.subagent)));
873
+ };
874
+ const setArchives = enabled => {
875
+ stored.includeArchived = enabled; setIncludeArchived(enabled);
876
+ if (!enabled) setTarget(sessionIds.filter(id => !catalog.find(item => item.sessionId === id)?.archived));
877
+ };
878
+ React.useEffect(() => {
879
+ const refocus = () => {input.current?.focus(); input.current?.select();};
880
+ focusListeners.add(refocus); refocus();
881
+ return () => focusListeners.delete(refocus);
882
+ }, []);
883
+ React.useEffect(() => {
884
+ let active = true;
885
+ const controller = new AbortController();
886
+ setCatalogState('loading'); setCatalogError('');
887
+ const load = async () => {
888
+ let value;
889
+ try {value = await api({action: 'sessions', workspaceIds, includeSubagents, includeArchived}, controller.signal);}
890
+ catch (err) {
891
+ if (controller.signal.aborted || !workspaceIds.length) throw err;
892
+ // A deleted workspace makes the scoped catalog invalid. Read
893
+ // the full catalog only to recover its current selection IDs.
894
+ value = await api({action: 'sessions', workspaceIds: [], includeSubagents, includeArchived}, controller.signal);
895
+ if (workspaceIds.every(id => value.workspaces.some(item => item.workspaceId === id))) throw err;
896
+ }
897
+ if (!active || controller.signal.aborted) return;
898
+ setWorkspaces(value.workspaces || []);
899
+ const knownWorkspaces = new Set(value.workspaces.map(item => item.workspaceId));
900
+ const remainingWorkspaces = workspaceIds.filter(id => knownWorkspaces.has(id));
901
+ if (remainingWorkspaces.length !== workspaceIds.length) {
902
+ stored.workspaceIds = remainingWorkspaces; setWorkspaceIds(remainingWorkspaces);
903
+ setTarget([]); setCatalog([]);
904
+ return; // Re-fetch using the reconciled plural workspace scope.
905
+ }
906
+ const knownSessions = new Set(value.items.map(item => item.sessionId));
907
+ const remainingSessions = stored.sessionIds.filter(id => knownSessions.has(id));
908
+ if (remainingSessions.length !== stored.sessionIds.length) setTarget(remainingSessions);
909
+ setCatalog(value.items); setCatalogState('ready'); setLoadedCatalogScope(catalogScopeKey);
910
+ };
911
+ load().catch(err => {if (active && !controller.signal.aborted) {setCatalogError(err.message); setCatalogState('error');}});
912
+ return () => {active = false; controller.abort();};
913
+ }, [catalogVersion, JSON.stringify(workspaceIds), includeSubagents, includeArchived]);
914
+ const within = sessionId => {
915
+ if (!enabled) return;
916
+ const bounds = timeBounds(timePreset, startDate, endDate, Date.now());
917
+ if (!bounds) return;
918
+ setTarget([sessionId]);
919
+ const nextDraft = {...draft, sessionIds: [sessionId]};
920
+ setSubmitted({draftKey: JSON.stringify(nextDraft), settingsRevision: settings.revision, request: {...makeRequest(bounds), sessionIds: [sessionId]}});
921
+ setVersion(v => v + 1);
922
+ };
923
+ const selected = sessionIds.length === 1 ? catalog.find(item => item.sessionId === sessionIds[0]) : null;
924
+ const workspaceName = item => item.ungrouped || item.workspaceId === '__ungrouped__' ? t('ungroupedWorkspace') : item.title || item.path || item.workspaceId;
925
+ const visible = catalog.filter(item => (!workspaceIds.length || workspaceIds.includes(item.workspaceId)) && (includeSubagents || !item.subagent) && (includeArchived || !item.archived));
926
+ const options = visible.map(item => ({id: item.sessionId, title: `${item.sessionId}${item.workspacePath ? ` · ${item.workspacePath}` : ''}`, label: `${item.title || t('untitled')}${item.subagent ? ` · ${t('subagent')}` : ''}${item.archived ? ` · ${t('archived')}` : ''}${workspaceIds.length !== 1 ? ` · ${item.workspaceId === '__ungrouped__' ? t('ungroupedWorkspace') : item.workspaceTitle || item.workspacePath || ''}` : ''} · ${shortId(item.sessionId)}`}));
927
+ return h('section', {ref: markRoot, className: 'dss-page', 'aria-label': t('title'), onKeyDown: e => {
928
+ if (e.key === 'Escape' && e.target.tagName !== 'SELECT') {e.preventDefault(); ctx.layout.selectPanel(null);}
929
+ }}, h('style', null, css),
930
+ h('header', {className: 'dss-head'},
931
+ h('div', {className: 'dss-brand'}, h('span', {className: 'dss-emblem'}, h(Icon, {size: 22})),
932
+ h('div', null, h('h1', null, t('title')), h('p', {className: 'dss-muted'}, t('intro')))),
933
+ h('nav', {className: 'dss-head-actions', 'aria-label': t('navigation')}, h('kbd', {className: 'dss-shortcut'}, t('shortcut')),
934
+ h('button', {type: 'button', title: t('openSettings'), 'aria-label': t('openSettings'), onClick: openSettings}, h(Glyph, {kind: 'settings', size: 16}), t('settings')),
935
+ h('button', {className: 'dss-icon-button', type: 'button', title: t('close'), 'aria-label': t('close'), onClick: () => ctx.layout.selectPanel(null)}, h(Glyph, {kind: 'back', size: 19})))),
936
+ h('div', {className: 'dss-body'}, h('div', {className: 'dss-inner'},
937
+ navigationError && h('p', {className: 'dss-error', role: 'alert'}, t('settingsUnavailable')),
938
+ h('section', {className: 'dss-controls', 'aria-label': t('filters')},
939
+ h('form', {className: 'dss-form', onSubmit: e => {e.preventDefault(); if (!e.nativeEvent?.isComposing) submit();}},
940
+ h('div', {className: 'dss-searchbox'}, h(Icon, {size: 18}),
941
+ h('input', {ref: input, className: 'dss-query', type: 'search', value: query, maxLength: 1024, placeholder: t('placeholder'), 'aria-label': t('placeholder'), onKeyDown: e => {if (e.key === 'Enter' && (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229)) e.preventDefault();}, onChange: e => setText(e.target.value)}),
942
+ query && h('button', {className: 'dss-icon-button dss-clear', type: 'button', title: t('clear'), 'aria-label': t('clear'), onClick: () => {setText(''); input.current?.focus();}}, '×'),
943
+ h('div', {className: 'dss-modes', role: 'group', 'aria-label': t('searchModes')},
944
+ ...[
945
+ ['matchCase', 'Aa', matchCase, setMatchCase],
946
+ ['wholeWord', 'ab', wholeWord, setWholeWord],
947
+ ['useRegex', '.*', useRegex, setRegexMode]
948
+ ].map(([name, label, enabled, setEnabled]) => h('button', {key: name, type: 'button', className: `dss-mode${name === 'wholeWord' ? ' dss-mode-word' : ''}`, title: t(name), 'aria-label': t(name), 'aria-pressed': enabled, onClick: () => {stored[name] = !enabled; setEnabled(!enabled);}}, label)))),
949
+ h('button', {className: 'dss-primary dss-submit', disabled: !query.trim() || !settings.mode || Boolean(settings.error) || !resolved || Boolean(selectionError) || !catalogReady, type: 'submit'}, t('search'), h(Glyph, {kind: 'arrow'}))),
950
+ h('div', {className: 'dss-filter-grid'},
951
+ h('div', {className: 'dss-field'}, h('span', {className: 'dss-field-label'}, t('workspace')),
952
+ h(MultiPicker, {label: t('workspace'), allLabel: t('allWorkspaces'), values: workspaceIds, hint: t('workspaceHint'), options: workspaces.map(item => ({id: item.workspaceId, label: workspaceName(item), title: item.path})), onChange: setWorkspace})),
953
+ h('div', {className: 'dss-field dss-session-field'}, h('span', {className: 'dss-field-label'}, t('session')),
954
+ h(MultiPicker, {label: t('session'), allLabel: t('all'), values: sessionIds, hint: t('pickerHint'), options, onChange: setTarget, disabled: !catalogReady}))),
955
+ h('div', {className: 'dss-filter-grid dss-time-grid'},
956
+ h('div', {className: 'dss-field'}, h('label', {htmlFor: 'dss-time'}, t('timeRange')),
957
+ h('select', {id: 'dss-time', value: timePreset, 'aria-describedby': 'dss-time-hint', onChange: e => {stored.timePreset = e.target.value; setTimePreset(e.target.value);}},
958
+ ...[['all', 'allTime'], ['today', 'today'], ['24h', 'last24h'], ['7d', 'last7d'], ['month', 'thisMonth'], ['custom', 'custom']].map(([value, label]) => h('option', {key: value, value}, t(label))))),
959
+ timePreset === 'custom' && h('div', {className: 'dss-field'}, h('label', {htmlFor: 'dss-start-date'}, t('startDate')),
960
+ h('input', {id: 'dss-start-date', type: 'date', value: startDate, 'aria-invalid': !resolved, onChange: e => {stored.startDate = e.target.value; setStartDate(e.target.value);}})),
961
+ timePreset === 'custom' && h('div', {className: 'dss-field'}, h('label', {htmlFor: 'dss-end-date'}, t('endDate')),
962
+ h('input', {id: 'dss-end-date', type: 'date', value: endDate, 'aria-invalid': !resolved, onChange: e => {stored.endDate = e.target.value; setEndDate(e.target.value);}}))),
963
+ h('p', {className: 'dss-muted', id: 'dss-time-hint'}, t('timeHint')),
964
+ !resolved && h('p', {className: 'dss-error', role: 'alert'}, t('timeError')),
965
+ !settings.mode && !settings.error && h('p', {className: 'dss-muted', role: 'status'}, t('settingsLoading')),
966
+ settings.error && h('div', {className: 'dss-error', role: 'alert'}, t('settingsError'), ' ', settings.error, ' ', h('button', {type: 'button', onClick: () => setSettingsRetry(v => v + 1)}, t('retry'))),
967
+ pendingChanges && h('p', {className: 'dss-pending', role: 'status'}, t('pendingChanges')),
968
+ selectionError && h('p', {className: 'dss-error', role: 'alert'}, t(selectionError)),
969
+ h('div', {className: 'dss-match-row'}, h('label', {htmlFor: 'dss-fuzzy'}, t('fuzzy')),
970
+ h('select', {id: 'dss-fuzzy', value: fuzzy, 'aria-describedby': 'dss-fuzzy-hint', onChange: e => setFuzzyMode(e.target.value)},
971
+ ...[['off', 'fuzzyOff'], ['typo', 'fuzzyTypo'], ['subsequence', 'fuzzySubsequence']].map(([value, label]) => h('option', {key: value, value}, t(label)))),
972
+ fuzzy !== 'off' && h('span', {className: 'dss-muted'}, t(fuzzy === 'typo' ? 'typoExample' : 'subsequenceExample'))),
973
+ h('div', {className: 'dss-options'},
974
+ h('label', {className: 'dss-check', title: t('finalHint')}, h('input', {type: 'checkbox', checked: finalOnly, onChange: e => {stored.finalOnly = e.target.checked; setFinalOnly(e.target.checked);}}), t('finalOnly')),
975
+ h('label', {className: 'dss-check'}, h('input', {type: 'checkbox', checked: includeSubagents, onChange: e => setSubagents(e.target.checked)}), t('includeSubagents')),
976
+ h('label', {className: 'dss-check'}, h('input', {type: 'checkbox', checked: includeArchived, onChange: e => setArchives(e.target.checked)}), t('includeArchived')),
977
+ h('button', {className: 'dss-refresh', type: 'button', onClick: () => setCatalogVersion(v => v + 1)}, h(Glyph, {kind: 'refresh'}), t('refresh'))),
978
+ h('details', {className: 'dss-tips'}, h('summary', null, t('tips')),
979
+ h('div', {className: 'dss-tip-body'},
980
+ h('p', {id: 'dss-fuzzy-hint'}, h('strong', null, `${t('fuzzy')}. `), t(fuzzy === 'typo' ? 'fuzzyTypoHint' : fuzzy === 'subsequence' ? 'fuzzySubsequenceHint' : 'fuzzyOffHint')),
981
+ h('p', null, t('workspaceHint')), h('p', null, t('pickerHint')), h('p', null, t('finalHint')), h('p', null, t('matching')))),
982
+ useRegex && h('p', {className: 'dss-muted'}, t('regexHint')),
983
+ catalogState === 'loading' && h('p', {className: 'dss-muted', role: 'status'}, t('loadingSessions')),
984
+ catalogState === 'error' && h('div', {className: 'dss-error', role: 'alert'}, t('catalogError'), ' ', catalogError, ' ', h('button', {type: 'button', onClick: () => setCatalogVersion(v => v + 1)}, t('retry')))),
985
+ h('hr', {className: 'dss-divider'}),
986
+ h('div', {className: 'dss-results-toolbar'}, h('h2', {className: 'dss-results-title'}, t('results')),
987
+ h('div', {className: 'dss-display-options'},
988
+ sessionIds.length !== 1 && h('div', {className: 'dss-views', role: 'group', 'aria-label': t('view')},
989
+ ...[['timeline', 'timeline'], ['session', 'bySession']].map(([value, label]) => h('button', {key: value, type: 'button', className: 'dss-view', 'aria-pressed': view === value, onClick: () => {stored.view = value; setView(value);}}, h(Glyph, {kind: value === 'timeline' ? 'timeline' : 'folder', size: 13}), t(label)))),
990
+ h('div', {className: 'dss-views dss-sort', role: 'group', 'aria-label': t('sort')},
991
+ ...['newest', 'oldest'].map(value => h('button', {key: value, type: 'button', className: 'dss-view', 'aria-pressed': order === value, onClick: () => {stored.order = value; setOrder(value);}}, t(value)))))),
992
+ tree && !enabled && !query.trim() && h(EmptyState),
993
+ h(SessionGroups, {request, enabled: enabled && tree, revision, within, delay}),
994
+ h('div', {hidden: tree},
995
+ h('div', {className: 'dss-note dss-muted'}, h('span', {title: sessionIds.length === 1 ? t('events') : t('grouped')}, selected?.title || (sessionIds.length === 1 ? t('unavailable') : t('resultsHint'))), page && h('span', {className: 'dss-result-count'}, `${page.items.length}${Number.isInteger(page.total) ? ` / ${page.total}` : page.nextCursor ? '+' : ''} · ${t('results')}`)),
996
+ error && h('div', {className: 'dss-error', role: 'alert'}, h('p', null, error), h('button', {type: 'button', onClick: () => setVersion(v => v + 1)}, t('retry'))),
997
+ page?.warnings?.length > 0 && h('div', {className: 'dss-error', role: 'status'}, `${t('partial')} (${page.warnings.length})`),
998
+ h('div', {'aria-live': 'polite', 'aria-busy': busy},
999
+ busy && !page ? h('div', {className: 'dss-message', role: 'status'}, t('loading')) : !query.trim() ? h(EmptyState) : page?.items.length === 0 ? h(EmptyState, {empty: true, pending: Boolean(page.nextCursor)}) : null,
1000
+ h(FuzzyNotice, {page, busy, error}),
1001
+ page?.items.map(hit => h(ResultCard, {key: `${hit.sessionId}:${hit.seq}`, hit, request, fallbackTitle: selected?.title, showWorkspace: workspaceIds.length !== 1, within: sessionIds.length !== 1 ? within : undefined})),
1002
+ page?.nextCursor && h('button', {className: 'dss-more', type: 'button', disabled: busy, onClick: more}, busy ? t('loading') : t('more'))))
1003
+ )));
1004
+ }
1005
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({name: 'sidebar.panellist', id: PANEL, order: -10, label: () => t('title')}, Icon));
1006
+ ctx.slots.inject('main', () => ctx.slots.register({name: 'main', key: PANEL}, SearchPage));
1007
+ // Highlight shell registration exists only for a live highlight intent;
1008
+ // clearing it restores the untouched resident Conversation entry.
1009
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({name: 'plugins.bundle.config', key: '@lizimin/dsh-session-search', locale: NS}, SettingsForm));
1010
+ }
1011
+ };
1012
+ }
1013
+ });