dsh-rwkv-plugin 0.0.0-stage → 0.2.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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/cordis.patch.yml +59 -0
  4. package/lib/client.js +3148 -0
  5. package/lib/client.js.map +7 -0
  6. package/lib/index.js +6294 -0
  7. package/lib/index.js.map +7 -0
  8. package/lib/line-edit.js +1423 -0
  9. package/lib/line-edit.js.map +7 -0
  10. package/lib/todo.js +610 -0
  11. package/lib/todo.js.map +7 -0
  12. package/package.json +72 -4
  13. package/scripts/build.mjs +77 -0
  14. package/scripts/headless.ts +279 -0
  15. package/scripts/link-dsh.sh +31 -0
  16. package/scripts/relay-e2e.mjs +157 -0
  17. package/scripts/smoke.ts +116 -0
  18. package/scripts/state.ts +39 -0
  19. package/scripts/tokenizer-parity.ts +107 -0
  20. package/scripts/trace-stats.ts +33 -0
  21. package/src/adapter.ts +388 -0
  22. package/src/backend/generator.ts +221 -0
  23. package/src/backend/irwkv.ts +117 -0
  24. package/src/backend/lightning.ts +228 -0
  25. package/src/backend/stream.ts +97 -0
  26. package/src/client/AdapterPicker.tsx +264 -0
  27. package/src/client/DeveloperPanel.tsx +403 -0
  28. package/src/client/FoldNode.tsx +82 -0
  29. package/src/client/ModelCard.tsx +230 -0
  30. package/src/client/RwkvSettings.tsx +265 -0
  31. package/src/client/Segment.tsx +15 -0
  32. package/src/client/StatePicker.tsx +248 -0
  33. package/src/client/TraceFrames.tsx +462 -0
  34. package/src/client/TraceView.tsx +77 -0
  35. package/src/client/WirePanel.tsx +566 -0
  36. package/src/client/fields.tsx +362 -0
  37. package/src/client/index.tsx +109 -0
  38. package/src/client/styles.ts +277 -0
  39. package/src/client/traces-api.ts +222 -0
  40. package/src/client/url.ts +20 -0
  41. package/src/core/agent.ts +586 -0
  42. package/src/core/defaults.ts +51 -0
  43. package/src/core/dsh-prompt.ts +32 -0
  44. package/src/core/edit-modes/index.ts +108 -0
  45. package/src/core/edit-modes/line-edit.ts +793 -0
  46. package/src/core/edit-modes/literal.ts +26 -0
  47. package/src/core/edit-modes/shared.ts +213 -0
  48. package/src/core/edit-modes/tolerant.ts +558 -0
  49. package/src/core/fold-pairs.ts +407 -0
  50. package/src/core/fold-window.ts +563 -0
  51. package/src/core/line-edit.ts +33 -0
  52. package/src/core/parse.ts +290 -0
  53. package/src/core/policy.ts +500 -0
  54. package/src/core/prompt.ts +220 -0
  55. package/src/core/relay.ts +400 -0
  56. package/src/core/step-gates.ts +371 -0
  57. package/src/core/time-zone.ts +32 -0
  58. package/src/core/todo-state.ts +227 -0
  59. package/src/core/tolerant-edit.ts +14 -0
  60. package/src/core/tool-mappings.ts +209 -0
  61. package/src/core/tool-repairs.ts +255 -0
  62. package/src/core/tools.ts +162 -0
  63. package/src/core/worklist.ts +606 -0
  64. package/src/dsh-host.ts +48 -0
  65. package/src/edit-modes/folded-read-guard.ts +32 -0
  66. package/src/edit-modes/index.ts +26 -0
  67. package/src/edit-modes/line-edit.ts +154 -0
  68. package/src/edit-modes/literal.ts +9 -0
  69. package/src/edit-modes/observations.ts +234 -0
  70. package/src/edit-modes/syntax-check.ts +226 -0
  71. package/src/edit-modes/tolerant.ts +232 -0
  72. package/src/folded-read-guard.ts +6 -0
  73. package/src/history.ts +163 -0
  74. package/src/index.ts +287 -0
  75. package/src/line-edit.ts +15 -0
  76. package/src/live-wire.ts +133 -0
  77. package/src/paths.ts +91 -0
  78. package/src/relay-store.ts +59 -0
  79. package/src/result-budget.ts +225 -0
  80. package/src/routes.ts +324 -0
  81. package/src/session-setup.ts +150 -0
  82. package/src/syntax-check.ts +2 -0
  83. package/src/todo.ts +328 -0
  84. package/src/tokenizer.ts +48 -0
  85. package/src/tolerant-edit.ts +2 -0
  86. package/src/trace-stats.ts +225 -0
  87. package/src/traces.ts +289 -0
  88. package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
  89. package/vendor/rwkv-tokenizer/package.json +5 -0
  90. package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
  91. package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
  92. package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
@@ -0,0 +1,566 @@
1
+ // Right-sidebar panel: live character-level RWKV wire context viewer.
2
+ // Connects via SSE (`/api/rwkv/live/<session>`) to display either:
3
+ // - "模型实时" (exact prompt the model currently sees, with empty historical
4
+ // thinks and folded `[Old ...]` placeholders), or
5
+ // - "全量历史" (full unfolded history with faded past thoughts).
6
+ // Every block is a clickable card (click to expand/collapse, drag-to-select
7
+ // safe), with a global toolbar toggle to pretty-print JSON in tool calls,
8
+ // tool responses, and System tool-format templates (raw by default).
9
+
10
+ import { useEffect, useMemo, useRef, useState } from 'react'
11
+ import { ctxTier, foldKindLabel, formatTokens, type ContextFoldTrace } from './traces-api.ts'
12
+
13
+ export const WIRE_TAB_ID = 'rwkv-wire'
14
+
15
+ const LONG_BLOCK_CHARS = 480
16
+ const LONG_BLOCK_LINES = 6
17
+
18
+ type ViewMode = 'model' | 'full'
19
+
20
+ interface LiveWireSnapshot {
21
+ readonly sessionId: string
22
+ readonly model: string
23
+ readonly stage: 'decision' | 'answer' | 'card' | 'idle'
24
+ readonly streaming: boolean
25
+ readonly prompt: string
26
+ readonly fullPrompt?: string
27
+ readonly promptTokens: number
28
+ readonly blockTokens?: readonly number[]
29
+ readonly fullBlockTokens?: readonly number[]
30
+ readonly pastThinks?: readonly string[]
31
+ readonly output: string
32
+ readonly outputTokens: number
33
+ readonly fold?: ContextFoldTrace
34
+ readonly updatedAt: string
35
+ }
36
+
37
+ type SpanKind = 'plain' | 'label' | 'think' | 'think-past' | 'think-empty' | 'tool-call' | 'tool-result' | 'tool-error' | 'folded'
38
+ type RoleKind = 'system' | 'user' | 'assistant' | 'tool' | 'other'
39
+ type CardKind = 'system' | 'user' | 'assistant' | 'tool' | 'error' | 'folded' | 'other'
40
+
41
+ interface InlineSpan {
42
+ readonly kind: SpanKind
43
+ readonly text: string
44
+ readonly title?: string
45
+ }
46
+
47
+ interface WireBlock {
48
+ readonly role: RoleKind
49
+ readonly cardKind: CardKind
50
+ readonly raw: string
51
+ readonly spans: readonly InlineSpan[]
52
+ }
53
+
54
+ /** Splits a block's text into lossless inline spans with background color tags. */
55
+ function tokenizeBody(
56
+ text: string,
57
+ role: RoleKind,
58
+ options: { readonly isPastAssistant: boolean; readonly pastThink?: string; readonly fillPastThink: boolean },
59
+ ): InlineSpan[] {
60
+ const spans: InlineSpan[] = []
61
+ let i = 0
62
+ let usedPastThink = false
63
+ const push = (kind: SpanKind, slice: string, title?: string) => {
64
+ if (slice === '') return
65
+ const prev = spans[spans.length - 1]
66
+ if (prev !== undefined && prev.kind === kind && prev.title === title) {
67
+ spans[spans.length - 1] = { kind, text: prev.text + slice, ...(title === undefined ? {} : { title }) }
68
+ } else {
69
+ spans.push({ kind, text: slice, ...(title === undefined ? {} : { title }) })
70
+ }
71
+ }
72
+
73
+ const prefixMatch = /^(System:|User:|Assistant:|Tool:)/.exec(text)
74
+ if (prefixMatch !== null) {
75
+ push('label', prefixMatch[0])
76
+ i = prefixMatch[0].length
77
+ }
78
+
79
+ if (role === 'system') {
80
+ push('plain', text.slice(i))
81
+ return spans
82
+ }
83
+
84
+ const TAG_RE = /<think>|<tool_call>|<tool_response>/g
85
+ while (i < text.length) {
86
+ TAG_RE.lastIndex = i
87
+ const match = TAG_RE.exec(text)
88
+ if (match === null) {
89
+ const rest = text.slice(i)
90
+ const openThinkIdx = rest.indexOf('<think')
91
+ if (openThinkIdx >= 0 && openThinkIdx === rest.length - '<think'.length) {
92
+ push('plain', rest.slice(0, openThinkIdx))
93
+ push('think', rest.slice(openThinkIdx))
94
+ } else {
95
+ push('plain', rest)
96
+ }
97
+ break
98
+ }
99
+ if (match.index > i) {
100
+ push('plain', text.slice(i, match.index))
101
+ }
102
+ const openTag = match[0]
103
+ const closeTag = openTag === '<think>' ? '</think>'
104
+ : openTag === '<tool_call>' ? '</tool_call>'
105
+ : '</tool_response>'
106
+ const closeIdx = text.indexOf(closeTag, match.index + openTag.length)
107
+ const endIdx = closeIdx >= 0 ? closeIdx + closeTag.length : text.length
108
+ const chunk = text.slice(match.index, endIdx)
109
+
110
+ if (openTag === '<think>') {
111
+ const inner = closeIdx >= 0 ? text.slice(match.index + openTag.length, closeIdx).trim() : 'streaming'
112
+ if (inner === '' && options.fillPastThink && !usedPastThink && options.pastThink) {
113
+ usedPastThink = true
114
+ push('think-past', `<think>${options.pastThink}</think>`, '历史思考(未回传给模型,仅全量历史展示)')
115
+ } else if (inner === '') {
116
+ push('think-empty', chunk)
117
+ } else if (options.isPastAssistant) {
118
+ push('think-past', chunk, '历史思考(模型实时视图中置空)')
119
+ } else {
120
+ push('think', chunk)
121
+ }
122
+ } else if (openTag === '<tool_call>') {
123
+ push('tool-call', chunk)
124
+ } else {
125
+ const isFolded = chunk.includes('[Old ')
126
+ const isError = /"ok"\s*:\s*false/.test(chunk)
127
+ push(isFolded ? 'folded' : isError ? 'tool-error' : 'tool-result', chunk)
128
+ }
129
+ i = endIdx
130
+ }
131
+ return spans
132
+ }
133
+
134
+ /** Losslessly splits the raw RWKV wire string into role-tagged block cards. */
135
+ function parseWireBlocks(raw: string, mode: ViewMode, pastThinks?: readonly string[]): WireBlock[] {
136
+ if (raw === '') return []
137
+ const splitRe = /(?=\n\n(?:System:|User:|Assistant:|Tool:))/g
138
+ const parts = raw.split(splitRe)
139
+ const assistantCount = parts.filter(part => part.replace(/^\n+/, '').startsWith('Assistant:')).length
140
+ const historyAssistants = Math.max(0, assistantCount - 1)
141
+ const pastOffset = pastThinks && pastThinks.length > historyAssistants ? pastThinks.length - historyAssistants : 0
142
+ let assistantSeen = 0
143
+ return parts.map(part => {
144
+ const trimmed = part.replace(/^\n+/, '')
145
+ const role: RoleKind = trimmed.startsWith('System:') ? 'system'
146
+ : trimmed.startsWith('User:') ? 'user'
147
+ : trimmed.startsWith('Assistant:') ? 'assistant'
148
+ : trimmed.startsWith('Tool:') ? 'tool'
149
+ : 'other'
150
+ let isPastAssistant = false
151
+ let pastThink: string | undefined
152
+ if (role === 'assistant') {
153
+ isPastAssistant = assistantSeen < historyAssistants
154
+ if (isPastAssistant && mode === 'full' && pastThinks !== undefined) {
155
+ pastThink = pastThinks[pastOffset + assistantSeen]
156
+ }
157
+ assistantSeen++
158
+ }
159
+ const spans = tokenizeBody(trimmed, role, {
160
+ isPastAssistant,
161
+ ...(pastThink === undefined ? {} : { pastThink }),
162
+ fillPastThink: mode === 'full',
163
+ })
164
+ const hasFolded = spans.some(s => s.kind === 'folded')
165
+ const hasError = spans.some(s => s.kind === 'tool-error')
166
+ const hasResult = spans.some(s => s.kind === 'tool-result')
167
+ const cardKind: CardKind = role === 'system' ? 'system'
168
+ : hasFolded ? 'folded'
169
+ : hasError ? 'error'
170
+ : hasResult || role === 'tool' ? 'tool'
171
+ : role
172
+ return {
173
+ role,
174
+ cardKind,
175
+ raw: trimmed,
176
+ spans,
177
+ }
178
+ })
179
+ }
180
+
181
+ /** Pretty-prints JSON inside `<tool_call>` / `<tool_response>` and System tool templates. */
182
+ function prettyJsonObject(rawJson: string): string {
183
+ try {
184
+ const parsed = JSON.parse(rawJson) as Record<string, unknown>
185
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
186
+ const multilineKey = typeof parsed.result === 'string' && parsed.result.includes('\n') ? 'result'
187
+ : typeof parsed.error === 'string' && parsed.error.includes('\n') ? 'error'
188
+ : undefined
189
+ if (multilineKey !== undefined) {
190
+ const textVal = parsed[multilineKey] as string
191
+ const rest = Object.fromEntries(Object.entries(parsed).filter(([k]) => k !== multilineKey))
192
+ const head = JSON.stringify(rest, null, 2)
193
+ const indented = textVal.split('\n').map(line => ` ${line}`).join('\n')
194
+ return head === '{}'
195
+ ? `{\n "${multilineKey}": """\n${indented}\n """\n}`
196
+ : `${head.slice(0, -1).trimEnd()},\n "${multilineKey}": """\n${indented}\n """\n}`
197
+ }
198
+ }
199
+ return JSON.stringify(parsed, null, 2)
200
+ } catch {
201
+ return rawJson
202
+ }
203
+ }
204
+
205
+ function prettySystemText(text: string): string {
206
+ // Format `<tool_call>{...}</tool_call>` and inline JSON templates like `{"name":"...","arguments":{...}}`.
207
+ return text.replace(/<tool_call>(\{[^\n]*\})<\/tool_call>/g, (full, json: string) => {
208
+ const formatted = prettyJsonObject(json)
209
+ return formatted === json ? full : `<tool_call>\n${formatted}\n</tool_call>`
210
+ }).replace(/(^|\n)([ \t]*)(\{"name":[^\n]+\})(?=\n|$)/g, (full, lead: string, indent: string, json: string) => {
211
+ const formatted = prettyJsonObject(json)
212
+ if (formatted === json) return full
213
+ const indented = formatted.split('\n').map(line => `${indent}${line}`).join('\n')
214
+ return `${lead}${indented}`
215
+ })
216
+ }
217
+
218
+ function prettySpanText(span: InlineSpan, role: RoleKind): string {
219
+ if (role === 'system' && span.kind === 'plain') return prettySystemText(span.text)
220
+ if (span.kind !== 'tool-call' && span.kind !== 'tool-result' && span.kind !== 'tool-error' && span.kind !== 'folded') return span.text
221
+ const tag = span.kind === 'tool-call' ? 'tool_call' : 'tool_response'
222
+ const open = `<${tag}>`
223
+ const close = `</${tag}>`
224
+ if (!span.text.startsWith(open) || !span.text.endsWith(close)) return span.text
225
+ const inner = span.text.slice(open.length, span.text.length - close.length).trim()
226
+ const formatted = prettyJsonObject(inner)
227
+ return formatted === inner ? span.text : `${open}\n${formatted}\n${close}`
228
+ }
229
+
230
+ function isLongBlock(raw: string): boolean {
231
+ if (raw.length > LONG_BLOCK_CHARS) return true
232
+ let lines = 1
233
+ for (let i = 0; i < raw.length; i++) {
234
+ if (raw.charCodeAt(i) === 10 && ++lines > LONG_BLOCK_LINES) return true
235
+ }
236
+ return false
237
+ }
238
+
239
+ function TokChevron(props: { open: boolean }) {
240
+ return (
241
+ <svg
242
+ className={props.open ? 'rw-tok-chevron rw-tok-chevron-open' : 'rw-tok-chevron'}
243
+ width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden="true"
244
+ >
245
+ <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
246
+ </svg>
247
+ )
248
+ }
249
+
250
+ function CardTokBadge(props: {
251
+ tokens: number | undefined
252
+ collapsible: boolean
253
+ expanded: boolean
254
+ floating?: boolean
255
+ onToggle?: () => void
256
+ }) {
257
+ if (props.tokens === undefined && !props.collapsible) return null
258
+ const text = props.tokens !== undefined ? `${formatTokens(props.tokens)} tok` : (props.expanded ? '收起' : '展开')
259
+ const title = props.collapsible
260
+ ? `${props.tokens !== undefined ? `${props.tokens.toLocaleString()} RWKV token · ` : ''}${props.expanded ? '点击收起' : '点击展开全部'}`
261
+ : `${props.tokens?.toLocaleString()} RWKV token`
262
+ if (!props.collapsible) {
263
+ return (
264
+ <span className={props.floating ? 'rw-card-tok rw-card-tok-float' : 'rw-card-tok'} title={title}>
265
+ {text}
266
+ </span>
267
+ )
268
+ }
269
+ const cls = props.floating
270
+ ? (props.expanded ? 'rw-card-tok rw-card-tok-btn rw-card-tok-sticky' : 'rw-card-tok rw-card-tok-btn rw-card-tok-float')
271
+ : 'rw-card-tok rw-card-tok-btn'
272
+ return (
273
+ <button
274
+ type="button"
275
+ className={cls}
276
+ aria-expanded={props.expanded}
277
+ title={title}
278
+ onClick={event => {
279
+ event.stopPropagation()
280
+ props.onToggle?.()
281
+ }}
282
+ >
283
+ <span>{text}</span>
284
+ <TokChevron open={props.expanded} />
285
+ </button>
286
+ )
287
+ }
288
+
289
+ const RWKV_LOGO_PIXELS: readonly (readonly [number, number])[] = [
290
+ [133.4, 310.04], [192.28, 310.04], [251.16, 310.04], [310.04, 310.04],
291
+ [133.4, 368.92], [368.92, 368.92], [486.68, 368.92],
292
+ [133.4, 427.8], [368.92, 427.8], [545.56, 427.8],
293
+ [133.4, 486.68], [192.28, 486.68], [251.16, 486.68], [310.04, 486.68], [604.44, 486.68],
294
+ [133.4, 545.56], [251.16, 545.56], [545.56, 545.56],
295
+ [133.4, 604.44], [310.04, 604.44], [486.68, 604.44],
296
+ [133.4, 663.32], [368.92, 663.32], [722.2, 663.32], [781.08, 663.32], [839.96, 663.32],
297
+ ]
298
+
299
+ export function RwkvWireIcon() {
300
+ return (
301
+ <svg width="22" height="22" viewBox="0 0 1024 1024" fill="none" aria-hidden="true">
302
+ <rect x="40.96" y="40.96" width="942.08" height="942.08" rx="188.42" fill="#18181B" />
303
+ <g fill="#FFFFFF">
304
+ {RWKV_LOGO_PIXELS.map(([x, y], index) => (
305
+ <rect key={index} x={x} y={y} width="54" height="54" rx="11" />
306
+ ))}
307
+ </g>
308
+ </svg>
309
+ )
310
+ }
311
+
312
+ export function RwkvWirePanel(props: { session?: string; sessionId?: string }) {
313
+ const session = props.session ?? props.sessionId ?? ''
314
+ const [snapshot, setSnapshot] = useState<LiveWireSnapshot | undefined>()
315
+ const [connected, setConnected] = useState(false)
316
+ const [mode, setMode] = useState<ViewMode>('model')
317
+ const [prettyAll, setPrettyAll] = useState(false)
318
+ const [expandAll, setExpandAll] = useState(false)
319
+ const [autoScroll, setAutoScroll] = useState(true)
320
+ const [copied, setCopied] = useState(false)
321
+ const [expanded, setExpanded] = useState<Readonly<Record<string, boolean>>>({})
322
+ const scrollRef = useRef<HTMLDivElement>(null)
323
+
324
+ useEffect(() => {
325
+ setSnapshot(undefined)
326
+ setExpandAll(false)
327
+ setExpanded({})
328
+ if (!session) return
329
+ const url = `/api/rwkv/live/${encodeURIComponent(session)}`
330
+ const source = new EventSource(url)
331
+ source.onopen = () => setConnected(true)
332
+ source.onerror = () => setConnected(false)
333
+ source.addEventListener('snapshot', event => {
334
+ try {
335
+ const next = JSON.parse((event as MessageEvent).data as string) as LiveWireSnapshot
336
+ setSnapshot(next)
337
+ } catch {
338
+ // Ignore malformed frame.
339
+ }
340
+ })
341
+ source.addEventListener('delta', event => {
342
+ try {
343
+ const payload = JSON.parse((event as MessageEvent).data as string) as { text: string }
344
+ setSnapshot(current => current === undefined ? current : { ...current, streaming: true, output: current.output + payload.text })
345
+ } catch {
346
+ // Ignore malformed frame.
347
+ }
348
+ })
349
+ source.addEventListener('done', event => {
350
+ try {
351
+ const payload = JSON.parse((event as MessageEvent).data as string) as { output: string; outputTokens: number; updatedAt: string }
352
+ setSnapshot(current => current === undefined ? current : {
353
+ ...current,
354
+ streaming: false,
355
+ output: payload.output,
356
+ outputTokens: payload.outputTokens,
357
+ updatedAt: payload.updatedAt,
358
+ })
359
+ } catch {
360
+ // Ignore malformed frame.
361
+ }
362
+ })
363
+ return () => {
364
+ source.close()
365
+ setConnected(false)
366
+ }
367
+ }, [session])
368
+
369
+ const activePrompt = snapshot
370
+ ? (mode === 'full' && snapshot.fullPrompt ? snapshot.fullPrompt : snapshot.prompt)
371
+ : ''
372
+ const activeBlockTokens = snapshot
373
+ ? (mode === 'full' && snapshot.fullBlockTokens ? snapshot.fullBlockTokens : snapshot.blockTokens)
374
+ : undefined
375
+ const fullWire = snapshot ? `${activePrompt}${snapshot.output}` : ''
376
+ const blocks = useMemo(() => parseWireBlocks(fullWire, mode, snapshot?.pastThinks), [fullWire, mode, snapshot?.pastThinks])
377
+
378
+ useEffect(() => {
379
+ if (!autoScroll) return
380
+ const el = scrollRef.current
381
+ if (el !== null) el.scrollTop = el.scrollHeight
382
+ }, [fullWire, autoScroll])
383
+
384
+ const onScroll = () => {
385
+ const el = scrollRef.current
386
+ if (el === null) return
387
+ const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 36
388
+ if (!nearBottom && autoScroll) setAutoScroll(false)
389
+ else if (nearBottom && !autoScroll) setAutoScroll(true)
390
+ }
391
+
392
+ const copyRaw = () => {
393
+ if (!fullWire) return
394
+ void navigator.clipboard?.writeText(fullWire).then(() => {
395
+ setCopied(true)
396
+ setTimeout(() => setCopied(false), 1500)
397
+ })
398
+ }
399
+
400
+ const toggleCard = (key: string) => {
401
+ if (window.getSelection()?.toString()) return
402
+ setExpanded(cur => ({ ...cur, [key]: !(cur[key] ?? expandAll) }))
403
+ }
404
+
405
+ const toggleExpandAll = () => {
406
+ setExpandAll(v => !v)
407
+ setExpanded({})
408
+ }
409
+
410
+ const tokens = snapshot?.promptTokens ?? 0
411
+ const tier = ctxTier(tokens)
412
+
413
+ return (
414
+ <div className="rw-root">
415
+ <div className="rw-toolbar">
416
+ {tokens > 0 ? (
417
+ <span
418
+ className={`rl-ctx rl-ctx-${tier} rw-ctx-pill`}
419
+ title={`${snapshot?.streaming ? '实时生成中' : '已同步'} · 模型实时上下文 ${tokens.toLocaleString()} RWKV token`}
420
+ >
421
+ <span className={snapshot?.streaming ? 'rw-dot rw-dot-live' : connected ? 'rw-dot rw-dot-idle' : 'rw-dot'} />
422
+ <span>{formatTokens(tokens)}</span>
423
+ </span>
424
+ ) : (
425
+ <span className="rw-status">
426
+ <span className={connected ? 'rw-dot rw-dot-idle' : 'rw-dot'} />
427
+ <span>等待请求</span>
428
+ </span>
429
+ )}
430
+ {snapshot?.fold ? (
431
+ <span
432
+ className="rl-cut"
433
+ title={`${foldKindLabel(snapshot.fold.kind)}:${snapshot.fold.beforeTokens.toLocaleString()} → ${snapshot.fold.afterTokens.toLocaleString()} tok`}
434
+ >
435
+ <svg width="11" height="11" viewBox="0 0 14 14" fill="none" aria-hidden="true" style={{ marginRight: 3, verticalAlign: '-1.5px' }}>
436
+ <path d="M4.5 2.5L7 5L9.5 2.5M4.5 11.5L7 9L9.5 11.5M2.5 7H11.5" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round" />
437
+ </svg>
438
+ {formatTokens(snapshot.fold.beforeTokens)}→{formatTokens(snapshot.fold.afterTokens)}
439
+ </span>
440
+ ) : null}
441
+ <div className="rw-controls">
442
+ <span className="rw-mode-seg" role="group" aria-label="上下文视图模式">
443
+ <button type="button" className="rw-mode-btn" aria-pressed={mode === 'model'} onClick={() => setMode('model')} title="严格显示当前模型实际看得见的内容(含空思考与折叠占位)">
444
+ 模型实时
445
+ </button>
446
+ <button type="button" className="rw-mode-btn" aria-pressed={mode === 'full'} onClick={() => setMode('full')} title="完整回溯视角:显示全部历史思考与被折叠的工具结果">
447
+ 全量历史
448
+ </button>
449
+ </span>
450
+ <button
451
+ type="button"
452
+ className="rl-toggle"
453
+ aria-pressed={expandAll}
454
+ title={expandAll ? '收起全部长卡片与 System' : '展开全部长卡片与 System'}
455
+ onClick={toggleExpandAll}
456
+ >
457
+ {expandAll ? '收起' : '全展'}
458
+ </button>
459
+ <button
460
+ type="button"
461
+ className="rl-toggle"
462
+ aria-pressed={prettyAll}
463
+ title="全局美化 System 工具模板与工具调用/结果 JSON(默认显示原始紧凑文本)"
464
+ onClick={() => setPrettyAll(v => !v)}
465
+ >
466
+ 美化
467
+ </button>
468
+ <button type="button" className="rl-toggle" aria-pressed={autoScroll} onClick={() => setAutoScroll(v => !v)}>
469
+ 跟底
470
+ </button>
471
+ <button type="button" className="rl-toggle" disabled={!fullWire} onClick={copyRaw}>
472
+ {copied ? '已复制' : '复制'}
473
+ </button>
474
+ </div>
475
+ </div>
476
+
477
+ <div className="rw-legend">
478
+ <span className="rw-swatch rw-swatch-user">User</span>
479
+ <span className="rw-swatch rw-swatch-assistant">Assistant</span>
480
+ <span className="rw-swatch rw-swatch-think">Think</span>
481
+ <span className="rw-swatch rw-swatch-call">Tool Call</span>
482
+ <span className="rw-swatch rw-swatch-result">Tool Result</span>
483
+ <span className="rw-swatch rw-swatch-error">Error</span>
484
+ <span className="rw-swatch rw-swatch-folded">Folded</span>
485
+ </div>
486
+
487
+ {!snapshot ? (
488
+ <div className="rw-empty">
489
+ <p className="rl-empty">发一条 RWKV 消息后,这里会实时逐字展示发给模型的原始字符级上下文。</p>
490
+ </div>
491
+ ) : (
492
+ <div ref={scrollRef} className="rw-scroll" onScroll={onScroll}>
493
+ <div className="rw-blocks">
494
+ {blocks.map((block, blockIdx) => {
495
+ const key = `${mode}-${blockIdx}`
496
+ const isLast = blockIdx === blocks.length - 1
497
+ const isLiveTail = isLast && snapshot.streaming
498
+ const baseBlockTok = activeBlockTokens?.[blockIdx]
499
+ const cardTokens = baseBlockTok === undefined
500
+ ? undefined
501
+ : isLast ? baseBlockTok + snapshot.outputTokens : baseBlockTok
502
+
503
+ if (block.role === 'system') {
504
+ const open = expanded[key] ?? expandAll
505
+ if (!open) {
506
+ const firstLine = block.raw.split('\n')[0]?.slice(0, 72) ?? 'System:'
507
+ return (
508
+ <div
509
+ key={key}
510
+ className="rw-card rw-card-system rw-system-collapsed"
511
+ >
512
+ <span className="rw-span-label">System:</span>
513
+ <span className="rw-system-preview">{firstLine.replace(/^System:\s*/, '')}…</span>
514
+ <CardTokBadge tokens={cardTokens} collapsible expanded={false} onToggle={() => toggleCard(key)} />
515
+ </div>
516
+ )
517
+ }
518
+ return (
519
+ <div key={key} className="rw-card rw-card-system">
520
+ <div className="rw-card-content">
521
+ <div className="rw-card-body">
522
+ <CardTokBadge tokens={cardTokens} collapsible expanded floating onToggle={() => toggleCard(key)} />
523
+ {block.spans.map((span, spanIdx) => (
524
+ <span key={spanIdx} className={`rw-span rw-span-${span.kind}`} title={span.title}>
525
+ {prettyAll ? prettySpanText(span, block.role) : span.text}
526
+ </span>
527
+ ))}
528
+ </div>
529
+ </div>
530
+ </div>
531
+ )
532
+ }
533
+
534
+ const renderedSpans = prettyAll
535
+ ? block.spans.map(span => ({ ...span, text: prettySpanText(span, block.role) }))
536
+ : block.spans
537
+ const renderedText = prettyAll ? renderedSpans.map(s => s.text).join('') : block.raw
538
+ const collapsible = !isLiveTail && isLongBlock(renderedText)
539
+ const isCollapsed = collapsible && !(expanded[key] ?? expandAll)
540
+
541
+ return (
542
+ <div key={key} className={`rw-card rw-card-${block.cardKind}`}>
543
+ <div className="rw-card-content">
544
+ <div className={isCollapsed ? 'rw-card-body rw-card-hardcut' : 'rw-card-body'}>
545
+ <CardTokBadge
546
+ tokens={cardTokens}
547
+ collapsible={collapsible}
548
+ expanded={!isCollapsed}
549
+ floating
550
+ onToggle={() => toggleCard(key)}
551
+ />
552
+ {renderedSpans.map((span, spanIdx) => (
553
+ <span key={spanIdx} className={`rw-span rw-span-${span.kind}`} title={span.title}>{span.text}</span>
554
+ ))}
555
+ {isLiveTail ? <span className="rw-cursor" aria-hidden="true">▍</span> : null}
556
+ </div>
557
+ </div>
558
+ </div>
559
+ )
560
+ })}
561
+ </div>
562
+ </div>
563
+ )}
564
+ </div>
565
+ )
566
+ }