@zhengxiantai/dsh-mindmap 0.0.0-stage → 0.7.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/lib/client.js ADDED
@@ -0,0 +1,2531 @@
1
+ /**
2
+ * dsh-mindmap — browser half.
3
+ *
4
+ * A `main` panel plus a sidebar entry. The panel renders every branch of the
5
+ * session tree as a mind map, auto-summarizes each branch through the host
6
+ * half, and offers the two actions that make a tree pleasant to learn with:
7
+ *
8
+ * - create a subtopic (fork at the current completed turn, then open it)
9
+ * - return to the parent (optionally carrying the subtopic summary back as
10
+ * a draft, so the parent learns the conclusion without the transcript)
11
+ *
12
+ * The browser bundle is authored directly in the module-loader format used by
13
+ * the other DSH client plugins, so the package needs no build step.
14
+ */
15
+ window.__ModuleLoader__.load({
16
+ id: 'dsh-mindmap',
17
+ factory: (require) => {
18
+ const module = { exports: {} }
19
+ const exports = module.exports
20
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
21
+
22
+ const React = require('react')
23
+ const h = React.createElement
24
+ const { useState, useEffect, useMemo, useRef, useCallback, useSyncExternalStore } = React
25
+
26
+ const NS = 'mindmap'
27
+ const PANEL_ID = 'mindmap'
28
+ const API = '/mindmap/api'
29
+
30
+ const NODE_W = 252
31
+ const NODE_H = 112
32
+ const GAP_X = 96
33
+ const GAP_Y = 18
34
+ const PAD = 56
35
+
36
+ /* ── stylesheet ─────────────────────────────────────────────────────── */
37
+
38
+ const CSS = `
39
+ .mm-root{--mm-accent:var(--dsw-alias-state-business-primary,#4d6bfe);--mm-card:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.06));--mm-border:var(--dsw-alias-border-l2,rgba(127,127,127,.24));--mm-border-strong:var(--dsw-alias-border-l3,rgba(127,127,127,.36));--mm-text:var(--dsw-alias-label-primary,#e8e8ec);--mm-sub:var(--dsw-alias-label-secondary,#b4b4bd);--mm-mute:var(--dsw-alias-label-tertiary,#8b8b95);--mm-hover:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));box-sizing:border-box;height:100%;min-height:0;color:var(--mm-text);font-size:13px;line-height:20px;display:flex;flex-direction:column;background:transparent;position:relative}
40
+ .mm-head{box-sizing:border-box;flex:none;align-items:center;gap:12px;min-height:56px;padding:10px 18px;border-bottom:.5px solid var(--mm-border);display:flex;flex-wrap:wrap}
41
+ .mm-headMain{flex-direction:column;gap:1px;min-width:0;display:flex}
42
+ .mm-headTitle{white-space:nowrap;font-size:15px;font-weight:600;line-height:22px}
43
+ .mm-headSub{white-space:nowrap;color:var(--mm-mute);font-size:12px;line-height:18px}
44
+ .mm-headActions{margin-left:auto;align-items:center;gap:6px;display:flex}
45
+ .mm-btn{box-sizing:border-box;height:28px;color:var(--mm-sub);cursor:pointer;white-space:nowrap;background:0 0;border:.5px solid var(--mm-border);border-radius:8px;align-items:center;gap:5px;padding:0 9px;font:inherit;font-size:12px;display:inline-flex}
46
+ .mm-btn:hover:not(:disabled){background:var(--mm-hover);color:var(--mm-text)}
47
+ .mm-btn:disabled{opacity:.45;cursor:default}
48
+ .mm-btn.primary{background:var(--mm-accent);border-color:transparent;color:#fff}
49
+ .mm-btn.primary:hover:not(:disabled){background:var(--mm-accent);color:#fff;filter:brightness(1.08)}
50
+ .mm-btn.icon{width:28px;justify-content:center;padding:0}
51
+ .mm-select{box-sizing:border-box;height:28px;max-width:240px;color:var(--mm-sub);background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.06));border:.5px solid var(--mm-border);border-radius:8px;outline:none;padding:0 8px;font:inherit;font-size:12px}
52
+ .mm-select:hover{color:var(--mm-text)}
53
+ .mm-select:focus{border-color:var(--mm-accent)}
54
+ .mm-body{min-height:0;flex:1;display:flex;position:relative}
55
+ .mm-canvas{min-width:0;flex:1;position:relative;overflow:hidden;cursor:grab;background-image:radial-gradient(circle,var(--mm-border) 1px,transparent 1.2px);background-size:24px 24px}
56
+ .mm-canvas[data-dragging=true]{cursor:grabbing}
57
+ .mm-canvas:focus{outline:none}
58
+ .mm-world{position:absolute;top:0;left:0;transform-origin:0 0;will-change:transform}
59
+ .mm-edges{position:absolute;top:0;left:0;overflow:visible;pointer-events:none}
60
+ .mm-edge{fill:none;stroke:var(--mm-mute);stroke-width:1.25;opacity:.7}
61
+ .mm-edge[data-active=true]{stroke:var(--mm-accent);stroke-width:1.75;opacity:1}
62
+ .mm-node{box-sizing:border-box;position:absolute;width:252px;height:112px;padding:11px 13px 10px;border-radius:12px;border:.5px solid var(--mm-border-strong);background:var(--mm-card);text-align:left;cursor:pointer;display:flex;flex-direction:column;gap:5px;overflow:hidden;transition:border-color .12s,box-shadow .12s,background .12s}
63
+ .mm-node:hover{background:color-mix(in srgb,var(--mm-card) 82%,var(--mm-hover))}
64
+ .mm-node[data-selected=true]{border-color:var(--mm-accent);box-shadow:0 0 0 1px var(--mm-accent),0 6px 22px rgba(0,0,0,.18)}
65
+ .mm-node[data-current=true]:before{content:"";position:absolute;left:0;top:14px;bottom:14px;width:3px;border-radius:0 3px 3px 0;background:var(--mm-accent)}
66
+ .mm-nodeTop{align-items:center;gap:6px;min-width:0;display:flex}
67
+ .mm-nodeTitle{min-width:0;flex:1;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:600;line-height:19px;overflow:hidden}
68
+ .mm-dot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--mm-mute)}
69
+ .mm-dot[data-running=true]{background:#22c55e;box-shadow:0 0 0 3px rgba(34,197,94,.18);animation:mm-pulse 1.6s ease-in-out infinite}
70
+ .mm-nodeSummary{color:var(--mm-sub);-webkit-line-clamp:2;-webkit-box-orient:vertical;font-size:12px;line-height:17px;display:-webkit-box;overflow:hidden;flex:1}
71
+ .mm-nodeSummary[data-empty=true]{color:var(--mm-mute);font-style:italic}
72
+ .mm-nodeMeta{margin-top:auto;color:var(--mm-mute);align-items:center;gap:6px;font-size:11px;line-height:16px;display:flex}
73
+ .mm-nodeMeta .mm-spacer{flex:1}
74
+ .mm-badge{color:var(--mm-mute);border:.5px solid var(--mm-border);border-radius:5px;padding:0 4px;font-size:10px;line-height:15px}
75
+ .mm-badge[data-kind=current]{color:var(--mm-accent);border-color:color-mix(in srgb,var(--mm-accent) 45%,transparent)}
76
+ .mm-badge[data-kind=degraded]{color:#d97706;border-color:rgba(217,119,6,.4)}
77
+ .mm-nodeTools{opacity:0;position:absolute;top:6px;right:6px;align-items:center;gap:2px;display:flex;transition:opacity .12s}
78
+ .mm-node:hover .mm-nodeTools,.mm-node:focus-within .mm-nodeTools,.mm-node[data-selected=true] .mm-nodeTools{opacity:1}
79
+ .mm-nodeTool{width:22px;height:22px;color:var(--mm-sub);cursor:pointer;background:var(--mm-card);border:.5px solid var(--mm-border);border-radius:6px;justify-content:center;align-items:center;padding:0;font:inherit;font-size:13px;line-height:1;display:inline-flex}
80
+ .mm-nodeTool:hover{color:var(--mm-text);background:var(--mm-hover)}
81
+ .mm-drawer{box-sizing:border-box;width:336px;flex:none;border-left:.5px solid var(--mm-border);background:var(--dsw-alias-bg-layer-2,var(--mm-card));flex-direction:column;min-height:0;display:flex;overflow:auto}
82
+ .mm-drawerHead{position:sticky;top:0;z-index:2;background:inherit;border-bottom:.5px solid var(--mm-border);align-items:flex-start;gap:8px;padding:14px 14px 12px;display:flex}
83
+ .mm-drawerTitle{margin:0;flex:1;overflow-wrap:anywhere;font-size:14px;font-weight:600;line-height:20px}
84
+ .mm-drawerBody{flex-direction:column;gap:14px;padding:14px;display:flex}
85
+ .mm-kicker{color:var(--mm-mute);letter-spacing:.04em;text-transform:uppercase;font-size:10.5px;font-weight:600;line-height:16px}
86
+ .mm-summary{color:var(--mm-sub);white-space:pre-wrap;margin:0;font-size:12.5px;line-height:19px}
87
+ .mm-emptyLine{color:var(--mm-mute);margin:0;font-size:12px;font-style:italic;line-height:18px}
88
+ .mm-openList{margin:0;padding-left:18px;color:var(--mm-sub);font-size:12px;line-height:18px}
89
+ .mm-openList li{margin:2px 0}
90
+ .mm-actions{flex-wrap:wrap;gap:6px;display:flex}
91
+ .mm-facts{margin:0;flex-direction:column;gap:0;display:flex}
92
+ .mm-fact{border-bottom:.5px solid var(--mm-border);justify-content:space-between;align-items:baseline;gap:12px;padding:6px 0;display:flex}
93
+ .mm-fact:last-child{border-bottom:0}
94
+ .mm-fact dt{color:var(--mm-mute);flex:none;font-size:11.5px}
95
+ .mm-fact dd{text-align:right;overflow-wrap:anywhere;margin:0;font-size:11.5px}
96
+ .mm-code{font-family:var(--dsw-font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:11px}
97
+ .mm-empty{text-align:center;flex:1;justify-content:center;align-items:center;gap:8px;padding:32px;display:flex;flex-direction:column}
98
+ .mm-emptyTitle{margin:0;font-size:15px;font-weight:600}
99
+ .mm-emptyText{max-width:380px;color:var(--mm-mute);margin:0;font-size:12.5px;line-height:19px}
100
+ .mm-error{border:.5px solid rgba(239,68,68,.35);border-radius:8px;background:rgba(239,68,68,.08);color:var(--dsw-alias-state-error-primary,#ef4444);margin:10px 18px 0;padding:8px 10px;font-size:12px;line-height:18px}
101
+ .mm-overlay{z-index:1000;background:rgba(0,0,0,.42);justify-content:center;align-items:center;padding:24px;display:flex;position:fixed;inset:0}
102
+ .mm-modal{box-sizing:border-box;width:min(480px,100%);max-height:min(86vh,720px);overflow:auto;background:var(--dsw-alias-bg-layer-1,#1c1c20);border:.5px solid var(--mm-border-strong);border-radius:14px;box-shadow:0 24px 70px rgba(0,0,0,.42);flex-direction:column;gap:12px;padding:18px;display:flex}
103
+ .mm-modalTitle{margin:0;font-size:15px;font-weight:600;line-height:22px}
104
+ .mm-modalText{color:var(--mm-mute);margin:0;font-size:12px;line-height:18px}
105
+ .mm-input{box-sizing:border-box;width:100%;min-height:96px;resize:vertical;color:var(--mm-text);background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.08));border:.5px solid var(--mm-border-strong);border-radius:10px;outline:none;padding:10px 12px;font:inherit;font-size:13px;line-height:20px}
106
+ .mm-input:focus{border-color:var(--mm-accent);box-shadow:inset 0 0 0 .5px var(--mm-accent)}
107
+ .mm-renameInput{min-height:40px;height:40px;resize:none;font-size:13px}
108
+ .mm-modes{flex-direction:column;gap:6px;display:flex}
109
+ .mm-mode{box-sizing:border-box;cursor:pointer;border:.5px solid var(--mm-border);border-radius:10px;align-items:flex-start;gap:9px;padding:9px 11px;display:flex}
110
+ .mm-mode[data-active=true]{border-color:var(--mm-accent);background:color-mix(in srgb,var(--mm-accent) 8%,transparent)}
111
+ .mm-mode input{margin:3px 0 0;accent-color:var(--mm-accent)}
112
+ .mm-modeMain{flex-direction:column;gap:1px;min-width:0;display:flex}
113
+ .mm-modeTitle{font-size:12.5px;font-weight:600;line-height:18px}
114
+ .mm-modeHint{color:var(--mm-mute);font-size:11.5px;line-height:17px}
115
+ .mm-modalFoot{justify-content:flex-end;align-items:center;gap:8px;display:flex}
116
+ .mm-modal.wide{width:min(680px,100%)}
117
+ .mm-turnsHead{display:flex;align-items:center;justify-content:space-between;gap:8px}
118
+ .mm-turns{flex-direction:column;gap:8px;max-height:56vh;display:flex;overflow:auto;padding-right:2px}
119
+ .mm-turn{border:.5px solid var(--mm-border);border-radius:10px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1,#1c1c20) 55%,transparent);padding:9px 11px}
120
+ .mm-turnHead{flex-wrap:wrap;align-items:center;gap:8px;display:flex}
121
+ .mm-turnIndex{font-size:12px;font-weight:600;line-height:18px}
122
+ .mm-turnTime{color:var(--mm-mute);margin-right:auto;font-size:11px;line-height:17px}
123
+ .mm-turnText{text-overflow:ellipsis;margin-top:5px;font-size:12px;line-height:18px;overflow:hidden}
124
+ .mm-turnSub{color:var(--mm-mute);text-overflow:ellipsis;margin-top:3px;font-size:11.5px;line-height:17px;overflow:hidden}
125
+ .mm-toast{z-index:1200;position:fixed;left:50%;bottom:26px;transform:translateX(-50%);background:var(--dsw-alias-bg-layer-3,#26262b);border:.5px solid var(--mm-border-strong);border-radius:9px;box-shadow:0 10px 30px rgba(0,0,0,.28);color:var(--mm-text);max-width:min(560px,90vw);padding:9px 14px;font-size:12.5px;line-height:18px}
126
+ .mm-spin{width:12px;height:12px;border:1.5px solid color-mix(in srgb,var(--mm-mute) 40%,transparent);border-top-color:var(--mm-sub);border-radius:50%;display:inline-block;animation:mm-spin .8s linear infinite}
127
+ @keyframes mm-spin{to{transform:rotate(360deg)}}
128
+ @keyframes mm-pulse{0%,to{opacity:1}50%{opacity:.45}}
129
+ .mm-mode[data-active=true]{color:var(--mm-text);border-color:color-mix(in srgb,var(--mm-accent) 55%,var(--mm-border));background:color-mix(in srgb,var(--mm-accent) 9%,transparent)}
130
+ .mm-cta{z-index:24;position:absolute;left:50%;bottom:20px;transform:translateX(-50%);box-shadow:0 10px 28px rgba(0,0,0,.24);white-space:nowrap;background:var(--mm-accent);border:0;border-radius:999px;color:#fff;cursor:pointer;align-items:center;gap:8px;padding:8px 16px;font:inherit;font-size:12.5px;font-weight:600;display:inline-flex}
131
+ .mm-cta:hover{filter:brightness(1.08)}
132
+ .mm-cta kbd{background:#ffffff2b;border-radius:5px;padding:1px 5px;font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:10.5px;font-weight:500}
133
+ .mm-float{z-index:35;box-sizing:border-box;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1,#1c1c20) 62%,transparent);backdrop-filter:blur(24px) saturate(1.3);-webkit-backdrop-filter:blur(24px) saturate(1.3);border:.5px solid color-mix(in srgb,var(--mm-border-strong) 70%,transparent);border-radius:16px;box-shadow:0 30px 90px rgba(0,0,0,.42),inset 0 1px 0 #ffffff1f;flex-direction:column;min-width:400px;min-height:280px;display:flex;position:absolute;overflow:hidden}
134
+ @supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.mm-float{background:var(--dsw-alias-bg-layer-1,#1c1c20)}}
135
+ .mm-float[data-minimized=true]{min-height:0;height:auto!important}
136
+ .mm-float[data-minimized=true] .mm-floatBody,.mm-float[data-minimized=true] .mm-resize{display:none}
137
+ .mm-floatHead{cursor:grab;touch-action:none;-webkit-app-region:no-drag;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1,#1c1c20) 38%,transparent);flex:none;align-items:center;gap:8px;height:40px;padding:0 8px 0 13px;border-bottom:.5px solid var(--mm-border);display:flex;user-select:none}
138
+ .mm-floatHead:active{cursor:grabbing}
139
+ .mm-floatTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;font-size:12.5px;font-weight:600}
140
+ .mm-floatTools{flex:none;align-items:center;gap:2px;display:flex}
141
+ .mm-floatTool{width:26px;height:26px;color:var(--mm-sub);cursor:pointer;background:0 0;border:0;border-radius:6px;justify-content:center;align-items:center;padding:0;font:inherit;font-size:14px;line-height:1;display:inline-flex}
142
+ .mm-floatTool:hover{background:var(--mm-hover);color:var(--mm-text)}
143
+ .mm-floatBody{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
144
+ .mm-floatChat{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
145
+ .mm-floatChat>[data-conversation-content]{flex:1;min-height:0}
146
+ .mm-floatFallback{color:var(--mm-sub);flex:1;justify-content:center;align-items:center;gap:10px;padding:24px;display:flex;flex-direction:column;text-align:center}
147
+ .mm-floatFallback p{margin:0;font-size:12.5px;line-height:19px}
148
+ .mm-resize{z-index:4;background:transparent;position:absolute;touch-action:none}
149
+ .mm-resize[data-dir=n]{top:0;left:14px;right:14px;height:8px;cursor:ns-resize}
150
+ .mm-resize[data-dir=s]{bottom:0;left:14px;right:14px;height:8px;cursor:ns-resize}
151
+ .mm-resize[data-dir=w]{top:14px;bottom:14px;left:0;width:8px;cursor:ew-resize}
152
+ .mm-resize[data-dir=e]{top:14px;bottom:14px;right:0;width:8px;cursor:ew-resize}
153
+ .mm-resize[data-dir=nw],.mm-resize[data-dir=ne],.mm-resize[data-dir=sw],.mm-resize[data-dir=se]{width:16px;height:16px}
154
+ .mm-resize[data-dir=nw]{top:0;left:0;cursor:nwse-resize}
155
+ .mm-resize[data-dir=ne]{top:0;right:0;cursor:nesw-resize}
156
+ .mm-resize[data-dir=sw]{bottom:0;left:0;cursor:nesw-resize}
157
+ .mm-resize[data-dir=se]{bottom:0;right:0;cursor:nwse-resize}
158
+ .mm-resize[data-dir=se]:after{content:"";border-right:2px solid var(--mm-border-strong);border-bottom:2px solid var(--mm-border-strong);border-radius:0 0 3px 0;width:7px;height:7px;position:absolute;bottom:4px;right:4px;opacity:.65}
159
+ @media (max-width:900px){.mm-drawer{box-sizing:border-box;z-index:20;background:var(--dsw-alias-bg-layer-1,#1c1c20);border-left:.5px solid var(--mm-border-strong);position:absolute;top:0;right:0;bottom:0;box-shadow:-18px 0 50px rgba(0,0,0,.28)}.mm-float{min-width:0;left:8px!important;right:8px;width:auto!important}}
160
+ @media (prefers-reduced-motion:reduce){.mm-dot,.mm-spin{animation:none}.mm-node,.mm-nodeTools{transition:none}}
161
+ `
162
+ const STYLE_ID = 'dsh-mindmap/styles.css'
163
+ if (typeof document !== 'undefined' && document.querySelector(`style[data-plugin-css="${STYLE_ID}"]`) === null) {
164
+ const style = document.createElement('style')
165
+ style.dataset.plugin = 'dsh-mindmap'
166
+ style.dataset.pluginCss = STYLE_ID
167
+ style.textContent = CSS
168
+ document.head.appendChild(style)
169
+ }
170
+
171
+ /* ── dictionary ─────────────────────────────────────────────────────── */
172
+
173
+ const zh = {
174
+ panel: '话题地图',
175
+ title: '话题地图',
176
+ subtitle: '{n} 个话题 · {running} 个进行中',
177
+ emptyTitle: '还没有可显示的话题',
178
+ emptyText: '先开始一段对话,或在侧边栏新建会话。之后每次「插入子话题」都会在这里长出一根新枝。',
179
+ fit: '适配视图',
180
+ zoomIn: '放大',
181
+ zoomOut: '缩小',
182
+ expandAll: '展开全部',
183
+ collapseAll: '收起全部',
184
+ showSubagents: '显示子代理',
185
+ refreshAll: '总结全部',
186
+ refreshOne: '重新总结',
187
+ summarizing: '总结中…',
188
+ noSummary: '尚未总结',
189
+ open: '打开对话',
190
+ openFloat: '浮窗对话',
191
+ rename: '重命名',
192
+ renameTitle: '重命名话题',
193
+ renameHint: '会同步修改左侧栏和思维导图中的会话标题。',
194
+ renamePlaceholder: '输入新的会话标题',
195
+ renameRequired: '标题不能为空',
196
+ renamed: '已重命名',
197
+ renameFailed: '重命名失败',
198
+ save: '保存',
199
+ saving: '保存中…',
200
+ newChild: '新子话题',
201
+ childDraft: '子话题草稿',
202
+ briefBranch: '轻量子话题',
203
+ viewChat: '查看对话',
204
+ newChildHint: '在浮窗中输入并在发送后生成子节点',
205
+ floatToggle: '浮窗',
206
+ askChild: '提问新子话题',
207
+ deleteSession: '删除/归档会话',
208
+ archiveTitle: '归档这个会话?',
209
+ archiveText: '它会从侧边栏和话题地图中移除;会话日志仍保留,可在归档中恢复。若正在运行,会先停止。子话题会保留。',
210
+ archive: '归档',
211
+ archiving: '归档中…',
212
+ archived: '已归档',
213
+ archiveFailed: '归档失败',
214
+ turnsTitle: '轮次',
215
+ turnsEmpty: '这个节点还没有可回退的轮次',
216
+ turnN: '第 {n} 轮',
217
+ rewindTitle: '从此轮重开',
218
+ rewindHint: '会创建一个新节点,只继承这一轮之前的历史;这一轮及之后都不会进入新节点。旧节点会归档(可恢复)。',
219
+ rewindAction: '创建回退节点',
220
+ rewindConfirm: '从第 {n} 轮重开并归档旧节点?',
221
+ rewound: '已创建回退节点,旧节点已归档',
222
+ rewindFailed: '回退失败',
223
+ rewindArchiveFailed: '回退节点已创建,但旧节点归档失败',
224
+ hostStale: 'Host 半侧仍是旧版本,缺少 /mindmap/api/turns。请完全退出并重启 DSH 后再试。',
225
+ floatOpen: '在浮窗中打开',
226
+ floatFull: '在主页打开',
227
+ floatClose: '关闭浮窗',
228
+ floatMinimize: '最小化',
229
+ floatRestore: '还原',
230
+ floatResize: '拖动边缘或角调整大小',
231
+ floatUnavailable: '当前 DSH 版本不支持嵌入式会话,请在主页打开',
232
+ floatFallback: '浮窗加载失败,请在主页打开',
233
+ floatBlank: '这是新会话,在主页打开后开始对话',
234
+ floatShortcut: 'Ctrl+Shift+M',
235
+ floatHint: '选中节点后按 Ctrl+Shift+M 新建子话题浮窗',
236
+ mapHome: '地图主区',
237
+ mapHomeHint: '开启后,左栏选择会话只会载入地图,不再切换主面板',
238
+ fullOpen: '完整会话',
239
+ branch: '新建子话题',
240
+ backToParent: '回到父话题',
241
+ backToRoot: '回到根话题',
242
+ bridge: '把结论带回父话题',
243
+ copy: '复制概要',
244
+ copied: '概要已复制',
245
+ current: '当前',
246
+ root: '根话题',
247
+ degraded: '离线概要',
248
+ turns: '{n} 轮',
249
+ steps: '{n} 步',
250
+ turnsLabel: '轮次',
251
+ stepsLabel: '步骤',
252
+ justNow: '刚刚',
253
+ minutesAgo: '{n} 分钟前',
254
+ hoursAgo: '{n} 小时前',
255
+ daysAgo: '{n} 天前',
256
+ branchTitle: '从「{name}」生长一个子话题',
257
+ branchHint: '子话题会从当前话题的最后一个完整轮次分叉;之后回到父话题时,父话题不会带上子话题的对话内容。',
258
+ question: '你想深入的问题',
259
+ questionPlaceholder: '例如:为什么这个协议需要三次握手?',
260
+ modeInherit: '继承当前上下文',
261
+ modeInheritHint: '子话题从父话题的完整讨论继续,适合顺着当前思路深入。',
262
+ modeBrief: '只带摘要',
263
+ modeBriefHint: '子话题只收到一段父话题摘要和你的问题,上下文最小,适合跳出去查一个独立概念。',
264
+ create: '创建并打开',
265
+ cancel: '取消',
266
+ creating: '创建中…',
267
+ created: '子话题已创建,在输入框写下你的问题即可开始',
268
+ branchFailed: '创建子话题失败',
269
+ openFailed: '打开会话失败',
270
+ noTurn: '当前话题还没有完整的一轮对话,先聊一轮再来分支',
271
+ questionRequired: '请先写下要讨论的问题',
272
+ summaryFailed: '总结失败,稍后重试',
273
+ fetchFailed: '话题摘要服务不可用,请刷新页面重试',
274
+ carry: '已把「{name}」的结论放进父话题的输入框',
275
+ carryFailed: '没有可带回的结论,先总结这个话题',
276
+ openHint: '双击话题卡片也可以打开对话',
277
+ sessionId: '会话 ID',
278
+ workspace: '工作目录',
279
+ updated: '最近活动',
280
+ parent: '父话题',
281
+ children: '直接子话题',
282
+ openQuestions: '待探索',
283
+ overview: '概要',
284
+ details: '详情',
285
+ close: '关闭',
286
+ selectHint: '选择一个话题查看详情',
287
+ summarizingCount: '{n} 个话题总结中',
288
+ allFresh: '所有话题都已总结',
289
+ }
290
+
291
+ const en = {
292
+ panel: 'Topic map',
293
+ title: 'Topic map',
294
+ subtitle: '{n} topics · {running} running',
295
+ emptyTitle: 'No topics yet',
296
+ emptyText: 'Start a conversation, or create a session from the sidebar. Every “New subtopic” grows a new branch here.',
297
+ fit: 'Fit view',
298
+ zoomIn: 'Zoom in',
299
+ zoomOut: 'Zoom out',
300
+ expandAll: 'Expand all',
301
+ collapseAll: 'Collapse all',
302
+ showSubagents: 'Show subagents',
303
+ refreshAll: 'Summarize all',
304
+ refreshOne: 'Summarize again',
305
+ summarizing: 'Summarizing…',
306
+ noSummary: 'Not summarized yet',
307
+ open: 'Open conversation',
308
+ openFloat: 'Floating chat',
309
+ rename: 'Rename',
310
+ renameTitle: 'Rename topic',
311
+ renameHint: 'This updates the session title in the left sidebar and on the mind map.',
312
+ renamePlaceholder: 'Enter a new session title',
313
+ renameRequired: 'Title cannot be empty',
314
+ renamed: 'Renamed',
315
+ renameFailed: 'Rename failed',
316
+ save: 'Save',
317
+ saving: 'Saving…',
318
+ newChild: 'New subtopic',
319
+ childDraft: 'Subtopic draft',
320
+ briefBranch: 'Light subtopic',
321
+ viewChat: 'View conversation',
322
+ newChildHint: 'Type in the floating window; sending creates a child node',
323
+ floatToggle: 'Float',
324
+ askChild: 'Ask as a subtopic',
325
+ deleteSession: 'Delete / archive session',
326
+ archiveTitle: 'Archive this session?',
327
+ archiveText: 'It will disappear from the sidebar and the map. The session log is kept and can be restored from the archive. Running work is stopped first. Child topics are kept.',
328
+ archive: 'Archive',
329
+ archiving: 'Archiving…',
330
+ archived: 'Archived',
331
+ archiveFailed: 'Archive failed',
332
+ turnsTitle: 'Turns',
333
+ turnsEmpty: 'No turns available to rewind in this node',
334
+ turnN: 'Turn {n}',
335
+ rewindTitle: 'Restart from this turn',
336
+ rewindHint: 'Creates a new node with only the history before this turn. This turn and everything after it are left out. The old node is archived (recoverable).',
337
+ rewindAction: 'Create rewound node',
338
+ rewindConfirm: 'Restart from turn {n} and archive the old node?',
339
+ rewound: 'Rewound node created; the old node was archived',
340
+ rewindFailed: 'Rewind failed',
341
+ rewindArchiveFailed: 'Rewound node created, but the old node could not be archived',
342
+ hostStale: 'The Host half is still an older build without /mindmap/api/turns. Fully quit and restart DSH, then retry.',
343
+ floatOpen: 'Open in floating window',
344
+ floatFull: 'Open in main view',
345
+ floatClose: 'Close floating window',
346
+ floatMinimize: 'Minimize',
347
+ floatRestore: 'Restore',
348
+ floatResize: 'Drag an edge or corner to resize',
349
+ floatUnavailable: 'This DSH version cannot embed the conversation; open it in the main view',
350
+ floatFallback: 'The floating conversation failed to load; open it in the main view',
351
+ floatBlank: 'New session: open it in the main view to start chatting',
352
+ floatShortcut: 'Ctrl+Shift+M',
353
+ floatHint: 'Select a topic and press Ctrl+Shift+M to start a subtopic float',
354
+ mapHome: 'Map home',
355
+ mapHomeHint: 'When on, choosing a session in the sidebar loads the map instead of switching the main panel',
356
+ fullOpen: 'Full conversation',
357
+ branch: 'New subtopic',
358
+ backToParent: 'Back to parent',
359
+ backToRoot: 'Back to root',
360
+ bridge: 'Carry conclusion to parent',
361
+ copy: 'Copy summary',
362
+ copied: 'Summary copied',
363
+ current: 'Current',
364
+ root: 'Root',
365
+ degraded: 'Offline summary',
366
+ turns: '{n} turns',
367
+ steps: '{n} steps',
368
+ turnsLabel: 'Turns',
369
+ stepsLabel: 'Steps',
370
+ justNow: 'just now',
371
+ minutesAgo: '{n} min ago',
372
+ hoursAgo: '{n} h ago',
373
+ daysAgo: '{n} d ago',
374
+ branchTitle: 'Grow a subtopic from “{name}”',
375
+ branchHint: 'The subtopic forks at the last completed turn. When you come back, the parent keeps no transcript from the child.',
376
+ question: 'What do you want to explore?',
377
+ questionPlaceholder: 'e.g. Why does this protocol need a three-way handshake?',
378
+ modeInherit: 'Inherit current context',
379
+ modeInheritHint: 'The child continues from the full discussion — best for drilling into the current thread.',
380
+ modeBrief: 'Brief only',
381
+ modeBriefHint: 'The child receives only a parent summary and your question — smallest context, best for an independent concept.',
382
+ create: 'Create and open',
383
+ cancel: 'Cancel',
384
+ creating: 'Creating…',
385
+ created: 'Subtopic created. Type your question to begin',
386
+ branchFailed: 'Could not create the subtopic',
387
+ openFailed: 'Could not open the session',
388
+ noTurn: 'This topic has no completed turn yet; chat one round before branching',
389
+ questionRequired: 'Write the question first',
390
+ summaryFailed: 'Summarization failed, try again later',
391
+ fetchFailed: 'Summary service is unavailable; reload the page and retry',
392
+ carry: 'Put the conclusion of “{name}” into the parent draft',
393
+ carryFailed: 'Nothing to carry yet — summarize this topic first',
394
+ openHint: 'Double-click a card to open its conversation',
395
+ sessionId: 'Session id',
396
+ workspace: 'Workspace',
397
+ updated: 'Last activity',
398
+ parent: 'Parent',
399
+ children: 'Direct children',
400
+ openQuestions: 'To explore',
401
+ overview: 'Overview',
402
+ details: 'Details',
403
+ close: 'Close',
404
+ selectHint: 'Select a topic to see its details',
405
+ summarizingCount: '{n} topics summarizing',
406
+ allFresh: 'Everything is summarized',
407
+ }
408
+
409
+ function interpolate(text, vars) {
410
+ if (vars === undefined) return text
411
+ return text.replace(/\{(\w+)\}/g, (match, key) => (vars[key] === undefined ? match : String(vars[key])))
412
+ }
413
+
414
+ function makeT(dict) {
415
+ return (key, vars) => interpolate(dict[key] ?? key, vars)
416
+ }
417
+
418
+ const FALLBACK_T = makeT(zh)
419
+
420
+ /* ── tiny utilities ─────────────────────────────────────────────────── */
421
+
422
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
423
+
424
+ function relTime(ts, t) {
425
+ if (typeof ts !== 'number' || !Number.isFinite(ts)) return ''
426
+ const diff = Math.max(0, Date.now() - ts)
427
+ if (diff < 60_000) return t('justNow')
428
+ if (diff < 3_600_000) return t('minutesAgo', { n: Math.floor(diff / 60_000) })
429
+ if (diff < 86_400_000) return t('hoursAgo', { n: Math.floor(diff / 3_600_000) })
430
+ return t('daysAgo', { n: Math.floor(diff / 86_400_000) })
431
+ }
432
+
433
+ function titleOf(node, summary) {
434
+ /* The durable session title is the user-facing name: renaming in the
435
+ * left sidebar must win over a stale summary topic. */
436
+ if (typeof node.title === 'string' && node.title !== '') return node.title
437
+ if (summary !== undefined && typeof summary.topic === 'string' && summary.topic !== '') return summary.topic
438
+ return node.displayTitle ?? node.id
439
+ }
440
+
441
+ function statsOf(node) {
442
+ const stats = node.projectionValues?.sessionStats
443
+ return stats !== null && typeof stats === 'object' ? stats : undefined
444
+ }
445
+
446
+ function countTurns(node) {
447
+ const stats = statsOf(node)
448
+ return typeof stats?.turns === 'number' ? stats.turns : undefined
449
+ }
450
+
451
+ function countSteps(node) {
452
+ const stats = statsOf(node)
453
+ return typeof stats?.steps === 'number' ? stats.steps : undefined
454
+ }
455
+
456
+ function hasChildrenInTree(tree) {
457
+ return tree.children !== undefined && tree.children.length > 0
458
+ }
459
+
460
+ function countDescendants(tree) {
461
+ let total = 0
462
+ for (const child of tree.children ?? []) total += 1 + countDescendants(child)
463
+ return total
464
+ }
465
+
466
+ function containsId(tree, id) {
467
+ if (tree.id === id) return true
468
+ for (const child of tree.children ?? []) if (containsId(child, id)) return true
469
+ return false
470
+ }
471
+
472
+ function buildForest(snapshot, includeSubagents) {
473
+ const byId = snapshot.byId ?? {}
474
+ const all = []
475
+ for (const id of snapshot.ids ?? Object.keys(byId)) {
476
+ const node = byId[id]
477
+ if (node === undefined) continue
478
+ if (!includeSubagents && node.origin === 'subagent') continue
479
+ all.push(node)
480
+ }
481
+ const present = new Set(all.map((node) => node.id))
482
+ const childrenOf = new Map()
483
+ const roots = []
484
+ for (const node of all) {
485
+ let parentId = node.parentId
486
+ let guard = 0
487
+ while (typeof parentId === 'string' && !present.has(parentId) && guard < 128) {
488
+ const ancestor = byId[parentId]
489
+ if (ancestor === undefined) break
490
+ parentId = ancestor.parentId
491
+ guard += 1
492
+ }
493
+ if (typeof parentId === 'string' && present.has(parentId)) {
494
+ const siblings = childrenOf.get(parentId) ?? []
495
+ siblings.push(node)
496
+ childrenOf.set(parentId, siblings)
497
+ } else {
498
+ roots.push(node)
499
+ }
500
+ }
501
+ const newestFirst = (a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)
502
+ roots.sort(newestFirst)
503
+ for (const siblings of childrenOf.values()) siblings.sort(newestFirst)
504
+ const materialize = (node, depth) => ({
505
+ id: node.id,
506
+ node,
507
+ depth,
508
+ children: (childrenOf.get(node.id) ?? []).map((child) => materialize(child, depth + 1)),
509
+ })
510
+ return {
511
+ roots: roots.map((node) => materialize(node, 0)),
512
+ byId: new Map(all.map((node) => [node.id, node])),
513
+ }
514
+ }
515
+
516
+ function layoutTree(root, collapsed) {
517
+ if (root === undefined) return { items: [], edges: [], width: 0, height: 0 }
518
+ const items = []
519
+ const edges = []
520
+ let cursor = 0
521
+ const walk = (tree, parent) => {
522
+ const item = { ...tree, x: PAD + tree.depth * (NODE_W + GAP_X), y: 0, parent }
523
+ const kids = collapsed.has(tree.id) ? [] : tree.children
524
+ if (kids.length > 0) {
525
+ const childItems = kids.map((child) => walk(child, item))
526
+ item.y = (childItems[0].y + childItems[childItems.length - 1].y) / 2
527
+ } else {
528
+ item.y = cursor
529
+ cursor += NODE_H + GAP_Y
530
+ }
531
+ items.push(item)
532
+ if (parent !== undefined) edges.push({ from: parent, to: item })
533
+ return item
534
+ }
535
+ walk(root, undefined)
536
+ const width = Math.max(...items.map((item) => item.x + NODE_W)) + PAD
537
+ const height = Math.max(cursor + PAD - GAP_Y, NODE_H + PAD * 2)
538
+ return { items, edges, width, height }
539
+ }
540
+
541
+ function edgePath(from, to) {
542
+ const x1 = from.x + NODE_W
543
+ const y1 = from.y + NODE_H / 2
544
+ const x2 = to.x
545
+ const y2 = to.y + NODE_H / 2
546
+ const mid = (x1 + x2) / 2
547
+ return `M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2},${y2}`
548
+ }
549
+
550
+ async function api(method, payload) {
551
+ const response = await fetch(`${API}/${method}`, {
552
+ method: 'POST',
553
+ headers: { 'content-type': 'application/json' },
554
+ body: JSON.stringify(payload ?? {}),
555
+ })
556
+ const value = await response.json().catch(() => undefined)
557
+ if (value === undefined) throw new Error(`mindmap ${method}: invalid response`)
558
+ if (value.ok !== true) throw new Error(value.error?.message ?? `mindmap ${method} failed`)
559
+ return value
560
+ }
561
+
562
+ async function openSession(ctx, id) {
563
+ const workspace = ctx.get('uiWorkspace')
564
+ if (workspace !== undefined && typeof workspace.openSession === 'function') {
565
+ workspace.openSession(id)
566
+ return true
567
+ }
568
+ try {
569
+ ctx.sessions.retain(id, { source: 'mainView' })
570
+ ctx.layout?.selectPanel?.(null)
571
+ return true
572
+ } catch {
573
+ return false
574
+ }
575
+ }
576
+
577
+ async function renameSession(ctx, id, title) {
578
+ const result = await ctx.sessions.using(id, { source: 'mindmap' }, (reference) =>
579
+ reference.binding.session.rename(title))
580
+ if (result !== undefined && result.ok === false) {
581
+ throw new Error(result.error?.message ?? 'rename failed')
582
+ }
583
+ }
584
+
585
+ async function prefillDraft(ctx, id, text, whenDraftExists) {
586
+ const conversation = ctx.get('conversation')
587
+ const input = conversation?.input
588
+ if (input === undefined || typeof input.requestDraftInitialization !== 'function') return false
589
+ for (let attempt = 0; attempt < 50; attempt += 1) {
590
+ const binding = ctx.sessions.binding?.(id)
591
+ if (binding !== undefined) {
592
+ try {
593
+ const outcome = input.requestDraftInitialization(binding, {
594
+ prompt: text,
595
+ whenDraftExists: whenDraftExists ?? 'replace',
596
+ })
597
+ if (outcome !== 'blocked') return true
598
+ } catch {
599
+ // The session shell may still be mounting; retry briefly.
600
+ }
601
+ }
602
+ await sleep(100)
603
+ }
604
+ return false
605
+ }
606
+
607
+ /* ── React hooks / components ───────────────────────────────────────── */
608
+
609
+ function useSessionList(ctx) {
610
+ const store = ctx.sessions.list
611
+ return React.useSyncExternalStore(
612
+ React.useCallback((listener) => store.subscribe(listener), [store]),
613
+ React.useCallback(() => store.getSnapshot(), [store]),
614
+ )
615
+ }
616
+
617
+ function IconMindmap({ size = 16 }) {
618
+ return h(
619
+ 'svg',
620
+ { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true' },
621
+ h('rect', { x: 1, y: 6.2, width: 4.4, height: 3.6, rx: 1.1, stroke: 'currentColor', strokeWidth: 1.1 }),
622
+ h('rect', { x: 10.6, y: 1, width: 4.4, height: 3.4, rx: 1.1, stroke: 'currentColor', strokeWidth: 1.1 }),
623
+ h('rect', { x: 10.6, y: 6.1, width: 4.4, height: 3.4, rx: 1.1, stroke: 'currentColor', strokeWidth: 1.1 }),
624
+ h('rect', { x: 10.6, y: 11.2, width: 4.4, height: 3.4, rx: 1.1, stroke: 'currentColor', strokeWidth: 1.1 }),
625
+ h('path', { d: 'M5.4 8h2.4M7.8 2.7v10.6M7.8 2.7h2.8M7.8 8h2.8M7.8 13.3h2.8', stroke: 'currentColor', strokeWidth: 1.1, strokeLinecap: 'round' }),
626
+ )
627
+ }
628
+
629
+ function NodeCard({ item, summary, pending, selected, current, collapsed, t, onSelect, onOpen, onFloat, onBranch, onRename, onToggle }) {
630
+ const node = item.node
631
+ const label = titleOf(node, summary)
632
+ const summaryLine = summary?.summary !== undefined && summary.summary !== '' ? summary.summary : t('noSummary')
633
+ const turns = countTurns(node)
634
+ const kids = countDescendants(item)
635
+ return h(
636
+ 'div',
637
+ {
638
+ className: 'mm-node',
639
+ style: { left: item.x, top: item.y },
640
+ role: 'button',
641
+ tabIndex: 0,
642
+ 'aria-label': label,
643
+ 'data-selected': selected === true,
644
+ 'data-current': current === true,
645
+ onClick: () => onSelect(item.id),
646
+ onDoubleClick: () => onFloat(item.id),
647
+ onKeyDown: (event) => {
648
+ if (event.key === 'Enter') {
649
+ event.preventDefault()
650
+ onFloat(item.id)
651
+ } else if (event.key === ' ') {
652
+ event.preventDefault()
653
+ onSelect(item.id)
654
+ }
655
+ },
656
+ },
657
+ h(
658
+ 'div',
659
+ { className: 'mm-nodeTop' },
660
+ h('span', { className: 'mm-dot', 'data-running': node.running === true }),
661
+ h('span', { className: 'mm-nodeTitle' }, label),
662
+ current === true ? h('span', { className: 'mm-badge', 'data-kind': 'current' }, t('current')) : null,
663
+ ),
664
+ h('div', { className: 'mm-nodeSummary', 'data-empty': summary?.summary === undefined || summary.summary === '' }, summaryLine),
665
+ h(
666
+ 'div',
667
+ { className: 'mm-nodeMeta' },
668
+ turns !== undefined ? h('span', null, t('turns', { n: turns })) : null,
669
+ pending === true
670
+ ? h('span', { className: 'mm-spinner' }, h('span', { className: 'mm-spin' }), ` ${t('summarizing')}`)
671
+ : h('span', null, relTime(node.updatedAt, t)),
672
+ h('span', { className: 'mm-spacer' }),
673
+ summary?.degraded === true ? h('span', { className: 'mm-badge', 'data-kind': 'degraded' }, t('degraded')) : null,
674
+ hasChildrenInTree(item) && collapsed === false ? h('span', { className: 'mm-badge' }, `${item.children.length}`) : null,
675
+ hasChildrenInTree(item) && collapsed === true
676
+ ? h('button', {
677
+ type: 'button',
678
+ className: 'mm-nodeTool',
679
+ style: { position: 'static', width: '20px', height: '18px', opacity: 1, marginLeft: '2px' },
680
+ title: t('expandAll'),
681
+ onClick: (event) => {
682
+ event.stopPropagation()
683
+ onToggle(item.id)
684
+ },
685
+ }, `+${kids}`)
686
+ : null,
687
+ ),
688
+ h(
689
+ 'div',
690
+ { className: 'mm-nodeTools' },
691
+ h('button', {
692
+ type: 'button',
693
+ className: 'mm-nodeTool',
694
+ title: t('rename'),
695
+ onClick: (event) => {
696
+ event.stopPropagation()
697
+ onRename(item.id)
698
+ },
699
+ }, '✎'),
700
+ h('button', {
701
+ type: 'button',
702
+ className: 'mm-nodeTool',
703
+ title: t('floatOpen'),
704
+ onClick: (event) => {
705
+ event.stopPropagation()
706
+ onFloat(item.id)
707
+ },
708
+ }, '◱'),
709
+ h('button', {
710
+ type: 'button',
711
+ className: 'mm-nodeTool',
712
+ title: t('branch'),
713
+ onClick: (event) => {
714
+ event.stopPropagation()
715
+ onBranch(item.id)
716
+ },
717
+ }, '+'),
718
+ hasChildrenInTree(item)
719
+ ? h('button', {
720
+ type: 'button',
721
+ className: 'mm-nodeTool',
722
+ title: collapsed === true ? t('expandAll') : t('collapseAll'),
723
+ onClick: (event) => {
724
+ event.stopPropagation()
725
+ onToggle(item.id)
726
+ },
727
+ }, collapsed === true ? '▾' : '−')
728
+ : null,
729
+ ),
730
+ )
731
+ }
732
+
733
+ function Drawer({ item, summary, pending, t, ctx, current, onClose, onOpen, onFloat, onChild, onBranch, onRename, onRefresh, onBridge, toast }) {
734
+ const node = item.node
735
+ const label = titleOf(node, summary)
736
+ const turns = countTurns(node)
737
+ const steps = countSteps(node)
738
+ const parentId = node.parentId
739
+ const openQuestions = Array.isArray(summary?.open) ? summary.open : []
740
+ return h(
741
+ 'aside',
742
+ { className: 'mm-drawer', 'aria-label': t('details') },
743
+ h(
744
+ 'div',
745
+ { className: 'mm-drawerHead' },
746
+ h('h2', { className: 'mm-drawerTitle' }, label),
747
+ h('button', { type: 'button', className: 'mm-btn icon', title: t('close'), onClick: onClose }, '×'),
748
+ ),
749
+ h(
750
+ 'div',
751
+ { className: 'mm-drawerBody' },
752
+ h(
753
+ 'div',
754
+ { className: 'mm-actions' },
755
+ h('button', { type: 'button', className: 'mm-btn primary', onClick: () => onChild(node.id, false) }, `+ ${t('newChild')}`),
756
+ h('button', { type: 'button', className: 'mm-btn', onClick: () => onFloat(node.id) }, `◱ ${t('viewChat')}`),
757
+ h('button', { type: 'button', className: 'mm-btn', onClick: () => onRename(node.id) }, `✎ ${t('rename')}`),
758
+ h('button', { type: 'button', className: 'mm-btn', onClick: () => onChild(node.id, true) }, t('briefBranch')),
759
+ h('button', { type: 'button', className: 'mm-btn', onClick: () => onOpen(node.id) }, t('floatFull')),
760
+ typeof parentId === 'string'
761
+ ? h('button', {
762
+ type: 'button',
763
+ className: 'mm-btn',
764
+ onClick: () => onFloat(parentId),
765
+ }, `↑ ${t('backToParent')}`)
766
+ : null,
767
+ ),
768
+ h(
769
+ 'div',
770
+ null,
771
+ h('div', { className: 'mm-kicker' }, t('overview')),
772
+ h('p', { className: 'mm-summary' }, summary?.summary !== undefined && summary.summary !== ''
773
+ ? summary.summary
774
+ : pending === true ? t('summarizing') : t('noSummary')),
775
+ pending === true
776
+ ? h('div', { className: 'mm-emptyLine', style: { display: 'flex', alignItems: 'center', gap: '6px' } },
777
+ h('span', { className: 'mm-spin' }), t('summarizing'))
778
+ : null,
779
+ ),
780
+ openQuestions.length > 0
781
+ ? h(
782
+ 'div',
783
+ null,
784
+ h('div', { className: 'mm-kicker' }, t('openQuestions')),
785
+ h('ul', { className: 'mm-openList' }, openQuestions.map((question, index) => h('li', { key: index }, question))),
786
+ )
787
+ : null,
788
+ h(
789
+ 'div',
790
+ { className: 'mm-actions' },
791
+ h('button', {
792
+ type: 'button',
793
+ className: 'mm-btn',
794
+ disabled: pending === true,
795
+ onClick: () => onRefresh(node.id),
796
+ }, pending === true ? t('summarizing') : t('refreshOne')),
797
+ summary?.summary !== undefined && summary.summary !== ''
798
+ ? h('button', {
799
+ type: 'button',
800
+ className: 'mm-btn',
801
+ onClick: async () => {
802
+ try {
803
+ await navigator.clipboard.writeText(`${label}\n${summary.summary}`)
804
+ toast(t('copied'))
805
+ } catch {
806
+ toast(t('summaryFailed'))
807
+ }
808
+ },
809
+ }, t('copy'))
810
+ : null,
811
+ typeof parentId === 'string' && summary?.summary !== undefined && summary.summary !== ''
812
+ ? h('button', {
813
+ type: 'button',
814
+ className: 'mm-btn',
815
+ onClick: () => onBridge(node.id, parentId),
816
+ }, `↩ ${t('bridge')}`)
817
+ : null,
818
+ ),
819
+ h(
820
+ 'div',
821
+ null,
822
+ h('div', { className: 'mm-kicker' }, t('details')),
823
+ h(
824
+ 'dl',
825
+ { className: 'mm-facts' },
826
+ current === true
827
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('current')), h('dd', null, '●'))
828
+ : null,
829
+ turns !== undefined
830
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('turnsLabel')), h('dd', null, turns))
831
+ : null,
832
+ steps !== undefined
833
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('stepsLabel')), h('dd', null, steps))
834
+ : null,
835
+ typeof node.updatedAt === 'number'
836
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('updated')), h('dd', null, relTime(node.updatedAt, t)))
837
+ : null,
838
+ typeof node.cwd === 'string' && node.cwd !== ''
839
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('workspace')), h('dd', { className: 'mm-code' }, node.cwd))
840
+ : null,
841
+ typeof parentId === 'string'
842
+ ? h('div', { className: 'mm-fact' }, h('dt', null, t('parent')), h('dd', { className: 'mm-code' }, parentId))
843
+ : null,
844
+ h('div', { className: 'mm-fact' }, h('dt', null, t('sessionId')), h('dd', { className: 'mm-code' }, node.id)),
845
+ ),
846
+ ),
847
+ ),
848
+ )
849
+ }
850
+
851
+ /* ── floating conversation ──────────────────────────────────────────── */
852
+
853
+ const MAP_HOME_KEY = 'dsh-mindmap.mapHome'
854
+ const FLOAT_KEY = 'dsh-mindmap.float.v2'
855
+ const FLOAT_STATE_KEY = 'dsh-mindmap.floatState.v1'
856
+ const MODE = { mapHome: true, bypass: false }
857
+
858
+ function readStorage(key) {
859
+ try {
860
+ const raw = localStorage.getItem(key)
861
+ return raw === null ? undefined : JSON.parse(raw)
862
+ } catch {
863
+ return undefined
864
+ }
865
+ }
866
+
867
+ function writeStorage(key, value) {
868
+ try {
869
+ localStorage.setItem(key, JSON.stringify(value))
870
+ } catch {
871
+ // Private windows and quota failures must not break the map.
872
+ }
873
+ }
874
+
875
+ function readMapHome() {
876
+ const stored = readStorage(MAP_HOME_KEY)
877
+ return typeof stored === 'boolean' ? stored : true
878
+ }
879
+
880
+ function loadGeometry() {
881
+ const stored = readStorage(FLOAT_KEY)
882
+ if (stored !== undefined && typeof stored === 'object' && stored !== null
883
+ && ['x', 'y', 'w', 'h'].every((key) => Number.isFinite(stored[key]))) {
884
+ return { x: stored.x, y: stored.y, w: stored.w, h: stored.h }
885
+ }
886
+ return undefined
887
+ }
888
+
889
+ function readFloatMinimized() {
890
+ const stored = readStorage(FLOAT_KEY)
891
+ return stored !== undefined && stored !== null && stored.minimized === true
892
+ }
893
+
894
+ function readFloatState() {
895
+ const stored = readStorage(FLOAT_STATE_KEY)
896
+ if (stored === undefined || stored === null || typeof stored !== 'object') return undefined
897
+ if (stored.open !== true && stored.open !== false) return undefined
898
+ return {
899
+ open: stored.open === true && typeof stored.sessionId === 'string',
900
+ sessionId: typeof stored.sessionId === 'string' ? stored.sessionId : undefined,
901
+ mode: stored.mode === 'child' ? 'child' : 'chat',
902
+ parentId: typeof stored.parentId === 'string' ? stored.parentId : undefined,
903
+ brief: stored.brief === true,
904
+ startedAt: typeof stored.startedAt === 'number' ? stored.startedAt : 0,
905
+ }
906
+ }
907
+
908
+ function clampBox(box, bounds) {
909
+ const width = Math.max(400, Math.min(box.w, Math.max(400, bounds.width - 16)))
910
+ const height = Math.max(280, Math.min(box.h, Math.max(280, bounds.height - 16)))
911
+ const x = Math.max(8, Math.min(box.x, Math.max(8, bounds.width - width - 8)))
912
+ const y = Math.max(8, Math.min(box.y, Math.max(8, bounds.height - height - 8)))
913
+ return { x, y, w: width, h: height }
914
+ }
915
+
916
+ /** Retain the selected Session for the float; release it when the target changes. */
917
+ function useSessionReference(ctx, sessionId) {
918
+ const [reference, setReference] = useState(undefined)
919
+ useEffect(() => {
920
+ if (sessionId === undefined || typeof ctx.sessions?.retain !== 'function') {
921
+ setReference(undefined)
922
+ return undefined
923
+ }
924
+ let next
925
+ try {
926
+ next = ctx.sessions.retain(sessionId, { source: 'mindmap-float' })
927
+ } catch {
928
+ setReference(undefined)
929
+ return undefined
930
+ }
931
+ setReference(next)
932
+ return () => {
933
+ setReference(undefined)
934
+ try {
935
+ next.release()
936
+ } catch {
937
+ // The controller may already have retired the generation.
938
+ }
939
+ }
940
+ }, [ctx, sessionId])
941
+ return reference
942
+ }
943
+
944
+ class FloatBoundary extends React.Component {
945
+ constructor(props) {
946
+ super(props)
947
+ this.state = { failed: false }
948
+ }
949
+
950
+ static getDerivedStateFromError() {
951
+ return { failed: true }
952
+ }
953
+
954
+ componentDidCatch(error) {
955
+ console.error('[mindmap] floating conversation crashed:', error)
956
+ }
957
+
958
+ render() {
959
+ return this.state.failed ? this.props.fallback : this.props.children
960
+ }
961
+ }
962
+
963
+ function FloatingConversation({
964
+ sessionId,
965
+ node,
966
+ parentLabel,
967
+ summary,
968
+ mode,
969
+ brief,
970
+ t,
971
+ ctx,
972
+ SessionProvider,
973
+ renderFactorySlot,
974
+ initialGeometry,
975
+ minimized,
976
+ boundsRef,
977
+ onGeometry,
978
+ onMinimize,
979
+ onRestore,
980
+ onNewChild,
981
+ onRename,
982
+ onDelete,
983
+ onTurns,
984
+ onClose,
985
+ onFull,
986
+ }) {
987
+ const reference = useSessionReference(ctx, sessionId)
988
+ const [box, setBox] = useState(initialGeometry ?? { x: 48, y: 56, w: 560, h: 600 })
989
+ const boxRef = useRef(initialGeometry ?? { x: 48, y: 56, w: 560, h: 600 })
990
+ const dragRef = useRef(undefined)
991
+ const resizeRef = useRef(undefined)
992
+ const frameRef = useRef(null)
993
+ boxRef.current = box
994
+
995
+ useEffect(() => {
996
+ const frame = frameRef.current
997
+ if (frame !== null) frame.focus({ preventScroll: true })
998
+ const bounds = boundsRef.current?.getBoundingClientRect()
999
+ if (bounds === undefined || bounds.width < 80) return
1000
+ let next
1001
+ if (initialGeometry === undefined) {
1002
+ const margin = 28
1003
+ const header = boundsRef.current?.querySelector?.('.mm-head')
1004
+ const headerHeight = header?.getBoundingClientRect?.().height ?? 56
1005
+ const width = Math.max(400, Math.round(bounds.width - margin * 2))
1006
+ const height = Math.max(280, Math.round(bounds.height - headerHeight - margin * 2))
1007
+ next = clampBox({
1008
+ x: margin,
1009
+ y: headerHeight + margin,
1010
+ w: width,
1011
+ h: height,
1012
+ }, bounds)
1013
+ } else {
1014
+ next = clampBox(initialGeometry, bounds)
1015
+ }
1016
+ setBox(next)
1017
+ boxRef.current = next
1018
+ }, [])
1019
+
1020
+ const beginDrag = (event) => {
1021
+ if (event.button !== 0) return
1022
+ const target = event.target
1023
+ if (target !== null && typeof target.closest === 'function' && target.closest('button') !== null) return
1024
+ event.preventDefault()
1025
+ event.stopPropagation()
1026
+ const bounds = boundsRef.current?.getBoundingClientRect()
1027
+ dragRef.current = { x: event.clientX, y: event.clientY, box: boxRef.current, bounds }
1028
+ event.currentTarget.setPointerCapture?.(event.pointerId)
1029
+ }
1030
+
1031
+ const moveDrag = (event) => {
1032
+ const drag = dragRef.current
1033
+ if (drag === undefined) return
1034
+ const raw = {
1035
+ ...drag.box,
1036
+ x: drag.box.x + event.clientX - drag.x,
1037
+ y: drag.box.y + event.clientY - drag.y,
1038
+ }
1039
+ const next = drag.bounds === undefined ? raw : clampBox(raw, drag.bounds)
1040
+ boxRef.current = next
1041
+ setBox(next)
1042
+ }
1043
+
1044
+ const endDrag = (event) => {
1045
+ if (dragRef.current === undefined) return
1046
+ dragRef.current = undefined
1047
+ try {
1048
+ event.currentTarget.releasePointerCapture?.(event.pointerId)
1049
+ } catch {
1050
+ // The pointer may already be gone; the geometry is still saved.
1051
+ }
1052
+ onGeometry(boxRef.current)
1053
+ }
1054
+
1055
+ const beginResize = (event, direction) => {
1056
+ if (event.button !== 0) return
1057
+ event.preventDefault()
1058
+ event.stopPropagation()
1059
+ const bounds = boundsRef.current?.getBoundingClientRect()
1060
+ resizeRef.current = {
1061
+ x: event.clientX,
1062
+ y: event.clientY,
1063
+ box: boxRef.current,
1064
+ bounds,
1065
+ direction,
1066
+ }
1067
+ try {
1068
+ event.currentTarget.setPointerCapture?.(event.pointerId)
1069
+ } catch {
1070
+ // Synthetic pointer events may not have a capturable pointer id.
1071
+ }
1072
+ }
1073
+
1074
+ const moveResize = (event) => {
1075
+ const resize = resizeRef.current
1076
+ if (resize === undefined) return
1077
+ const dx = event.clientX - resize.x
1078
+ const dy = event.clientY - resize.y
1079
+ const direction = resize.direction
1080
+ let { x, y, w, h } = resize.box
1081
+ if (direction.includes('e')) w = resize.box.w + dx
1082
+ if (direction.includes('s')) h = resize.box.h + dy
1083
+ if (direction.includes('w')) {
1084
+ x = resize.box.x + dx
1085
+ w = resize.box.w - dx
1086
+ }
1087
+ if (direction.includes('n')) {
1088
+ y = resize.box.y + dy
1089
+ h = resize.box.h - dy
1090
+ }
1091
+ const minWidth = 400
1092
+ const minHeight = 280
1093
+ if (w < minWidth) {
1094
+ if (direction.includes('w')) x = resize.box.x + resize.box.w - minWidth
1095
+ w = minWidth
1096
+ }
1097
+ if (h < minHeight) {
1098
+ if (direction.includes('n')) y = resize.box.y + resize.box.h - minHeight
1099
+ h = minHeight
1100
+ }
1101
+ let next = { x, y, w, h }
1102
+ if (resize.bounds !== undefined) {
1103
+ const gutter = 8
1104
+ x = Math.max(gutter, Math.min(x, resize.bounds.width - minWidth - gutter))
1105
+ y = Math.max(gutter, Math.min(y, resize.bounds.height - minHeight - gutter))
1106
+ w = Math.max(minWidth, Math.min(w, resize.bounds.width - x - gutter))
1107
+ h = Math.max(minHeight, Math.min(h, resize.bounds.height - y - gutter))
1108
+ next = { x, y, w, h }
1109
+ }
1110
+ boxRef.current = next
1111
+ setBox(next)
1112
+ }
1113
+
1114
+ const endResize = (event) => {
1115
+ if (resizeRef.current === undefined) return
1116
+ resizeRef.current = undefined
1117
+ try {
1118
+ event.currentTarget.releasePointerCapture?.(event.pointerId)
1119
+ } catch {
1120
+ // The pointer may already be gone; the geometry is still saved.
1121
+ }
1122
+ onGeometry(boxRef.current)
1123
+ }
1124
+
1125
+ const resizeHandles = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((direction) =>
1126
+ h('div', {
1127
+ key: direction,
1128
+ className: 'mm-resize',
1129
+ 'data-dir': direction,
1130
+ title: t('floatResize'),
1131
+ onPointerDown: (event) => beginResize(event, direction),
1132
+ onPointerMove: moveResize,
1133
+ onPointerUp: endResize,
1134
+ onPointerCancel: endResize,
1135
+ }))
1136
+
1137
+ const label = titleOf(node ?? { id: sessionId }, summary)
1138
+ const child = mode === 'child'
1139
+ const heading = child
1140
+ ? `${t('newChild')}${parentLabel === undefined ? '' : ` · ${parentLabel}`}`
1141
+ : label
1142
+ const canEmbed = typeof SessionProvider === 'function' && typeof renderFactorySlot === 'function'
1143
+ const hero = node?.blank === true
1144
+ const fallbackText = canEmbed ? t('floatFallback') : t('floatUnavailable')
1145
+ const fallback = h(
1146
+ 'div',
1147
+ { className: 'mm-floatFallback' },
1148
+ h('p', null, fallbackText),
1149
+ h('button', { type: 'button', className: 'mm-btn primary', onClick: onFull }, t('floatFull')),
1150
+ )
1151
+ const content = reference !== undefined && canEmbed
1152
+ ? h(
1153
+ FloatBoundary,
1154
+ { fallback },
1155
+ h(
1156
+ SessionProvider,
1157
+ {
1158
+ key: sessionId,
1159
+ session: reference,
1160
+ empty: () => fallback,
1161
+ },
1162
+ renderFactorySlot(
1163
+ 'conversation.content',
1164
+ { variant: 'embedded', phase: hero ? 'hero' : 'active', hero },
1165
+ { fallback },
1166
+ ),
1167
+ ),
1168
+ )
1169
+ : fallback
1170
+
1171
+ return h(
1172
+ 'section',
1173
+ {
1174
+ ref: frameRef,
1175
+ className: 'mm-float',
1176
+ style: { left: `${box.x}px`, top: `${box.y}px`, width: `${box.w}px`, height: `${box.h}px` },
1177
+ 'data-minimized': minimized === true,
1178
+ tabIndex: -1,
1179
+ role: 'dialog',
1180
+ 'aria-label': `${t('openFloat')}: ${heading}`,
1181
+ 'data-mode': mode,
1182
+ onPointerDown: (event) => event.stopPropagation(),
1183
+ },
1184
+ h(
1185
+ 'div',
1186
+ {
1187
+ className: 'mm-floatHead',
1188
+ onPointerDown: beginDrag,
1189
+ onPointerMove: moveDrag,
1190
+ onPointerUp: endDrag,
1191
+ onPointerCancel: endDrag,
1192
+ },
1193
+ h('span', { className: 'mm-dot', 'data-running': node?.running === true }),
1194
+ h('span', { className: 'mm-floatTitle', title: heading }, heading),
1195
+ child
1196
+ ? h('span', { className: 'mm-badge', 'data-kind': brief === true ? 'degraded' : 'current' },
1197
+ brief === true ? t('briefBranch') : t('childDraft'))
1198
+ : null,
1199
+ h(
1200
+ 'div',
1201
+ { className: 'mm-floatTools' },
1202
+ !child
1203
+ ? h('button', {
1204
+ type: 'button',
1205
+ className: 'mm-floatTool',
1206
+ title: t('rename'),
1207
+ onClick: onRename,
1208
+ }, '✎')
1209
+ : null,
1210
+ !child && node?.blank !== true
1211
+ ? h('button', {
1212
+ type: 'button',
1213
+ className: 'mm-floatTool',
1214
+ title: t('newChild'),
1215
+ onClick: onNewChild,
1216
+ }, '+')
1217
+ : null,
1218
+ h('button', {
1219
+ type: 'button',
1220
+ className: 'mm-floatTool',
1221
+ title: t('turnsTitle'),
1222
+ onClick: onTurns,
1223
+ }, '☰'),
1224
+ h('button', {
1225
+ type: 'button',
1226
+ className: 'mm-floatTool',
1227
+ title: t('deleteSession'),
1228
+ onClick: onDelete,
1229
+ }, '🗑'),
1230
+ h('button', {
1231
+ type: 'button',
1232
+ className: 'mm-floatTool',
1233
+ title: minimized === true ? t('floatRestore') : t('floatMinimize'),
1234
+ onClick: minimized === true ? onRestore : onMinimize,
1235
+ }, minimized === true ? '▢' : '−'),
1236
+ h('button', { type: 'button', className: 'mm-floatTool', title: t('floatFull'), onClick: onFull }, '↗'),
1237
+ h('button', { type: 'button', className: 'mm-floatTool', title: t('floatClose'), onClick: onClose }, '×'),
1238
+ ),
1239
+ ),
1240
+ h('div', { className: 'mm-floatBody' }, h('div', { className: 'mm-floatChat' }, content)),
1241
+ resizeHandles,
1242
+ )
1243
+ }
1244
+
1245
+ function RenameDialog({ target, t, onCancel, onRename }) {
1246
+ const [title, setTitle] = useState(target.title ?? '')
1247
+ const [busy, setBusy] = useState(false)
1248
+ const [error, setError] = useState(undefined)
1249
+ const submit = async () => {
1250
+ const text = title.trim()
1251
+ if (text === '') {
1252
+ setError(t('renameRequired'))
1253
+ return
1254
+ }
1255
+ setBusy(true)
1256
+ setError(undefined)
1257
+ try {
1258
+ await onRename(target.id, text)
1259
+ } catch (reason) {
1260
+ setError(reason instanceof Error ? reason.message : String(reason))
1261
+ setBusy(false)
1262
+ }
1263
+ }
1264
+ return h(
1265
+ 'div',
1266
+ {
1267
+ className: 'mm-overlay',
1268
+ role: 'presentation',
1269
+ onMouseDown: (event) => {
1270
+ if (event.target === event.currentTarget && !busy) onCancel()
1271
+ },
1272
+ },
1273
+ h(
1274
+ 'div',
1275
+ { className: 'mm-modal mm-rename', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('rename') },
1276
+ h('h2', { className: 'mm-modalTitle' }, t('renameTitle')),
1277
+ h('p', { className: 'mm-modalText' }, t('renameHint')),
1278
+ h('input', {
1279
+ className: 'mm-input mm-renameInput',
1280
+ autoFocus: true,
1281
+ value: title,
1282
+ maxLength: 120,
1283
+ placeholder: t('renamePlaceholder'),
1284
+ onChange: (event) => setTitle(event.target.value),
1285
+ onKeyDown: (event) => {
1286
+ if (event.key === 'Enter') {
1287
+ event.preventDefault()
1288
+ void submit()
1289
+ } else if (event.key === 'Escape') {
1290
+ event.preventDefault()
1291
+ if (!busy) onCancel()
1292
+ }
1293
+ },
1294
+ }),
1295
+ error !== undefined ? h('div', { className: 'mm-error', style: { margin: 0 } }, error) : null,
1296
+ h(
1297
+ 'div',
1298
+ { className: 'mm-modalFoot' },
1299
+ h('button', { type: 'button', className: 'mm-btn', disabled: busy, onClick: onCancel }, t('cancel')),
1300
+ h('button', { type: 'button', className: 'mm-btn primary', disabled: busy, onClick: () => void submit() },
1301
+ busy ? t('saving') : t('save')),
1302
+ ),
1303
+ ),
1304
+ )
1305
+ }
1306
+
1307
+ function App({ t: providedT, SessionProvider, renderFactorySlot }) {
1308
+ const t = typeof providedT === 'function' ? providedT : FALLBACK_T
1309
+ const ctx = REACT_CTX
1310
+ const list = useSessionList(ctx)
1311
+ const [selectedId, setSelectedId] = useState(undefined)
1312
+ const [rootOverride, setRootOverride] = useState(undefined)
1313
+ const [summaries, setSummaries] = useState({})
1314
+ const [pending, setPending] = useState({})
1315
+ const [collapsed, setCollapsed] = useState(() => new Set())
1316
+ const [showSubagents, setShowSubagents] = useState(false)
1317
+ const [toast, setToast] = useState(undefined)
1318
+ const [renameTarget, setRenameTarget] = useState(undefined)
1319
+ const [fetchError, setFetchError] = useState(false)
1320
+ const [hostConfig, setHostConfig] = useState({ autoSummarize: true, available: true })
1321
+ const [view, setView] = useState({ x: 20, y: 20, k: 1 })
1322
+ const [float, setFloat] = useState(() => {
1323
+ const saved = readFloatState()
1324
+ return {
1325
+ open: saved?.open === true,
1326
+ minimized: readFloatMinimized(),
1327
+ sessionId: saved?.sessionId,
1328
+ mode: saved?.mode ?? 'chat',
1329
+ parentId: saved?.parentId,
1330
+ brief: saved?.brief ?? false,
1331
+ startedAt: saved?.startedAt ?? 0,
1332
+ }
1333
+ })
1334
+ const [mapHome, setMapHomeState] = useState(() => MODE.mapHome)
1335
+ const [archivedIds, setArchivedIds] = useState(() => {
1336
+ const snapshot = ctx.uiWorkspace?.workspaces?.list?.getSnapshot?.()
1337
+ return new Set(snapshot?.archivedSessionIds ?? [])
1338
+ })
1339
+ const [deleteTarget, setDeleteTarget] = useState(undefined)
1340
+ const [deleting, setDeleting] = useState(false)
1341
+ const [turnsTarget, setTurnsTarget] = useState(undefined)
1342
+ const [turns, setTurns] = useState([])
1343
+ const [turnsLoading, setTurnsLoading] = useState(false)
1344
+ const [turnsError, setTurnsError] = useState(undefined)
1345
+ const [turnConfirm, setTurnConfirm] = useState(undefined)
1346
+ const [rewinding, setRewinding] = useState(false)
1347
+ const [geometry, setGeometry] = useState(loadGeometry)
1348
+ const canvasRef = React.useRef(null)
1349
+ const rootRef = React.useRef(null)
1350
+ const dragRef = React.useRef(undefined)
1351
+ const requestedRef = React.useRef(new Set())
1352
+ const pendingRef = React.useRef(new Set())
1353
+ const viewRef = React.useRef(view)
1354
+ viewRef.current = view
1355
+ const toastTimer = React.useRef(undefined)
1356
+ const pendingCenterRef = React.useRef(undefined)
1357
+ const lastCurrentRef = React.useRef(undefined)
1358
+ const lastDraftRef = React.useRef('')
1359
+ const settlingRef = React.useRef(undefined)
1360
+
1361
+ const notify = React.useCallback((text) => {
1362
+ setToast(text)
1363
+ clearTimeout(toastTimer.current)
1364
+ toastTimer.current = setTimeout(() => setToast(undefined), 3200)
1365
+ }, [])
1366
+
1367
+ const formatTurnTime = (at) => {
1368
+ if (typeof at !== 'number' || !Number.isFinite(at)) return ''
1369
+ try {
1370
+ return new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
1371
+ } catch {
1372
+ return ''
1373
+ }
1374
+ }
1375
+
1376
+ React.useEffect(() => {
1377
+ writeStorage(FLOAT_STATE_KEY, {
1378
+ open: float.open,
1379
+ sessionId: float.sessionId,
1380
+ mode: float.mode,
1381
+ parentId: float.parentId,
1382
+ brief: float.brief,
1383
+ startedAt: float.startedAt,
1384
+ })
1385
+ }, [float.open, float.sessionId, float.mode, float.parentId, float.brief, float.startedAt])
1386
+
1387
+ /* While the float is open it owns the map surface: an automatic panel
1388
+ * switch (for example when a turn settles) must not unmount it. */
1389
+ React.useEffect(() => {
1390
+ if (!float.open) return undefined
1391
+ const source = ctx.layout?.panelInfo
1392
+ const check = () => {
1393
+ try {
1394
+ const active = source?.getSnapshot?.().activePanelId
1395
+ if (active !== PANEL_ID && (active === null || active === undefined || active === 'conversation')) {
1396
+ ctx.layout.selectPanel(PANEL_ID)
1397
+ }
1398
+ } catch {
1399
+ // The panel tree may be between registrations during HMR.
1400
+ }
1401
+ }
1402
+ check()
1403
+ if (typeof source?.subscribe !== 'function') return undefined
1404
+ return source.subscribe(check)
1405
+ }, [float.open, ctx])
1406
+
1407
+ React.useEffect(() => {
1408
+ const list = ctx.uiWorkspace?.workspaces?.list
1409
+ if (typeof list?.subscribe !== 'function') return undefined
1410
+ const refresh = () => {
1411
+ const snapshot = list.getSnapshot()
1412
+ setArchivedIds(new Set(snapshot?.archivedSessionIds ?? []))
1413
+ }
1414
+ refresh()
1415
+ return list.subscribe(refresh)
1416
+ }, [ctx])
1417
+
1418
+ /* A blank fork is a draft branch: it stays off the canvas until its
1419
+ * first message. Blank roots (a fresh Session) still render. */
1420
+ const mapList = React.useMemo(() => {
1421
+ const draftId = float.mode === 'child' ? float.sessionId : undefined
1422
+ const ids = (list.ids ?? Object.keys(list.byId ?? {})).filter((id) => {
1423
+ const node = list.byId?.[id]
1424
+ if (node === undefined) return false
1425
+ if (archivedIds.has(id)) return false
1426
+ if (id === draftId) return false
1427
+ return !(node.blank === true && typeof node.parentId === 'string')
1428
+ })
1429
+ if (ids.length === (list.ids ?? []).length) return list
1430
+ return { ...list, ids }
1431
+ }, [list, float.mode, float.sessionId, archivedIds])
1432
+
1433
+ const currentId = React.useMemo(() => {
1434
+ for (const node of Object.values(mapList.byId ?? {})) {
1435
+ if ((node.retainedBy?.mainView ?? 0) > 0) return node.id
1436
+ }
1437
+ return undefined
1438
+ }, [mapList])
1439
+
1440
+ const forest = React.useMemo(() => buildForest(mapList, showSubagents), [mapList, showSubagents])
1441
+
1442
+ const rootTree = React.useMemo(() => {
1443
+ if (rootOverride !== undefined) {
1444
+ const picked = forest.roots.find((root) => root.id === rootOverride)
1445
+ if (picked !== undefined) return picked
1446
+ }
1447
+ for (const candidate of [selectedId, currentId]) {
1448
+ if (candidate === undefined) continue
1449
+ const found = forest.roots.find((root) => containsId(root, candidate))
1450
+ if (found !== undefined) return found
1451
+ }
1452
+ return forest.roots[0]
1453
+ }, [forest, rootOverride, selectedId, currentId])
1454
+
1455
+ const layout = React.useMemo(() => layoutTree(rootTree, collapsed), [rootTree, collapsed])
1456
+ const itemById = React.useMemo(() => new Map(layout.items.map((item) => [item.id, item])), [layout])
1457
+ const treeIds = React.useMemo(() => layout.items.map((item) => item.id), [layout])
1458
+ const selected = selectedId === undefined ? undefined : itemById.get(selectedId)
1459
+ const rootId = rootTree?.id
1460
+
1461
+ const centerOnItem = React.useCallback((item) => {
1462
+ const canvas = canvasRef.current
1463
+ if (canvas === null || item === undefined) return
1464
+ const rect = canvas.getBoundingClientRect()
1465
+ if (rect.width < 40 || rect.height < 40) return
1466
+ const k = Math.max(0.65, viewRef.current.k)
1467
+ setView({
1468
+ k,
1469
+ x: rect.width / 2 - (item.x + NODE_W / 2) * k,
1470
+ y: rect.height / 2 - (item.y + NODE_H / 2) * k,
1471
+ })
1472
+ }, [])
1473
+
1474
+ /* A session selected in the left sidebar roots the map at its topic and focuses its node. */
1475
+ React.useEffect(() => {
1476
+ if (currentId === undefined || currentId === lastCurrentRef.current) return
1477
+ lastCurrentRef.current = currentId
1478
+ setSelectedId(currentId)
1479
+ setRootOverride(undefined)
1480
+ pendingCenterRef.current = currentId
1481
+ }, [currentId])
1482
+
1483
+ /* health + cached summaries */
1484
+ React.useEffect(() => {
1485
+ let alive = true
1486
+ fetch(`${API}/health`)
1487
+ .then((response) => response.json())
1488
+ .then((value) => {
1489
+ if (!alive || value.ok !== true) return
1490
+ setHostConfig({ autoSummarize: value.autoSummarize !== false, available: true })
1491
+ })
1492
+ .catch(() => {
1493
+ if (alive) setHostConfig({ autoSummarize: false, available: false })
1494
+ })
1495
+ return () => {
1496
+ alive = false
1497
+ }
1498
+ }, [])
1499
+
1500
+ const requestSummary = React.useCallback(async (node, force) => {
1501
+ if (node === undefined) return undefined
1502
+ if (pendingRef.current.has(node.id)) return undefined
1503
+ const key = `${node.id}:${node.updatedAt}`
1504
+ if (force !== true && requestedRef.current.has(key)) return undefined
1505
+ requestedRef.current.add(key)
1506
+ pendingRef.current.add(node.id)
1507
+ setPending((previous) => ({ ...previous, [node.id]: true }))
1508
+ try {
1509
+ const value = await api('summarize', { sessionId: node.id, force: force === true })
1510
+ if (value.summary !== null && value.summary !== undefined) {
1511
+ setSummaries((previous) => ({ ...previous, [node.id]: value.summary }))
1512
+ return value.summary
1513
+ }
1514
+ } catch (error) {
1515
+ notify(`${t('summaryFailed')}: ${error.message}`)
1516
+ } finally {
1517
+ pendingRef.current.delete(node.id)
1518
+ setPending((previous) => {
1519
+ const next = { ...previous }
1520
+ delete next[node.id]
1521
+ return next
1522
+ })
1523
+ }
1524
+ return undefined
1525
+ }, [notify, t])
1526
+
1527
+ /* cached summaries for the current tree */
1528
+ React.useEffect(() => {
1529
+ if (rootId === undefined) return
1530
+ let alive = true
1531
+ if (treeIds.length === 0) return
1532
+ api('summaries', { ids: treeIds }).then((value) => {
1533
+ if (!alive) return
1534
+ setSummaries((previous) => ({ ...previous, ...(value.summaries ?? {}) }))
1535
+ }).catch(() => {
1536
+ if (alive) setFetchError(true)
1537
+ })
1538
+ return () => {
1539
+ alive = false
1540
+ }
1541
+ }, [rootId, treeIds])
1542
+
1543
+ /* auto-summary: idle, non-blank topics of this tree, one small batch */
1544
+ React.useEffect(() => {
1545
+ if (hostConfig.autoSummarize !== true) return
1546
+ const timer = setTimeout(() => {
1547
+ const now = Date.now()
1548
+ const candidates = layout.items
1549
+ .map((item) => item.node)
1550
+ .filter((node) => {
1551
+ if (node.blank === true || node.running === true) return false
1552
+ const turns = countTurns(node)
1553
+ if (turns === undefined || turns < 1) return false
1554
+ if (typeof node.updatedAt === 'number' && now - node.updatedAt < 12_000) return false
1555
+ if (typeof node.updatedAt === 'number' && now - node.updatedAt > 30 * 86_400_000) return false
1556
+ const cached = summaries[node.id]
1557
+ if (cached !== undefined && cached.at >= node.updatedAt) return false
1558
+ return true
1559
+ })
1560
+ for (const node of candidates.slice(0, 3)) void requestSummary(node, false)
1561
+ }, 1400)
1562
+ return () => clearTimeout(timer)
1563
+ }, [layout, summaries, hostConfig.autoSummarize, requestSummary])
1564
+
1565
+ /* fit on root change */
1566
+ React.useEffect(() => {
1567
+ if (pendingCenterRef.current !== undefined) return
1568
+ const canvas = canvasRef.current
1569
+ if (canvas === null || layout.items.length === 0) return
1570
+ const rect = canvas.getBoundingClientRect()
1571
+ if (rect.width < 40 || rect.height < 40) return
1572
+ const scale = Math.min(1.05, Math.max(0.28, Math.min((rect.width - 72) / layout.width, (rect.height - 72) / layout.height)))
1573
+ setView({
1574
+ k: scale,
1575
+ x: (rect.width - layout.width * scale) / 2,
1576
+ y: (rect.height - layout.height * scale) / 2,
1577
+ })
1578
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- refit only when the root changes
1579
+ }, [rootId])
1580
+
1581
+ /* Center the node chosen from the left sidebar after its tree/layout exists. */
1582
+ React.useEffect(() => {
1583
+ const id = pendingCenterRef.current
1584
+ if (id === undefined) return
1585
+ const item = layout.items.find((candidate) => candidate.id === id)
1586
+ if (item === undefined) return
1587
+ pendingCenterRef.current = undefined
1588
+ centerOnItem(item)
1589
+ }, [layout, centerOnItem])
1590
+
1591
+ /* wheel zoom (non-passive listener so ctrl+wheel does not zoom the page) */
1592
+ React.useEffect(() => {
1593
+ const canvas = canvasRef.current
1594
+ if (canvas === null) return undefined
1595
+ const onWheel = (event) => {
1596
+ const rect = canvas.getBoundingClientRect()
1597
+ const pointerX = event.clientX - rect.left
1598
+ const pointerY = event.clientY - rect.top
1599
+ if (event.ctrlKey || event.metaKey) {
1600
+ event.preventDefault()
1601
+ setView((previous) => {
1602
+ const factor = Math.exp(-event.deltaY * 0.0018)
1603
+ const k = Math.min(2.2, Math.max(0.25, previous.k * factor))
1604
+ const ratio = k / previous.k
1605
+ return { k, x: pointerX - (pointerX - previous.x) * ratio, y: pointerY - (pointerY - previous.y) * ratio }
1606
+ })
1607
+ } else {
1608
+ event.preventDefault()
1609
+ setView((previous) => ({ ...previous, x: previous.x - event.deltaX, y: previous.y - event.deltaY }))
1610
+ }
1611
+ }
1612
+ canvas.addEventListener('wheel', onWheel, { passive: false })
1613
+ return () => canvas.removeEventListener('wheel', onWheel)
1614
+ }, [])
1615
+
1616
+ /* keyboard */
1617
+ React.useEffect(() => {
1618
+ const onKey = (event) => {
1619
+ if ((event.ctrlKey || event.metaKey) && event.shiftKey && (event.key === 'M' || event.key === 'm')) {
1620
+ event.preventDefault()
1621
+ if (float.open) hideFloat()
1622
+ else if (selectedId !== undefined) void toggleFloat()
1623
+ return
1624
+ }
1625
+ if (event.key !== 'Escape') return
1626
+ const target = event.target
1627
+ const insideFloat = target !== null && typeof target.closest === 'function' && target.closest('.mm-float') !== null
1628
+ if (float.open && !insideFloat) {
1629
+ hideFloat()
1630
+ return
1631
+ }
1632
+ if (selectedId !== undefined) setSelectedId(undefined)
1633
+ }
1634
+ window.addEventListener('keydown', onKey)
1635
+ return () => window.removeEventListener('keydown', onKey)
1636
+ }, [selectedId, float.open])
1637
+
1638
+ const fit = React.useCallback(() => {
1639
+ const canvas = canvasRef.current
1640
+ if (canvas === null) return
1641
+ const rect = canvas.getBoundingClientRect()
1642
+ const scale = Math.min(1.05, Math.max(0.28, Math.min((rect.width - 72) / layout.width, (rect.height - 72) / layout.height)))
1643
+ setView({ k: scale, x: (rect.width - layout.width * scale) / 2, y: (rect.height - layout.height * scale) / 2 })
1644
+ }, [layout])
1645
+
1646
+ const zoom = (factor) => {
1647
+ const canvas = canvasRef.current
1648
+ if (canvas === null) return
1649
+ const rect = canvas.getBoundingClientRect()
1650
+ setView((previous) => {
1651
+ const k = Math.min(2.2, Math.max(0.25, previous.k * factor))
1652
+ const ratio = k / previous.k
1653
+ return { k, x: rect.width / 2 - (rect.width / 2 - previous.x) * ratio, y: rect.height / 2 - (rect.height / 2 - previous.y) * ratio }
1654
+ })
1655
+ }
1656
+
1657
+ const toggle = (id) => {
1658
+ setCollapsed((previous) => {
1659
+ const next = new Set(previous)
1660
+ if (next.has(id)) next.delete(id)
1661
+ else next.add(id)
1662
+ return next
1663
+ })
1664
+ }
1665
+
1666
+ const archiveDraft = () => {
1667
+ const id = float.sessionId
1668
+ if (float.mode !== 'child' || id === undefined) return
1669
+ const node = list.byId?.[id]
1670
+ const startedAt = float.startedAt ?? 0
1671
+ const untouched = node === undefined
1672
+ || node.blank === true
1673
+ || (typeof node.updatedAt === 'number' && node.updatedAt <= startedAt)
1674
+ if (!untouched) return
1675
+ try {
1676
+ const result = ctx.uiWorkspace?.archiveSession?.(id)
1677
+ if (result !== undefined && typeof result.catch === 'function') result.catch(() => {})
1678
+ } catch {
1679
+ // A draft that cannot be archived stays hidden until the next workspace refresh.
1680
+ }
1681
+ }
1682
+
1683
+ const resetFloat = () => {
1684
+ setTurnsTarget(undefined)
1685
+ setTurnConfirm(undefined)
1686
+ setFloat({
1687
+ open: false,
1688
+ minimized: false,
1689
+ sessionId: undefined,
1690
+ mode: 'chat',
1691
+ parentId: undefined,
1692
+ brief: false,
1693
+ startedAt: 0,
1694
+ })
1695
+ }
1696
+
1697
+ const closeFloat = () => {
1698
+ archiveDraft()
1699
+ resetFloat()
1700
+ }
1701
+
1702
+ const confirmDelete = async () => {
1703
+ if (deleteTarget === undefined || deleting) return
1704
+ setDeleting(true)
1705
+ try {
1706
+ await ctx.uiWorkspace.archiveSession(deleteTarget.id, { stopActivity: true })
1707
+ if (float.sessionId === deleteTarget.id) resetFloat()
1708
+ if (selectedId === deleteTarget.id) setSelectedId(undefined)
1709
+ notify(t('archived'))
1710
+ setDeleteTarget(undefined)
1711
+ } catch (error) {
1712
+ notify(`${t('archiveFailed')}: ${error instanceof Error ? error.message : String(error)}`)
1713
+ } finally {
1714
+ setDeleting(false)
1715
+ }
1716
+ }
1717
+
1718
+ const hideFloat = () => {
1719
+ setFloat((previous) => ({ ...previous, open: false }))
1720
+ }
1721
+
1722
+ const setFloatMinimized = (minimized) => {
1723
+ setFloat((previous) => {
1724
+ const next = { ...previous, minimized }
1725
+ writeStorage(FLOAT_KEY, { ...geometry, minimized })
1726
+ return next
1727
+ })
1728
+ }
1729
+
1730
+ const rememberGeometry = (value) => {
1731
+ setGeometry(value)
1732
+ writeStorage(FLOAT_KEY, { ...value, minimized: float.minimized })
1733
+ }
1734
+
1735
+ /* View or continue an existing topic. */
1736
+ const showChat = async (id) => {
1737
+ if (id === undefined || id === null) return false
1738
+ archiveDraft()
1739
+ if (float.open && float.mode === 'chat' && float.sessionId === id) {
1740
+ if (float.minimized) setFloatMinimized(false)
1741
+ return true
1742
+ }
1743
+ setSelectedId(id)
1744
+ setRootOverride(undefined)
1745
+ pendingCenterRef.current = id
1746
+ setFloat({
1747
+ open: true,
1748
+ minimized: false,
1749
+ sessionId: id,
1750
+ mode: 'chat',
1751
+ parentId: undefined,
1752
+ brief: false,
1753
+ startedAt: 0,
1754
+ })
1755
+ let opened = false
1756
+ try {
1757
+ opened = await openSession(ctx, id)
1758
+ } catch (error) {
1759
+ console.warn('[mindmap] could not select the session for the float:', error)
1760
+ }
1761
+ try {
1762
+ ctx.layout.selectPanel(PANEL_ID)
1763
+ } catch {
1764
+ // The map panel can be between registrations during HMR; selection still worked.
1765
+ }
1766
+ if (!opened) {
1767
+ notify(t('openFailed'))
1768
+ // Keep the retained float alive: the workspace selection may be
1769
+ // temporarily unavailable while a turn is settling.
1770
+ return false
1771
+ }
1772
+ return true
1773
+ }
1774
+
1775
+ /* New child: fork eagerly, keep the parent selected, and let the first
1776
+ * message turn the blank draft into a visible child node. */
1777
+ const startChild = async (parentId, brief = false) => {
1778
+ if (parentId === undefined || parentId === null) return false
1779
+ archiveDraft()
1780
+ let childId
1781
+ let effectiveBrief = brief
1782
+ try {
1783
+ childId = brief
1784
+ ? await ctx.sessions.fork({ sessionId: parentId, atSeq: 0 })
1785
+ : await ctx.sessions.fork({ sessionId: parentId })
1786
+ } catch (error) {
1787
+ if (!brief) {
1788
+ try {
1789
+ childId = await ctx.sessions.fork({ sessionId: parentId, atSeq: 0 })
1790
+ effectiveBrief = true
1791
+ } catch (fallbackError) {
1792
+ notify(`${t('branchFailed')}: ${fallbackError instanceof Error ? fallbackError.message : String(fallbackError)}`)
1793
+ return false
1794
+ }
1795
+ } else {
1796
+ notify(`${t('branchFailed')}: ${error instanceof Error ? error.message : String(error)}`)
1797
+ return false
1798
+ }
1799
+ }
1800
+ setSelectedId(parentId)
1801
+ setRootOverride(undefined)
1802
+ pendingCenterRef.current = parentId
1803
+ setFloat({
1804
+ open: true,
1805
+ minimized: false,
1806
+ sessionId: childId,
1807
+ mode: 'child',
1808
+ parentId,
1809
+ brief: effectiveBrief,
1810
+ startedAt: Date.now(),
1811
+ })
1812
+ try {
1813
+ ctx.layout.selectPanel(PANEL_ID)
1814
+ } catch {
1815
+ // Already on the map in the normal path.
1816
+ }
1817
+ return true
1818
+ }
1819
+
1820
+ const openTurns = async (sessionId) => {
1821
+ setTurnsTarget(sessionId)
1822
+ setTurns([])
1823
+ setTurnsLoading(true)
1824
+ setTurnsError(undefined)
1825
+ setTurnConfirm(undefined)
1826
+ try {
1827
+ const response = await fetch(`${API}/turns`, {
1828
+ method: 'POST',
1829
+ headers: { 'content-type': 'application/json' },
1830
+ body: JSON.stringify({ sessionId }),
1831
+ })
1832
+ const payload = await response.json()
1833
+ if (payload.ok !== true) throw new Error(payload.error?.message ?? 'could not read turns')
1834
+ setTurns(Array.isArray(payload.turns) ? payload.turns : [])
1835
+ } catch (error) {
1836
+ const message = error instanceof Error ? error.message : String(error)
1837
+ setTurnsError(/unknown mindmap method\s+["']?turns/i.test(message) ? t('hostStale') : message)
1838
+ } finally {
1839
+ setTurnsLoading(false)
1840
+ }
1841
+ }
1842
+
1843
+ const closeTurns = () => {
1844
+ if (rewinding) return
1845
+ setTurnsTarget(undefined)
1846
+ setTurns([])
1847
+ setTurnConfirm(undefined)
1848
+ setTurnsError(undefined)
1849
+ }
1850
+
1851
+ const rewindTo = async (turn) => {
1852
+ if (turnsTarget === undefined || rewinding || turn?.rewindAt === undefined) return
1853
+ const oldId = turnsTarget
1854
+ setRewinding(true)
1855
+ try {
1856
+ const childId = await ctx.sessions.fork({ sessionId: oldId, atSeq: turn.rewindAt })
1857
+ const oldTitle = titleOf(list.byId?.[oldId] ?? { id: oldId }, summaries[oldId])
1858
+ try {
1859
+ const title = `${oldTitle} · 回退`
1860
+ await renameSession(ctx, childId, title.length > 64 ? `${title.slice(0, 63)}…` : title)
1861
+ } catch {
1862
+ // A fork is still usable with the inherited title.
1863
+ }
1864
+ try {
1865
+ await ctx.uiWorkspace.archiveSession(oldId, { stopActivity: true })
1866
+ } catch (error) {
1867
+ notify(`${t('rewindArchiveFailed')}: ${error instanceof Error ? error.message : String(error)}`)
1868
+ }
1869
+ setTurnsTarget(undefined)
1870
+ setTurns([])
1871
+ setTurnConfirm(undefined)
1872
+ await showChat(childId)
1873
+ notify(t('rewound'))
1874
+ } catch (error) {
1875
+ notify(`${t('rewindFailed')}: ${error instanceof Error ? error.message : String(error)}`)
1876
+ } finally {
1877
+ setRewinding(false)
1878
+ }
1879
+ }
1880
+
1881
+ const toggleFloat = async () => {
1882
+ if (float.open) {
1883
+ hideFloat()
1884
+ return
1885
+ }
1886
+ if (float.sessionId !== undefined) {
1887
+ const node = list.byId?.[float.sessionId]
1888
+ if (float.mode === 'chat') {
1889
+ if (selectedId !== undefined && selectedId !== float.sessionId) {
1890
+ await showChat(selectedId)
1891
+ return
1892
+ }
1893
+ setFloat((previous) => ({ ...previous, open: true, minimized: false }))
1894
+ return
1895
+ }
1896
+ if (node?.blank !== false) {
1897
+ if (float.parentId === selectedId) {
1898
+ setFloat((previous) => ({ ...previous, open: true, minimized: false }))
1899
+ return
1900
+ }
1901
+ await startChild(selectedId)
1902
+ return
1903
+ }
1904
+ await showChat(float.sessionId)
1905
+ return
1906
+ }
1907
+ if (selectedId !== undefined) await startChild(selectedId)
1908
+ }
1909
+
1910
+ /* Remember the question while it is still in the draft box; the title
1911
+ * is applied when the first message turns the draft into a node. */
1912
+ React.useEffect(() => {
1913
+ lastDraftRef.current = ''
1914
+ if (!float.open || float.mode !== 'child' || float.sessionId === undefined) return undefined
1915
+ let disposed = false
1916
+ let unsubscribe
1917
+ let timer
1918
+ const shellRef = { current: undefined }
1919
+ const read = () => {
1920
+ if (disposed) return
1921
+ const shell = shellRef.current
1922
+ if (shell === undefined) return
1923
+ const text = shell.draftSnapshot
1924
+ if (typeof text === 'string' && text.trim() !== '') lastDraftRef.current = text.trim()
1925
+ }
1926
+ const attach = () => {
1927
+ if (disposed || shellRef.current !== undefined) return
1928
+ try {
1929
+ const input = ctx.get('conversation')?.input
1930
+ const shell = input?.shell?.(float.sessionId)
1931
+ if (shell === undefined) return
1932
+ shellRef.current = shell
1933
+ read()
1934
+ const stop = shell.state?.subscribe?.(read)
1935
+ if (typeof stop === 'function') unsubscribe = stop
1936
+ } catch {
1937
+ // The Session binding may still be materializing; retry once on the next task.
1938
+ if (timer === undefined) timer = setTimeout(attach, 60)
1939
+ }
1940
+ }
1941
+ attach()
1942
+ if (shellRef.current === undefined && timer === undefined) timer = setTimeout(attach, 0)
1943
+ return () => {
1944
+ disposed = true
1945
+ clearTimeout(timer)
1946
+ if (typeof unsubscribe === 'function') unsubscribe()
1947
+ }
1948
+ }, [float.open, float.mode, float.sessionId])
1949
+
1950
+ /* Turn a draft into a normal topic without touching the float's open
1951
+ * state. Workspace selection is best-effort; a settling turn must not
1952
+ * be allowed to close a window the user opened. */
1953
+ const settleChild = (childId) => {
1954
+ setFloat((previous) => previous.sessionId === childId
1955
+ ? { ...previous, mode: 'chat', parentId: undefined, brief: false, startedAt: 0 }
1956
+ : previous)
1957
+ setSelectedId(childId)
1958
+ setRootOverride(undefined)
1959
+ pendingCenterRef.current = childId
1960
+ try {
1961
+ const result = ctx.get('uiWorkspace')?.openSession?.(childId)
1962
+ if (result !== undefined && typeof result.catch === 'function') result.catch(() => {})
1963
+ } catch {
1964
+ // The float already owns a retained reference; selection can catch up later.
1965
+ }
1966
+ try {
1967
+ ctx.layout.selectPanel(PANEL_ID)
1968
+ } catch {
1969
+ // The map panel may be between registrations during HMR.
1970
+ }
1971
+ }
1972
+
1973
+ /* The draft child became a real topic after its first new message. */
1974
+ React.useEffect(() => {
1975
+ if (!float.open || float.mode !== 'child' || float.sessionId === undefined) return undefined
1976
+ if (settlingRef.current === float.sessionId) return undefined
1977
+ const node = list.byId?.[float.sessionId]
1978
+ if (node === undefined) return undefined
1979
+ const startedAt = float.startedAt ?? 0
1980
+ if (typeof node.updatedAt !== 'number' || node.updatedAt <= startedAt) return undefined
1981
+ let alive = true
1982
+ settlingRef.current = float.sessionId
1983
+ const childId = float.sessionId
1984
+ const question = lastDraftRef.current
1985
+ void (async () => {
1986
+ if (question !== '') {
1987
+ try {
1988
+ await renameSession(ctx, childId, question.length > 60 ? `${question.slice(0, 59)}…` : question)
1989
+ } catch {
1990
+ // The map still gets a node; the inherited title is a safe fallback.
1991
+ }
1992
+ }
1993
+ if (alive) settleChild(childId)
1994
+ })().finally(() => {
1995
+ if (settlingRef.current === childId) settlingRef.current = undefined
1996
+ })
1997
+ return () => {
1998
+ alive = false
1999
+ }
2000
+ }, [list, float.open, float.mode, float.sessionId, float.startedAt])
2001
+
2002
+ const openFull = async (id) => {
2003
+ closeFloat()
2004
+ MODE.bypass = true
2005
+ try {
2006
+ let opened = false
2007
+ try {
2008
+ opened = await openSession(ctx, id)
2009
+ } catch (error) {
2010
+ console.warn('[mindmap] could not open the full conversation:', error)
2011
+ }
2012
+ try {
2013
+ ctx.layout.selectPanel(null)
2014
+ } catch {
2015
+ // The floating fallback still offers a working map.
2016
+ }
2017
+ if (!opened) notify(t('openFailed'))
2018
+ } finally {
2019
+ setTimeout(() => {
2020
+ MODE.bypass = false
2021
+ }, 0)
2022
+ }
2023
+ }
2024
+
2025
+ const applyMapHome = (value) => {
2026
+ MODE.mapHome = value
2027
+ setMapHomeState(value)
2028
+ writeStorage(MAP_HOME_KEY, value)
2029
+ try {
2030
+ ctx.layout.selectPanel(value ? PANEL_ID : null)
2031
+ } catch {
2032
+ // Layout may still be mounting; the guard retries on the next selection.
2033
+ }
2034
+ }
2035
+
2036
+ const focusNode = (id) => {
2037
+ setSelectedId(id)
2038
+ if (!float.open) return
2039
+ if (float.mode === 'chat' && float.sessionId !== id) void showChat(id)
2040
+ else if (float.mode === 'child' && float.parentId !== id) hideFloat()
2041
+ }
2042
+
2043
+ const bridge = async (childId, parentId) => {
2044
+ const summary = summaries[childId]
2045
+ if (summary?.summary === undefined || summary.summary === '') {
2046
+ notify(t('carryFailed'))
2047
+ return
2048
+ }
2049
+ const label = titleOf(itemById.get(childId)?.node ?? { id: childId }, summary)
2050
+ const opened = await showChat(parentId)
2051
+ if (!opened) return
2052
+ const text = `【子话题「${label}」的结论】${summary.summary}`
2053
+ const prefilled = await prefillDraft(ctx, parentId, `${text}\n\n`, 'append')
2054
+ notify(prefilled ? t('carry', { name: label }) : t('openFailed'))
2055
+ }
2056
+
2057
+ const openRename = (id) => {
2058
+ if (id === undefined || id === null) return
2059
+ const node = itemById.get(id)?.node ?? list.byId?.[id] ?? { id }
2060
+ setRenameTarget({ id, title: titleOf(node, summaries[id]) })
2061
+ }
2062
+
2063
+ const performRename = async (id, title) => {
2064
+ await renameSession(ctx, id, title)
2065
+ setRenameTarget(undefined)
2066
+ notify(t('renamed'))
2067
+ }
2068
+
2069
+ const summarizeAll = async () => {
2070
+ if (hostConfig.available !== true) return
2071
+ const nodes = layout.items.map((item) => item.node)
2072
+ for (const node of nodes) {
2073
+ if (node.blank === true) continue
2074
+ if (pendingRef.current.has(node.id)) continue
2075
+ const cached = summaries[node.id]
2076
+ if (cached !== undefined && cached.at >= node.updatedAt) continue
2077
+ await requestSummary(node, false)
2078
+ }
2079
+ notify(t('allFresh'))
2080
+ }
2081
+
2082
+ const runningCount = layout.items.filter((item) => item.node.running === true).length
2083
+ const pendingCount = layout.items.filter((item) => pending[item.id] === true).length
2084
+
2085
+ const turnModal = turnsTarget === undefined ? null : h(
2086
+ 'div',
2087
+ {
2088
+ className: 'mm-overlay',
2089
+ role: 'presentation',
2090
+ onMouseDown: (event) => {
2091
+ if (event.target === event.currentTarget) closeTurns()
2092
+ },
2093
+ },
2094
+ h(
2095
+ 'div',
2096
+ { className: 'mm-modal wide', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('turnsTitle') },
2097
+ h(
2098
+ 'div',
2099
+ { className: 'mm-turnsHead' },
2100
+ h('h2', { className: 'mm-modalTitle' }, t('turnsTitle')),
2101
+ h('button', {
2102
+ type: 'button',
2103
+ className: 'mm-btn icon',
2104
+ disabled: rewinding,
2105
+ onClick: closeTurns,
2106
+ }, '×'),
2107
+ ),
2108
+ turnConfirm !== undefined
2109
+ ? h(
2110
+ 'div',
2111
+ null,
2112
+ h('p', { className: 'mm-modalText' }, t('rewindConfirm', { n: turnConfirm.index })),
2113
+ h('p', { className: 'mm-modalText' }, t('rewindHint')),
2114
+ h(
2115
+ 'div',
2116
+ { className: 'mm-modalFoot' },
2117
+ h('button', {
2118
+ type: 'button',
2119
+ className: 'mm-btn',
2120
+ disabled: rewinding,
2121
+ onClick: () => setTurnConfirm(undefined),
2122
+ }, t('cancel')),
2123
+ h('button', {
2124
+ type: 'button',
2125
+ className: 'mm-btn primary',
2126
+ disabled: rewinding,
2127
+ onClick: () => void rewindTo(turnConfirm),
2128
+ }, rewinding ? t('archiving') : t('rewindAction')),
2129
+ ),
2130
+ )
2131
+ : h(
2132
+ 'div',
2133
+ null,
2134
+ turnsLoading
2135
+ ? h('div', { className: 'mm-emptyLine' }, h('span', { className: 'mm-spin' }), t('summarizing'))
2136
+ : null,
2137
+ turnsError !== undefined ? h('div', { className: 'mm-error' }, turnsError) : null,
2138
+ !turnsLoading && turnsError === undefined && turns.length === 0
2139
+ ? h('p', { className: 'mm-modalText' }, t('turnsEmpty'))
2140
+ : null,
2141
+ h(
2142
+ 'div',
2143
+ { className: 'mm-turns' },
2144
+ turns.map((turn) => h(
2145
+ 'div',
2146
+ { className: 'mm-turn', key: String(turn.startSeq ?? turn.index) },
2147
+ h(
2148
+ 'div',
2149
+ { className: 'mm-turnHead' },
2150
+ h('span', { className: 'mm-turnIndex' }, t('turnN', { n: turn.index })),
2151
+ h('span', { className: 'mm-turnTime' }, formatTurnTime(turn.at)),
2152
+ h('button', {
2153
+ type: 'button',
2154
+ className: 'mm-btn',
2155
+ disabled: turn.rewindAt === undefined,
2156
+ onClick: () => setTurnConfirm(turn),
2157
+ }, t('rewindTitle')),
2158
+ ),
2159
+ h('div', { className: 'mm-turnText' }, turn.user),
2160
+ turn.assistant !== '' ? h('div', { className: 'mm-turnSub' }, turn.assistant) : null,
2161
+ )),
2162
+ ),
2163
+ ),
2164
+ ),
2165
+ )
2166
+
2167
+ if (list.phase === 'pending' && forest.roots.length === 0) {
2168
+ return h('div', { className: 'mm-root' },
2169
+ h('div', { className: 'mm-empty' }, h('span', { className: 'mm-spin', style: { width: '18px', height: '18px' } })))
2170
+ }
2171
+
2172
+ if (forest.roots.length === 0) {
2173
+ return h(
2174
+ 'div',
2175
+ { className: 'mm-root' },
2176
+ h('div', { className: 'mm-head' },
2177
+ h('div', { className: 'mm-headMain' },
2178
+ h('div', { className: 'mm-headTitle' }, t('title')),
2179
+ h('div', { className: 'mm-headSub' }, t('panel'))),
2180
+ h('div', { className: 'mm-headActions' },
2181
+ h('button', { type: 'button', className: 'mm-btn', onClick: () => setShowSubagents((value) => !value) },
2182
+ t('showSubagents')))),
2183
+ h('div', { className: 'mm-empty' },
2184
+ h(IconMindmap, { size: 34 }),
2185
+ h('h2', { className: 'mm-emptyTitle' }, t('emptyTitle')),
2186
+ h('p', { className: 'mm-emptyText' }, t('emptyText'))),
2187
+ )
2188
+ }
2189
+
2190
+ return h(
2191
+ 'div',
2192
+ { className: 'mm-root', ref: rootRef },
2193
+ h(
2194
+ 'div',
2195
+ { className: 'mm-head' },
2196
+ h(
2197
+ 'div',
2198
+ { className: 'mm-headMain' },
2199
+ h('div', { className: 'mm-headTitle' }, t('title')),
2200
+ h('div', { className: 'mm-headSub' },
2201
+ t('subtitle', { n: layout.items.length, running: runningCount }),
2202
+ pendingCount > 0 ? ` · ${t('summarizingCount', { n: pendingCount })}` : ''),
2203
+ ),
2204
+ h(
2205
+ 'div',
2206
+ { className: 'mm-headActions' },
2207
+ h('button', {
2208
+ type: 'button',
2209
+ className: 'mm-btn mm-mode',
2210
+ 'data-active': mapHome,
2211
+ title: t('mapHomeHint'),
2212
+ onClick: () => applyMapHome(!mapHome),
2213
+ }, t('mapHome')),
2214
+ h('button', {
2215
+ type: 'button',
2216
+ className: 'mm-btn mm-mode',
2217
+ 'data-active': float.open,
2218
+ title: t('floatHint'),
2219
+ onClick: () => void toggleFloat(),
2220
+ }, t('floatToggle')),
2221
+ forest.roots.length > 1
2222
+ ? h('select', {
2223
+ className: 'mm-select',
2224
+ 'aria-label': t('title'),
2225
+ value: rootTree?.id ?? '',
2226
+ onChange: (event) => {
2227
+ setRootOverride(event.target.value)
2228
+ setSelectedId(undefined)
2229
+ },
2230
+ }, forest.roots.map((candidate) => {
2231
+ const label = titleOf(candidate.node, summaries[candidate.id])
2232
+ const total = 1 + countDescendants(candidate)
2233
+ return h('option', { key: candidate.id, value: candidate.id }, `${label} · ${total}`)
2234
+ }))
2235
+ : null,
2236
+ h('button', { type: 'button', className: 'mm-btn', title: t('zoomOut'), onClick: () => zoom(0.85) }, '−'),
2237
+ h('button', { type: 'button', className: 'mm-btn', title: t('zoomIn'), onClick: () => zoom(1.18) }, '+'),
2238
+ h('button', { type: 'button', className: 'mm-btn', onClick: fit }, t('fit')),
2239
+ h('button', {
2240
+ type: 'button',
2241
+ className: 'mm-btn',
2242
+ disabled: !hostConfig.available,
2243
+ onClick: () => void summarizeAll(),
2244
+ }, t('refreshAll')),
2245
+ h('button', {
2246
+ type: 'button',
2247
+ className: 'mm-btn',
2248
+ 'data-active': showSubagents,
2249
+ onClick: () => setShowSubagents((value) => !value),
2250
+ }, t('showSubagents')),
2251
+ ),
2252
+ ),
2253
+ fetchError === true || hostConfig.available === false
2254
+ ? h('div', { className: 'mm-error' }, t('fetchFailed'))
2255
+ : null,
2256
+ h(
2257
+ 'div',
2258
+ { className: 'mm-body' },
2259
+ h(
2260
+ 'div',
2261
+ {
2262
+ className: 'mm-canvas',
2263
+ ref: canvasRef,
2264
+ tabIndex: 0,
2265
+ 'data-dragging': dragRef.current !== undefined,
2266
+ onPointerDown: (event) => {
2267
+ if (event.button !== 0) return
2268
+ const target = event.target
2269
+ if (target !== null && typeof target.closest === 'function' && target.closest('.mm-node') !== null) return
2270
+ dragRef.current = { x: event.clientX, y: event.clientY, ox: viewRef.current.x, oy: viewRef.current.y }
2271
+ event.currentTarget.setPointerCapture?.(event.pointerId)
2272
+ event.currentTarget.dataset.dragging = 'true'
2273
+ },
2274
+ onPointerMove: (event) => {
2275
+ const drag = dragRef.current
2276
+ if (drag === undefined) return
2277
+ setView((previous) => ({
2278
+ ...previous,
2279
+ x: drag.ox + event.clientX - drag.x,
2280
+ y: drag.oy + event.clientY - drag.y,
2281
+ }))
2282
+ },
2283
+ onPointerUp: (event) => {
2284
+ dragRef.current = undefined
2285
+ event.currentTarget.dataset.dragging = 'false'
2286
+ event.currentTarget.releasePointerCapture?.(event.pointerId)
2287
+ },
2288
+ onPointerCancel: () => {
2289
+ dragRef.current = undefined
2290
+ },
2291
+ },
2292
+ h(
2293
+ 'div',
2294
+ {
2295
+ className: 'mm-world',
2296
+ style: { transform: `translate(${view.x}px, ${view.y}px) scale(${view.k})`, width: layout.width, height: layout.height },
2297
+ },
2298
+ h(
2299
+ 'svg',
2300
+ { className: 'mm-edges', width: layout.width, height: layout.height, 'aria-hidden': 'true' },
2301
+ layout.edges.map((edge, index) => h('path', {
2302
+ key: index,
2303
+ className: 'mm-edge',
2304
+ d: edgePath(edge.from, edge.to),
2305
+ 'data-active': selectedId === edge.to.id,
2306
+ })),
2307
+ ),
2308
+ layout.items.map((item) => h(NodeCard, {
2309
+ key: item.id,
2310
+ item,
2311
+ summary: summaries[item.id],
2312
+ pending: pending[item.id] === true,
2313
+ selected: selectedId === item.id,
2314
+ current: currentId === item.id,
2315
+ collapsed: collapsed.has(item.id),
2316
+ t,
2317
+ onSelect: focusNode,
2318
+ onOpen: (id) => void openFull(id),
2319
+ onFloat: (id) => void showChat(id),
2320
+ onBranch: (id) => void startChild(id),
2321
+ onRename: openRename,
2322
+ onToggle: toggle,
2323
+ })),
2324
+ ),
2325
+ ),
2326
+ selected !== undefined && float.open !== true
2327
+ ? h(Drawer, {
2328
+ item: selected,
2329
+ summary: summaries[selected.id],
2330
+ pending: pending[selected.id] === true,
2331
+ t,
2332
+ ctx,
2333
+ current: currentId === selected.id,
2334
+ onClose: () => setSelectedId(undefined),
2335
+ onOpen: (id) => void openFull(id),
2336
+ onFloat: (id) => void showChat(id),
2337
+ onChild: (id, brief) => void startChild(id, brief === true),
2338
+ onBranch: (id) => void startChild(id),
2339
+ onRename: openRename,
2340
+ onRefresh: (id) => void requestSummary(itemById.get(id)?.node, true),
2341
+ onBridge: (childId, parentId) => void bridge(childId, parentId),
2342
+ toast: notify,
2343
+ })
2344
+ : null,
2345
+ ),
2346
+ selected !== undefined && float.open !== true
2347
+ ? h('button', {
2348
+ type: 'button',
2349
+ className: 'mm-cta',
2350
+ onClick: () => void startChild(selected.id),
2351
+ title: t('newChildHint'),
2352
+ }, `+ ${t('askChild')}`, h('kbd', null, t('floatShortcut')))
2353
+ : null,
2354
+ float.open === true && float.sessionId !== undefined
2355
+ ? h(FloatingConversation, {
2356
+ sessionId: float.sessionId,
2357
+ node: itemById.get(float.sessionId)?.node ?? list.byId?.[float.sessionId],
2358
+ parentLabel: float.parentId === undefined
2359
+ ? undefined
2360
+ : titleOf(list.byId?.[float.parentId] ?? { id: float.parentId }, summaries[float.parentId]),
2361
+ summary: summaries[float.sessionId],
2362
+ mode: float.mode,
2363
+ brief: float.brief,
2364
+ t,
2365
+ ctx,
2366
+ SessionProvider,
2367
+ renderFactorySlot,
2368
+ initialGeometry: geometry,
2369
+ minimized: float.minimized === true,
2370
+ boundsRef: rootRef,
2371
+ onGeometry: rememberGeometry,
2372
+ onMinimize: () => setFloatMinimized(true),
2373
+ onRestore: () => setFloatMinimized(false),
2374
+ onNewChild: () => void startChild(float.sessionId),
2375
+ onRename: () => openRename(float.sessionId),
2376
+ onDelete: () => setDeleteTarget({
2377
+ id: float.sessionId,
2378
+ title: float.mode === 'child'
2379
+ ? t('newChild')
2380
+ : titleOf(list.byId?.[float.sessionId] ?? { id: float.sessionId }, summaries[float.sessionId]),
2381
+ }),
2382
+ onTurns: () => void openTurns(float.sessionId),
2383
+ onClose: closeFloat,
2384
+ onFull: () => void openFull(
2385
+ float.mode === 'child' && float.parentId !== undefined ? float.parentId : float.sessionId,
2386
+ ),
2387
+ })
2388
+ : null,
2389
+ renameTarget !== undefined
2390
+ ? h(RenameDialog, {
2391
+ target: renameTarget,
2392
+ t,
2393
+ onCancel: () => setRenameTarget(undefined),
2394
+ onRename: performRename,
2395
+ })
2396
+ : null,
2397
+ turnModal,
2398
+ deleteTarget !== undefined
2399
+ ? h('div', {
2400
+ className: 'mm-overlay',
2401
+ role: 'presentation',
2402
+ onMouseDown: (event) => {
2403
+ if (event.target === event.currentTarget && !deleting) setDeleteTarget(undefined)
2404
+ },
2405
+ },
2406
+ h('div', { className: 'mm-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('archiveTitle') },
2407
+ h('h2', { className: 'mm-modalTitle' }, t('archiveTitle')),
2408
+ h('p', { className: 'mm-modalText' }, `${deleteTarget.title} — ${t('archiveText')}`),
2409
+ h('div', { className: 'mm-modalFoot' },
2410
+ h('button', {
2411
+ type: 'button',
2412
+ className: 'mm-btn',
2413
+ disabled: deleting,
2414
+ onClick: () => setDeleteTarget(undefined),
2415
+ }, t('cancel')),
2416
+ h('button', {
2417
+ type: 'button',
2418
+ className: 'mm-btn primary',
2419
+ disabled: deleting,
2420
+ onClick: () => void confirmDelete(),
2421
+ }, deleting ? t('archiving') : t('archive')))))
2422
+ : null,
2423
+ toast !== undefined ? h('div', { className: 'mm-toast', role: 'status' }, toast) : null,
2424
+ )
2425
+ }
2426
+
2427
+ /* `apply` runs inside the client Cordis fiber; components reach the same
2428
+ * context through this module-scope binding. */
2429
+ let REACT_CTX
2430
+
2431
+ const inject = ['slots', 'sessions', 'locale', 'layout', 'uiWorkspace']
2432
+
2433
+ function apply(ctx) {
2434
+ REACT_CTX = ctx
2435
+ MODE.mapHome = readMapHome()
2436
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'mindmap: dictionaries')
2437
+ const t = ctx.locale.bind(NS)
2438
+
2439
+ ctx.slots.inject('main', () => {
2440
+ const dispose = ctx.slots.register({
2441
+ name: 'main',
2442
+ key: PANEL_ID,
2443
+ locale: NS,
2444
+ label: () => t('panel'),
2445
+ // A non-root child gives this entry the standard SessionProvider and
2446
+ // lets the floating window host the official conversation content.
2447
+ children: {
2448
+ 'mindmap.session-host': { kind: 'single', scope: 'session' },
2449
+ },
2450
+ }, App)
2451
+ setTimeout(() => {
2452
+ if (!MODE.mapHome || MODE.bypass) return
2453
+ try {
2454
+ ctx.layout.selectPanel(PANEL_ID)
2455
+ } catch {
2456
+ // Layout may not have committed the panel registry yet.
2457
+ }
2458
+ }, 0)
2459
+ return dispose
2460
+ })
2461
+
2462
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
2463
+ name: 'sidebar.panellist',
2464
+ id: PANEL_ID,
2465
+ order: 20,
2466
+ locale: NS,
2467
+ label: () => t('panel'),
2468
+ }, IconMindmap))
2469
+
2470
+ /* In map-home mode a Session selection (left sidebar, search, a plugin)
2471
+ * must load the map instead of switching the main panel to conversation.
2472
+ * uiWorkspace.openSession already retains/selects the session; only the
2473
+ * panel choice is overridden, so the right sidebar follows normally. */
2474
+ const workspace = ctx.uiWorkspace
2475
+ const originalOpenSession = workspace?.openSession
2476
+ if (workspace !== undefined && typeof originalOpenSession === 'function') {
2477
+ try {
2478
+ workspace.openSession = function guardedOpenSession(target, ...rest) {
2479
+ const result = originalOpenSession.apply(this, [target, ...rest])
2480
+ if (MODE.mapHome && !MODE.bypass) {
2481
+ try {
2482
+ ctx.layout.selectPanel(PANEL_ID)
2483
+ } catch {
2484
+ // The map panel is between registration and layout during HMR.
2485
+ }
2486
+ }
2487
+ return result
2488
+ }
2489
+ ctx.effect(() => () => {
2490
+ if (workspace.openSession !== originalOpenSession) workspace.openSession = originalOpenSession
2491
+ }, 'mindmap: openSession guard')
2492
+ } catch {
2493
+ // A frozen service falls back to the panel-info guard below.
2494
+ }
2495
+ }
2496
+
2497
+ ctx.effect(() => {
2498
+ const info = ctx.layout.panelInfo
2499
+ const enforce = () => {
2500
+ if (!MODE.mapHome || MODE.bypass) return
2501
+ const active = info.getSnapshot().activePanelId
2502
+ if (active === null || active === 'conversation') {
2503
+ try {
2504
+ ctx.layout.selectPanel(PANEL_ID)
2505
+ } catch {
2506
+ // The main panel is not registered yet; the next change retries.
2507
+ }
2508
+ }
2509
+ }
2510
+ const dispose = info.subscribe(enforce)
2511
+ enforce()
2512
+ return dispose
2513
+ }, 'mindmap: map-home guard')
2514
+ }
2515
+
2516
+ exports.name = 'mindmap'
2517
+ exports.inject = inject
2518
+ exports.apply = apply
2519
+ exports.__test = {
2520
+ buildForest,
2521
+ layoutTree,
2522
+ edgePath,
2523
+ titleOf,
2524
+ relTime,
2525
+ makeT,
2526
+ dictionaries: { zh, en },
2527
+ constants: { NODE_W, NODE_H, GAP_X, GAP_Y, PAD, PANEL_ID },
2528
+ }
2529
+ return module.exports
2530
+ },
2531
+ })