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,462 @@
1
+ // One session's raw trace as a ledger in the style of DSH's Trajectory view:
2
+ // a row per generation (kind tag, one-line preview, repair chips), a thin row
3
+ // per DSH request saying what was handed to DSH, a rail with request labels,
4
+ // and an inspector panel for the selected generation. Shared by the RWKV
5
+ // conversation tab and the developer section of the settings page.
6
+
7
+ import { useEffect, useState } from 'react'
8
+ import {
9
+ ctxTier,
10
+ fetchRecord,
11
+ foldDetailText,
12
+ foldKindLabel,
13
+ formatTokens,
14
+ isCard,
15
+ isGeneration,
16
+ OUTCOME_LABEL,
17
+ REPAIR_LABEL,
18
+ touched,
19
+ type ArgumentChange,
20
+ type ContextFoldTrace,
21
+ type TraceRecord,
22
+ } from './traces-api.ts'
23
+
24
+ const SHORT_VALUE = 16
25
+ const MAX_CHANGES = 3
26
+
27
+ function valueText(value: unknown): string {
28
+ return typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value) ?? String(value)
29
+ }
30
+
31
+ /** One change in a few characters: offset 0→1, −include, +description, old_text→old_string, file_path 已改. */
32
+ function changeText(change: ArgumentChange): string {
33
+ switch (change.kind) {
34
+ case 'removed': return `−${change.key}`
35
+ case 'added': return `+${change.key}`
36
+ case 'renamed': return `${change.from}→${change.key}`
37
+ case 'changed': {
38
+ const before = valueText(change.before)
39
+ const after = valueText(change.after)
40
+ return before.length + after.length > SHORT_VALUE * 2 ? `${change.key} 已改` : `${change.key} ${before}→${after}`
41
+ }
42
+ }
43
+ }
44
+
45
+ function changeTitle(change: ArgumentChange): string {
46
+ switch (change.kind) {
47
+ case 'removed': return `删掉 ${change.key}=${valueText(change.before)}`
48
+ case 'added': return `补上 ${change.key}=${valueText(change.after)}`
49
+ case 'renamed': return `参数名 ${change.from} 改成 ${change.key}`
50
+ case 'changed': return `${change.key}:${valueText(change.before)} → ${valueText(change.after)}`
51
+ }
52
+ }
53
+
54
+ /** The DSH request line: what DSH got, and only the fields the plugin changed. */
55
+ function HandedLine(props: { record: TraceRecord }) {
56
+ const { record } = props
57
+ const changes = record.changes ?? []
58
+ const decision = (record.decision ?? '').replace(/^tool /, '')
59
+ return (
60
+ <span className="rl-step" title="交给 DSH">
61
+ <svg className="rl-step-arrow" width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
62
+ <path d="M2.5 2V6.5C2.5 7.05228 2.94772 7.5 3.5 7.5H9.5M9.5 7.5L7.25 5.25M9.5 7.5L7.25 9.75" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
63
+ </svg>
64
+ <code>{decision}</code>
65
+ {changes.slice(0, MAX_CHANGES).map((change, index) => (
66
+ <span key={index} className="rl-change" title={changeTitle(change)}>{changeText(change)}</span>
67
+ ))}
68
+ {record.changes === undefined ? (record.repairs ?? []).map(repair => (
69
+ // Records written before the changes field: name the repairs instead.
70
+ <span key={repair} className="rl-change" title={repair}>{REPAIR_LABEL[repair] ?? repair}</span>
71
+ )) : null}
72
+ {changes.length > MAX_CHANGES ? <span className="rl-change" title={changes.slice(MAX_CHANGES).map(changeTitle).join('\n')}>+{changes.length - MAX_CHANGES}</span> : null}
73
+ {record.attempts && record.attempts > 1 ? <span className="rl-step-note">生成 {record.attempts} 次</span> : null}
74
+ </span>
75
+ )
76
+ }
77
+
78
+ /** Short tag per outcome, like the native role tags. */
79
+ const OUTCOME_TAG: Record<string, string> = {
80
+ 'card': '写卡',
81
+ 'card-empty': '空卡',
82
+ 'card-failed': '卡失败',
83
+ 'run': '调用',
84
+ 'final': '作答',
85
+ 're-ask': '重问',
86
+ 'duplicate-retry': '重复',
87
+ 'closeout': '收尾',
88
+ 'rejected unknown-tool': '拒绝',
89
+ 'rejected blocked': '拒绝',
90
+ 'empty-exit': '空答',
91
+ 'raw': '原样',
92
+ }
93
+
94
+ type Tone = 'clean' | 'touched' | 'error' | 'neutral'
95
+
96
+ function toneOf(record: TraceRecord): Tone {
97
+ if (record.outcome === undefined) return 'neutral'
98
+ if (record.outcome === 'raw' || record.outcome.startsWith('rejected')) return 'error'
99
+ return touched(record) ? 'touched' : 'clean'
100
+ }
101
+
102
+ /** The part after a leading think block. */
103
+ function afterThink(output: string): string {
104
+ const text = output.trimStart()
105
+ if (!text.startsWith('<think')) return text
106
+ const end = text.indexOf('</think>')
107
+ return end < 0 ? '' : text.slice(end + '</think>'.length).trim()
108
+ }
109
+
110
+ function thinkOf(output: string): string {
111
+ const text = output.trimStart()
112
+ if (!text.startsWith('<think')) return ''
113
+ const end = text.indexOf('</think>')
114
+ return text.slice(text.indexOf('>') + 1, end < 0 ? undefined : end).trim()
115
+ }
116
+
117
+ /** The cut a handoff card or stateful worklist checkpoint makes on THIS step. */
118
+ function CutNote(props: { record: TraceRecord; worklistFold?: { fromTokens?: number; toTokens: number } | undefined }) {
119
+ const relay = props.record.relay
120
+ const wl = props.record.worklist
121
+ const fold = props.worklistFold
122
+ return (
123
+ <>
124
+ {relay !== undefined ? (
125
+ <span className="rl-cut" title={`第 ${relay.from}–${relay.to - 1} 条历史(用户第 ${relay.turn} 轮,共 ${relay.to - relay.from} 条)被这张卡替换;此前的调用与结果不再逐条可见`}>
126
+ ✂ 压缩 {relay.to - relay.from} 条历史 · 第 {relay.turn} 轮
127
+ </span>
128
+ ) : null}
129
+ {fold !== undefined ? (
130
+ <span
131
+ className="rl-cut"
132
+ title={`上一步写入工单 note 后,本步折叠了早期探索输出(提示词 ${fold.fromTokens !== undefined ? `${fold.fromTokens} → ` : ''}${fold.toTokens} token)`}
133
+ >
134
+ ✂ 本步折叠 · {fold.fromTokens !== undefined ? `${fold.fromTokens}→${fold.toTokens}` : fold.toTokens} tok
135
+ </span>
136
+ ) : null}
137
+ {wl !== undefined && wl.nudged ? (
138
+ <span className="rl-chip rl-chip-warn" title={`当前提示词 ${wl.promptTokens} token 超过工单预算 ${wl.budgetTokens} token,已追加不撤回预算提醒`}>
139
+ 预算提醒
140
+ </span>
141
+ ) : null}
142
+ </>
143
+ )
144
+ }
145
+
146
+ /** One-line preview: the call as name + arguments, else the answer text. */
147
+ function Preview(props: { record: TraceRecord }) {
148
+ if (props.record.stage === 'card') {
149
+ // Records written before the relay field existed carry only the raw output.
150
+ const card = props.record.relay?.card ?? afterThink(props.record.output ?? '')
151
+ const fallback = props.record.relay?.fallback === true || props.record.outcome === 'card-empty'
152
+ return (
153
+ <span className="rl-text">
154
+ {fallback ? <span className="rl-chip rl-chip-warn">自动摘要</span> : null}
155
+ {card.replace(/\s+/g, ' ').slice(0, 220) || '(空卡)'}
156
+ </span>
157
+ )
158
+ }
159
+ const output = props.record.output ?? ''
160
+ const action = afterThink(output)
161
+ const call = /<tool_calls?>\s*([\s\S]*)/.exec(action)
162
+ if (call !== null) {
163
+ let name = ''
164
+ let payload = call[1]!.replace(/<\/tool_calls?>\s*$/, '').trim()
165
+ try {
166
+ const parsed = JSON.parse(payload) as { name?: unknown; arguments?: unknown; function?: { name?: unknown; arguments?: unknown } }
167
+ const inner = parsed.function ?? parsed
168
+ if (typeof inner.name === 'string') {
169
+ name = inner.name
170
+ payload = JSON.stringify(inner.arguments ?? {})
171
+ }
172
+ } catch {
173
+ // Unparseable call: show it as written.
174
+ }
175
+ return (
176
+ <span className="rl-text">
177
+ {name ? <span className="rl-call-name">{name}</span> : null}
178
+ <span className="rl-call-payload">{payload}</span>
179
+ </span>
180
+ )
181
+ }
182
+ const text = action || thinkOf(output)
183
+ return <span className={`rl-text${action ? '' : ' rl-dim'}`}>{text.replace(/\s+/g, ' ') || '(空输出)'}</span>
184
+ }
185
+
186
+ interface Row {
187
+ readonly index: number
188
+ readonly record: TraceRecord
189
+ readonly request: number
190
+ readonly generation: number
191
+ readonly first: boolean
192
+ readonly worklistFold?: { readonly fromTokens?: number; readonly toTokens: number } | undefined
193
+ }
194
+
195
+ function time(at: string | undefined): string {
196
+ if (at === undefined) return ''
197
+ const date = new Date(at)
198
+ return Number.isNaN(date.getTime()) ? at : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
199
+ }
200
+
201
+ function KeyValue(props: { label: string; children: React.ReactNode }) {
202
+ return (
203
+ <>
204
+ <span className="rl-kv-key">{props.label}</span>
205
+ <span className="rl-kv-value">{props.children}</span>
206
+ </>
207
+ )
208
+ }
209
+
210
+ function Inspector(props: { session: string; row: Row; step: TraceRecord | undefined; onClose: () => void }) {
211
+ const { row, step } = props
212
+ const { record } = row
213
+ const [tab, setTab] = useState<'overview' | 'output' | 'prompt'>('overview')
214
+ const [prompt, setPrompt] = useState<string | undefined>()
215
+ const [error, setError] = useState('')
216
+ useEffect(() => {
217
+ setPrompt(undefined)
218
+ setError('')
219
+ }, [row.index])
220
+ useEffect(() => {
221
+ if (tab !== 'prompt' || prompt !== undefined) return
222
+ let stopped = false
223
+ fetchRecord(props.session, row.index)
224
+ .then(body => { if (!stopped) setPrompt(body.record.prompt ?? '') })
225
+ .catch((cause: unknown) => { if (!stopped) setError(cause instanceof Error ? cause.message : String(cause)) })
226
+ return () => { stopped = true }
227
+ }, [tab, prompt, props.session, row.index])
228
+ const tone = toneOf(record)
229
+ const repairs = record.repairs ?? []
230
+ const think = thinkOf(record.output ?? '')
231
+ return (
232
+ <aside className="rl-inspector" aria-label="生成详情">
233
+ <div className="rl-inspector-head">
234
+ <span className={`rl-tag rl-tone-${tone}`}>{OUTCOME_TAG[record.outcome ?? ''] ?? '生成'}</span>
235
+ <span className="rl-inspector-title">请求 {row.request} · 第 {row.generation} 次生成{record.stage === 'answer' ? ' · 收尾阶段' : record.stage === 'card' ? ' · 写交接卡' : ''}</span>
236
+ <button type="button" className="rl-icon" aria-label="关闭" onClick={props.onClose}>×</button>
237
+ </div>
238
+ <div className="rl-tabs" role="tablist">
239
+ {([['overview', '概述'], ['output', '原始输出'], ['prompt', '提示词']] as const).map(([id, label]) => (
240
+ <button key={id} type="button" role="tab" aria-selected={tab === id} onClick={() => setTab(id)}>{label}</button>
241
+ ))}
242
+ </div>
243
+ <div className="rl-inspector-body">
244
+ {tab === 'overview' ? (
245
+ <>
246
+ <div className="rl-kv">
247
+ <KeyValue label="插件处理">{record.outcome === undefined ? `${record.action ?? '—'}(旧记录,没有判定)` : OUTCOME_LABEL[record.outcome] ?? record.outcome}</KeyValue>
248
+ <KeyValue label="用到的修复">
249
+ {repairs.length === 0 ? '无' : (
250
+ <span className="rl-chips">{repairs.map(repair => <span key={repair} className="rl-chip" title={repair}>{REPAIR_LABEL[repair] ?? repair}</span>)}</span>
251
+ )}
252
+ </KeyValue>
253
+ <KeyValue label="解析为"><code>{record.action ?? '—'}</code></KeyValue>
254
+ <KeyValue label="停止原因">{record.finish === 'length' ? '写满 token 上限' : record.finish ?? '—'}{record.stop ? `(${record.stop})` : ''}</KeyValue>
255
+ {step ? <KeyValue label="交给 DSH"><code>{step.decision}</code>{step.attempts && step.attempts > 1 ? ` · 这次请求生成了 ${step.attempts} 次` : ''}</KeyValue> : null}
256
+ {step?.changes && step.changes.length > 0 ? (
257
+ <KeyValue label="插件改的参数">
258
+ <span className="rl-change-list">{step.changes.map((change, index) => <span key={index}>{changeTitle(change)}</span>)}</span>
259
+ </KeyValue>
260
+ ) : null}
261
+ {step && (step.outputRepairs === false || step.guards === false) ? (
262
+ <KeyValue label="开关">{step.outputRepairs === false ? '修正模型输出:关 ' : ''}{step.guards === false ? '插件修复:关' : ''}</KeyValue>
263
+ ) : null}
264
+ {record.worklist ? (
265
+ <KeyValue label="上下文预算">
266
+ 提示词 {record.worklist.promptTokens.toLocaleString()} / {record.worklist.budgetTokens.toLocaleString()} token
267
+ {row.worklistFold !== undefined
268
+ ? ` · 本步刚执行折叠(${row.worklistFold.fromTokens !== undefined ? `${row.worklistFold.fromTokens} → ` : ''}${row.worklistFold.toTokens} token,检查点 #${record.worklist.checkpointAt})`
269
+ : record.worklist.checkpointAt !== undefined
270
+ ? ` · 沿用已折叠窗口(检查点 #${record.worklist.checkpointAt})`
271
+ : ''}
272
+ {record.worklist.nudged ? ' · 本步触发不撤回预算提醒' : ''}
273
+ </KeyValue>
274
+ ) : record.promptTokens !== undefined ? (
275
+ <KeyValue label="上下文长度">{record.promptTokens.toLocaleString()} RWKV token</KeyValue>
276
+ ) : null}
277
+ {record.fold ? (
278
+ <KeyValue label="本步折叠">
279
+ {foldKindLabel(record.fold.kind)}:{foldDetailText(record.fold)}
280
+ </KeyValue>
281
+ ) : null}
282
+ <KeyValue label="模型">{record.model ?? '—'}</KeyValue>
283
+ {record.purpose ? <KeyValue label="用途">{record.purpose}</KeyValue> : null}
284
+ <KeyValue label="时间">{time(record.at)}</KeyValue>
285
+ </div>
286
+ {think ? (
287
+ <>
288
+ <div className="rl-section-title">思考</div>
289
+ <div className="rl-prose">{think}</div>
290
+ </>
291
+ ) : null}
292
+ {record.stage === 'card' && record.relay !== undefined ? (
293
+ <>
294
+ <div className="rl-section-title">这一步切掉了什么</div>
295
+ <div className="rl-kv">
296
+ <KeyValue label="覆盖范围">第 {record.relay.from}–{record.relay.to - 1} 条历史(共 {record.relay.to - record.relay.from} 条)</KeyValue>
297
+ <KeyValue label="所属轮次">用户第 {record.relay.turn} 轮</KeyValue>
298
+ <KeyValue label="卡片来源">{record.relay.fallback ? '自动摘要(模型没写出可用的卡)' : '模型自己写的'}</KeyValue>
299
+ </div>
300
+ <div className="rl-section-title">写进上下文的卡片</div>
301
+ <pre className="rl-pre">{record.relay.card || '(空卡)'}</pre>
302
+ <p className="rwkv-hint">这张卡会替换上面那些历史;此后的请求只能看到卡片,看不到被压缩的调用与结果原文。</p>
303
+ </>
304
+ ) : null}
305
+ <div className="rl-section-title">模型写的动作</div>
306
+ <pre className="rl-pre">{afterThink(record.output ?? '') || '(无)'}</pre>
307
+ {step?.args && (record.outcome === 'run') ? (
308
+ <>
309
+ <div className="rl-section-title">DSH 收到的参数</div>
310
+ <pre className="rl-pre">{JSON.stringify(step.args, null, 2)}</pre>
311
+ </>
312
+ ) : null}
313
+ </>
314
+ ) : tab === 'output' ? (
315
+ <pre className="rl-pre rl-pre-full">{record.output ?? ''}</pre>
316
+ ) : error ? <p className="rwkv-error">{error}</p> : prompt === undefined ? <p className="rwkv-hint">加载中…</p> : (
317
+ <pre className="rl-pre rl-pre-full">{prompt}</pre>
318
+ )}
319
+ </div>
320
+ </aside>
321
+ )
322
+ }
323
+
324
+ function CtxBadge(props: { tokens: number | undefined }) {
325
+ if (props.tokens === undefined) return null
326
+ const tier = ctxTier(props.tokens)
327
+ return (
328
+ <span className={`rl-ctx rl-ctx-${tier}`} title={`提示词 ${props.tokens.toLocaleString()} RWKV token`}>
329
+ {formatTokens(props.tokens)}
330
+ </span>
331
+ )
332
+ }
333
+
334
+ function foldForRow(row: Row): ContextFoldTrace | undefined {
335
+ if (row.record.fold !== undefined) return row.record.fold
336
+ if (row.worklistFold !== undefined) {
337
+ return {
338
+ kind: 'worklist',
339
+ beforeTokens: row.worklistFold.fromTokens ?? row.worklistFold.toTokens,
340
+ afterTokens: row.worklistFold.toTokens,
341
+ foldedTools: 0,
342
+ }
343
+ }
344
+ return undefined
345
+ }
346
+
347
+ export function TraceFrames(props: { session: string; records: readonly TraceRecord[]; onlyTouched: boolean; showSide: boolean }) {
348
+ const [selected, setSelected] = useState<number | undefined>()
349
+ const rows: Row[] = []
350
+ const steps = new Map<number, TraceRecord>()
351
+ let request = 1
352
+ let generation = 0
353
+ let lastCheckpointAt: number | undefined
354
+ let lastPromptTokens: number | undefined
355
+ props.records.forEach((record, index) => {
356
+ if (!props.showSide && record.purpose !== undefined) return
357
+ if (record.stage === 'step') {
358
+ steps.set(request, record)
359
+ rows.push({ index, record, request, generation, first: false })
360
+ request++
361
+ generation = 0
362
+ return
363
+ }
364
+ // A handoff card is its own generation: it runs before the decision of the
365
+ // same request and is the reason that decision sees less history.
366
+ if (!isGeneration(record) && !isCard(record)) return
367
+ generation++
368
+ let worklistFold: { fromTokens?: number; toTokens: number } | undefined
369
+ if (record.purpose === undefined && generation === 1 && record.worklist !== undefined) {
370
+ const cp = record.worklist.checkpointAt
371
+ if (cp !== undefined && cp !== lastCheckpointAt) {
372
+ worklistFold = {
373
+ ...(lastPromptTokens !== undefined ? { fromTokens: lastPromptTokens } : {}),
374
+ toTokens: record.worklist.promptTokens,
375
+ }
376
+ }
377
+ lastCheckpointAt = cp
378
+ lastPromptTokens = record.worklist.promptTokens
379
+ }
380
+ rows.push({ index, record, request, generation, first: generation === 1, worklistFold })
381
+ })
382
+ const visible = props.onlyTouched ? rows.filter(row => row.record.stage !== 'step' && touched(row.record)) : rows
383
+ const current = rows.find(row => row.index === selected)
384
+ if (visible.length === 0) {
385
+ return <p className="rl-empty">{props.onlyTouched ? '这个会话里没有用到兜底的生成。' : '这个会话还没有 RWKV 记录。'}</p>
386
+ }
387
+ return (
388
+ <div className="rl-ledger">
389
+ <div className="rl-scroll">
390
+ <table className="rl-table">
391
+ <colgroup><col className="rl-event-col" /><col /><col className="rl-ctx-col" /></colgroup>
392
+ <tbody>
393
+ {visible.flatMap(row => {
394
+ if (row.record.stage === 'step') {
395
+ return [(
396
+ <tr key={row.index} className="rl-step-row">
397
+ <td className="rl-event"><span className="rl-rail" /></td>
398
+ <td className="rl-content" colSpan={2}><HandedLine record={row.record} /></td>
399
+ </tr>
400
+ )]
401
+ }
402
+ const tone = toneOf(row.record)
403
+ const repairs = row.record.repairs ?? []
404
+ const ctxTokens = row.record.promptTokens ?? row.record.worklist?.promptTokens
405
+ const fold = !props.onlyTouched ? foldForRow(row) : undefined
406
+ const out = []
407
+ if (fold !== undefined) {
408
+ out.push(
409
+ <tr key={`fold-${row.index}`} className="rl-fold-row" data-turn-start={row.first}>
410
+ <td className="rl-event">
411
+ <span className="rl-rail rl-rail-fold" />
412
+ <span className="rl-tag rl-tone-fold">折叠</span>
413
+ </td>
414
+ <td className="rl-content">
415
+ <span className="rl-content-inner rl-fold-text">
416
+ <svg className="rl-fold-icon" width="12" height="12" viewBox="0 0 14 14" fill="none" aria-hidden="true">
417
+ <path d="M4.5 2.5L7 5L9.5 2.5M4.5 11.5L7 9L9.5 11.5M2.5 7H11.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
418
+ </svg>
419
+ <span className="rl-fold-badge">{foldKindLabel(fold.kind)}</span>
420
+ <span className="rl-dim">·</span>
421
+ <span className="rl-fold-range">{formatTokens(fold.beforeTokens)} → {formatTokens(fold.afterTokens)}</span>
422
+ {fold.foldedTools > 0 ? <span className="rl-dim">· 已折叠 {fold.foldedTools} 条工具调用</span> : null}
423
+ </span>
424
+ </td>
425
+ <td className="rl-ctx-cell" />
426
+ </tr>,
427
+ )
428
+ }
429
+ out.push(
430
+ <tr
431
+ key={row.index} tabIndex={0} data-selected={row.index === selected} data-turn-start={row.first && fold === undefined && !props.onlyTouched}
432
+ onClick={() => setSelected(current => current === row.index ? undefined : row.index)}
433
+ onKeyDown={event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); setSelected(row.index) } }}
434
+ >
435
+ <td className="rl-event">
436
+ <span className={`rl-rail rl-rail-${tone}`} />
437
+ {row.first || props.onlyTouched ? <span className="rl-turn-label">请求 {row.request}</span> : null}
438
+ <span className={`rl-tag rl-tone-${tone}`} title={row.record.outcome === undefined ? '旧记录' : OUTCOME_LABEL[row.record.outcome] ?? row.record.outcome}>
439
+ {row.record.outcome === undefined ? '生成' : OUTCOME_TAG[row.record.outcome] ?? row.record.outcome}
440
+ </span>
441
+ </td>
442
+ <td className="rl-content">
443
+ <span className="rl-content-inner">
444
+ {row.record.stage === 'answer' ? <span className="rl-chip rl-chip-muted">收尾阶段</span> : null}
445
+ <CutNote record={row.record} worklistFold={row.record.fold === undefined ? row.worklistFold : undefined} />
446
+ {row.record.finish === 'length' ? <span className="rl-chip rl-chip-warn">写满上限</span> : null}
447
+ <Preview record={row.record} />
448
+ {repairs.map(repair => <span key={repair} className="rl-chip rl-chip-warn" title={repair}>{REPAIR_LABEL[repair] ?? repair}</span>)}
449
+ </span>
450
+ </td>
451
+ <td className="rl-ctx-cell"><CtxBadge tokens={ctxTokens} /></td>
452
+ </tr>,
453
+ )
454
+ return out
455
+ })}
456
+ </tbody>
457
+ </table>
458
+ </div>
459
+ {current ? <Inspector session={props.session} row={current} step={steps.get(current.request)} onClose={() => setSelected(undefined)} /> : null}
460
+ </div>
461
+ )
462
+ }
@@ -0,0 +1,77 @@
1
+ // "RWKV" tab in the conversation view ring: the current session's raw trace
2
+ // as a ledger, laid out like DSH's Trajectory tab. DSH's own Trajectory shows
3
+ // DSH's record (repaired calls, merged reasoning); this one shows what RWKV
4
+ // received and wrote per generation and where the plugin stepped in.
5
+
6
+ import { useEffect, useState } from 'react'
7
+ import { TraceFrames } from './TraceFrames.tsx'
8
+ import { fetchSession, isCard, isGeneration, percent, touched, type TraceRecord } from './traces-api.ts'
9
+
10
+ const POLL_MS = 2500
11
+
12
+ export function RwkvTraceView(props: { session: string }) {
13
+ const [records, setRecords] = useState<TraceRecord[] | undefined>()
14
+ const [recording, setRecording] = useState(false)
15
+ const [error, setError] = useState('')
16
+ const [onlyTouched, setOnlyTouched] = useState(false)
17
+ const [showSide, setShowSide] = useState(false)
18
+ useEffect(() => {
19
+ setRecords(undefined)
20
+ let stopped = false
21
+ let timer: ReturnType<typeof setTimeout> | undefined
22
+ let first = true
23
+ const load = async () => {
24
+ // The first load always runs; polling pauses while the page is hidden.
25
+ if (first || document.visibilityState === 'visible') {
26
+ first = false
27
+ try {
28
+ const body = await fetchSession(props.session)
29
+ if (stopped) return
30
+ setRecording(body.recording)
31
+ // Same length: nothing new was appended, keep the rendered rows (and the selection).
32
+ setRecords(current => current !== undefined && current.length === body.records.length ? current : body.records)
33
+ setError('')
34
+ } catch (cause) {
35
+ if (!stopped) setError(cause instanceof Error ? cause.message : String(cause))
36
+ }
37
+ }
38
+ if (!stopped) timer = setTimeout(() => { void load() }, POLL_MS)
39
+ }
40
+ void load()
41
+ return () => {
42
+ stopped = true
43
+ if (timer !== undefined) clearTimeout(timer)
44
+ }
45
+ }, [props.session])
46
+
47
+ const generations = (records ?? []).filter(record => isGeneration(record) && record.purpose === undefined)
48
+ // Handoff cards are generations too, but they are not decisions: they are
49
+ // counted apart so "原样可用" keeps meaning "the model decided correctly".
50
+ const cards = (records ?? []).filter(record => isCard(record) && record.purpose === undefined)
51
+ const fallbackCards = cards.filter(record => record.relay?.fallback === true).length
52
+ const judged = generations.filter(record => record.outcome !== undefined)
53
+ const hit = judged.filter(touched).length
54
+ return (
55
+ <div className="rl-root">
56
+ <div className="rl-toolbar">
57
+ <div className="rl-toggles">
58
+ <button type="button" className="rl-toggle" aria-pressed={onlyTouched} onClick={() => setOnlyTouched(value => !value)}>只看兜底</button>
59
+ <button type="button" className="rl-toggle" aria-pressed={showSide} onClick={() => setShowSide(value => !value)}>附带请求</button>
60
+ </div>
61
+ <span className="rl-summary">
62
+ {generations.length} 次生成 · {hit} 次用到兜底{judged.length > 0 ? ` · 原样可用 ${percent(judged.length - hit, judged.length)}` : ''}
63
+ {cards.length > 0 ? ` · 接力卡 ${cards.length} 张${fallbackCards > 0 ? `(自动摘要 ${fallbackCards})` : ''}` : ''}
64
+ </span>
65
+ </div>
66
+ {error ? <p className="rl-notice rwkv-error">{error}</p> : null}
67
+ {records !== undefined && records.length > 0 && !recording ? (
68
+ <p className="rl-notice">轨迹只在内存里,DSH 重启后清空。要落盘,去设置 → RWKV Agent → 开发者打开「原始运行轨迹落盘」。</p>
69
+ ) : null}
70
+ {records === undefined ? <p className="rl-empty">加载中…</p> : records.length === 0 ? (
71
+ <p className="rl-empty">这个会话没有 RWKV 记录:它没用 RWKV 模型,或者轨迹没有保存到磁盘、已被删除。</p>
72
+ ) : (
73
+ <TraceFrames session={props.session} records={records} onlyTouched={onlyTouched} showSide={showSide} />
74
+ )}
75
+ </div>
76
+ )
77
+ }