dsh-session-matrix 0.0.0-stage → 0.16.2

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,3398 @@
1
+ /**
2
+ * DSH Session Matrix — browser half.
3
+ *
4
+ * Two surfaces, and only two:
5
+ * workspace — one pane per session, showing that session's own transcript
6
+ * (read through the plugin's host route) plus the metrics that
7
+ * decide whether it needs attention. "Enter" hands over to the
8
+ * native conversation, which is where writing happens.
9
+ * Panes are NOT iframes: the desktop shell only runs preload in
10
+ * the main frame, so a framed copy of the app hangs forever on
11
+ * `__DSH_BOOT_READY__` before any plugin can load.
12
+ * cockpit — rectangular layered session network + three context modules.
13
+ *
14
+ * All colour, radius and hairline values come from the host theme
15
+ * (`--dsw-alias-*`, `--dsw-radius-*`, `--dsh-hairline-width`). No palette is
16
+ * hardcoded, so light / dark / third-party themes all apply. No glow, no blur:
17
+ * hierarchy comes from spacing, weight and hairlines.
18
+ */
19
+
20
+ window.__ModuleLoader__.load({
21
+ id: 'dsh-session-matrix',
22
+ factory(require) {
23
+ const React = require('react')
24
+ const h = React.createElement
25
+
26
+ const API = 'api/session-matrix'
27
+
28
+ const T = {
29
+ product: '会话矩阵工作台',
30
+ viewWorkspace: '工作区',
31
+ viewCockpit: '智能体脉络',
32
+ all: '全部',
33
+ search: '搜索会话、模型…',
34
+ sessions: '会话',
35
+ refresh: '刷新',
36
+ previewRisk: '模拟预警',
37
+ restore: '恢复真实值',
38
+ openNative: '在原生界面打开',
39
+ enter: '进入',
40
+ newPane: '分栏',
41
+ closePane: '关闭',
42
+ pickSession: '从左侧选择一个会话',
43
+ pickSessionHint: '点左侧任一会话,这里直接嵌入它的原生对话;同一个会话只占一个窗格,最多 4 栏',
44
+ composition: '上下文构成',
45
+ matrix: '会话概览',
46
+ inspector: '会话详情',
47
+ pickNode: '点击网络中的任一节点查看详情',
48
+ noSession: '当前筛选下没有会话',
49
+ used: '已用',
50
+ capacity: '容量',
51
+ usage: '占用',
52
+ turnsSteps: '轮次 / 步',
53
+ noDaily: '无按日统计',
54
+ parts: '构成明细',
55
+ noParts: '该会话暂无构成数据',
56
+ cost: '预估费用',
57
+ cacheHit: '缓存命中',
58
+ usageTitle: '累计用量与费用',
59
+ tokIn: '输入',
60
+ tokOut: '输出',
61
+ tokRead: '缓存读',
62
+ tokWrite: '缓存写',
63
+ requests: '请求',
64
+ zoom: '缩放',
65
+ scopeAll: '全部会话',
66
+ scopePrefix: '范围',
67
+ handoff: '通用交接提示词',
68
+ handoffTitle: '通用交接提示词',
69
+ handoffNote: '只复制,不发送、不改动任何会话',
70
+ handoffTip: '点开看看、改改、复制走。不会替你发送,也不会动任何会话。',
71
+ handoffTip2: '换模型、换 Agent、今天先收工,用得上就来复制。',
72
+ whyTitle: '为什么建议交接',
73
+ howTitle: '怎么用',
74
+ targetTitle: '交接对象',
75
+ scopeSub: '该子代理会话',
76
+ edgesNote: (p, s, c) => `${p} 个项目 · ${s} 个会话 · ${c} 条父子链路 · 0 条跨分支关联(数据源无此关系,不绘制)`,
77
+ levelOk: '正常',
78
+ levelWarn: '注意',
79
+ levelCrit: '临界',
80
+ levelUnknown: '无数据',
81
+ noRisk: '无风险',
82
+ loadFail: '数据加载失败',
83
+ loadFailHint: '请确认宿主半边已加载:GET /api/session-matrix/capabilities',
84
+ main: '主会话',
85
+ sub: '子代理',
86
+ hub: '工作台',
87
+ colProject: '项目',
88
+ colSession: '会话',
89
+ colSub: '子代理',
90
+ noTitle: '未命名会话',
91
+ ungrouped: '未归类',
92
+ }
93
+
94
+ const PARTS = [
95
+ ['system', '系统提示', 'var(--dsw-alias-chart-system)'],
96
+ ['tools', '工具定义', 'var(--dsw-alias-chart-tools)'],
97
+ ['user', '用户输入', 'var(--dsw-alias-chart-messages)'],
98
+ ['inject', '注入内容', 'var(--dsw-alias-state-done-primary)'],
99
+ ['skill', '技能目录', 'var(--dsw-alias-state-warn-primary)'],
100
+ ['assistant', '助手回复', 'var(--dsw-alias-state-success-primary)'],
101
+ ['tool', '工具返回', 'var(--dsw-alias-label-tertiary)'],
102
+ ]
103
+
104
+ const LEVEL_VAR = {
105
+ ok: 'var(--dsw-alias-label-tertiary)',
106
+ warn: 'var(--dsw-alias-state-warn-primary)',
107
+ crit: 'var(--dsw-alias-state-error-primary)',
108
+ unknown: 'var(--dsw-alias-state-idle-primary)',
109
+ }
110
+
111
+ const fmt = n => (n == null ? '—'
112
+ : n >= 1e9 ? (n / 1e9).toFixed(2) + 'G'
113
+ : n >= 1e6 ? (n / 1e6).toFixed(n >= 1e8 ? 0 : 2) + 'M'
114
+ : n >= 1e3 ? (n / 1e3).toFixed(n >= 1e5 ? 0 : 1) + 'k'
115
+ : String(n))
116
+
117
+ const pct = r => (r == null ? '—' : (r * 100).toFixed(1) + '%')
118
+
119
+ function relTime(ms) {
120
+ if (!ms) return '—'
121
+ const d = (Date.now() - ms) / 1000
122
+ if (d < 90) return '刚刚'
123
+ if (d < 3600) return `${Math.floor(d / 60)} 分钟前`
124
+ if (d < 86400) return `${Math.floor(d / 3600)} 小时前`
125
+ return `${Math.floor(d / 86400)} 天前`
126
+ }
127
+
128
+ /** Live-ish pulse factor: recency decays, and each node gets its own phase
129
+ * so the network never blinks in unison. */
130
+ function activityOf(session, t) {
131
+ const hours = session.updatedAt ? (Date.now() - session.updatedAt) / 3600000 : 999
132
+ const base = hours < 1 ? 1 : hours < 6 ? 0.8 : hours < 24 ? 0.55 : hours < 72 ? 0.32 : 0.14
133
+ let hash = 0
134
+ const id = String(session.id)
135
+ for (let i = 0; i < id.length; i += 1) hash = (hash * 31 + id.charCodeAt(i)) % 997
136
+ return Math.max(0.08, Math.min(1, base * (0.78 + 0.22 * Math.sin(t / 2.1 + hash))))
137
+ }
138
+
139
+ const isActive = s => Boolean(s.updatedAt) && Date.now() - s.updatedAt < 2 * 3600000
140
+
141
+ /** Threshold factors used only when the host sends none. */
142
+ const DEFAULT_FACTORS = { warnFactor: 0.8, criticalFactor: 0.92 }
143
+
144
+ const projName = p => p || T.ungrouped
145
+
146
+ const levelOf = s => LEVEL_VAR[s.risk] ?? LEVEL_VAR.unknown
147
+
148
+ const levelText = s => (s.risk === 'crit' ? T.levelCrit
149
+ : s.risk === 'warn' ? T.levelWarn
150
+ : s.risk === 'unknown' ? T.levelUnknown : T.levelOk)
151
+
152
+ /**
153
+ * Where auto-compaction fires, straight from the host.
154
+ *
155
+ * This used to be recomputed here from `window × 0.8` and a 64K headroom,
156
+ * which drifted from the host the moment the host was corrected to mirror
157
+ * `dsh-compaction-basic` (window − reserved output − 4096). Two copies of
158
+ * one formula is a bug waiting for a release; the panel now renders what
159
+ * the host computed and keeps only the threshold factors on this side.
160
+ * @param session - wire DTO.
161
+ * @returns `{ tokens, ratio, retain }` or null when the host sent none.
162
+ */
163
+ function compactPoint(session) {
164
+ if (!(session?.compactTokens > 0)) return null
165
+ return {
166
+ tokens: session.compactTokens,
167
+ ratio: session.compactRatio ?? session.compactTokens / session.contextWindow,
168
+ retain: session.compactRetain ?? 0,
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Pre-warning thresholds for one session: the host's factors applied to the
174
+ * host's compaction point.
175
+ * @param session - wire DTO.
176
+ * @param cfg - `{ warnFactor, criticalFactor }` from the host (optional).
177
+ * @returns `{ warn, crit, point }` — ratios; `point` is null when the
178
+ * window is unknown (then the documented defaults apply).
179
+ */
180
+ function thresholdsOf(session, cfg) {
181
+ const point = compactPoint(session)
182
+ const wf = cfg?.warnFactor ?? 0.8
183
+ const cf = cfg?.criticalFactor ?? 0.92
184
+ if (!point) return { warn: 0.7, crit: 0.85, point: null }
185
+ return { warn: point.ratio * wf, crit: point.ratio * cf, point }
186
+ }
187
+
188
+ /**
189
+ * Risk level as classified by the host, so the graph colour and the DTO
190
+ * never disagree.
191
+ * @param session - wire DTO.
192
+ * @returns `'ok' | 'warn' | 'crit' | 'unknown'`.
193
+ */
194
+ function riskOf(session) {
195
+ return session?.risk ?? 'unknown'
196
+ }
197
+
198
+ /**
199
+ * Hover text for any context percentage. Every number is derived from the
200
+ * shipped compressor's formula plus this session's own capacity, so the
201
+ * tooltip never claims a percentage the product would not honour.
202
+ * @param session - wire DTO.
203
+ * @param cfg - thresholds config.
204
+ * @returns multi-line tooltip text.
205
+ */
206
+ function contextHint(session, cfg) {
207
+ const point = compactPoint(session)
208
+ const t = thresholdsOf(session, cfg)
209
+ const lines = [
210
+ '上下文占用 = 已用 / 容量',
211
+ session.contextWindow
212
+ ? `已用 ${fmt(session.total)} / 容量 ${fmt(session.contextWindow)} tokens`
213
+ : '该会话没有上下文数据',
214
+ ]
215
+ // Say where the number came from. The event estimate runs ~1.4× low on
216
+ // Chinese-heavy logs, so a mismatch with DSH's own footer needs an
217
+ // explanation here rather than a silent disagreement.
218
+ if (session.contextSource && session.contextSource !== 'estimate') {
219
+ lines.push('已用取服务端返回的实际 prompt(含缓存读写),与状态栏一致')
220
+ } else if (session.contextSource === 'estimate') {
221
+ lines.push('该会话还没有服务端用量样本,这里按事件估算,通常偏低')
222
+ }
223
+ if (session.estimatedTotal > 0 && session.total > 0
224
+ && Math.abs(session.total - session.estimatedTotal) > session.total * 0.05) {
225
+ lines.push(`逐事件估算为 ${fmt(session.estimatedTotal)},比实际低约 `
226
+ + `${Math.round((session.total / session.estimatedTotal - 1) * 100)}%`)
227
+ }
228
+ if (point) {
229
+ lines.push(
230
+ `DSH 会在约 ${pct(point.ratio)}(${fmt(point.tokens)} tokens)自动压缩历史:`
231
+ + '窗口 − 输出预留 − 4K 余量(与 dsh-compaction-basic 一致)',
232
+ `提醒线按这个点换算:注意 ≥${pct(t.warn)}(${fmt(Math.round(t.warn * session.contextWindow))}),`
233
+ + `临界 ≥${pct(t.crit)}(${fmt(Math.round(t.crit * session.contextWindow))})`,
234
+ `压缩后只逐字保留最近约 ${fmt(Math.round(point.retain))} tokens,更早的内容换成摘要`,
235
+ )
236
+ }
237
+ lines.push('越接近上限,可用的工作记忆越少;建议在临界线之前收尾或另开会话')
238
+ return lines.join('\n')
239
+ }
240
+
241
+ /** Titles the host may already have replaced with its old placeholder. */
242
+ const LEGACY_PLACEHOLDER = /^(untitled( session)?|未命名会话|新会话)$/i
243
+
244
+ /**
245
+ * Titles straight from the client session store.
246
+ *
247
+ * `SessionSummary.displayTitle` is documented as "durable title, project
248
+ * basename, then session id" — the same string the native sidebar shows.
249
+ * Reading it here means the panel is correct even when the host half is an
250
+ * older build that still sends a placeholder.
251
+ * @returns id → title map (empty when the service is unavailable).
252
+ */
253
+ function clientTitles() {
254
+ const map = new Map()
255
+ try {
256
+ const c = window.__SESSION_MATRIX_CTX__
257
+ const svc = c && (typeof c.get === 'function' ? c.get('sessions') : c.sessions)
258
+ const list = svc && svc.list
259
+ // `list` is an observable snapshot whose accessor is not part of any
260
+ // documented plugin contract; accept the common shapes instead of
261
+ // betting the feature on one method name.
262
+ let snap = null
263
+ if (list) {
264
+ if (typeof list.getSnapshot === 'function') snap = list.getSnapshot()
265
+ else if (typeof list.get === 'function') snap = list.get()
266
+ else if (typeof list === 'function') snap = list()
267
+ else if (typeof list === 'object' && 'value' in list) snap = list.value
268
+ }
269
+ const rows = snap?.sessions ?? snap?.entries ?? snap?.items
270
+ ?? snap?.list ?? (Array.isArray(snap) ? snap : [])
271
+ for (const row of rows) {
272
+ const id = row?.id ?? row?.sessionId
273
+ if (!id) continue
274
+ const text = row.displayTitle || row.title
275
+ if (typeof text === 'string' && text.trim()) map.set(String(id), text.trim())
276
+ }
277
+ } catch { /* the store is optional; fall back to host titles */ }
278
+ return map
279
+ }
280
+
281
+ /**
282
+ * Resolve one session's display title, preferring a real title over any
283
+ * placeholder, and never repeating the same placeholder for every row.
284
+ * @param session - wire DTO.
285
+ * @param map - client title map.
286
+ * @returns display title.
287
+ */
288
+ function titleOf(session, map) {
289
+ const raw = String(session.title ?? '').trim()
290
+ if (raw && !LEGACY_PLACEHOLDER.test(raw)) return raw
291
+ const fromClient = map?.get(String(session.id))
292
+ if (fromClient && !LEGACY_PLACEHOLDER.test(fromClient)) return fromClient
293
+ const kind = session.origin === 'subagent' ? T.sub : T.sessions
294
+ const tail = String(session.id).replace(/^session-/, '').slice(-4)
295
+ return `${projName(session.project)} · ${kind} ${tail}`
296
+ }
297
+
298
+ async function fetchOverview(force) {
299
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
300
+ const timer = controller ? setTimeout(() => controller.abort(), 15000) : 0
301
+ try {
302
+ const res = await fetch(`${API}/overview${force ? '?refresh=1' : ''}`, {
303
+ headers: { accept: 'application/json' },
304
+ signal: controller ? controller.signal : undefined,
305
+ })
306
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
307
+ return await res.json()
308
+ } finally {
309
+ if (timer) clearTimeout(timer)
310
+ }
311
+ }
312
+
313
+ /* ══════════════════ graph layout ══════════════════
314
+ * Rectangular layered layout, because the panel is wide and short: a radial
315
+ * tree pushes 40 nodes onto one circle and leaves two-thirds of the width
316
+ * empty. Columns are hierarchy depth (workbench → project → session →
317
+ * subagent) and rows are real membership, so every link is a fact from the
318
+ * session header — no "same project" links, no invented delegation edges.
319
+ */
320
+
321
+ const COL = { hub: 0.032, project: 0.20, main: 0.50, sub: 0.845 }
322
+
323
+ /**
324
+ * One session plus every session that descends from it.
325
+ *
326
+ * Used by the cockpit's scope: selecting a main session must make the
327
+ * bottom-left panel talk about that session *and* the subagents it spawned,
328
+ * otherwise the numbers look frozen when you click around the graph.
329
+ * @param id - root session id.
330
+ * @param sessions - all sessions in view.
331
+ * @returns array of sessions (the root first, then descendants in order).
332
+ */
333
+ function subtreeOf(id, sessions) {
334
+ const byId = new Map(sessions.map(s => [s.id, s]))
335
+ const out = []
336
+ for (const s of sessions) {
337
+ let cursor = s.id
338
+ for (let depth = 0; depth < 24 && cursor; depth += 1) {
339
+ if (cursor === id) { out.push(s); break }
340
+ cursor = byId.get(cursor)?.parentId ?? null
341
+ }
342
+ }
343
+ return out
344
+ }
345
+
346
+ function computeGraph(data, filter, w, hgt) {
347
+ const all = data?.sessions ?? []
348
+ const q = String(filter.query ?? '').trim().toLowerCase()
349
+ const hitQuery = s => !q
350
+ || `${s.title ?? ''} ${s.project ?? ''} ${s.model ?? ''}`.toLowerCase().includes(q)
351
+ const shown = all.filter(s => (filter.project === '__all' || s.project === filter.project) && hitQuery(s))
352
+
353
+ const byId = new Map(all.map(s => [s.id, s]))
354
+ const mains = shown.filter(s => s.origin !== 'subagent')
355
+ const subs = shown.filter(s => s.origin === 'subagent')
356
+ const mainIds = new Set(mains.map(s => s.id))
357
+
358
+ // Attach every subagent to its nearest main ancestor inside the current
359
+ // selection. A subagent whose chain leaves the set stays attached to its
360
+ // project, never to a session it is not actually a child of.
361
+ const childrenOf = new Map()
362
+ for (const sub of subs) {
363
+ let cur = sub.parentId
364
+ let owner = null
365
+ for (let guard = 0; cur && guard < 24; guard += 1) {
366
+ if (mainIds.has(cur)) { owner = cur; break }
367
+ cur = byId.get(cur)?.parentId ?? null
368
+ }
369
+ const key = owner ?? `p:${sub.project}`
370
+ if (!childrenOf.has(key)) childrenOf.set(key, [])
371
+ childrenOf.get(key).push(sub)
372
+ }
373
+
374
+ const groups = []
375
+ const groupOf = new Map()
376
+ for (const m of mains) {
377
+ let g = groupOf.get(m.project)
378
+ if (!g) {
379
+ g = { name: m.project, mains: [] }
380
+ groupOf.set(m.project, g)
381
+ groups.push(g)
382
+ }
383
+ g.mains.push(m)
384
+ }
385
+ groups.sort((a, b) => b.mains.length - a.mains.length)
386
+ for (const g of groups) g.mains.sort((a, b) => (b.ratio ?? -1) - (a.ratio ?? -1))
387
+
388
+ // Shared vertical budget. Every node gets a weighted slot in one pass, so
389
+ // a parent and its children stay adjacent without ever overlapping and
390
+ // without leaving the far column empty.
391
+ const top = 30
392
+ const bottom = 16
393
+ const innerH = Math.max(120, hgt - top - bottom)
394
+ const W_MAIN = 1
395
+ const W_SUB = 0.62
396
+ const W_GROUP = 0.7
397
+
398
+ const order = []
399
+ for (let gi = 0; gi < groups.length; gi += 1) {
400
+ const g = groups[gi]
401
+ if (gi > 0) order.push({ kind: 'gap' })
402
+ for (const m of g.mains) {
403
+ order.push({ kind: 'main', session: m, project: g.name })
404
+ for (const sub of childrenOf.get(m.id) ?? []) {
405
+ order.push({ kind: 'sub', session: sub, parentId: m.id, project: g.name })
406
+ }
407
+ }
408
+ }
409
+
410
+ const units = order.reduce((sum, it) => sum
411
+ + (it.kind === 'gap' ? W_GROUP : it.kind === 'sub' ? W_SUB : W_MAIN), 0)
412
+ const unit = innerH / Math.max(units, 1)
413
+ const unitMain = unit * W_MAIN
414
+
415
+ const x = {
416
+ hub: Math.max(20, w * COL.hub),
417
+ project: Math.max(92, w * COL.project),
418
+ main: Math.max(170, w * COL.main),
419
+ sub: Math.min(w - 26, w * COL.sub),
420
+ }
421
+
422
+ const nodes = []
423
+ const links = []
424
+ const hub = { id: '__hub__', kind: 'hub', x: x.hub, y: hgt / 2, r: 6 }
425
+ nodes.push(hub)
426
+
427
+ const projectRows = new Map()
428
+ let cursor = top
429
+ let mainOrd = 0
430
+ for (const item of order) {
431
+ if (item.kind === 'gap') { cursor += unit * W_GROUP; continue }
432
+ const weight = item.kind === 'sub' ? W_SUB : W_MAIN
433
+ const y = cursor + (unit * weight) / 2
434
+ cursor += unit * weight
435
+
436
+ if (item.kind === 'main') {
437
+ const m = item.session
438
+ const node = {
439
+ id: m.id,
440
+ kind: 'main',
441
+ session: m,
442
+ project: item.project,
443
+ ord: mainOrd++,
444
+ x: x.main,
445
+ y,
446
+ r: 4.6 + 3.1 * Math.min(1, m.ratio ?? 0),
447
+ activity: activityOf(m, 0),
448
+ active: isActive(m),
449
+ risk: m.risk,
450
+ }
451
+ nodes.push(node)
452
+ if (!projectRows.has(item.project)) projectRows.set(item.project, [])
453
+ projectRows.get(item.project).push(node)
454
+ } else {
455
+ const sub = item.session
456
+ const node = {
457
+ id: sub.id,
458
+ kind: 'sub',
459
+ session: sub,
460
+ parentId: item.parentId,
461
+ project: item.project,
462
+ x: x.sub,
463
+ y,
464
+ r: 3.3 + 1.4 * Math.min(1, sub.ratio ?? 0),
465
+ activity: activityOf(sub, 1.4),
466
+ active: isActive(sub),
467
+ risk: sub.risk,
468
+ }
469
+ nodes.push(node)
470
+ links.push({
471
+ from: item.parentId,
472
+ to: sub.id,
473
+ kind: 'child',
474
+ activity: node.activity,
475
+ active: node.active,
476
+ risk: sub.risk,
477
+ })
478
+ }
479
+ }
480
+
481
+ for (const g of groups) {
482
+ const rows = projectRows.get(g.name) ?? []
483
+ if (!rows.length) continue
484
+ const projectId = `__p__:${g.name}`
485
+ const project = {
486
+ id: projectId,
487
+ kind: 'project',
488
+ name: g.name,
489
+ x: x.project,
490
+ y: rows.reduce((sum, r) => sum + r.y, 0) / rows.length,
491
+ r: 9.5,
492
+ count: rows.length + rows.reduce((sum, r) => sum + (childrenOf.get(r.id)?.length ?? 0), 0),
493
+ ratio: rows.reduce((sum, r) => sum + (r.session.ratio ?? 0), 0) / rows.length,
494
+ }
495
+ nodes.push(project)
496
+ links.push({ from: hub.id, to: projectId, kind: 'root' })
497
+ for (const r of rows) {
498
+ links.push({
499
+ from: projectId,
500
+ to: r.id,
501
+ kind: 'project',
502
+ activity: r.activity,
503
+ active: r.active,
504
+ risk: r.risk,
505
+ })
506
+ }
507
+ }
508
+
509
+ // Subagents whose project has no main session in the current selection:
510
+ // anchor them to the project itself rather than dropping them.
511
+ for (const key of [...childrenOf.keys()].filter(k => k.startsWith('p:'))) {
512
+ const name = key.slice(2)
513
+ const projectId = `__p__:${name}`
514
+ let project = nodes.find(nd => nd.id === projectId)
515
+ const orphans = childrenOf.get(key) ?? []
516
+ if (!project) {
517
+ project = {
518
+ id: projectId, kind: 'project', name, x: x.project,
519
+ y: top + innerH / 2, r: 8, count: orphans.length, ratio: null,
520
+ }
521
+ nodes.push(project)
522
+ links.push({ from: hub.id, to: projectId, kind: 'root' })
523
+ }
524
+ orphans.forEach((sub, i) => {
525
+ const node = {
526
+ id: sub.id,
527
+ kind: 'sub',
528
+ session: sub,
529
+ parentId: projectId,
530
+ project: name,
531
+ x: x.sub,
532
+ y: Math.max(top, Math.min(hgt - bottom, project.y + (i - (orphans.length - 1) / 2) * unit * W_SUB)),
533
+ r: 2.4,
534
+ activity: activityOf(sub, 2.1),
535
+ active: isActive(sub),
536
+ risk: sub.risk,
537
+ }
538
+ nodes.push(node)
539
+ links.push({ from: projectId, to: sub.id, kind: 'child', activity: node.activity, active: node.active, risk: sub.risk })
540
+ })
541
+ }
542
+
543
+ const nodeById = new Map(nodes.map(nd => [nd.id, nd]))
544
+ return {
545
+ w, hgt, x, nodes, links, nodeById, unitMain,
546
+ projects: groups.length,
547
+ sessions: shown.length,
548
+ edges: links.length,
549
+ parentChild: links.filter(l => l.kind === 'child').length,
550
+ }
551
+ }
552
+
553
+ /** Cubic curve with horizontal tangents at both ends: every edge from one
554
+ * source leaves in the same direction, so siblings bundle visually. */
555
+ function linkPath(a, b) {
556
+ const dx = Math.max(26, Math.abs(b.x - a.x) * 0.42)
557
+ return `M${a.x.toFixed(1)},${a.y.toFixed(1)}C${(a.x + dx).toFixed(1)},${a.y.toFixed(1)} ${(b.x - dx).toFixed(1)},${b.y.toFixed(1)} ${b.x.toFixed(1)},${b.y.toFixed(1)}`
558
+ }
559
+
560
+ /* ══════════════════ styles ══════════════════ */
561
+
562
+ const CSS = `
563
+ .aw{
564
+ position:relative;
565
+ --aw-hair: var(--dsh-hairline-width, 0.5px);
566
+ --aw-r: var(--dsw-radius-sm, 8px);
567
+ --aw-r-lg: var(--dsw-radius-md, 12px);
568
+ --aw-mono: var(--dsh-font-family-code, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
569
+ height:100%;display:flex;flex-direction:column;overflow:hidden;
570
+ background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);
571
+ font-family:var(--dsh-font-family-text, -apple-system, "Segoe UI", "Microsoft YaHei", system-ui, sans-serif);
572
+ font-size:13px;line-height:20px;-webkit-font-smoothing:antialiased;
573
+ }
574
+ .aw *{box-sizing:border-box}
575
+ .aw button{font-family:inherit;font-size:13px;line-height:20px;cursor:pointer;border:0;background:none;color:inherit}
576
+ .aw input{font-family:inherit;font-size:13px;color:inherit}
577
+ .aw-hdr{flex:0 0 auto;display:flex;align-items:center;gap:12px;padding:10px 16px;
578
+ border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l2);min-height:52px;flex-wrap:wrap;
579
+ container-type:inline-size}
580
+ .aw-title{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;white-space:nowrap}
581
+ .aw-title svg{width:16px;height:16px;flex:0 0 auto;color:var(--dsw-alias-label-secondary)}
582
+ .aw-sub{font-size:11px;font-weight:400;color:var(--dsw-alias-label-caption)}
583
+ .aw-seg{display:flex;gap:2px;padding:2px;border-radius:var(--aw-r);
584
+ background:var(--dsw-alias-bg-layer-1);border:var(--aw-hair) solid var(--dsw-alias-border-l2)}
585
+ .aw-seg button{padding:3px 12px;border-radius:6px;font-size:12px;color:var(--dsw-alias-label-tertiary)}
586
+ .aw-seg button:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
587
+ .aw-seg button[aria-selected="true"]{background:var(--dsw-alias-bg-layer-3);
588
+ color:var(--dsw-alias-label-primary);font-weight:500}
589
+ .aw-grow{flex:1 1 auto;min-width:8px}
590
+ .aw-stat{display:flex;align-items:center;gap:12px;font-size:12px;
591
+ color:var(--dsw-alias-label-tertiary);white-space:nowrap}
592
+ .aw-stat b{font-family:var(--aw-mono);font-weight:500;color:var(--dsw-alias-label-secondary);
593
+ font-variant-numeric:tabular-nums}
594
+ .aw-stat .risk{color:var(--dsw-alias-state-warn-label)}
595
+ .aw-field{display:flex;align-items:center;gap:6px;height:28px;padding:0 9px;
596
+ border:var(--aw-hair) solid var(--dsw-alias-border-l3);border-radius:var(--aw-r);
597
+ background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-tertiary);font-size:12px}
598
+ .aw-field:focus-within{border-color:var(--dsw-alias-border-selected)}
599
+ .aw-field input{border:0;outline:0;background:none;padding:0;min-width:0;flex:1;font-size:12px}
600
+ /* Sort cycle: one 34px pill instead of a dropdown the rail cannot fit. */
601
+ .aw-sort{flex:0 0 auto;height:20px;padding:0 6px;border-radius:10px;font-size:10px;
602
+ background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-secondary);
603
+ display:flex;align-items:center;gap:3px;white-space:nowrap}
604
+ .aw-sort:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
605
+ .aw-field input::placeholder{color:var(--dsw-alias-label-caption)}
606
+ .aw-field svg{width:14px;height:14px;flex:0 0 auto}
607
+ .aw-btn{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 10px;
608
+ border:var(--aw-hair) solid var(--dsw-alias-border-l3);border-radius:var(--aw-r);
609
+ background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-secondary);
610
+ font-size:12px;white-space:nowrap}
611
+ .aw-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
612
+ .aw-btn:active{background:var(--dsw-alias-interactive-bg-active)}
613
+ .aw-btn svg{width:14px;height:14px;flex:0 0 auto}
614
+ /* Emphasis without the brand pair: button-primary-fill resolves to the
615
+ near-white brand colour in dark mode while label-on-color stays #fff, which
616
+ renders white-on-white. A raised layer + primary label is theme-safe. */
617
+ .aw-btn.primary{background:var(--dsw-alias-bg-layer-3);
618
+ border-color:var(--dsw-alias-border-l4);color:var(--dsw-alias-label-primary)}
619
+ .aw-btn.primary:hover{background:var(--dsw-alias-interactive-bg-hover)}
620
+ .aw-btn.ghost{border-color:transparent;background:none}
621
+ .aw-btn.ghost:hover{background:var(--dsw-alias-interactive-bg-hover)}
622
+ .aw-btn.on{background:var(--dsw-alias-bg-layer-3);border-color:var(--dsw-alias-border-l4);
623
+ color:var(--dsw-alias-label-primary)}
624
+ .aw-btn:disabled{opacity:.45;cursor:default}
625
+ .aw-dot{width:6px;height:6px;border-radius:50%;flex:0 0 auto}
626
+ .aw-main{flex:1 1 auto;min-height:0;display:flex;flex-direction:column;overflow:hidden}
627
+
628
+ /* ── workspace: session rail + native panes ── */
629
+ .aw-ws{flex:1 1 auto;min-height:0;display:grid;
630
+ grid-template-columns:var(--aw-rail,288px) 0 minmax(0,1fr)}
631
+ .aw-rail{display:flex;flex-direction:column;min-height:0;overflow:hidden}
632
+ .aw-rail-h{flex:0 0 auto;display:flex;flex-direction:column;gap:8px;padding:10px 12px;
633
+ border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l1)}
634
+ .aw-chips{display:flex;gap:4px;flex-wrap:wrap}
635
+ .aw-chip{height:22px;padding:0 8px;border-radius:11px;font-size:11px;
636
+ border:var(--aw-hair) solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary);
637
+ display:inline-flex;align-items:center;gap:4px;max-width:100%}
638
+ .aw-chip:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
639
+ .aw-chip[aria-pressed="true"]{background:var(--dsw-alias-bg-layer-3);
640
+ border-color:var(--dsw-alias-border-l4);color:var(--dsw-alias-label-primary)}
641
+ .aw-chip .n{font-family:var(--aw-mono);font-size:10px;color:var(--dsw-alias-label-caption)}
642
+ .aw-rail-list{flex:1 1 auto;min-height:0;overflow:auto;padding:4px 0 12px}
643
+ .aw-rg{padding:8px 12px 2px;font-size:11px;color:var(--dsw-alias-label-caption);
644
+ display:flex;align-items:center;gap:6px}
645
+ .aw-rg .line{flex:1;height:1px;background:var(--dsw-alias-border-l1)}
646
+ .aw-ri{display:flex;align-items:center;gap:7px;padding:3px 12px;cursor:pointer;min-width:0}
647
+ .aw-ri:hover{background:var(--dsw-alias-interactive-bg-hover)}
648
+ .aw-ri[aria-current="true"]{background:var(--dsw-alias-bg-multi-select)}
649
+ .aw-ri .st{width:6px;height:6px;border-radius:50%;flex:0 0 auto}
650
+ .aw-ri .body{flex:1;min-width:0}
651
+ .aw-ri .l1{display:flex;align-items:center;gap:6px;font-size:11.5px;line-height:16px;
652
+ color:var(--dsw-alias-label-primary)}
653
+ .aw-ri .l1 .t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
654
+ .aw-ri .l2{display:flex;align-items:center;gap:6px;font-size:10px;line-height:15px;
655
+ color:var(--dsw-alias-label-caption)}
656
+ .aw-ri .l2 .bar{flex:0 0 44px;height:3px;border-radius:2px;margin-left:auto;
657
+ background:var(--dsw-alias-border-l1);overflow:hidden}
658
+ .aw-ri .l2 .bar i{display:block;height:100%}
659
+ .aw-ri .pc{font-family:var(--aw-mono);font-size:10.5px;color:var(--dsw-alias-label-secondary);
660
+ font-variant-numeric:tabular-nums;flex:0 0 auto}
661
+ .aw-rnode{display:flex;flex-direction:column;min-width:0}
662
+ .aw-ri-sub{padding-left:26px;position:relative}
663
+ .aw-ri-sub::before{content:'';position:absolute;left:18px;top:0;bottom:0;width:1px;
664
+ background:var(--dsw-alias-border-l1)}
665
+ .aw-ri-sub .l1{font-size:11.5px;color:var(--dsw-alias-label-secondary)}
666
+ .aw-rtoggle{display:flex;align-items:center;gap:6px;padding:1px 12px 5px 28px;
667
+ font-size:11px;line-height:16px;color:var(--dsw-alias-label-caption);text-align:left}
668
+ .aw-rtoggle:hover{color:var(--dsw-alias-label-secondary)}
669
+ .aw-rtoggle .caret{width:0;height:0;display:inline-block;
670
+ border-left:4px solid currentColor;border-top:3.5px solid transparent;
671
+ border-bottom:3.5px solid transparent;transition:transform .14s}
672
+ .aw-rtoggle .caret.open{transform:rotate(90deg)}
673
+ .aw-grip{position:relative;z-index:3;cursor:col-resize;margin-left:-3px;width:6px;
674
+ background:none;border:0;padding:0}
675
+ .aw-grip::after{content:'';position:absolute;inset:0 2px;background:var(--dsw-alias-border-l2);
676
+ transition:background .15s}
677
+ .aw-grip:hover::after,.aw-grip[data-drag]{background:var(--dsw-alias-trajectory-accent)}
678
+ .aw-pane-wrap{display:flex;flex-direction:column;min-height:0;min-width:0}
679
+ .aw-pane-wrap>.aw-toolbar{padding:6px 12px;gap:6px}
680
+ .aw-panes{display:grid;flex:1 1 auto;min-height:0;min-width:0;
681
+ grid-template-columns:1fr;gap:0;background:var(--dsw-alias-border-l2)}
682
+ /* Track sizes come from inline styles: the dividers are real grid items, so
683
+ the drag ratio maps 1:1 onto the visible layout. */
684
+ .aw-pane-slot{min-width:0;min-height:0;display:flex;background:var(--dsw-alias-bg-base)}
685
+ .aw-pane-slot>.aw-pane{width:100%}
686
+ .aw-split{background:var(--dsw-alias-border-l2);transition:background .12s}
687
+ .aw-split[data-split="col"]{cursor:col-resize}
688
+ .aw-split[data-split="row"]{cursor:row-resize}
689
+ .aw-split:hover{background:var(--dsw-alias-trajectory-accent)}
690
+ .aw-pane{position:relative;display:flex;flex-direction:column;min-width:0;min-height:0;
691
+ background:var(--dsw-alias-bg-base)}
692
+ .aw-pane-h{position:relative;flex:0 0 auto;height:34px;display:flex;align-items:center;gap:8px;padding:0 10px;
693
+ border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l1);min-width:0;
694
+ background:var(--dsw-alias-bg-layer-1);container-type:inline-size}
695
+ .aw-pane-h .t{flex:0 1 auto;min-width:0;max-width:30%;font-size:12px;color:var(--dsw-alias-label-secondary);
696
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
697
+ .aw-pane-h .ctx{flex:0 0 auto;font-size:10.5px;color:var(--dsw-alias-label-caption);
698
+ white-space:nowrap;display:inline-flex;align-items:baseline;gap:4px}
699
+ .aw-pane-h .ctx .ctxv{font-family:var(--aw-mono);font-size:10.5px;
700
+ color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
701
+ .aw-pane-h .x{width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center;
702
+ border-radius:4px;color:var(--dsw-alias-label-caption)}
703
+ .aw-pane-h .x:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
704
+ .aw-pane-b{flex:1 1 auto;min-height:0;min-width:0;position:relative;
705
+ display:flex;flex-direction:column;overflow:hidden;
706
+ background:var(--dsw-alias-bg-base)}
707
+ .aw-zoombox{flex:1 1 auto;min-height:0;min-width:0;overflow:hidden}
708
+ .aw-zoom-inner{display:flex;flex-direction:column;min-height:0}
709
+ .aw-native{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
710
+ .aw-pane-fallback{flex:1 1 auto;display:flex;flex-direction:column;align-items:center;
711
+ justify-content:center;gap:6px;padding:20px;text-align:center;
712
+ font-size:12px;line-height:18px;color:var(--dsw-alias-label-caption)}
713
+ .aw-pane-fallback .sub{font-size:11px;opacity:.8}
714
+ .aw-pane-h.warn{box-shadow: inset 2px 0 0 var(--dsw-alias-state-warn-primary)}
715
+ .aw-pane-h.crit{box-shadow: inset 2px 0 0 var(--dsw-alias-state-error-primary)}
716
+ .aw-risk{flex:0 0 auto;font-size:9.5px;line-height:15px;padding:0 5px;border-radius:3px;
717
+ font-weight:600;letter-spacing:.02em}
718
+ .aw-risk.warn{color:var(--dsw-alias-state-warn-label);
719
+ background:color-mix(in oklab, var(--dsw-alias-state-warn-primary) 18%, transparent)}
720
+ .aw-risk.crit{color:var(--dsw-alias-state-error-label);
721
+ background:color-mix(in oklab, var(--dsw-alias-state-error-primary) 18%, transparent)}
722
+ .aw-ro{flex:0 0 auto;font-size:9.5px;line-height:15px;padding:0 5px;border-radius:3px;
723
+ background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-caption);
724
+ border:var(--aw-hair) solid var(--dsw-alias-border-l1)}
725
+ .aw-zoom{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
726
+ display:inline-flex;align-items:center;gap:5px;flex:0 0 auto}
727
+ .aw-zoom-k{font-size:10px;color:var(--dsw-alias-label-caption);white-space:nowrap}
728
+ .aw-zoom-range{-webkit-appearance:none;appearance:none;width:58px;height:14px;
729
+ background:none;cursor:pointer;margin:0}
730
+ .aw-zoom-range::-webkit-slider-runnable-track{height:3px;border-radius:2px;
731
+ background:var(--dsw-alias-border-l3)}
732
+ .aw-zoom-range::-webkit-slider-thumb{-webkit-appearance:none;width:10px;height:10px;
733
+ margin-top:-3.5px;border-radius:50%;background:var(--dsw-alias-trajectory-accent);
734
+ border:0;box-shadow:0 0 0 1px var(--dsw-alias-bg-base)}
735
+ .aw-zoom-range:hover::-webkit-slider-thumb{transform:scale(1.15)}
736
+ .aw-zoom-val{font-size:10px;line-height:14px;color:var(--dsw-alias-label-caption);
737
+ font-variant-numeric:tabular-nums;min-width:28px;text-align:right}
738
+ /* Narrow panes: drop the words, keep the numbers. A 4-up pane is ~420px, and
739
+ the labels are what push the zoom slider into the context figure. */
740
+ @container (max-width:520px){
741
+ .aw-pane-h .ctxk{display:none}
742
+ .aw-zoom-k{display:none}
743
+ .aw-zoom-range{width:46px}
744
+ }
745
+ @container (max-width:430px){
746
+ .aw-pane-h .t{max-width:24%}
747
+ .aw-pane-h{gap:6px}
748
+ .aw-zoom-val{display:none}
749
+ .aw-zoom-range{width:40px}
750
+ }
751
+ .aw-veil{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;
752
+ justify-content:center;gap:10px;padding:28px;text-align:center;
753
+ background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:19px}
754
+ .aw-veil .big{font-size:13px;color:var(--dsw-alias-label-secondary)}
755
+ .aw-veil code{font-family:var(--aw-mono);font-size:11px;color:var(--dsw-alias-label-caption);word-break:break-all}
756
+ .aw-veil .row{display:flex;gap:8px;flex-wrap:wrap;justify-content:center}
757
+
758
+ /* ── handoff: top-bar entry, hover card, dialog ── */
759
+ .aw-hbtn{position:relative;flex:0 0 auto}
760
+ .aw-handoff{height:26px;gap:5px}
761
+ .aw-hbtn-dot{position:absolute;top:0;right:0;width:7px;height:7px;border-radius:50%;
762
+ background:var(--dsw-alias-state-warn-primary);box-shadow:0 0 0 2px var(--dsw-alias-bg-base)}
763
+ .aw-hbtn-dot.crit{background:var(--dsw-alias-state-error-primary)}
764
+ /* Hover explains, click opens. A delay keeps the pointer on its way to the
765
+ refresh button from flashing a card. */
766
+ .aw-tip{position:absolute;top:calc(100% + 8px);right:0;width:268px;z-index:30;padding:9px 10px;
767
+ border-radius:7px;border:var(--aw-hair) solid var(--dsw-alias-border-l3);
768
+ background:var(--dsw-alias-bg-layer-2);box-shadow:0 8px 26px rgba(0,0,0,.2);
769
+ font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary);
770
+ opacity:0;pointer-events:none;transition:opacity .12s ease .2s;text-align:left}
771
+ .aw-hbtn:hover .aw-tip{opacity:1}
772
+ .aw-tip b{display:block;margin-bottom:4px;font-size:11.5px;color:var(--dsw-alias-label-secondary)}
773
+ .aw-tip .sub{margin-top:4px;color:var(--dsw-alias-label-caption)}
774
+ /* Instant tooltips. Native title waits ~1s; these open on hover with no
775
+ delay. Only used on elements whose ancestors do not clip overflow. */
776
+ [data-tip]{position:relative}
777
+ [data-tip]::after{content:attr(data-tip);position:absolute;z-index:60;top:calc(100% + 8px);left:0;
778
+ width:max-content;max-width:320px;padding:8px 10px;border-radius:7px;white-space:pre-line;
779
+ border:var(--aw-hair) solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-layer-2);
780
+ box-shadow:0 10px 28px rgba(0,0,0,.22);font-size:11px;line-height:16px;font-weight:400;
781
+ color:var(--dsw-alias-label-tertiary);text-align:left;opacity:0;pointer-events:none;
782
+ transition:opacity .08s ease}
783
+ [data-tip]:hover::after{opacity:1}
784
+ [data-tip].tip-r::after{left:auto;right:0}
785
+ /* Theme-dependent bits: dust specks and shadows. The rest of the panel uses
786
+ --dsw-alias-* tokens, which already flip with the shell theme. */
787
+ .aw{--aw-dust:#ffffff}
788
+ .aw[data-theme="light"]{--aw-dust:#5b6472}
789
+ .aw[data-theme="light"] .aw-modal{background:rgba(15,23,42,.26)}
790
+ .aw[data-theme="light"] .aw-tip{box-shadow:0 10px 28px rgba(15,23,42,.14)}
791
+ .aw[data-theme="light"] .aw-modal-c{box-shadow:0 20px 64px rgba(15,23,42,.2)}
792
+ /* Narrow headers keep the icon and drop the words. */
793
+ @container (max-width:880px){ .aw-hbtn-k{display:none} }
794
+ .aw-ver{font-family:var(--aw-mono);font-size:10px;color:var(--dsw-alias-label-caption);
795
+ padding:1px 6px;border-radius:8px;background:var(--dsw-alias-bg-layer-2)}
796
+ .aw-modal{position:absolute;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;
797
+ padding:18px;background:rgba(0,0,0,.44);container-type:inline-size}
798
+ .aw-modal-c{display:flex;flex-direction:column;width:min(800px,100%);height:min(640px,100%);
799
+ border-radius:10px;border:var(--aw-hair) solid var(--dsw-alias-border-l3);
800
+ background:var(--dsw-alias-bg-layer-1);box-shadow:0 20px 64px rgba(0,0,0,.38);overflow:hidden}
801
+ .aw-modal-h{flex:0 0 auto;display:flex;align-items:center;gap:8px;padding:11px 14px;
802
+ border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l1)}
803
+ .aw-modal-h h2{margin:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary)}
804
+ .aw-modal-h .x{margin-left:auto;width:24px;height:24px;border:0;border-radius:5px;cursor:pointer;
805
+ background:none;color:var(--dsw-alias-label-caption);display:flex;align-items:center;justify-content:center}
806
+ .aw-modal-h .x:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
807
+ .aw-modal-b{flex:1 1 auto;min-height:0;display:grid;grid-template-columns:296px minmax(0,1fr)}
808
+ .aw-modal-l{overflow:auto;padding:12px 14px;border-right:var(--aw-hair) solid var(--dsw-alias-border-l1)}
809
+ .aw-modal-r{display:flex;flex-direction:column;min-width:0;gap:6px;padding:12px 14px}
810
+ .aw-modal-r textarea{flex:1 1 auto;min-height:0;width:100%;box-sizing:border-box;resize:none;
811
+ font-family:var(--aw-mono);font-size:11px;line-height:17px;padding:8px 10px;border-radius:6px;
812
+ border:var(--aw-hair) solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);
813
+ color:var(--dsw-alias-label-secondary)}
814
+ .aw-modal-r .lab{font-size:10.5px;color:var(--dsw-alias-label-caption)}
815
+ .aw-modal-f{flex:0 0 auto;display:flex;align-items:center;gap:8px;padding:10px 14px;
816
+ border-top:var(--aw-hair) solid var(--dsw-alias-border-l1)}
817
+ .aw-fnote{margin-right:auto}
818
+ .aw-fnote>div{font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-caption)}
819
+ .aw-fnote .sub{color:var(--dsw-alias-label-tertiary)}
820
+ .aw-hsec{margin:0 0 4px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-secondary)}
821
+ .aw-hsec-sub{margin-left:6px;font-weight:400;font-size:10px;color:var(--dsw-alias-label-caption)}
822
+ .aw-hp{margin:0 0 10px;font-size:11px;line-height:17px;color:var(--dsw-alias-label-tertiary)}
823
+ .aw-hp b{color:var(--dsw-alias-label-secondary);font-weight:600}
824
+ .aw-hp>div{margin-bottom:5px}
825
+ .aw-hp>div:last-child{margin-bottom:0}
826
+ .aw-steps>div{margin-bottom:5px}
827
+ .aw-hp code{font-family:var(--aw-mono);font-size:10.5px;padding:0 3px;border-radius:3px;
828
+ background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-tertiary)}
829
+ .aw-hcard{display:flex;flex-direction:column;gap:4px;width:100%;text-align:left;padding:8px 10px;
830
+ margin-bottom:6px;border-radius:7px;
831
+ border:var(--aw-hair) solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);cursor:pointer}
832
+ .aw-hcard:hover{border-color:var(--dsw-alias-border-l3)}
833
+ .aw-hcard[aria-pressed="true"]{border-color:var(--dsw-alias-trajectory-accent);background:var(--dsw-alias-bg-multi-select)}
834
+ .aw-hcard-h{display:flex;align-items:baseline;gap:6px;min-width:0}
835
+ .aw-hcard-h .t{flex:1 1 auto;min-width:0;font-size:11.5px;color:var(--dsw-alias-label-secondary);
836
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
837
+ .aw-hcard .tag{flex:0 0 auto;font-size:9.5px;color:var(--dsw-alias-trajectory-accent)}
838
+ /* One bar, two facts: the fill is current usage, the tick is where DSH compacts. */
839
+ .aw-hcard-bar{position:relative;display:block;height:3px;border-radius:2px;
840
+ background:var(--dsw-alias-bg-layer-3);overflow:hidden}
841
+ .aw-hcard-bar i{position:absolute;left:0;top:0;bottom:0;border-radius:2px;opacity:.85}
842
+ .aw-hcard-bar em{position:absolute;top:-2px;bottom:-2px;width:1px;
843
+ background:var(--dsw-alias-label-primary);opacity:.45}
844
+ .aw-hcard-r{display:flex;align-items:baseline;justify-content:space-between;gap:8px;
845
+ font-family:var(--aw-mono);font-size:10px;color:var(--dsw-alias-label-caption)}
846
+ .aw-hcard .d{font-size:10px;color:var(--dsw-alias-label-tertiary)}
847
+ /* The two sentences that explain the trade-off; bold + a left rule so they read
848
+ as the conclusion rather than as more body copy. */
849
+ .aw-hp-strong{padding:7px 9px;border-radius:0 5px 5px 0;margin:2px 0 7px;
850
+ border-left:2px solid var(--dsw-alias-trajectory-accent);
851
+ background:var(--dsw-alias-bg-layer-2)}
852
+ .aw-hp-strong b{font-weight:600;color:var(--dsw-alias-label-primary)}
853
+ .aw-rot{display:inline-flex;animation:aw-rot .9s linear infinite}
854
+ @keyframes aw-rot{to{transform:rotate(360deg)}}
855
+ /* Mini spec sheet: the three lines the panel paints. */
856
+ .aw-tbl{display:flex;flex-direction:column;gap:0;margin:2px 0 4px;
857
+ border:var(--aw-hair) solid var(--dsw-alias-border-l2);border-radius:6px;overflow:hidden}
858
+ .aw-tbl-h,.aw-tbl-r{display:grid;grid-template-columns:78px minmax(0,1fr);gap:8px;padding:5px 8px}
859
+ .aw-tbl-h{font-size:10px;color:var(--dsw-alias-label-caption);
860
+ background:var(--dsw-alias-bg-layer-2);border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l2)}
861
+ .aw-tbl-r{font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-tertiary)}
862
+ .aw-tbl-r + .aw-tbl-r{border-top:var(--aw-hair) solid var(--dsw-alias-border-l1)}
863
+ .aw-tbl-r .n{font-family:var(--aw-mono);color:var(--dsw-alias-label-secondary)}
864
+ .aw-tbl-note{margin-bottom:8px;font-size:10px;line-height:14px;color:var(--dsw-alias-label-caption)}
865
+ .aw-other{width:100%;margin-top:2px;padding:4px 6px;border-radius:5px;font-size:11px;
866
+ border:var(--aw-hair) solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);
867
+ color:var(--dsw-alias-label-secondary)}
868
+ @container (max-width:700px){
869
+ .aw-modal-b{grid-template-columns:1fr;grid-template-rows:minmax(0,auto) minmax(0,1fr)}
870
+ .aw-modal-l{border-right:0;border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l1);max-height:44%}
871
+ }
872
+ @keyframes aw-flash{0%,100%{box-shadow:inset 0 0 0 0 transparent}50%{box-shadow:inset 0 0 0 2px var(--dsw-alias-trajectory-accent)}}
873
+ .aw-pane[data-flash="1"]{animation:aw-flash .78s ease-in-out 3}
874
+ @media (prefers-reduced-motion: reduce){.aw-pane[data-flash="1"]{animation:none;outline:1px solid var(--dsw-alias-trajectory-accent)}}
875
+
876
+ /* ── cockpit: canvas + modules ── */
877
+ .aw-toolbar{flex:0 0 auto;display:flex;align-items:center;gap:8px;
878
+ padding:8px 16px;border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l2);flex-wrap:wrap}
879
+ .aw-canvas{flex:1 1 auto;min-height:0;position:relative;overflow:hidden}
880
+ .aw-canvas svg{display:block;width:100%;height:100%}
881
+ .aw-node{cursor:pointer}
882
+ .aw-node:focus{outline:none}
883
+ .aw-breathe{animation:aw-breathe 3.8s ease-in-out infinite}
884
+ @keyframes aw-breathe{0%,100%{opacity:.14}50%{opacity:.4}}
885
+ .aw-risk-ring{transform-box:fill-box;transform-origin:center;
886
+ animation:aw-risk 2.8s ease-out infinite}
887
+ @keyframes aw-risk{0%{transform:scale(1);opacity:.5}70%{transform:scale(2.2);opacity:0}100%{opacity:0}}
888
+ .aw-flow{animation:aw-flow linear infinite}
889
+ @keyframes aw-flow{to{stroke-dashoffset:-28}}
890
+ /* A label the density rules hid becomes readable while its node is hovered.
891
+ Done in CSS on purpose: a React state change here meant re-rendering the
892
+ whole graph (40 nodes, 58 animations) on every pointer move. */
893
+ .aw-node .aw-ml-hide{opacity:0}
894
+ .aw-node:hover .aw-ml-hide{opacity:1}
895
+ @media (prefers-reduced-motion: reduce){
896
+ .aw-breathe,.aw-risk-ring,.aw-flow{animation:none}
897
+ }
898
+ .aw-legend{display:flex;align-items:center;gap:12px;font-size:11px;
899
+ color:var(--dsw-alias-label-caption);white-space:nowrap}
900
+ .aw-legend span{display:inline-flex;align-items:center;gap:5px}
901
+ .aw-note{position:absolute;right:10px;bottom:10px;font-size:11px;padding:2px 6px;
902
+ color:var(--dsw-alias-label-caption);pointer-events:none;text-align:right;max-width:60%;
903
+ background:var(--dsw-alias-bg-base)}
904
+ .aw-bot{flex:0 0 auto;display:grid;grid-template-columns:1fr 1.25fr 1.15fr;
905
+ border-top:var(--aw-hair) solid var(--dsw-alias-border-l2);height:288px}
906
+ .aw-mod{min-width:0;min-height:0;display:flex;flex-direction:column;padding:10px 16px 8px;overflow:hidden}
907
+ .aw-mod+.aw-mod{border-left:var(--aw-hair) solid var(--dsw-alias-border-l2)}
908
+ .aw-mh{display:flex;align-items:baseline;justify-content:space-between;gap:8px;
909
+ margin-bottom:6px;flex:0 0 auto}
910
+ .aw-mh h3{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary);margin:0}
911
+ .aw-mh span{font-size:11px;color:var(--dsw-alias-label-caption);font-family:var(--aw-mono)}
912
+ .aw-scope{flex:0 0 auto;margin:-4px 0 6px;font-size:10.5px;line-height:14px;
913
+ color:var(--dsw-alias-label-caption);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
914
+ .aw-mb{flex:1 1 auto;min-height:0;overflow:auto;display:flex;flex-direction:column}
915
+ .aw-stack{display:flex;height:6px;border-radius:3px;overflow:hidden;margin-bottom:8px;
916
+ background:var(--dsw-alias-bg-layer-2)}
917
+ .aw-stack i{height:100%;transition:width .3s}
918
+ .aw-comp{display:grid;grid-template-columns:1fr 1fr;gap:1px 12px;font-size:11.5px}
919
+ .aw-comp div{display:flex;align-items:center;gap:5px;min-width:0;line-height:16px}
920
+ .aw-comp .k{color:var(--dsw-alias-label-tertiary);flex:1;overflow:hidden;
921
+ text-overflow:ellipsis;white-space:nowrap}
922
+ .aw-comp .v{font-family:var(--aw-mono);font-size:11px;color:var(--dsw-alias-label-secondary);
923
+ font-variant-numeric:tabular-nums}
924
+ .aw-comp .sw{width:8px;height:8px;border-radius:2px;flex:0 0 auto}
925
+ .aw-ug{display:grid;grid-template-columns:1fr 1fr;gap:1px 12px;font-size:11.5px}
926
+ .aw-ug>div{display:flex;align-items:baseline;gap:6px;min-width:0;line-height:17px}
927
+ .aw-ug .k{color:var(--dsw-alias-label-tertiary);flex:1;overflow:hidden;
928
+ text-overflow:ellipsis;white-space:nowrap}
929
+ .aw-ug .v{font-family:var(--aw-mono);font-size:11.5px;color:var(--dsw-alias-label-secondary);
930
+ font-variant-numeric:tabular-nums}
931
+ .aw-mb>.aw-sec{display:flex;align-items:baseline;justify-content:space-between;gap:8px;
932
+ margin:10px 0 5px}
933
+ .aw-sec-sum{font-family:var(--aw-mono);font-size:10px;color:var(--dsw-alias-label-caption)}
934
+ .aw-cap{font-size:11px;line-height:17px;color:var(--dsw-alias-label-caption);
935
+ margin-top:auto;padding-top:8px}
936
+ .aw-cap b{font-weight:500;color:var(--dsw-alias-label-tertiary);font-family:var(--aw-mono)}
937
+ .aw-mx{flex:1;min-height:0;overflow:auto}
938
+ .aw-mxh,.aw-row{display:grid;grid-template-columns:minmax(0,1fr) 84px 74px 52px;
939
+ gap:8px;align-items:center;padding:0 6px}
940
+ .aw-mxh{position:sticky;top:0;z-index:1;height:22px;font-size:11px;
941
+ color:var(--dsw-alias-label-caption);background:var(--dsw-alias-bg-base);
942
+ border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l2);padding-bottom:4px;margin-bottom:2px}
943
+ .aw-row{height:26px;border-radius:5px;cursor:pointer;font-size:12px}
944
+ .aw-row:hover{background:var(--dsw-alias-interactive-bg-hover)}
945
+ .aw-row[aria-selected="true"]{background:var(--dsw-alias-bg-multi-select)}
946
+ .aw-row.dim{opacity:.4}
947
+ .aw-row .nm{display:flex;align-items:center;gap:5px;min-width:0;
948
+ color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
949
+ .aw-row .nm svg{width:12px;height:12px;flex:0 0 auto;color:var(--dsw-alias-label-caption)}
950
+ .aw-row .mdl{color:var(--dsw-alias-label-caption);font-family:var(--aw-mono);font-size:11px;
951
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
952
+ .aw-row .bar{height:4px;border-radius:2px;background:var(--dsw-alias-bg-layer-2);overflow:hidden}
953
+ .aw-row .bar i{display:block;height:100%}
954
+ .aw-row .pc{text-align:right;font-family:var(--aw-mono);font-size:11px;
955
+ font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
956
+ .aw-insp{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:5px;padding-right:2px}
957
+ .aw-insp-empty{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;
958
+ gap:6px;font-size:12px;color:var(--dsw-alias-label-caption);text-align:center}
959
+ .aw-insp-empty svg{width:20px;height:20px;opacity:.5}
960
+ .aw-it{font-size:12.5px;font-weight:600;line-height:18px;color:var(--dsw-alias-label-primary);flex:0 0 auto}
961
+ .aw-im{display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:11px;
962
+ line-height:15px;color:var(--dsw-alias-label-caption)}
963
+ .aw-ig{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:2px 10px;flex:0 0 auto}
964
+ .aw-kv .k{font-size:11px;color:var(--dsw-alias-label-caption);line-height:16px}
965
+ .aw-kv .v{font-family:var(--aw-mono);font-size:13px;line-height:18px;
966
+ color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}
967
+ .aw-kv .v small{font-size:11px;color:var(--dsw-alias-label-caption);margin-left:2px}
968
+ .aw-sec{font-size:11px;font-weight:600;line-height:15px;color:var(--dsw-alias-label-tertiary)}
969
+ .aw-muted{font-size:11px;color:var(--dsw-alias-label-caption)}
970
+ .aw-iact{flex:0 0 auto;display:flex;gap:8px;padding-top:4px}
971
+ .aw-iact .aw-btn{height:26px}
972
+ .aw-iact .aw-btn{flex:1;justify-content:center}
973
+ .aw-empty{display:flex;align-items:center;justify-content:center;height:100%;
974
+ font-size:12px;color:var(--dsw-alias-label-caption)}
975
+ .aw-toast{position:absolute;left:50%;transform:translateX(-50%);bottom:18px;z-index:20;
976
+ max-width:70%;padding:8px 14px;border-radius:var(--aw-r);
977
+ border:var(--aw-hair) solid var(--dsw-alias-border-l3);
978
+ background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);
979
+ font-size:12px;line-height:18px;box-shadow:0 4px 16px rgba(0,0,0,.18);
980
+ display:flex;align-items:center}
981
+ .aw-err{padding:16px;font-size:12px;line-height:20px;color:var(--dsw-alias-state-warn-label)}
982
+ .aw-err code{font-family:var(--aw-mono);font-size:11px;color:var(--dsw-alias-label-tertiary);
983
+ display:block;margin-top:6px}
984
+ @media (max-width:1180px){
985
+ .aw-bot{grid-template-columns:1fr 1fr;height:190px}
986
+ .aw-mod:last-child{display:none}
987
+ }
988
+ @media (max-width:920px){
989
+ .aw-ws{grid-template-columns:1fr !important;grid-template-rows:minmax(0,38%) minmax(0,1fr)}
990
+ .aw-grip{display:none}
991
+ .aw-rail{border-right:0;border-bottom:var(--aw-hair) solid var(--dsw-alias-border-l2)}
992
+ .aw-bot{grid-template-columns:1fr;height:172px}
993
+ .aw-mod:nth-child(2){display:none}
994
+ .aw-pane+.aw-pane{display:none}
995
+ }
996
+ `
997
+
998
+ /* ══════════════════ icons ══════════════════ */
999
+
1000
+ function Icon({ name, size = 16 }) {
1001
+ const p = {
1002
+ width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
1003
+ stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round',
1004
+ }
1005
+ switch (name) {
1006
+ case 'network':
1007
+ return h('svg', p, [
1008
+ h('circle', { key: 'a', cx: 3, cy: 8, r: 1.4, fill: 'currentColor', stroke: 'none' }),
1009
+ h('circle', { key: 'b', cx: 8, cy: 4, r: 1.2 }),
1010
+ h('circle', { key: 'c', cx: 8, cy: 12, r: 1.2 }),
1011
+ h('circle', { key: 'd', cx: 13, cy: 6, r: 1.1 }),
1012
+ h('circle', { key: 'e', cx: 13, cy: 11, r: 1.1 }),
1013
+ h('path', { key: 'f', d: 'M3 8l5-4M3 8l5 4M8 4l5 2M8 12l5-1' }),
1014
+ ])
1015
+ case 'chat':
1016
+ return h('svg', p, [
1017
+ h('path', { key: 'a', d: 'M2.6 3.4h10.8v7.2H7.4L4.4 13v-2.4H2.6z' }),
1018
+ ])
1019
+ case 'search':
1020
+ return h('svg', p, [
1021
+ h('circle', { key: 'a', cx: 7, cy: 7, r: 4 }),
1022
+ h('path', { key: 'b', d: 'M10 10l3.2 3.2' }),
1023
+ ])
1024
+ case 'refresh':
1025
+ return h('svg', p, [
1026
+ h('path', { key: 'a', d: 'M13 8a5 5 0 1 1-1.6-3.7' }),
1027
+ h('path', { key: 'b', d: 'M13 2.6v2.6h-2.6' }),
1028
+ ])
1029
+ case 'enter':
1030
+ return h('svg', p, [
1031
+ h('path', { key: 'a', d: 'M6 3H3.6v10H6' }),
1032
+ h('path', { key: 'b', d: 'M9 5.6L12 8l-3 2.4M12 8H6' }),
1033
+ ])
1034
+ case 'close':
1035
+ return h('svg', p, [h('path', { key: 'a', d: 'M4 4l8 8M12 4l-8 8' })])
1036
+ case 'single':
1037
+ return h('svg', p, [h('rect', { key: 'a', x: 2.2, y: 3, width: 11.6, height: 10, rx: 1.6 })])
1038
+ case 'plus':
1039
+ return h('svg', p, h('path', { d: 'M8 3.4v9.2M3.4 8h9.2' }))
1040
+ case 'sub':
1041
+ return h('svg', p, [
1042
+ h('path', { key: 'a', d: 'M4 3v4.4a2 2 0 0 0 2 2h6' }),
1043
+ h('path', { key: 'b', d: 'M9.6 7l2.4 2.4L9.6 12' }),
1044
+ ])
1045
+ // A sheet with an arrow leaving it: "take this elsewhere".
1046
+ case 'handoff':
1047
+ return h('svg', p, [
1048
+ h('path', { key: 'a', d: 'M9.4 2.6H3.4v10.8h7.2V9.2' }),
1049
+ h('path', { key: 'b', d: 'M7.6 8.4l5-5M9 3.2h3.8v3.8' }),
1050
+ ])
1051
+ default:
1052
+ return h('svg', p, h('circle', { cx: 8, cy: 8, r: 5 }))
1053
+ }
1054
+ }
1055
+
1056
+ /* ══════════════════ network ══════════════════ */
1057
+
1058
+ /** Honour the OS "reduce motion" setting: particles are decoration. */
1059
+ const REDUCE_MOTION = (() => {
1060
+ try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches } catch { return false }
1061
+ })()
1062
+
1063
+ function Network({ graph, selected, onSelect, onProject, pinned }) {
1064
+ const pinnedSet = React.useMemo(() => new Set(pinned ?? []), [pinned])
1065
+ const subOrd = React.useMemo(() => {
1066
+ const map = new Map()
1067
+ const rows = (graph?.nodes ?? []).filter(nd => nd.kind === 'sub').sort((a, b) => a.y - b.y)
1068
+ rows.forEach((nd, i) => map.set(nd.id, i))
1069
+ return map
1070
+ }, [graph])
1071
+ if (!graph) return null
1072
+ if (!graph.sessions) {
1073
+ return h('div', { className: 'aw-canvas' },
1074
+ h('div', { className: 'aw-empty' }, T.noSession))
1075
+ }
1076
+ const { w, hgt, nodes, links, x } = graph
1077
+ const selNode = selected ? nodes.find(nd => nd.id === selected) : null
1078
+ const selPath = new Set()
1079
+ if (selNode) {
1080
+ selPath.add(selNode.id)
1081
+ let cur = selNode
1082
+ for (let i = 0; i < 4 && cur; i += 1) {
1083
+ const up = cur.kind === 'sub' ? cur.parentId
1084
+ : cur.kind === 'main' ? `__p__:${cur.session.project}`
1085
+ : cur.kind === 'project' ? '__hub__' : null
1086
+ if (!up) break
1087
+ selPath.add(up)
1088
+ cur = graph.nodeById.get(up)
1089
+ }
1090
+ }
1091
+ const dimmed = nd => Boolean(selNode) && !selPath.has(nd.id)
1092
+ // Selecting a main session also lights up its own subagents: that is the
1093
+ // one moment where their titles are guaranteed to fit, because the
1094
+ // density rules never hide a child of the selected node.
1095
+ const selKids = new Set()
1096
+ if (selNode?.kind === 'main') {
1097
+ for (const lk of links) {
1098
+ if (lk.kind === 'child' && lk.from === selNode.id) {
1099
+ selKids.add(lk.to)
1100
+ selPath.add(lk.to)
1101
+ }
1102
+ }
1103
+ }
1104
+
1105
+ const guides = [
1106
+ { at: x.project, label: T.colProject, anchor: 'end' },
1107
+ { at: x.main, label: T.colSession, anchor: 'start' },
1108
+ { at: x.sub - 14, label: T.colSub, anchor: 'start' },
1109
+ ]
1110
+
1111
+ return h('div', { className: 'aw-canvas' }, [
1112
+ h('svg', { key: 'svg', viewBox: `0 0 ${w} ${hgt}`, preserveAspectRatio: 'xMidYMid meet' }, [
1113
+ h('g', { key: 'grid' },
1114
+ guides.map((gd, i) => h('g', { key: i }, [
1115
+ h('line', {
1116
+ key: 'l',
1117
+ x1: gd.at, y1: 26, x2: gd.at, y2: hgt - 10,
1118
+ stroke: 'var(--dsw-alias-border-l1)', strokeWidth: 1, strokeDasharray: '2 6',
1119
+ }),
1120
+ h('text', {
1121
+ key: 't',
1122
+ x: gd.anchor === 'end' ? gd.at - 8 : gd.at + 8,
1123
+ y: 16,
1124
+ textAnchor: gd.anchor,
1125
+ fontSize: 10.5,
1126
+ fill: 'var(--dsw-alias-label-caption)',
1127
+ letterSpacing: '0.08em',
1128
+ }, gd.label),
1129
+ ])),
1130
+ h('text', {
1131
+ key: 'hub',
1132
+ x: x.hub, y: 16, fontSize: 10.5,
1133
+ fill: 'var(--dsw-alias-label-caption)', letterSpacing: '0.08em',
1134
+ }, T.hub),
1135
+ ),
1136
+
1137
+ h('g', { key: 'links' },
1138
+ links.map((lk, i) => {
1139
+ const a = graph.nodeById.get(lk.from)
1140
+ const b = graph.nodeById.get(lk.to)
1141
+ if (!a || !b) return null
1142
+ const on = selPath.has(lk.from) && selPath.has(lk.to)
1143
+ const dim = Boolean(selNode) && !on
1144
+ const base = lk.kind === 'root' ? 0.34 : lk.kind === 'project' ? 0.24 : 0.2
1145
+ const width = lk.kind === 'root' ? 1.3 : lk.kind === 'project' ? 1 : 0.85
1146
+ const d = linkPath(a, b)
1147
+ // Particles ride only the links that end at a session currently
1148
+ // loaded in a workspace pane: the cockpit then shows "these are
1149
+ // the ones I am watching", not 40 identical animations.
1150
+ const traced = pinnedSet.has(lk.to)
1151
+ const pathId = `aw-lp-${i}`
1152
+ // Traffic, not decoration: the old 2.2–4.2s crawl read as a slow
1153
+ // drift. Four dots on a link the user is watching, two on a
1154
+ // subagent link, all at roughly twice the old speed.
1155
+ const speed = Math.max(0.95, 1.9 - (lk.activity ?? 0) * 0.9)
1156
+ const dots = lk.kind === 'child' ? 2 : 4
1157
+ const rDot = lk.kind === 'child' ? 1.8 : 2.6
1158
+ return h('g', { key: `${lk.from}>${lk.to}:${i}`, opacity: dim ? 0.18 : 1 }, [
1159
+ lk.kind !== 'child' ? h('path', {
1160
+ key: 'glow',
1161
+ d, fill: 'none',
1162
+ stroke: on ? 'var(--dsw-alias-trajectory-accent)' : 'var(--dsw-alias-label-tertiary)',
1163
+ strokeWidth: on ? 4.5 : 3.4,
1164
+ strokeOpacity: on ? 0.16 : 0.07,
1165
+ strokeLinecap: 'round',
1166
+ }) : null,
1167
+ h('path', {
1168
+ key: 'p',
1169
+ id: pathId,
1170
+ d, fill: 'none',
1171
+ stroke: on ? 'var(--dsw-alias-trajectory-accent)' : 'var(--dsw-alias-label-tertiary)',
1172
+ strokeWidth: on ? 1.7 : width,
1173
+ strokeOpacity: on ? 0.9 : base + (lk.activity ?? 0) * 0.22,
1174
+ strokeLinecap: 'round',
1175
+ }),
1176
+ traced && !REDUCE_MOTION ? h('g', { key: 'pt' },
1177
+ Array.from({ length: dots }, (_, d) => {
1178
+ const tint = lk.risk === 'crit' ? 'var(--dsw-alias-state-error-primary)'
1179
+ : lk.risk === 'warn' ? 'var(--dsw-alias-state-warn-primary)'
1180
+ : 'var(--dsw-alias-trajectory-accent)'
1181
+ return h('g', { key: `p${d}` }, [
1182
+ // Halo + core: a 2.6px dot on a 1px line is easy to miss,
1183
+ // a soft 6px glow travelling with it is not.
1184
+ h('circle', { key: 'h', r: rDot * 2.4, fill: tint, opacity: 0.16 }),
1185
+ h('circle', { key: 'c', r: rDot, fill: tint, opacity: on ? 1 : 0.85 }),
1186
+ h('animateMotion', {
1187
+ key: 'm',
1188
+ dur: `${speed.toFixed(2)}s`,
1189
+ begin: `${((d / dots) * speed).toFixed(2)}s`,
1190
+ repeatCount: 'indefinite',
1191
+ rotate: 'auto',
1192
+ }, h('mpath', { key: 'mp', href: `#${pathId}`, xlinkHref: `#${pathId}` })),
1193
+ ])
1194
+ })) : null,
1195
+ !traced && !REDUCE_MOTION ? h('g', { key: 'dust' },
1196
+ // Faint dust on every idle link. The graph sits on an empty
1197
+ // background, so twenty dead grey curves read as a wireframe;
1198
+ // a couple of slow white specks make it look alive without
1199
+ // competing with the coloured traffic on the watched panes.
1200
+ Array.from({ length: lk.kind === 'child' ? 1 : 2 }, (_, d) => {
1201
+ const drift = 7.5 + ((i + d * 3) % 5) * 1.3
1202
+ return h('g', { key: `d${d}` }, [
1203
+ h('circle', { key: 'h', r: 2.4, fill: 'var(--aw-dust)', opacity: 0.14 }),
1204
+ h('circle', { key: 'c', r: 1.15, fill: 'var(--aw-dust)', opacity: 0.5 }),
1205
+ h('animateMotion', {
1206
+ key: 'm',
1207
+ dur: `${drift.toFixed(2)}s`,
1208
+ begin: `${((d / 2) * drift + (i % 3) * 0.6).toFixed(2)}s`,
1209
+ repeatCount: 'indefinite',
1210
+ }, h('mpath', { key: 'mp', href: `#${pathId}`, xlinkHref: `#${pathId}` })),
1211
+ ])
1212
+ })) : null,
1213
+ // Flow only where the target session has real recent activity.
1214
+ lk.active && lk.kind !== 'root' ? h('path', {
1215
+ key: 'f',
1216
+ d, fill: 'none',
1217
+ stroke: lk.risk === 'crit' ? 'var(--dsw-alias-state-error-primary)'
1218
+ : lk.risk === 'warn' ? 'var(--dsw-alias-state-warn-primary)' : 'var(--dsw-alias-trajectory-accent)',
1219
+ strokeWidth: on ? 2 : 1.2,
1220
+ strokeOpacity: on ? 0.85 : 0.55,
1221
+ strokeLinecap: 'round',
1222
+ strokeDasharray: '2 11',
1223
+ className: 'aw-flow',
1224
+ style: { animationDuration: `${(2.1 - (lk.activity ?? 0) * 0.9).toFixed(2)}s` },
1225
+ }) : null,
1226
+ ].filter(Boolean))
1227
+ }),
1228
+ ),
1229
+
1230
+ h('g', { key: 'nodes' },
1231
+ nodes.map(nd => {
1232
+ const dim = dimmed(nd)
1233
+ const isSel = selected === nd.id
1234
+ const isHub = nd.kind === 'hub'
1235
+ const isProject = nd.kind === 'project'
1236
+ const color = isHub || isProject
1237
+ ? 'var(--dsw-alias-label-secondary)'
1238
+ : levelOf(nd.session)
1239
+ const riskVar = nd.risk === 'crit' ? 'var(--dsw-alias-state-error-primary)'
1240
+ : nd.risk === 'warn' ? 'var(--dsw-alias-state-warn-primary)' : null
1241
+ const label = nd.session?.title || T.noTitle
1242
+ // Vertical room decides how many titles fit: a subagent row is
1243
+ // 0.62 of a main one, so the two columns get separate budgets.
1244
+ // 1 = every row, 2 = every other row, 0 = only on demand.
1245
+ const rowH = graph.unitMain ?? 20
1246
+ const subH = rowH * 0.62
1247
+ const dense = rowH < 13
1248
+ const subBudget = subOrd.size <= 8 || subH >= 20 ? 1 : subH >= 9 ? 2 : 0
1249
+ const staggered = (subOrd.get(nd.id) ?? 0) % 2 === 0
1250
+ // When a main session is selected its subagents are the subject,
1251
+ // so they take priority over the rest of the column.
1252
+ const focus = selKids.size > 0
1253
+ const subLabel = focus
1254
+ ? selKids.has(nd.id) && (subBudget === 1 || staggered || isSel)
1255
+ : subBudget === 1 || (subBudget === 2 && staggered) || isSel
1256
+ const showLabel = isProject
1257
+ || (nd.kind === 'main'
1258
+ && (!dense || isSel || nd.risk !== 'ok' || (nd.ord ?? 0) % 2 === 0))
1259
+ // A subagent title is the only thing that explains that
1260
+ // column, so show it whenever it fits and on demand (hover /
1261
+ // select) when it does not. Risk deliberately does not force it
1262
+ // here: at 10px rows the forced labels collide, and the red
1263
+ // ring already says it.
1264
+ || (nd.kind === 'sub' && subLabel)
1265
+ const maxChars = nd.kind === 'sub' ? 12 : 17
1266
+
1267
+ const clickable = Boolean(nd.session) || isHub || isProject
1268
+ return h('g', {
1269
+ key: nd.id,
1270
+ className: 'aw-node',
1271
+ role: clickable ? 'button' : undefined,
1272
+ tabIndex: clickable ? 0 : undefined,
1273
+ style: clickable ? { cursor: 'pointer' } : undefined,
1274
+ 'aria-label': nd.session ? `${label} · ${pct(nd.session.ratio)}`
1275
+ : isHub ? '工作台:显示全部项目' : `${nd.name}:只看该项目`,
1276
+ opacity: dim ? 0.34 : 1,
1277
+ onClick: () => {
1278
+ if (nd.session) { onSelect(isSel ? null : nd.session.id); return }
1279
+ if (isHub) { onSelect(null); onProject('__all'); return }
1280
+ if (isProject) { onSelect(null); onProject(nd.name) }
1281
+ },
1282
+ onKeyDown: ev => {
1283
+ if (!nd.session && !isHub && !isProject) return
1284
+ if (ev.key === 'Enter' || ev.key === ' ') {
1285
+ ev.preventDefault()
1286
+ if (nd.session) onSelect(isSel ? null : nd.session.id)
1287
+ else if (isHub) { onSelect(null); onProject('__all') }
1288
+ else { onSelect(null); onProject(nd.name) }
1289
+ }
1290
+ },
1291
+ }, [
1292
+ !isHub && !isProject ? h('circle', {
1293
+ key: 'soft',
1294
+ cx: nd.x, cy: nd.y, r: nd.r * 2.9,
1295
+ fill: levelOf(nd.session),
1296
+ fillOpacity: 0.07 + (nd.active ? 0.05 : 0),
1297
+ }) : null,
1298
+
1299
+ nd.active && !isHub ? h('circle', {
1300
+ key: 'halo',
1301
+ cx: nd.x, cy: nd.y, r: nd.r * 2.6,
1302
+ fill: riskVar ?? 'var(--dsw-alias-trajectory-accent)',
1303
+ className: 'aw-breathe',
1304
+ style: { animationDelay: `${((nd.x + nd.y) % 24) / 10}s` },
1305
+ }) : null,
1306
+
1307
+ riskVar ? h('circle', {
1308
+ key: 'risk',
1309
+ cx: nd.x, cy: nd.y, r: nd.r,
1310
+ fill: 'none', stroke: riskVar, strokeWidth: 1.2,
1311
+ className: 'aw-risk-ring',
1312
+ }) : null,
1313
+
1314
+ h('circle', {
1315
+ key: 'core',
1316
+ cx: nd.x, cy: nd.y, r: isSel ? nd.r + 2.5 : nd.r,
1317
+ fill: isProject ? 'var(--dsw-alias-bg-layer-3)' : (riskVar ? 'var(--dsw-alias-bg-base)' : color),
1318
+ fillOpacity: isProject ? 1 : (riskVar ? 0.95 : (isHub ? 1 : 0.88 + 0.12 * (nd.activity ?? 0.4))),
1319
+ stroke: isSel ? 'var(--dsw-alias-trajectory-accent)'
1320
+ : isProject ? 'var(--dsw-alias-border-l4)' : (riskVar ?? 'none'),
1321
+ strokeWidth: isSel ? 2 : (isProject ? 1.2 : 1),
1322
+ }),
1323
+
1324
+ isProject ? h('text', {
1325
+ key: 'pl',
1326
+ x: nd.x - nd.r - 10, y: nd.y,
1327
+ textAnchor: 'end', dominantBaseline: 'middle',
1328
+ fontSize: 12, fontWeight: 600,
1329
+ fill: isSel ? 'var(--dsw-alias-trajectory-accent)' : 'var(--dsw-alias-label-primary)',
1330
+ stroke: 'var(--dsw-alias-bg-base)', strokeWidth: 3,
1331
+ paintOrder: 'stroke', strokeLinejoin: 'round',
1332
+ }, nd.name) : null,
1333
+
1334
+ isProject ? h('text', {
1335
+ key: 'pn',
1336
+ x: nd.x - nd.r - 10, y: nd.y + 14,
1337
+ textAnchor: 'end', fontSize: 10.5,
1338
+ fill: 'var(--dsw-alias-label-caption)',
1339
+ stroke: 'var(--dsw-alias-bg-base)', strokeWidth: 3,
1340
+ paintOrder: 'stroke', strokeLinejoin: 'round',
1341
+ }, `${nd.count} 个会话`) : null,
1342
+
1343
+ // Usage ring: the percentage is a ring around the dot, so the
1344
+ // label stays one line and 16 rows still fit without touching.
1345
+ nd.kind === 'main' && nd.session.ratio != null ? (() => {
1346
+ const c = 2 * Math.PI * (nd.r + 3)
1347
+ return h('circle', {
1348
+ key: 'ring',
1349
+ cx: nd.x, cy: nd.y, r: nd.r + 3,
1350
+ fill: 'none',
1351
+ stroke: levelOf(nd.session),
1352
+ strokeWidth: 1.3,
1353
+ strokeDasharray: `${(Math.min(1, nd.session.ratio) * c).toFixed(2)} ${c.toFixed(2)}`,
1354
+ strokeLinecap: 'round',
1355
+ transform: `rotate(-90 ${nd.x} ${nd.y})`,
1356
+ opacity: 0.9,
1357
+ })
1358
+ })() : null,
1359
+
1360
+ // Rendered even when the density rules hide it: a hover that
1361
+ // toggled React state used to re-render all 40 nodes and 58
1362
+ // SMIL animations on every pointer move, which is what made the
1363
+ // cockpit feel sticky. CSS does the reveal now.
1364
+ !isProject ? h('g', {
1365
+ key: 'ml',
1366
+ className: showLabel ? 'aw-ml' : 'aw-ml aw-ml-hide',
1367
+ }, [
1368
+ h('text', {
1369
+ key: 't',
1370
+ x: nd.x - nd.r - (nd.kind === 'sub' ? 6 : 8), y: nd.y,
1371
+ textAnchor: 'end', dominantBaseline: 'middle',
1372
+ fontSize: nd.kind === 'sub' ? 10.5 : 11.5,
1373
+ fill: isSel ? 'var(--dsw-alias-trajectory-accent)'
1374
+ : dim ? 'var(--dsw-alias-label-caption)'
1375
+ : nd.kind === 'sub' ? 'var(--dsw-alias-label-tertiary)'
1376
+ : 'var(--dsw-alias-label-secondary)',
1377
+ stroke: 'var(--dsw-alias-bg-base)', strokeWidth: 3,
1378
+ paintOrder: 'stroke', strokeLinejoin: 'round',
1379
+ }, label.length > maxChars ? label.slice(0, maxChars) + '…' : label),
1380
+ // The percentage sits to the right of the dot, where the
1381
+ // subagent column has no room left.
1382
+ isSel && nd.kind !== 'sub' ? h('text', {
1383
+ key: 'p',
1384
+ x: nd.x + nd.r + 8, y: nd.y,
1385
+ textAnchor: 'start', dominantBaseline: 'middle',
1386
+ fontSize: 10.5,
1387
+ fontFamily: 'var(--aw-mono)',
1388
+ fill: levelOf(nd.session),
1389
+ stroke: 'var(--dsw-alias-bg-base)', strokeWidth: 3,
1390
+ paintOrder: 'stroke', strokeLinejoin: 'round',
1391
+ }, pct(nd.session.ratio)) : null,
1392
+ ].filter(Boolean)) : null,
1393
+
1394
+ isHub ? h('title', { key: 'tt' }, '工作台 · 点击显示全部项目') : null,
1395
+ isProject ? h('title', { key: 'tt' },
1396
+ `${nd.name} · ${nd.count} 个会话 · 点击只看该项目`) : null,
1397
+ nd.session ? h('title', { key: 'tt' },
1398
+ `${label}\n${nd.session.project} · ${nd.session.origin === 'subagent' ? T.sub : T.main}`
1399
+ + `\n${nd.session.model ?? '模型未知'} · 占用 ${pct(nd.session.ratio)}`
1400
+ + `\n${fmt(nd.session.total)} / ${nd.session.contextWindow ? fmt(nd.session.contextWindow) : '未知'} tok`
1401
+ + `\n最近活动 ${relTime(nd.session.updatedAt)}`) : null,
1402
+ ].filter(Boolean))
1403
+ }),
1404
+ ),
1405
+ ]),
1406
+
1407
+ h('div', {
1408
+ key: 'nt',
1409
+ className: 'aw-note',
1410
+ title: T.edgesNote(graph.projects, graph.sessions, graph.parentChild),
1411
+ }, `${graph.sessions} 会话 · ${graph.parentChild} 条父子链路 · 0 条跨分支关联`),
1412
+ ])
1413
+ }
1414
+
1415
+ /**
1416
+ * The graph is the most expensive thing in the panel — ~40 nodes and ~60 SMIL
1417
+ * animations. Re-rendering it on unrelated state (a toast, a poll) restarts
1418
+ * those animations and drops frames, so skip the render unless the layout,
1419
+ * the selection or the pinned panes actually changed.
1420
+ */
1421
+ const NetworkMemo = React.memo(Network, (a, b) => a.graph === b.graph
1422
+ && a.selected === b.selected
1423
+ && a.pinned.length === b.pinned.length
1424
+ && a.pinned.every((v, i) => v === b.pinned[i]))
1425
+
1426
+ /* ══════════════════ bottom modules ══════════════════ */
1427
+
1428
+ /** Sum one numeric field across a session's daily activity rows. */
1429
+ function activitySum(session, field) {
1430
+ let sum = 0
1431
+ for (const day of Object.values(session.activityDays ?? {})) {
1432
+ const v = day?.[field]
1433
+ if (typeof v === 'number' && Number.isFinite(v)) sum += v
1434
+ }
1435
+ return sum
1436
+ }
1437
+
1438
+ /** `$0.0042` — small amounts need more decimals than a total. */
1439
+ /**
1440
+ * Friendly model names.
1441
+ *
1442
+ * `deepseek-flash` is the **current** API id and serves V4.1-Flash;
1443
+ * `deepseek-v4-flash` is the old name of the same model (still accepted, and
1444
+ * priced identically), so both read as V4.1 Flash. The raw id stays in the
1445
+ * tooltip for anyone who needs to check.
1446
+ */
1447
+ const MODEL_LABEL = {
1448
+ 'deepseek-flash': 'V4.1 Flash',
1449
+ 'deepseek-v4-flash': 'V4.1 Flash 旧名',
1450
+ 'deepseek-v4.1-flash': 'V4.1 Flash',
1451
+ 'deepseek-v4-pro': 'V4 Pro',
1452
+ 'deepseek-chat': 'V3.2 Chat',
1453
+ 'deepseek-reasoner': 'V3.2 Reasoner',
1454
+ }
1455
+ // Grouping key: the old id belongs to the same model, so the caption adds
1456
+ // them up instead of listing the same model twice.
1457
+ const MODEL_KEY = { 'deepseek-v4-flash': 'deepseek-flash', 'deepseek-v4.1-flash': 'deepseek-flash' }
1458
+ /** Sort modes for the session rail, in cycle order. */
1459
+ const SORT = [
1460
+ ['ratio', '占用'],
1461
+ ['recent', '最近'],
1462
+ ['cost', '费用'],
1463
+ ]
1464
+ const sortLabel = key => SORT.find(x => x[0] === key)?.[1] ?? '占用'
1465
+
1466
+ const modelKey = m => (m == null ? '—' : (MODEL_KEY[m] ?? m))
1467
+ const modelLabel = m => (m == null ? '—' : (MODEL_LABEL[m] ?? String(m).replace(/^deepseek-/, '')))
1468
+
1469
+ /**
1470
+ * Money in CNY.
1471
+ *
1472
+ * The host prices DeepSeek's own models from the official CNY list and only
1473
+ * falls back to models.dev (USD) for third-party routes, so this is the same
1474
+ * number the official pricing page implies — dollars here made the panel
1475
+ * disagree with every other DSH cost readout by 6.7×.
1476
+ */
1477
+ const cny = v => (v == null || !Number.isFinite(v) ? '—'
1478
+ : v >= 100 ? `¥${v.toFixed(0)}`
1479
+ : v >= 1 ? `¥${v.toFixed(2)}`
1480
+ : v >= 0.01 ? `¥${v.toFixed(3)}`
1481
+ : `¥${v.toFixed(4)}`)
1482
+
1483
+ /**
1484
+ * Prompt-cache hit rate: cached reads over every input token billed.
1485
+ * @param session - wire DTO.
1486
+ * @returns ratio in [0,1], or null when the host sent no usage.
1487
+ */
1488
+ function hitRateOf(session) {
1489
+ const u = session?.usage
1490
+ if (!u) return null
1491
+ const side = (u.uncached ?? 0) + (u.cacheRead ?? 0) + (u.cacheWrite ?? 0)
1492
+ return side > 0 ? (u.cacheRead ?? 0) / side : null
1493
+ }
1494
+
1495
+ /**
1496
+ * Bottom-left module: what the context is made of, and what it has cost.
1497
+ *
1498
+ * The part breakdown comes from `contextTimeline.current`; the usage and
1499
+ * cost numbers come from the provider's own token accounting
1500
+ * (`tokenUsage` / `contextActivity.cost`), priced at models.dev list rates.
1501
+ * Nothing here is inferred from message counts.
1502
+ */
1503
+ function Composition({ sessions, pricing, scopeLabel }) {
1504
+ const totals = {}
1505
+ let sum = 0
1506
+ for (const s of sessions) {
1507
+ if (!s.parts) continue
1508
+ for (const [k] of PARTS) {
1509
+ const v = s.parts[k] ?? 0
1510
+ totals[k] = (totals[k] ?? 0) + v
1511
+ sum += v
1512
+ }
1513
+ }
1514
+ const caps = new Map()
1515
+ for (const s of sessions) {
1516
+ if (!s.contextWindow) continue
1517
+ const key = modelLabel(modelKey(s.model))
1518
+ const prev = caps.get(key) ?? { count: 0, cap: s.contextWindow }
1519
+ caps.set(key, { count: prev.count + 1, cap: s.contextWindow })
1520
+ }
1521
+ const unknown = sessions.filter(s => s.ratio == null).length
1522
+
1523
+ // Provider token accounting, aggregated over the current selection.
1524
+ const usage = { uncached: 0, cacheRead: 0, cacheWrite: 0, output: 0 }
1525
+ let usageSessions = 0
1526
+ let costSum = 0
1527
+ let costSessions = 0
1528
+ let peakBuckets = 0
1529
+ for (const s of sessions) {
1530
+ if (s.usage) {
1531
+ usageSessions += 1
1532
+ usage.uncached += s.usage.uncached ?? 0
1533
+ usage.cacheRead += s.usage.cacheRead ?? 0
1534
+ usage.cacheWrite += s.usage.cacheWrite ?? 0
1535
+ usage.output += s.usage.output ?? 0
1536
+ }
1537
+ if (typeof s.costCny === 'number') {
1538
+ costSum += s.costCny
1539
+ costSessions += 1
1540
+ }
1541
+ peakBuckets += s.costPeakBuckets ?? 0
1542
+ }
1543
+ const inputSide = usage.uncached + usage.cacheRead + usage.cacheWrite
1544
+ const hitRate = inputSide > 0 ? usage.cacheRead / inputSide : null
1545
+ const requests = sessions.reduce((n, s) => n + activitySum(s, 'requests'), 0)
1546
+
1547
+ const cell = (key, k, v, title) => h('div', { key, title },
1548
+ h('span', { key: 'k', className: 'k' }, k),
1549
+ h('span', { key: 'v', className: 'v' }, v))
1550
+
1551
+ return h('section', { className: 'aw-mod' }, [
1552
+ h('div', { className: 'aw-mh', key: 'h' }, [
1553
+ h('h3', { key: 't' }, T.composition),
1554
+ h('span', {
1555
+ key: 's',
1556
+ title: '当前上下文快照:把所有选中会话此刻占用的 prompt 加起来。'
1557
+ + '它不是累计消耗——累计在下面的「累计用量与费用」里。'
1558
+ + '容量按模型分别统计,不混算成单一百分比',
1559
+ }, sum ? fmt(sum) + ' tok · 当前' : '—'),
1560
+ ]),
1561
+ // Which sessions this panel is talking about. Without it, a project
1562
+ // click and a session click look identical: both just show numbers.
1563
+ scopeLabel ? h('div', {
1564
+ key: 'scope',
1565
+ className: 'aw-scope',
1566
+ title: '面板统计范围:跟着驾驶舱里选中的节点走',
1567
+ }, scopeLabel) : null,
1568
+ h('div', { className: 'aw-mb', key: 'b' }, [
1569
+ h('div', {
1570
+ className: 'aw-stack',
1571
+ key: 'st',
1572
+ title: '构成比例由事件逐条估算;总量按服务端返回的 prompt 校准,所以各项之和等于顶部那个数',
1573
+ },
1574
+ PARTS.map(([k, , color]) => (totals[k]
1575
+ ? h('i', {
1576
+ key: k,
1577
+ style: { width: `${(totals[k] / sum) * 100}%`, background: color },
1578
+ title: `${k} ${fmt(totals[k])}`,
1579
+ })
1580
+ : null)).filter(Boolean)),
1581
+ h('div', { className: 'aw-comp', key: 'cp' },
1582
+ PARTS.map(([k, label, color]) => h('div', { key: k }, [
1583
+ h('span', { key: 's', className: 'sw', style: { background: color } }),
1584
+ h('span', { key: 'k', className: 'k' }, label),
1585
+ h('span', { key: 'v', className: 'v' },
1586
+ sum ? ((totals[k] ?? 0) / sum * 100).toFixed(1) + '%' : '—'),
1587
+ ]))),
1588
+
1589
+ h('div', {
1590
+ className: 'aw-sec',
1591
+ key: 's2',
1592
+ title: '会话开始至今的累计计费 token,与上面「当前上下文」不是同一口径:'
1593
+ + '上面是此刻占着多少,这里是历史上一共读过多少',
1594
+ }, [
1595
+ h('span', { key: 't' }, T.usageTitle),
1596
+ // "这个项目一共烧了多少" is the sum of all four billing buckets —
1597
+ // a different number from the current context above.
1598
+ h('span', { key: 's', className: 'aw-sec-sum' },
1599
+ usageSessions
1600
+ ? `合计 ${fmt(usage.uncached + usage.cacheRead + usage.cacheWrite + usage.output)} tok`
1601
+ : ''),
1602
+ ]),
1603
+ h('div', { className: 'aw-ug', key: 'ug' }, [
1604
+ cell('cost', T.cost, cny(costSessions ? costSum : null),
1605
+ costSessions
1606
+ ? 'DeepSeek 官方人民币价:谷时价,峰时(北京时间工作日 '
1607
+ + '09:00–12:00、14:00–18:00)按 2 倍计;第三方路由按 models.dev 美元价折算\n'
1608
+ + '不含折扣与订阅优惠'
1609
+ + `\n覆盖 ${costSessions} / ${sessions.length} 个会话`
1610
+ + (peakBuckets ? `,其中 ${peakBuckets} 个峰时桶` : '')
1611
+ + (pricing?.ready ? '' : '\n价格表尚未取到,下次刷新会重试')
1612
+ : `暂无价格数据${pricing?.ready ? '(这些会话的模型不在价格表里)' : '(价格表未取到,无法联网时会一直为空)'}`),
1613
+ cell('hit', T.cacheHit, hitRate == null ? '—' : (hitRate * 100).toFixed(1) + '%',
1614
+ `命中缓存的输入 token / 全部输入 token(含缓存写)`
1615
+ + `\n${fmt(usage.cacheRead)} / ${fmt(inputSide)} tok`
1616
+ + '\n越高越省钱:未命中的输入按全价计费'),
1617
+ cell('in', T.tokIn, usageSessions ? fmt(usage.uncached) : '—',
1618
+ `未命中缓存的输入 token,按全价计费\n合计 ${fmt(inputSide)} 输入 token`),
1619
+ cell('out', T.tokOut, usageSessions ? fmt(usage.output) : '—',
1620
+ '模型生成的输出 token'),
1621
+ cell('read', T.tokRead, usageSessions ? fmt(usage.cacheRead) : '—',
1622
+ '从服务端提示缓存命中的输入 token'),
1623
+ cell('write', T.tokWrite, usageSessions ? fmt(usage.cacheWrite) : '—',
1624
+ '写入提示缓存的输入 token(通常按输入价计费)'),
1625
+ cell('rq', T.requests, requests ? fmt(requests) : '—',
1626
+ '按会话按日累计的模型请求次数(来自 host 的活动统计)'),
1627
+ cell('ss', T.sessions, String(sessions.length),
1628
+ `当前统计范围内的会话数;费用与用量覆盖其中 `
1629
+ + `${usageSessions} 个有 token 记账的会话`),
1630
+ ]),
1631
+ ].filter(Boolean)),
1632
+ h('div', { className: 'aw-cap', key: 'c' }, [
1633
+ // The currency needs a word next to it: a bare "$" in a Chinese UI
1634
+ // reads as a rendering mistake, and we have no CNY price source.
1635
+ h('div', { key: 'm' }, '费用按人民币 · 峰时 2 倍 · 官方价目表'),
1636
+ h('div', { key: 'b' },
1637
+ [...caps.entries()].map(([m, v]) => `${m} × ${v.count}`).join(' · ')),
1638
+ unknown ? h('div', { key: 'c' },
1639
+ `${unknown} 个会话缺少上下文数据,显示为未知而非 0`) : null,
1640
+ ].filter(Boolean)),
1641
+ ])
1642
+ }
1643
+
1644
+ function Matrix({ sessions, selected, onSelect, th }) {
1645
+ return h('section', { className: 'aw-mod' }, [
1646
+ h('div', { className: 'aw-mh', key: 'h' }, [
1647
+ h('h3', { key: 't' }, T.matrix),
1648
+ h('span', { key: 's' }, `${sessions.length}`),
1649
+ ]),
1650
+ h('div', { className: 'aw-mb', key: 'b' }, [
1651
+ // Every column names its own unit: a bare "%" next to "占用" reads as
1652
+ // decoration, and nobody can tell which of the two columns is which.
1653
+ h('div', {
1654
+ className: 'aw-mxh',
1655
+ key: 'h',
1656
+ title: '上下文占用 = 已用 / 容量(与服务端状态栏同口径);'
1657
+ + '条形上的竖线刻度是该会话的压缩点,越过它 DSH 就会压缩历史',
1658
+ }, [
1659
+ h('span', { key: 'a' }, '会话'),
1660
+ h('span', { key: 'b' }, '模型'),
1661
+ h('span', { key: 'c' }, '上下文占用'),
1662
+ h('span', { key: 'd', style: { textAlign: 'right' } }, '占用率'),
1663
+ ]),
1664
+ h('div', { className: 'aw-mx', key: 'l', role: 'listbox', 'aria-label': T.matrix },
1665
+ sessions.map(s => {
1666
+ const point = compactPoint(s)
1667
+ return h('div', {
1668
+ key: s.id,
1669
+ className: 'aw-row',
1670
+ role: 'option',
1671
+ tabIndex: 0,
1672
+ 'aria-selected': selected === s.id,
1673
+ title: contextHint(s, th),
1674
+ onKeyDown: ev => {
1675
+ if (ev.key !== 'Enter' && ev.key !== ' ') return
1676
+ ev.preventDefault()
1677
+ onSelect(selected === s.id ? null : s.id)
1678
+ },
1679
+ onClick: () => onSelect(selected === s.id ? null : s.id),
1680
+ }, [
1681
+ h('span', { key: 'n', className: 'nm' }, [
1682
+ h(Icon, { key: 'i', name: s.origin === 'subagent' ? 'sub' : 'chat', size: 12 }),
1683
+ h('span', {
1684
+ key: 't',
1685
+ style: { overflow: 'hidden', textOverflow: 'ellipsis' },
1686
+ }, s.title || T.noTitle),
1687
+ ]),
1688
+ h('span', { key: 'm', className: 'mdl' }, modelLabel(s.model)),
1689
+ h('span', { key: 'b', className: 'bar' }, [
1690
+ h('i', {
1691
+ key: 'f',
1692
+ style: {
1693
+ width: `${Math.min(100, (s.ratio ?? 0) * 100)}%`,
1694
+ background: levelOf(s),
1695
+ },
1696
+ }),
1697
+ // The mark is the point where compaction actually fires for
1698
+ // this session; a full bar is not the danger line.
1699
+ point ? h('b', {
1700
+ key: 'k',
1701
+ style: { left: `${Math.min(100, point.ratio * 100)}%` },
1702
+ title: `压缩点 ${pct(point.ratio)}`,
1703
+ }) : null,
1704
+ ]),
1705
+ h('span', { key: 'p', className: 'pc' }, pct(s.ratio)),
1706
+ ])
1707
+ })),
1708
+ ]),
1709
+ ])
1710
+ }
1711
+
1712
+ function Inspector({ session, onOpen, th }) {
1713
+ if (!session) {
1714
+ return h('section', { className: 'aw-mod' }, [
1715
+ h('div', { className: 'aw-mh', key: 'h' }, [h('h3', { key: 't' }, T.inspector)]),
1716
+ h('div', { className: 'aw-insp', key: 'e' }, h('div', { className: 'aw-insp-empty' }, [
1717
+ h(Icon, { key: 'i', name: 'network', size: 20 }),
1718
+ h('span', { key: 's' }, T.pickNode),
1719
+ ])),
1720
+ ])
1721
+ }
1722
+ const days = Object.keys(session.activityDays ?? {}).sort()
1723
+ const vals = days.map(d => session.activityDays[d]?.tokens ?? 0)
1724
+ const mx = Math.max(1, ...vals)
1725
+ let spark
1726
+ if (vals.length >= 3) {
1727
+ spark = vals.map((v, i) => h('i', {
1728
+ key: i,
1729
+ style: { height: `${Math.max(6, (v / mx) * 100)}%`, background: levelOf(session) },
1730
+ }))
1731
+ } else if (vals.length > 0) {
1732
+ spark = h('div', { className: 'aw-muted', key: 'one' },
1733
+ `${fmt(vals[vals.length - 1])} tok · ${days[days.length - 1]} · 仅 ${vals.length} 天数据`)
1734
+ } else {
1735
+ spark = h('div', { className: 'aw-muted', key: 'none' }, T.noDaily)
1736
+ }
1737
+ const partsTotal = session.parts
1738
+ ? PARTS.reduce((sum, [k]) => sum + (session.parts[k] ?? 0), 0) : 0
1739
+
1740
+ return h('section', { className: 'aw-mod' }, [
1741
+ h('div', { className: 'aw-mh', key: 'h' }, [
1742
+ h('h3', { key: 't' }, T.inspector),
1743
+ h('span', { key: 's', style: { color: levelOf(session) } }, levelText(session)),
1744
+ ]),
1745
+ h('div', { className: 'aw-insp', key: 'b' }, [
1746
+ h('div', { key: 't', className: 'aw-it' }, session.title || T.noTitle),
1747
+ h('div', { key: 'm', className: 'aw-im' }, [
1748
+ h('span', { key: 'p' }, session.project),
1749
+ h('span', { key: 'd' }, '·'),
1750
+ h('span', { key: 'o' }, session.origin === 'subagent' ? T.sub : T.main),
1751
+ h('span', { key: 'd2' }, '·'),
1752
+ h('span', { key: 'mo', title: session.model ?? '' }, modelLabel(session.model)),
1753
+ h('span', { key: 'd3' }, '·'),
1754
+ h('span', { key: 't2' }, relTime(session.updatedAt)),
1755
+ vals.length ? h('span', { key: 't3' },
1756
+ `· 近 ${vals.length} 天 ${fmt(vals.reduce((a, b) => a + b, 0))} tok`) : null,
1757
+ ].filter(Boolean)),
1758
+ h('div', { key: 'g', className: 'aw-ig' }, [
1759
+ h('div', { key: 'a', className: 'aw-kv' }, [
1760
+ h('div', { key: 'k', className: 'k' }, T.used),
1761
+ h('div', { key: 'v', className: 'v' }, fmt(session.total)),
1762
+ ]),
1763
+ h('div', { key: 'b', className: 'aw-kv' }, [
1764
+ h('div', { key: 'k', className: 'k' }, T.capacity),
1765
+ h('div', { key: 'v', className: 'v' }, fmt(session.contextWindow)),
1766
+ ]),
1767
+ h('div', { key: 'c', className: 'aw-kv', title: contextHint(session, th) }, [
1768
+ h('div', { key: 'k', className: 'k' }, T.usage),
1769
+ h('div', { key: 'v', className: 'v', style: { color: levelOf(session) } },
1770
+ pct(session.ratio)),
1771
+ ]),
1772
+ h('div', { key: 'd', className: 'aw-kv' }, [
1773
+ h('div', { key: 'k', className: 'k' }, T.turnsSteps),
1774
+ h('div', { key: 'v', className: 'v' },
1775
+ `${session.turns ?? '—'} / ${session.steps ?? '—'}`),
1776
+ ]),
1777
+ h('div', {
1778
+ key: 'e',
1779
+ className: 'aw-kv',
1780
+ title: session.costSource === 'totals'
1781
+ ? '按谷时价估算:没读到请求时间,仅供比较,不是账单金额'
1782
+ : session.costSource === 'log'
1783
+ ? '按 DeepSeek 官方价目表计价,峰谷按会话日志里的请求时间分桶'
1784
+ : '按 DeepSeek 官方价目表计价,峰时按 2× 计',
1785
+ }, [
1786
+ h('div', { key: 'k', className: 'k' }, T.cost),
1787
+ h('div', { key: 'v', className: 'v' },
1788
+ session.costSource === 'totals' && session.costCny != null
1789
+ ? `≈${cny(session.costCny)}`
1790
+ : cny(session.costCny)),
1791
+ ]),
1792
+ h('div', {
1793
+ key: 'f',
1794
+ className: 'aw-kv',
1795
+ title: session.usage
1796
+ ? `命中缓存的输入 token / 全部输入 token`
1797
+ + `\n${fmt(session.usage.cacheRead)} / `
1798
+ + `${fmt((session.usage.uncached ?? 0) + (session.usage.cacheRead ?? 0) + (session.usage.cacheWrite ?? 0))} tok`
1799
+ : '该会话还没有取到 token 用量',
1800
+ }, [
1801
+ h('div', { key: 'k', className: 'k' }, T.cacheHit),
1802
+ h('div', { key: 'v', className: 'v' }, pct(hitRateOf(session))),
1803
+ ]),
1804
+ ]),
1805
+ h('div', { key: 's2', className: 'aw-sec' }, T.parts),
1806
+ session.parts ? h('div', { key: 'pt' }, [
1807
+ h('div', { key: 'bar', className: 'aw-stack', style: { marginBottom: 6 } },
1808
+ PARTS.map(([k, , color]) => (session.parts[k]
1809
+ ? h('i', {
1810
+ key: k,
1811
+ style: {
1812
+ width: `${partsTotal ? (session.parts[k] / partsTotal) * 100 : 0}%`,
1813
+ background: color,
1814
+ },
1815
+ })
1816
+ : null)).filter(Boolean)),
1817
+ h('div', { key: 'lg', className: 'aw-comp' },
1818
+ PARTS.map(([k, label, color]) => h('div', { key: k }, [
1819
+ h('span', { key: 's', className: 'sw', style: { background: color } }),
1820
+ h('span', { key: 'k', className: 'k' }, label),
1821
+ h('span', { key: 'v', className: 'v' },
1822
+ partsTotal ? ((session.parts[k] / partsTotal) * 100).toFixed(0) + '%' : '—'),
1823
+ ]))),
1824
+ ]) : h('div', { key: 'np', className: 'aw-muted' }, T.noParts),
1825
+ ]),
1826
+ h('div', { className: 'aw-iact', key: 'act' },
1827
+ h('button', {
1828
+ className: 'aw-btn primary',
1829
+ onClick: () => onOpen(session.id),
1830
+ }, [h(Icon, { key: 'i', name: 'enter', size: 14 }), T.openNative])),
1831
+ ])
1832
+ }
1833
+
1834
+ /* ══════════════════ workspace: native panes ══════════════════ */
1835
+
1836
+ /** Zoom levels offered in each pane header. */
1837
+ const ZOOM_STEPS = [1, 0.85, 0.7, 0.55]
1838
+ /** Slider order: small on the left, 100% on the right. */
1839
+ const ZOOM_LADDER = [0.55, 0.7, 0.85, 1]
1840
+
1841
+ /**
1842
+ * One pane = one **native** conversation.
1843
+ *
1844
+ * The shipped `conversation.content` factory is hosted here, wrapped in the
1845
+ * `SessionProvider` the renderer hands our registration. That is the whole
1846
+ * reason the panel declares a session-scoped child slot: it is what makes
1847
+ * `standardKit()` inject `SessionProvider` + `renderFactorySlot`.
1848
+ *
1849
+ * Not an iframe: the desktop shell runs preload only in the main frame, so a
1850
+ * framed copy of the app never boots. Not a re-implementation either — this
1851
+ * is the same component the shipped Conversation panel renders, so tool
1852
+ * rows, approvals and Chat/Trajectory tabs come for free.
1853
+ *
1854
+ * Zoom renders the conversation at `1/zoom` of the pane and scales it back
1855
+ * down, so 70% shows ~1.4x more content at 70% size.
1856
+ */
1857
+ function NativePane({ session, kit, index, total, onClose, onOpenNative, th, flash }) {
1858
+ const ctx = React.useRef(window.__SESSION_MATRIX_CTX__).current
1859
+ const [reference, setReference] = React.useState(null)
1860
+ const [ready, setReady] = React.useState(false)
1861
+ const [retainError, setRetainError] = React.useState(null)
1862
+ // Zoom is per session, not global: a value set in one pane must not make
1863
+ // every newly opened pane start zoomed out.
1864
+ const [zoom, setZoom] = React.useState(() => {
1865
+ try {
1866
+ const v = Number(localStorage.getItem(`aw.zoom.${session.id}`))
1867
+ return ZOOM_STEPS.includes(v) ? v : 1
1868
+ } catch { return 1 }
1869
+ })
1870
+ const id = session.id
1871
+
1872
+ // Retain for exactly as long as this pane shows the session. The signal is
1873
+ // the backstop for unmounts that skip cleanup (fast refresh, error
1874
+ // boundary); release() runs in the cleanup path either way.
1875
+ React.useEffect(() => {
1876
+ if (!id || typeof ctx?.sessions?.retain !== 'function') return undefined
1877
+ const controller = new AbortController()
1878
+ let ref = null
1879
+ try {
1880
+ ref = ctx.sessions.retain(id, { source: 'dsh-session-matrix', signal: controller.signal })
1881
+ setRetainError(null)
1882
+ // The reference is a handle, not an opened session: rendering the
1883
+ // factory before `ready` settles makes the conversation paint its
1884
+ // "会话不可用" state, which then sticks.
1885
+ Promise.resolve(ref.ready).then(() => {
1886
+ if (!controller.signal.aborted) {
1887
+ setReference(ref)
1888
+ setReady(true)
1889
+ }
1890
+ }, error => {
1891
+ if (!controller.signal.aborted) setRetainError(error)
1892
+ })
1893
+ } catch (error) {
1894
+ setRetainError(error)
1895
+ }
1896
+ return () => {
1897
+ controller.abort()
1898
+ try { ref?.release?.() } catch { /* already released */ }
1899
+ setReference(null)
1900
+ setReady(false)
1901
+ }
1902
+ }, [id, ctx])
1903
+
1904
+ const applyZoom = next => {
1905
+ setZoom(next)
1906
+ try { localStorage.setItem(`aw.zoom.${id}`, String(next)) } catch { /* private mode */ }
1907
+ }
1908
+
1909
+ const { SessionProvider, renderFactorySlot } = kit ?? {}
1910
+ // Verified against the shipped panel: it derives the factory phase from
1911
+ // shellPhase, openState and the session-list blank flag.
1912
+ //
1913
+ // settling = shellPhase === blank && openState === loading
1914
+ // hero = blank === true || (shellPhase === blank && openState === open)
1915
+ //
1916
+ // The pane slot injects neither a session id nor the conversation store,
1917
+ // and the one status hook it does inject (useSessionStatus) carries run
1918
+ // state only: { running, pendingInteraction, completionUnread }. There is
1919
+ // no settling/hero signal to read here. Every session this panel lists is
1920
+ // already open and non-blank, which is exactly the active case, so the
1921
+ // constant is correct rather than lazy.
1922
+ const phase = 'active'
1923
+
1924
+ const scaled = zoom < 0.999
1925
+ const canRender = typeof SessionProvider === 'function' && typeof renderFactorySlot === 'function'
1926
+
1927
+ const risk = session.risk === 'crit' ? 'crit' : session.risk === 'warn' ? 'warn' : null
1928
+ const zoomIdx = Math.max(0, ZOOM_LADDER.indexOf(zoom))
1929
+
1930
+ return h('div', {
1931
+ className: 'aw-pane',
1932
+ 'data-pane': id,
1933
+ 'data-risk': risk ?? 'ok',
1934
+ 'data-flash': flash ? '1' : undefined,
1935
+ 'data-phase': phase,
1936
+ }, [
1937
+ h('div', { className: `aw-pane-h${risk ? ` ${risk}` : ''}`, key: 'h' }, [
1938
+ h('span', { key: 'dot', className: 'aw-dot', style: { background: levelOf(session) } }),
1939
+ h('span', { key: 't', className: 't', title: session.title }, session.title || T.noTitle),
1940
+ // A subagent session cannot be prompted directly, so its composer
1941
+ // reports "会话不可用". Say so up front instead of letting it look
1942
+ // like a broken pane.
1943
+ session.origin === 'subagent' ? h('span', {
1944
+ key: 'ro',
1945
+ className: 'aw-ro',
1946
+ title: '子代理会话:可以查看,但不能在这里直接发消息',
1947
+ }, '只读 · 子代理') : null,
1948
+ // Zoom is pinned to the optical centre of the header, on purpose:
1949
+ // while it sat next to the context figure it read as "the slider that
1950
+ // controls context". It only changes the display size.
1951
+ h('span', {
1952
+ key: 'zoom',
1953
+ className: 'aw-zoom',
1954
+ title: `内容缩放 ${Math.round(zoom * 100)}%(只改变显示大小,不影响会话)`,
1955
+ }, [
1956
+ h('span', { key: 'k', className: 'aw-zoom-k' }, T.zoom),
1957
+ h('input', {
1958
+ key: 'r',
1959
+ type: 'range',
1960
+ className: 'aw-zoom-range',
1961
+ min: 0,
1962
+ max: ZOOM_LADDER.length - 1,
1963
+ step: 1,
1964
+ value: zoomIdx,
1965
+ 'aria-label': `内容缩放,当前 ${Math.round(zoom * 100)}%`,
1966
+ onChange: ev => applyZoom(ZOOM_LADDER[Number(ev.target.value)] ?? 1),
1967
+ }),
1968
+ h('span', { key: 'v', className: 'aw-zoom-val' }, `${Math.round(zoom * 100)}%`),
1969
+ ]),
1970
+ h('span', { key: 'sp', className: 'aw-grow' }),
1971
+ // data-tip instead of title: the native tooltip waits ~1s, and this is
1972
+ // the number people hover most often.
1973
+ h('span', { key: 'm', className: 'ctx tip-r', 'data-tip': contextHint(session, th) }, [
1974
+ h('span', { key: 'k', className: 'ctxk' }, '上下文占用'),
1975
+ h('span', { key: 'v', className: 'ctxv' }, pct(session.ratio)),
1976
+ ]),
1977
+ risk ? h('span', {
1978
+ key: 'rk',
1979
+ className: `aw-risk ${risk} tip-r`,
1980
+ 'data-tip': risk === 'crit'
1981
+ ? `已到预警线(压缩点 × ${Math.round((th?.criticalFactor ?? DEFAULT_FACTORS.criticalFactor) * 100)}%):继续对话很可能触发自动压缩`
1982
+ : `接近压缩点(压缩点 × ${Math.round((th?.warnFactor ?? DEFAULT_FACTORS.warnFactor) * 100)}%):再增长一段就会触发自动压缩`,
1983
+ }, risk === 'crit' ? T.levelCrit : T.levelWarn) : null,
1984
+ h('button', {
1985
+ key: 'open',
1986
+ className: 'aw-btn ghost',
1987
+ style: { height: 22, padding: '0 8px' },
1988
+ title: T.openNative,
1989
+ onClick: () => onOpenNative(id),
1990
+ }, [h(Icon, { key: 'i', name: 'enter', size: 13 }), T.enter]),
1991
+ total > 1 ? h('button', {
1992
+ key: 'x',
1993
+ className: 'x',
1994
+ title: T.closePane,
1995
+ onClick: () => onClose(index),
1996
+ }, h(Icon, { name: 'close', size: 13 })) : null,
1997
+ ].filter(Boolean)),
1998
+
1999
+ h('div', { key: 'b', className: 'aw-pane-b' }, [
2000
+ !canRender
2001
+ ? h('div', { key: 'nc', className: 'aw-pane-fallback' }, [
2002
+ h('div', { key: 'a' }, '当前 DSH 版本没有向插件面板注入会话渲染入口'),
2003
+ h('div', { key: 'b', className: 'sub' },
2004
+ 'fallback 生效:可以点「进入」在原生界面查看该会话'),
2005
+ ])
2006
+ : retainError
2007
+ ? h('div', { key: 're', className: 'aw-pane-fallback' },
2008
+ `会话引用失败:${retainError.message ?? retainError}`)
2009
+ : reference && ready
2010
+ ? h('div', {
2011
+ key: 'box',
2012
+ className: 'aw-zoombox',
2013
+ 'data-zoom': zoom,
2014
+ }, h('div', {
2015
+ className: 'aw-zoom-inner',
2016
+ style: scaled ? {
2017
+ width: `${(100 / zoom).toFixed(2)}%`,
2018
+ height: `${(100 / zoom).toFixed(2)}%`,
2019
+ transform: `scale(${zoom})`,
2020
+ transformOrigin: '0 0',
2021
+ } : { width: '100%', height: '100%' },
2022
+ }, h(SessionProvider, { session: reference },
2023
+ h('div', { className: 'aw-native', 'data-native': id },
2024
+ renderFactorySlot('conversation.content', {
2025
+ variant: 'embedded',
2026
+ phase,
2027
+ hero: phase === 'hero',
2028
+ })))))
2029
+ : h('div', { key: 'w', className: 'aw-pane-fallback' }, '正在接管会话…'),
2030
+ ]),
2031
+ ])
2032
+ }
2033
+
2034
+ const MAX_PANES = 4
2035
+
2036
+ function WorkspaceView({
2037
+ sessions, projects, filter, setFilter, panes, setPanes, onOpenNative, railW, onRailW, kit, th, flashId,
2038
+ }) {
2039
+ const openIds = new Set(panes.filter(Boolean))
2040
+ const full = panes.length >= MAX_PANES
2041
+
2042
+ // Split ratios live in (0,1); the grid turns them into `fr` tracks so both
2043
+ // sides stay proportional when the window or the rail resizes.
2044
+ const [col, setCol] = React.useState(() => {
2045
+ try {
2046
+ const v = Number(localStorage.getItem('aw.splitCol'))
2047
+ return v > 0.1 && v < 0.9 ? v : 0.5
2048
+ } catch { return 0.5 }
2049
+ })
2050
+ const [rowRatio, setRowRatio] = React.useState(() => {
2051
+ try {
2052
+ const v = Number(localStorage.getItem('aw.splitRow'))
2053
+ return v > 0.1 && v < 0.9 ? v : 0.5
2054
+ } catch { return 0.5 }
2055
+ })
2056
+ const gridRef = React.useRef(null)
2057
+
2058
+ /** Drag one axis; ratio is measured against the grid box, clamped. */
2059
+ const startDrag = axis => ev => {
2060
+ ev.preventDefault()
2061
+ const box = gridRef.current
2062
+ if (!box) return
2063
+ const rect = box.getBoundingClientRect()
2064
+ const move = e => {
2065
+ const raw = axis === 'col'
2066
+ ? (e.clientX - rect.left) / rect.width
2067
+ : (e.clientY - rect.top) / rect.height
2068
+ const next = Math.min(0.85, Math.max(0.15, raw))
2069
+ if (axis === 'col') {
2070
+ setCol(next)
2071
+ try { localStorage.setItem('aw.splitCol', String(next)) } catch { /* ignore */ }
2072
+ } else {
2073
+ setRowRatio(next)
2074
+ try { localStorage.setItem('aw.splitRow', String(next)) } catch { /* ignore */ }
2075
+ }
2076
+ }
2077
+ const up = () => {
2078
+ window.removeEventListener('pointermove', move)
2079
+ window.removeEventListener('pointerup', up)
2080
+ }
2081
+ window.addEventListener('pointermove', move)
2082
+ window.addEventListener('pointerup', up, { once: true })
2083
+ }
2084
+
2085
+ // `twoCols` adds the vertical divider, `twoRows` the horizontal one, so
2086
+ // 3–4 panes are a grid and 1–2 panes a single row.
2087
+ const twoCols = panes.length > 1
2088
+ const twoRows = panes.length > 2
2089
+ // 3 panes: the third spans the full bottom row. 4 panes: a plain 2x2.
2090
+ const areaOf = i => {
2091
+ if (i === 0) return '1 / 1 / 2 / 2'
2092
+ if (i === 1) return '1 / 3 / 2 / 4'
2093
+ if (i === 2) return panes.length === 3 ? '3 / 1 / 4 / 4' : '3 / 1 / 4 / 2'
2094
+ return '3 / 3 / 4 / 4'
2095
+ }
2096
+
2097
+ // Subagents are folded under their nearest main session by default: a
2098
+ // flat list of 42 rows (24 of them children) buries the sessions you
2099
+ // actually start. Expanded state is per main session.
2100
+ const byId = new Map(sessions.map(s => [s.id, s]))
2101
+ const mainIds = new Set(sessions.filter(s => s.origin !== 'subagent').map(s => s.id))
2102
+ const ownerCache = new Map()
2103
+ const ownerOf = sub => {
2104
+ if (ownerCache.has(sub.id)) return ownerCache.get(sub.id)
2105
+ let cur = sub.parentId
2106
+ let owner = null
2107
+ for (let guard = 0; cur && guard < 24; guard += 1) {
2108
+ if (mainIds.has(cur)) { owner = cur; break }
2109
+ cur = byId.get(cur)?.parentId ?? null
2110
+ }
2111
+ ownerCache.set(sub.id, owner)
2112
+ return owner
2113
+ }
2114
+
2115
+ const kidsOf = new Map()
2116
+ const groups = []
2117
+ const byProject = new Map()
2118
+ for (const s of sessions) {
2119
+ const nested = s.origin === 'subagent' && ownerOf(s)
2120
+ if (nested) {
2121
+ const owner = ownerOf(s)
2122
+ if (!kidsOf.has(owner)) kidsOf.set(owner, [])
2123
+ kidsOf.get(owner).push(s)
2124
+ continue
2125
+ }
2126
+ let g = byProject.get(s.project)
2127
+ if (!g) { g = { name: s.project, rows: [] }; byProject.set(s.project, g); groups.push(g) }
2128
+ g.rows.push(s)
2129
+ }
2130
+ for (const arr of kidsOf.values()) arr.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
2131
+
2132
+ // Which main sessions have their subagents unfolded. Persisted, because
2133
+ // a collapsed tree that re-collapses on every visit is a small annoyance
2134
+ // that adds up when you check the same session ten times an hour.
2135
+ //
2136
+ // Sort mode sits next to it: a preference, not a filter — it survives
2137
+ // reloads and never hides a session.
2138
+ const [sort, setSort] = usePersisted('aw.sort', 'ratio',
2139
+ v => v === 'ratio' || v === 'recent' || v === 'cost')
2140
+ const [expandedIds, setExpandedIds] = usePersisted(
2141
+ 'aw.expanded', [],
2142
+ v => Array.isArray(v) && v.every(x => typeof x === 'string'),
2143
+ )
2144
+
2145
+ // One comparator drives both levels, so a subagent list is never in a
2146
+ // different order than the list it sits in.
2147
+ const order = {
2148
+ ratio: (a, b) => (b.ratio ?? -1) - (a.ratio ?? -1),
2149
+ recent: (a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0),
2150
+ cost: (a, b) => (b.costCny ?? -1) - (a.costCny ?? -1),
2151
+ }[sort]
2152
+ for (const g of groups) g.rows.sort(order)
2153
+ for (const arr of kidsOf.values()) arr.sort(order)
2154
+
2155
+ // Panes are persisted by id, so a session deleted in another window
2156
+ // leaves a slot that can never resolve and sits on "pick a session"
2157
+ // forever. Clear those ids once the list has loaded; never prune while
2158
+ // the list is empty (that is a failed poll, not an empty workspace).
2159
+ React.useEffect(() => {
2160
+ if (!sessions.length) return
2161
+ const known = new Set(sessions.map(s => s.id))
2162
+ setPanes(prev => {
2163
+ const next = prev.map(v => (v && !known.has(v) ? null : v))
2164
+ return next.some((v, i) => v !== prev[i]) ? next : prev
2165
+ })
2166
+ }, [sessions, setPanes])
2167
+ const expanded = React.useMemo(() => new Set(expandedIds), [expandedIds])
2168
+ // A subagent opened in a pane must be visible even while collapsed.
2169
+ const forced = new Set()
2170
+ for (const id of openIds) {
2171
+ const s = byId.get(id)
2172
+ if (s && s.origin === 'subagent') {
2173
+ const owner = ownerOf(s)
2174
+ if (owner) forced.add(owner)
2175
+ }
2176
+ }
2177
+ const isExpanded = id => expanded.has(id) || forced.has(id)
2178
+ const toggle = id => setExpandedIds(prev => (prev.includes(id)
2179
+ ? prev.filter(x => x !== id)
2180
+ : [...prev, id]))
2181
+
2182
+ // Drag the divider: pointer capture keeps the drag alive outside the
2183
+ // grip, and the width is persisted so the layout survives a reload.
2184
+ const dragRef = React.useRef(null)
2185
+ const [dragging, setDragging] = React.useState(false)
2186
+
2187
+ const onPointerDown = ev => {
2188
+ ev.preventDefault()
2189
+ dragRef.current = { startX: ev.clientX, startW: railW }
2190
+ setDragging(true)
2191
+ ev.currentTarget.setPointerCapture?.(ev.pointerId)
2192
+ }
2193
+ const onPointerMove = ev => {
2194
+ const d = dragRef.current
2195
+ if (!d) return
2196
+ const next = Math.max(200, Math.min(560, d.startW + (ev.clientX - d.startX)))
2197
+ onRailW(next)
2198
+ }
2199
+ const onPointerUp = ev => {
2200
+ if (!dragRef.current) return
2201
+ dragRef.current = null
2202
+ setDragging(false)
2203
+ ev.currentTarget.releasePointerCapture?.(ev.pointerId)
2204
+ }
2205
+
2206
+ return h('div', { className: 'aw-ws', style: { '--aw-rail': `${railW}px` } }, [
2207
+ h('aside', { className: 'aw-rail', key: 'rail' }, [
2208
+ h('div', { className: 'aw-rail-h', key: 'h' }, [
2209
+ h('div', { className: 'aw-field', key: 's' }, [
2210
+ h(Icon, { key: 'i', name: 'search', size: 14 }),
2211
+ h('input', {
2212
+ key: 'in',
2213
+ value: filter.query,
2214
+ placeholder: T.search,
2215
+ onChange: ev => setFilter({ ...filter, query: ev.target.value }),
2216
+ }),
2217
+ h('button', {
2218
+ key: 'so',
2219
+ className: 'aw-sort',
2220
+ type: 'button',
2221
+ title: `排序:${sortLabel(sort)}(点击换一种)`,
2222
+ onClick: () => {
2223
+ const at = SORT.findIndex(x => x[0] === sort)
2224
+ setSort(SORT[(at + 1) % SORT.length][0])
2225
+ },
2226
+ }, sortLabel(sort)),
2227
+ ]),
2228
+ h('div', { className: 'aw-chips', key: 'c' }, [
2229
+ h('button', {
2230
+ key: '__all',
2231
+ className: 'aw-chip',
2232
+ 'aria-pressed': filter.project === '__all',
2233
+ onClick: () => setFilter({ ...filter, project: '__all' }),
2234
+ }, [h('span', { key: 't' }, T.all), h('span', { key: 'n', className: 'n' }, sessions.length)]),
2235
+ projects.map(p => h('button', {
2236
+ key: p.title || '__ungrouped',
2237
+ className: 'aw-chip',
2238
+ title: p.title ? undefined : '这些会话的目录不属于任何工作空间',
2239
+ 'aria-pressed': filter.project === p.title,
2240
+ onClick: () => setFilter({ ...filter, project: p.title }),
2241
+ }, [h('span', { key: 't' }, projName(p.title)),
2242
+ h('span', { key: 'n', className: 'n' }, p.count)])),
2243
+ ]),
2244
+ ]),
2245
+ h('div', { className: 'aw-rail-list', key: 'l' },
2246
+ groups.length ? groups.map(g => h('div', { key: g.name }, [
2247
+ h('div', { key: 'g', className: 'aw-rg' }, [
2248
+ h('span', { key: 't' }, projName(g.name)),
2249
+ h('span', { key: 'l', className: 'line' }),
2250
+ h('span', { key: 'c' }, g.rows.length),
2251
+ ]),
2252
+ g.rows.map(s => {
2253
+ const kids = kidsOf.get(s.id) ?? []
2254
+ const open = isExpanded(s.id)
2255
+ const row = (item, depth) => h('div', {
2256
+ key: item.id,
2257
+ className: `aw-ri${depth ? ' aw-ri-sub' : ''}`,
2258
+ 'data-id': item.id,
2259
+ role: 'button',
2260
+ tabIndex: 0,
2261
+ 'aria-current': openIds.has(item.id),
2262
+ title: item.title,
2263
+ onKeyDown: ev => {
2264
+ if (ev.key !== 'Enter' && ev.key !== ' ') return
2265
+ ev.preventDefault()
2266
+ ev.currentTarget.click()
2267
+ },
2268
+ onClick: () => {
2269
+ if (openIds.has(item.id)) return
2270
+ setPanes(prev => {
2271
+ const idx = prev.findIndex(p => p === null || p === undefined)
2272
+ const next = [...prev]
2273
+ if (idx >= 0) next[idx] = item.id
2274
+ else next[next.length - 1] = item.id
2275
+ return next
2276
+ })
2277
+ },
2278
+ }, [
2279
+ h('span', { key: 'd', className: 'st', style: { background: levelOf(item) } }),
2280
+ h('span', { key: 'b', className: 'body' }, [
2281
+ h('span', { key: 'l1', className: 'l1' }, [
2282
+ item.origin === 'subagent' ? h(Icon, { key: 'i', name: 'sub', size: 11 }) : null,
2283
+ h('span', { key: 't', className: 't' }, item.title),
2284
+ ].filter(Boolean)),
2285
+ h('span', { key: 'l2', className: 'l2' }, [
2286
+ h('span', { key: 'm', style: { flex: '0 0 auto' } },
2287
+ modelLabel(item.model)),
2288
+ h('span', { key: 'bar', className: 'bar' },
2289
+ h('i', {
2290
+ style: {
2291
+ width: `${Math.min(100, (item.ratio ?? 0) * 100)}%`,
2292
+ background: levelOf(item),
2293
+ },
2294
+ })),
2295
+ ]),
2296
+ ]),
2297
+ h('span', { key: 'p', className: 'pc' }, pct(item.ratio)),
2298
+ ])
2299
+
2300
+ return h('div', { key: s.id, className: 'aw-rnode' }, [
2301
+ row(s, 0),
2302
+ kids.length ? h('button', {
2303
+ key: 'tg',
2304
+ className: 'aw-rtoggle',
2305
+ 'aria-expanded': open,
2306
+ title: open ? '折叠子代理' : '展开子代理',
2307
+ onClick: ev => { ev.stopPropagation(); toggle(s.id) },
2308
+ }, [
2309
+ h('span', { key: 'c', className: `caret${open ? ' open' : ''}` }),
2310
+ `${kids.length} 个子代理`,
2311
+ ]) : null,
2312
+ open ? kids.map(k => row(k, 1)) : null,
2313
+ ].filter(Boolean))
2314
+ }),
2315
+ ])) : h('div', { key: 'e', className: 'aw-empty' }, T.noSession)),
2316
+ ]),
2317
+
2318
+ h('button', {
2319
+ key: 'grip',
2320
+ className: 'aw-grip',
2321
+ 'data-drag': dragging ? '' : undefined,
2322
+ 'aria-label': '调整列表宽度',
2323
+ title: '拖动调整列表宽度',
2324
+ onPointerDown,
2325
+ onPointerMove,
2326
+ onPointerUp,
2327
+ onPointerCancel: onPointerUp,
2328
+ }),
2329
+
2330
+ h('div', { className: 'aw-pane-wrap', key: 'wrap' }, [
2331
+ h('div', { className: 'aw-toolbar', key: 'tb' }, [
2332
+ h('span', { key: 'l', className: 'aw-muted' },
2333
+ `${panes.filter(Boolean).length} / ${panes.length} 栏`),
2334
+ h('div', { className: 'aw-grow', key: 'g' }),
2335
+ h('button', {
2336
+ key: 'add',
2337
+ className: 'aw-btn',
2338
+ disabled: full,
2339
+ title: full ? `最多 ${MAX_PANES} 栏` : '增加一栏',
2340
+ onClick: () => setPanes(prev => (prev.length >= MAX_PANES ? prev : [...prev, null])),
2341
+ }, [h(Icon, { key: 'i', name: 'plus', size: 14 }), T.newPane]),
2342
+ panes.length > 1 ? h('button', {
2343
+ key: 'rm',
2344
+ className: 'aw-btn ghost',
2345
+ title: '减少一栏',
2346
+ onClick: () => setPanes(prev => (prev.length > 1 ? prev.slice(0, -1) : prev)),
2347
+ }, h(Icon, { key: 'i', name: 'single', size: 14 })) : null,
2348
+ ].filter(Boolean)),
2349
+ h('div', {
2350
+ className: 'aw-panes',
2351
+ key: 'panes',
2352
+ ref: gridRef,
2353
+ 'data-n': panes.length,
2354
+ style: {
2355
+ gridTemplateColumns: twoCols ? `${col}fr 5px ${1 - col}fr` : '1fr',
2356
+ gridTemplateRows: twoRows ? `${rowRatio}fr 5px ${1 - rowRatio}fr` : '1fr',
2357
+ },
2358
+ }, [
2359
+ ...panes.map((id, i) => {
2360
+ const session = sessions.find(s => s.id === id) ?? null
2361
+ return h('div', {
2362
+ key: `slot${i}`,
2363
+ className: 'aw-pane-slot',
2364
+ style: { gridArea: areaOf(i) },
2365
+ }, session
2366
+ ? h(NativePane, {
2367
+ // Keyed by session, not by slot: retain/release follows the
2368
+ // session, and switching the session in a pane must rebind.
2369
+ key: id,
2370
+ session,
2371
+ kit,
2372
+ th,
2373
+ flash: flashId === id,
2374
+ index: i,
2375
+ total: panes.length,
2376
+ onOpenNative,
2377
+ onClose: idx => setPanes(prev => {
2378
+ const next = prev.filter((_, j) => j !== idx)
2379
+ return next.length ? next : [null]
2380
+ }),
2381
+ })
2382
+ : h('div', { className: 'aw-pane' }, [
2383
+ h('div', { className: 'aw-veil', key: 'v' }, [
2384
+ h(Icon, { key: 'i', name: 'chat', size: 22 }),
2385
+ h('div', { key: 't', className: 'big' }, T.pickSession),
2386
+ h('div', { key: 'h' }, T.pickSessionHint),
2387
+ ]),
2388
+ ]))
2389
+ }),
2390
+ twoCols ? h('div', {
2391
+ key: 'vsplit',
2392
+ className: 'aw-split',
2393
+ 'data-split': 'col',
2394
+ title: '拖动调整左右宽度',
2395
+ onPointerDown: startDrag('col'),
2396
+ style: { gridColumn: '2', gridRow: '1 / -1' },
2397
+ }) : null,
2398
+ twoRows ? h('div', {
2399
+ key: 'hsplit',
2400
+ className: 'aw-split',
2401
+ 'data-split': 'row',
2402
+ title: '拖动调整上下高度',
2403
+ onPointerDown: startDrag('row'),
2404
+ style: { gridRow: '2', gridColumn: '1 / -1' },
2405
+ }) : null,
2406
+ ]),
2407
+ ]),
2408
+ ])
2409
+ }
2410
+
2411
+ /* ══════════════════ handoff ══════════════════ */
2412
+
2413
+ /** File-name stamp for a handoff: 20261117-0145 (local time). */
2414
+ function handoffStamp(when) {
2415
+ const pad = n => String(n).padStart(2, '0')
2416
+ return `${when.getFullYear()}${pad(when.getMonth() + 1)}${pad(when.getDate())}`
2417
+ + `-${pad(when.getHours())}${pad(when.getMinutes())}`
2418
+ }
2419
+
2420
+ /**
2421
+ * How far this session is from the point where DSH rewrites its history.
2422
+ * @param session - wire DTO.
2423
+ * @returns one line of plain text.
2424
+ */
2425
+ function distanceText(session) {
2426
+ const point = compactPoint(session)
2427
+ if (!point || session.ratio == null) return '缺少上下文数据'
2428
+ const left = Math.round((point.ratio - session.ratio) * session.contextWindow)
2429
+ return left >= 0
2430
+ ? `距压缩点 ${fmt(left)} tokens`
2431
+ : `已越过压缩点 ${fmt(-left)} tokens`
2432
+ }
2433
+
2434
+ /**
2435
+ * Copy text with two fallbacks.
2436
+ *
2437
+ * A clipboard write can be refused by the shell's permission handler, and a
2438
+ * button that appears to do nothing is worse than no button at all. The last
2439
+ * resort leaves the text selected and tells the user to press Ctrl+C.
2440
+ * @param text - what to put on the clipboard.
2441
+ * @returns `'clipboard' | 'exec' | 'manual'`.
2442
+ */
2443
+ async function copyToClipboard(text) {
2444
+ try {
2445
+ if (navigator.clipboard?.writeText) {
2446
+ await navigator.clipboard.writeText(text)
2447
+ return 'clipboard'
2448
+ }
2449
+ } catch { /* fall through */ }
2450
+ try {
2451
+ const area = document.createElement('textarea')
2452
+ area.value = text
2453
+ area.setAttribute('readonly', '')
2454
+ area.style.cssText = 'position:fixed;top:-1000px;left:-1000px;opacity:0'
2455
+ document.body.appendChild(area)
2456
+ area.select()
2457
+ const ok = document.execCommand?.('copy')
2458
+ document.body.removeChild(area)
2459
+ if (ok) return 'exec'
2460
+ } catch { /* fall through */ }
2461
+ return 'manual'
2462
+ }
2463
+
2464
+ /**
2465
+ * The handoff dialog: why, how, which session, and the prompt itself.
2466
+ *
2467
+ * Deliberately does nothing but copy. It never sends a message, never opens
2468
+ * a session, never touches a file — the old agent does the work after the
2469
+ * user pastes the prompt, and the user stays in control of every step.
2470
+ * @param props - sessions, preset id, pane ids, thresholds, close/copied.
2471
+ */
2472
+ /**
2473
+ * Last line of defence.
2474
+ *
2475
+ * A throw inside one component took the whole main slot down with
2476
+ * `SlotAssemblyError` — the user saw a blank area and no way back. A
2477
+ * boundary turns that into a small retry card; the rest of the app keeps
2478
+ * running.
2479
+ */
2480
+ class Boundary extends React.Component {
2481
+ constructor(props) {
2482
+ super(props)
2483
+ this.state = { error: null }
2484
+ }
2485
+
2486
+ static getDerivedStateFromError(error) { return { error } }
2487
+
2488
+ componentDidCatch(error) { console.error('dsh-session-matrix: render failed', error) }
2489
+
2490
+ render() {
2491
+ if (!this.state.error) return this.props.children
2492
+ return h('div', { className: 'aw-err', key: 'b', style: { margin: 16 } }, [
2493
+ h('div', { key: 'a' }, '这一块渲染失败了,其他面板不受影响'),
2494
+ h('code', { key: 'b' }, String(this.state.error?.message ?? this.state.error)),
2495
+ h('div', { key: 'c', className: 'row' }, [
2496
+ h('button', {
2497
+ key: 'r',
2498
+ className: 'aw-btn',
2499
+ type: 'button',
2500
+ onClick: () => this.setState({ error: null }),
2501
+ }, '重试'),
2502
+ ]),
2503
+ ])
2504
+ }
2505
+ }
2506
+
2507
+ function HandoffModal({ sessions, preset, paneIds, th, onClose, onCopied }) {
2508
+ const ranked = React.useMemo(
2509
+ () => [...sessions].sort((a, b) => (b.ratio ?? -1) - (a.ratio ?? -1)),
2510
+ [sessions],
2511
+ )
2512
+ const top = ranked.slice(0, 3)
2513
+ const [targetId, setTargetId] = React.useState(() => preset || top[0]?.id || null)
2514
+ const [raw, setRaw] = React.useState(null)
2515
+ const [meta, setMeta] = React.useState(null)
2516
+ const [error, setError] = React.useState(null)
2517
+ const [text, setText] = React.useState('')
2518
+ const [hint, setHint] = React.useState(null)
2519
+ const [busy, setBusy] = React.useState(false)
2520
+ const edited = React.useRef(false)
2521
+ const areaRef = React.useRef(null)
2522
+ const target = sessions.find(s => s.id === targetId) ?? null
2523
+ const mark = target ? compactPoint(target) : null
2524
+ const warnAt = mark ? mark.ratio * th.warnFactor : null
2525
+ const critAt = mark ? mark.ratio * th.criticalFactor : null
2526
+
2527
+ // Fetch at open time, so an edited prompt file takes effect without a
2528
+ // rebuild of the browser half.
2529
+ React.useEffect(() => {
2530
+ let alive = true
2531
+ fetch('/api/session-matrix/handoff', { credentials: 'same-origin' })
2532
+ .then(res => (res.ok ? res.json() : Promise.reject(new Error(`HTTP ${res.status}`))))
2533
+ .then(json => {
2534
+ if (!alive) return
2535
+ setRaw(json.text)
2536
+ setMeta(json)
2537
+ })
2538
+ .catch(err => { if (alive) setError(String(err?.message ?? err)) })
2539
+ return () => { alive = false }
2540
+ }, [])
2541
+
2542
+ const rendered = React.useMemo(() => {
2543
+ if (!raw) return ''
2544
+ const when = new Date()
2545
+ return raw
2546
+ .replaceAll('{{SESSION_TITLE}}', target?.title ?? '')
2547
+ .replaceAll('{{HANDOFF_ID}}', handoffStamp(when))
2548
+ .replaceAll('{{DATE}}', when.toLocaleString('zh-CN', { hour12: false }))
2549
+ }, [raw, target])
2550
+
2551
+ React.useEffect(() => {
2552
+ edited.current = false
2553
+ setText(rendered)
2554
+ }, [rendered])
2555
+
2556
+ React.useEffect(() => {
2557
+ const onKey = ev => { if (ev.key === 'Escape') onClose() }
2558
+ window.addEventListener('keydown', onKey)
2559
+ return () => window.removeEventListener('keydown', onKey)
2560
+ }, [onClose])
2561
+
2562
+ const commit = async () => {
2563
+ if (busy || !text.trim()) return
2564
+ setBusy(true)
2565
+ const how = await copyToClipboard(text)
2566
+ setBusy(false)
2567
+ if (how === 'manual') {
2568
+ setHint('剪贴板不可用:文本已全选,按 Ctrl+C 复制')
2569
+ const area = areaRef.current
2570
+ if (area) { area.focus(); area.select() }
2571
+ return
2572
+ }
2573
+ onCopied(targetId)
2574
+ }
2575
+
2576
+ const card = s => {
2577
+ const point = compactPoint(s)
2578
+ const risk = s.risk === 'crit' ? 'var(--dsw-alias-state-error-primary)'
2579
+ : s.risk === 'warn' ? 'var(--dsw-alias-state-warn-primary)'
2580
+ : 'var(--dsw-alias-label-tertiary)'
2581
+ const used = Math.min(100, (s.ratio ?? 0) * 100)
2582
+ const at = point ? Math.min(100, point.ratio * 100) : null
2583
+ return h('button', {
2584
+ key: s.id,
2585
+ className: 'aw-hcard',
2586
+ type: 'button',
2587
+ 'aria-pressed': s.id === targetId,
2588
+ title: contextHint(s, th),
2589
+ onClick: () => setTargetId(s.id),
2590
+ }, [
2591
+ h('span', { key: 'h', className: 'aw-hcard-h' }, [
2592
+ h('span', { key: 't', className: 't' }, s.title || T.noTitle),
2593
+ paneIds.includes(s.id) ? h('span', { key: 'g', className: 'tag' }, '已载入') : null,
2594
+ ].filter(Boolean)),
2595
+ // One bar, two facts: how full it is, and where DSH would compact.
2596
+ h('span', { key: 'bar', className: 'aw-hcard-bar' }, [
2597
+ h('i', { key: 'f', style: { width: `${used}%`, background: risk } }),
2598
+ at == null ? null : h('em', { key: 't', style: { left: `${at}%` } }),
2599
+ ].filter(Boolean)),
2600
+ h('span', { key: 'r', className: 'aw-hcard-r' }, [
2601
+ h('span', { key: 'u', style: { color: risk } }, `已用 ${pct(s.ratio)}`),
2602
+ h('span', { key: 'c' }, point ? `压缩点 ${pct(point.ratio)}` : '压缩点未知'),
2603
+ ]),
2604
+ h('span', { key: 'd', className: 'd' }, distanceText(s)),
2605
+ ])
2606
+ }
2607
+
2608
+ return h('div', {
2609
+ className: 'aw-modal',
2610
+ role: 'dialog',
2611
+ 'aria-modal': 'true',
2612
+ 'aria-label': '通用交接提示词',
2613
+ onMouseDown: ev => { if (ev.target === ev.currentTarget) onClose() },
2614
+ }, h('div', { className: 'aw-modal-c' }, [
2615
+ h('div', { className: 'aw-modal-h', key: 'h' }, [
2616
+ h(Icon, { key: 'i', name: 'handoff', size: 15 }),
2617
+ h('h2', { key: 't' }, T.handoffTitle),
2618
+ meta ? h('span', { key: 'v', className: 'aw-ver' }, `协议 ${meta.version} · ${meta.hash}`) : null,
2619
+ h('button', {
2620
+ key: 'x', className: 'x', type: 'button', title: '关闭', onClick: onClose,
2621
+ }, h(Icon, { name: 'close', size: 13 })),
2622
+ ]),
2623
+ h('div', { className: 'aw-modal-b', key: 'b' }, [
2624
+ h('div', { className: 'aw-modal-l', key: 'l' }, [
2625
+ h('p', { className: 'aw-hsec', key: 'w1' }, T.whyTitle),
2626
+ h('div', { className: 'aw-hp', key: 'w2' }, [
2627
+ h('div', { key: 'a' },
2628
+ '上下文是这个会话里模型能看到的全部内容——你说的话、它的回复、读过的文件、跑过的命令。'
2629
+ + '当前模型上限约 100 万 token。'),
2630
+ h('div', { key: 'b' },
2631
+ '每个会话有一个压缩点,DSH 到这里会把早期对话换成摘要。压缩点 = 窗口 − 最大输出 − 4K 余量,'
2632
+ + '和 dsh-compaction-basic 的 messageBudget − headroomTokens 一致。'),
2633
+ h('div', { key: 'c' },
2634
+ '减去输出预留,是因为压缩之后仍要生成内容;4K 余量是压缩器自己留的安全垫。'
2635
+ + '1,048,576 的窗口配 256,000 的输出预留,压缩点是 788,480(75.2%)。'),
2636
+ ]),
2637
+ // The three lines the panel paints, computed for the session that is
2638
+ // about to receive the prompt — a different model means different
2639
+ // numbers, and a hard-coded table would be wrong for half of them.
2640
+ h('div', { className: 'aw-tbl', key: 'tbl' }, [
2641
+ h('div', { key: 'h', className: 'aw-tbl-h' }, [
2642
+ h('span', { key: 'a' }, '阈值'),
2643
+ h('span', { key: 'b' }, '含义'),
2644
+ ]),
2645
+ h('div', { key: 'w', className: 'aw-tbl-r' }, [
2646
+ h('span', { key: 'a', className: 'n' }, warnAt ? pct(warnAt) : '压缩点 × 80%'),
2647
+ h('span', { key: 'b' }, '标「注意」,还能撑一次较长的回复'),
2648
+ ]),
2649
+ h('div', { key: 'c', className: 'aw-tbl-r' }, [
2650
+ h('span', { key: 'a', className: 'n' }, critAt ? pct(critAt) : '压缩点 × 92%'),
2651
+ h('span', { key: 'b' }, '标「临界」,下一次大请求就可能触发压缩'),
2652
+ ]),
2653
+ h('div', { key: 'p', className: 'aw-tbl-r' }, [
2654
+ h('span', { key: 'a', className: 'n' }, mark ? pct(mark.ratio) : '压缩点'),
2655
+ h('span', { key: 'b' }, 'DSH 开始把早期对话替换成摘要'),
2656
+ ]),
2657
+ ]),
2658
+ h('div', { className: 'aw-tbl-note', key: 'tn' },
2659
+ mark
2660
+ ? `按《${target?.title || T.noTitle}》的模型算(${fmt(target?.contextWindow)} 窗口 / `
2661
+ + `${fmt(target?.maxOutputTokens)} 输出预留),换模型数值会变`
2662
+ : '这些比例固定,具体数值随模型的窗口和输出预留变化'),
2663
+ h('div', { className: 'aw-hp aw-hp-strong', key: 'w3' }, [
2664
+ h('div', { key: 'a' },
2665
+ h('b', { key: 'b' },
2666
+ '压缩之后,早期的对话只剩摘要,路径、命令、报错这些细节一般留不下来。'
2667
+ + '接手的人要接着做,只能重新找。')),
2668
+ h('div', { key: 'b' },
2669
+ h('b', { key: 'b' },
2670
+ '交接是在压缩之前,把目标、进度、关键文件、已否决的方案写成文件,'
2671
+ + '新会话读文件接着做。')),
2672
+ ]),
2673
+ h('p', { className: 'aw-hsec', key: 'o1' }, [
2674
+ T.targetTitle,
2675
+ h('span', { key: 's', className: 'aw-hsec-sub' }, '离压缩线最近的会话'),
2676
+ ]),
2677
+ top.map(card),
2678
+ ranked.length > top.length ? h('select', {
2679
+ key: 'other',
2680
+ className: 'aw-other',
2681
+ value: top.some(s => s.id === targetId) ? '' : (targetId ?? ''),
2682
+ title: '换模型、把活交给别的 Agent、或者今天收工——都可以选任意会话',
2683
+ onChange: ev => { if (ev.target.value) setTargetId(ev.target.value) },
2684
+ }, [
2685
+ h('option', { key: 'p', value: '' },
2686
+ top.some(s => s.id === targetId) ? '其他会话…' : (target?.title ?? '其他会话…')),
2687
+ ranked.filter(s => !top.includes(s)).map(s => h('option', {
2688
+ key: s.id, value: s.id,
2689
+ }, `${s.title || T.noTitle} · ${pct(s.ratio)}`)),
2690
+ ]) : null,
2691
+ ].filter(Boolean)),
2692
+ h('div', { className: 'aw-modal-r', key: 'r' }, [
2693
+ h('div', { className: 'lab', key: 'l' }, '提示词(可编辑,改完再复制)'),
2694
+ error
2695
+ ? h('div', { className: 'aw-hp', key: 'e' }, `读取提示词失败:${error}`)
2696
+ : h('textarea', {
2697
+ key: 't',
2698
+ ref: areaRef,
2699
+ value: text,
2700
+ spellCheck: false,
2701
+ 'aria-label': '交接提示词',
2702
+ onChange: ev => { edited.current = true; setText(ev.target.value) },
2703
+ }),
2704
+ ]),
2705
+ ]),
2706
+ h('div', { className: 'aw-modal-f', key: 'f' }, [
2707
+ h('div', { className: 'aw-fnote', key: 'n' }, [
2708
+ h('div', { key: 'a' }, hint || T.handoffNote),
2709
+ hint ? null : h('div', { key: 'b', className: 'sub' },
2710
+ '复制 → 回本会话发送 → 它给出接管消息 → 新会话粘贴'),
2711
+ ].filter(Boolean)),
2712
+ h('button', { key: 'c', className: 'aw-btn ghost', type: 'button', onClick: onClose }, '关闭'),
2713
+ h('button', {
2714
+ key: 'p',
2715
+ className: 'aw-btn primary',
2716
+ type: 'button',
2717
+ disabled: busy || !text.trim(),
2718
+ onClick: commit,
2719
+ }, busy ? '复制中…' : '复制'),
2720
+ ]),
2721
+ ]))
2722
+ }
2723
+
2724
+ /* ══════════════════ workbench shell ══════════════════ */
2725
+
2726
+ /**
2727
+ * State that has to survive the panel being unmounted.
2728
+ *
2729
+ * DSH unmounts a panel when you switch to another one, so plain `useState`
2730
+ * drops the active view and the selected node — which is why coming back
2731
+ * from anywhere reset the cockpit to the workspace with nothing selected.
2732
+ * localStorage is per machine, already used for panes / rail width / zoom.
2733
+ * @param key - storage key.
2734
+ * @param initial - value (or factory) when nothing usable is stored.
2735
+ * @param valid - predicate that rejects stale or hand-edited values.
2736
+ * @returns `[value, setValue]`, same shape as `useState`.
2737
+ */
2738
+ function usePersisted(key, initial, valid) {
2739
+ const [value, setValue] = React.useState(() => {
2740
+ try {
2741
+ const raw = localStorage.getItem(key)
2742
+ if (raw != null) {
2743
+ const parsed = JSON.parse(raw)
2744
+ if (!valid || valid(parsed)) return parsed
2745
+ }
2746
+ } catch { /* private mode, or a value written by an older build */ }
2747
+ return typeof initial === 'function' ? initial() : initial
2748
+ })
2749
+ const live = React.useRef(value)
2750
+ live.current = value
2751
+ const set = React.useCallback(next => {
2752
+ const resolved = typeof next === 'function' ? next(live.current) : next
2753
+ live.current = resolved
2754
+ setValue(resolved)
2755
+ try { localStorage.setItem(key, JSON.stringify(resolved)) } catch { /* private mode */ }
2756
+ }, [key])
2757
+ return [value, set]
2758
+ }
2759
+
2760
+ const isView = v => v === 'workspace' || v === 'cockpit'
2761
+ const isFilter = v => Boolean(v) && typeof v.project === 'string' && typeof v.query === 'string'
2762
+ const isSelected = v => v === null || typeof v === 'string'
2763
+
2764
+ function Workbench(kit) {
2765
+ // The shell themes itself by swapping CSS variables, not by a class we can
2766
+ // read. Sampling the background colour is the one signal that works for
2767
+ // every skin, and the observer catches a live theme switch.
2768
+ const [theme, setTheme] = React.useState('dark')
2769
+ React.useEffect(() => {
2770
+ /** @returns `[r, g, b]` from `#rrggbb` or `rgb()`/`rgba()`, else null. */
2771
+ const parseColor = raw => {
2772
+ const text = String(raw ?? '').trim()
2773
+ const hex = /^#([0-9a-f]{6})$/i.exec(text)
2774
+ if (hex) {
2775
+ const n = parseInt(hex[1], 16)
2776
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
2777
+ }
2778
+ const m = /(\d{1,3})\D+(\d{1,3})\D+(\d{1,3})/.exec(text)
2779
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
2780
+ }
2781
+ const read = () => {
2782
+ const rootStyle = getComputedStyle(document.documentElement)
2783
+ const bodyStyle = getComputedStyle(document.body)
2784
+ // The token may live on :root or on the app shell, and a third-party
2785
+ // skin may only paint the body background — try all three.
2786
+ const rgb = parseColor(rootStyle.getPropertyValue('--dsw-alias-bg-base'))
2787
+ ?? parseColor(bodyStyle.getPropertyValue('--dsw-alias-bg-base'))
2788
+ ?? parseColor(bodyStyle.backgroundColor)
2789
+ if (!rgb) return
2790
+ const lum = (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255
2791
+ setTheme(lum > 0.55 ? 'light' : 'dark')
2792
+ }
2793
+ read()
2794
+ const observer = new MutationObserver(read)
2795
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] })
2796
+ return () => observer.disconnect()
2797
+ }, [])
2798
+
2799
+ const [data, setData] = React.useState(null)
2800
+ const [error, setError] = React.useState(null)
2801
+ // View, selection and filter are persisted: leaving the panel and coming
2802
+ // back must not restart the workbench at its first screen.
2803
+ const [view, setView] = usePersisted('aw.view', 'workspace', isView)
2804
+ const [selected, setSelected] = usePersisted('aw.selected', null, isSelected)
2805
+ const [demo, setDemo] = React.useState(false)
2806
+ const [size, setSize] = React.useState({ w: 1000, hgt: 380 })
2807
+ const [filter, setFilter] = usePersisted('aw.filter', { project: '__all', query: '' }, isFilter)
2808
+ // Panes survive leaving the panel (e.g. "进入" opens the native view, then
2809
+ // the user comes back). Without this the whole layout resets to one empty
2810
+ // pane, which reads as data loss.
2811
+ const [panes, setPanes] = React.useState(() => {
2812
+ try {
2813
+ const raw = JSON.parse(localStorage.getItem('aw.panes') || '[]')
2814
+ if (!Array.isArray(raw)) return [null]
2815
+ const kept = []
2816
+ for (const v of raw) {
2817
+ if (v === null) { kept.push(null); continue }
2818
+ if (typeof v !== 'string') continue
2819
+ // One session, one pane: a duplicate would retain the same session
2820
+ // twice and show the same transcript in two cells.
2821
+ if (kept.includes(v)) continue
2822
+ kept.push(v)
2823
+ }
2824
+ return kept.slice(0, MAX_PANES).length ? kept.slice(0, MAX_PANES) : [null]
2825
+ } catch { return [null] }
2826
+ })
2827
+
2828
+ React.useEffect(() => {
2829
+ try { localStorage.setItem('aw.panes', JSON.stringify(panes)) } catch { /* private mode */ }
2830
+ }, [panes])
2831
+ const stageRef = React.useRef(null)
2832
+ const [tick, setTick] = React.useState(0)
2833
+ const [notice, setNotice] = React.useState(null)
2834
+ const [handoffOpen, setHandoffOpen] = React.useState(false)
2835
+ // Which pane should flash after a handoff copy. `at` makes a repeat copy
2836
+ // of the same session restart the animation instead of being ignored.
2837
+ const [flash, setFlash] = React.useState(null)
2838
+ const [railW, setRailW] = React.useState(() => {
2839
+ try {
2840
+ const v = Number(localStorage.getItem('aw.railWidth'))
2841
+ return v >= 200 && v <= 560 ? v : 288
2842
+ } catch { return 288 }
2843
+ })
2844
+ React.useEffect(() => {
2845
+ if (!notice) return undefined
2846
+ const t = setTimeout(() => setNotice(null), notice?.action ? 9000 : 5000)
2847
+ return () => clearTimeout(t)
2848
+ }, [notice])
2849
+
2850
+ const setRail = React.useCallback(w => {
2851
+ setRailW(w)
2852
+ try { localStorage.setItem('aw.railWidth', String(w)) } catch { /* private mode */ }
2853
+ }, [])
2854
+
2855
+ // A manual refresh used to be invisible: the payload is identical, so
2856
+ // nothing on screen moved. Track the request itself and spin the icon.
2857
+ const [busy, setBusy] = React.useState(false)
2858
+ const load = React.useCallback(async force => {
2859
+ const startedAt = Date.now()
2860
+ if (force) setBusy(true)
2861
+ try {
2862
+ const next = await fetchOverview(force)
2863
+ // The host caches for 45s, so a 15s poll usually returns the very
2864
+ // same snapshot. Keeping the previous object skips a re-render of
2865
+ // every native pane for a payload that did not change.
2866
+ setData(prev => (prev && next?.generatedAt === prev.generatedAt ? prev : next))
2867
+ setError(null)
2868
+ } catch (e) { setError(e) } finally {
2869
+ if (force) {
2870
+ // A cached overview can answer in under one frame, which would make
2871
+ // the spinner a no-op. Keep it up long enough to be seen.
2872
+ const wait = Math.max(0, 420 - (Date.now() - startedAt))
2873
+ setTimeout(() => setBusy(false), wait)
2874
+ }
2875
+ }
2876
+ }, [])
2877
+
2878
+ React.useEffect(() => { load(false) }, [load])
2879
+
2880
+ // Relative times ("3 分钟前") only need a slow clock; the graph layout
2881
+ // must not be rebuilt every couple of seconds.
2882
+ React.useEffect(() => {
2883
+ const id = setInterval(() => setTick(x => (x + 1) % 100000), 30_000)
2884
+ return () => clearInterval(id)
2885
+ }, [])
2886
+
2887
+ // The refresh button's tooltip promises a background refresh, so there is
2888
+ // one. Paused while the window is hidden: a panel nobody is looking at
2889
+ // should not keep waking the host.
2890
+ React.useEffect(() => {
2891
+ const id = setInterval(() => { if (!document.hidden) load(false) }, 15_000)
2892
+ return () => clearInterval(id)
2893
+ }, [load])
2894
+
2895
+ React.useEffect(() => {
2896
+ if (view !== 'cockpit') return undefined
2897
+ const el = stageRef.current
2898
+ if (!el) return undefined
2899
+ const measure = () => {
2900
+ const r = el.getBoundingClientRect()
2901
+ if (r.width > 0 && r.height > 0) setSize({ w: r.width, hgt: r.height })
2902
+ }
2903
+ measure()
2904
+ if (typeof ResizeObserver === 'function') {
2905
+ const ro = new ResizeObserver(measure)
2906
+ ro.observe(el)
2907
+ return () => ro.disconnect()
2908
+ }
2909
+ window.addEventListener('resize', measure)
2910
+ return () => window.removeEventListener('resize', measure)
2911
+ }, [view])
2912
+
2913
+ // Titles come from the client session store too: the native sidebar shows
2914
+ // real names even when the host half is older and still sends a
2915
+ // placeholder for every row.
2916
+ const display = React.useMemo(() => {
2917
+ if (!data) return null
2918
+ const titles = clientTitles()
2919
+ const factors = data.thresholds ?? DEFAULT_FACTORS
2920
+ const base = demo
2921
+ ? data.sessions.map(s => {
2922
+ if (s.ratio == null) return s
2923
+ const r = Math.min(0.995, s.ratio * 3.2 + 0.02)
2924
+ return { ...s, ratio: r }
2925
+ })
2926
+ : data.sessions
2927
+ // A session created but never used is a stub, not a conversation — the
2928
+ // native sidebar does not list it either. The host filters these too,
2929
+ // but the client must not depend on the host half having been reloaded
2930
+ // (it is a long-lived module: an old build keeps sending stubs).
2931
+ const real = base.filter(s => !(s.blank === true && (s.turns ?? 0) === 0))
2932
+ const kept = new Set(real.map(s => s.project))
2933
+ // Rebuild the chip counts from the sessions that survived, so a project
2934
+ // that only ever held a stub disappears instead of showing "… 1".
2935
+ const byProject = new Map()
2936
+ for (const s of real) byProject.set(s.project, (byProject.get(s.project) ?? 0) + 1)
2937
+ const projects = data.projects
2938
+ .filter(p => kept.has(p.title))
2939
+ .map(p => ({ ...p, count: byProject.get(p.title) ?? p.count }))
2940
+ return {
2941
+ ...data,
2942
+ projects,
2943
+ // Risk is recomputed here, not trusted from the wire: the thresholds
2944
+ // are derived per session from its own compaction point, so a host
2945
+ // half that still ships flat 70/85 numbers cannot mis-colour a pane.
2946
+ sessions: real.map(s => ({
2947
+ ...s, title: titleOf(s, titles), risk: riskOf(s, factors),
2948
+ })),
2949
+ }
2950
+ }, [data, demo])
2951
+
2952
+ const sessions = display?.sessions ?? []
2953
+ const projects = display?.projects ?? []
2954
+ // Threshold *factors*: the absolute percentage is per session, because
2955
+ // the compaction point depends on that session's own window and output
2956
+ // reservation.
2957
+ const th = display?.thresholds ?? DEFAULT_FACTORS
2958
+ const pricing = display?.pricing ?? null
2959
+
2960
+ // Open the busiest session on first load, and drop pane ids that no
2961
+ // longer exist (deleted or archived session) instead of leaving a pane
2962
+ // stuck on "从左侧选择一个会话" that can never be filled.
2963
+ React.useEffect(() => {
2964
+ if (!sessions.length) return
2965
+ const ids = new Set(sessions.map(s => s.id))
2966
+ setPanes(prev => {
2967
+ const pruned = prev.map(id => (id && ids.has(id) ? id : null))
2968
+ const next = pruned.some(Boolean) ? pruned : [sessions[0].id]
2969
+ const same = next.length === prev.length && next.every((v, i) => v === prev[i])
2970
+ return same ? prev : next
2971
+ })
2972
+ }, [sessions, setPanes])
2973
+
2974
+ const graph = React.useMemo(
2975
+ () => (display ? computeGraph(display, filter, size.w, size.hgt) : null),
2976
+ [display, filter, size],
2977
+ )
2978
+
2979
+ // A saved filter can name a project that no longer exists (renamed
2980
+ // workspace, sessions deleted). Reset instead of showing an empty list
2981
+ // with no highlighted chip to click off.
2982
+ React.useEffect(() => {
2983
+ if (!display || filter.project === '__all') return
2984
+ if (projects.some(p => p.title === filter.project)) return
2985
+ setFilter(prev => ({ ...prev, project: '__all' }))
2986
+ }, [display, projects, filter.project, setFilter])
2987
+
2988
+ const selectedSession = selected ? sessions.find(s => s.id === selected) ?? null : null
2989
+ const filtered = React.useMemo(() => {
2990
+ const q = filter.query.trim().toLowerCase()
2991
+ return sessions.filter(s => (filter.project === '__all' || s.project === filter.project)
2992
+ && (!q || `${s.title} ${s.project} ${s.model ?? ''}`.toLowerCase().includes(q)))
2993
+ }, [sessions, filter])
2994
+
2995
+ // What the bottom-left panel aggregates. It follows the selected node:
2996
+ // click a session and you get that session plus its subagents, click a
2997
+ // subagent and you get just it, click nothing and you get the filter.
2998
+ // (Project / hub clicks clear the selection and move the chip filter, so
2999
+ // they land on the third branch.)
3000
+ const scope = React.useMemo(() => {
3001
+ const node = selected && graph ? graph.nodeById.get(selected) : null
3002
+ if (node?.kind === 'sub' && node.session) {
3003
+ return {
3004
+ sessions: [node.session],
3005
+ label: `${T.scopePrefix} · ${T.scopeSub}:${node.session.title || T.noTitle}`,
3006
+ }
3007
+ }
3008
+ if (node?.kind === 'main' && node.session) {
3009
+ const tree = subtreeOf(node.id, sessions)
3010
+ const kids = Math.max(0, tree.length - 1)
3011
+ return {
3012
+ sessions: tree,
3013
+ label: `${T.scopePrefix} · ${node.session.title || T.noTitle}`
3014
+ + (kids ? ` 及 ${kids} 个子代理` : ''),
3015
+ }
3016
+ }
3017
+ if (filter.project !== '__all') {
3018
+ return {
3019
+ sessions: filtered,
3020
+ label: `${T.scopePrefix} · ${projName(filter.project)} · ${filtered.length} 个会话`,
3021
+ }
3022
+ }
3023
+ return { sessions: filtered, label: `${T.scopePrefix} · ${T.scopeAll} · ${filtered.length} 个` }
3024
+ }, [selected, graph, sessions, filtered, filter.project])
3025
+
3026
+ const risky = sessions.filter(s => s.risk === 'warn' || s.risk === 'crit').length
3027
+ const critical = sessions.filter(s => s.risk === 'crit').length
3028
+ const active = sessions.filter(isActive).length
3029
+ const known = sessions.filter(s => s.ratio != null)
3030
+ const avg = known.length ? known.reduce((sum, s) => sum + s.ratio, 0) / known.length : null
3031
+
3032
+ /**
3033
+ * After the prompt is on the clipboard: say where to paste it, and point
3034
+ * at the pane when that session happens to be on screen.
3035
+ * @param id - the session the prompt was written for.
3036
+ */
3037
+ function handoffCopied(id) {
3038
+ setHandoffOpen(false)
3039
+ const session = sessions.find(s => s.id === id)
3040
+ const title = session?.title || T.noTitle
3041
+ setFlash(id ? { id, at: Date.now() } : null)
3042
+ const slot = panes.indexOf(id)
3043
+ if (slot >= 0) {
3044
+ setNotice(`交接提示词已复制 · 请到第 ${slot + 1} 格《${title}》里粘贴发送`)
3045
+ return
3046
+ }
3047
+ // Not on screen. Say it in plain words ("not open in a pane"), because
3048
+ // "不在工作区" reads like the DSH workspace/project, which is a
3049
+ // different thing entirely.
3050
+ setNotice({
3051
+ text: `交接提示词已复制 · 《${title}》没有在窗格里打开`,
3052
+ action: {
3053
+ label: '载入窗格',
3054
+ run: () => {
3055
+ setPanes(prev => {
3056
+ const at = prev.findIndex(v => v === null)
3057
+ if (at >= 0) {
3058
+ const next = [...prev]
3059
+ next[at] = id
3060
+ return next
3061
+ }
3062
+ return [...prev.slice(0, MAX_PANES - 1), id]
3063
+ })
3064
+ setView('workspace')
3065
+ setFlash({ id, at: Date.now() })
3066
+ },
3067
+ },
3068
+ })
3069
+ }
3070
+
3071
+ // The flash is a three-beat animation; clear the flag once it has played.
3072
+ React.useEffect(() => {
3073
+ if (!flash) return undefined
3074
+ const timer = setTimeout(() => setFlash(null), 2600)
3075
+ return () => clearTimeout(timer)
3076
+ }, [flash])
3077
+
3078
+ function openNative(id) {
3079
+ const c = window.__SESSION_MATRIX_CTX__
3080
+ const face = c && (typeof c.get === 'function' ? c.get('uiWorkspace') : c.uiWorkspace)
3081
+ try {
3082
+ if (face && typeof face.openSession === 'function') {
3083
+ face.openSession(id)
3084
+ return
3085
+ }
3086
+ // No silent failure: a click that does nothing is indistinguishable
3087
+ // from a click that worked, so say which one it was.
3088
+ setNotice('当前环境没有 uiWorkspace.openSession,无法跳转到原生会话')
3089
+ } catch (error) {
3090
+ setNotice(`打开会话失败:${error?.message ?? error}`)
3091
+ }
3092
+ }
3093
+
3094
+ return h('div', { className: 'aw', 'data-theme': theme }, [
3095
+ h('style', { key: 'css' }, CSS),
3096
+
3097
+ h('header', { className: 'aw-hdr', key: 'hdr' }, [
3098
+ h('div', { className: 'aw-title', key: 't' }, [
3099
+ h(Icon, { key: 'i', name: 'network', size: 16 }),
3100
+ h('span', { key: 's' }, T.product),
3101
+ h('span', { key: 'sub', className: 'aw-sub' },
3102
+ `· ${filter.project === '__all' ? T.all : projName(filter.project)}`),
3103
+ ]),
3104
+ h('div', { className: 'aw-seg', key: 'v', role: 'tablist' }, [
3105
+ h('button', {
3106
+ key: 'w',
3107
+ role: 'tab',
3108
+ 'aria-selected': view === 'workspace',
3109
+ onClick: () => setView('workspace'),
3110
+ }, T.viewWorkspace),
3111
+ h('button', {
3112
+ key: 'c',
3113
+ role: 'tab',
3114
+ 'aria-selected': view === 'cockpit',
3115
+ onClick: () => setView('cockpit'),
3116
+ }, T.viewCockpit),
3117
+ ]),
3118
+ h('div', { className: 'aw-grow', key: 'g' }),
3119
+ view === 'cockpit' ? h('div', { className: 'aw-field', key: 'q', style: { width: 196 } }, [
3120
+ h(Icon, { key: 'i', name: 'search', size: 14 }),
3121
+ h('input', {
3122
+ key: 'in',
3123
+ value: filter.query,
3124
+ placeholder: T.search,
3125
+ onChange: ev => setFilter({ ...filter, query: ev.target.value }),
3126
+ }),
3127
+ ]) : null,
3128
+ h('div', { className: 'aw-stat', key: 'st' }, [
3129
+ h('span', {
3130
+ key: 'a',
3131
+ title: '当前筛选下的会话数(创建后从未使用过的空壳会话不计)',
3132
+ }, [h('b', { key: 'b' }, sessions.length), ' 会话']),
3133
+ h('span', {
3134
+ key: 'b',
3135
+ title: '最近 2 小时内有过更新的会话数;休眠会话仍会统计在左侧总数里',
3136
+ }, [h('b', { key: 'b' }, active), ' 活跃']),
3137
+ h('span', {
3138
+ key: 'c',
3139
+ title: '所有会话上下文占用的平均值。不同模型容量不同,所以总和不会混算成一个百分比',
3140
+ }, [h('b', { key: 'b' }, pct(avg)), ' 平均占用']),
3141
+ display?.capabilities?.coldPending ? h('span', {
3142
+ key: 'e',
3143
+ title: '还有冷会话的投影没读完,下一轮刷新补齐;已读部分照常显示',
3144
+ }, [h('b', { key: 'b' }, display.capabilities.coldPending), ' 读取中']) : null,
3145
+ h('span', {
3146
+ key: 'd',
3147
+ className: risky ? 'risk' : undefined,
3148
+ title: risky
3149
+ ? `${risky} 个会话已进入提醒区:注意 = 该会话压缩点 × ${Math.round(th.warnFactor * 100)}%,`
3150
+ + `预警 = 压缩点 × ${Math.round(th.criticalFactor * 100)}%。压缩点按各自模型容量换算,`
3151
+ + '不是固定的 70% / 85%'
3152
+ : `没有会话进入提醒区(注意 = 压缩点 × ${Math.round(th.warnFactor * 100)}%,`
3153
+ + `预警 = 压缩点 × ${Math.round(th.criticalFactor * 100)}%)`,
3154
+ }, risky ? `${risky} 需注意` : T.noRisk),
3155
+ ]),
3156
+ // Handoff entry. Always available, because a handoff is not only for a
3157
+ // full context: changing model, handing the work to another agent, or
3158
+ // picking it up tomorrow all need the same prompt.
3159
+ h('span', { key: 'ho', className: 'aw-hbtn' }, [
3160
+ h('button', {
3161
+ key: 'b',
3162
+ className: 'aw-btn ghost aw-handoff',
3163
+ type: 'button',
3164
+ 'aria-haspopup': 'dialog',
3165
+ title: T.handoffTitle,
3166
+ onClick: () => setHandoffOpen(true),
3167
+ }, [
3168
+ h(Icon, { key: 'i', name: 'handoff', size: 14 }),
3169
+ h('span', { key: 'k', className: 'aw-hbtn-k' }, T.handoff),
3170
+ ]),
3171
+ // A dot, not a red button: a whole warning-coloured button in the
3172
+ // toolbar shouts, and this is an offer, not an alarm.
3173
+ risky ? h('span', {
3174
+ key: 'd',
3175
+ className: `aw-hbtn-dot${critical ? ' crit' : ''}`,
3176
+ title: critical
3177
+ ? `${critical} 个会话已到临界线`
3178
+ : `${risky} 个会话进入注意区`,
3179
+ }) : null,
3180
+ h('span', { key: 't', className: 'aw-tip', role: 'tooltip' }, [
3181
+ h('b', { key: 'a' }, T.handoffTitle),
3182
+ h('div', { key: 'b' }, T.handoffTip),
3183
+ h('div', { key: 'c', className: 'sub' }, T.handoffTip2),
3184
+ ]),
3185
+ ]),
3186
+ h('button', {
3187
+ key: 'rf',
3188
+ className: 'aw-btn ghost',
3189
+ title: '立即从宿主重新读取一次(跳过 45 秒缓存)。面板开着的这期间每 15 秒自动刷新,'
3190
+ + '窗口隐藏时暂停,一般不需要手动点',
3191
+ onClick: () => { if (!busy) load(true) },
3192
+ disabled: busy,
3193
+ 'aria-busy': busy ? 'true' : 'false',
3194
+ }, h('span', { key: 'i', className: busy ? 'aw-rot' : undefined },
3195
+ h(Icon, { name: 'refresh', size: 14 }))),
3196
+ ].filter(Boolean)),
3197
+
3198
+ // The toast floats over whatever sits at the bottom of the current
3199
+ // view: the native composer in the workspace, the three modules in the
3200
+ // cockpit. Clear both instead of covering the input box.
3201
+ notice ? h('div', {
3202
+ key: 'toast',
3203
+ className: 'aw-toast',
3204
+ role: 'status',
3205
+ // 136px clears the native composer (~120px) in the workspace; 296px
3206
+ // clears the three bottom modules in the cockpit.
3207
+ style: { bottom: view === 'cockpit' ? 296 : 136 },
3208
+ }, [
3209
+ h('span', { key: 't' }, typeof notice === 'string' ? notice : notice.text),
3210
+ notice?.action ? h('button', {
3211
+ key: 'a',
3212
+ className: 'aw-btn ghost',
3213
+ style: { height: 22, marginLeft: 10, padding: '0 8px' },
3214
+ type: 'button',
3215
+ onClick: () => { notice.action.run(); setNotice(null) },
3216
+ }, notice.action.label) : null,
3217
+ ].filter(Boolean)) : null,
3218
+
3219
+ handoffOpen ? h(Boundary, { key: 'hb' }, h(HandoffModal, {
3220
+ key: 'handoff',
3221
+ sessions,
3222
+ // Preselect what the user is actually looking at: in the workspace
3223
+ // that is the pane on screen, in the cockpit it is the selected node.
3224
+ // (A stale persisted selection used to win here, so the dialog could
3225
+ // preselect a session that is nowhere on screen.)
3226
+ preset: view === 'workspace'
3227
+ ? (panes.find(Boolean) ?? selected)
3228
+ : (selected ?? panes.find(Boolean)),
3229
+ paneIds: panes.filter(Boolean),
3230
+ th,
3231
+ onClose: () => setHandoffOpen(false),
3232
+ onCopied: handoffCopied,
3233
+ })) : null,
3234
+
3235
+ error ? h('div', { className: 'aw-err', key: 'err' }, [
3236
+ h('div', { key: 'a' }, T.loadFail),
3237
+ h('code', { key: 'b' }, String(error.message ?? error)),
3238
+ h('div', { key: 'c' }, T.loadFailHint),
3239
+ ]) : view === 'workspace'
3240
+ ? h(WorkspaceView, {
3241
+ key: 'ws',
3242
+ sessions: filtered,
3243
+ projects,
3244
+ filter,
3245
+ setFilter,
3246
+ panes,
3247
+ setPanes,
3248
+ onOpenNative: openNative,
3249
+ railW,
3250
+ onRailW: setRail,
3251
+ kit,
3252
+ th,
3253
+ flashId: flash?.id ?? null,
3254
+ })
3255
+ : h('div', { className: 'aw-main', key: 'ck' }, [
3256
+ h('div', { className: 'aw-toolbar', key: 'tb' }, [
3257
+ h('button', {
3258
+ key: '__all',
3259
+ className: 'aw-chip',
3260
+ 'aria-pressed': filter.project === '__all',
3261
+ onClick: () => setFilter({ ...filter, project: '__all' }),
3262
+ }, [h('span', { key: 't' }, T.all), h('span', { key: 'n', className: 'n' }, sessions.length)]),
3263
+ projects.map(p => h('button', {
3264
+ key: p.title || '__ungrouped',
3265
+ className: 'aw-chip',
3266
+ title: p.title ? undefined : '这些会话的目录不属于任何工作空间',
3267
+ 'aria-pressed': filter.project === p.title,
3268
+ onClick: () => setFilter({ ...filter, project: p.title }),
3269
+ }, [h('span', { key: 't' }, projName(p.title)),
3270
+ h('span', { key: 'n', className: 'n' }, p.count)])),
3271
+ h('div', { className: 'aw-grow', key: 'g' }),
3272
+ h('button', {
3273
+ key: 'demo',
3274
+ className: `aw-btn${demo ? ' on' : ''}`,
3275
+ title: '把占用率放大以预览预警配色(仅影响显示)',
3276
+ onClick: () => setDemo(!demo),
3277
+ }, demo ? T.restore : T.previewRisk),
3278
+ h('div', { className: 'aw-legend', key: 'lg' }, [
3279
+ h('span', { key: 'a', title: '主会话:你自己开的会话' }, [
3280
+ h('i', { key: 'd', className: 'aw-dot', style: { background: 'var(--dsw-alias-label-secondary)' } }),
3281
+ T.main,
3282
+ ]),
3283
+ h('span', { key: 'b', title: '子代理会话:由主会话派生,可查看但不能直接对话' }, [
3284
+ h('i', { key: 'd', className: 'aw-dot', style: { background: 'var(--dsw-alias-label-tertiary)' } }),
3285
+ T.sub,
3286
+ ]),
3287
+ h('span', {
3288
+ key: 'c',
3289
+ title: `注意:占用达到该会话压缩点的 ${Math.round(th.warnFactor * 100)}%。`
3290
+ + '压缩点按各自模型的窗口与输出预留换算(常见 1M 窗口约 56%–69%),'
3291
+ + '所以这里不写死一个百分比',
3292
+ }, [
3293
+ h('i', { key: 'd', className: 'aw-dot', style: { background: 'var(--dsw-alias-state-warn-primary)' } }),
3294
+ T.levelWarn,
3295
+ ]),
3296
+ h('span', {
3297
+ key: 'd',
3298
+ title: `预警:占用达到压缩点的 ${Math.round(th.criticalFactor * 100)}%,`
3299
+ + '再往下就会真的触发自动压缩(历史被摘要替换)',
3300
+ }, [
3301
+ h('i', { key: 'd', className: 'aw-dot', style: { background: 'var(--dsw-alias-state-error-primary)' } }),
3302
+ T.levelCrit,
3303
+ ]),
3304
+ ]),
3305
+ ]),
3306
+ h('div', { className: 'aw-canvas', key: 'cv', ref: stageRef },
3307
+ h(NetworkMemo, {
3308
+ graph,
3309
+ selected,
3310
+ onSelect: setSelected,
3311
+ onProject: name => setFilter({ ...filter, project: name }),
3312
+ // Only the sessions the user is actually watching get flow.
3313
+ pinned: panes.filter(Boolean),
3314
+ })),
3315
+ h('div', { className: 'aw-bot', key: 'bot' }, [
3316
+ h(Composition, { key: 'c', sessions: scope.sessions, pricing, scopeLabel: scope.label }),
3317
+ h(Matrix, { key: 'm', sessions: filtered, selected, onSelect: setSelected, th }),
3318
+ h(Inspector, { key: 'i', session: selectedSession, onOpen: openNative, th }),
3319
+ ]),
3320
+ ]),
3321
+ ])
3322
+ }
3323
+
3324
+ /* ══════════════════ registration ══════════════════ */
3325
+
3326
+ function SidebarIcon(props) {
3327
+ const size = props?.size ?? 16
3328
+ const active = props?.active === true
3329
+ return h('svg', {
3330
+ width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
3331
+ stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round',
3332
+ style: { opacity: active ? 1 : 0.75 },
3333
+ }, [
3334
+ h('circle', { key: 'a', cx: 2.6, cy: 8, r: 1.3, fill: 'currentColor', stroke: 'none' }),
3335
+ h('circle', { key: 'b', cx: 8, cy: 4, r: 1.1 }),
3336
+ h('circle', { key: 'c', cx: 8, cy: 12, r: 1.1 }),
3337
+ h('circle', { key: 'd', cx: 13.4, cy: 6, r: 1.1 }),
3338
+ h('circle', { key: 'e', cx: 13.4, cy: 11, r: 1.1 }),
3339
+ h('path', { key: 'f', d: 'M2.6 8L8 4M2.6 8L8 12M8 4l5.4 2M8 12l5.4-1' }),
3340
+ ])
3341
+ }
3342
+
3343
+ return {
3344
+ inject: ['slots', 'sessions', 'locale'],
3345
+ apply(ctx) {
3346
+ window.__SESSION_MATRIX_CTX__ = ctx
3347
+
3348
+ if (ctx.locale && typeof ctx.locale.register === 'function') {
3349
+ ctx.effect(() => ctx.locale.register('sessionMatrix', {
3350
+ zh: { title: '会话矩阵工作台' },
3351
+ en: { title: 'Session Matrix' },
3352
+ }), 'dsh-session-matrix: locale')
3353
+ }
3354
+
3355
+ // The session-scoped child slot is what makes the renderer inject
3356
+ // `SessionProvider` + `renderFactorySlot` into this panel. Registration
3357
+ // is guarded: if the Host lacks the session scope adapter (a trimmed
3358
+ // profile) the entry would throw SlotAssemblyError and the whole main
3359
+ // area would go blank, so we fall back to a panel without children.
3360
+ try {
3361
+ ctx.slots.inject('main', () => ctx.slots.register({
3362
+ name: 'main',
3363
+ key: 'dsh-session-matrix',
3364
+ locale: 'sessionMatrix',
3365
+ children: {
3366
+ 'dsh-session-matrix.pane': { kind: 'single', scope: 'session' },
3367
+ },
3368
+ }, props => h(Boundary, null, h(Workbench, props))))
3369
+ } catch (error) {
3370
+ console.error('dsh-session-matrix: native registration failed, falling back', error)
3371
+ try {
3372
+ ctx.slots.inject('main', () => ctx.slots.register({
3373
+ name: 'main',
3374
+ key: 'dsh-session-matrix',
3375
+ locale: 'sessionMatrix',
3376
+ }, props => h(Boundary, null, h(Workbench, props))))
3377
+ } catch (second) {
3378
+ console.error('dsh-session-matrix: fallback registration failed', second)
3379
+ }
3380
+ }
3381
+
3382
+ try {
3383
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
3384
+ name: 'sidebar.panellist',
3385
+ id: 'dsh-session-matrix',
3386
+ order: 40,
3387
+ // Without `label` the sidebar falls back to the raw entry id —
3388
+ // which is why this panel used to read the raw entry id.
3389
+ label: () => '会话矩阵工作台',
3390
+ locale: 'sessionMatrix',
3391
+ }, SidebarIcon))
3392
+ } catch (error) {
3393
+ console.error('dsh-session-matrix: sidebar entry registration failed', error)
3394
+ }
3395
+ },
3396
+ }
3397
+ },
3398
+ })