@nethiel/dsh-turn-report 0.0.0-stage → 0.1.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.
package/client.js ADDED
@@ -0,0 +1,940 @@
1
+ /**
2
+ * dsh-turn-report — browser half.
3
+ *
4
+ * Renders one card beneath every completed turn: emoji progress chips, a
5
+ * compact metrics table, the files this turn touched, and an ASCII project
6
+ * tree derived from the turn's todo snapshot.
7
+ *
8
+ * The value comes from the `turnReport` session projection — the host folds it
9
+ * from the session log, so this module only formats a finished object.
10
+ */
11
+
12
+ window.__ModuleLoader__.load({
13
+ // This id must equal the name the host registers the bundle under, which is the
14
+ // profile's dependency key — `dsh-turn-report`, not the scoped npm name. Using
15
+ // the npm name here made the host report `could not load "dsh-turn-report":
16
+ // loaded without registering "dsh-turn-report"` and then a duplicate-factory
17
+ // error, so the whole client half silently failed to mount.
18
+ id: '@nethiel/dsh-turn-report',
19
+ factory: (require) => {
20
+ const React = require('react')
21
+ const h = React.createElement
22
+
23
+ const NS = 'turnReport'
24
+
25
+ const copy = {
26
+ zh: {
27
+ title: '本轮项目汇报',
28
+ turn: '第 {n} 轮',
29
+ metric: '项',
30
+ value: '值',
31
+ tools: '工具调用',
32
+ failed: '失败',
33
+ files: '改动文件',
34
+ ended: '结束状态',
35
+ tree: '任务树',
36
+ treeSummary: '{done}/{total} 完成',
37
+ finished: '本轮完成',
38
+ finishedCount: '{n} 项',
39
+ llmCalls: '调用 {n} 次',
40
+ llmTokens: 'in {input} / out {output}',
41
+ llmCache: '缓存命中 {n}%',
42
+ llmDetailInput: '未缓存输入:{n}',
43
+ llmDetailCacheRead: '缓存读:{n}',
44
+ llmDetailCacheWrite: '缓存写:{n}',
45
+ llmDetailOutput: '输出:{n}',
46
+ llmDetailTotal: '合计:{n}',
47
+ sbPlan: '当前计划',
48
+ sbStale: '本轮未更新',
49
+ sbStaleFrom: '沿用第 {n} 轮清单',
50
+ sbStaleHint: '本轮没有写任务清单,上面是仍在生效的最近一份计划',
51
+ sbSeenAbove: '见上方',
52
+ sbCleared: '本轮清空了任务清单',
53
+ sbDecisions: '本轮决定',
54
+ emptySession: '本会话未使用任务清单(模型未调用 todo_write)',
55
+ hudTaskProgress: '任务 {done}/{total}',
56
+ hudGroupProgress: '已完成 {done}/{total}',
57
+ sbAllDone: '全部完成',
58
+ sbNext: '下一项',
59
+ sbExpand: '展开状态栏',
60
+ sbCollapse: '收起状态栏',
61
+ more: '还有 {n} 条未展开',
62
+ empty: '本轮没有任务清单',
63
+ filesLabel: '产出文件',
64
+ },
65
+ en: {
66
+ title: 'Turn report',
67
+ turn: 'Turn {n}',
68
+ metric: 'Metric',
69
+ value: 'Value',
70
+ tools: 'Tool calls',
71
+ failed: 'Failures',
72
+ files: 'Files changed',
73
+ ended: 'End state',
74
+ tree: 'Project tree',
75
+ treeSummary: '{done}/{total} done',
76
+ finished: 'Finished this turn',
77
+ finishedCount: '{n} items',
78
+ llmCalls: '{n} calls',
79
+ llmTokens: '{input} in / {output} out',
80
+ llmCache: '{n}% cached',
81
+ llmDetailInput: 'Uncached input: {n}',
82
+ llmDetailCacheRead: 'Cache read: {n}',
83
+ llmDetailCacheWrite: 'Cache write: {n}',
84
+ llmDetailOutput: 'Output: {n}',
85
+ llmDetailTotal: 'Total: {n}',
86
+ sbPlan: 'Current plan',
87
+ sbStale: 'not updated this turn',
88
+ sbStaleFrom: 'carried over from turn {n}',
89
+ sbStaleHint: 'This turn wrote no task list; the newest plan still in force is shown.',
90
+ sbSeenAbove: 'listed above',
91
+ sbCleared: 'the task list was cleared this turn',
92
+ sbDecisions: 'Decided this turn',
93
+ emptySession: 'No task list has been used in this session (the model never called todo_write)',
94
+ hudTaskProgress: 'tasks {done}/{total}',
95
+ hudGroupProgress: '{done}/{total} done',
96
+ sbAllDone: 'All done',
97
+ sbNext: 'Next',
98
+ sbExpand: 'Expand status bar',
99
+ sbCollapse: 'Collapse status bar',
100
+ more: '{n} more not shown',
101
+ empty: 'No task list this turn',
102
+ filesLabel: 'Files',
103
+ },
104
+ }
105
+
106
+ /** Status glyph and colour token per todo state. */
107
+ const STATUS = {
108
+ done: { icon: '✅', color: 'var(--dsw-alias-state-success-primary)' },
109
+ doing: { icon: '⏳', color: 'var(--dsw-alias-state-warn-primary)' },
110
+ left: { icon: '⬜', color: 'var(--dsw-alias-label-tertiary)' },
111
+ }
112
+
113
+ const style = {
114
+ card: {
115
+ marginTop: 8,
116
+ padding: '12px 14px',
117
+ border: '1px solid var(--dsw-alias-border-l2)',
118
+ borderRadius: 12,
119
+ background: 'var(--dsw-alias-bg-layer-1)',
120
+ color: 'var(--dsw-alias-label-primary)',
121
+ fontSize: 13,
122
+ lineHeight: 1.55,
123
+ },
124
+ head: {
125
+ display: 'flex',
126
+ alignItems: 'center',
127
+ gap: 8,
128
+ flexWrap: 'wrap',
129
+ marginBottom: 10,
130
+ },
131
+ title: { fontWeight: 600, fontSize: 13 },
132
+ turnBadge: {
133
+ fontSize: 11,
134
+ padding: '1px 7px',
135
+ borderRadius: 999,
136
+ border: '1px solid var(--dsw-alias-border-l3)',
137
+ color: 'var(--dsw-alias-label-secondary)',
138
+ },
139
+ chips: { marginLeft: 'auto', display: 'flex', gap: 10, fontSize: 12, fontVariantNumeric: 'tabular-nums' },
140
+ table: {
141
+ width: '100%',
142
+ borderCollapse: 'collapse',
143
+ fontSize: 12,
144
+ marginBottom: 10,
145
+ },
146
+ th: {
147
+ textAlign: 'left',
148
+ padding: '4px 8px',
149
+ fontWeight: 500,
150
+ color: 'var(--dsw-alias-label-secondary)',
151
+ borderBottom: '1px solid var(--dsw-alias-border-l2)',
152
+ },
153
+ td: {
154
+ padding: '4px 8px',
155
+ borderBottom: '1px solid var(--dsw-alias-border-l1)',
156
+ fontVariantNumeric: 'tabular-nums',
157
+ },
158
+ sectionTitle: {
159
+ display: 'flex',
160
+ alignItems: 'baseline',
161
+ gap: 6,
162
+ margin: '0 0 6px',
163
+ fontSize: 12,
164
+ fontWeight: 600,
165
+ color: 'var(--dsw-alias-label-secondary)',
166
+ },
167
+ pre: {
168
+ margin: 0,
169
+ padding: '8px 10px',
170
+ borderRadius: 8,
171
+ background: 'var(--dsw-alias-bg-module-platform)',
172
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
173
+ fontSize: 12,
174
+ lineHeight: 1.65,
175
+ // Long tree lines scroll inside the card instead of widening it.
176
+ overflowX: 'auto',
177
+ maxWidth: '100%',
178
+ boxSizing: 'border-box',
179
+ },
180
+ treeRow: {
181
+ display: 'flex',
182
+ alignItems: 'baseline',
183
+ whiteSpace: 'nowrap',
184
+ },
185
+ rail: {
186
+ // One fixed-width cell per level keeps every vertical aligned even when
187
+ // the box-drawing glyph comes from a fallback face.
188
+ display: 'inline-block',
189
+ width: '1.1em',
190
+ textAlign: 'center',
191
+ color: 'var(--dsw-alias-label-tertiary)',
192
+ },
193
+ branch: {
194
+ display: 'inline-block',
195
+ width: '1.6em',
196
+ textAlign: 'center',
197
+ color: 'var(--dsw-alias-label-tertiary)',
198
+ },
199
+ treeText: {
200
+ fontFamily: 'inherit',
201
+ whiteSpace: 'nowrap',
202
+ },
203
+ pendingBox: {
204
+ margin: '0 0 10px',
205
+ padding: '8px 10px',
206
+ borderRadius: 8,
207
+ border: '1px solid var(--dsw-alias-border-l2)',
208
+ background: 'var(--dsw-alias-bg-module-platform)',
209
+ },
210
+ llmLine: {
211
+ display: 'flex',
212
+ flexWrap: 'wrap',
213
+ alignItems: 'baseline',
214
+ gap: 6,
215
+ margin: '0 0 8px',
216
+ fontSize: 12,
217
+ color: 'var(--dsw-alias-label-secondary)',
218
+ fontVariantNumeric: 'tabular-nums',
219
+ },
220
+ llmModel: {
221
+ fontWeight: 600,
222
+ color: 'var(--dsw-alias-label-primary)',
223
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
224
+ fontSize: 11.5,
225
+ },
226
+ // ── plan HUD (inside the turn-end card) ───────────────────────────────
227
+ hud: {
228
+ margin: '0 0 10px',
229
+ padding: '8px 10px',
230
+ borderRadius: 8,
231
+ border: '1px solid var(--dsw-alias-border-l2)',
232
+ background: 'var(--dsw-alias-bg-module-platform)',
233
+ fontVariantNumeric: 'tabular-nums',
234
+ },
235
+ hudBar: {
236
+ display: 'flex',
237
+ alignItems: 'center',
238
+ gap: 8,
239
+ flexWrap: 'wrap',
240
+ lineHeight: 1.6,
241
+ },
242
+ hudProgress: {
243
+ flex: '1 1 200px',
244
+ minWidth: 140,
245
+ height: 8,
246
+ borderRadius: 4,
247
+ background: 'var(--dsw-alias-border-l2)',
248
+ overflow: 'hidden',
249
+ display: 'block',
250
+ boxSizing: 'border-box',
251
+ },
252
+ hudProgressFill: {
253
+ display: 'block',
254
+ height: '100%',
255
+ borderRadius: 4,
256
+ transition: 'width .25s ease',
257
+ },
258
+ hudCount: {
259
+ fontWeight: 600,
260
+ color: 'var(--dsw-alias-label-primary)',
261
+ fontVariantNumeric: 'tabular-nums',
262
+ },
263
+ hudChip: { color: 'var(--dsw-alias-label-secondary)', fontSize: 12 },
264
+ hudChipZero: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12, opacity: 0.45 },
265
+ hudAllDone: { color: 'var(--dsw-alias-state-success-primary, #2f9e5e)', fontSize: 12 },
266
+ hudNextRow: {
267
+ marginTop: 4,
268
+ fontSize: 12,
269
+ color: 'var(--dsw-alias-label-secondary)',
270
+ overflow: 'hidden',
271
+ textOverflow: 'ellipsis',
272
+ whiteSpace: 'nowrap',
273
+ },
274
+ sbSection: { marginTop: 6 },
275
+ sbSectionTitle: {
276
+ fontSize: 11,
277
+ color: 'var(--dsw-alias-label-tertiary)',
278
+ letterSpacing: '.02em',
279
+ marginBottom: 2,
280
+ },
281
+ sbGroupTitle: {
282
+ display: 'flex',
283
+ alignItems: 'center',
284
+ gap: 7,
285
+ width: '100%',
286
+ border: '1px solid var(--dsw-alias-border-l2)',
287
+ background: 'var(--dsw-alias-bg-layer-1)',
288
+ color: 'var(--dsw-alias-label-primary)',
289
+ font: 'inherit',
290
+ textAlign: 'left',
291
+ cursor: 'pointer',
292
+ padding: '4px 8px',
293
+ borderRadius: 6,
294
+ marginTop: 3,
295
+ },
296
+ sbGroupTitleOpen: {
297
+ display: 'flex',
298
+ alignItems: 'center',
299
+ gap: 7,
300
+ width: '100%',
301
+ border: '1px solid var(--dsw-alias-border-l2)',
302
+ background: 'var(--dsw-alias-bg-module-platform)',
303
+ color: 'var(--dsw-alias-label-primary)',
304
+ font: 'inherit',
305
+ textAlign: 'left',
306
+ cursor: 'pointer',
307
+ padding: '4px 8px',
308
+ borderRadius: 6,
309
+ marginTop: 3,
310
+ },
311
+ sbChevron: {
312
+ display: 'inline-block',
313
+ width: '1em',
314
+ textAlign: 'center',
315
+ color: 'var(--dsw-alias-label-secondary)',
316
+ fontSize: 9,
317
+ lineHeight: 1,
318
+ },
319
+ sbGroupLabel: { fontWeight: 600 },
320
+ // An empty HUD slot: present, but visibly inert.
321
+ sbGroupEmpty: {
322
+ display: 'flex',
323
+ alignItems: 'center',
324
+ gap: 7,
325
+ width: '100%',
326
+ border: '1px dashed var(--dsw-alias-border-l2)',
327
+ background: 'transparent',
328
+ padding: '4px 8px',
329
+ borderRadius: 6,
330
+ marginTop: 3,
331
+ boxSizing: 'border-box',
332
+ opacity: 0.55,
333
+ cursor: 'default',
334
+ },
335
+ sbGroupLabelEmpty: { fontWeight: 400, color: 'var(--dsw-alias-label-tertiary)' },
336
+ // A section whose rows already appear in the finished block above.
337
+ sbGroupSuppressed: {
338
+ display: 'flex',
339
+ alignItems: 'center',
340
+ gap: 7,
341
+ width: '100%',
342
+ border: '1px solid var(--dsw-alias-border-l2)',
343
+ background: 'transparent',
344
+ padding: '4px 8px',
345
+ borderRadius: 6,
346
+ marginTop: 3,
347
+ boxSizing: 'border-box',
348
+ opacity: 0.7,
349
+ cursor: 'default',
350
+ },
351
+ sbSeenAbove: {
352
+ marginLeft: 'auto',
353
+ fontSize: 10,
354
+ color: 'var(--dsw-alias-label-tertiary)',
355
+ },
356
+ sbCleared: {
357
+ fontSize: 12,
358
+ color: 'var(--dsw-alias-label-secondary)',
359
+ padding: '2px 0',
360
+ },
361
+ sbDecision: {
362
+ fontSize: 12,
363
+ lineHeight: 1.6,
364
+ color: 'var(--dsw-alias-label-primary)',
365
+ borderLeft: '2px solid var(--dsw-alias-border-l2)',
366
+ paddingLeft: 8,
367
+ margin: '2px 0',
368
+ overflow: 'hidden',
369
+ textOverflow: 'ellipsis',
370
+ whiteSpace: 'nowrap',
371
+ },
372
+ sbStale: {
373
+ marginLeft: 6,
374
+ padding: '0 5px',
375
+ borderRadius: 6,
376
+ border: '1px solid var(--dsw-alias-border-l2)',
377
+ fontSize: 10,
378
+ fontWeight: 400,
379
+ color: 'var(--dsw-alias-label-tertiary)',
380
+ letterSpacing: '0.02em',
381
+ },
382
+ sbGroupCount: {
383
+ marginLeft: 'auto',
384
+ fontSize: 11,
385
+ color: 'var(--dsw-alias-label-tertiary)',
386
+ fontVariantNumeric: 'tabular-nums',
387
+ background: 'var(--dsw-alias-bg-module-platform)',
388
+ borderRadius: 6,
389
+ padding: '0 5px',
390
+ },
391
+ sbRow: {
392
+ padding: '1px 0 1px 14px',
393
+ overflow: 'hidden',
394
+ textOverflow: 'ellipsis',
395
+ whiteSpace: 'nowrap',
396
+ },
397
+ pendingRow: {
398
+ display: 'flex',
399
+ alignItems: 'baseline',
400
+ gap: 6,
401
+ fontSize: 12.5,
402
+ lineHeight: 1.7,
403
+ },
404
+ pendingIcon: { flex: '0 0 auto' },
405
+ pendingText: { flex: '1 1 auto', minWidth: 0 },
406
+ files: {
407
+ margin: '0 0 10px',
408
+ display: 'flex',
409
+ flexWrap: 'wrap',
410
+ gap: 6,
411
+ fontSize: 12,
412
+ color: 'var(--dsw-alias-label-secondary)',
413
+ maxWidth: '100%',
414
+ },
415
+ file: {
416
+ padding: '1px 7px',
417
+ borderRadius: 6,
418
+ border: '1px solid var(--dsw-alias-border-l2)',
419
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
420
+ // A chip never grows past the card; the full path stays in its tooltip.
421
+ maxWidth: '100%',
422
+ overflow: 'hidden',
423
+ textOverflow: 'ellipsis',
424
+ whiteSpace: 'nowrap',
425
+ fontSize: 11,
426
+ },
427
+ more: { marginTop: 4, fontSize: 11, color: 'var(--dsw-alias-label-tertiary)' },
428
+ // Explains an otherwise-empty card. Dimmer than body text but not as faint as
429
+ // the overflow counter, because it is the only thing the card is saying.
430
+ emptyNote: {
431
+ marginTop: 2,
432
+ fontSize: 12,
433
+ lineHeight: 1.6,
434
+ color: 'var(--dsw-alias-label-secondary)',
435
+ },
436
+ }
437
+
438
+ /**
439
+ * Fill `{name}` placeholders in a locale string.
440
+ * @param {string} text - the template.
441
+ * @param {object} params - replacement values.
442
+ * @returns {string} the filled text.
443
+ */
444
+ function fmt(text, params) {
445
+ return String(text).replace(/\{(\w+)\}/g, (_, key) => (params[key] === undefined ? '' : String(params[key])))
446
+ }
447
+
448
+ /**
449
+ * Compact token count: 999 → `999`, 1234 → `1.2k`, 468123 → `468k`.
450
+ * @param {number} value - the count.
451
+ * @returns {string} the display form.
452
+ */
453
+ function shortTokens(value) {
454
+ const n = typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
455
+ if (n < 1000) return String(n)
456
+ if (n < 10000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k'
457
+ if (n < 1000000) return Math.round(n / 1000) + 'k'
458
+ return (n / 1000000).toFixed(1).replace(/\.0$/, '') + 'M'
459
+ }
460
+
461
+ /**
462
+ * Cache hit share of the prompt, as a whole percent.
463
+ * @param {object} usage - the turn's token buckets.
464
+ * @returns {number | null} the percent, or null when the prompt was empty.
465
+ */
466
+ function cacheHitPercent(usage) {
467
+ const prompt = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0)
468
+ if (prompt <= 0) return null
469
+ return Math.round(((usage.cacheRead ?? 0) / prompt) * 100)
470
+ }
471
+
472
+ /**
473
+ * One-line token summary: `input / output` plus cache hit when known.
474
+ * @param {object} usage - the turn's token buckets.
475
+ * @param {function} label - locale lookup.
476
+ * @returns {string} the summary.
477
+ */
478
+ function tokenSummary(usage, label) {
479
+ const shown = fmt(label('llmTokens'), {
480
+ input: shortTokens(usage.input),
481
+ output: shortTokens(usage.output),
482
+ })
483
+ const hit = cacheHitPercent(usage)
484
+ return hit === null ? shown : shown + ' · ' + fmt(label('llmCache'), { n: hit })
485
+ }
486
+
487
+ /**
488
+ * Full breakdown for the hover title, where exact numbers belong.
489
+ * @param {object} usage - the turn's token buckets.
490
+ * @param {function} label - locale lookup.
491
+ * @returns {string} the tooltip text.
492
+ */
493
+ function tokenDetail(usage, label) {
494
+ // Sum the buckets we display rather than echoing the provider's total: if a
495
+ // provider reports an inconsistent total, a tooltip whose parts do not add
496
+ // up reads as a bug.
497
+ const sum = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0) + (usage.output ?? 0)
498
+ return [
499
+ fmt(label('llmDetailInput'), { n: usage.input ?? 0 }),
500
+ fmt(label('llmDetailCacheRead'), { n: usage.cacheRead ?? 0 }),
501
+ fmt(label('llmDetailCacheWrite'), { n: usage.cacheWrite ?? 0 }),
502
+ fmt(label('llmDetailOutput'), { n: usage.output ?? 0 }),
503
+ fmt(label('llmDetailTotal'), { n: sum }),
504
+ ].join('\n')
505
+ }
506
+
507
+ /**
508
+ * Turn the flat todo rows into tree rows carrying a rail prefix and an indent.
509
+ *
510
+ * The rails are drawn as per-level segments with CSS indent rather than as a
511
+ * padded string: box-drawing glyphs (`│ ├─ └─`) only join when every glyph
512
+ * comes from one monospace face, and a fallback face breaks the alignment.
513
+ * Splitting the prefix into one span per level makes each segment's width
514
+ * explicit, so the verticals line up under any font.
515
+ * @param {object[]} rows - rows of `{ s, c, d }`.
516
+ * @returns {object[]} rows of `{ s, c, d, rail }` where rail is one string per level.
517
+ */
518
+ function treeLines(rows) {
519
+ const lines = []
520
+ const lastAt = []
521
+ for (let index = 0; index < rows.length; index += 1) {
522
+ const row = rows[index]
523
+ const depth = Math.max(0, Math.min(Number(row.d) || 0, lastAt.length))
524
+ lastAt.length = depth
525
+ let isLast = true
526
+ for (let next = index + 1; next < rows.length; next += 1) {
527
+ const nextDepth = Number(rows[next].d) || 0
528
+ if (nextDepth > depth) continue
529
+ isLast = nextDepth < depth
530
+ break
531
+ }
532
+ const rail = []
533
+ for (let level = 0; level < depth; level += 1) rail.push(lastAt[level] === true ? ' ' : '│ ')
534
+ const branch = depth === 0 && rows.length === 1 ? '' : isLast ? '└─' : '├─'
535
+ const status = STATUS[row.s] ?? STATUS.left
536
+ lines.push({ s: row.s, c: row.c, d: depth, rail, branch, icon: status.icon })
537
+ lastAt[depth] = isLast
538
+ }
539
+ return lines
540
+ }
541
+
542
+ /**
543
+ * Render the completed-turn card.
544
+ * @param {object} props - slot props.
545
+ * @returns {object | null} the card, or null when this turn has no report.
546
+ */
547
+ function TurnReport(props) {
548
+ const { turn, useProjection, t } = props
549
+ // Keep the hook call unconditional: returning before it on a missing view
550
+ // would change the hook count on the next render (React #310).
551
+ let view
552
+ try {
553
+ view = useProjection('turnReport')
554
+ } catch {
555
+ view = undefined
556
+ }
557
+ // Explicit fold overrides per section. Absent keys fall back to the default
558
+ // (finished sections folded, active ones open).
559
+ const [overrides, setOverrides] = React.useState(() => new Map())
560
+ const toggleSection = (index, open) => {
561
+ setOverrides((current) => {
562
+ const next = new Map(current)
563
+ next.set(index, open)
564
+ return next
565
+ })
566
+ }
567
+ if (view === undefined || view === null || view.turns === undefined) return null
568
+ if (turn === undefined || turn.end === undefined) return null
569
+ const entry = view.turns[String(turn.turn)]
570
+ if (entry === undefined || entry === null) return null
571
+
572
+ const opts = view.opts ?? {}
573
+ const todo = entry.todo
574
+ if (todo === null && opts.showWithoutTasks !== true) return null
575
+
576
+ // Decide the todo area up front: the header's plan-wide chips belong to the
577
+ // whole-plan view only. In the default view the card reports what this turn
578
+ // finished, and the live plan counts live in the built-in input-dock panel.
579
+ const finished = Array.isArray(todo?.finished) ? todo.finished : []
580
+ const todoView = opts.todoView ?? 'auto'
581
+ const showsWholePlan = opts.showTree !== false
582
+ && todo !== null && todo.rows.length > 0
583
+ && (todoView === 'both' || todoView === 'tree')
584
+ const showFinished = opts.showFinished !== false && finished.length > 0
585
+ && (todoView === 'both' || todoView === 'auto')
586
+
587
+ const label = typeof t === 'function' ? t : key => (copy.zh[key] ?? key)
588
+ const head = []
589
+ head.push(h('span', { key: 't', style: style.title }, '📊 ' + label('title')))
590
+ head.push(h('span', { key: 'n', style: style.turnBadge }, fmt(label('turn'), { n: entry.n })))
591
+
592
+ if (showsWholePlan) {
593
+ const chips = []
594
+ if (todo.done > 0) chips.push(h('span', { key: 'd' }, '✅ ' + todo.done))
595
+ if (todo.doing > 0) chips.push(h('span', { key: 'g' }, '⏳ ' + todo.doing))
596
+ if (todo.left > 0) chips.push(h('span', { key: 'l' }, '⬜ ' + todo.left))
597
+ if (chips.length > 0) head.push(h('span', { key: 'c', style: style.chips }, chips))
598
+ }
599
+
600
+ // One line of execution facts: which model answered, how many times it was
601
+ // asked, and what it cost. The built-in usage panel shows a turn total but
602
+ // never the call count, and this line stays readable without opening anything.
603
+ const llm = entry.llm
604
+ let llmLine = null
605
+ if (opts.showLlm !== false && llm !== null && llm !== undefined && (llm.calls ?? 0) > 0) {
606
+ const parts = []
607
+ const routes = Array.isArray(llm.models) && llm.models.length > 0 ? llm.models : []
608
+ if (routes.length > 0) {
609
+ parts.push(h('span', {
610
+ key: 'm',
611
+ style: style.llmModel,
612
+ title: routes.join(', '),
613
+ }, routes.map(route => String(route).split('/').pop()).join(' + ')))
614
+ }
615
+ parts.push(h('span', { key: 'c' }, fmt(label('llmCalls'), { n: llm.calls })))
616
+ const usage = llm.usage ?? {}
617
+ if ((usage.total ?? 0) > 0) {
618
+ parts.push(h('span', { key: 't', title: tokenDetail(usage, label) }, tokenSummary(usage, label)))
619
+ }
620
+ llmLine = h('div', { key: 'llm', style: style.llmLine }, '⚙️ ', parts)
621
+ }
622
+
623
+ const rows = [
624
+ [label('tools'), String(entry.tools ?? 0)],
625
+ ]
626
+ // A failure count of zero is good news and needs no row; showing "失败 0" on
627
+ // every clean turn just makes the table longer without saying anything.
628
+ if ((entry.failed ?? 0) > 0) rows.push([label('failed'), String(entry.failed)])
629
+ if (opts.showFiles !== false) rows.push([label('files'), String((entry.files ?? []).length)])
630
+ rows.push([label('ended'), String(entry.end ?? 'completed')])
631
+
632
+ const table = h('table', { style: style.table, key: 'table' }, [
633
+ h('thead', { key: 'h' }, h('tr', null, [
634
+ h('th', { key: 'a', style: style.th }, label('metric')),
635
+ h('th', { key: 'b', style: style.th }, label('value')),
636
+ ])),
637
+ h('tbody', { key: 'b' }, rows.map((row, index) => h('tr', { key: String(index) },
638
+ h('td', { style: style.td }, row[0]),
639
+ h('td', { style: style.td }, row[1])))),
640
+ ])
641
+
642
+ const blocks = []
643
+ if (llmLine !== null) blocks.push(llmLine)
644
+ blocks.push(table)
645
+
646
+ if (opts.showFiles !== false && Array.isArray(entry.files) && entry.files.length > 0) {
647
+ blocks.push(h('div', { key: 'files', style: style.files },
648
+ h('span', { key: 'l' }, '📄 ' + label('filesLabel')),
649
+ entry.files.map((file, index) => h('code', { key: String(index), style: style.file, title: file }, file))))
650
+ }
651
+
652
+ // The card reports what this turn FINISHED, never the current list.
653
+ // The built-in input-dock panel already renders the live list and its
654
+ // counts, so repeating it here would be pure duplication; "newly finished"
655
+ // is the one todo fact that panel does not have.
656
+ let finishedBox = null
657
+ if (showFinished) {
658
+ finishedBox = h('div', { key: 'finished', style: style.pendingBox },
659
+ h('div', { key: 'h', style: style.sectionTitle },
660
+ h('span', null, '📝 ' + label('finished')),
661
+ h('span', { style: style.turnBadge }, fmt(label('finishedCount'), {
662
+ n: finished.length + (todo.finishedMore ?? 0),
663
+ }))),
664
+ finished.map((row, index) => h('div', { key: String(index), style: style.pendingRow, 'data-finished': '1' },
665
+ h('span', { key: 'i', style: style.pendingIcon }, '✅'),
666
+ h('span', { key: 'c', style: style.pendingText }, row.c))),
667
+ (todo.finishedMore ?? 0) > 0
668
+ ? h('div', { key: 'm', style: style.more }, '… ' + fmt(label('more'), { n: todo.finishedMore }))
669
+ : null)
670
+ blocks.push(finishedBox)
671
+ }
672
+
673
+ // The plan HUD: progress strip and the plan by section, each section foldable.
674
+ // `entry.plan` is this turn's own list when it wrote one; otherwise the newest
675
+ // list still in force, flagged `stale` so the HUD can say "this turn did not
676
+ // update the plan" instead of silently repeating identical blocks.
677
+ //
678
+ // When the finished block already lists exactly the rows a finished section
679
+ // would show, that section is redundant — the same five lines appeared twice
680
+ // on every all-done turn. Such a section is passed to the HUD as
681
+ // `suppressed`, which renders its heading and count but not its rows.
682
+ const plan = entry.plan ?? null
683
+ // Decisions the person stated this turn, quoted verbatim. This sits above the
684
+ // plan because it explains WHY the plan may differ from the previous turn —
685
+ // and it is the only block that survives a turn whose task list did not change.
686
+ if (opts.showStatusBar !== false && Array.isArray(entry.decisions) && entry.decisions.length > 0) {
687
+ blocks.push(h('div', { key: 'decisions', style: style.hud },
688
+ h('div', { key: 'h', style: style.sbSectionTitle }, '💬 ' + label('sbDecisions')),
689
+ entry.decisions.map((text, index) => h('div', {
690
+ key: String(index),
691
+ style: style.sbDecision,
692
+ 'data-decision': '1',
693
+ title: text,
694
+ }, '“' + text + '”'))))
695
+ }
696
+ // A cleared plan is news: say so, rather than falling silent. Silence here is
697
+ // indistinguishable from "no plan ever existed", which is a different fact.
698
+ if (opts.showStatusBar !== false && plan === null && entry.cleared === true) {
699
+ blocks.push(h('div', { key: 'cleared', style: style.hud },
700
+ h('div', { key: 'h', style: style.sbSectionTitle }, '📋 ' + label('sbPlan')),
701
+ h('div', { key: 'c', style: style.sbCleared }, '🗑 ' + label('sbCleared'))))
702
+ }
703
+ if (opts.showStatusBar !== false && plan !== null && plan.total > 0) {
704
+ const finishedKeys = new Set(finished.map(row => row.c))
705
+ const sections = plan.groups.map((group) => {
706
+ // Only a FULLY completed section can be covered by the finished block.
707
+ // Testing coverage without the completeness condition suppressed a 0/1
708
+ // pending section too, because its single row's text happened to match a
709
+ // finished row from a DIFFERENT section with the same name. The section
710
+ // kept its heading but lost its rows and its expander, so pending work
711
+ // became invisible.
712
+ const fullyDone = group.total > 0 && group.done === group.total
713
+ const covered = finishedBox !== null
714
+ && fullyDone
715
+ && group.children.length === group.total
716
+ && group.children.every(row => finishedKeys.has(row.c))
717
+ return covered ? { ...group, suppressed: true } : group
718
+ })
719
+ blocks.push(planHud({ ...plan, groups: sections }, label, overrides, toggleSection))
720
+ }
721
+
722
+ if (showsWholePlan) {
723
+ const lines = treeLines(todo.rows)
724
+ const tree = [
725
+ h('div', { key: 'h', style: style.sectionTitle },
726
+ h('span', null, '📦 ' + label('tree')),
727
+ h('span', { style: style.turnBadge }, fmt(label('treeSummary'), { done: todo.done, total: todo.total }))),
728
+ h('div', { key: 'p', style: style.pre }, lines.map((line, index) => h('div', {
729
+ key: String(index),
730
+ style: style.treeRow,
731
+ 'data-depth': String(line.d),
732
+ },
733
+ line.rail.map((segment, level) => h('span', { key: 'r' + level, style: style.rail }, segment)),
734
+ h('span', { style: style.branch }, line.branch),
735
+ h('span', { style: style.treeText }, line.icon + ' ' + line.c)))),
736
+ ]
737
+ if (todo.more > 0) tree.push(h('div', { key: 'm', style: style.more }, '… ' + fmt(label('more'), { n: todo.more })))
738
+ blocks.push(h('div', { key: 'tree' }, tree))
739
+ }
740
+
741
+ // Two different silences, and the reader needs to tell them apart:
742
+ // - this turn wrote no list, but the session has used one → nothing to add
743
+ // - the session has NEVER used a list → say so, or the empty card reads as
744
+ // "the plugin is broken" rather than "this conversation never planned"
745
+ //
746
+ // The test is "no plan block was rendered", not "the card has only one block":
747
+ // a card that also lists touched files has two blocks and would otherwise stay
748
+ // silent about why the plan area is missing.
749
+ const renderedPlan = blocks.some(block => block?.props?.['data-plan'] !== undefined
750
+ || block?.props?.['data-stale'] !== undefined)
751
+ if (todo === null && plan === null && !renderedPlan) {
752
+ blocks.push(h('div', {
753
+ key: 'empty',
754
+ style: style.emptyNote,
755
+ 'data-no-plan': entry.sessionHasPlan === true ? 'turn' : 'session',
756
+ }, entry.sessionHasPlan === true ? label('empty') : label('emptySession')))
757
+ }
758
+
759
+ return h('section', {
760
+ style: style.card,
761
+ 'data-turn-report': String(entry.n),
762
+ 'aria-label': label('title') + ' ' + fmt(label('turn'), { n: entry.n }),
763
+ }, head, blocks)
764
+ }
765
+
766
+ /**
767
+ * Game-style status bar under the composer: a plan progress strip that stays
768
+ * put across turns, with one collapsible section per first-level task group.
769
+ *
770
+ * It shows a focused slice (what just finished, what is next), not the whole
771
+ * list — the built-in panel above the composer already owns the full list.
772
+ /**
773
+ * Game-HUD plan strip rendered INSIDE the turn-end card.
774
+ *
775
+ * It sits with the card rather than pinned near the composer: the plan belongs
776
+ * to the turn that just ended, and the conversation column is where a reader
777
+ * looks for "what did that turn do". A plain function, not a component, so it
778
+ * adds no hooks of its own — the card owns the fold state.
779
+ * @param {object} plan - this turn's frozen plan snapshot.
780
+ * @param {function} label - locale lookup.
781
+ * @param {Map<number, boolean>} overrides - reader-opened/closed sections.
782
+ * @param {function} toggle - record one section's explicit fold state.
783
+ * @returns {object} the block.
784
+ */
785
+ function planHud(plan, label, overrides, toggle) {
786
+ const pct = plan.total > 0 ? Math.round((plan.done / plan.total) * 100) : 0
787
+ const allDone = plan.left === 0 && plan.doing === 0
788
+ const bar = h('div', { key: 'bar', style: style.hudBar },
789
+ h('span', {
790
+ key: 'p',
791
+ // A 0% rail is just an empty grey strip, which reads as "broken" rather
792
+ // than "nothing done yet"; a dashed outline says 0% on purpose.
793
+ style: pct === 0
794
+ ? { ...style.hudProgress, border: '1px dashed var(--dsw-alias-border-l3, #c9ccd1)' }
795
+ : style.hudProgress,
796
+ },
797
+ h('span', {
798
+ style: {
799
+ ...style.hudProgressFill,
800
+ width: pct + '%',
801
+ background: allDone
802
+ ? 'var(--dsw-alias-state-success-primary, #2f9e5e)'
803
+ : 'var(--dsw-alias-state-business-primary, #3f6fd8)',
804
+ },
805
+ })),
806
+ h('span', { key: 'n', style: style.hudCount }, fmt(label('hudTaskProgress'), { done: plan.done, total: plan.total })),
807
+ // The three counters are a fixed HUD readout: a game bar does not hide the
808
+ // "0" slots, and a missing group read as "the plugin lost my todo". They are
809
+ // always present; a zero is dimmed rather than dropped.
810
+ h('span', { key: 'd', style: plan.done > 0 ? style.hudChip : style.hudChipZero }, '✅ ' + plan.done),
811
+ h('span', { key: 'g', style: plan.doing > 0 ? style.hudChip : style.hudChipZero }, '⏳ ' + plan.doing),
812
+ h('span', { key: 'l', style: plan.left > 0 ? style.hudChip : style.hudChipZero }, '⬜ ' + plan.left),
813
+ allDone ? h('span', { key: 'a', style: style.hudAllDone }, '✨ ' + label('sbAllDone')) : null)
814
+
815
+ const parts = [bar]
816
+ // No separate "next up" line: the in-progress section below already lists
817
+ // that exact item, and repeating it three lines above said it twice. The next
818
+ // item is only worth its own row when no in-progress section will show it —
819
+ // i.e. when everything left is still just pending.
820
+ const hasRunningSection = plan.groups.some(group => group.k === 'doing' && group.total > 0)
821
+ if (!allDone && !hasRunningSection && plan.nextUp.length > 0) {
822
+ parts.push(h('div', {
823
+ key: 'next',
824
+ style: style.hudNextRow,
825
+ title: plan.nextUp.map(row => row.c).join('\n'),
826
+ }, '⏭ ' + label('sbNext') + ':' + plan.nextUp[0].c))
827
+ }
828
+
829
+ const sections = plan.groups.map((group, index) => {
830
+
831
+ // Finished work starts folded — it is already listed as "本轮完成" above.
832
+ // Exception: when it is the ONLY non-empty section, folding it leaves the
833
+ // card looking empty, so open it. Pending and in-progress always open.
834
+ const populated = plan.groups.filter(candidate => candidate.empty !== true)
835
+ const onlyGroup = populated.length === 1 && populated[0] === group
836
+ const defaultOpen = group.startOpen !== false || onlyGroup
837
+ const isOpen = group.empty === true
838
+ ? false
839
+ : overrides.has(index) ? overrides.get(index) : defaultOpen
840
+
841
+ // A section whose rows are already listed verbatim in the "本轮完成" block above
842
+ // shows its heading and count only — no chevron, since there is nothing new to
843
+ // reveal. This is what stops an all-done turn from printing the same five
844
+ // lines twice.
845
+ if (group.suppressed === true) {
846
+ return h('div', {
847
+ key: 'g' + index,
848
+ style: style.sbGroupSuppressed,
849
+ 'data-group': group.k,
850
+ 'data-suppressed': '1',
851
+ title: label('sbSeenAbove'),
852
+ },
853
+ h('span', { key: 'i' }, (STATUS[group.s] ?? STATUS.left).icon),
854
+ h('span', { key: 't', style: style.sbGroupLabel }, group.t),
855
+ h('span', { key: 'n', style: style.sbGroupCount }, fmt(label('hudGroupProgress'), { done: group.done, total: group.total })),
856
+ h('span', { key: 'h', style: style.sbSeenAbove }, label('sbSeenAbove')))
857
+ }
858
+
859
+ // An empty slot stays visible but goes flat: no chevron, no button, no
860
+ // click target. It reports "0 here", not "you can open this".
861
+ if (group.empty === true) {
862
+ return h('div', {
863
+ key: 'g' + index,
864
+ style: style.sbGroupEmpty,
865
+ 'data-group': group.k,
866
+ 'data-empty': '1',
867
+ },
868
+ h('span', { key: 'i' }, (STATUS[group.s] ?? STATUS.left).icon),
869
+ h('span', { key: 't', style: style.sbGroupLabelEmpty }, group.t),
870
+ h('span', { key: 'n', style: style.sbGroupCount }, '0'))
871
+ }
872
+
873
+ return h('div', { key: 'g' + index, 'data-group': group.k },
874
+ h('button', {
875
+ type: 'button',
876
+ style: isOpen ? style.sbGroupTitleOpen : style.sbGroupTitle,
877
+ 'aria-expanded': isOpen ? 'true' : 'false',
878
+ 'data-toggle': group.k,
879
+ onClick: () => { toggle(index, !isOpen) },
880
+ },
881
+ h('span', { key: 'c', style: style.sbChevron }, isOpen ? '▼' : '▶'),
882
+ h('span', { key: 'i' }, (STATUS[group.s] ?? STATUS.left).icon),
883
+ h('span', { key: 't', style: style.sbGroupLabel }, group.t),
884
+ h('span', { key: 'n', style: style.sbGroupCount }, fmt(label('hudGroupProgress'), { done: group.done, total: group.total }))),
885
+ isOpen
886
+ ? group.children.map((row, childIndex) => h('div', {
887
+ key: String(childIndex),
888
+ style: { ...style.sbRow, paddingLeft: 24 + (row.d ?? 0) * 12 },
889
+ 'data-child': group.k,
890
+ },
891
+ (STATUS[row.s] ?? STATUS.left).icon + ' ' + row.c))
892
+ : null)
893
+ })
894
+
895
+ parts.push(h('div', { key: 'groups', style: style.sbSection },
896
+ h('div', { key: 'h', style: style.sbSectionTitle },
897
+ '📋 ' + label('sbPlan'),
898
+ // "not updated this turn" alone leaves the reader guessing how old the plan
899
+ // is. Naming the turn it came from ("carried over from turn 2") is what
900
+ // makes the plan's age something they can judge.
901
+ plan.stale === true
902
+ ? h('span', {
903
+ key: 's',
904
+ style: style.sbStale,
905
+ title: label('sbStaleHint'),
906
+ }, plan.sourceTurn === undefined || plan.sourceTurn === null
907
+ ? label('sbStale')
908
+ : fmt(label('sbStaleFrom'), { n: plan.sourceTurn }))
909
+ : null),
910
+ sections))
911
+ if (plan.more > 0) parts.push(h('div', { key: 'more', style: style.more }, '… ' + fmt(label('more'), { n: plan.more })))
912
+
913
+ return h('div', {
914
+ key: 'plan',
915
+ style: plan.stale === true ? { ...style.hud, opacity: 0.82 } : style.hud,
916
+ 'data-stale': plan.stale === true ? '1' : undefined,
917
+ }, parts)
918
+ }
919
+
920
+ /**
921
+ * Register the card and its dictionaries.
922
+ * @param {object} ctx - client context.
923
+ * @returns {void}
924
+ */
925
+ function apply(ctx) {
926
+ if (ctx.locale !== undefined) {
927
+ ctx.effect(() => ctx.locale.register(NS, { zh: copy.zh, en: copy.en }), 'turn-report: dictionaries')
928
+ }
929
+ ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
930
+ name: 'conversation.chat.turnTail',
931
+ id: '@nethiel/dsh-turn-report',
932
+ order: -10,
933
+ locale: NS,
934
+ }, TurnReport))
935
+ }
936
+
937
+ return { inject: ['slots', 'locale'], apply, TurnReport, planHud, treeLines }
938
+ },
939
+ })
940
+