dsh-status-map 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,945 @@
1
+ import React, { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
+ import {
3
+ ReactFlow, ReactFlowProvider, Background, Controls, MiniMap,
4
+ Handle, Position, MarkerType, useNodesState, useReactFlow,
5
+ } from '@xyflow/react'
6
+ import flowCss from '@xyflow/react/dist/style.css'
7
+
8
+ const h = React.createElement
9
+ const NS = 'dsh-status-map'
10
+ const THEME_KEY = 'dsh-status-map:theme'
11
+
12
+ const THEME_PRESETS = {
13
+ light: {
14
+ accent: '#3b6fe0', bg: '#f6f8fb', surface: '#ffffff',
15
+ surface2: '#eef1f6', text: '#1f2430', text2: '#5d677a',
16
+ },
17
+ dark: {
18
+ accent: '#6f9dff', bg: '#0f1420', surface: '#1a2130',
19
+ surface2: '#232c3d', text: '#e7ebf3', text2: '#9aa5b8',
20
+ },
21
+ }
22
+
23
+ const DEFAULT_CUSTOM = {
24
+ accent: '#4a65e8', bg: '#10151f', surface: '#1a2130',
25
+ surface2: '#232c3d', text: '#e7ebf3', text2: '#9aa5b8',
26
+ }
27
+
28
+ function validateCustom(custom) {
29
+ const result = Object.assign({}, DEFAULT_CUSTOM)
30
+ for (const key of Object.keys(result)) {
31
+ const value = custom && custom[key]
32
+ if (typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value)) result[key] = value
33
+ }
34
+ return result
35
+ }
36
+
37
+ function readTheme() {
38
+ try {
39
+ const parsed = JSON.parse(localStorage.getItem(THEME_KEY) || 'null')
40
+ if (parsed && typeof parsed === 'object') {
41
+ const mode = ['system', 'light', 'dark', 'custom'].includes(parsed.mode)
42
+ ? parsed.mode : 'system'
43
+ return { mode, custom: validateCustom(parsed.custom) }
44
+ }
45
+ } catch (_error) {
46
+ // Fall through to the default theme.
47
+ }
48
+ return { mode: 'system', custom: validateCustom(null) }
49
+ }
50
+
51
+ function themeVariables(theme) {
52
+ if (theme.mode === 'system') return {}
53
+ const palette = theme.mode === 'custom' ? theme.custom : THEME_PRESETS[theme.mode]
54
+ return {
55
+ '--cm-bg': palette.bg,
56
+ '--cm-surface': palette.surface,
57
+ '--cm-surface2': palette.surface2,
58
+ '--cm-text': palette.text,
59
+ '--cm-text2': palette.text2,
60
+ '--cm-border': palette.text2 + '55',
61
+ '--cm-border2': palette.text2 + '88',
62
+ '--cm-accent': palette.accent,
63
+ }
64
+ }
65
+
66
+ function blockText(block) {
67
+ if (!block || typeof block !== 'object') return ''
68
+ const kind = block.kind || block.type || ''
69
+ if (kind === 'text' || kind === 'reasoning') {
70
+ return typeof block.text === 'string' ? block.text : ''
71
+ }
72
+ if (kind === 'image') return '[image]'
73
+ if (kind === 'tool-call') return String(block.name || '')
74
+ if (typeof block.text === 'string') return block.text
75
+ return ''
76
+ }
77
+
78
+ function textOf(blocks) {
79
+ if (!Array.isArray(blocks)) return ''
80
+ return blocks.map(blockText).filter(Boolean).join('\n')
81
+ }
82
+
83
+ function clip(value, max) {
84
+ const oneLine = String(value || '').replace(/\s+/g, ' ').trim()
85
+ return oneLine.length > max ? oneLine.slice(0, max - 1) + '\u2026' : oneLine
86
+ }
87
+
88
+ function timeLabel(time) {
89
+ if (typeof time !== 'number' || !Number.isFinite(time)) return ''
90
+ try {
91
+ return new Date(time).toLocaleTimeString([], {
92
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
93
+ })
94
+ } catch (_error) {
95
+ return ''
96
+ }
97
+ }
98
+
99
+ function firstString(...values) {
100
+ for (const value of values) {
101
+ if (typeof value === 'string' && value.trim()) return value
102
+ }
103
+ return ''
104
+ }
105
+
106
+ function isForkableSeq(seq) {
107
+ return Number.isSafeInteger(seq) && seq >= 0
108
+ }
109
+
110
+ function describe(node, t) {
111
+ const kind = node && node.kind ? String(node.kind) : ''
112
+ if (kind === 'unknown') {
113
+ return {
114
+ title: t('node.unknown') + (node.type ? ' \u00b7 ' + String(node.type) : ''),
115
+ body: clip(JSON.stringify(node.data === undefined ? '' : node.data), 90),
116
+ }
117
+ }
118
+ const data = node && node.data && typeof node.data === 'object' ? node.data : node
119
+ switch (kind) {
120
+ case 'user':
121
+ return { title: t('node.question'), body: textOf(data.content) }
122
+ case 'steering':
123
+ return { title: t('node.steering'), body: textOf(data.content) }
124
+ case 'assistant':
125
+ return { title: t('node.answer'), body: textOf(data.blocks) }
126
+ case 'tool-result': {
127
+ const name = firstString(data.name, data.call && data.call.name)
128
+ const body = firstString(
129
+ textOf(data.content), data.call && data.call.argsRaw,
130
+ data.error && data.error.reason,
131
+ )
132
+ return {
133
+ title: t('node.tool') + (name ? ' \u00b7 ' + name : '')
134
+ + (data.isError ? ' \u00b7 ' + t('node.error') : ''),
135
+ body,
136
+ }
137
+ }
138
+ case 'command': {
139
+ const command = data.command || data
140
+ return { title: t('node.command'), body: clip(firstString(command.name, command.args), 90) }
141
+ }
142
+ case 'context':
143
+ return { title: t('node.context'), body: textOf(data.content) }
144
+ case 'turn-error':
145
+ return { title: t('node.error'), body: clip(firstString(data.message, data.code), 90) }
146
+ case 'turn-max-tokens':
147
+ return { title: t('node.maxTokens'), body: '' }
148
+ case 'model-retry':
149
+ return {
150
+ title: t('node.retry'),
151
+ body: clip(firstString(
152
+ data.failure && data.failure.message, data.message, data.reason, data.retryState,
153
+ ), 90),
154
+ }
155
+ case 'compaction':
156
+ return { title: t('node.compaction'), body: clip(data.summary || '', 90) }
157
+ default:
158
+ return { title: t('node.fallback') + (kind ? ' \u00b7 ' + kind : ''), body: '' }
159
+ }
160
+ }
161
+
162
+ function buildFlows(nodes, partial, runningCalls, t) {
163
+ const flows = []
164
+ let current = null
165
+ nodes.forEach((node, index) => {
166
+ if (!node || typeof node !== 'object') return
167
+ const kind = String(node.kind || '')
168
+ const usableSeq = isForkableSeq(node.seq)
169
+ const turn = typeof node.turn === 'number'
170
+ ? node.turn
171
+ : (node.data && typeof node.data.turn === 'number' ? node.data.turn : undefined)
172
+ if (kind === 'user') {
173
+ current = {
174
+ key: 'flow-' + (usableSeq ? node.seq : index),
175
+ seq: usableSeq ? node.seq : undefined,
176
+ question: describe(node, t),
177
+ questionTime: timeLabel(node.time),
178
+ turn: undefined,
179
+ items: [],
180
+ }
181
+ flows.push(current)
182
+ return
183
+ }
184
+ if (kind === 'assistant' || kind === 'tool-result' || kind === 'command'
185
+ || kind === 'context' || kind === 'turn-error' || kind === 'turn-max-tokens'
186
+ || kind === 'model-retry' || kind === 'compaction' || kind === 'unknown'
187
+ || kind === 'steering') {
188
+ if (current === null) {
189
+ current = {
190
+ key: 'flow-head-' + (usableSeq ? node.seq : index),
191
+ seq: usableSeq ? node.seq : undefined,
192
+ question: { title: t('node.context'), body: '' },
193
+ questionTime: timeLabel(node.time),
194
+ turn: undefined,
195
+ items: [],
196
+ }
197
+ flows.push(current)
198
+ }
199
+ if (kind === 'assistant' && typeof turn === 'number' && current.turn === undefined) {
200
+ current.turn = turn
201
+ }
202
+ current.items.push(Object.assign({ seq: usableSeq ? node.seq : undefined }, describe(node, t)))
203
+ }
204
+ })
205
+ if (partial || runningCalls.length > 0) {
206
+ if (flows.length === 0) {
207
+ flows.push({
208
+ key: 'flow-live',
209
+ seq: undefined,
210
+ question: { title: t('node.context'), body: '' },
211
+ questionTime: '',
212
+ turn: undefined,
213
+ items: [],
214
+ })
215
+ }
216
+ const flowFor = (turn) => {
217
+ if (typeof turn !== 'number') return undefined
218
+ return flows.find(flow => flow.turn === turn)
219
+ }
220
+ if (partial) {
221
+ const target = flowFor(partial.turn) || flows[flows.length - 1]
222
+ target.items.push({ title: t('node.generating'), body: textOf(partial.blocks) })
223
+ }
224
+ runningCalls.forEach((call) => {
225
+ const target = flowFor(call.turn) || flows[flows.length - 1]
226
+ target.items.push({
227
+ title: t('node.toolRunning') + (call.name ? ' \u00b7 ' + String(call.name) : ''),
228
+ body: clip(call.argsRaw || '', 90),
229
+ })
230
+ })
231
+ }
232
+ return flows
233
+ }
234
+
235
+ function summarize(flow, t) {
236
+ const answers = flow.items.filter(item => item.title === t('node.answer'))
237
+ const tools = flow.items.filter(item => item.title.startsWith(t('node.tool')))
238
+ const errors = flow.items.filter(item => item.title.includes(t('node.error'))
239
+ || item.title === t('node.maxTokens') || item.title === t('node.retry'))
240
+ const body = (answers[0] && answers[0].body) || (flow.items[0] && flow.items[0].body) || ''
241
+ const counts = []
242
+ if (answers.length) counts.push(t('count.answer') + ': ' + answers.length)
243
+ if (tools.length) counts.push(t('count.tool') + ': ' + tools.length)
244
+ if (errors.length) counts.push(t('count.error') + ': ' + errors.length)
245
+ const seqs = flow.items.map(item => item.seq).filter(isForkableSeq)
246
+ return {
247
+ title: flow.items.length ? (answers.length ? t('node.answer') : flow.items[0].title) : t('noWork'),
248
+ body: clip(body, 110),
249
+ meta: counts.join(' \u00b7 '),
250
+ endSeq: seqs.length ? Math.max(...seqs) : undefined,
251
+ }
252
+ }
253
+
254
+ function ForkButton({ onFork, seq, kind, label, t }) {
255
+ const [busy, setBusy] = useState(false)
256
+ if (!isForkableSeq(seq) || typeof onFork !== 'function') return null
257
+ return h('button', {
258
+ type: 'button',
259
+ className: 'cm-fork nodrag',
260
+ disabled: busy,
261
+ onClick: async () => {
262
+ setBusy(true)
263
+ try {
264
+ await onFork(seq, kind)
265
+ } catch (_error) {
266
+ // A failed fork leaves the source session unchanged.
267
+ } finally {
268
+ setBusy(false)
269
+ }
270
+ },
271
+ }, busy ? t('forking') : label)
272
+ }
273
+
274
+ function QuestionNode({ data }) {
275
+ return h('div', { className: 'cm-node cm-question' },
276
+ h(Handle, { type: 'target', position: Position.Top, id: 'up', className: 'cm-handle' }),
277
+ h(Handle, { type: 'source', position: Position.Bottom, id: 'down', className: 'cm-handle' }),
278
+ h(Handle, { type: 'source', position: Position.Right, id: 'right', className: 'cm-handle' }),
279
+ h(Handle, { type: 'source', position: Position.Left, id: 'left', className: 'cm-handle' }),
280
+ h('div', { className: 'cm-node-head' },
281
+ h('span', { className: 'cm-node-title' }, data.title),
282
+ data.time ? h('span', { className: 'cm-node-time' }, data.time) : null,
283
+ ),
284
+ data.body ? h('div', { className: 'cm-node-body' }, data.body) : null,
285
+ h(ForkButton, {
286
+ onFork: data.onFork, seq: data.forkSeq, kind: 'question',
287
+ label: data.forkLabel, t: data.t,
288
+ }),
289
+ )
290
+ }
291
+
292
+ function AnswerNode({ data }) {
293
+ const [expanded, setExpanded] = useState(false)
294
+ return h('div', { className: 'cm-node cm-answer' },
295
+ h(Handle, { type: 'target', position: Position.Left, id: 'left', className: 'cm-handle' }),
296
+ h(Handle, { type: 'target', position: Position.Right, id: 'right', className: 'cm-handle' }),
297
+ h(Handle, { type: 'source', position: Position.Right, id: 'branch', className: 'cm-handle' }),
298
+ h('div', { className: 'cm-node-head' },
299
+ h('span', { className: 'cm-node-title' }, data.title),
300
+ data.time ? h('span', { className: 'cm-node-time' }, data.time) : null,
301
+ ),
302
+ data.body ? h('div', { className: 'cm-node-body' }, data.body) : null,
303
+ data.meta ? h('div', { className: 'cm-node-meta' }, data.meta) : null,
304
+ data.items.length > 0 ? h('button', {
305
+ type: 'button',
306
+ className: 'cm-toggle nodrag',
307
+ 'aria-expanded': expanded,
308
+ onClick: () => setExpanded(value => !value),
309
+ }, expanded ? data.collapseLabel : data.expandLabel) : null,
310
+ expanded ? h('div', { className: 'cm-items nowheel nodrag' },
311
+ data.items.map((item, index) => h('div', { key: index, className: 'cm-item' },
312
+ h('span', { className: 'cm-item-title' }, item.title),
313
+ item.body ? h('span', { className: 'cm-item-body' }, item.body) : null,
314
+ )),
315
+ ) : null,
316
+ h(ForkButton, {
317
+ onFork: data.onFork, seq: data.forkSeq, kind: 'answer',
318
+ label: data.forkLabel, t: data.t,
319
+ }),
320
+ )
321
+ }
322
+
323
+ function BranchHeaderNode({ data }) {
324
+ return h('div', { className: 'cm-node cm-branch' },
325
+ h(Handle, { type: 'target', position: Position.Left, id: 'left', className: 'cm-handle' }),
326
+ h('div', { className: 'cm-node-head' },
327
+ h('span', { className: 'cm-node-title' }, data.title),
328
+ data.time ? h('span', { className: 'cm-node-time' }, data.time) : null,
329
+ ),
330
+ h('div', { className: 'cm-node-meta' }, data.meta),
331
+ h('div', { className: 'cm-branch-actions' },
332
+ h('button', {
333
+ type: 'button', className: 'cm-fork nodrag',
334
+ onClick: data.onOpen,
335
+ }, data.openLabel),
336
+ h('button', {
337
+ type: 'button', className: 'cm-toggle nodrag',
338
+ onClick: data.onHide,
339
+ }, data.hideLabel),
340
+ ),
341
+ )
342
+ }
343
+
344
+ function createBranchStore(ctx, sessionId, t) {
345
+ const key = 'dsh-status-map:branches:' + sessionId
346
+ let value = []
347
+ let rebuilding = false
348
+ const listeners = new Set()
349
+ const childSubs = new Map()
350
+ const emit = () => { for (const listener of listeners) listener() }
351
+ const read = () => {
352
+ try {
353
+ const parsed = JSON.parse(localStorage.getItem(key) || '[]')
354
+ return Array.isArray(parsed) ? parsed : []
355
+ } catch (_error) {
356
+ return []
357
+ }
358
+ }
359
+ const write = (entries) => {
360
+ try {
361
+ localStorage.setItem(key, JSON.stringify(entries))
362
+ } catch (_error) {
363
+ // Storage may be unavailable; branches then last only for this mount.
364
+ }
365
+ }
366
+ const ensureChildSub = (childId) => {
367
+ if (childSubs.has(childId)) return
368
+ try {
369
+ const target = ctx.uiConversation.binding(childId).target('chat')
370
+ const unsubscribe = target.subscribe(() => { if (!rebuilding) rebuild() })
371
+ childSubs.set(childId, unsubscribe)
372
+ } catch (_error) {
373
+ childSubs.set(childId, () => {})
374
+ }
375
+ }
376
+ const rebuild = () => {
377
+ if (rebuilding) return
378
+ rebuilding = true
379
+ try {
380
+ const entries = read().filter(entry => entry && typeof entry.childId === 'string')
381
+ const ids = new Set(entries.map(entry => entry.childId))
382
+ for (const [childId, unsubscribe] of childSubs) {
383
+ if (!ids.has(childId)) {
384
+ unsubscribe()
385
+ childSubs.delete(childId)
386
+ }
387
+ }
388
+ value = entries.map((entry) => {
389
+ ensureChildSub(entry.childId)
390
+ let flows = []
391
+ try {
392
+ const target = ctx.uiConversation.binding(entry.childId).target('chat')
393
+ const snapshot = target.getSnapshot()
394
+ if (snapshot) {
395
+ flows = buildFlows(
396
+ snapshot.legacy.nodes, snapshot.legacy.partial,
397
+ snapshot.legacy.runningCalls, t,
398
+ )
399
+ }
400
+ } catch (_error) {
401
+ flows = []
402
+ }
403
+ return Object.assign({}, entry, { flows })
404
+ })
405
+ } finally {
406
+ rebuilding = false
407
+ }
408
+ emit()
409
+ }
410
+ rebuild()
411
+ return {
412
+ getSnapshot: () => value,
413
+ subscribe(listener) {
414
+ listeners.add(listener)
415
+ return () => listeners.delete(listener)
416
+ },
417
+ add(childId, forkedAtSeq, forkKind) {
418
+ const entries = read().filter(entry => entry.childId !== childId)
419
+ entries.push({
420
+ childId,
421
+ forkedAtSeq,
422
+ forkKind,
423
+ createdAt: Date.now(),
424
+ })
425
+ write(entries)
426
+ rebuild()
427
+ window.dispatchEvent(new Event('dsh-status-map:branches'))
428
+ },
429
+ remove(childId) {
430
+ write(read().filter(entry => entry.childId !== childId))
431
+ rebuild()
432
+ window.dispatchEvent(new Event('dsh-status-map:branches'))
433
+ },
434
+ }
435
+ }
436
+
437
+ function ThemePanel({ theme, onChange, t }) {
438
+ const modes = [
439
+ ['system', t('theme.system')],
440
+ ['light', t('theme.light')],
441
+ ['dark', t('theme.dark')],
442
+ ['custom', t('theme.custom')],
443
+ ]
444
+ const colors = [
445
+ ['accent', t('theme.accent')],
446
+ ['bg', t('theme.background')],
447
+ ['surface', t('theme.surface')],
448
+ ['surface2', t('theme.surface2')],
449
+ ['text', t('theme.text')],
450
+ ['text2', t('theme.text2')],
451
+ ]
452
+ const setMode = (mode) => onChange({ mode, custom: theme.custom })
453
+ const setColor = (key, value) => onChange({
454
+ mode: 'custom',
455
+ custom: Object.assign({}, theme.custom, { [key]: value }),
456
+ })
457
+ return h('div', {
458
+ className: 'cm-theme-panel nowheel nodrag',
459
+ id: 'cm-theme-panel',
460
+ role: 'dialog',
461
+ 'aria-label': t('theme.button'),
462
+ },
463
+ h('div', { className: 'cm-theme-modes' },
464
+ modes.map(([mode, label]) => h('button', {
465
+ key: mode,
466
+ type: 'button',
467
+ className: 'cm-theme-mode' + (theme.mode === mode ? ' is-active' : ''),
468
+ 'aria-pressed': theme.mode === mode,
469
+ onClick: () => setMode(mode),
470
+ }, label)),
471
+ ),
472
+ theme.mode === 'custom' ? h('div', { className: 'cm-theme-colors' },
473
+ colors.map(([key, label]) => h('label', { key, className: 'cm-theme-color' },
474
+ h('span', null, label),
475
+ h('input', {
476
+ type: 'color',
477
+ value: theme.custom[key] || DEFAULT_CUSTOM[key],
478
+ onChange: event => setColor(key, event.target.value),
479
+ }),
480
+ )),
481
+ ) : h('div', { className: 'cm-theme-note' }, t('theme.hint')),
482
+ )
483
+ }
484
+
485
+ const themeCss = `
486
+ .cm-root {
487
+ --cm-bg: var(--dsw-alias-bg-base);
488
+ --cm-surface: var(--dsw-alias-bg-layer-1);
489
+ --cm-surface2: var(--dsw-alias-bg-layer-2);
490
+ --cm-border: var(--dsw-alias-border-l1);
491
+ --cm-border2: var(--dsw-alias-border-l2);
492
+ --cm-border-soft: var(--cm-border);
493
+ --cm-text: var(--dsw-alias-label-primary);
494
+ --cm-text2: var(--dsw-alias-label-secondary);
495
+ --cm-accent: var(--dsw-alias-brand-primary);
496
+ --xy-background-color: transparent; --xy-edge-stroke: var(--cm-text2);
497
+ --xy-edge-stroke-selected: var(--cm-accent); --xy-edge-stroke-width: 2;
498
+ --xy-node-color: var(--cm-text); --xy-handle-background-color: var(--cm-accent);
499
+ --xy-handle-border-color: var(--cm-surface);
500
+ --xy-controls-button-background-color: var(--cm-surface);
501
+ --xy-controls-button-color: var(--cm-text);
502
+ --xy-controls-button-border-color: var(--cm-border);
503
+ --xy-controls-box-shadow: none;
504
+ --xy-minimap-background-color: var(--cm-surface);
505
+ --xy-minimap-mask-background-color: var(--cm-bg);
506
+ --xy-minimap-node-background-color: var(--cm-accent);
507
+ --xy-background-pattern-dots-color-default: var(--cm-border);
508
+ --xy-background-pattern-color: var(--cm-border);
509
+ --xy-attribution-background-color: transparent; }
510
+ @supports (color: color-mix(in srgb, red, blue)) {
511
+ .cm-root { --cm-border-soft: color-mix(in srgb, var(--cm-border) 40%, transparent); }
512
+ }
513
+ .cm-root { box-sizing:border-box; height:100%; display:flex; flex-direction:column;
514
+ width:calc(100% + var(--dsh-scrollbar-width, 5px) + 2px);
515
+ margin-right:calc(-1 * (var(--dsh-scrollbar-width, 5px) + 2px));
516
+ font-family:inherit; color:var(--cm-text); }
517
+ .cm-canvas-tools { position:absolute; top:10px; right:10px; z-index:15;
518
+ display:flex; flex-direction:column; align-items:flex-end; gap:6px; }
519
+ .cm-canvas-tool { box-sizing:border-box; width:28px; height:28px; padding:0; display:flex;
520
+ align-items:center; justify-content:center; border-radius:4px; cursor:pointer;
521
+ border:1px solid var(--cm-border); background:var(--cm-surface); color:var(--cm-text); }
522
+ .cm-theme-panel { position:absolute; right:0; top:34px; z-index:20; width:260px; padding:12px;
523
+ border:1px solid var(--cm-border); border-radius:10px; background:var(--cm-surface);
524
+ box-shadow:0 8px 24px rgba(0,0,0,0.18); }
525
+ .cm-theme-modes { display:grid; grid-template-columns:repeat(2,1fr); gap:6px; }
526
+ .cm-theme-mode { padding:5px 4px; font-size:11px; cursor:pointer; border-radius:5px;
527
+ border:1px solid var(--cm-border); background:transparent; color:var(--cm-text2); }
528
+ .cm-theme-mode.is-active { border-color:var(--cm-accent); color:var(--cm-accent); background:var(--cm-surface2); }
529
+ .cm-theme-colors { display:grid; grid-template-columns:1fr 1fr; gap:7px; margin-top:10px; }
530
+ .cm-theme-color { display:flex; align-items:center; justify-content:space-between; gap:5px;
531
+ font-size:11px; color:var(--cm-text2); }
532
+ .cm-theme-color input { width:30px; height:22px; padding:0; border:1px solid var(--cm-border);
533
+ background:transparent; cursor:pointer; }
534
+ .cm-theme-note { margin-top:9px; font-size:11px; color:var(--cm-text2); line-height:16px; }
535
+ .cm-canvas { position:relative; flex:1 1 auto; min-height:0; width:100%; border:0.5px solid var(--cm-border-soft);
536
+ border-radius:0; overflow:hidden; background:var(--cm-bg); }
537
+ .cm-empty { position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
538
+ font-size:13px; color:var(--cm-text2); pointer-events:none; }
539
+ .cm-node { box-sizing:border-box; width:320px; padding:12px 14px; border-radius:10px;
540
+ background:var(--cm-surface); border:1px solid var(--cm-border);
541
+ color:var(--cm-text); font-family:inherit; }
542
+ .cm-question { border-left:3px solid var(--cm-accent); }
543
+ .cm-answer { border-left:3px solid var(--cm-text2); }
544
+ .cm-branch { border-left:3px dashed var(--cm-accent); background:var(--cm-surface2); }
545
+ .cm-node-head { display:flex; justify-content:space-between; gap:8px; align-items:baseline; }
546
+ .cm-node-title { font-size:12px; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
547
+ .cm-node-time { flex:0 0 auto; font-size:11px; color:var(--cm-text2); font-variant-numeric:tabular-nums; }
548
+ .cm-node-body { margin-top:6px; font-size:12px; line-height:18px; color:var(--cm-text2);
549
+ overflow-wrap:anywhere; display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; overflow:hidden; }
550
+ .cm-node-meta { margin-top:8px; font-size:11px; color:var(--cm-text2); }
551
+ .cm-toggle { margin-top:8px; padding:3px 8px; font-size:11px; cursor:pointer; border-radius:5px;
552
+ border:1px solid var(--cm-border); background:transparent; color:var(--cm-text2); }
553
+ .cm-fork { margin-top:8px; margin-right:6px; padding:3px 8px; font-size:11px; cursor:pointer; border-radius:5px;
554
+ border:1px solid var(--cm-accent); background:transparent; color:var(--cm-accent); }
555
+ .cm-fork:disabled { opacity:0.6; cursor:default; }
556
+ .cm-branch-actions { display:flex; gap:6px; margin-top:8px; }
557
+ .cm-branch-actions .cm-fork, .cm-branch-actions .cm-toggle { margin-top:0; }
558
+ .cm-items { margin-top:8px; max-height:180px; overflow:auto; display:flex; flex-direction:column; gap:6px; }
559
+ .cm-item { padding:5px 7px; border-left:2px solid var(--cm-border2); background:var(--cm-surface2); }
560
+ .cm-item-title { display:block; font-size:11px; font-weight:600; color:var(--cm-text); }
561
+ .cm-item-body { display:block; margin-top:2px; font-size:11px; line-height:15px; color:var(--cm-text2); overflow-wrap:anywhere; }
562
+ .cm-handle { width:7px; height:7px; }
563
+ `
564
+
565
+ function StateFlowView({ useChat, t, openView, fork, branchStore, openSession }) {
566
+ const { fitView } = useReactFlow()
567
+ const [theme, setTheme] = useState(readTheme)
568
+ const [themeOpen, setThemeOpen] = useState(false)
569
+ const changeTheme = (next) => {
570
+ setTheme(next)
571
+ try {
572
+ localStorage.setItem(THEME_KEY, JSON.stringify(next))
573
+ } catch (_error) {
574
+ // The theme still applies for this mount.
575
+ }
576
+ }
577
+ useEffect(() => {
578
+ if (!themeOpen) return undefined
579
+ const close = (event) => {
580
+ if (!event.target.closest || !event.target.closest('.cm-canvas-tool, .cm-theme-panel')) {
581
+ setThemeOpen(false)
582
+ }
583
+ }
584
+ const escape = (event) => {
585
+ if (event.key === 'Escape') setThemeOpen(false)
586
+ }
587
+ window.addEventListener('pointerdown', close)
588
+ window.addEventListener('keydown', escape)
589
+ return () => {
590
+ window.removeEventListener('pointerdown', close)
591
+ window.removeEventListener('keydown', escape)
592
+ }
593
+ }, [themeOpen])
594
+ useEffect(() => {
595
+ const sync = (event) => {
596
+ if (event.key === THEME_KEY) setTheme(readTheme())
597
+ }
598
+ window.addEventListener('storage', sync)
599
+ return () => window.removeEventListener('storage', sync)
600
+ }, [])
601
+ const nodes = useChat(s => s.legacy.nodes) || []
602
+ const partial = useChat(s => s.legacy.partial)
603
+ const runningCalls = useChat(s => s.legacy.runningCalls) || []
604
+ const flows = useMemo(
605
+ () => buildFlows(nodes, partial, runningCalls, t),
606
+ [nodes, partial, runningCalls, t],
607
+ )
608
+ const branches = useSyncExternalStore(branchStore.subscribe, branchStore.getSnapshot)
609
+ const nodeTypes = useMemo(() => ({
610
+ question: QuestionNode, answer: AnswerNode, branch: BranchHeaderNode,
611
+ }), [])
612
+ const computedNodes = useMemo(() => {
613
+ const result = flows.flatMap((flow, index) => {
614
+ const answer = summarize(flow, t)
615
+ const reversed = index % 2 === 1
616
+ const qx = reversed ? 440 : 40
617
+ const ax = reversed ? 40 : 440
618
+ return [
619
+ {
620
+ id: 'q-' + flow.key,
621
+ type: 'question',
622
+ position: { x: qx, y: index * 360 },
623
+ data: {
624
+ title: flow.question.title, body: flow.question.body,
625
+ time: flow.questionTime,
626
+ forkSeq: flow.seq, forkLabel: t('fork.question'),
627
+ onFork: fork, t,
628
+ },
629
+ },
630
+ {
631
+ id: 'a-' + flow.key,
632
+ type: 'answer',
633
+ position: { x: ax, y: index * 360 },
634
+ data: {
635
+ title: answer.title, body: answer.body, meta: answer.meta,
636
+ time: '',
637
+ items: flow.items,
638
+ forkSeq: answer.endSeq, forkLabel: t('fork.answer'),
639
+ onFork: fork, t,
640
+ expandLabel: t('expand') + ' (' + flow.items.length + ')',
641
+ collapseLabel: t('collapse'),
642
+ },
643
+ },
644
+ ]
645
+ })
646
+ branches.forEach((branch, branchIndex) => {
647
+ const x = 900 + branchIndex * 760
648
+ result.push({
649
+ id: 'bh-' + branch.childId,
650
+ type: 'branch',
651
+ position: { x, y: 0 },
652
+ data: {
653
+ title: t('branch.title') + ' ' + String(branchIndex + 1),
654
+ meta: t('branch.meta').replace('{seq}', String(branch.forkedAtSeq)),
655
+ time: timeLabel(branch.createdAt),
656
+ openLabel: t('branch.open'),
657
+ hideLabel: t('branch.hide'),
658
+ onOpen: () => openSession(branch.childId),
659
+ onHide: () => branchStore.remove(branch.childId),
660
+ t,
661
+ },
662
+ })
663
+ branch.flows.forEach((flow, index) => {
664
+ const answer = summarize(flow, t)
665
+ const prefix = 'b-' + branch.childId + '-'
666
+ const reversed = index % 2 === 1
667
+ const qx = reversed ? x + 400 : x
668
+ const ax = reversed ? x : x + 400
669
+ result.push({
670
+ id: prefix + 'q-' + flow.key,
671
+ type: 'question',
672
+ position: { x: qx, y: 120 + index * 360 },
673
+ data: {
674
+ title: flow.question.title, body: flow.question.body,
675
+ time: flow.questionTime, t,
676
+ },
677
+ })
678
+ result.push({
679
+ id: prefix + 'a-' + flow.key,
680
+ type: 'answer',
681
+ position: { x: ax, y: 120 + index * 360 },
682
+ data: {
683
+ title: answer.title, body: answer.body, meta: answer.meta,
684
+ time: '', items: flow.items, t,
685
+ expandLabel: t('expand') + ' (' + flow.items.length + ')',
686
+ collapseLabel: t('collapse'),
687
+ },
688
+ })
689
+ })
690
+ })
691
+ return result
692
+ }, [flows, branches, t, fork, branchStore, openSession])
693
+ const [rfNodes, setRfNodes, onNodesChange] = useNodesState([])
694
+ useEffect(() => {
695
+ setRfNodes((current) => {
696
+ const previous = new Map(current.map(node => [node.id, node]))
697
+ return computedNodes.map((node) => {
698
+ const old = previous.get(node.id)
699
+ return old ? { ...node, position: old.position, selected: old.selected } : node
700
+ })
701
+ })
702
+ }, [computedNodes, setRfNodes])
703
+ const previousCount = useRef(flows.length)
704
+ useEffect(() => {
705
+ if (flows.length > previousCount.current) {
706
+ previousCount.current = flows.length
707
+ const frame = requestAnimationFrame(() => fitView({ padding: 0.18, duration: 300 }))
708
+ return () => cancelAnimationFrame(frame)
709
+ }
710
+ previousCount.current = flows.length
711
+ return undefined
712
+ }, [flows.length, fitView])
713
+ useEffect(() => {
714
+ const refresh = () => branchStore.getSnapshot()
715
+ window.addEventListener('dsh-status-map:branches', refresh)
716
+ return () => window.removeEventListener('dsh-status-map:branches', refresh)
717
+ }, [branchStore])
718
+ const rfEdges = useMemo(() => {
719
+ const edge = (id, source, sourceHandle, target, targetHandle, dashed) => ({
720
+ id, source, sourceHandle, target, targetHandle,
721
+ type: 'smoothstep',
722
+ markerEnd: { type: MarkerType.ArrowClosed },
723
+ ...(dashed ? { style: { stroke: 'var(--dsw-alias-brand-primary)', strokeDasharray: '6 4' } } : {}),
724
+ })
725
+ const result = []
726
+ flows.forEach((flow, index) => {
727
+ const next = flows[index + 1]
728
+ const reversed = index % 2 === 1
729
+ result.push(edge(
730
+ 'qa-' + flow.key, 'q-' + flow.key, reversed ? 'left' : 'right',
731
+ 'a-' + flow.key, reversed ? 'right' : 'left',
732
+ ))
733
+ if (next) {
734
+ result.push(edge('qq-' + flow.key, 'q-' + flow.key, 'down', 'q-' + next.key, 'up'))
735
+ }
736
+ })
737
+ branches.forEach((branch, branchIndex) => {
738
+ const parent = flows.find(flow => flow.seq === branch.forkedAtSeq
739
+ || flow.items.some(item => item.seq === branch.forkedAtSeq))
740
+ if (parent) {
741
+ const sourceId = branch.forkKind === 'question' ? 'q-' + parent.key : 'a-' + parent.key
742
+ const sourceHandle = branch.forkKind === 'question' ? 'right' : 'branch'
743
+ result.push(edge(
744
+ 'link-' + branch.childId, sourceId, sourceHandle,
745
+ 'bh-' + branch.childId, 'left', true,
746
+ ))
747
+ }
748
+ branch.flows.forEach((flow, index) => {
749
+ const prefix = 'b-' + branch.childId + '-'
750
+ const next = branch.flows[index + 1]
751
+ const reversed = index % 2 === 1
752
+ result.push(edge(
753
+ prefix + 'qa-' + flow.key, prefix + 'q-' + flow.key,
754
+ reversed ? 'left' : 'right',
755
+ prefix + 'a-' + flow.key, reversed ? 'right' : 'left',
756
+ ))
757
+ if (next) {
758
+ result.push(edge(
759
+ prefix + 'qq-' + flow.key, prefix + 'q-' + flow.key, 'down',
760
+ prefix + 'q-' + next.key, 'up',
761
+ ))
762
+ }
763
+ })
764
+ })
765
+ return result
766
+ }, [flows, branches])
767
+
768
+ return h('div', { className: 'cm-root', style: themeVariables(theme) },
769
+ h('style', null, flowCss + themeCss),
770
+ h('div', { className: 'cm-canvas' },
771
+ flows.length === 0 && branches.length === 0
772
+ ? h('div', { className: 'cm-empty' }, t('empty'))
773
+ : null,
774
+ h('div', { className: 'cm-canvas-tools' },
775
+ h('button', {
776
+ type: 'button',
777
+ className: 'cm-canvas-tool nodrag',
778
+ title: t('theme.button'),
779
+ 'aria-label': t('theme.button'),
780
+ 'aria-expanded': themeOpen,
781
+ 'aria-controls': 'cm-theme-panel',
782
+ onClick: () => setThemeOpen(value => !value),
783
+ },
784
+ h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', 'aria-hidden': true },
785
+ h('circle', { cx: 6, cy: 6, r: 4, fill: 'var(--cm-accent)' }),
786
+ h('circle', { cx: 10, cy: 10, r: 4, fill: 'var(--cm-text2)', opacity: 0.75 }),
787
+ ),
788
+ ),
789
+ themeOpen ? h(ThemePanel, { theme, onChange: changeTheme, t }) : null,
790
+ ),
791
+ h(ReactFlow, {
792
+ nodes: rfNodes,
793
+ edges: rfEdges,
794
+ onNodesChange,
795
+ nodeTypes,
796
+ fitView: true,
797
+ fitViewOptions: { padding: 0.18 },
798
+ minZoom: 0.1,
799
+ maxZoom: 2,
800
+ nodesDraggable: true,
801
+ edgesFocusable: false,
802
+ proOptions: { hideAttribution: true },
803
+ },
804
+ h(Background, { variant: 'dots', gap: 18, size: 1.5 }),
805
+ h(Controls, { showInteractive: false }),
806
+ h(MiniMap, { pannable: true, zoomable: true }),
807
+ ),
808
+ ),
809
+ )
810
+ }
811
+
812
+ function StateFlowViewOuter(props) {
813
+ return h(ReactFlowProvider, null, h(StateFlowView, props))
814
+ }
815
+
816
+ export function install() {
817
+ const dictionaries = {
818
+ en: {
819
+ 'meta.title': 'Status map',
820
+ 'meta.description': 'Adds a Conversation tab with one node per Q&A, a zoom/pan canvas, side-by-side fork branches, and a per-view theme picker.',
821
+ 'view.statusMap': 'Status map',
822
+ 'theme.button': 'Theme',
823
+ 'theme.system': 'Follow system',
824
+ 'theme.light': 'Light',
825
+ 'theme.dark': 'Dark',
826
+ 'theme.custom': 'Custom',
827
+ 'theme.hint': 'Follow system uses the app theme. Choose Custom to edit colors.',
828
+ 'theme.accent': 'Accent',
829
+ 'theme.background': 'Background',
830
+ 'theme.surface': 'Cards',
831
+ 'theme.surface2': 'Nested',
832
+ 'theme.text': 'Text',
833
+ 'theme.text2': 'Muted text',
834
+ 'node.question': 'Your question',
835
+ 'node.steering': 'Follow-up during turn',
836
+ 'node.answer': 'AI answer',
837
+ 'node.tool': 'Tool',
838
+ 'node.command': 'Command',
839
+ 'node.context': 'Context',
840
+ 'node.error': 'Error',
841
+ 'node.maxTokens': 'Output limit reached',
842
+ 'node.retry': 'Retry',
843
+ 'node.compaction': 'Context compaction',
844
+ 'node.unknown': 'Event',
845
+ 'node.generating': 'Generating\u2026',
846
+ 'node.toolRunning': 'Running tool',
847
+ 'node.fallback': 'Activity',
848
+ 'count.answer': 'answers',
849
+ 'count.tool': 'tools',
850
+ 'count.error': 'errors',
851
+ 'expand': 'Show steps',
852
+ 'collapse': 'Hide steps',
853
+ 'fork.question': 'Continue from here',
854
+ 'fork.answer': 'Continue after this answer',
855
+ 'forking': 'Branching\u2026',
856
+ 'branch.title': 'Branch',
857
+ 'branch.meta': 'forked at seq {seq}',
858
+ 'branch.open': 'Open',
859
+ 'branch.hide': 'Hide',
860
+ 'noWork': 'No answer recorded yet',
861
+ 'empty': 'No conversation content yet',
862
+ },
863
+ zh: {
864
+ 'meta.title': '状态地图',
865
+ 'meta.description': '新增一个对话视图:一次问答一个节点,可缩放平移,分叉分支并列显示,并提供独立的主题切换。',
866
+ 'view.statusMap': '状态地图',
867
+ 'theme.button': '主题',
868
+ 'theme.system': '跟随系统',
869
+ 'theme.light': '浅色',
870
+ 'theme.dark': '深色',
871
+ 'theme.custom': '自定义',
872
+ 'theme.hint': '跟随系统使用软件主题;选择自定义可编辑颜色。',
873
+ 'theme.accent': '强调色',
874
+ 'theme.background': '背景',
875
+ 'theme.surface': '卡片',
876
+ 'theme.surface2': '嵌套层',
877
+ 'theme.text': '文字',
878
+ 'theme.text2': '次要文字',
879
+ 'node.question': '我的提问',
880
+ 'node.steering': '轮次中的追问',
881
+ 'node.answer': 'AI 回答',
882
+ 'node.tool': '工具',
883
+ 'node.command': '命令',
884
+ 'node.context': '上下文',
885
+ 'node.error': '错误',
886
+ 'node.maxTokens': '输出已达上限',
887
+ 'node.retry': '重试',
888
+ 'node.compaction': '上下文压缩',
889
+ 'node.unknown': '事件',
890
+ 'node.generating': '正在生成\u2026',
891
+ 'node.toolRunning': '工具执行中',
892
+ 'node.fallback': '活动',
893
+ 'count.answer': '回答',
894
+ 'count.tool': '工具',
895
+ 'count.error': '错误',
896
+ 'expand': '展开步骤',
897
+ 'collapse': '收起步骤',
898
+ 'fork.question': '从此处继续',
899
+ 'fork.answer': '从此回答后继续',
900
+ 'forking': '正在创建分支\u2026',
901
+ 'branch.title': '分支',
902
+ 'branch.meta': '分叉于 seq {seq}',
903
+ 'branch.open': '打开',
904
+ 'branch.hide': '隐藏',
905
+ 'noWork': '尚无对应回答',
906
+ 'empty': '当前会话还没有内容',
907
+ },
908
+ }
909
+ return {
910
+ inject: ['slots', 'locale', 'sessions', 'uiWorkspace', 'uiConversation'],
911
+ apply(ctx) {
912
+ ctx.effect(() => {
913
+ const disposers = [
914
+ ctx.locale.register(NS, 'en', dictionaries.en),
915
+ ctx.locale.register(NS, 'zh', dictionaries.zh),
916
+ ]
917
+ return () => disposers.forEach(dispose => dispose())
918
+ }, 'dsh-status-map: locale')
919
+ const t = ctx.locale.bind(NS)
920
+ ctx.slots.inject('conversation.view', () => ctx.slots.register({
921
+ name: 'conversation.view',
922
+ id: 'status-map',
923
+ order: 20,
924
+ locale: NS,
925
+ inject: (sessionId) => {
926
+ const branchStore = createBranchStore(ctx, sessionId, t)
927
+ return {
928
+ branchStore,
929
+ openSession: (childId) => ctx.uiWorkspace.openSession(childId),
930
+ fork: async (seq, kind) => {
931
+ if (!isForkableSeq(seq)) return
932
+ const childId = await ctx.sessions.fork({
933
+ sessionId,
934
+ atSeq: seq,
935
+ increaseTitle: true,
936
+ })
937
+ branchStore.add(childId, seq, kind)
938
+ ctx.uiWorkspace.openSession(childId)
939
+ },
940
+ }
941
+ },
942
+ }, StateFlowViewOuter))
943
+ },
944
+ }
945
+ }