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