dsh-session-pages 0.0.0-stage → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js ADDED
@@ -0,0 +1,970 @@
1
+ // dsh-session-pages - browser half.
2
+ //
3
+ // Registers ONE conversation view tab (id 'windows', order 30) beside the chat
4
+ // view (0) and the trajectory views (10, 20). It draws the session as windows:
5
+ // the session origin opens window 1, every compaction checkpoint opens the next
6
+ // one, and each window is headed by the summary that replaced the older range.
7
+ //
8
+ // A window is shown in two layers, because it IS two layers:
9
+ // frame - what every request in this window carries in front: system prompt,
10
+ // tool declarations, checkpoint, retained tail;
11
+ // rows - the window's own timeline, fetched per window on expand.
12
+ //
13
+ // The tab is read-only: it GETs this plugin's own routes, on a timer while the
14
+ // tab is open and never otherwise. Nothing here can write a session event.
15
+ window.__ModuleLoader__.load({
16
+ id: 'dsh-session-pages',
17
+ factory: (require) => {
18
+ var module = { exports: {} }
19
+ var exports = module.exports
20
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
21
+
22
+ const react = require('react')
23
+
24
+ const NS = 'dsh-session-pages'
25
+ const VERSION = '0.5.7'
26
+ const ROUTE_PREFIX = '/dsh-session-pages'
27
+ const VIEW_ID = 'windows'
28
+ const VIEW_ORDER = 30
29
+ const REFRESH_INTERVAL_MS = 10000
30
+
31
+ const zh = {
32
+ 'view.windows': '窗口',
33
+ 'head.title': '{pages} 个窗口',
34
+ 'head.meta': '{turns} 轮 · {steps} 步 · {items} 条 · 峰值 {peak}',
35
+ 'head.trim': '累计裁掉 {windows} 窗 / {events} 条',
36
+ 'head.trimNone': '未裁剪',
37
+ 'head.loading': '正在读取会话…',
38
+ 'head.failed': '读取失败:{error}',
39
+ 'head.empty': '这个会话还没有任何事件。',
40
+ 'page.title': '第 {n} 窗',
41
+ 'page.origin': '会话开头',
42
+ 'page.born': '始于 {time}',
43
+ 'page.compacted': '压缩于第 {turn} 轮',
44
+ 'page.meta': '第 {from}–{to} 轮 · {steps} 次请求 · {messages} 条消息 · {tools} 次工具调用 · 峰值 {peak} token',
45
+ 'page.boundary': '本窗从这里开始 · 第 {from}–{to} 轮 · {steps} 次请求 · {messages} 条消息 · {tools} 次工具调用 · 峰值 {peak}',
46
+ 'frame.preset': '预设',
47
+ 'frame.system': '系统提示词',
48
+ 'frame.expand': '展开',
49
+ 'frame.collapse': '收起',
50
+ 'frame.loading': '读取中…',
51
+ 'frame.presetChanged': '(本窗内切换:{list})',
52
+ 'frame.systemInherited': '沿用上一窗',
53
+ 'frame.systemAbsent': '无(预设未给提示词)',
54
+ 'frame.tools': '工具声明',
55
+ 'frame.toolsNone': '无工具',
56
+ 'frame.toolsInherited': '(沿用同一份请求头)',
57
+ 'frame.more': '等 {n} 个',
58
+ 'frame.checkpoint': '开窗摘要({chars} 字符)',
59
+ 'frame.checkpointHint': '这一窗以 checkpoint 摘要开头,之前窗口的原文不再发送。',
60
+ 'frame.retained': '保留尾部',
61
+ 'frame.retainedRange': '替换 seq {from}–{to} · 尾部 {tail} 条对话消息(用户 {user} / 助手 {assistant} / 结果 {tool})',
62
+ 'frame.retainedHint': '区间来自 checkpoint 的 surfaceOp 记录;实际发送集合未逐条记录,这里只报区间与条数。',
63
+ 'frame.noSummary': '这一窗从会话开头起算,没有前置摘要。',
64
+ 'rows.expand': '展开明细({n} 块)',
65
+ 'rows.expandEmpty': '展开明细',
66
+ 'rows.collapse': '收起明细',
67
+ 'rows.loading': '正在读取明细…',
68
+ 'rows.failed': '明细读取失败:{error}',
69
+ 'rows.chunk': '第 {i} 块 · {n} 条',
70
+ 'rows.empty': '这一窗没有可列出的条目。',
71
+ 'row.injection': '注入',
72
+ 'row.reasoning': '思考',
73
+ 'row.user': '用户',
74
+ 'row.assistant': '助手',
75
+ 'row.toolCall': '工具',
76
+ 'row.toolResult': '结果',
77
+ 'turn.n': '第 {n} 轮',
78
+ 'turn.meta': '{steps} 次请求 · {messages} 条消息',
79
+ 'group.untagged': '未归入轮次',
80
+ 'turn.metaOnly': '{messages} 条',
81
+ 'footer.hint': '窗口按压缩分界切开;页首是这一窗每次请求都带在对话前面的东西。',
82
+ }
83
+ const en = {
84
+ 'view.windows': 'Windows',
85
+ 'head.title': '{pages} window(s)',
86
+ 'head.meta': '{turns} turns · {steps} steps · {items} items · peak {peak}',
87
+ 'head.trim': '{windows} windows / {events} events trimmed away',
88
+ 'head.trimNone': 'no trimming',
89
+ 'head.loading': 'Reading the session…',
90
+ 'head.failed': 'Read failed: {error}',
91
+ 'head.empty': 'This session has no events yet.',
92
+ 'page.title': 'Window {n}',
93
+ 'page.origin': 'session origin',
94
+ 'page.compacted': 'compacted at turn {turn}',
95
+ 'page.meta': 'turns {from}–{to} · {steps} requests · {messages} messages · {tools} tool calls · peak {peak} tokens',
96
+ 'page.boundary': 'window starts here · turns {from}–{to} · {steps} requests · {messages} messages · {tools} tool calls · peak {peak}',
97
+ 'frame.preset': 'Preset',
98
+ 'frame.system': 'System prompt',
99
+ 'frame.expand': 'Show',
100
+ 'frame.collapse': 'Hide',
101
+ 'frame.loading': 'Loading…',
102
+ 'frame.presetChanged': ' (switched in this window: {list})',
103
+ 'frame.systemInherited': 'inherited',
104
+ 'frame.systemAbsent': 'none (the preset gives no prompt)',
105
+ 'frame.tools': 'Tool declarations',
106
+ 'frame.toolsNone': 'no tools',
107
+ 'frame.toolsInherited': '(same request header)',
108
+ 'frame.more': 'and {n} more',
109
+ 'frame.checkpoint': 'Opening summary ({chars} chars)',
110
+ 'frame.checkpointHint': 'This window opens with a checkpoint; the earlier windows are no longer sent.',
111
+ 'frame.retained': 'Retained tail',
112
+ 'frame.retainedRange': 'replaced seq {from}–{to} · tail {tail} messages (user {user} / assistant {assistant} / result {tool})',
113
+ 'frame.retainedHint': 'The interval comes from the checkpoint\'s surfaceOp record; the exact set re-sent is not logged, so only the range and counts are reported.',
114
+ 'frame.noSummary': 'This window starts at the session origin; it has no preceding summary.',
115
+ 'rows.expand': 'Show rows ({n} blocks)',
116
+ 'rows.expandEmpty': 'Show rows',
117
+ 'rows.collapse': 'Hide rows',
118
+ 'rows.loading': 'Reading rows…',
119
+ 'rows.failed': 'Rows failed: {error}',
120
+ 'rows.chunk': 'block {i} · {n} items',
121
+ 'rows.empty': 'No rows in this window.',
122
+ 'row.injection': 'Injected',
123
+ 'row.reasoning': 'Thinking',
124
+ 'row.user': 'User',
125
+ 'row.assistant': 'Assistant',
126
+ 'row.toolCall': 'Tool',
127
+ 'row.toolResult': 'Result',
128
+ 'turn.n': 'Turn {n}',
129
+ 'turn.meta': '{steps} requests · {messages} messages',
130
+ 'group.untagged': 'Not in a turn',
131
+ 'turn.metaOnly': '{messages} items',
132
+ 'footer.hint': 'Windows are cut at compactions; each page head is what every request in that window carries in front of the dialogue.',
133
+ }
134
+
135
+ function formatText(template, values) {
136
+ return String(template).replace(/\{(\w+)\}/g, (match, key) =>
137
+ values !== null && values !== undefined && Object.prototype.hasOwnProperty.call(values, key)
138
+ ? String(values[key])
139
+ : match,
140
+ )
141
+ }
142
+
143
+ /** Local wall-clock stamp for a window's opening event. */
144
+ function formatTime(ms) {
145
+ if (typeof ms !== 'number' || Number.isFinite(ms) === false) return null
146
+ const date = new Date(ms)
147
+ if (Number.isNaN(date.getTime())) return null
148
+ const pad = (n) => String(n).padStart(2, '0')
149
+ return String(date.getFullYear()) + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
150
+ + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes())
151
+ }
152
+
153
+ function formatCount(value) {
154
+ if (value === null || value === undefined) return '—'
155
+ if (value >= 10000) return (value / 10000).toFixed(1) + '万'
156
+ return String(value)
157
+ }
158
+
159
+ // Colours come from the platform's own design tokens (--dsw-alias-*), never
160
+ // from hard-coded hex: this view has to read on the light theme and the dark
161
+ // one. Every token has a neutral fallback so a renamed token degrades to
162
+ // legible rather than to invisible.
163
+ const CSS = `/* dsh-session-pages - window view styles.
164
+ The scale is the host's: 14/22 for a window title, 13/20 body, 12/18 meta,
165
+ 11/16 micro; spacing in 4/8/12/16; every colour a --dsw-alias-* token so the
166
+ theme switch is free. */
167
+ .dspsp-root{padding:16px 20px 24px;display:flex;flex-direction:column;gap:12px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary,inherit)}
168
+ .dspsp-root *{box-sizing:border-box}
169
+
170
+ /* ---- page head ---------------------------------------------------------- */
171
+ .dspsp-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}
172
+ .dspsp-head-title{font-size:14px;line-height:22px;font-weight:600}
173
+ .dspsp-head-meta{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95))}
174
+ .dspsp-head-trim{font-size:11px;line-height:16px;padding:0 6px;border-radius:4px;border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.3));color:var(--dsw-alias-label-secondary,inherit);cursor:help}
175
+
176
+ /* ---- one window --------------------------------------------------------- */
177
+ .dspsp-page{border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.25));border-radius:10px;background:var(--dsw-alias-bg-layer-1,transparent);overflow:hidden}
178
+ .dspsp-page.is-current{border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.4))}
179
+ .dspsp-page-head{display:flex;align-items:baseline;gap:8px;padding:10px 14px 8px;flex-wrap:wrap}
180
+ .dspsp-page-title{font-size:14px;line-height:22px;font-weight:600}
181
+ .dspsp-page-born{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9));font-variant-numeric:tabular-nums}
182
+ .dspsp-tag{font-size:11px;line-height:16px;padding:0 6px;border-radius:4px;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-state-warn-label,#8a5a00);border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.32))}
183
+ .dspsp-page-origin{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9))}
184
+ .dspsp-page-meta{padding:2px 14px 6px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95))}
185
+
186
+ /* ---- the frame: what every request carries in front --------------------- */
187
+ .dspsp-frame{margin:8px 14px 10px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05));display:flex;flex-direction:column;gap:6px}
188
+ .dspsp-frame-row{display:flex;align-items:baseline;gap:8px;font-size:12px;line-height:18px}
189
+ .dspsp-frame-row.is-clickable{cursor:pointer;border-radius:4px;padding:1px 4px;margin:-1px -4px}
190
+ .dspsp-frame-row.is-clickable:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.08))}
191
+ .dspsp-frame-key{flex:0 0 76px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95))}
192
+ .dspsp-frame-val{flex:1 1 auto;min-width:0;color:var(--dsw-alias-label-secondary,inherit);word-break:break-word}
193
+ .dspsp-frame-val.is-absent{color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.8))}
194
+ .dspsp-frame-pre{margin:2px 0 6px 84px;padding:6px 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-1,transparent);white-space:pre-wrap;word-break:break-word;font-size:11px;line-height:17px;max-height:320px;overflow:auto;font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace);color:var(--dsw-alias-label-secondary,inherit)}
195
+ .dspsp-chip{display:inline-block;font-size:11px;line-height:16px;padding:0 5px;margin:0 4px 2px 0;border-radius:4px;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12));color:var(--dsw-alias-label-secondary,inherit);font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace)}
196
+ .dspsp-fold-btn{flex:0 0 auto;min-width:38px;text-align:center;font-size:11px;line-height:16px;padding:0 6px;border-radius:4px;border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));color:var(--dsw-alias-label-secondary,inherit);background:transparent}
197
+ .dspsp-fold-btn.is-empty{border:0;padding:0;width:0;min-width:0;overflow:hidden}
198
+ .dspsp-fold-head{display:flex;gap:8px;align-items:baseline;cursor:pointer;padding:2px 4px;margin:0 -4px;border-radius:4px}
199
+ .dspsp-fold-head:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.08))}
200
+ .dspsp-fold-body{margin:2px 0 6px 20px;white-space:pre-wrap;word-break:break-word;font-size:12px;line-height:19px;color:var(--dsw-alias-label-secondary,inherit);font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace);max-height:280px;overflow:auto}
201
+ .dspsp-full{margin:0;white-space:pre-wrap;word-break:break-word;font-size:12px;line-height:19px;color:var(--dsw-alias-label-primary,inherit)}
202
+
203
+ /* ---- tool declarations -------------------------------------------------- */
204
+ .dspsp-tools{margin:2px 0 4px 84px;display:flex;flex-direction:column;gap:8px;max-height:420px;overflow:auto}
205
+ .dspsp-tool{padding-left:8px;border-left:2px solid var(--dsw-alias-border-l2,rgba(127,127,127,.25))}
206
+ .dspsp-tool-name{font-size:12px;line-height:18px;font-weight:600;font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace)}
207
+ .dspsp-tool-desc{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,inherit)}
208
+ .dspsp-tool-params{margin-top:2px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9));font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace)}
209
+
210
+ /* ---- checkpoint summary ------------------------------------------------- */
211
+ .dspsp-summary{margin:8px 14px 4px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05))}
212
+ .dspsp-summary>summary{padding:6px 10px;font-size:12px;line-height:18px;cursor:pointer;color:var(--dsw-alias-label-secondary,inherit);list-style:none}
213
+ .dspsp-summary>summary::-webkit-details-marker{display:none}
214
+ .dspsp-summary>summary::before{content:"▸ ";color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9))}
215
+ .dspsp-summary[open]>summary::before{content:"▾ "}
216
+ .dspsp-summary pre{margin:0;padding:0 10px 8px;white-space:pre-wrap;word-break:break-word;font-size:12px;line-height:19px;max-height:340px;overflow:auto;color:var(--dsw-alias-label-secondary,inherit)}
217
+
218
+ /* ---- the window-start boundary ------------------------------------------ */
219
+ .dspsp-boundary{display:flex;align-items:center;gap:8px;margin:12px 14px 8px}
220
+ .dspsp-boundary-line{flex:1 1 auto;height:1px;background:var(--dsw-alias-border-l2,rgba(127,127,127,.28))}
221
+ .dspsp-boundary-text{flex:0 1 auto;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary,inherit);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
222
+
223
+ /* ---- toggle ------------------------------------------------------------- */
224
+ .dspsp-toggle{margin:0 14px 12px;align-self:flex-start;padding:3px 10px;border-radius:6px;border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));background:transparent;color:var(--dsw-alias-label-secondary,inherit);font-size:12px;line-height:18px;cursor:pointer}
225
+ .dspsp-toggle:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.1))}
226
+
227
+ /* ---- one 100-row block -------------------------------------------------- */
228
+ .dspsp-chunk{margin:8px 14px 4px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.16));border-radius:8px;padding:6px 8px 8px}
229
+ .dspsp-chunk-label{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,inherit)}
230
+ .dspsp-rows{display:flex;flex-direction:column;gap:2px;padding-top:4px}
231
+
232
+ /* ---- one turn ----------------------------------------------------------- */
233
+ .dspsp-turn-block{margin:10px 0 0}
234
+ .dspsp-turn-block:first-child{margin-top:2px}
235
+ .dspsp-turn-head{display:flex;align-items:baseline;gap:8px;padding:0 4px 3px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.16));margin-bottom:4px}
236
+ .dspsp-turn-n{font-size:12px;line-height:18px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)}
237
+ .dspsp-turn-meta{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9))}
238
+ .dspsp-turn-body{display:flex;flex-direction:column;gap:1px}
239
+
240
+ /* ---- one row ------------------------------------------------------------ */
241
+ .dspsp-item{display:flex;align-items:flex-start;gap:8px;padding:2px 4px;border-radius:4px}
242
+ .dspsp-item.is-fold{cursor:default}
243
+ .dspsp-item.is-fold:has(.dspsp-fold-btn:not(.is-empty)){cursor:pointer}
244
+ .dspsp-item.is-fold:has(.dspsp-fold-btn:not(.is-empty)):hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.07))}
245
+ .dspsp-item-kind{flex:0 0 48px;font-size:11px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95));white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
246
+ .dspsp-item-text{flex:1 1 auto;min-width:0;font-size:13px;line-height:20px;white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-primary,inherit)}
247
+ .dspsp-item.is-error .dspsp-item-text{color:var(--dsw-alias-state-error-primary,#c0392b)}
248
+ .dspsp-item[data-kind="tool-call"],.dspsp-item[data-kind="tool-result"]{margin-left:56px;padding-left:8px;border-left:2px solid var(--dsw-alias-border-l1,rgba(127,127,127,.2))}
249
+ .dspsp-item[data-kind="tool-call"] .dspsp-item-text,.dspsp-item[data-kind="tool-result"] .dspsp-item-text{font-size:12px;line-height:19px;font-family:var(--dsh-font-family-code-default,ui-monospace,Menlo,monospace);color:var(--dsw-alias-label-secondary,inherit)}
250
+ .dspsp-item[data-kind="injection"],.dspsp-reasoning{font-size:12px}
251
+ .dspsp-injection-preview,.dspsp-reasoning-preview{flex:1 1 auto;min-width:0;font-style:italic;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95));overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
252
+ .dspsp-expand{flex:0 0 auto;align-self:flex-start;margin-left:8px;padding:0 6px;border-radius:4px;border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.3));background:transparent;color:var(--dsw-alias-label-secondary,inherit);font-size:11px;line-height:16px;cursor:pointer}
253
+
254
+ /* ---- misc --------------------------------------------------------------- */
255
+ .dspsp-empty{padding:8px 14px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.9))}
256
+ .dspsp-foot{padding:4px 2px 0;font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.8))}
257
+ `
258
+
259
+ if (typeof document !== 'undefined' && document !== null) {
260
+ // A hot reload re-runs this module: drop the previous sheet instead of
261
+ // stacking a second copy of the same rules.
262
+ const stale = document.querySelector('style[data-dsh-session-pages]')
263
+ if (stale !== null && stale !== undefined) stale.remove()
264
+ const tag = document.createElement('style')
265
+ tag.setAttribute('data-dsh-session-pages', VERSION)
266
+ tag.textContent = CSS
267
+ document.head.appendChild(tag)
268
+ }
269
+
270
+ // --- controller ------------------------------------------------------------
271
+
272
+ class PagesController {
273
+ constructor(sessionId) {
274
+ this.sessionId = sessionId
275
+ this.listeners = new Set()
276
+ this.timer = null
277
+ this.inFlight = false
278
+ this.state = { summary: null, failure: null, loading: true, rows: new Map() }
279
+ }
280
+
281
+ getSnapshot() {
282
+ return this.state
283
+ }
284
+
285
+ subscribe(listener) {
286
+ this.listeners.add(listener)
287
+ return () => {
288
+ this.listeners.delete(listener)
289
+ }
290
+ }
291
+
292
+ publish(patch) {
293
+ this.state = { ...this.state, ...patch }
294
+ for (const listener of this.listeners) listener()
295
+ }
296
+
297
+ rowsFor(pageIndex) {
298
+ const entry = this.state.rows.get(pageIndex)
299
+ return entry === undefined
300
+ ? { status: 'idle', itemCount: null, chunkSize: 100, chunkCount: null, chunks: new Map(), error: null }
301
+ : entry
302
+ }
303
+
304
+ async refresh() {
305
+ if (this.inFlight === true) return
306
+ this.inFlight = true
307
+ try {
308
+ const response = await fetch(
309
+ ROUTE_PREFIX + '/state?sessionId=' + encodeURIComponent(this.sessionId),
310
+ { headers: { accept: 'application/json' } },
311
+ )
312
+ const body = await response.json()
313
+ if (response.ok === false || body.ok === false) {
314
+ this.publish({ failure: String(body.error || response.status), loading: false })
315
+ return
316
+ }
317
+ this.publish({ summary: body, failure: null, loading: false })
318
+ } catch (error) {
319
+ this.publish({ failure: String((error && error.message) || error), loading: false })
320
+ } finally {
321
+ this.inFlight = false
322
+ }
323
+ }
324
+
325
+ async loadChunk(pageIndex, chunkIndex) {
326
+ const entry = this.rowsFor(pageIndex)
327
+ const existing = entry.chunks.get(chunkIndex)
328
+ if (existing !== undefined && (existing.status === 'loading' || existing.status === 'ready')) return
329
+ const pending = new Map(entry.chunks)
330
+ pending.set(chunkIndex, { status: 'loading', items: [], error: null })
331
+ this.state.rows.set(pageIndex, { ...entry, status: 'loading', chunks: pending })
332
+ this.publish({ rows: this.state.rows })
333
+ try {
334
+ const url = ROUTE_PREFIX + '/items?sessionId=' + encodeURIComponent(this.sessionId)
335
+ + '&page=' + String(pageIndex) + '&chunk=' + String(chunkIndex)
336
+ const response = await fetch(url, { headers: { accept: 'application/json' } })
337
+ const body = await response.json()
338
+ const fresh = this.rowsFor(pageIndex)
339
+ const next = new Map(fresh.chunks)
340
+ if (response.ok === false || body.ok === false) {
341
+ const message = String(body.error || response.status)
342
+ next.set(chunkIndex, { status: 'error', items: [], error: message })
343
+ this.state.rows.set(pageIndex, { ...fresh, status: 'error', error: message, chunks: next })
344
+ } else {
345
+ next.set(chunkIndex, { status: 'ready', items: Array.isArray(body.items) ? body.items : [], error: null })
346
+ this.state.rows.set(pageIndex, {
347
+ ...fresh,
348
+ status: 'ready',
349
+ error: null,
350
+ itemCount: body.page === undefined ? fresh.itemCount : body.page.itemCount,
351
+ chunkSize: body.chunk === undefined ? fresh.chunkSize : body.chunk.size,
352
+ chunkCount: body.chunk === undefined ? fresh.chunkCount : body.chunk.chunks,
353
+ chunks: next,
354
+ })
355
+ }
356
+ this.publish({ rows: this.state.rows })
357
+ } catch (error) {
358
+ const fresh = this.rowsFor(pageIndex)
359
+ const next = new Map(fresh.chunks)
360
+ const message = String((error && error.message) || error)
361
+ next.set(chunkIndex, { status: 'error', items: [], error: message })
362
+ this.state.rows.set(pageIndex, { ...fresh, status: 'error', error: message, chunks: next })
363
+ this.publish({ rows: this.state.rows })
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Fetch only the block map for one window. Expanding the window must NOT
369
+ * pull a block: the reader chooses which 100-item block to open.
370
+ */
371
+ async loadRows(pageIndex) {
372
+ const entry = this.rowsFor(pageIndex)
373
+ if (entry.chunkCount !== null) return
374
+ this.state.rows.set(pageIndex, { ...entry, status: 'loading' })
375
+ this.publish({ rows: this.state.rows })
376
+ try {
377
+ const url = ROUTE_PREFIX + '/items?sessionId=' + encodeURIComponent(this.sessionId)
378
+ + '&page=' + String(pageIndex) + '&meta=1'
379
+ const response = await fetch(url, { headers: { accept: 'application/json' } })
380
+ const body = await response.json()
381
+ const fresh = this.rowsFor(pageIndex)
382
+ if (response.ok === false || body.ok === false) {
383
+ const message = String(body.error || response.status)
384
+ this.state.rows.set(pageIndex, { ...fresh, status: 'error', error: message })
385
+ } else {
386
+ this.state.rows.set(pageIndex, {
387
+ ...fresh,
388
+ status: 'ready',
389
+ error: null,
390
+ itemCount: body.page === undefined ? fresh.itemCount : body.page.itemCount,
391
+ chunkSize: body.chunk === undefined ? fresh.chunkSize : body.chunk.size,
392
+ chunkCount: body.chunk === undefined ? fresh.chunkCount : body.chunk.chunks,
393
+ })
394
+ }
395
+ this.publish({ rows: this.state.rows })
396
+ } catch (error) {
397
+ const fresh = this.rowsFor(pageIndex)
398
+ const message = String((error && error.message) || error)
399
+ this.state.rows.set(pageIndex, { ...fresh, status: 'error', error: message })
400
+ this.publish({ rows: this.state.rows })
401
+ }
402
+ }
403
+
404
+ attach() {
405
+ this.refresh()
406
+ this.timer = setInterval(() => this.refresh(), REFRESH_INTERVAL_MS)
407
+ return () => {
408
+ if (this.timer !== null) clearInterval(this.timer)
409
+ this.timer = null
410
+ }
411
+ }
412
+
413
+ detach() {
414
+ if (this.timer !== null) clearInterval(this.timer)
415
+ this.timer = null
416
+ }
417
+ }
418
+
419
+ // --- view ------------------------------------------------------------------
420
+
421
+ function PagesView(props) {
422
+ const t = props.t
423
+ const controller = props.controller
424
+ const state = react.useSyncExternalStore(
425
+ (listener) => controller.subscribe(listener),
426
+ () => controller.getSnapshot(),
427
+ () => controller.getSnapshot(),
428
+ )
429
+ react.useEffect(() => controller.attach(), [controller])
430
+
431
+ const summary = state.summary
432
+ // Optional: how much of this log dsh-log-trim already rewrote. Absent when
433
+ // the package is not installed, the session has no record, or nothing was
434
+ // removed - in every case the header simply does not mention it.
435
+ const trim = summary === null || summary.trim === undefined ? null : summary.trim
436
+ const trimNote = trim === null
437
+ ? null
438
+ : (trim.windowsRemoved > 0 || trim.eventsRemoved > 0)
439
+ ? {
440
+ text: formatText(t('head.trim'), {
441
+ windows: formatCount(trim.windowsRemoved),
442
+ events: formatCount(trim.eventsRemoved),
443
+ }),
444
+ title: trimTooltip(trim),
445
+ }
446
+ : null
447
+ const head = react.createElement(
448
+ 'div',
449
+ { className: 'dspsp-head' },
450
+ react.createElement('span', { className: 'dspsp-head-title' },
451
+ summary === null ? t('view.windows') : formatText(t('head.title'), { pages: summary.totals.pages })),
452
+ summary === null
453
+ ? null
454
+ : react.createElement('span', { className: 'dspsp-head-meta' },
455
+ formatText(t('head.meta'), {
456
+ turns: summary.totals.turns,
457
+ steps: summary.totals.steps,
458
+ items: summary.totals.items,
459
+ peak: formatCount(summary.totals.peakTokens),
460
+ })),
461
+ trimNote === null
462
+ ? null
463
+ : react.createElement('span', {
464
+ className: 'dspsp-head-trim',
465
+ title: trimNote.title,
466
+ }, trimNote.text),
467
+ )
468
+
469
+ const children = [head]
470
+ if (state.failure !== null) {
471
+ children.push(react.createElement('div', { key: 'fail', className: 'dspsp-note' },
472
+ formatText(t('head.failed'), { error: state.failure })))
473
+ }
474
+ if (summary === null) {
475
+ if (state.failure === null) {
476
+ children.push(react.createElement('div', { key: 'loading', className: 'dspsp-note' }, t('head.loading')))
477
+ }
478
+ } else if (summary.pages.length === 0) {
479
+ children.push(react.createElement('div', { key: 'empty', className: 'dspsp-note' }, t('head.empty')))
480
+ } else {
481
+ summary.pages.forEach((page, index) => {
482
+ children.push(react.createElement(PageCard, {
483
+ key: 'p' + page.index,
484
+ page,
485
+ rows: controller.rowsFor(page.index),
486
+ controller,
487
+ onLoadRows: () => controller.loadRows(page.index),
488
+ t,
489
+ isLast: index === summary.pages.length - 1,
490
+ }))
491
+ })
492
+ children.push(react.createElement('div', { key: 'foot', className: 'dspsp-foot' }, t('footer.hint') + ' · v' + VERSION))
493
+ }
494
+
495
+ return react.createElement('div', { className: 'dspsp-root', 'data-dspsp-view': VIEW_ID }, children)
496
+ }
497
+
498
+ function FrameBlock(props) {
499
+ const page = props.page
500
+ const controller = props.controller
501
+ const t = props.t
502
+ const context = page.context || {}
503
+ const system = context.system || {}
504
+ const tools = context.tools || {}
505
+ const preset = context.preset || {}
506
+ const [sysOpen, setSysOpen] = react.useState(false)
507
+ const [toolOpen, setToolOpen] = react.useState(false)
508
+ const [toolDetail, setToolDetail] = react.useState(null)
509
+ const rows = []
510
+
511
+ const loadTools = () => {
512
+ if (toolDetail !== null || controller === undefined) return
513
+ fetch(ROUTE_PREFIX + '/tools?sessionId=' + encodeURIComponent(controller.sessionId) + '&page=' + String(page.index), { headers: { accept: 'application/json' } })
514
+ .then((response) => response.json())
515
+ .then((body) => setToolDetail(Array.isArray(body.tools) ? body.tools : []))
516
+ .catch(() => setToolDetail([]))
517
+ }
518
+
519
+ // Same fold affordance as the 注入 / 思考 rows: the control sits on the
520
+ // LEFT and the whole line is the hit area.
521
+ const foldRow = (key, label, value, open, toggle) =>
522
+ react.createElement('div', {
523
+ key,
524
+ className: 'dspsp-frame-row is-clickable',
525
+ onClick: toggle,
526
+ }, [
527
+ react.createElement('span', { key: 'b', className: 'dspsp-fold-btn' }, open === true ? t('frame.collapse') : t('frame.expand')),
528
+ react.createElement('span', { key: 'k', className: 'dspsp-frame-key' }, label),
529
+ react.createElement('span', { key: 'v', className: 'dspsp-frame-val' }, value),
530
+ ])
531
+
532
+ rows.push(react.createElement('div', { key: 'preset', className: 'dspsp-frame-row' }, [
533
+ react.createElement('span', { key: 'k', className: 'dspsp-frame-key' }, t('frame.preset')),
534
+ react.createElement('span', { key: 'v', className: 'dspsp-frame-val' },
535
+ (preset.id || '—') + (Array.isArray(preset.switches) && preset.switches.length > 0
536
+ ? formatText(t('frame.presetChanged'), { list: preset.switches.join(' → ') })
537
+ : '')),
538
+ ]))
539
+
540
+ const sysValue = system.present === true
541
+ ? formatCount(system.chars) + ' 字符' + (system.inherited === true ? ' · ' + t('frame.systemInherited') : '')
542
+ : t('frame.systemAbsent')
543
+ rows.push(foldRow('sys', t('frame.system'), sysValue, sysOpen, () => {
544
+ if (system.present === true) setSysOpen(sysOpen === false)
545
+ }))
546
+ if (sysOpen === true && typeof system.full === 'string') {
547
+ rows.push(react.createElement('pre', { key: 'sysfull', className: 'dspsp-frame-pre' }, system.full))
548
+ }
549
+
550
+ const names = Array.isArray(tools.names) ? tools.names : []
551
+ const shown = names.slice(0, 14)
552
+ const toolsValue = names.length === 0
553
+ ? t('frame.toolsNone')
554
+ : react.createElement('span', null, [
555
+ shown.map((name) => react.createElement('span', { key: name, className: 'dspsp-chip' }, name)),
556
+ names.length > shown.length
557
+ ? react.createElement('span', { key: 'more', className: 'dspsp-page-origin' },
558
+ ' ' + formatText(t('frame.more'), { n: names.length - shown.length }))
559
+ : null,
560
+ tools.inherited === true
561
+ ? react.createElement('span', { key: 'inh', className: 'dspsp-page-origin' }, ' ' + t('frame.toolsInherited'))
562
+ : null,
563
+ ])
564
+ rows.push(foldRow('tools', t('frame.tools'), toolsValue, toolOpen, () => {
565
+ const next = toolOpen === false
566
+ setToolOpen(next)
567
+ if (next === true) loadTools()
568
+ }))
569
+ if (toolOpen === true) {
570
+ rows.push(react.createElement('div', { key: 'toolfull', className: 'dspsp-tools' },
571
+ toolDetail === null
572
+ ? [react.createElement('div', { key: 'l', className: 'dspsp-empty' }, t('frame.loading'))]
573
+ : toolDetail.map((tool) => react.createElement('div', { key: tool.name, className: 'dspsp-tool' }, [
574
+ react.createElement('div', { key: 'n', className: 'dspsp-tool-name' }, tool.name),
575
+ react.createElement('div', { key: 'd', className: 'dspsp-tool-desc' }, tool.description),
576
+ react.createElement('div', { key: 'p', className: 'dspsp-tool-params' },
577
+ tool.params.length === 0 ? '(无参数)' : tool.params.join(' · ')),
578
+ ]))))
579
+ }
580
+
581
+ if (page.summaryChars > 0) {
582
+ rows.push(react.createElement('details', { key: 'sum', className: 'dspsp-summary' },
583
+ react.createElement('summary', null, formatText(t('frame.checkpoint'), { chars: page.summaryChars })),
584
+ react.createElement('pre', null, page.summary)))
585
+ }
586
+ const tail = context.retainedTail
587
+ if (tail !== null && tail !== undefined && tail !== false) {
588
+ if (typeof tail === 'object') {
589
+ rows.push(react.createElement('div', { key: 'ret', className: 'dspsp-frame-row' }, [
590
+ react.createElement('span', { key: 'k', className: 'dspsp-frame-key' }, t('frame.retained')),
591
+ react.createElement('span', { key: 'v', className: 'dspsp-frame-val' },
592
+ formatText(t('frame.retainedRange'), {
593
+ from: tail.replacedFrom,
594
+ to: tail.replacedTo,
595
+ tail: tail.messages,
596
+ user: tail.byKind.user,
597
+ assistant: tail.byKind.assistant,
598
+ tool: tail.byKind.toolResult,
599
+ })),
600
+ ]))
601
+ rows.push(react.createElement('div', { key: 'reth', className: 'dspsp-frame-row' }, [
602
+ react.createElement('span', { key: 'k', className: 'dspsp-frame-key' }, ''),
603
+ react.createElement('span', { key: 'v', className: 'dspsp-frame-val is-absent' }, t('frame.retainedHint')),
604
+ ]))
605
+ } else {
606
+ rows.push(react.createElement('div', { key: 'ret', className: 'dspsp-frame-row' }, [
607
+ react.createElement('span', { key: 'k', className: 'dspsp-frame-key' }, t('frame.retained')),
608
+ react.createElement('span', { key: 'v', className: 'dspsp-frame-val' }, t('frame.retainedHint')),
609
+ ]))
610
+ }
611
+ }
612
+ return react.createElement('div', { className: 'dspsp-frame' }, rows)
613
+ }
614
+
615
+ function ItemRow(props) {
616
+ const item = props.item
617
+ const controller = props.controller
618
+ const t = props.t
619
+ const [full, setFull] = react.useState(null)
620
+ const [busy, setBusy] = react.useState(false)
621
+ const [open, setOpen] = react.useState(false)
622
+ const expand = () => {
623
+ if (busy === true || full !== null || controller === undefined) return
624
+ setBusy(true)
625
+ const url = ROUTE_PREFIX + '/item?sessionId=' + encodeURIComponent(controller.sessionId)
626
+ + '&seq=' + String(item.seq)
627
+ fetch(url, { headers: { accept: 'application/json' } })
628
+ .then((response) => response.json())
629
+ .then((body) => { setFull(typeof body.text === 'string' ? body.text : '') })
630
+ .catch(() => { setFull('') })
631
+ .finally(() => { setBusy(false) })
632
+ }
633
+ const kindKey = {
634
+ 'injection': 'row.injection',
635
+ 'user': 'row.user',
636
+ 'assistant': 'row.assistant',
637
+ 'tool-call': 'row.toolCall',
638
+ 'tool-result': 'row.toolResult',
639
+ }[item.kind] || 'row.assistant'
640
+ const label = item.kind === 'tool-call'
641
+ ? formatText('{k} · {name}', { k: t(kindKey), name: item.label })
642
+ : t(kindKey)
643
+ if (item.kind === 'reasoning') {
644
+ const preview = String(item.text || '').replace(/\s+/g, ' ').slice(0, 60)
645
+ const expandReasoning = () => {
646
+ if (busy === true || full !== null || controller === undefined) return
647
+ setBusy(true)
648
+ const url = ROUTE_PREFIX + '/item?sessionId=' + encodeURIComponent(controller.sessionId)
649
+ + '&seq=' + String(item.seq) + '&kind=reasoning'
650
+ fetch(url, { headers: { accept: 'application/json' } })
651
+ .then((response) => response.json())
652
+ .then((body) => { setFull(typeof body.text === 'string' ? body.text : '') })
653
+ .catch(() => { setFull('') })
654
+ .finally(() => { setBusy(false) })
655
+ }
656
+ return react.createElement('div', { className: 'dspsp-reasoning', 'data-kind': 'reasoning' }, [
657
+ react.createElement('div', {
658
+ key: 'h',
659
+ className: 'dspsp-fold-head',
660
+ onClick: () => setOpen(open === false),
661
+ }, [
662
+ react.createElement('span', { key: 'a', className: 'dspsp-fold-btn' }, open === true ? '收起' : '展开'),
663
+ react.createElement('span', { key: 'k', className: 'dspsp-item-kind' }, t('row.reasoning')),
664
+ react.createElement('span', { key: 't', className: 'dspsp-reasoning-preview' },
665
+ preview + (item.truncated === true ? '… (' + item.chars + ' 字符)' : '')),
666
+ ]),
667
+ open === true
668
+ ? react.createElement('pre', { key: 'b', className: 'dspsp-fold-body', onClick: expandReasoning },
669
+ full !== null ? full : String(item.text || ''))
670
+ : null,
671
+ ])
672
+ }
673
+ if (item.kind === 'injection') {
674
+ const preview = String(item.text || '').replace(/\s+/g, ' ').slice(0, 60)
675
+ return react.createElement('div', { className: 'dspsp-injection', 'data-kind': 'injection' }, [
676
+ react.createElement('div', { key: 'h', className: 'dspsp-fold-head', onClick: () => setOpen(open === false) }, [
677
+ react.createElement('span', { key: 'a', className: 'dspsp-fold-btn' }, open === true ? '收起' : '展开'),
678
+ react.createElement('span', { key: 'k', className: 'dspsp-item-kind' }, label),
679
+ react.createElement('span', { key: 't', className: 'dspsp-injection-preview' }, preview),
680
+ ]),
681
+ open === true
682
+ ? react.createElement('pre', { key: 'b', className: 'dspsp-fold-body' }, item.text === '' || item.text === undefined ? '—' : item.text)
683
+ : null,
684
+ ])
685
+ }
686
+ const empty = item.text === '' || item.text === undefined
687
+ const calls = Number.isFinite(item.toolCalls) ? item.toolCalls : 0
688
+ const text = empty
689
+ ? (item.kind === 'assistant' && calls > 0 ? '(工具调用 ×' + calls + ')' : '—')
690
+ : item.text
691
+ // Same fold pattern as the other rows: the control sits on the LEFT and
692
+ // the whole line is the hit area. A right-hand button was pushed out of
693
+ // view by long unbroken text.
694
+ const canExpand = item.truncated === true
695
+ const body = open === true && full !== null
696
+ ? react.createElement('pre', { key: 'f', className: 'dspsp-fold-body' }, full)
697
+ : react.createElement('span', { key: 't', className: 'dspsp-item-text' }, text)
698
+ return react.createElement('div', {
699
+ className: 'dspsp-item is-fold' + (item.isError === true ? ' is-error' : ''),
700
+ 'data-kind': item.kind,
701
+ onClick: canExpand === true
702
+ ? () => {
703
+ const next = open === false
704
+ setOpen(next)
705
+ if (next === true && full === null) expand()
706
+ }
707
+ : undefined,
708
+ }, [
709
+ react.createElement('span', {
710
+ key: 'x',
711
+ className: 'dspsp-fold-btn' + (canExpand === true ? '' : ' is-empty'),
712
+ }, canExpand === true ? (open === true ? t('frame.collapse') : t('frame.expand')) : ''),
713
+ react.createElement('span', { key: 'k', className: 'dspsp-item-kind' }, label),
714
+ body,
715
+ ])
716
+ }
717
+
718
+ /** Group one chunk's items by turn and draw them. */
719
+ function renderItems(items, controller, t) {
720
+ const groups = []
721
+ let current = null
722
+ for (const item of items) {
723
+ const key = item.turn === null || item.turn === undefined ? 'none' : 't' + item.turn
724
+ if (current === null || current.key !== key) {
725
+ current = { key, turn: item.turn, items: [] }
726
+ groups.push(current)
727
+ }
728
+ current.items.push(item)
729
+ }
730
+ return groups.map((group) => {
731
+ const steps = group.items.filter((item) => item.kind === 'assistant').length
732
+ // A tool-call is a block inside the assistant message, not a message of
733
+ // its own; the tool RESULT is. Counting both double-counted every call.
734
+ const messages = group.items.filter((item) =>
735
+ item.kind === 'user' || item.kind === 'assistant' || item.kind === 'tool-result').length
736
+ const untagged = group.turn === null || group.turn === undefined
737
+ return react.createElement('div', { key: 'g' + group.key, className: 'dspsp-turn-block' }, [
738
+ react.createElement('div', { key: 'h', className: 'dspsp-turn-head' }, [
739
+ react.createElement('span', { key: 'n', className: 'dspsp-turn-n' },
740
+ untagged ? t('group.untagged') : formatText(t('turn.n'), { n: group.turn })),
741
+ react.createElement('span', { key: 'm', className: 'dspsp-turn-meta' },
742
+ untagged
743
+ ? formatText(t('turn.metaOnly'), { messages })
744
+ : formatText(t('turn.meta'), { steps, messages })),
745
+ ]),
746
+ react.createElement('div', { key: 'l', className: 'dspsp-turn-body' },
747
+ group.items.map((item) => react.createElement(ItemRow, {
748
+ key: 'i' + item.seq + '-' + item.kind, item, controller, t,
749
+ }))),
750
+ ])
751
+ })
752
+ }
753
+
754
+ /** One 200-item block of a window: its own fold, its own fetch. */
755
+ function ChunkBlock(props) {
756
+ const rows = props.rows
757
+ const index = props.index
758
+ const t = props.t
759
+ const chunk = rows.chunks.get(index)
760
+ const size = rows.chunkSize || 100
761
+ const total = rows.itemCount || 0
762
+ const expected = Math.max(0, Math.min(size, total - (index - 1) * size))
763
+ const [open, setOpen] = react.useState(false)
764
+ const count = chunk !== undefined && chunk.status === 'ready' ? chunk.items.length : expected
765
+ const head = react.createElement('div', {
766
+ className: 'dspsp-fold-head',
767
+ onClick: () => {
768
+ const next = open === false
769
+ setOpen(next)
770
+ if (next === true && (chunk === undefined || chunk.status === 'idle' || chunk.status === 'error')) {
771
+ props.controller.loadChunk(props.pageIndex, index)
772
+ }
773
+ },
774
+ }, [
775
+ react.createElement('span', { key: 'b', className: 'dspsp-fold-btn' },
776
+ open === true ? t('rows.collapse') : t('rows.expand')),
777
+ react.createElement('span', { key: 'l', className: 'dspsp-chunk-label' },
778
+ formatText(t('rows.chunk'), { i: index, n: count })),
779
+ ])
780
+ const body = []
781
+ if (open === true) {
782
+ if (chunk === undefined || chunk.status === 'loading') {
783
+ body.push(react.createElement('div', { key: 'l', className: 'dspsp-empty' }, t('rows.loading')))
784
+ } else if (chunk.status === 'error') {
785
+ body.push(react.createElement('div', { key: 'e', className: 'dspsp-empty' },
786
+ formatText(t('rows.failed'), { error: chunk.error })))
787
+ } else {
788
+ body.push(react.createElement('div', { key: 'b', className: 'dspsp-rows' },
789
+ renderItems(chunk.items, props.controller, t)))
790
+ }
791
+ }
792
+ return react.createElement('div', { className: 'dspsp-chunk' }, [head].concat(body))
793
+ }
794
+
795
+ function RowsBlock(props) {
796
+ const rows = props.rows
797
+ const count = rows.chunkCount === null ? 1 : rows.chunkCount
798
+ const out = []
799
+ for (let i = 1; i <= count; i += 1) {
800
+ out.push(react.createElement(ChunkBlock, {
801
+ key: 'c' + i, pageIndex: props.page.index, index: i, rows, controller: props.controller, t: props.t,
802
+ }))
803
+ }
804
+ return react.createElement('div', null, out)
805
+ }
806
+
807
+ function PageCard(props) {
808
+ const page = props.page
809
+ const rows = props.rows
810
+ const t = props.t
811
+ const meta = formatText(t('page.meta'), {
812
+ from: page.turnFrom === null ? '—' : page.turnFrom,
813
+ to: page.turnTo === null ? '—' : page.turnTo,
814
+ steps: page.steps,
815
+ messages: page.messages,
816
+ tools: page.toolCalls,
817
+ peak: formatCount(page.peakTokens),
818
+ })
819
+ const tag = page.compactionId === null
820
+ ? react.createElement('span', { className: 'dspsp-page-origin' }, t('page.origin'))
821
+ : react.createElement('span', { className: 'dspsp-tag' },
822
+ formatText(t('page.compacted'), { turn: page.turnFrom === null ? '—' : page.turnFrom }))
823
+
824
+ // Open/closed is local UI state; what was fetched lives in the controller,
825
+ // so collapsing and re-opening never refetches.
826
+ const [open, setOpen] = react.useState(false)
827
+ const loaded = rows.chunkCount !== null
828
+ const expanded = open === true && loaded === true
829
+ // The window-level label counts BLOCKS: the item count lives on each block.
830
+ const blockSize = rows.chunkSize || 100
831
+ const blocks = page.itemCount === null || page.itemCount === undefined
832
+ ? 0
833
+ : Math.ceil(page.itemCount / blockSize)
834
+ const toggle = react.createElement('button', {
835
+ className: 'dspsp-toggle',
836
+ onClick: () => {
837
+ const next = expanded === false
838
+ setOpen(next)
839
+ if (next === true && loaded === false) props.onLoadRows()
840
+ },
841
+ }, expanded
842
+ ? t('rows.collapse')
843
+ : blocks === 0 ? t('rows.expandEmpty') : formatText(t('rows.expand'), { n: blocks }))
844
+
845
+ const body = []
846
+ if (expanded === false) {
847
+ // collapsed: nothing else to draw
848
+ } else if (rows.chunkCount === null) {
849
+ body.push(react.createElement('div', { key: 'l', className: 'dspsp-empty' }, t('rows.loading')))
850
+ } else {
851
+ body.push(react.createElement(RowsBlock, { key: 'r', rows, page, controller: props.controller, t }))
852
+ }
853
+
854
+ return react.createElement('section', {
855
+ className: 'dspsp-page' + (props.isLast ? ' is-current' : ''),
856
+ 'data-dspsp-page': page.index,
857
+ }, [
858
+ react.createElement('div', { key: 'h', className: 'dspsp-page-head' }, [
859
+ react.createElement('span', { key: 't', className: 'dspsp-page-title' },
860
+ formatText(t('page.title'), { n: page.index })),
861
+ tag,
862
+ typeof page.startTime === 'number'
863
+ ? react.createElement('span', {
864
+ key: 'b',
865
+ className: 'dspsp-page-born',
866
+ title: new Date(page.startTime).toLocaleString(),
867
+ }, formatText(t('page.born'), { time: formatTime(page.startTime) }))
868
+ : null,
869
+ ]),
870
+ react.createElement(FrameBlock, { key: 'f', page, controller: props.controller, t }),
871
+ page.summaryChars > 0
872
+ ? react.createElement('div', { key: 'hint', className: 'dspsp-page-meta' }, t('frame.checkpointHint'))
873
+ : react.createElement('div', { key: 'hint', className: 'dspsp-page-meta' }, t('frame.noSummary')),
874
+ react.createElement('div', { key: 'b', className: 'dspsp-boundary' }, [
875
+ react.createElement('span', { key: 'l1', className: 'dspsp-boundary-line' }),
876
+ react.createElement('span', { key: 't', className: 'dspsp-boundary-text' },
877
+ formatText(t('page.boundary'), {
878
+ from: page.turnFrom === null ? '—' : page.turnFrom,
879
+ to: page.turnTo === null ? '—' : page.turnTo,
880
+ steps: page.steps,
881
+ messages: page.messages,
882
+ tools: page.toolCalls,
883
+ peak: formatCount(page.peakTokens),
884
+ })),
885
+ react.createElement('span', { key: 'l2', className: 'dspsp-boundary-line' }),
886
+ ]),
887
+ toggle,
888
+ ].concat(body))
889
+ }
890
+
891
+ // --- plugin ----------------------------------------------------------------
892
+
893
+ const TRIM_MODES = {
894
+ window: '裁窗口',
895
+ flatten: '折叠痕迹',
896
+ stream: '清流式回放',
897
+ lossless: '清理已遮蔽事件',
898
+ rebuild: '按表面重建',
899
+ }
900
+
901
+ /** "最近一次 2026-11-04 12:57(裁窗口,3→2 窗)" */
902
+ function trimTooltip(trim) {
903
+ const last = Array.isArray(trim.trims) && trim.trims.length > 0 ? trim.trims[trim.trims.length - 1] : null
904
+ const parts = []
905
+ if (last !== null && typeof last.at === 'string') {
906
+ const when = formatTime(Date.parse(last.at))
907
+ if (when !== null) parts.push('最近一次 ' + when)
908
+ const mode = TRIM_MODES[last.mode] || last.mode
909
+ const span = last.windowsBefore !== undefined && last.windowsAfter !== undefined
910
+ ? ',' + String(last.windowsBefore) + '→' + String(last.windowsAfter) + ' 窗'
911
+ : ''
912
+ if (typeof mode === 'string' && mode.length > 0) parts.push('(' + mode + span + ')')
913
+ }
914
+ if (Number.isFinite(trim.bytesSaved) && trim.bytesSaved > 0) {
915
+ parts.push('已省 ' + formatCount(trim.bytesSaved) + ' 字节')
916
+ }
917
+ return parts.filter((part) => part.length > 0).join(' · ')
918
+ }
919
+
920
+ function registerView(slots, controllerFor, t) {
921
+ slots.inject('conversation.view', () =>
922
+ slots.register(
923
+ {
924
+ name: 'conversation.view',
925
+ id: VIEW_ID,
926
+ order: VIEW_ORDER,
927
+ locale: NS,
928
+ label: () => t('view.windows'),
929
+ inject: (sessionId) => ({ controller: controllerFor(sessionId) }),
930
+ },
931
+ PagesView,
932
+ ),
933
+ )
934
+ }
935
+
936
+ function apply(ctx) {
937
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), NS + ': dictionaries')
938
+ const t = ctx.locale.bind(NS)
939
+
940
+ const controllers = new Map()
941
+ const controllerFor = (sessionId) => {
942
+ let controller = controllers.get(sessionId)
943
+ if (controller === undefined) {
944
+ controller = new PagesController(sessionId)
945
+ controllers.set(sessionId, controller)
946
+ }
947
+ return controller
948
+ }
949
+ ctx.effect(
950
+ () => () => {
951
+ for (const controller of controllers.values()) controller.detach()
952
+ controllers.clear()
953
+ },
954
+ NS + ': per-session controllers',
955
+ )
956
+
957
+ if (ctx.slots !== undefined && ctx.slots !== null) registerView(ctx.slots, controllerFor, t)
958
+ else if (typeof ctx.inject === 'function') ctx.inject(['slots'], (scope) => registerView(scope.slots, controllerFor, t))
959
+ }
960
+
961
+ exports.apply = apply
962
+ exports.inject = ['slots', 'locale']
963
+ exports.version = VERSION
964
+ exports.__test = {
965
+ NS, VERSION, ROUTE_PREFIX, VIEW_ID, VIEW_ORDER,
966
+ formatText, formatCount, zh, en, PagesController, PagesView, PageCard, FrameBlock, ItemRow, RowsBlock, registerView,
967
+ }
968
+ return module.exports
969
+ },
970
+ })