dsh-context-graph 0.6.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,880 @@
1
+ // The browser side of dsh-context-graph, hand-written in dsh's client-bundle format (no build step).
2
+ // The shell loads this file as a plain script; `require` reaches only the shell's shared modules.
3
+ // Three contributions:
4
+ // - the chat card for `/context-graph`: dsh's own DisclosureRow, a one-line summary that opens
5
+ // to the details;
6
+ // - the plugin's page in Plugins (`plugins.bundle.config`, #35): what memory saved and cost in
7
+ // each workspace;
8
+ // - Memory tree, an entry of its own in the sidebar's panel list with a page in the main column
9
+ // (#85): what the memory holds. Data comes from the host's owner-only routes (src/host/page.js).
10
+ window.__ModuleLoader__.load({
11
+ id: 'dsh-context-graph',
12
+ factory: (require) => {
13
+ var module = { exports: {} }
14
+ var exports = module.exports
15
+ const React = require('react')
16
+ const { useState } = React
17
+ const { jsx, jsxs } = require('react/jsx-runtime')
18
+ const { DisclosureRow } = require('@deepseek-ai/dsh-client-ui-primitives')
19
+
20
+ const NAMESPACE = 'dsh-context-graph'
21
+ const en = {
22
+ stats: 'Context graph',
23
+ on: 'Memory on',
24
+ off: 'Memory off',
25
+ share: 'Share with workspace',
26
+ unshare: 'Stop sharing',
27
+ build: 'Index this chat',
28
+ map: 'Memory map',
29
+ find: 'Find topics',
30
+ running: 'Working…',
31
+ failed: 'Failed',
32
+ pageIntro: 'What memory saved and cost in each workspace. Numbers marked as estimates follow the rule shown under them.',
33
+ treeHint: 'What the memory holds is drawn as a tree: Memory tree in the left sidebar.',
34
+ panel: 'Memory tree',
35
+ treeIntro: 'Each workspace\'s memory: its chats, their topics, and the messages each topic came from.',
36
+ loading: 'Loading…',
37
+ loadFailed: 'Could not read the memory. Try again in a moment.',
38
+ retry: 'Retry',
39
+ noWorkspaces: 'No memory yet. Chats index themselves every 4 turns; /context-graph build indexes one now.',
40
+ chats: 'chats',
41
+ topics: 'topics',
42
+ saved: 'Saved (estimate)',
43
+ cost: 'Memory cost',
44
+ net: 'Net',
45
+ savingsRule: 'Saved: for each topic the model used (it recalled it, or its answer says two of the topic\'s words your message did not), its newest messages as stored, each counted once per chat. Cost: notes and recalls sent, their cached re-sends (x0.1), the recall tool, and indexing (output x4). In input tokens.',
46
+ topicFailed: 'Could not read this topic.',
47
+ savingsUnavailable: 'Savings: unavailable for now (the ledger could not be read).',
48
+ search: 'Search topics',
49
+ allKinds: 'All',
50
+ zoomIn: 'Zoom in',
51
+ zoomOut: 'Zoom out',
52
+ resetView: 'Reset view',
53
+ tree_label: 'The memory as a tree: the workspace, its chats, their topics',
54
+ close: 'Close',
55
+ copyId: 'Copy id',
56
+ copied: 'Copied',
57
+ fromChat: 'From chat',
58
+ links: 'Linked topics',
59
+ sources: 'Source messages',
60
+ private: 'private',
61
+ memoryOff: 'memory off',
62
+ more: 'more not drawn',
63
+ decision: 'Decision',
64
+ fact: 'Fact',
65
+ task: 'Task',
66
+ artifact: 'Artifact',
67
+ 'open-question': 'Open question'
68
+ }
69
+ const zh = {
70
+ stats: '上下文图谱',
71
+ on: '开启记忆',
72
+ off: '关闭记忆',
73
+ share: '共享到工作区',
74
+ unshare: '取消共享',
75
+ build: '索引当前对话',
76
+ map: '记忆地图',
77
+ find: '查找主题',
78
+ running: '处理中…',
79
+ failed: '失败',
80
+ pageIntro: '每个工作区里记忆节省和花费了多少。标为估算的数字按下面写明的规则计算。',
81
+ treeHint: '记忆里有什么画成了一棵树:左侧边栏的“记忆树”。',
82
+ panel: '记忆树',
83
+ treeIntro: '每个工作区的记忆:它的对话、对话里的主题,以及每个主题来自哪些消息。',
84
+ loading: '正在读取…',
85
+ loadFailed: '无法读取记忆,请稍后再试。',
86
+ retry: '重试',
87
+ noWorkspaces: '还没有记忆。对话每 4 轮会自动索引;/context-graph build 可以立即索引当前对话。',
88
+ chats: '个对话',
89
+ topics: '个主题',
90
+ saved: '节省(估算)',
91
+ cost: '记忆开销',
92
+ net: '净值',
93
+ savingsRule: '节省:模型用到的每个主题(被取回,或回答里出现了它的两个词而你的消息里没有)最新的几条消息,按保存的长度计,同一条消息在一个对话里只算一次。开销:发送的笔记和取回内容、它们作为缓存再次发送的部分(×0.1)、recall 工具、以及索引(输出 ×4)。单位为输入 token。',
94
+ topicFailed: '无法读取这个主题。',
95
+ savingsUnavailable: '节省:暂时无法读取(账本文件读不到)。',
96
+ search: '搜索主题',
97
+ allKinds: '全部',
98
+ zoomIn: '放大',
99
+ zoomOut: '缩小',
100
+ resetView: '还原视图',
101
+ tree_label: '记忆树:工作区、它的对话、对话里的主题',
102
+ close: '关闭',
103
+ copyId: '复制编号',
104
+ copied: '已复制',
105
+ fromChat: '来自对话',
106
+ links: '相关主题',
107
+ sources: '来源消息',
108
+ private: '私有',
109
+ memoryOff: '记忆已关闭',
110
+ more: '个未画出',
111
+ decision: '决定',
112
+ fact: '事实',
113
+ task: '任务',
114
+ artifact: '产物',
115
+ 'open-question': '待定问题'
116
+ }
117
+ const KINDS = ['decision', 'fact', 'task', 'artifact', 'open-question']
118
+ const COLORS = { decision: '#4A65E8', fact: '#2BA471', task: '#E5973C', artifact: '#8E5BE8', 'open-question': '#E5484D' }
119
+
120
+ const CSS = [
121
+ '.dshcg-root{margin:2px 0}',
122
+ '.dshcg-summary{margin-left:8px;font-size:13px;opacity:.72}',
123
+ '.dshcg-summary[data-error]{color:var(--dsw-alias-state-error-primary,#d64545);opacity:1}',
124
+ '.dshcg-body{padding:6px 0 6px 24px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word}',
125
+ '.dshcg-page{display:flex;flex-direction:column;gap:12px;font-size:13px;color:var(--dsw-alias-label-primary)}',
126
+ // The Memory tree page, laid out like dsh's own first-level pages (Plugins, Automation tasks):
127
+ // a 20px title row 28px from the top, a centred column with responsive side insets.
128
+ '.dshcg-main{width:100%;height:100%;min-width:0;min-height:0;overflow:auto;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}',
129
+ '.dshcg-column{max-width:1280px;margin:0 auto;padding:28px clamp(24px,4vw,48px) 48px;box-sizing:border-box}',
130
+ '[data-platform="darwin"] .dshcg-column{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}',
131
+ '.dshcg-heading{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:16px;margin-bottom:12px}',
132
+ '.dshcg-heading h1{margin:0;font-size:20px;line-height:28px;font-weight:500}',
133
+ '.dshcg-muted{color:var(--dsw-alias-label-secondary)}',
134
+ '.dshcg-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center}',
135
+ '.dshcg-btn{border:1px solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-layer-1);color:inherit;border-radius:var(--dsw-radius-md,8px);padding:4px 10px;cursor:pointer;font:inherit}',
136
+ '.dshcg-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}',
137
+ '.dshcg-btn[aria-pressed="true"]{border-color:var(--dsw-alias-brand-primary,#4A65E8)}',
138
+ '.dshcg-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:8px}',
139
+ '.dshcg-card{border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg,10px);padding:10px;background:var(--dsw-alias-bg-layer-2)}',
140
+ '.dshcg-big{font-size:18px;font-weight:600}',
141
+ '.dshcg-good{color:var(--dsw-alias-state-success-primary,#2BA471)}',
142
+ '.dshcg-bad{color:var(--dsw-alias-state-error-primary,#E5484D)}',
143
+ // The tree scrolls natively in its box; zoom only scales the drawing.
144
+ '.dshcg-treebox{overflow:auto;min-height:240px;max-height:calc(100vh - 220px);border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg,10px);background:var(--dsw-alias-bg-layer-1)}',
145
+ '.dshcg-tree{display:block}',
146
+ '.dshcg-link{fill:none;stroke:var(--dsw-alias-border-l2);stroke-width:1.25}',
147
+ '.dshcg-node{cursor:pointer}',
148
+ '.dshcg-pill{fill:var(--dsw-alias-bg-layer-2);stroke:var(--dsw-alias-border-l3);stroke-width:1}',
149
+ '.dshcg-node:hover .dshcg-pill,.dshcg-node[data-match="true"] .dshcg-pill{stroke:var(--dsw-alias-brand-primary,#4A65E8)}',
150
+ '.dshcg-label{font-size:12px;fill:var(--dsw-alias-label-primary)}',
151
+ '.dshcg-node[data-kind="workspace"] .dshcg-label{font-weight:600}',
152
+ '.dshcg-count{font-size:11px;fill:var(--dsw-alias-label-secondary)}',
153
+ '.dshcg-node[data-dim="true"],.dshcg-link[data-dim="true"]{opacity:.18}',
154
+ // #88: a moving node or link eases to its new place (Material 3: 300 ms, emphasized); pointing
155
+ // at or focusing a node fades everything outside its family.
156
+ '.dshcg-node{transition:transform 300ms cubic-bezier(0.2,0,0,1),opacity 150ms linear}',
157
+ '.dshcg-link{transition:d 300ms cubic-bezier(0.2,0,0,1),opacity 150ms linear}',
158
+ '.dshcg-node[data-family="false"],.dshcg-link[data-family="false"]{opacity:.25}',
159
+ '.dshcg-node[data-family="true"] .dshcg-pill{stroke:var(--dsw-alias-label-secondary)}',
160
+ '.dshcg-link[data-family="true"]{stroke:var(--dsw-alias-label-secondary)}',
161
+ '.dshcg-node:focus{outline:none}',
162
+ '.dshcg-node:focus-visible .dshcg-pill{stroke:var(--dsw-alias-brand-primary,#4A65E8);stroke-width:2}',
163
+ '@media (prefers-reduced-motion:reduce){.dshcg-node,.dshcg-link{transition:none}}',
164
+ '.dshcg-node[data-selected="true"] .dshcg-pill{stroke:var(--dsw-alias-brand-primary,#4A65E8);stroke-width:2}',
165
+ // The details sit beside the tree, and below it on a narrow window (#87).
166
+ '.dshcg-split{display:grid;grid-template-columns:minmax(0,1fr) minmax(260px,360px);gap:12px;align-items:start}',
167
+ '.dshcg-split>.dshcg-panel{position:sticky;top:12px;max-height:calc(100vh - 220px);overflow:auto}',
168
+ '@media (max-width:900px){.dshcg-split{grid-template-columns:minmax(0,1fr)}}',
169
+ '.dshcg-panel{border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg,10px);padding:12px;background:var(--dsw-alias-bg-layer-2);display:flex;flex-direction:column;gap:8px}',
170
+ '.dshcg-pre{white-space:pre-wrap;word-break:break-word;font-family:var(--dsw-font-mono,monospace);font-size:12px;margin:0;padding:8px;border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-1)}',
171
+ '.dshcg-input{border:1px solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-layer-1);color:inherit;border-radius:var(--dsw-radius-md,8px);padding:4px 8px;font:inherit;min-width:180px}',
172
+ '.dshcg-dot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:4px}'
173
+ ].join('')
174
+ if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css="dsh-context-graph"]') === null) {
175
+ const tag = document.createElement('style')
176
+ tag.dataset.pluginCss = NAMESPACE
177
+ tag.textContent = CSS
178
+ document.head.appendChild(tag)
179
+ }
180
+
181
+ // Three linked nodes: the same mark as the plugin icon, drawn in the current text colour.
182
+ const ICON = jsxs('svg', {
183
+ width: 14,
184
+ height: 14,
185
+ viewBox: '0 0 24 24',
186
+ fill: 'none',
187
+ stroke: 'currentColor',
188
+ strokeWidth: 2,
189
+ strokeLinecap: 'round',
190
+ 'aria-hidden': true,
191
+ children: [
192
+ jsx('path', { d: 'M7 7l10 3M7 7l3 10M17 10l-7 7' }),
193
+ jsx('circle', { cx: 7, cy: 7, r: 2.5, fill: 'currentColor' }),
194
+ jsx('circle', { cx: 17, cy: 10, r: 2, fill: 'currentColor' }),
195
+ jsx('circle', { cx: 10, cy: 17, r: 2, fill: 'currentColor' })
196
+ ]
197
+ })
198
+
199
+ /** The sidebar's Memory tree entry: a root and two branches, at the size and colour the row asks for. */
200
+ function TreeIcon({ size }) {
201
+ const edge = typeof size === 'number' ? size : 20
202
+ return jsxs('svg', {
203
+ width: edge,
204
+ height: edge,
205
+ viewBox: '0 0 20 20',
206
+ fill: 'none',
207
+ stroke: 'currentColor',
208
+ strokeWidth: 1.5,
209
+ strokeLinecap: 'round',
210
+ 'aria-hidden': true,
211
+ children: [
212
+ jsx('path', { d: 'M6 10C10 10 10 5 14 5M6 10C10 10 10 15 14 15' }),
213
+ jsx('circle', { cx: 4, cy: 10, r: 2 }),
214
+ jsx('circle', { cx: 16, cy: 5, r: 2 }),
215
+ jsx('circle', { cx: 16, cy: 15, r: 2 })
216
+ ]
217
+ })
218
+ }
219
+
220
+ const SUBCOMMANDS = ['stats', 'on', 'off', 'share', 'unshare', 'build', 'map', 'find']
221
+
222
+ /** Title key from the typed arguments (`/context-graph on` -> on); no argument means stats. */
223
+ function subcommandOf(args) {
224
+ const first = String(args ?? '').trim().split(/\s+/)[0] || 'stats'
225
+ return SUBCOMMANDS.includes(first) ? first : 'stats'
226
+ }
227
+
228
+ /** Host text: line 1 is the summary, later lines are the details shown when expanded. */
229
+ function splitText(text) {
230
+ const lines = String(text ?? '').split('\n')
231
+ return { summary: lines[0] ?? '', body: lines.slice(1).join('\n').trim() }
232
+ }
233
+
234
+ function ContextGraphCard({ node, t }) {
235
+ const [open, setOpen] = useState(false)
236
+ const outcome = node.outcome
237
+ const running = outcome === null
238
+ const failed = outcome?.kind === 'error'
239
+ const { summary, body } = splitText(outcome?.text)
240
+ const shown = running ? t('running') : summary || (failed ? t('failed') : '')
241
+ const hasBody = !running && body.length > 0
242
+ return jsx('div', {
243
+ className: 'dshcg-root',
244
+ 'data-state': running ? 'running' : failed ? 'error' : 'ok',
245
+ children: jsx(DisclosureRow, {
246
+ icon: ICON,
247
+ title: t(subcommandOf(node.args)),
248
+ running,
249
+ open: open && hasBody,
250
+ expandable: hasBody,
251
+ expandOnRowClick: true,
252
+ keepContentWhenOpen: true,
253
+ onToggle: () => setOpen((value) => !value),
254
+ collapsedContent: shown ? jsx('span', { className: 'dshcg-summary', 'data-error': failed || undefined, children: shown }) : undefined,
255
+ children: open && hasBody ? jsx('div', { className: 'dshcg-body', children: body }) : undefined
256
+ })
257
+ })
258
+ }
259
+
260
+ // ---- the plugin's page -------------------------------------------------------------------
261
+
262
+ /** The host's owner-only routes, document-relative like dsh's own (session export). */
263
+ async function getJson(name, query) {
264
+ const response = await fetch(`api/context-graph.${name}${query ? `?${new URLSearchParams(query)}` : ''}`)
265
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
266
+ return response.json()
267
+ }
268
+
269
+ const number = (n) => Number(n ?? 0).toLocaleString()
270
+ const translator = (t) => (typeof t === 'function' ? (key) => { const s = t(key); return s && s !== key ? s : en[key] ?? key } : (key) => en[key] ?? key)
271
+
272
+ // East Asian wide characters (CJK, kana, Hangul, full-width forms) and symbols such as \ud83d\udd12 \u23f8:
273
+ // about two Latin letters wide.
274
+ const WIDE = /[\u2300-\u23ff\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f000}-\u{1faff}]/u
275
+
276
+ /** How many Latin letters wide `text` is: a wide character counts two. */
277
+ const letters = (text) => [...text].reduce((sum, ch) => sum + (WIDE.test(ch) ? 2 : 1), 0)
278
+
279
+ /** `text` cut to about `room` Latin letters, ending in … if cut. */
280
+ function fit(text, room) {
281
+ const chars = [...text]
282
+ let used = letters(text)
283
+ if (used <= room) return text
284
+ let end = chars.length
285
+ while (end > 0 && used + 2 > room) used -= letters(chars[--end]) // 2: the ellipsis
286
+ return `${chars.slice(0, end).join('')}…`
287
+ }
288
+
289
+ /**
290
+ * A chat's number, marks and hidden-topic count, whole (a cut 'memory off' reads as on), then as much
291
+ * of its summary as `room` letters leave. A slot too small for the marks in words gets them as
292
+ * symbols, 🔒 private and ⏸ memory off; hover shows the full label (review).
293
+ */
294
+ function chatLabel(c, t, room = Infinity) {
295
+ let head = [`c${c.cid}`, c.shared ? '' : t('private'), c.memory ? '' : t('memoryOff'), c.total > c.shown ? `+${c.total - c.shown} ${t('more')}` : ''].filter(Boolean).join(' · ')
296
+ if (letters(head) > room) head = [`c${c.cid}`, `${c.shared ? '' : '🔒'}${c.memory ? '' : '⏸'}`, c.total > c.shown ? `+${c.total - c.shown}` : ''].filter(Boolean).join(' · ')
297
+ const rest = room - letters(head) - 3 // 3: the ' · ' before the summary
298
+ return c.summary && rest >= 6 ? `${head} · ${fit(c.summary, rest)}` : head // 6: four letters and the …
299
+ }
300
+
301
+ function Savings({ s, t }) {
302
+ // null: the ledger cannot be read right now (a sync tool holding it), not zero.
303
+ if (s === null) return jsx('div', { className: 'dshcg-muted', children: t('savingsUnavailable') })
304
+ const net = s?.net ?? 0
305
+ return jsxs('div', {
306
+ className: 'dshcg-cards',
307
+ children: [
308
+ jsxs('div', { className: 'dshcg-card', children: [jsx('div', { className: 'dshcg-muted', children: t('saved') }), jsx('div', { className: 'dshcg-big', children: number(s?.saved) })] }),
309
+ jsxs('div', { className: 'dshcg-card', children: [jsx('div', { className: 'dshcg-muted', children: t('cost') }), jsx('div', { className: 'dshcg-big', children: number(s?.cost) })] }),
310
+ jsxs('div', { className: 'dshcg-card', children: [jsx('div', { className: 'dshcg-muted', children: t('net') }), jsx('div', { className: `dshcg-big ${net >= 0 ? 'dshcg-good' : 'dshcg-bad'}`, children: `${net >= 0 ? '+' : '−'}${number(Math.abs(net))}` })] })
311
+ ]
312
+ })
313
+ }
314
+
315
+ /** One topic, opened from the map: its gist, chat, links, sources and the id to paste. */
316
+ function TopicPanel({ detail, t, onOpen, onClose }) {
317
+ const [copied, setCopied] = useState(false)
318
+ const copy = () => {
319
+ // No clipboard on plain-http remote access: nothing is copied, so nothing says Copied.
320
+ globalThis.navigator?.clipboard?.writeText?.(detail.id).then(() => setCopied(true), () => {})
321
+ }
322
+ return jsxs('div', {
323
+ className: 'dshcg-panel',
324
+ role: 'region',
325
+ 'aria-label': detail.label,
326
+ children: [
327
+ jsxs('div', {
328
+ className: 'dshcg-row',
329
+ children: [
330
+ jsx('span', { className: 'dshcg-dot', style: { background: COLORS[detail.kind] ?? '#888' } }),
331
+ jsx('strong', { children: detail.label }),
332
+ jsx('span', { className: 'dshcg-muted', children: `${detail.id} · ${t(detail.kind)}` }),
333
+ jsx('button', { type: 'button', className: 'dshcg-btn', onClick: copy, children: copied ? t('copied') : t('copyId') }),
334
+ jsx('button', { type: 'button', className: 'dshcg-btn', onClick: onClose, children: t('close') })
335
+ ]
336
+ }),
337
+ jsx('div', { children: detail.gist }),
338
+ jsx('div', { className: 'dshcg-muted', children: `${t('fromChat')} c${detail.chat.cid}: ${detail.chat.summary}` }),
339
+ // One topic can be linked twice (n1 uses n2, n2 part-of n1), so the key is the whole link.
340
+ detail.links.length > 0
341
+ ? jsxs('div', { children: [jsx('div', { className: 'dshcg-muted', children: t('links') }), jsx('div', { className: 'dshcg-row', children: detail.links.map((l) => jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => onOpen(l.id), children: `${l.label} (${l.relation})` }, `${l.id} ${l.relation} ${l.direction}`)) })] })
342
+ : null,
343
+ detail.sources.length > 0
344
+ ? jsxs('div', { children: [jsx('div', { className: 'dshcg-muted', children: t('sources') }), ...detail.sources.map((s, i) => jsx('pre', { className: 'dshcg-pre', children: `${s.role}${s.turn ? ` (t${s.turn})` : ''}:\n${s.text}` }, i))] })
345
+ : null
346
+ ]
347
+ })
348
+ }
349
+
350
+ // ---- the memory tree (#86) ----------------------------------------------------------------
351
+ // A node-link tree, root on the left. The layout keeps d3-hierarchy's tidy-tree rules (one column
352
+ // per depth, a parent centred on its children, a leaf one row from its sibling and half a row more
353
+ // from another parent's child); each column is as wide as its widest node, as in AntV G6's
354
+ // compactBox; links are d3.linkHorizontal's curves. Techniques credited in the README.
355
+
356
+ const ROW = 30 // px from one row to the next
357
+ const PILL = 22 // px, a node's height
358
+ const LETTER = 6.6 // px a Latin letter takes at 12px
359
+ const HGAP = 40 // px from a column's widest node to the next column
360
+ const PAD = 16
361
+ const OPEN_ROWS = 40 // the newest chats start open while their topics stay within this many rows
362
+ const ROOM = [32, 48, 44, 52] // letters a label keeps, by depth; the full text shows on hover
363
+
364
+ /** A source message in one line: who, its turn, and its text with the line breaks flattened. */
365
+ const sourceLine = (s) => `${s.role}${s.turn ? ` t${s.turn}` : ''} · ${String(s.text ?? '').replace(/\s+/g, ' ').trim()}`
366
+
367
+ /**
368
+ * The host's tree as nested items: workspace, chats, topics, and (#87) the messages of each topic
369
+ * read so far. `details` maps a topic id to its answer, `{ loading: true }` or `{ error: true }`;
370
+ * a topic not read yet has no children, a loading one shows …, a failed one !.
371
+ */
372
+ function treeItems(data, t, details = {}) {
373
+ const topic = (cid, [id, label, kind], links) => {
374
+ const tid = `c${cid}${id}`
375
+ const detail = details[tid]
376
+ return {
377
+ id: tid,
378
+ kind: 'topic',
379
+ topicKind: kind,
380
+ label: fit(String(label), ROOM[2]),
381
+ full: detail?.error ? `${tid} ${label}: ${t('topicFailed')}` : `${tid} ${label}`,
382
+ badge: detail?.loading ? '…' : detail?.error ? '!' : undefined,
383
+ linked: links.flatMap(([from, to]) => (from === id ? [`c${cid}${to}`] : to === id ? [`c${cid}${from}`] : [])),
384
+ children: detail?.sources?.map((s, i) => ({ id: `${tid}s${i}`, kind: 'source', topic: tid, label: fit(sourceLine(s), ROOM[3]), full: sourceLine(s) }))
385
+ }
386
+ }
387
+ return {
388
+ id: 'w',
389
+ kind: 'workspace',
390
+ label: data.title,
391
+ children: data.chats.map((c) => {
392
+ const chat = { ...c, shown: c.topics.length }
393
+ return {
394
+ id: `c${c.cid}`,
395
+ kind: 'chat',
396
+ chat: c,
397
+ label: chatLabel(chat, t, ROOM[1]),
398
+ full: chatLabel(chat, t),
399
+ children: c.topics.map((entry) => topic(c.cid, entry, c.links ?? []))
400
+ }
401
+ })
402
+ }
403
+ }
404
+
405
+ /** Ids open at first: the workspace and the newest chats, while their topics fit OPEN_ROWS (one at least). */
406
+ function initialOpen(data) {
407
+ const open = new Set(['w'])
408
+ let rows = 0
409
+ for (const c of data.chats) {
410
+ if (open.size > 1 && rows + c.topics.length > OPEN_ROWS) break
411
+ open.add(`c${c.cid}`)
412
+ rows += c.topics.length
413
+ }
414
+ return open
415
+ }
416
+
417
+ /** What a node shows at its end: a topic's … or !, else how many a closed branch holds. */
418
+ const countOf = (item, open) => item.badge ?? (item.children?.length && !open.has(item.id) ? String(item.children.length) : '')
419
+
420
+ /** A node's width: dot, label, and the count of a closed branch. */
421
+ const widthOf = (item, open) => {
422
+ const count = countOf(item, open)
423
+ return Math.round(24 + letters(item.label) * LETTER + (count ? letters(count) * LETTER + 8 : 0) + 10)
424
+ }
425
+
426
+ /**
427
+ * Where each visible node goes. `open` holds the ids whose children show.
428
+ * @returns { nodes: [{ id, item, depth, parent, x, y, w }] in tree order, width, height } in px;
429
+ * x is a node's left edge, y its middle
430
+ */
431
+ function layoutTree(root, open) {
432
+ const nodes = []
433
+ let next = 0
434
+ let lastParent = null
435
+ const place = (item, depth, parent) => {
436
+ const node = { id: item.id, item, depth, parent, x: 0, y: 0, w: widthOf(item, open), pos: 1, size: 1 }
437
+ nodes.push(node)
438
+ const kids = open.has(item.id) ? item.children ?? [] : []
439
+ if (kids.length === 0) {
440
+ if (lastParent !== null && lastParent !== parent) next += 0.5
441
+ node.y = next++
442
+ lastParent = parent
443
+ } else {
444
+ const placed = kids.map((kid, i) => Object.assign(place(kid, depth + 1, node), { pos: i + 1, size: kids.length }))
445
+ node.y = (placed[0].y + placed[placed.length - 1].y) / 2
446
+ }
447
+ return node
448
+ }
449
+ place(root, 0, null)
450
+ const widths = []
451
+ for (const n of nodes) widths[n.depth] = Math.max(widths[n.depth] ?? 0, n.w)
452
+ const left = [PAD]
453
+ for (let d = 1; d < widths.length; d++) left[d] = left[d - 1] + widths[d - 1] + HGAP
454
+ for (const n of nodes) {
455
+ n.x = left[n.depth]
456
+ n.y = PAD + PILL / 2 + n.y * ROW
457
+ }
458
+ const last = widths.length - 1
459
+ return { nodes, width: left[last] + widths[last] + PAD, height: PAD * 2 + PILL + (next - 1) * ROW }
460
+ }
461
+
462
+ /** d3.linkHorizontal's curve from the right end of `from` to the left end of `to`. */
463
+ function linkPath(from, to) {
464
+ const x0 = from.x + from.w
465
+ const mid = (x0 + to.x) / 2
466
+ return `M${x0},${from.y}C${mid},${from.y} ${mid},${to.y} ${to.x},${to.y}`
467
+ }
468
+
469
+ // Topics are dots in their kind's colour; the workspace and chats, which hold them, are rings; a
470
+ // topic's messages are small grey dots.
471
+ const dotStyle = (item) => (item.kind === 'topic' ? { fill: COLORS[item.topicKind] ?? '#888' } : item.kind === 'source' ? { fill: 'var(--dsw-alias-label-secondary)' } : { fill: 'none', stroke: 'var(--dsw-alias-label-secondary)', strokeWidth: 1.5 })
472
+
473
+ /** A node that has children to show, or a topic whose messages are not read yet. */
474
+ const expandable = (item) => (item.children?.length ?? 0) > 0 || (item.kind === 'topic' && item.children === undefined)
475
+
476
+ /**
477
+ * The W3C WAI-ARIA tree view keys (#88), on the visible nodes in tree order: Up/Down move, Right
478
+ * opens a closed branch or steps into an open one, Left closes an open one or steps out to the
479
+ * parent, Home/End go to the ends, Enter or Space does what a click does.
480
+ * @returns { focus: id } | { open: id } | { close: id } | { activate: id } | null
481
+ */
482
+ function treeKey(nodes, id, key, isOpen) {
483
+ const i = nodes.findIndex((n) => n.id === id)
484
+ if (i < 0) return null
485
+ const n = nodes[i]
486
+ if (key === 'ArrowDown') return i + 1 < nodes.length ? { focus: nodes[i + 1].id } : null
487
+ if (key === 'ArrowUp') return i > 0 ? { focus: nodes[i - 1].id } : null
488
+ if (key === 'Home') return { focus: nodes[0].id }
489
+ if (key === 'End') return { focus: nodes[nodes.length - 1].id }
490
+ if (key === 'ArrowRight') {
491
+ if (!expandable(n.item)) return null
492
+ if (!isOpen(n.id)) return { open: n.id }
493
+ return nodes[i + 1]?.parent === n ? { focus: nodes[i + 1].id } : null
494
+ }
495
+ if (key === 'ArrowLeft') {
496
+ if (expandable(n.item) && isOpen(n.id)) return { close: n.id }
497
+ return n.parent ? { focus: n.parent.id } : null
498
+ }
499
+ if (key === 'Enter' || key === ' ') return { activate: n.id }
500
+ return null
501
+ }
502
+
503
+ /**
504
+ * A node's family (#88, Apache ECharts' emphasis focus 'relative'): its ancestors, its visible
505
+ * descendants and, for a topic, the topics it links to.
506
+ */
507
+ function familyOf(nodes, id) {
508
+ const n = nodes.find((x) => x.id === id)
509
+ if (!n) return null
510
+ const family = new Set([id, ...(n.item.linked ?? [])])
511
+ for (let up = n.parent; up; up = up.parent) family.add(up.id)
512
+ for (const m of nodes) for (let up = m.parent; up; up = up.parent) if (up === n) family.add(m.id)
513
+ return family
514
+ }
515
+
516
+ // Material 3 motion (Google, Apache-2.0): 300 ms (medium2); what enters decelerates
517
+ // (emphasized decelerate), what moves uses the emphasized curve (the CSS transitions above).
518
+ const ENTER = { duration: 300, easing: 'cubic-bezier(0.05, 0.7, 0.1, 1)' }
519
+ const stillness = () => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true
520
+
521
+ // A tree showing more rows than this draws what enters at once: a search that opens thousands of
522
+ // topics would start thousands of animations, on SVG transforms the browser cannot hand to the
523
+ // compositor (#90).
524
+ const CALM_ROWS = 400
525
+
526
+ /**
527
+ * A node or link drawn for the first time grows out of its parent, as in the D3 collapsible tree
528
+ * (#88); an element already shown is left to the CSS transitions. Nothing moves when the system
529
+ * asks for reduced motion, or when `calm` (a tree too big to follow the motion, #90).
530
+ */
531
+ function grow(el, frames, calm = false) {
532
+ if (!el || el.dataset?.grown) return
533
+ if (el.dataset) el.dataset.grown = '1'
534
+ if (calm || stillness() || typeof el.animate !== 'function') return
535
+ try { el.animate(frames, ENTER) } catch { /* a browser that cannot animate this property: shown at once */ }
536
+ }
537
+
538
+ /** Search, kind filter and zoom, above the tree and its panel. */
539
+ function TreeTools({ t, query, kind, onQuery, onKind, onScale }) {
540
+ return jsxs('div', {
541
+ className: 'dshcg-row',
542
+ children: [
543
+ jsx('input', { className: 'dshcg-input', type: 'search', placeholder: t('search'), 'aria-label': t('search'), value: query, onChange: (e) => onQuery(e.target.value) }),
544
+ jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': kind === '' ? 'true' : 'false', onClick: () => onKind(''), children: t('allKinds') }),
545
+ ...KINDS.map((k) => jsxs('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': kind === k ? 'true' : 'false', onClick: () => onKind(kind === k ? '' : k), children: [jsx('span', { className: 'dshcg-dot', style: { background: COLORS[k] } }), t(k)] }, k)),
546
+ jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-label': t('zoomOut'), onClick: () => onScale((s) => Math.max(0.5, s / 1.25)), children: '−' }),
547
+ jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-label': t('zoomIn'), onClick: () => onScale((s) => Math.min(2, s * 1.25)), children: '+' }),
548
+ jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => onScale(1), children: t('resetView') })
549
+ ]
550
+ })
551
+ }
552
+
553
+ /**
554
+ * The tree: a click opens or closes a branch and shows its details beside the tree (a chat's, or a
555
+ * topic's, which also brings its messages in as its children, #87); search and kinds dim the rest.
556
+ */
557
+ function MemoryTree({ data, t, query = '', kind = '', scale = 1, details = {}, selected = null, onOpen, onChat = () => {} }) {
558
+ const [open, setOpen] = useState(initialOpen(data))
559
+ const [hover, setHover] = useState(null) // the node under the pointer
560
+ const [focused, setFocused] = useState(null) // the node with keyboard focus
561
+ const [active, setActive] = useState('w') // the tree's one tab stop
562
+ const els = React.useRef(new Map())
563
+ // A topic chosen while its chat is closed (a linked topic opened from the panel) opens that chat
564
+ // once, so the selection is drawn; the chat can be closed again as any other (#89).
565
+ const reveal = /^(c\d+)n/.exec(selected?.topic ?? '')?.[1]
566
+ React.useEffect(() => {
567
+ if (reveal) setOpen((was) => (was.has(reveal) ? was : new Set([...was, reveal])))
568
+ }, [selected?.topic])
569
+ const q = query.trim().toLowerCase()
570
+ const root = treeItems(data, t, details)
571
+ const hit = (item) => item.kind === 'topic' && q !== '' && item.full.toLowerCase().includes(q)
572
+ // A search opens every chat with a match, without changing what is open once it is cleared.
573
+ const shown = new Set(open)
574
+ if (q) for (const chat of root.children) if (chat.children.some(hit)) shown.add(chat.id)
575
+ const layout = layoutTree(root, shown)
576
+ // Closes what is shown open (a chat opened by the search stays open until the search is cleared).
577
+ const toggle = (id) => setOpen((was) => {
578
+ const now = new Set(was)
579
+ if (shown.has(id)) now.delete(id)
580
+ else now.add(id)
581
+ return now
582
+ })
583
+ const activate = (item) => {
584
+ if (item.kind === 'source') return onOpen(item.topic)
585
+ toggle(item.id)
586
+ if (item.kind === 'chat') onChat(item.chat.cid)
587
+ if (item.kind === 'topic') onOpen(item.id)
588
+ }
589
+ const chosen = (item) => (item.kind === 'chat' ? selected?.chat === item.chat.cid : item.kind === 'topic' && selected?.topic === item.id)
590
+ const dim = (item) => item.kind === 'topic' && ((kind && item.topicKind !== kind) || (q && !hit(item)))
591
+ const center = hover ?? focused
592
+ const calm = layout.nodes.length > CALM_ROWS
593
+ const family = center ? familyOf(layout.nodes, center) : null
594
+ // A family holds each member's parent, so a link is in it when its child is.
595
+ const kin = (id) => (family ? (family.has(id) ? 'true' : 'false') : undefined)
596
+ // A node collapsed away hands the tab stop to the workspace, so Tab still reaches the tree.
597
+ const stop = layout.nodes.some((n) => n.id === active) ? active : 'w'
598
+ const key = (n, e) => {
599
+ const move = treeKey(layout.nodes, n.id, e.key, (id) => shown.has(id))
600
+ if (!move) return
601
+ e.preventDefault?.()
602
+ if (move.focus) {
603
+ setActive(move.focus)
604
+ els.current.get(move.focus)?.focus?.()
605
+ }
606
+ if (move.open) n.item.kind === 'topic' ? activate(n.item) : toggle(n.id)
607
+ if (move.close) toggle(n.id)
608
+ if (move.activate) activate(n.item)
609
+ }
610
+ return jsx('div', {
611
+ className: 'dshcg-treebox',
612
+ children: jsxs('svg', {
613
+ className: 'dshcg-tree',
614
+ role: 'tree',
615
+ 'aria-label': t('tree_label'),
616
+ width: Math.round(layout.width * scale),
617
+ height: Math.round(layout.height * scale),
618
+ viewBox: `0 0 ${layout.width} ${layout.height}`,
619
+ children: [
620
+ ...layout.nodes.filter((n) => n.parent).map((n) => {
621
+ const d = linkPath(n.parent, n)
622
+ const tip = { x: n.parent.x + n.parent.w, y: n.parent.y, w: 0 }
623
+ return jsx('path', {
624
+ className: 'dshcg-link',
625
+ d,
626
+ // As a style too, so a moving link is eased by the CSS transition on d.
627
+ style: { d: `path('${d}')` },
628
+ 'data-dim': dim(n.item) ? 'true' : 'false',
629
+ 'data-family': kin(n.id),
630
+ ref: (el) => grow(el, [{ d: `path('${linkPath(n.parent, tip)}')`, opacity: 0 }, { d: `path('${d}')`, opacity: 1 }], calm)
631
+ }, `l${n.id}`)
632
+ }),
633
+ ...layout.nodes.map((n) => {
634
+ const count = countOf(n.item, shown)
635
+ const at = `translate(${n.x}px,${n.y}px)`
636
+ const from = n.parent ? `translate(${n.parent.x + n.parent.w - PILL}px,${n.parent.y}px) scale(0.6)` : at
637
+ return jsxs('g', {
638
+ className: 'dshcg-node',
639
+ role: 'treeitem',
640
+ 'aria-level': n.depth + 1,
641
+ 'aria-posinset': n.pos,
642
+ 'aria-setsize': n.size,
643
+ 'aria-expanded': expandable(n.item) ? (shown.has(n.id) ? 'true' : 'false') : undefined,
644
+ 'aria-selected': chosen(n.item) ? 'true' : 'false',
645
+ tabIndex: n.id === stop ? 0 : -1,
646
+ 'data-kind': n.item.kind,
647
+ 'data-family': kin(n.id),
648
+ 'data-dim': dim(n.item) ? 'true' : 'false',
649
+ 'data-match': hit(n.item) ? 'true' : 'false',
650
+ 'data-selected': chosen(n.item) ? 'true' : 'false',
651
+ style: { transform: at },
652
+ ref: (el) => {
653
+ if (el) els.current.set(n.id, el)
654
+ grow(el, [{ transform: from, opacity: 0 }, { transform: at, opacity: 1 }], calm)
655
+ },
656
+ onClick: () => {
657
+ setActive(n.id)
658
+ activate(n.item)
659
+ },
660
+ onKeyDown: (e) => key(n, e),
661
+ onFocus: (e) => {
662
+ setActive(n.id)
663
+ // Keyboard focus shows the family; a click's focus does not, or every click would dim the tree.
664
+ if (e.currentTarget?.matches?.(':focus-visible')) setFocused(n.id)
665
+ },
666
+ onBlur: () => setFocused(null),
667
+ onPointerEnter: () => setHover(n.id),
668
+ onPointerLeave: () => setHover(null),
669
+ children: [
670
+ jsx('title', { children: n.item.full ?? n.item.label }),
671
+ jsx('rect', { className: 'dshcg-pill', x: 0, y: -PILL / 2, width: n.w, height: PILL, rx: PILL / 2 }),
672
+ jsx('circle', { cx: 12, cy: 0, r: 4, style: dotStyle(n.item) }),
673
+ jsx('text', { className: 'dshcg-label', x: 24, y: 4, children: n.item.label }),
674
+ count ? jsx('text', { className: 'dshcg-count', x: n.w - 10, y: 4, textAnchor: 'end', children: count }) : null
675
+ ]
676
+ }, n.id)
677
+ })
678
+ ]
679
+ })
680
+ })
681
+ }
682
+
683
+ /**
684
+ * The workspaces with memory, and the one shown: both pages start from the overview. `onChoose`
685
+ * runs when a workspace is chosen, the first one included.
686
+ */
687
+ function useWorkspaces(onChoose) {
688
+ const [state, setState] = useState({ status: 'loading' })
689
+ const [key, setKey] = useState(null)
690
+ const choose = (next) => {
691
+ setKey(next)
692
+ onChoose?.(next)
693
+ }
694
+ const load = () => {
695
+ setState({ status: 'loading' })
696
+ getJson('overview').then((value) => {
697
+ setState({ status: 'ready', workspaces: value.workspaces })
698
+ const first = value.workspaces.find((w) => w.indexed > 0) ?? value.workspaces[0]
699
+ if (first) choose(first.key)
700
+ }, () => setState({ status: 'error' }))
701
+ }
702
+ React.useEffect(load, [])
703
+ return { state, key, load, choose }
704
+ }
705
+
706
+ /** Loading, failed or empty overview: what a page shows instead of its body, or null once ready. */
707
+ function overviewNotice(ws, t) {
708
+ if (ws.state.status === 'loading') return jsx('div', { className: 'dshcg-muted', children: t('loading') })
709
+ if (ws.state.status === 'error') {
710
+ return jsxs('div', { className: 'dshcg-row', children: [jsx('div', { className: 'dshcg-bad', children: t('loadFailed') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: ws.load, children: t('retry') })] })
711
+ }
712
+ if (ws.state.workspaces.length === 0) return jsx('div', { className: 'dshcg-muted', children: t('noWorkspaces') })
713
+ return null
714
+ }
715
+
716
+ /** One button per workspace, shown only when there is more than one. */
717
+ function workspaceButtons(ws, t) {
718
+ if (ws.state.workspaces.length < 2) return null
719
+ return jsx('div', { className: 'dshcg-row', children: ws.state.workspaces.map((w) => jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': w.key === ws.key ? 'true' : 'false', onClick: () => ws.choose(w.key), children: `${w.title} · ${w.indexed} ${t('chats')} · ${w.topics} ${t('topics')}` }, w.key)) })
720
+ }
721
+
722
+ /** The plugin's page in Plugins: one workspace at a time and its savings; the tree has its own page (#85). */
723
+ function SavingsPage(props) {
724
+ const t = translator(props.t)
725
+ const ws = useWorkspaces()
726
+ const notice = overviewNotice(ws, t)
727
+ if (notice) return jsx('div', { className: 'dshcg-page', children: notice })
728
+ const current = ws.state.workspaces.find((w) => w.key === ws.key)
729
+ return jsxs('div', {
730
+ className: 'dshcg-page',
731
+ children: [
732
+ jsx('div', { className: 'dshcg-muted', children: t('pageIntro') }),
733
+ workspaceButtons(ws, t),
734
+ current ? jsx(Savings, { s: current.savings, t }) : null,
735
+ jsx('div', { className: 'dshcg-muted', children: t('savingsRule') }),
736
+ jsx('div', { children: t('treeHint') })
737
+ ]
738
+ })
739
+ }
740
+
741
+ /** A chat, selected in the tree: its marks, summary, dates and what memory saved in it (#87). */
742
+ function ChatPanel({ chat, t, onClose }) {
743
+ const marks = [chat.shared ? '' : t('private'), chat.memory ? '' : t('memoryOff')].filter(Boolean).join(' · ')
744
+ const day = (iso) => (iso ? new Date(iso).toLocaleDateString() : '?')
745
+ const s = chat.savings
746
+ return jsxs('div', {
747
+ className: 'dshcg-panel',
748
+ role: 'region',
749
+ 'aria-label': `c${chat.cid}`,
750
+ children: [
751
+ jsxs('div', {
752
+ className: 'dshcg-row',
753
+ children: [
754
+ jsx('strong', { children: `c${chat.cid}` }),
755
+ marks ? jsx('span', { className: 'dshcg-muted', children: marks }) : null,
756
+ jsx('button', { type: 'button', className: 'dshcg-btn', onClick: onClose, children: t('close') })
757
+ ]
758
+ }),
759
+ chat.title ? jsx('div', { children: chat.title }) : null,
760
+ chat.summary ? jsx('div', { className: 'dshcg-muted', children: chat.summary }) : null,
761
+ jsx('div', { className: 'dshcg-muted', children: `${chat.total} ${t('topics')} · ${day(chat.startedAt)} – ${day(chat.lastActiveAt)}` }),
762
+ s === null || s === undefined
763
+ ? jsx('div', { className: 'dshcg-muted', children: t('savingsUnavailable') })
764
+ : jsx('div', { children: `${t('saved')} ${number(s.saved)} · ${t('cost')} ${number(s.cost)} · ${t('net')} ${s.net >= 0 ? '+' : '−'}${number(Math.abs(s.net))}` })
765
+ ]
766
+ })
767
+ }
768
+
769
+ /** Memory tree, the page the sidebar entry opens in the main column (#85). */
770
+ function TreePage(props) {
771
+ const t = translator(props.t)
772
+ const [map, setMap] = useState(null)
773
+ // Topics read so far (#87): id -> the host's answer, { loading: true } or { error: true }.
774
+ const [details, setDetails] = useState({})
775
+ const [selected, setSelected] = useState(null) // { topic: id } or { chat: cid }
776
+ const [query, setQuery] = useState('')
777
+ const [kind, setKind] = useState('')
778
+ const [scale, setScale] = useState(1)
779
+ // Each workspace shown is a new generation: an answer asked in an older one is dropped, so a
780
+ // late tree or topic cannot land in the workspace chosen since.
781
+ const generation = React.useRef(0)
782
+ const show = (next) => {
783
+ const n = ++generation.current
784
+ setMap(null)
785
+ setDetails({})
786
+ setSelected(null)
787
+ getJson('tree', { w: next }).then((value) => { if (generation.current === n) setMap(value) }, () => { if (generation.current === n) setMap({ error: true }) })
788
+ }
789
+ const ws = useWorkspaces(show)
790
+ const read = (id) => {
791
+ const n = generation.current
792
+ const take = (value) => { if (generation.current === n) setDetails((was) => ({ ...was, [id]: value })) }
793
+ setDetails((was) => ({ ...was, [id]: { loading: true } }))
794
+ getJson('topic', { w: ws.key, id }).then(take, () => take({ id, error: true }))
795
+ }
796
+ // A topic is read once; one that failed is asked again when opened again.
797
+ const open = (id) => {
798
+ setSelected({ topic: id })
799
+ if (!details[id] || details[id].error) read(id)
800
+ }
801
+ const close = () => setSelected(null)
802
+ const detail = selected?.topic ? details[selected.topic] : undefined
803
+ const panel = !selected || !map?.chats ? null
804
+ : selected.chat !== undefined ? jsx(ChatPanel, { chat: map.chats.find((c) => c.cid === selected.chat), t, onClose: close }, `c${selected.chat}`)
805
+ : detail?.error ? jsxs('div', { className: 'dshcg-panel', children: [jsx('div', { className: 'dshcg-bad', children: t('topicFailed') }), jsxs('div', { className: 'dshcg-row', children: [jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => read(selected.topic), children: t('retry') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: close, children: t('close') })] })] })
806
+ : !detail || detail.loading ? jsx('div', { className: 'dshcg-panel dshcg-muted', children: t('loading') })
807
+ // Keyed by topic: another topic gets a new panel, not this one's buttons and Copied.
808
+ : jsx(TopicPanel, { detail, t, onOpen: open, onClose: close }, detail.id)
809
+ const notice = overviewNotice(ws, t)
810
+ const body = notice ? [notice] : [
811
+ workspaceButtons(ws, t),
812
+ !map ? jsx('div', { className: 'dshcg-muted', children: t('loading') })
813
+ : map.error ? jsxs('div', { className: 'dshcg-row', children: [jsx('div', { className: 'dshcg-bad', children: t('loadFailed') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => show(ws.key), children: t('retry') })] })
814
+ : map.chats.length === 0 ? jsx('div', { className: 'dshcg-muted', children: t('noWorkspaces') })
815
+ : jsxs('div', {
816
+ className: 'dshcg-page',
817
+ children: [
818
+ jsx(TreeTools, { t, query, kind, onQuery: setQuery, onKind: setKind, onScale: setScale }),
819
+ jsxs('div', {
820
+ className: panel ? 'dshcg-split' : undefined,
821
+ children: [jsx(MemoryTree, { data: map, t, query, kind, scale, details, selected, onOpen: open, onChat: (cid) => setSelected({ chat: cid }) }, map.key), panel]
822
+ })
823
+ ]
824
+ })
825
+ ]
826
+ return jsx('div', {
827
+ className: 'dshcg-main',
828
+ children: jsxs('div', {
829
+ className: 'dshcg-column dshcg-page',
830
+ children: [
831
+ jsx('div', { className: 'dshcg-heading', children: jsx('h1', { children: t('panel') }) }),
832
+ jsx('div', { className: 'dshcg-muted', children: t('treeIntro') }),
833
+ ...body
834
+ ]
835
+ })
836
+ })
837
+ }
838
+
839
+ // The sidebar entry and the page it opens share this id, as dsh's own Automation tasks do.
840
+ const PANEL = 'dsh-context-graph'
841
+
842
+ const inject = ['slots', 'locale']
843
+ function apply(ctx) {
844
+ ctx.effect(() => ctx.locale.register(NAMESPACE, { en, zh }), 'dsh-context-graph: dictionaries')
845
+ ctx.slots.inject('conversation.chat.commandview', () =>
846
+ ctx.slots.register({ name: 'conversation.chat.commandview', key: 'context-graph', locale: NAMESPACE }, ContextGraphCard)
847
+ )
848
+ // The plugin's own page in Plugins, keyed by the package name (rc.5 renders it with { view: 'page' }).
849
+ ctx.slots.inject('plugins.bundle.config', () =>
850
+ ctx.slots.register({ name: 'plugins.bundle.config', key: 'dsh-context-graph', locale: NAMESPACE }, SavingsPage)
851
+ )
852
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL, locale: NAMESPACE }, TreePage))
853
+ // The label is read again at every projection, so it follows the app's language.
854
+ const label = translator(typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NAMESPACE) : undefined)
855
+ ctx.slots.inject('sidebar.panellist', () =>
856
+ ctx.slots.register({ name: 'sidebar.panellist', id: PANEL, order: 30, locale: NAMESPACE, label: () => label('panel') }, TreeIcon)
857
+ )
858
+ }
859
+
860
+ exports.inject = inject
861
+ exports.apply = apply
862
+ exports.ContextGraphCard = ContextGraphCard
863
+ exports.SavingsPage = SavingsPage
864
+ exports.TreePage = TreePage
865
+ exports.TreeIcon = TreeIcon
866
+ exports.MemoryTree = MemoryTree
867
+ exports.TreeTools = TreeTools
868
+ exports.treeKey = treeKey
869
+ exports.familyOf = familyOf
870
+ exports.layoutTree = layoutTree
871
+ exports.treeItems = treeItems
872
+ exports.initialOpen = initialOpen
873
+ exports.chatLabel = chatLabel
874
+ exports.TopicPanel = TopicPanel
875
+ exports.ChatPanel = ChatPanel
876
+ exports.subcommandOf = subcommandOf
877
+ exports.splitText = splitText
878
+ return module.exports
879
+ }
880
+ })