dsh-context-graph 0.10.0 → 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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,57 @@ All notable changes to dsh-context-graph. Versions follow semver; each minor ver
4
4
  is one development cycle (audit, issues, fixes, independent review), documented in
5
5
  [docs/cycles](docs/cycles).
6
6
 
7
+ ## 0.11.0 — 2026-11-22 — the memory tree
8
+
9
+ The memory has always been a tree (workspace, chats, topics, the messages they came from); now it
10
+ is drawn as one, on a page of its own. The picture moves from the plugin's page in Plugins to a
11
+ Memory tree entry in the sidebar, next to Automation tasks. Its techniques come from projects big
12
+ companies publish under free licences; no code was copied and no dependency added (credits in the
13
+ README).
14
+
15
+ **Its own page** (#85)
16
+ - Memory tree in the sidebar's panel list opens a page in the main column, laid out like dsh's own
17
+ first-level pages. The plugin's page in Plugins keeps the savings and says where the tree is;
18
+ `/context-graph map` points there for the chats it leaves out.
19
+
20
+ **A tree, not circles** (#86)
21
+ - Root on the left, one column per level. The layout keeps D3's tidy-tree rules (a parent centred
22
+ on its children, siblings one row apart, another parent's children half a row further); each
23
+ column is as wide as its widest label, as in AntV G6's compactBox, so labels are no longer cut to
24
+ fit a circle; links are D3's horizontal curves.
25
+ - The newest chats start open while their topics fit 40 rows (the idea of ECharts'
26
+ initialTreeDepth); a closed chat shows how many topics it holds. Topics are grouped by kind, so
27
+ each colour forms one band; chats and the workspace are rings.
28
+ - Search opens the chats it matches and fades the other topics; the kind buttons fade the other
29
+ kinds. The tree scrolls natively; zoom scales the drawing.
30
+ - Host: the `map` route becomes `tree` (chats with their topics and the links among them), and
31
+ `src/core/layout.js` gives way to `src/core/tree.js`.
32
+
33
+ **The last level** (#87)
34
+ - Opening a topic reads it once and adds its newest stored messages as its children (`user t7 ·
35
+ ...`); a message leads back to its topic. A topic on its way shows `…`, one that failed `!`.
36
+ - A chat or topic you choose shows its details beside the tree: a topic's gist, links, sources and
37
+ id; a chat's marks, dates and savings.
38
+
39
+ **Focus, motion, keyboard** (#88)
40
+ - Pointing at a node, or focusing it by keyboard, fades everything but its family: ancestors,
41
+ descendants and the topics it links to (ECharts' emphasis focus).
42
+ - What opens grows out of its parent and what moves eases to its place (D3's collapsible tree;
43
+ Material 3 timing: 300 ms, emphasized easing). Nothing moves with reduced motion on.
44
+ - The tree is a WAI-ARIA tree (the W3C pattern Microsoft Fluent UI and GitHub Primer follow): one
45
+ tab stop, Up/Down, Right/Left to open, close or step in and out, Home/End, Enter/Space.
46
+
47
+ **Review** (#89, #90)
48
+ - A linked topic opened from the details panel opens its chat once, so the selection is drawn; the
49
+ chat can still be closed. (#89)
50
+ - A tree showing more than 400 rows (a broad search in a big workspace) draws what enters at once
51
+ instead of starting an animation per node. (#90)
52
+
53
+ Checks: 320 tests in three time zones; every rule of the tree was broken on purpose and a test
54
+ failed each time (49 mutants; one more showed a check that could never fail, which was removed). The motion was
55
+ checked in Chromium: transitions on transform and on a link's path, and the grow-in keyframes,
56
+ interpolate as intended.
57
+
7
58
  ## 0.10.0 — 2026-11-17 — memory for the way dsh is used
8
59
 
9
60
  Cycle 4. Memory now works for every way dsh drives a chat, not only typed prompts: `/goal` rounds,
package/README.md CHANGED
@@ -147,7 +147,7 @@ Card: `3 topics indexed (2 new) · this chat has 7 topics`
147
147
  Lists the indexed chats newest first: chat id, start date, summary, topic count and flags (`this
148
148
  chat`, `memory on`, `shared`/`private`), each followed by its most connected topics with their ids.
149
149
  This is the text form of the graph, and it stays in the chat's log, so it stops at the newest 40
150
- chats and names how many more there are; the whole picture is on the plugin's page (see below).
150
+ chats and names how many more there are; Memory tree in the sidebar has them all (see below).
151
151
 
152
152
  ```
153
153
  2 chats in C:\Projects\site\.context-graph
@@ -166,17 +166,29 @@ are left out because they are already in its context.
166
166
 
167
167
  Card: `2 matching topics`, then `c3n12 builder timeout: ...` per line.
168
168
 
169
- ## The plugin's page
170
-
171
- Plugins → Context Graph shows, for each workspace with memory: what memory saved, what it cost and
172
- the balance, and a map of the memory. Chats are circles (newest first), topics are dots inside them
173
- coloured by kind (decision, fact, task, artifact, open question) and sized by their links, and
174
- links are lines. Hover a dot for its label, click it for its gist, its chat, its links, the first
175
- lines of its sources and the id to paste into a message (`c3n12`). Search and the kind buttons
176
- fade everything else; drag to move, + and − to zoom.
177
-
178
- It is your own view, so private and memory-off chats are shown and marked. The data comes from
179
- read-only routes dsh only answers for the app's owner; the page adds nothing to any chat.
169
+ ## Memory tree
170
+
171
+ **Memory tree** in the sidebar (under New Session, next to Automation tasks) opens the memory of a
172
+ workspace as a tree, root on the left: the workspace, its chats (newest first), each chat's topics
173
+ grouped by kind (decision, fact, task, artifact, open question), and the messages each topic came
174
+ from, with their turn ids. These are the same layers recall walks.
175
+
176
+ - **Open and close.** The newest chats start open while their topics fit 40 rows; a closed chat
177
+ shows how many topics it holds. Click a chat to open or close it. Click a topic to see its gist,
178
+ its chat, its links, its source messages and the id to paste into a message (`c3n12`), in a
179
+ panel beside the tree; the topic opens into its messages too. Click a chat for its dates, marks
180
+ and savings.
181
+ - **Find.** Search opens the chats it matches and fades the other topics; the kind buttons fade the
182
+ other kinds. Pointing at a node fades everything but its family: its ancestors, what it holds and
183
+ the topics it links to.
184
+ - **Keyboard.** Tab into the tree, then Up/Down to move, Right to open or step in, Left to close or
185
+ step out, Home/End, Enter or Space to open the details.
186
+ - **Motion.** What opens grows out of its parent and what moves eases to its place; nothing moves
187
+ when the system asks for reduced motion.
188
+
189
+ The plugin's page in Plugins shows what memory saved and cost in each workspace (see below). Both
190
+ are your own view, so private and memory-off chats are shown and marked. The data comes from
191
+ read-only routes dsh only answers for the app's owner; neither page adds anything to a chat.
180
192
 
181
193
  ## What memory saved
182
194
 
@@ -331,7 +343,7 @@ index.js package entry: re-exports the plugin from src/host/plugin.js
331
343
  src/core/ pure logic: tokenize, graph, matching, time, rendering, builder prompt and parser
332
344
  src/store/ files on disk: atomic JSON, chat folders, messages, upgrades from older versions
333
345
  src/host/ dsh wiring: builder, memory injection, recall tool, command, meter, update check
334
- src/client/ dsh chat card for /context-graph (DisclosureRow, en/zh titles)
346
+ src/client/ the browser module: the /context-graph card, the savings page in Plugins, the Memory tree page
335
347
  icon.svg Plugins page icon in dsh's built-in icon style
336
348
  locale/ Plugins page title and description (en, zh); zh links README.zh.md
337
349
  cordis.patch.yml mounts the plugin at the profile root with default config
@@ -370,11 +382,27 @@ Release: `npm test`, `npm version patch`, `npm publish`, `git push --follow-tags
370
382
  - Turn ids stored up to v0.9.0 count typed prompts; until the chat is indexed again or one of its
371
383
  topics is recalled, its sources name no turn.
372
384
  - The savings figure is an estimate (see [What memory saved](#what-memory-saved)); token counts are the plugin's own estimate, except indexing, which is what dsh reported. A subagent started fresh (not forked from the chat) is not charged the recall tool's share.
385
+ - Memory tree sizes each label from its letters, not from the font: a label of wide capitals can
386
+ run a little past its pill (the full text shows on hover). A tree showing more than 400 rows
387
+ draws what opens at once, without the motion.
373
388
  - A chat whose meta.json was damaged and whose off stretches could not be read back keeps its turns from before its next `on` closed to other chats (its topics still work), and forks made in that part start with memory off.
374
389
 
375
390
  Using Claude Code? The Claude version is a separate plugin built for Claude's app:
376
391
  [claude-context-graph](https://github.com/William20100221/claude-context-graph).
377
392
 
393
+ ## Credits
394
+
395
+ The Memory tree borrows techniques, not code, from projects that big companies publish under free
396
+ licences. Nothing was copied and no dependency was added; the plugin still ships without any.
397
+
398
+ | Technique | From | Licence |
399
+ |---|---|---|
400
+ | Tidy tree layout: one column per level, a parent centred on its children, siblings closer than cousins (Reingold-Tilford as improved by Buchheim et al.); horizontal link curves; branches that grow out of their parent when opened | [D3](https://d3js.org) (`d3-hierarchy`, `d3-shape`, the collapsible tree), Observable | ISC |
401
+ | Each column as wide as its widest node | [AntV G6](https://g6.antv.antgroup.com) compactBox layout, Ant Group | MIT |
402
+ | Only the first levels open at the start; fade everything but a node's family | [Apache ECharts](https://echarts.apache.org) tree series (`initialTreeDepth`, `emphasis.focus`), first built at Baidu | Apache-2.0 |
403
+ | Motion: 300 ms, emphasized easing for what moves, emphasized decelerate for what enters | [Material Design 3](https://m3.material.io/styles/motion/easing-and-duration/tokens-specs), Google | Apache-2.0 |
404
+ | Keyboard and roles: one tab stop, arrow keys, `tree` / `treeitem` with level, position, expanded and selected | [WAI-ARIA tree view pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/), W3C; Microsoft Fluent UI and GitHub Primer follow it too | W3C (pattern only) |
405
+
378
406
  ## Contributors
379
407
 
380
408
  - [William20100221](https://github.com/William20100221): author and maintainer
package/README.zh.md CHANGED
@@ -53,11 +53,18 @@ DeepSeek Harness 插件:给每个对话一张小型记忆图谱,安装后默
53
53
 
54
54
  **`build` — 立即索引。** 不等下一个 4 轮节点,适合在切换对话前运行。需要记忆已开启。很长的对话分几次读完,从最早的轮次开始,每条提问都会被索引。模型输出无法使用时,原始输出保存到该对话文件夹的 `last-builder-output.txt`;失败的那一段原样重试(被输出上限截断的,先重试前一半),连续三次失败只跳过那一段。
55
55
 
56
- **`map` — 工作区的全部对话。** 结果会留在会话日志里,所以只列出最新的 40 个,并注明还有多少个;完整的地图在插件页里。最新在前:对话编号、开始日期、摘要、主题数和标记(`this chat`、`memory on`、`shared`/`private`),下面列出各自连接最多的主题及编号。这是图谱的文字版;图形版在插件页里(见下)。
56
+ **`map` — 工作区的全部对话。** 结果会留在会话日志里,所以只列出最新的 40 个,并注明还有多少个;完整的树在侧边栏的“记忆树”里。最新在前:对话编号、开始日期、摘要、主题数和标记(`this chat`、`memory on`、`shared`/`private`),下面列出各自连接最多的主题及编号。这是图谱的文字版;图形版是侧边栏的“记忆树”(见下)。
57
57
 
58
- ### 插件页
58
+ ### 记忆树
59
59
 
60
- 插件 → 上下文图谱:每个有记忆的工作区里记忆节省了多少、花费了多少、净值,以及一张记忆地图。圆圈是对话(最新在前),圆圈里的点是主题,颜色表示类型(决定、事实、任务、产物、待定问题),大小表示连接数,线是主题之间的关系。鼠标停在点上看名称,点击查看要点、所属对话、相关主题、来源消息的开头和可以粘贴到消息里的编号(`c3n12`)。搜索和类型按钮会淡化其他内容;拖动移动,+ 和 − 缩放。这是你自己的视图,私有和关闭了记忆的对话也会显示并标出。数据来自只对本机主人开放的只读接口,不会往任何对话里加内容。
60
+ 侧边栏的 **记忆树**(在“新建会话”下面,和“自动化任务”在一起)把一个工作区的记忆画成一棵树,根在左边:工作区、它的对话(最新在前)、每个对话的主题(按类型分组:决定、事实、任务、产物、待定问题),以及每个主题来自的消息和它们的轮次编号。这就是 recall 一层层取回的那几层。
61
+
62
+ - **展开与收起。** 最新的几个对话一开始是展开的,直到主题占满 40 行;收起的对话会显示它有多少个主题。点击对话展开或收起。点击主题,旁边的面板会显示它的要点、所属对话、相关主题、来源消息和可以粘贴到消息里的编号(`c3n12`),这个主题也会展开出它的消息。点击对话可以看到它的日期、标记和节省。
63
+ - **查找。** 搜索会展开有匹配的对话并淡化其他主题;类型按钮会淡化其他类型。鼠标停在某个节点上时,除了它的“家族”(上级、下级和它关联的主题)以外都会淡化。
64
+ - **键盘。** 用 Tab 进入树,上下键移动,右键展开或进入,左键收起或回到上级,Home/End 到两端,Enter 或空格打开详情。
65
+ - **动效。** 展开的部分从上级节点里长出来,移动的部分平滑地移到新位置;系统要求减少动态效果时不做动画。
66
+
67
+ 插件 → 上下文图谱 这一页显示每个工作区里记忆节省和花费了多少。两个页面都是你自己的视图,私有和关闭了记忆的对话也会显示并标出。数据来自只对本机主人开放的只读接口,不会往任何对话里加内容。
61
68
 
62
69
  ### 记忆节省了多少(估算)
63
70
 
@@ -109,6 +116,19 @@ DeepSeek Harness 插件:给每个对话一张小型记忆图谱,安装后默
109
116
  - 工具输出不会被索引,也不在取回的整轮里(只有一行工具名称),批准的计划和你对模型提问的回答除外。
110
117
  - 区分“问以前的事”和日常聊天也是按词语判断:讲某天做过的事的日常请求(“找一个像昨晚那道咖喱的菜谱”)仍可能收到一小段当天摘要。
111
118
  - 在 dsh 的提醒管理器里(对话之外)修改的提醒内容,在记忆开启时触发,会像新输入一样被索引,即使修改发生在记忆关闭期间。
112
- - 记忆地图在插件页里;`/context-graph map` 是文字版。
119
+ - 记忆树按字母数估算标签宽度,不按实际字体:全是宽大写字母的标签可能略微超出它的圆角框(鼠标悬停可看全文)。树里显示超过 400 行时,新展开的部分直接出现,没有动画。`/context-graph map` 是文字版。
113
120
  - 节省数字是估算;新启动(不是从对话分叉)的子代理不计 recall 工具的份额。
114
121
  - 若某个对话的 meta.json 损坏、且记忆关闭的区段读不回来,它在下次 `on` 之前的轮次对其他对话保持关闭(主题仍可用),在这一段里分叉出的对话从记忆关闭开始。
122
+
123
+ ## 致谢
124
+
125
+ 记忆树借鉴的是做法,不是代码,来自大公司以免费许可发布的项目。没有复制代码,也没有增加依赖。
126
+
127
+ | 做法 | 来源 | 许可 |
128
+ |---|---|---|
129
+ | 整齐树布局:每层一列,上级居中于下级,同一上级的节点比不同上级的更近(Reingold-Tilford,经 Buchheim 等人改进);水平曲线连线;展开时分支从上级长出 | [D3](https://d3js.org)(`d3-hierarchy`、`d3-shape`、可折叠树示例),Observable | ISC |
130
+ | 每列的宽度等于该列最宽的节点 | [AntV G6](https://g6.antv.antgroup.com) compactBox 布局,蚂蚁集团 | MIT |
131
+ | 一开始只展开前几层;淡化节点家族以外的内容 | [Apache ECharts](https://echarts.apache.org) 树图(`initialTreeDepth`、`emphasis.focus`),最初由百度开发 | Apache-2.0 |
132
+ | 动效:300 毫秒,移动用 emphasized 缓动,出现用 emphasized decelerate | [Material Design 3](https://m3.material.io/styles/motion/easing-and-duration/tokens-specs),Google | Apache-2.0 |
133
+ | 键盘与角色:一个 Tab 停靠点、方向键、带层级、位置、展开和选中状态的 `tree` / `treeitem` | [WAI-ARIA 树视图模式](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/),W3C;微软 Fluent UI 和 GitHub Primer 也遵循它 | W3C(仅模式) |
134
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-graph",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "DeepSeek Harness plugin: memory graphs for every chat, on by default (switch the plugin off on the Plugins page to stop); other chats in the workspace recall exact past text by topic, chat or day, so fewer input tokens are re-sent",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",
@@ -1,11 +1,12 @@
1
1
  // The browser side of dsh-context-graph, hand-written in dsh's client-bundle format (no build step).
2
2
  // The shell loads this file as a plain script; `require` reaches only the shell's shared modules.
3
- // Two contributions:
3
+ // Three contributions:
4
4
  // - the chat card for `/context-graph`: dsh's own DisclosureRow, a one-line summary that opens
5
5
  // to the details;
6
- // - the plugin's page in Plugins (`plugins.bundle.config`, #35, #36): what memory saved and cost
7
- // in each workspace, and a map of the memory. Data comes from the host's owner-only routes
8
- // (src/host/page.js), already laid out, so this file only draws.
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).
9
10
  window.__ModuleLoader__.load({
10
11
  id: 'dsh-context-graph',
11
12
  factory: (require) => {
@@ -28,7 +29,10 @@ window.__ModuleLoader__.load({
28
29
  find: 'Find topics',
29
30
  running: 'Working…',
30
31
  failed: 'Failed',
31
- pageIntro: 'What memory saved and cost in each workspace, and a map of what it holds. Numbers marked as estimates follow the rule shown under them.',
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.',
32
36
  loading: 'Loading…',
33
37
  loadFailed: 'Could not read the memory. Try again in a moment.',
34
38
  retry: 'Retry',
@@ -46,7 +50,7 @@ window.__ModuleLoader__.load({
46
50
  zoomIn: 'Zoom in',
47
51
  zoomOut: 'Zoom out',
48
52
  resetView: 'Reset view',
49
- map_label: 'Map of the memory: chats as circles, topics inside them',
53
+ tree_label: 'The memory as a tree: the workspace, its chats, their topics',
50
54
  close: 'Close',
51
55
  copyId: 'Copy id',
52
56
  copied: 'Copied',
@@ -73,7 +77,10 @@ window.__ModuleLoader__.load({
73
77
  find: '查找主题',
74
78
  running: '处理中…',
75
79
  failed: '失败',
76
- pageIntro: '每个工作区里记忆节省和花费了多少,以及记忆里有什么。标为估算的数字按下面写明的规则计算。',
80
+ pageIntro: '每个工作区里记忆节省和花费了多少。标为估算的数字按下面写明的规则计算。',
81
+ treeHint: '记忆里有什么画成了一棵树:左侧边栏的“记忆树”。',
82
+ panel: '记忆树',
83
+ treeIntro: '每个工作区的记忆:它的对话、对话里的主题,以及每个主题来自哪些消息。',
77
84
  loading: '正在读取…',
78
85
  loadFailed: '无法读取记忆,请稍后再试。',
79
86
  retry: '重试',
@@ -91,7 +98,7 @@ window.__ModuleLoader__.load({
91
98
  zoomIn: '放大',
92
99
  zoomOut: '缩小',
93
100
  resetView: '还原视图',
94
- map_label: '记忆地图:圆圈是对话,圆圈里的点是主题',
101
+ tree_label: '记忆树:工作区、它的对话、对话里的主题',
95
102
  close: '关闭',
96
103
  copyId: '复制编号',
97
104
  copied: '已复制',
@@ -116,6 +123,13 @@ window.__ModuleLoader__.load({
116
123
  '.dshcg-summary[data-error]{color:var(--dsw-alias-state-error-primary,#d64545);opacity:1}',
117
124
  '.dshcg-body{padding:6px 0 6px 24px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word}',
118
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}',
119
133
  '.dshcg-muted{color:var(--dsw-alias-label-secondary)}',
120
134
  '.dshcg-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center}',
121
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}',
@@ -126,13 +140,32 @@ window.__ModuleLoader__.load({
126
140
  '.dshcg-big{font-size:18px;font-weight:600}',
127
141
  '.dshcg-good{color:var(--dsw-alias-state-success-primary,#2BA471)}',
128
142
  '.dshcg-bad{color:var(--dsw-alias-state-error-primary,#E5484D)}',
129
- '.dshcg-mapbox{position:relative;border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg,10px);background:var(--dsw-alias-bg-layer-1);overflow:hidden}',
130
- '.dshcg-map{display:block;width:100%;height:460px;touch-action:none;cursor:grab}',
131
- '.dshcg-chat{fill:none;stroke:var(--dsw-alias-border-l2)}',
132
- '.dshcg-chat-label{font-size:11px;fill:var(--dsw-alias-label-secondary)}',
133
- '.dshcg-edge{stroke:var(--dsw-alias-border-l2);stroke-width:1}',
134
- '.dshcg-topic{cursor:pointer;stroke:var(--dsw-alias-bg-layer-1);stroke-width:1}',
135
- '.dshcg-topic[data-dim="true"]{opacity:.15}',
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)}}',
136
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}',
137
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)}',
138
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}',
@@ -163,6 +196,27 @@ window.__ModuleLoader__.load({
163
196
  ]
164
197
  })
165
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
+
166
220
  const SUBCOMMANDS = ['stats', 'on', 'off', 'share', 'unshare', 'build', 'map', 'find']
167
221
 
168
222
  /** Title key from the typed arguments (`/context-graph on` -> on); no argument means stats. */
@@ -293,112 +347,349 @@ window.__ModuleLoader__.load({
293
347
  })
294
348
  }
295
349
 
296
- /** The map: drawn from the host's layout; drag to move, buttons to zoom, click a topic to open it. */
297
- function MemoryMap({ map, t, onOpen }) {
298
- const [query, setQuery] = useState('')
299
- const [kind, setKind] = useState('')
300
- const [view, setView] = useState({ x: 0, y: 0, scale: 1 })
301
- const [drag, setDrag] = useState(null)
302
- // The map box's height / width (460 px by the page's width), so the view has its proportions:
303
- // scale 1 is the layout's whole width, from its top row (the newest chats).
304
- const [aspect, setAspect] = useState(460 / 1000)
305
- const box = React.useRef(null)
306
- React.useEffect(() => {
307
- const observer = new ResizeObserver(([entry]) => {
308
- const { width: w, height: h } = entry.contentRect
309
- if (w > 0) setAspect(h / w) // 0 while the page is hidden
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
+ }
310
401
  })
311
- observer.observe(box.current)
312
- return () => observer.disconnect()
313
- }, [])
314
- const width = map.width / view.scale
315
- const height = width * aspect
316
- const q = query.trim().toLowerCase()
317
- const zoom = (factor) => setView((v) => ({ ...v, scale: Math.min(8, Math.max(0.5, v.scale * factor)) }))
318
- const pointer = {
319
- onPointerDown: (e) => setDrag({ x: e.clientX, y: e.clientY, view }),
320
- onPointerUp: () => setDrag(null),
321
- onPointerLeave: () => setDrag(null),
322
- onPointerMove: (e) => {
323
- if (!drag) return
324
- // Units per pixel: the box fits the view by its tighter side (either, once measured).
325
- const k = Math.max(width / (e.currentTarget.clientWidth || 1), height / (e.currentTarget.clientHeight || 1))
326
- setView({ ...drag.view, x: drag.view.x - (e.clientX - drag.x) * k, y: drag.view.y - (e.clientY - drag.y) * k })
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
327
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
328
457
  }
329
- const at = new Map(map.topics.map((p) => [`${p[0]}${p[1]}`, p]))
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 }) {
330
540
  return jsxs('div', {
331
- className: 'dshcg-page',
541
+ className: 'dshcg-row',
332
542
  children: [
333
- jsxs('div', {
334
- className: 'dshcg-row',
335
- children: [
336
- jsx('input', { className: 'dshcg-input', type: 'search', placeholder: t('search'), 'aria-label': t('search'), value: query, onChange: (e) => setQuery(e.target.value) }),
337
- jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': kind === '' ? 'true' : 'false', onClick: () => setKind(''), children: t('allKinds') }),
338
- ...KINDS.map((k) => jsxs('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': kind === k ? 'true' : 'false', onClick: () => setKind(kind === k ? '' : k), children: [jsx('span', { className: 'dshcg-dot', style: { background: COLORS[k] } }), t(k)] }, k)),
339
- jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-label': t('zoomIn'), onClick: () => zoom(1.4), children: '+' }),
340
- jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-label': t('zoomOut'), onClick: () => zoom(1 / 1.4), children: '−' }),
341
- jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => setView({ x: 0, y: 0, scale: 1 }), children: t('resetView') })
342
- ]
343
- }),
344
- jsx('div', {
345
- className: 'dshcg-mapbox',
346
- ref: box,
347
- children: jsxs('svg', {
348
- className: 'dshcg-map',
349
- role: 'img',
350
- 'aria-label': t('map_label'),
351
- viewBox: `${view.x} ${view.y} ${width} ${height}`,
352
- ...pointer,
353
- children: [
354
- ...map.edges.map(([cid, from, to], i) => {
355
- const a = at.get(`${cid}${from}`)
356
- const b = at.get(`${cid}${to}`)
357
- return a && b ? jsx('line', { className: 'dshcg-edge', x1: a[4], y1: a[5], x2: b[4], y2: b[5] }, `e${i}`) : null
358
- }),
359
- ...map.chats.map((c) => jsxs('g', {
360
- children: [
361
- jsx('title', { children: chatLabel(c, t) }),
362
- jsx('circle', { className: 'dshcg-chat', cx: c.x, cy: c.y, r: c.r }),
363
- // Cut to the chat's slot in its row (2r + 24 units, layout.js), about 6 units a letter at 11px.
364
- jsx('text', { className: 'dshcg-chat-label', x: c.x - c.r, y: c.y - c.r - 4, children: chatLabel(c, t, (2 * c.r + 24) / 6) })
365
- ]
366
- }, `c${c.cid}`)),
367
- ...map.topics.map(([cid, id, label, k, x, y, degree]) => {
368
- const dim = (kind && k !== kind) || (q && !String(label).toLowerCase().includes(q))
369
- return jsx('circle', {
370
- className: 'dshcg-topic',
371
- cx: x,
372
- cy: y,
373
- r: 4 + Math.min(5, degree),
374
- fill: COLORS[k] ?? '#888',
375
- 'data-dim': dim ? 'true' : 'false',
376
- tabIndex: 0,
377
- onClick: () => onOpen(`c${cid}${id}`),
378
- onKeyDown: (e) => { if (e.key === 'Enter') onOpen(`c${cid}${id}`) },
379
- children: jsx('title', { children: `c${cid}${id} ${label}` })
380
- }, `t${cid}${id}`)
381
- })
382
- ]
383
- })
384
- })
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') })
385
549
  ]
386
550
  })
387
551
  }
388
552
 
389
- /** The plugin's page in Plugins: one workspace at a time, its savings, then its map. */
390
- function MemoryPage(props) {
391
- const t = translator(props.t)
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) {
392
688
  const [state, setState] = useState({ status: 'loading' })
393
689
  const [key, setKey] = useState(null)
394
- const [map, setMap] = useState(null)
395
- const [detail, setDetail] = useState(null)
396
- // Answers can come back out of order (a slow map, then a quick one): requests of each kind are
397
- // numbered, and only the latest one's answer is taken.
398
- const asked = React.useRef({ map: 0, topic: 0 })
399
- const ask = (kind) => {
400
- const n = ++asked.current[kind]
401
- return (take) => (value) => { if (asked.current[kind] === n) take(value) }
690
+ const choose = (next) => {
691
+ setKey(next)
692
+ onChoose?.(next)
402
693
  }
403
694
  const load = () => {
404
695
  setState({ status: 'loading' })
@@ -408,47 +699,146 @@ window.__ModuleLoader__.load({
408
699
  if (first) choose(first.key)
409
700
  }, () => setState({ status: 'error' }))
410
701
  }
411
- const choose = (next) => {
412
- const latest = ask('map')
413
- ask('topic') // a topic still on its way was asked in the workspace being left
414
- setKey(next)
415
- setMap(null)
416
- setDetail(null)
417
- getJson('map', { w: next }).then(latest(setMap), latest(() => setMap({ error: true })))
418
- }
419
- const open = (id) => {
420
- const latest = ask('topic')
421
- // A topic that cannot be read says so instead of leaving the last one open (review).
422
- getJson('topic', { w: key, id }).then(latest(setDetail), latest(() => setDetail({ id, error: true })))
423
- }
424
- // Close also drops a topic still on its way, so a late answer cannot reopen the panel.
425
- const close = () => { ask('topic'); setDetail(null) }
426
702
  React.useEffect(load, [])
427
- if (state.status === 'loading') return jsx('div', { className: 'dshcg-page dshcg-muted', children: t('loading') })
428
- if (state.status === 'error') {
429
- return jsxs('div', { className: 'dshcg-page', children: [jsx('div', { className: 'dshcg-bad', children: t('loadFailed') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: load, children: t('retry') })] })
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') })] })
430
711
  }
431
- if (state.workspaces.length === 0) return jsx('div', { className: 'dshcg-page dshcg-muted', children: t('noWorkspaces') })
432
- const current = state.workspaces.find((w) => w.key === key)
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)
433
729
  return jsxs('div', {
434
730
  className: 'dshcg-page',
435
731
  children: [
436
732
  jsx('div', { className: 'dshcg-muted', children: t('pageIntro') }),
437
- state.workspaces.length > 1
438
- ? jsx('div', { className: 'dshcg-row', children: state.workspaces.map((w) => jsx('button', { type: 'button', className: 'dshcg-btn', 'aria-pressed': w.key === key ? 'true' : 'false', onClick: () => choose(w.key), children: `${w.title} · ${w.indexed} ${t('chats')} · ${w.topics} ${t('topics')}` }, w.key)) })
439
- : null,
733
+ workspaceButtons(ws, t),
440
734
  current ? jsx(Savings, { s: current.savings, t }) : null,
441
735
  jsx('div', { className: 'dshcg-muted', children: t('savingsRule') }),
442
- !map ? jsx('div', { className: 'dshcg-muted', children: t('loading') })
443
- : map.error ? jsxs('div', { className: 'dshcg-row', children: [jsx('div', { className: 'dshcg-bad', children: t('loadFailed') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: () => choose(key), children: t('retry') })] })
444
- : jsx(MemoryMap, { map, t, onOpen: open }),
445
- // Keyed by topic: another topic gets a new panel, not this one's buttons and Copied.
446
- detail?.error ? jsxs('div', { className: 'dshcg-row', children: [jsx('div', { className: 'dshcg-bad', children: t('topicFailed') }), jsx('button', { type: 'button', className: 'dshcg-btn', onClick: close, children: t('close') })] })
447
- : detail ? jsx(TopicPanel, { detail, t, onOpen: open, onClose: close }, detail.id) : null
736
+ jsx('div', { children: t('treeHint') })
448
737
  ]
449
738
  })
450
739
  }
451
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
+
452
842
  const inject = ['slots', 'locale']
453
843
  function apply(ctx) {
454
844
  ctx.effect(() => ctx.locale.register(NAMESPACE, { en, zh }), 'dsh-context-graph: dictionaries')
@@ -457,16 +847,32 @@ window.__ModuleLoader__.load({
457
847
  )
458
848
  // The plugin's own page in Plugins, keyed by the package name (rc.5 renders it with { view: 'page' }).
459
849
  ctx.slots.inject('plugins.bundle.config', () =>
460
- ctx.slots.register({ name: 'plugins.bundle.config', key: 'dsh-context-graph', locale: NAMESPACE }, MemoryPage)
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)
461
857
  )
462
858
  }
463
859
 
464
860
  exports.inject = inject
465
861
  exports.apply = apply
466
862
  exports.ContextGraphCard = ContextGraphCard
467
- exports.MemoryPage = MemoryPage
468
- exports.MemoryMap = MemoryMap
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
469
874
  exports.TopicPanel = TopicPanel
875
+ exports.ChatPanel = ChatPanel
470
876
  exports.subcommandOf = subcommandOf
471
877
  exports.splitText = splitText
472
878
  return module.exports
package/src/core/index.js CHANGED
@@ -11,4 +11,4 @@ export * from './render.js'
11
11
  export * from './builder.js'
12
12
  export * from './session.js'
13
13
  export * from './ledger.js'
14
- export * from './layout.js'
14
+ export * from './tree.js'
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The memory as the tree the Memory tree page draws (#86): a workspace's chats, newest first, each
3
+ * with its topics grouped by kind. Pure and deterministic; the page lays it out itself, because the
4
+ * layout changes as branches open and close.
5
+ */
6
+
7
+ import { degree } from './graph.js'
8
+
9
+ /** Kinds in the order a chat lists them, so each kind's colour forms one band. */
10
+ export const KINDS = ['decision', 'fact', 'task', 'artifact', 'open-question']
11
+
12
+ const kindRank = (kind) => {
13
+ const i = KINDS.indexOf(kind)
14
+ return i < 0 ? KINDS.length : i
15
+ }
16
+
17
+ /**
18
+ * @param chats [{ cid, lastActiveAt, graph }] the chats to draw
19
+ * @param maxTopics a chat's topics listed at most (the most connected); the rest are counted
20
+ * @returns [{ cid, total, topics: [[id, label, kind]], links: [[from, to]] }], newest chat first
21
+ */
22
+ export function memoryTree(chats, { maxTopics = 120 } = {}) {
23
+ const newest = [...chats].sort((a, b) => String(b.lastActiveAt ?? '').localeCompare(String(a.lastActiveAt ?? '')))
24
+ return newest.map((chat) => {
25
+ const { nodes, edges } = chat.graph
26
+ const ids = Object.keys(nodes)
27
+ .map((id) => ({ id, d: degree(chat.graph, id), u: String(nodes[id].updated ?? '') }))
28
+ .sort((a, b) => b.d - a.d || b.u.localeCompare(a.u))
29
+ .slice(0, maxTopics)
30
+ .sort((a, b) => kindRank(nodes[a.id].kind) - kindRank(nodes[b.id].kind) || b.d - a.d || b.u.localeCompare(a.u))
31
+ const kept = new Set(ids.map((t) => t.id))
32
+ return {
33
+ cid: chat.cid,
34
+ total: Object.keys(nodes).length,
35
+ topics: ids.map(({ id }) => [id, nodes[id].label, nodes[id].kind]),
36
+ links: edges.filter(([from, to]) => kept.has(from) && kept.has(to)).map(([from, to]) => [from, to])
37
+ }
38
+ })
39
+ }
@@ -95,7 +95,7 @@ export function registerCommand(ctx, rt, { build, turnOn, onAtIdle, meter, updat
95
95
  const all = await rt.loadViews(agent, { all: true })
96
96
  // dsh keeps the card's whole text in the chat's session log, at every call: the newest
97
97
  // chats only (loadViews keeps listChats' order, newest first), the page has the rest (#82).
98
- const more = all.length > MAP_MAX_CHATS ? `\n… ${plural(all.length - MAP_MAX_CHATS, 'more chat')}; Plugins → Context Graph has the full map` : ''
98
+ const more = all.length > MAP_MAX_CHATS ? `\n… ${plural(all.length - MAP_MAX_CHATS, 'more chat')}; Memory tree in the sidebar has them all` : ''
99
99
  return { kind: 'success', text: `${plural(all.length, 'chat')} in ${rt.dirFor(agent)}\n${renderMap(all.slice(0, MAP_MAX_CHATS))}${more}` }
100
100
  }
101
101
  const views = await rt.loadViews(agent)
package/src/host/page.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
- * The plugin's page in Plugins (#35, #36): read-only routes for the client module.
2
+ * Read-only routes for the client module: the savings on the plugin's page in Plugins (#35) and
3
+ * the Memory tree page (#85, #86).
3
4
  * GET api/context-graph.overview workspaces with memory: chats, topics, savings
4
- * GET api/context-graph.map?w=<key> one workspace, laid out: chats, topics, links
5
+ * GET api/context-graph.tree?w=<key> one workspace as a tree: chats, their topics, links (#86)
5
6
  * GET api/context-graph.topic?w=<key>&id=c3n12 one topic: gist, aliases, links, its sources
6
7
  *
7
8
  * Nested plugin with `inject: ['connection']`: it starts only where dsh's connection exists, and
@@ -17,7 +18,7 @@ import { isAbsolute, join } from 'node:path'
17
18
 
18
19
  import { memoryOn, sharedOn } from '../core/chat.js'
19
20
  import { has, neighbors } from '../core/graph.js'
20
- import { layoutMap } from '../core/layout.js'
21
+ import { memoryTree } from '../core/tree.js'
21
22
  import { addCounters, balance, counters, emptyCounters } from '../core/ledger.js'
22
23
  import { chatSummary } from '../core/render.js'
23
24
  import { chatDir, listChats, loadGraph } from '../store/chats.js'
@@ -46,7 +47,7 @@ export function registerPage(ctx, rt) {
46
47
  return out
47
48
  }
48
49
 
49
- /** The ledger, or none for this answer while it cannot be read (a sync tool holding it): chats and the map still load. */
50
+ /** The ledger, or none for this answer while it cannot be read (a sync tool holding it): chats and the tree still load. */
50
51
  const ledgerOf = (dir) => loadLedger(dir).catch((error) => {
51
52
  console.error(`context-graph: page reads no savings for ${dir} (${error?.code ?? error?.message})`)
52
53
  return { v: 1, chats: {}, unreadable: true }
@@ -90,7 +91,7 @@ export function registerPage(ctx, rt) {
90
91
  }
91
92
 
92
93
  /**
93
- * The chats the map draws, which are the chats the topic route opens: each needs topics and its
94
+ * The chats the tree draws, which are the chats the topic route opens: each needs topics and its
94
95
  * own number (a meta that could not be read has none until it is written again, and a copied
95
96
  * folder can repeat one: the first chat with topics keeps it).
96
97
  */
@@ -99,19 +100,17 @@ export function registerPage(ctx, rt) {
99
100
  return (await chatsOf(dir, options)).filter((c) => Number.isInteger(c.cid) && Object.keys(c.graph.nodes).length > 0 && !seen.has(c.cid) && seen.add(c.cid))
100
101
  }
101
102
 
102
- async function map(w) {
103
+ async function tree(w) {
103
104
  const chats = await drawn(w.dir)
104
- const layout = layoutMap(chats.map((c) => ({ cid: c.cid, lastActiveAt: c.meta.lastActiveAt, graph: c.graph })))
105
105
  const byCid = new Map(chats.map((c) => [c.cid, c]))
106
106
  return {
107
107
  key: w.key,
108
108
  title: w.title,
109
- width: layout.width,
110
- height: layout.height,
111
- chats: layout.chats.map((spot) => {
112
- const c = byCid.get(spot.cid)
109
+ // Labels only: gists and sources are fetched when a topic is opened.
110
+ chats: memoryTree(chats.map((c) => ({ cid: c.cid, lastActiveAt: c.meta.lastActiveAt, graph: c.graph }))).map((branch) => {
111
+ const c = byCid.get(branch.cid)
113
112
  return {
114
- ...spot,
113
+ ...branch,
115
114
  title: c.meta.title ?? '',
116
115
  summary: chatSummary({ meta: c.meta, graph: c.graph }),
117
116
  shared: sharedOn(c.meta),
@@ -121,13 +120,7 @@ export function registerPage(ctx, rt) {
121
120
  savings: c.unreadable ? null : balance(c.c),
122
121
  used: c.c.used
123
122
  }
124
- }),
125
- // Labels only: gists and sources are fetched when a topic is opened.
126
- topics: layout.topics.map((t) => {
127
- const node = byCid.get(t.cid).graph.nodes[t.id]
128
- return [t.cid, t.id, node.label, node.kind, t.x, t.y, t.degree]
129
- }),
130
- edges: layout.edges
123
+ })
131
124
  }
132
125
  }
133
126
 
@@ -181,7 +174,7 @@ export function registerPage(ctx, rt) {
181
174
  name: 'context-graph-page',
182
175
  inject: ['connection'],
183
176
  apply(pageCtx) {
184
- for (const r of [route('overview'), route('map', (w) => map(w)), route('topic', (w, q) => topic(w, q.get('id')))]) {
177
+ for (const r of [route('overview'), route('tree', (w) => tree(w)), route('topic', (w, q) => topic(w, q.get('id')))]) {
185
178
  pageCtx.effect(function* () {
186
179
  yield pageCtx.connection.fetch.register(r)
187
180
  }, `context-graph page: ${r.path}`)
@@ -189,5 +182,5 @@ export function registerPage(ctx, rt) {
189
182
  }
190
183
  })
191
184
 
192
- return { overview, map, topic, known }
185
+ return { overview, tree, topic, known }
193
186
  }
@@ -1,69 +0,0 @@
1
- /**
2
- * Where to draw the memory map (#36). Pure and deterministic, computed by the host so the browser
3
- * module only draws: the same memory always gives the same picture.
4
- *
5
- * Chats are circles packed in rows, newest first; a chat's topics sit on rings inside its circle,
6
- * the most connected nearest the centre. Units are SVG user units; the client scales the view.
7
- */
8
-
9
- import { degree } from './graph.js'
10
-
11
- const RING = 16
12
- const GAP = 24
13
- const WIDTH = 1400
14
-
15
- /** Positions of `count` topics on rings of growing size: ring k holds 6k topics at radius RING*k. */
16
- function rings(count) {
17
- const out = []
18
- for (let ring = 1; out.length < count; ring++) {
19
- const capacity = 6 * ring
20
- const here = Math.min(capacity, count - out.length)
21
- for (let i = 0; i < here; i++) {
22
- const angle = (2 * Math.PI * i) / here + ring * 0.6
23
- out.push({ x: Math.cos(angle) * RING * ring, y: Math.sin(angle) * RING * ring })
24
- }
25
- }
26
- return out
27
- }
28
-
29
- const ringCount = (count) => {
30
- let n = 0
31
- for (let ring = 1, held = 0; held < count; ring++) { held += 6 * ring; n = ring }
32
- return n
33
- }
34
-
35
- /**
36
- * @param chats [{ cid, lastActiveAt, graph }] the chats to draw
37
- * @param maxTopics a chat's most connected topics drawn at most; the rest are counted
38
- * @returns { width, height, chats: [{ cid, x, y, r, shown, total }],
39
- * topics: [{ cid, id, x, y, degree }], edges: [[cid, from, to, relation]] }
40
- */
41
- export function layoutMap(chats, { maxTopics = 120 } = {}) {
42
- const ordered = [...chats].sort((a, b) => String(b.lastActiveAt ?? '').localeCompare(String(a.lastActiveAt ?? '')))
43
- const out = { width: WIDTH, height: 0, chats: [], topics: [], edges: [] }
44
- let x = 0
45
- let y = 0
46
- let rowHeight = 0
47
- for (const chat of ordered) {
48
- const ids = Object.keys(chat.graph.nodes)
49
- .map((id) => ({ id, d: degree(chat.graph, id), u: String(chat.graph.nodes[id].updated ?? '') }))
50
- .sort((a, b) => b.d - a.d || b.u.localeCompare(a.u))
51
- const shown = ids.slice(0, maxTopics)
52
- const r = RING * (ringCount(shown.length) + 1)
53
- if (x > 0 && x + 2 * r > WIDTH) { x = 0; y += rowHeight + GAP; rowHeight = 0 }
54
- const cx = x + r
55
- const cy = y + r + 18
56
- out.chats.push({ cid: chat.cid, x: Math.round(cx), y: Math.round(cy), r, shown: shown.length, total: ids.length })
57
- const spots = rings(shown.length)
58
- const drawn = new Set()
59
- shown.forEach(({ id, d }, i) => {
60
- out.topics.push({ cid: chat.cid, id, x: Math.round(cx + spots[i].x), y: Math.round(cy + spots[i].y), degree: d })
61
- drawn.add(id)
62
- })
63
- for (const [from, to, relation] of chat.graph.edges) if (drawn.has(from) && drawn.has(to)) out.edges.push([chat.cid, from, to, relation])
64
- x += 2 * r + GAP
65
- rowHeight = Math.max(rowHeight, 2 * r + 18)
66
- }
67
- out.height = y + rowHeight
68
- return out
69
- }