dsh-better-display 0.3.7 → 0.3.9

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 (208) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/DESIGN.md +43 -3
  3. package/README.en.md +9 -1
  4. package/README.md +9 -1
  5. package/docs/dependency-update-policy.md +9 -0
  6. package/docs/extension-points.md +172 -0
  7. package/docs/official-rendering-bridge.md +59 -18
  8. package/docs/openapi.yaml +147 -0
  9. package/docs/runbooks/blank-reader.md +39 -0
  10. package/lib/client.js +1629 -586
  11. package/lib/client.js.map +1 -1
  12. package/lib/dsh-better-display.js +535 -57
  13. package/lib/types/client/AssistantNode.d.ts +20 -0
  14. package/lib/types/client/AssistantNode.d.ts.map +1 -0
  15. package/lib/types/client/AssistantNode.js +46 -0
  16. package/lib/types/client/AssistantNode.js.map +1 -0
  17. package/lib/types/client/Blocks.d.ts.map +1 -1
  18. package/lib/types/client/Blocks.js +33 -10
  19. package/lib/types/client/Blocks.js.map +1 -1
  20. package/lib/types/client/ChoreographedFlow.d.ts.map +1 -1
  21. package/lib/types/client/ChoreographedFlow.js +2 -0
  22. package/lib/types/client/ChoreographedFlow.js.map +1 -1
  23. package/lib/types/client/ClosedProcessSummary.d.ts.map +1 -1
  24. package/lib/types/client/ClosedProcessSummary.js +3 -1
  25. package/lib/types/client/ClosedProcessSummary.js.map +1 -1
  26. package/lib/types/client/McpAppFrame.d.ts.map +1 -1
  27. package/lib/types/client/McpAppFrame.js +5 -11
  28. package/lib/types/client/McpAppFrame.js.map +1 -1
  29. package/lib/types/client/OfficialContent.d.ts +17 -3
  30. package/lib/types/client/OfficialContent.d.ts.map +1 -1
  31. package/lib/types/client/OfficialContent.js +33 -7
  32. package/lib/types/client/OfficialContent.js.map +1 -1
  33. package/lib/types/client/Reader.d.ts.map +1 -1
  34. package/lib/types/client/Reader.js +76 -73
  35. package/lib/types/client/Reader.js.map +1 -1
  36. package/lib/types/client/SettingsSection.d.ts.map +1 -1
  37. package/lib/types/client/SettingsSection.js +0 -5
  38. package/lib/types/client/SettingsSection.js.map +1 -1
  39. package/lib/types/client/StickyLane.d.ts +12 -0
  40. package/lib/types/client/StickyLane.d.ts.map +1 -1
  41. package/lib/types/client/StickyLane.js +78 -2
  42. package/lib/types/client/StickyLane.js.map +1 -1
  43. package/lib/types/client/ToolActivity.d.ts.map +1 -1
  44. package/lib/types/client/ToolActivity.js +10 -5
  45. package/lib/types/client/ToolActivity.js.map +1 -1
  46. package/lib/types/client/deliverables.d.ts.map +1 -1
  47. package/lib/types/client/deliverables.js +2 -0
  48. package/lib/types/client/deliverables.js.map +1 -1
  49. package/lib/types/client/index.d.ts +3 -1
  50. package/lib/types/client/index.d.ts.map +1 -1
  51. package/lib/types/client/index.js +15 -1
  52. package/lib/types/client/index.js.map +1 -1
  53. package/lib/types/client/live-turn.d.ts +17 -5
  54. package/lib/types/client/live-turn.d.ts.map +1 -1
  55. package/lib/types/client/live-turn.js +106 -76
  56. package/lib/types/client/live-turn.js.map +1 -1
  57. package/lib/types/client/motion.d.ts +26 -2
  58. package/lib/types/client/motion.d.ts.map +1 -1
  59. package/lib/types/client/motion.js +144 -10
  60. package/lib/types/client/motion.js.map +1 -1
  61. package/lib/types/client/official-slots.d.ts +9 -0
  62. package/lib/types/client/official-slots.d.ts.map +1 -1
  63. package/lib/types/client/official-slots.js +22 -4
  64. package/lib/types/client/official-slots.js.map +1 -1
  65. package/lib/types/client/open-file.d.ts.map +1 -1
  66. package/lib/types/client/open-file.js +1 -6
  67. package/lib/types/client/open-file.js.map +1 -1
  68. package/lib/types/client/projection.d.ts +15 -2
  69. package/lib/types/client/projection.d.ts.map +1 -1
  70. package/lib/types/client/projection.js +16 -4
  71. package/lib/types/client/projection.js.map +1 -1
  72. package/lib/types/client/rewind-cut.d.ts +131 -0
  73. package/lib/types/client/rewind-cut.d.ts.map +1 -0
  74. package/lib/types/client/rewind-cut.js +321 -0
  75. package/lib/types/client/rewind-cut.js.map +1 -0
  76. package/lib/types/client/styles.d.ts +3 -0
  77. package/lib/types/client/styles.d.ts.map +1 -0
  78. package/lib/types/client/styles.js +25 -0
  79. package/lib/types/client/styles.js.map +1 -0
  80. package/lib/types/client/text-transform.d.ts +93 -0
  81. package/lib/types/client/text-transform.d.ts.map +1 -0
  82. package/lib/types/client/text-transform.js +183 -0
  83. package/lib/types/client/text-transform.js.map +1 -0
  84. package/lib/types/client/timeline.d.ts.map +1 -1
  85. package/lib/types/client/timeline.js.map +1 -1
  86. package/lib/types/client/tool-activity.d.ts +11 -4
  87. package/lib/types/client/tool-activity.d.ts.map +1 -1
  88. package/lib/types/client/tool-activity.js +54 -9
  89. package/lib/types/client/tool-activity.js.map +1 -1
  90. package/lib/types/client/turn-slots.d.ts +29 -0
  91. package/lib/types/client/turn-slots.d.ts.map +1 -0
  92. package/lib/types/client/turn-slots.js +62 -0
  93. package/lib/types/client/turn-slots.js.map +1 -0
  94. package/lib/types/client/types.d.ts +18 -0
  95. package/lib/types/client/types.d.ts.map +1 -1
  96. package/lib/types/dsh-better-display.d.ts +4 -1
  97. package/lib/types/dsh-better-display.d.ts.map +1 -1
  98. package/lib/types/dsh-better-display.js +55 -43
  99. package/lib/types/dsh-better-display.js.map +1 -1
  100. package/lib/types/flags.d.ts +7 -0
  101. package/lib/types/flags.d.ts.map +1 -0
  102. package/lib/types/flags.js +37 -0
  103. package/lib/types/flags.js.map +1 -0
  104. package/lib/types/log.d.ts +17 -0
  105. package/lib/types/log.d.ts.map +1 -0
  106. package/lib/types/log.js +122 -0
  107. package/lib/types/log.js.map +1 -0
  108. package/lib/types/metrics.d.ts +18 -0
  109. package/lib/types/metrics.d.ts.map +1 -0
  110. package/lib/types/metrics.js +35 -0
  111. package/lib/types/metrics.js.map +1 -0
  112. package/lib/types/reveal.d.ts +12 -0
  113. package/lib/types/reveal.d.ts.map +1 -0
  114. package/lib/types/reveal.js +147 -0
  115. package/lib/types/reveal.js.map +1 -0
  116. package/lib/types/workspace-path.d.ts +3 -0
  117. package/lib/types/workspace-path.d.ts.map +1 -0
  118. package/lib/types/workspace-path.js +5 -0
  119. package/lib/types/workspace-path.js.map +1 -0
  120. package/package.json +36 -5
  121. package/scripts/changelog.mjs +20 -0
  122. package/scripts/check-agents-md.mjs +67 -0
  123. package/scripts/check-bundle-size.mjs +38 -0
  124. package/scripts/check-dead-flags.mjs +55 -0
  125. package/scripts/check-todo-debt.mjs +69 -0
  126. package/scripts/security-audit-report.mjs +92 -0
  127. package/scripts/verify-commentary-visible.mjs +627 -0
  128. package/src/client/AssistantNode.tsx +72 -0
  129. package/src/client/Blocks.tsx +49 -10
  130. package/src/client/ChoreographedFlow.tsx +3 -1
  131. package/src/client/ClosedProcessSummary.tsx +3 -1
  132. package/src/client/McpAppFrame.tsx +5 -13
  133. package/src/client/OfficialContent.tsx +47 -9
  134. package/src/client/Reader.module.css +103 -21
  135. package/src/client/Reader.tsx +83 -88
  136. package/src/client/SettingsSection.tsx +1 -7
  137. package/src/client/StickyLane.tsx +81 -2
  138. package/src/client/ToolActivity.tsx +10 -6
  139. package/src/client/deliverables.ts +1 -0
  140. package/src/client/index.tsx +18 -2
  141. package/src/client/live-turn.ts +100 -69
  142. package/src/client/motion.tsx +142 -7
  143. package/src/client/official-slots.tsx +23 -4
  144. package/src/client/open-file.ts +2 -8
  145. package/src/client/projection.ts +16 -4
  146. package/src/client/rewind-cut.ts +340 -0
  147. package/src/client/styles.ts +22 -0
  148. package/src/client/text-transform.ts +265 -0
  149. package/src/client/timeline.ts +0 -2
  150. package/src/client/tool-activity.ts +67 -9
  151. package/src/client/turn-slots.ts +80 -0
  152. package/src/client/types.ts +19 -0
  153. package/src/dsh-better-display.ts +57 -42
  154. package/src/flags.ts +40 -0
  155. package/src/log.ts +137 -0
  156. package/src/metrics.ts +50 -0
  157. package/src/reveal.ts +90 -0
  158. package/src/workspace-path.ts +4 -0
  159. package/tests/browser-commentary.tsx +191 -0
  160. package/tests/chat-flow-hook.test.ts +1 -1
  161. package/tests/cloud-gate.test.ts +1 -1
  162. package/tests/context-tool-update.test.ts +1 -1
  163. package/tests/conversation-scroll.test.ts +1 -1
  164. package/tests/deliverables.test.ts +1 -1
  165. package/tests/entry.test.ts +1 -1
  166. package/tests/fixtures/reader-lane-owners.tsx +46 -0
  167. package/tests/fixtures/reader-official-users.tsx +234 -0
  168. package/tests/fixtures/reader-theme-overlap.html +80 -0
  169. package/tests/fixtures/reader-user-bubble.tsx +222 -0
  170. package/tests/flags.test.ts +66 -0
  171. package/tests/fold-choreography.test.ts +32 -8
  172. package/tests/fold-intensity.test.ts +11 -6
  173. package/tests/footer-precedence.test.ts +9 -1
  174. package/tests/history-word-regression.test.ts +1 -1
  175. package/tests/live-turn.test.ts +125 -54
  176. package/tests/log.test.ts +99 -0
  177. package/tests/mcp-apps.test.ts +1 -1
  178. package/tests/message-chrome.test.ts +1 -1
  179. package/tests/metrics.test.ts +52 -0
  180. package/tests/official-slots.test.ts +41 -2
  181. package/tests/open-file.test.ts +1 -1
  182. package/tests/pending-submission.test.ts +12 -1
  183. package/tests/pinned-selection.test.ts +16 -0
  184. package/tests/platform-media.test.ts +1 -1
  185. package/tests/projection.test.ts +66 -3
  186. package/tests/reader-glass-css.test.ts +28 -0
  187. package/tests/reader-official-users.test.ts +91 -0
  188. package/tests/reader-sticky-surface.test.ts +377 -0
  189. package/tests/reader-theme-lanes.test.ts +54 -0
  190. package/tests/reader-theme-overlap.test.ts +151 -0
  191. package/tests/reader-user-bubble.test.ts +137 -0
  192. package/tests/reasoning-follow.test.ts +1 -1
  193. package/tests/retiring-content.test.ts +229 -0
  194. package/tests/reveal.test.ts +128 -0
  195. package/tests/rewind-cut.test.ts +1090 -0
  196. package/tests/settings-copy.test.ts +1 -1
  197. package/tests/skill-status.test.ts +1 -1
  198. package/tests/stock-install.test.ts +9 -1
  199. package/tests/stream-buffer.test.ts +1 -1
  200. package/tests/styles.test.ts +75 -0
  201. package/tests/terminal-input-preview.test.ts +113 -0
  202. package/tests/text-transform.test.ts +272 -0
  203. package/tests/timeline.test.ts +1 -1
  204. package/tests/tool-clock.test.ts +1 -1
  205. package/tests/tool-diff.test.ts +1 -1
  206. package/tests/waiting-clock.test.ts +1 -1
  207. package/tests/word-timeline.test.ts +1 -1
  208. package/tsdown.config.ts +49 -1
@@ -0,0 +1,340 @@
1
+ /**
2
+ * Which chat rows a `/rewind` withdrew, expressed as a pure function of the
3
+ * chat snapshot.
4
+ *
5
+ * WHY THIS EXISTS. A rewind never deletes history: the host appends one
6
+ * replacement `user/message` marker whose `surfaceOp` shadows everything after
7
+ * the target, and the transcript must then read as it did *before* the target
8
+ * was sent. The official ChatView is a per-node renderer, so the rewind plugin
9
+ * (`dsh-rewind-plugin`) hides withdrawn rows by DOM: it computes the shadowed
10
+ * anchor seqs from the command node and sets `display:none` on every element
11
+ * carrying the official `data-chat-anchor-key` seat attribute.
12
+ *
13
+ * The Reader replaces ChatView's message list and renders its own row shapes
14
+ * (turn sections, answer articles, tool rows), so it does not republish that
15
+ * seat attribute on every row. DOM hiding therefore reaches only the user and
16
+ * steering bubbles, and every other withdrawn row — the answer, the tool rows,
17
+ * and the `/rewind` command row itself — stayed on screen. That is the reported
18
+ * defect: the command is recorded as a rewind row instead of the Reader rolling
19
+ * back to the state before the message was sent.
20
+ *
21
+ * The Reader decides visibility from React state, so it must apply the same
22
+ * contract itself instead of waiting for a third-party MutationObserver. The
23
+ * marker node is not admitted as a chat node (only append-origin surface events
24
+ * become nodes), so the command node's `outcome.sourceEventSeq` — the marker's
25
+ * log seq — plus the `@<seq>` target in its `args` are the only client-side
26
+ * signal for the shadowed range. This mirrors the plugin's own reader of that
27
+ * contract, and is pinned by `tests/rewind-cut.test.ts` so a plugin or host
28
+ * change cannot silently regress it.
29
+ *
30
+ * @module dsh-better-display/rewind-cut
31
+ */
32
+
33
+ /** A chat-snapshot view node, read structurally (only the fields this module needs). */
34
+ export interface CutChatNode {
35
+ readonly key: string;
36
+ readonly kind?: string;
37
+ readonly anchorSeq?: number;
38
+ readonly visibility?: string;
39
+ readonly data?: unknown;
40
+ /**
41
+ * Where the host placed the node in the session's location index. Only the
42
+ * owning turn is read from it, and an absent or foreign location is fine.
43
+ */
44
+ readonly location?: unknown;
45
+ }
46
+
47
+ /** The minimal chat-snapshot reader the cut logic needs. */
48
+ export interface CutChat {
49
+ readonly order: readonly string[];
50
+ readonly nodes: {
51
+ get(key: string): CutChatNode | undefined;
52
+ };
53
+ }
54
+
55
+ /** One closed shadow range `[start, end]` in surface/anchor seq space. */
56
+ export interface CutSpan {
57
+ readonly start: number;
58
+ readonly end: number;
59
+ }
60
+
61
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
62
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
63
+ ? (value as Record<string, unknown>)
64
+ : undefined;
65
+ }
66
+
67
+ function safeSeq(value: unknown): number | undefined {
68
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
69
+ }
70
+
71
+ /** The command payload of a `command` chat node, when it is structurally readable. */
72
+ function commandOf(node: CutChatNode): Record<string, unknown> | undefined {
73
+ if (node.kind !== 'command') return undefined;
74
+ return asRecord(node.data);
75
+ }
76
+
77
+ /**
78
+ * The engine names an executed rewind command node can carry. The plugin
79
+ * registers its command as `rewind-plugin` (`ENGINE_COMMANDS = new
80
+ * Set(['rewind-plugin', 'rewind'])` in dsh-rewind-plugin's
81
+ * `src/client/hidden.ts`), and that is the name the client projection actually
82
+ * publishes — the session log's `command/run.name` is not what the Reader sees.
83
+ * `rewind` stays accepted because older logs and the bili-side proxy record the
84
+ * shorter spelling.
85
+ */
86
+ const REWIND_COMMANDS: ReadonlySet<string> = new Set(['rewind-plugin', 'rewind']);
87
+
88
+ /** True when a command payload is the rewind engine command, in either spelling. */
89
+ function isRewindCommand(command: Record<string, unknown>): boolean {
90
+ return typeof command.name === 'string' && REWIND_COMMANDS.has(command.name);
91
+ }
92
+
93
+ /**
94
+ * The render POSITION a row is anchored at: the view node's `anchorSeq`, else
95
+ * its payload seq.
96
+ *
97
+ * This is deliberately NOT integer-only. The host anchors synthetic rows at
98
+ * fractional offsets off a real seq (`CHAT_SYNTHETIC_SEQ_OFFSETS` in the
99
+ * official ChatView: `turn-process` at `controlAnchorSeq - 0.1`, `turn-tail` at
100
+ * `seq + 0.1`, an interrupted assistant step at `seq - 0.9`). An integer-only
101
+ * read made those rows invisible to the cut, so the last `turn-process` of a
102
+ * withdrawn turn survived on its own. Log seqs (marker, target) stay integer:
103
+ * see `safeSeq`.
104
+ */
105
+ export function anchorSeqOf(node: CutChatNode): number | undefined {
106
+ const raw = node.anchorSeq ?? asRecord(node.data)?.seq;
107
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 ? raw : undefined;
108
+ }
109
+
110
+ /**
111
+ * Extract the rewind target seq from a `/rewind` command's structured `args`
112
+ * (e.g. `@5 chat`, `preview @5 both`). Locale-independent: it never parses the
113
+ * host's human outcome copy.
114
+ */
115
+ export function rewindTargetOfArgs(args: unknown): number | undefined {
116
+ if (typeof args !== 'string') return undefined;
117
+ const match = args.match(/@(\d+)/);
118
+ return match === null ? undefined : Number(match[1]);
119
+ }
120
+
121
+ /** True for the internal candidate-list probe (`/rewind __candidates`). */
122
+ function isCandidateCommand(command: Record<string, unknown>): boolean {
123
+ return typeof command.args === 'string' && command.args.includes('__candidates');
124
+ }
125
+
126
+ /** True for an impact preview (`/rewind preview @5 both`). */
127
+ function isPreviewCommand(command: Record<string, unknown>): boolean {
128
+ return typeof command.args === 'string' && command.args.includes('preview');
129
+ }
130
+
131
+ /**
132
+ * Merge overlapping or touching shadow ranges.
133
+ *
134
+ * Spans are kept SEPARATE unless they genuinely overlap: collapsing every cut
135
+ * to `[min target, max marker]` would hide a still-on-surface gap of new traffic
136
+ * between an earlier marker and a later target.
137
+ */
138
+ export function coalesceCutSpans(spans: readonly CutSpan[]): CutSpan[] {
139
+ if (spans.length < 2) return [...spans];
140
+ const sorted = [...spans].sort((left, right) => left.start - right.start || left.end - right.end);
141
+ const merged: { start: number; end: number }[] = [];
142
+ for (const span of sorted) {
143
+ const last = merged.at(-1);
144
+ if (last !== undefined && span.start <= last.end) {
145
+ if (span.end > last.end) last.end = span.end;
146
+ continue;
147
+ }
148
+ merged.push({ start: span.start, end: span.end });
149
+ }
150
+ return merged;
151
+ }
152
+
153
+ /**
154
+ * True when a row anchored at `seq` falls inside one of the cut spans.
155
+ *
156
+ * A cut runs from the target seq through the marker's own log seq, inclusive
157
+ * (`target <= anchorSeq && anchorSeq <= marker`), the same comparison
158
+ * `dsh-rewind-plugin`'s `RewindVisibilityBuilder` uses. The upper bound stops
159
+ * at the marker. Extending it to the next integer hides the following turn's
160
+ * process row, which the host anchors at `startSeq - 0.1` and therefore in
161
+ * `[marker, marker + 1)`. Fractional anchors inside the closed range still
162
+ * match: `anchorSeqOf` keeps them. A process or tail row parked outside the
163
+ * range is handled by `summaryTurns`, not by widening the cut. Spans stay
164
+ * disjoint, so new traffic between two rewinds survives.
165
+ */
166
+ export function cutContains(cuts: readonly CutSpan[], seq: number): boolean {
167
+ let low = 0;
168
+ let high = cuts.length - 1;
169
+ let found = -1;
170
+ while (low <= high) {
171
+ const middle = (low + high) >> 1;
172
+ const cut = cuts[middle];
173
+ if (cut === undefined) return false;
174
+ if (seq < cut.start) high = middle - 1;
175
+ else {
176
+ found = middle;
177
+ low = middle + 1;
178
+ }
179
+ }
180
+ const span = found < 0 ? undefined : cuts[found];
181
+ return span !== undefined && seq <= span.end;
182
+ }
183
+
184
+ /** The turn id a node belongs to (absent outside a turn). */
185
+ function turnIdOf(node: CutChatNode): unknown | undefined {
186
+ // The location's own `kind` varies (`turn` for a turn's synthetic rows,
187
+ // `step` for one of its messages); only the turn it carries matters here.
188
+ const turn = asRecord(asRecord(node.location)?.turn);
189
+ if (turn === undefined || !Object.hasOwn(turn, 'turn')) return undefined;
190
+ return turn.turn;
191
+ }
192
+
193
+ /**
194
+ * Node kinds that SUMMARIZE a turn instead of carrying its content, so the host
195
+ * anchors them at the turn's edges rather than at an event inside it.
196
+ */
197
+ const TURN_SUMMARY_KINDS: ReadonlySet<string> = new Set(['turn-process', 'turn-tail']);
198
+
199
+ /**
200
+ * True for a rewind command row the transcript should not keep.
201
+ *
202
+ * Probes (`preview`, `__candidates`) exist only to feed the popover. An
203
+ * executed rewind — success plus a marker seq — is the command that performed
204
+ * the cut, and the plugin hides that row even when its anchor sits outside
205
+ * the numeric range. A failed or still-running command stays visible.
206
+ */
207
+ function commandHidden(node: CutChatNode): boolean {
208
+ const command = commandOf(node);
209
+ if (command === undefined || !isRewindCommand(command)) return false;
210
+ if (isPreviewCommand(command) || isCandidateCommand(command)) return true;
211
+ const outcome = asRecord(command.outcome);
212
+ return outcome?.kind === 'success' && safeSeq(outcome.sourceEventSeq) !== undefined;
213
+ }
214
+
215
+ /** True when the row's own anchor falls in a cut, or the row is a rewind command to hide. */
216
+ function anchorWithdrawn(node: CutChatNode, cuts: readonly CutSpan[]): boolean {
217
+ if (commandHidden(node)) return true;
218
+ const seq = anchorSeqOf(node);
219
+ return seq !== undefined && cutContains(cuts, seq);
220
+ }
221
+
222
+ /**
223
+ * Turns whose process and tail rows must leave.
224
+ *
225
+ * The host opens a turn before its user message is logged and anchors
226
+ * `turn-process` at `controlAnchorSeq - 0.1`, below the first withdrawn
227
+ * event, and `turn-tail` at `turn.end.seq + 0.1`, which can sit past the
228
+ * marker. Containment therefore misses those two rows, and the transcript
229
+ * kept announcing `执行过程 / 本轮已停止,已生成的内容仍保留。`
230
+ *
231
+ * A summary leaves only when every content row of its turn is already
232
+ * withdrawn — the same rule as the plugin's `deriveTurnProcess`. One content
233
+ * row before the target (a mid-turn steering rewind) keeps the summary and
234
+ * that earlier message. A turn with no content rows is left alone.
235
+ */
236
+ function summaryTurns(chat: CutChat, cuts: readonly CutSpan[]): Set<unknown> {
237
+ const stays = new Map<unknown, boolean>();
238
+ for (const key of chat.order) {
239
+ const node = chat.nodes.get(key);
240
+ if (node === undefined || TURN_SUMMARY_KINDS.has(node.kind ?? '')) continue;
241
+ const id = turnIdOf(node);
242
+ if (id === undefined) continue;
243
+ const visible = node.visibility !== 'hidden' && !anchorWithdrawn(node, cuts);
244
+ stays.set(id, (stays.get(id) ?? false) || visible);
245
+ }
246
+ const withdrawn = new Set<unknown>();
247
+ for (const [id, visible] of stays) if (!visible) withdrawn.add(id);
248
+ return withdrawn;
249
+ }
250
+
251
+ /** True when this row is a summary of a turn whose content is fully withdrawn. */
252
+ function summaryWithdrawn(node: CutChatNode, summaries: ReadonlySet<unknown>): boolean {
253
+ if (!TURN_SUMMARY_KINDS.has(node.kind ?? '')) return false;
254
+ const id = turnIdOf(node);
255
+ return id !== undefined && summaries.has(id);
256
+ }
257
+
258
+ /**
259
+ * The shadow ranges a session's executed rewinds produced, newest state last.
260
+ * An executed rewind cuts `[target, marker]` — the target itself is included,
261
+ * because a rewind restores the state *before* that message was sent (its text
262
+ * goes back to the composer).
263
+ */
264
+ export function rewindCutSpans(chat: CutChat | undefined): CutSpan[] {
265
+ if (chat === undefined) return [];
266
+ const spans: CutSpan[] = [];
267
+ for (const key of chat.order) {
268
+ const node = chat.nodes.get(key);
269
+ if (node === undefined) continue;
270
+ const command = commandOf(node);
271
+ if (command === undefined || !isRewindCommand(command)) continue;
272
+ // Probes never open a span, even when a later host stamps them with a
273
+ // success marker. Matching them would roll the transcript back on preview.
274
+ if (isPreviewCommand(command) || isCandidateCommand(command)) continue;
275
+ const outcome = asRecord(command.outcome);
276
+ if (outcome?.kind !== 'success') continue;
277
+ const marker = safeSeq(outcome.sourceEventSeq);
278
+ if (marker === undefined) continue;
279
+ const target = rewindTargetOfArgs(command.args);
280
+ if (target === undefined || target > marker) continue;
281
+ spans.push({ start: target, end: marker });
282
+ }
283
+ return coalesceCutSpans(spans);
284
+ }
285
+
286
+ /**
287
+ * The anchor seqs the Reader must not render: every withdrawn message (the
288
+ * target, everything after it, and the unrendered marker), plus every `/rewind`
289
+ * row that exists only to feed the popover — the candidate-list probe and each
290
+ * impact preview. A SUCCESSFUL executed command row is covered by its own cut;
291
+ * a failed or unsettled one stays visible as an ordinary command record.
292
+ */
293
+ export function hiddenRewindSeqs(chat: CutChat | undefined): Set<number> {
294
+ const hidden = new Set<number>();
295
+ if (chat === undefined) return hidden;
296
+ const cuts = rewindCutSpans(chat);
297
+ const summaries = summaryTurns(chat, cuts);
298
+ for (const key of chat.order) {
299
+ const node = chat.nodes.get(key);
300
+ if (node === undefined) continue;
301
+ if (!anchorWithdrawn(node, cuts) && !summaryWithdrawn(node, summaries)) continue;
302
+ const seq = anchorSeqOf(node);
303
+ if (seq !== undefined) hidden.add(seq);
304
+ }
305
+ return hidden;
306
+ }
307
+
308
+ /**
309
+ * The chat keys the Reader should render, in snapshot order: withdrawn rows and
310
+ * rows the host itself marked hidden are dropped, everything else keeps its
311
+ * position. Returns the snapshot's own `order` array when nothing is filtered,
312
+ * so React selectors see a stable reference.
313
+ */
314
+ export function visibleChatKeys(chat: CutChat): readonly string[] {
315
+ const cuts = rewindCutSpans(chat);
316
+ const summaries = summaryTurns(chat, cuts);
317
+ const visible: string[] = [];
318
+ for (const key of chat.order) {
319
+ const node = chat.nodes.get(key);
320
+ if (node === undefined) continue;
321
+ if (node.visibility === 'hidden') continue;
322
+ if (anchorWithdrawn(node, cuts) || summaryWithdrawn(node, summaries)) continue;
323
+ visible.push(key);
324
+ }
325
+ return visible.length === chat.order.length ? chat.order : visible;
326
+ }
327
+
328
+ /**
329
+ * A comparable signal for the visible row set, built for
330
+ * `useSyncExternalStore`-style subscription: the host re-runs a chat selector
331
+ * on every publish and compares the RESULT by `Object.is`, and a rewind
332
+ * publishes an in-place upsert of an existing command row. The snapshot's
333
+ * `order` array and node store are therefore both reference-stable across a
334
+ * rewind, so a selector on them never re-renders; a string does change exactly
335
+ * when the visible set does. Never return the array itself from a selector —
336
+ * a fresh array fails the `Object.is` check on every publish.
337
+ */
338
+ export function visibleChatSignature(chat: CutChat): string {
339
+ return visibleChatKeys(chat).join('\u0000');
340
+ }
@@ -0,0 +1,22 @@
1
+ const plugin = 'dsh-better-display';
2
+ const styles = new Map<string, string>();
3
+
4
+ /** Retain injected CSS across host cleanup and restore it before Reader paints. */
5
+ export function ensureStyles(): void {
6
+ if (typeof document === 'undefined') return;
7
+ const live = new Set<string>();
8
+ for (const tag of document.querySelectorAll<HTMLStyleElement>(`style[data-plugin="${plugin}"][data-plugin-css]`)) {
9
+ const id = tag.dataset.pluginCss;
10
+ if (id === undefined) continue;
11
+ styles.set(id, tag.textContent ?? '');
12
+ live.add(id);
13
+ }
14
+ for (const [id, text] of styles) {
15
+ if (live.has(id)) continue;
16
+ const tag = document.createElement('style');
17
+ tag.dataset.plugin = plugin;
18
+ tag.dataset.pluginCss = id;
19
+ tag.textContent = text;
20
+ document.head.appendChild(tag);
21
+ }
22
+ }
@@ -0,0 +1,265 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import type { ReaderBlockOwner, ReaderBlockPresentation } from './types.js';
3
+
4
+ /**
5
+ * Cordis service name. Another client plugin lists this in `inject` and
6
+ * registers a transformer. The reading view paints the result. The session
7
+ * block, transcript, and fold inputs stay on the original text.
8
+ */
9
+ export const TEXT_TRANSFORM_SERVICE = 'dsh-better-display.text-transform';
10
+
11
+ export type DisplayTextKind = 'reasoning' | 'body';
12
+
13
+ export interface DisplayTextRequest {
14
+ /** Original block text. Registrants must not write it back onto the block. */
15
+ text: string;
16
+ streaming: boolean;
17
+ /** Opaque id of this mounted block. Stable until the block unmounts. */
18
+ blockKey: string;
19
+ kind: DisplayTextKind;
20
+ /** Assistant body and reasoning are the usual targets. Tool prose uses `tool`. */
21
+ source?: ReaderBlockOwner['source'];
22
+ }
23
+
24
+ export interface DisplayText {
25
+ text: string;
26
+ /**
27
+ * True when this string is the settled display for the current source.
28
+ * False keeps the live reveal open, including after the model has stopped
29
+ * but a translation batch is still outstanding.
30
+ */
31
+ final: boolean;
32
+ }
33
+
34
+ /**
35
+ * Sync `read` on every paint, plus `subscribe` when a later batch changes
36
+ * what `read` returns. `subscribe` may be called once per kind and must
37
+ * accept more than one listener.
38
+ */
39
+ export interface DisplayTextTransformer {
40
+ read(request: DisplayTextRequest): DisplayText | string | undefined;
41
+ subscribe?(listener: () => void): () => void;
42
+ }
43
+
44
+ export interface DisplayCursor extends DisplayText {
45
+ /**
46
+ * Increments when the displayed string or its `final` bit changes.
47
+ * This is not the reveal clock. Passing it to the word timeline as the
48
+ * motion revision replays or snaps the paragraph.
49
+ */
50
+ transformRevision: number;
51
+ /**
52
+ * Reveal identity. Stays put when the new string extends the previous
53
+ * display string, so an appended translation batch continues the fade.
54
+ * Increments only when the string is replaced, which settles the new
55
+ * text instead of typing it again from the first grapheme.
56
+ */
57
+ motionRevision: number;
58
+ }
59
+
60
+ export interface TextTransformRegistry {
61
+ register(kind: DisplayTextKind | readonly DisplayTextKind[], transformer: DisplayTextTransformer): () => void;
62
+ has(kind: DisplayTextKind): boolean;
63
+ read(request: DisplayTextRequest): DisplayCursor;
64
+ subscribe(kind: DisplayTextKind, listener: () => void): () => void;
65
+ release(kind: DisplayTextKind, blockKey: string): void;
66
+ }
67
+
68
+ const KINDS = new Set<DisplayTextKind>(['reasoning', 'body']);
69
+
70
+ function isKind(value: string): value is DisplayTextKind {
71
+ return KINDS.has(value as DisplayTextKind);
72
+ }
73
+
74
+ function reportTransformError(error: unknown): void {
75
+ console.warn('[dsh-better-display] text transform failed; showing original text', error);
76
+ }
77
+
78
+ function passthrough(request: DisplayTextRequest): DisplayCursor {
79
+ return { text: request.text, final: !request.streaming, transformRevision: 0, motionRevision: 0 };
80
+ }
81
+
82
+ function normalize(value: DisplayText | string | undefined, request: DisplayTextRequest): DisplayText {
83
+ if (typeof value === 'string') return { text: value, final: !request.streaming };
84
+ if (!value || typeof value.text !== 'string') return { text: request.text, final: !request.streaming };
85
+ return { text: value.text, final: typeof value.final === 'boolean' ? value.final : !request.streaming };
86
+ }
87
+
88
+ /**
89
+ * Appends keep the motion revision. A replacement gets a new one so the
90
+ * timeline treats the swapped string as already settled.
91
+ */
92
+ export function nextDisplayCursor(previous: DisplayCursor | undefined, display: DisplayText): DisplayCursor {
93
+ if (!previous) return { ...display, transformRevision: 0, motionRevision: 0 };
94
+ if (previous.text === display.text && previous.final === display.final) return previous;
95
+ const appended = display.text.startsWith(previous.text);
96
+ return {
97
+ text: display.text,
98
+ final: display.final,
99
+ transformRevision: previous.transformRevision + 1,
100
+ motionRevision: appended ? previous.motionRevision : previous.motionRevision + 1,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Streaming flag fed to the reveal. With no transformer this is the model's
106
+ * flag. A transformer that reports `final: !streaming` produces the same flag.
107
+ */
108
+ export function displayStreaming(sourceStreaming: boolean, shown: Pick<DisplayCursor, 'final'>, active: boolean): boolean {
109
+ return active ? !shown.final : sourceStreaming;
110
+ }
111
+
112
+ /** No registry, or none for this kind: the source string, and no cursor write. */
113
+ export function readDisplayText(registry: TextTransformRegistry | undefined, request: DisplayTextRequest): DisplayCursor {
114
+ if (!registry?.has(request.kind)) return passthrough(request);
115
+ return registry.read(request);
116
+ }
117
+
118
+ interface StackEntry {
119
+ transformer: DisplayTextTransformer;
120
+ unsubscribe?: () => void;
121
+ }
122
+
123
+ class TextTransformRegistryImpl implements TextTransformRegistry {
124
+ private readonly stacks = new Map<DisplayTextKind, StackEntry[]>();
125
+ private readonly listeners = new Map<DisplayTextKind, Set<() => void>>();
126
+ private readonly cursors = new Map<string, DisplayCursor>();
127
+
128
+ register(kind: DisplayTextKind | readonly DisplayTextKind[], transformer: DisplayTextTransformer): () => void {
129
+ const requested = [...new Set(Array.isArray(kind) ? kind : [kind])];
130
+ for (const item of requested) {
131
+ if (!isKind(item)) throw new Error(`Unknown display text kind: ${String(item)}`);
132
+ }
133
+ const bound: { kind: DisplayTextKind; entry: StackEntry }[] = [];
134
+ for (const item of requested) {
135
+ const entry: StackEntry = { transformer };
136
+ try {
137
+ entry.unsubscribe = transformer.subscribe?.(() => { this.emit(item); });
138
+ } catch (error) {
139
+ reportTransformError(error);
140
+ }
141
+ const stack = this.stacks.get(item) ?? [];
142
+ stack.push(entry);
143
+ this.stacks.set(item, stack);
144
+ bound.push({ kind: item, entry });
145
+ this.emit(item);
146
+ }
147
+ return () => {
148
+ for (const { kind: item, entry } of bound) {
149
+ try { entry.unsubscribe?.(); } catch (error) { reportTransformError(error); }
150
+ const stack = this.stacks.get(item);
151
+ if (!stack) continue;
152
+ const next = stack.filter(candidate => candidate !== entry);
153
+ if (next.length > 0) this.stacks.set(item, next);
154
+ else this.stacks.delete(item);
155
+ this.emit(item);
156
+ }
157
+ };
158
+ }
159
+
160
+ has(kind: DisplayTextKind): boolean {
161
+ return (this.stacks.get(kind)?.length ?? 0) > 0;
162
+ }
163
+
164
+ read(request: DisplayTextRequest): DisplayCursor {
165
+ const transformer = this.stacks.get(request.kind)?.at(-1)?.transformer;
166
+ if (!transformer) return passthrough(request);
167
+ let display: DisplayText;
168
+ try {
169
+ display = normalize(transformer.read(request), request);
170
+ } catch (error) {
171
+ // A broken transformer must never hide the original text. Show it and
172
+ // ask again on the next text change or notify, so a recovered
173
+ // transformer takes over without a remount.
174
+ reportTransformError(error);
175
+ display = { text: request.text, final: !request.streaming };
176
+ }
177
+ const key = `${request.kind}\u0000${request.blockKey}`;
178
+ const next = nextDisplayCursor(this.cursors.get(key), display);
179
+ this.cursors.set(key, next);
180
+ return next;
181
+ }
182
+
183
+ subscribe(kind: DisplayTextKind, listener: () => void): () => void {
184
+ const set = this.listeners.get(kind) ?? new Set();
185
+ set.add(listener);
186
+ this.listeners.set(kind, set);
187
+ return () => { set.delete(listener); };
188
+ }
189
+
190
+ release(kind: DisplayTextKind, blockKey: string): void {
191
+ this.cursors.delete(`${kind}\u0000${blockKey}`);
192
+ }
193
+
194
+ private emit(kind: DisplayTextKind): void {
195
+ const set = this.listeners.get(kind);
196
+ if (!set) return;
197
+ for (const listener of [...set]) listener();
198
+ }
199
+ }
200
+
201
+ export function createTextTransformRegistry(): TextTransformRegistry {
202
+ return new TextTransformRegistryImpl();
203
+ }
204
+
205
+ let active: TextTransformRegistry | undefined;
206
+
207
+ /** Points the reading view at the registry this client plugin provides. */
208
+ export function installTextTransformRegistry(registry: TextTransformRegistry | undefined): () => void {
209
+ const previous = active;
210
+ active = registry;
211
+ return () => { active = previous; };
212
+ }
213
+
214
+ export function activeTextTransform(): TextTransformRegistry | undefined {
215
+ return active;
216
+ }
217
+
218
+ /**
219
+ * Subscribe while mounted. The reveal components call this only after
220
+ * `has(kind)`, so an empty registry adds no hook and no listener.
221
+ */
222
+ export function useDisplayText(registry: TextTransformRegistry, request: DisplayTextRequest): DisplayCursor {
223
+ const [epoch, setEpoch] = useState(0);
224
+ const { text, streaming, blockKey, kind, source } = request;
225
+ useEffect(() => registry.subscribe(kind, () => { setEpoch(value => value + 1); }), [registry, kind]);
226
+ useEffect(() => () => { registry.release(kind, blockKey); }, [registry, kind, blockKey]);
227
+ return useMemo(
228
+ () => registry.read({ text, streaming, blockKey, kind, source }),
229
+ [registry, text, streaming, blockKey, kind, source, epoch],
230
+ );
231
+ }
232
+
233
+ /** Chain-slot owner. Extra fields are optional so older callers still type-check. */
234
+ export function readerBlockOwner(
235
+ block: ReaderBlockOwner['block'],
236
+ streaming: boolean,
237
+ source: ReaderBlockOwner['source'],
238
+ presentation: ReaderBlockPresentation,
239
+ holdFormatting: boolean,
240
+ ): ReaderBlockOwner {
241
+ return {
242
+ block,
243
+ streaming,
244
+ source,
245
+ presentation: {
246
+ startedAt: presentation.startedAt,
247
+ interrupted: presentation.interrupted,
248
+ liveText: presentation.liveText,
249
+ },
250
+ holdFormatting,
251
+ liveText: presentation.liveText,
252
+ };
253
+ }
254
+
255
+ /** Copy actions read this. Display text never replaces it. */
256
+ export function originalAnswerText(blocks: readonly { readonly kind: string; readonly text?: string }[]): string {
257
+ return blocks.flatMap(block => block.kind === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n\n');
258
+ }
259
+
260
+ declare module '@deepseek-ai/cordis' {
261
+ interface Context {
262
+ /** Display-only reader text transforms. Present after this client plugin applies. */
263
+ 'dsh-better-display.text-transform'?: TextTransformRegistry;
264
+ }
265
+ }
@@ -1,5 +1,3 @@
1
- import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
2
-
3
1
  export interface TimelineItem {
4
2
  readonly turn: number;
5
3
  readonly prompt: string;