@zyro-sec/session-ui 0.0.0-stage → 1.0.4

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 (261) hide show
  1. package/AGENTS.md +25 -0
  2. package/bunfig.toml +2 -0
  3. package/component-tests/basic-tool.fixture.tsx +46 -0
  4. package/component-tests/basic-tool.spec.ts +63 -0
  5. package/component-tests/file-media.fixture.tsx +39 -0
  6. package/component-tests/file-media.spec.ts +13 -0
  7. package/component-tests/file-tool.spec.ts +62 -0
  8. package/component-tests/file-viewer.fixture.tsx +109 -0
  9. package/component-tests/file-viewer.spec.ts +134 -0
  10. package/component-tests/file.spec.ts +33 -0
  11. package/component-tests/line-comment-v2.spec.ts +15 -0
  12. package/component-tests/markdown-code-wrap.spec.ts +94 -0
  13. package/component-tests/markdown-readiness.spec.ts +95 -0
  14. package/component-tests/markdown.fixture.tsx +104 -0
  15. package/component-tests/markdown.spec.ts +1564 -0
  16. package/component-tests/mermaid-preview.spec.ts +43 -0
  17. package/component-tests/patch-group.spec.ts +79 -0
  18. package/component-tests/read-group.spec.ts +72 -0
  19. package/component-tests/read-image.fixture.tsx +66 -0
  20. package/component-tests/read-image.spec.ts +154 -0
  21. package/component-tests/session-compaction.spec.ts +254 -0
  22. package/component-tests/session-lifecycle.spec.ts +190 -0
  23. package/component-tests/session-message-projection.spec.ts +639 -0
  24. package/component-tests/session-notice-projection.spec.ts +20 -0
  25. package/component-tests/session-review-comments.spec.ts +179 -0
  26. package/component-tests/session-shell.spec.ts +93 -0
  27. package/component-tests/session-timeline-mobile.spec.ts +201 -0
  28. package/component-tests/session-timeline-notices.spec.ts +38 -0
  29. package/component-tests/session-timeline-reasoning.spec.ts +107 -0
  30. package/component-tests/session-timeline.spec.ts +157 -0
  31. package/component-tests/session-tool-projection.spec.ts +323 -0
  32. package/component-tests/text-lifecycle.fixture.tsx +26 -0
  33. package/component-tests/text-lifecycle.spec.ts +42 -0
  34. package/component-tests/timeline-subagent-rows.spec.ts +33 -0
  35. package/component-tests/tool-disclosure.spec.ts +48 -0
  36. package/component-tests/tool-group-sticky.spec.ts +37 -0
  37. package/component-tests/tool-group.spec.ts +290 -0
  38. package/component-tests/tool-status-title.fixture.tsx +22 -0
  39. package/component-tests/tool-status-title.spec.ts +30 -0
  40. package/component-tests/user-message-quotes.spec.ts +111 -0
  41. package/package.json +91 -4
  42. package/playwright.components.config.ts +4 -0
  43. package/playwright.local.config.ts +2 -0
  44. package/src/actions.ts +54 -0
  45. package/src/components/apply-patch-file.ts +122 -0
  46. package/src/components/basic-tool.css +487 -0
  47. package/src/components/basic-tool.tsx +258 -0
  48. package/src/components/copy-machine.ts +78 -0
  49. package/src/components/copy.ts +85 -0
  50. package/src/components/diagram-preview.tsx +28 -0
  51. package/src/components/disclosure-machine.ts +188 -0
  52. package/src/components/disclosure.ts +129 -0
  53. package/src/components/dock-prompt.stories.tsx +73 -0
  54. package/src/components/dock-prompt.tsx +29 -0
  55. package/src/components/file-comment-selection.tsx +146 -0
  56. package/src/components/file-media-machine.ts +165 -0
  57. package/src/components/file-media.stories.tsx +112 -0
  58. package/src/components/file-media.tsx +323 -0
  59. package/src/components/file-search.tsx +73 -0
  60. package/src/components/file.css +59 -0
  61. package/src/components/file.tsx +1300 -0
  62. package/src/components/image-preview.tsx +35 -0
  63. package/src/components/line-comment-annotations.tsx +580 -0
  64. package/src/components/line-comment-machine.ts +262 -0
  65. package/src/components/line-comment-styles.ts +293 -0
  66. package/src/components/line-comment.stories.tsx +152 -0
  67. package/src/components/line-comment.tsx +448 -0
  68. package/src/components/link-segments.ts +20 -0
  69. package/src/components/linked-text.tsx +21 -0
  70. package/src/components/markdown-cache-machine.ts +257 -0
  71. package/src/components/markdown-cache.tsx +556 -0
  72. package/src/components/markdown-clipboard.ts +101 -0
  73. package/src/components/markdown-code-machine.ts +200 -0
  74. package/src/components/markdown-code-state.ts +22 -0
  75. package/src/components/markdown-fragment-links.ts +74 -0
  76. package/src/components/markdown-github.svg +3 -0
  77. package/src/components/markdown-globe.svg +5 -0
  78. package/src/components/markdown-image-machine.ts +170 -0
  79. package/src/components/markdown-image.ts +156 -0
  80. package/src/components/markdown-inline-code-kind.ts +39 -0
  81. package/src/components/markdown-mermaid.ts +18 -0
  82. package/src/components/markdown-phase-machine.ts +102 -0
  83. package/src/components/markdown-projection.ts +13 -0
  84. package/src/components/markdown-session-links.ts +183 -0
  85. package/src/components/markdown-solid.test.tsx +92 -0
  86. package/src/components/markdown-solid.tsx +113 -0
  87. package/src/components/markdown-stream.ts +95 -0
  88. package/src/components/markdown-worker-machine.ts +516 -0
  89. package/src/components/markdown-worker-protocol.ts +73 -0
  90. package/src/components/markdown-worker.ts +250 -0
  91. package/src/components/markdown.css +672 -0
  92. package/src/components/markdown.stories.tsx +199 -0
  93. package/src/components/markdown.tsx +1612 -0
  94. package/src/components/markdown.worker.ts +188 -0
  95. package/src/components/message-file.ts +102 -0
  96. package/src/components/message-nav.css +134 -0
  97. package/src/components/message-nav.tsx +159 -0
  98. package/src/components/message-part.css +2109 -0
  99. package/src/components/message-part.tsx +3 -0
  100. package/src/components/question-prompt-experimental.css +576 -0
  101. package/src/components/question-prompt.css +527 -0
  102. package/src/components/quote-highlight.css +59 -0
  103. package/src/components/review-focus-driver.ts +142 -0
  104. package/src/components/review-focus-machine.ts +95 -0
  105. package/src/components/session-compaction.css +270 -0
  106. package/src/components/session-diff.ts +358 -0
  107. package/src/components/session-error.tsx +41 -0
  108. package/src/components/session-retry.tsx +92 -0
  109. package/src/components/session-review-machine.ts +241 -0
  110. package/src/components/session-review.css +264 -0
  111. package/src/components/session-review.stories.tsx +232 -0
  112. package/src/components/session-review.tsx +733 -0
  113. package/src/components/session-turn.css +282 -0
  114. package/src/components/shell-submessage.css +24 -0
  115. package/src/components/timeline-separator.tsx +69 -0
  116. package/src/components/tool-count-label.css +57 -0
  117. package/src/components/tool-count-label.tsx +76 -0
  118. package/src/components/tool-count-summary.css +102 -0
  119. package/src/components/tool-count-summary.stories.tsx +99 -0
  120. package/src/components/tool-count-summary.tsx +44 -0
  121. package/src/components/tool-error-card.css +178 -0
  122. package/src/components/tool-error-card.stories.tsx +113 -0
  123. package/src/components/tool-error-card.tsx +202 -0
  124. package/src/components/tool-status-title-machine.ts +128 -0
  125. package/src/components/tool-status-title.css +89 -0
  126. package/src/components/tool-status-title.tsx +163 -0
  127. package/src/context/data.tsx +107 -0
  128. package/src/context/index.ts +1 -0
  129. package/src/context/markdown.tsx +129 -0
  130. package/src/context/sources.tsx +34 -0
  131. package/src/document.ts +8 -0
  132. package/src/file-presentation.ts +34 -0
  133. package/src/message/action-machine.ts +72 -0
  134. package/src/message/agent-label.ts +3 -0
  135. package/src/message/attachment-card.css +119 -0
  136. package/src/message/attachment-card.tsx +40 -0
  137. package/src/message/attachment-media-machine.ts +213 -0
  138. package/src/message/comment-card.tsx +155 -0
  139. package/src/message/compaction-entrance-machine.ts +93 -0
  140. package/src/message/current-message.tsx +157 -0
  141. package/src/message/current-tool-state.ts +161 -0
  142. package/src/message/message-content.tsx +1391 -0
  143. package/src/message/paced-text-machine.ts +73 -0
  144. package/src/message/prompt-message.stories.tsx +149 -0
  145. package/src/message/relative-time.ts +45 -0
  146. package/src/message/user-message-quote-parts.ts +16 -0
  147. package/src/message/user-message-quotes.stories.tsx +797 -0
  148. package/src/message/user-message-quotes.tsx +135 -0
  149. package/src/pierre/comment-hover-machine.ts +53 -0
  150. package/src/pierre/comment-hover.ts +131 -0
  151. package/src/pierre/comment-selection-machine.ts +257 -0
  152. package/src/pierre/commented-lines.ts +106 -0
  153. package/src/pierre/diff-selection.ts +91 -0
  154. package/src/pierre/file-find-machine.ts +323 -0
  155. package/src/pierre/file-find.ts +537 -0
  156. package/src/pierre/file-runtime.ts +42 -0
  157. package/src/pierre/file-selection.ts +140 -0
  158. package/src/pierre/index.ts +344 -0
  159. package/src/pierre/media.ts +140 -0
  160. package/src/pierre/render-machine.ts +381 -0
  161. package/src/pierre/selection-bridge.ts +82 -0
  162. package/src/pierre/selection-machine.ts +198 -0
  163. package/src/pierre/virtualizer.ts +114 -0
  164. package/src/pierre/worker.ts +46 -0
  165. package/src/sources/experiment.ts +59 -0
  166. package/src/sources/site-icon.tsx +53 -0
  167. package/src/sources/sources-chip.tsx +57 -0
  168. package/src/sources/sources-expand-machine.ts +101 -0
  169. package/src/sources/sources-panel.tsx +249 -0
  170. package/src/sources/sources-title.tsx +21 -0
  171. package/src/sources/sources.css +266 -0
  172. package/src/sources/sources.ts +141 -0
  173. package/src/storybook/current-session-fixtures.ts +1492 -0
  174. package/src/storybook/current-session-scenarios.ts +76 -0
  175. package/src/storybook/current-session-story.tsx +154 -0
  176. package/src/storybook/index.ts +43 -0
  177. package/src/styles/index.css +19 -0
  178. package/src/timeline/__snapshots__/group-labels.test.ts.snap +110 -0
  179. package/src/timeline/__snapshots__/placement.test.ts.snap +1041 -0
  180. package/src/timeline/code-blocks.stories.tsx +105 -0
  181. package/src/timeline/commentary.stories.tsx +70 -0
  182. package/src/timeline/commentary.ts +38 -0
  183. package/src/timeline/detail.ts +111 -0
  184. package/src/timeline/error-card.stories.tsx +134 -0
  185. package/src/timeline/error-spacing.stories.tsx +71 -0
  186. package/src/timeline/facts.ts +493 -0
  187. package/src/timeline/file-changes.stories.tsx +436 -0
  188. package/src/timeline/group-label-fixtures.ts +97 -0
  189. package/src/timeline/mermaid.stories.tsx +131 -0
  190. package/src/timeline/place.ts +280 -0
  191. package/src/timeline/placement-fixtures.ts +365 -0
  192. package/src/timeline/placement-reactivity.ts +133 -0
  193. package/src/timeline/projection.ts +1261 -0
  194. package/src/timeline/research-and-agents.stories.tsx +461 -0
  195. package/src/timeline/session-timeline-row.tsx +1675 -0
  196. package/src/timeline/session-timeline.tsx +68 -0
  197. package/src/timeline/steer-arrival-machine.ts +134 -0
  198. package/src/timeline/terminal-work.stories.tsx +464 -0
  199. package/src/timeline/timeline-row.stories.tsx +1069 -0
  200. package/src/timeline/timeline-row.ts +238 -0
  201. package/src/timeline/turn-phase-machine.ts +112 -0
  202. package/src/timeline/user-message-fold.stories.tsx +194 -0
  203. package/src/timeline/user-runs.ts +87 -0
  204. package/src/timeline-next/__snapshots__/placement.test.ts.snap +990 -0
  205. package/src/timeline-next/compaction.tsx +236 -0
  206. package/src/timeline-next/errors.ts +101 -0
  207. package/src/timeline-next/event-row.tsx +168 -0
  208. package/src/timeline-next/events.ts +103 -0
  209. package/src/timeline-next/index.ts +10 -0
  210. package/src/timeline-next/nested-rail.ts +125 -0
  211. package/src/timeline-next/projection.ts +1028 -0
  212. package/src/timeline-next/row.tsx +1728 -0
  213. package/src/timeline-next/rules.ts +89 -0
  214. package/src/timeline-next/separator.tsx +73 -0
  215. package/src/timeline-next/spacing.ts +127 -0
  216. package/src/timeline-next/status-line.tsx +41 -0
  217. package/src/timeline-next/status.ts +33 -0
  218. package/src/timeline-next/stories/compare-renderer.stories.tsx +190 -0
  219. package/src/timeline-next/stories/compare-sessions/.gitignore +3 -0
  220. package/src/timeline-next/stories/compare.stories.tsx +486 -0
  221. package/src/timeline-next/stories/playground.stories.tsx +297 -0
  222. package/src/timeline-next/stories/session-replay.ts +1156 -0
  223. package/src/timeline-next/stories/session-timeline.tsx +50 -0
  224. package/src/timeline-next/stories/subagent-status.stories.tsx +132 -0
  225. package/src/timeline-next/timeline-next.css +649 -0
  226. package/src/timeline-next/tools/__snapshots__/activity-label.test.ts.snap +39 -0
  227. package/src/timeline-next/tools/activity-label.ts +166 -0
  228. package/src/timeline-next/tools/assistant-content.tsx +84 -0
  229. package/src/timeline-next/tools/context-group.tsx +619 -0
  230. package/src/timeline-next/tools/error-card.tsx +147 -0
  231. package/src/timeline-next/tools/explore.tsx +119 -0
  232. package/src/timeline-next/tools/file-group.tsx +128 -0
  233. package/src/timeline-next/tools/patch.tsx +174 -0
  234. package/src/timeline-next/tools/shell.tsx +186 -0
  235. package/src/timeline-next/tools/thought.tsx +87 -0
  236. package/src/timeline-next/tools/tool-display.tsx +119 -0
  237. package/src/tools/ansi.ts +8 -0
  238. package/src/tools/context-group-label.ts +123 -0
  239. package/src/tools/file-runs.ts +35 -0
  240. package/src/tools/project-path.ts +18 -0
  241. package/src/tools/read-group.stories.tsx +159 -0
  242. package/src/tools/run-machine.ts +185 -0
  243. package/src/tools/shell-output-machine.ts +233 -0
  244. package/src/tools/shell-output.ts +91 -0
  245. package/src/tools/subagent-row-variants.stories.tsx +129 -0
  246. package/src/tools/tool-group.stories.tsx +345 -0
  247. package/src/tools/tool-renderer.tsx +2876 -0
  248. package/src/v2/components/line-comment-annotations-v2.tsx +215 -0
  249. package/src/v2/components/session-file-panel-v2.tsx +149 -0
  250. package/src/v2/components/session-progress-indicator-v2.css +5 -0
  251. package/src/v2/components/session-progress-indicator-v2.stories.tsx +86 -0
  252. package/src/v2/components/session-progress-indicator-v2.tsx +16 -0
  253. package/src/v2/components/session-review-empty-changes-v2.tsx +17 -0
  254. package/src/v2/components/session-review-empty-no-git-v2.tsx +28 -0
  255. package/src/v2/components/session-review-file-preview-v2-virtualize.ts +5 -0
  256. package/src/v2/components/session-review-file-preview-v2.tsx +266 -0
  257. package/src/v2/components/session-review-v2.css +653 -0
  258. package/src/v2/components/session-review-v2.tsx +422 -0
  259. package/src/v2/components/sidebar-presence-machine.ts +69 -0
  260. package/tsconfig.json +20 -0
  261. package/README.md +0 -3
@@ -0,0 +1,18 @@
1
+ let sequence = 0
2
+
3
+ export async function renderMermaidSvg(source: string) {
4
+ const pele = await import("pele/lazy")
5
+
6
+ if (!pele.detectType(source)) return
7
+
8
+ const result = await pele.renderAsync(source, {
9
+ idPrefix: `markdown-mermaid-${sequence++}-`,
10
+ // Pele sizes boxes from measured label widths, so it must measure the font the CSS applies.
11
+ fontFamily: getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans"),
12
+ fontSize: 14,
13
+ images: false,
14
+ linkRel: "noopener noreferrer",
15
+ })
16
+
17
+ return result.svg
18
+ }
@@ -0,0 +1,102 @@
1
+ /** A completed render waits this long for inline path checks before it reports ready anyway. */
2
+ export const INLINE_PATH_CHECK_TIMEOUT_MS = 2_000
3
+
4
+ /**
5
+ * `static` never streamed and renders its text in one pass. `streaming` projects each delta through the worker as live
6
+ * blocks. `settled` streamed earlier and now projects the final text once more as completed blocks, so the streamed DOM
7
+ * and the user's selection survive.
8
+ */
9
+ export type MarkdownMode = "static" | "streaming" | "settled"
10
+
11
+ /**
12
+ * Whether one Markdown component can report `data-markdown-ready`. `pending` waits for a render of the current text in
13
+ * the current mode. `checking` has rendered a completed text and waits for its inline path checks, numbered `attempt`.
14
+ * `ready` has rendered the current text and every check it needs. `attempts` counts started checks, so a check that
15
+ * settles after another started is stale. Every streamed delta dispatches here, so an event that changes nothing returns
16
+ * the same state, and every state with no started check is a frozen singleton.
17
+ */
18
+ export type MarkdownPhaseState =
19
+ | { readonly status: "pending"; readonly mode: MarkdownMode; readonly attempts: number }
20
+ | { readonly status: "checking"; readonly mode: Exclude<MarkdownMode, "streaming">; readonly attempt: number }
21
+ | { readonly status: "ready"; readonly mode: MarkdownMode; readonly attempts: number }
22
+ | { readonly status: "disposed" }
23
+
24
+ export type MarkdownPhaseEvent =
25
+ | { readonly type: "props.sync"; readonly streaming: boolean }
26
+ | {
27
+ readonly type: "dom.rendered"
28
+ /** The DOM shows a finished render of the current text, made for the current mode. */
29
+ readonly rendered: boolean
30
+ /** Inline path checks the rendered blocks still wait for. */
31
+ readonly pendingChecks: number
32
+ /** Every block is the one the previous DOM pass rendered, so no new check started. */
33
+ readonly reused: boolean
34
+ }
35
+ | { readonly type: "checks.settled"; readonly attempt: number }
36
+ | { readonly type: "checks.timed-out"; readonly attempt: number }
37
+ | { readonly type: "disposed" }
38
+
39
+ const PENDING = {
40
+ static: Object.freeze({ status: "pending", mode: "static", attempts: 0 }),
41
+ streaming: Object.freeze({ status: "pending", mode: "streaming", attempts: 0 }),
42
+ settled: Object.freeze({ status: "pending", mode: "settled", attempts: 0 }),
43
+ } as const satisfies Record<MarkdownMode, MarkdownPhaseState>
44
+
45
+ const READY = {
46
+ static: Object.freeze({ status: "ready", mode: "static", attempts: 0 }),
47
+ streaming: Object.freeze({ status: "ready", mode: "streaming", attempts: 0 }),
48
+ settled: Object.freeze({ status: "ready", mode: "settled", attempts: 0 }),
49
+ } as const satisfies Record<MarkdownMode, MarkdownPhaseState>
50
+
51
+ export const DISPOSED_MARKDOWN_PHASE_STATE: MarkdownPhaseState = Object.freeze({ status: "disposed" })
52
+
53
+ export const DISPOSED_MARKDOWN_PHASE_EVENT: MarkdownPhaseEvent = Object.freeze({ type: "disposed" })
54
+
55
+ export function createMarkdownPhaseState(streaming: boolean): MarkdownPhaseState {
56
+ return streaming ? PENDING.streaming : PENDING.static
57
+ }
58
+
59
+ export function transitionMarkdownPhase(state: MarkdownPhaseState, event: MarkdownPhaseEvent): MarkdownPhaseState {
60
+ if (state.status === "disposed") return state
61
+
62
+ if (event.type === "disposed") return DISPOSED_MARKDOWN_PHASE_STATE
63
+ const attempts = state.status === "checking" ? state.attempt : state.attempts
64
+
65
+ if (event.type === "props.sync") {
66
+ if (event.streaming) return state.mode === "streaming" ? state : phase("pending", "streaming", attempts)
67
+
68
+ // The last live render is not the settled one: completed blocks still need their path checks.
69
+ return state.mode === "streaming" ? phase("pending", "settled", attempts) : state
70
+ }
71
+
72
+ if (event.type === "checks.settled" || event.type === "checks.timed-out") {
73
+ if (state.status !== "checking" || event.attempt !== state.attempt) return state
74
+
75
+ return phase("ready", state.mode, state.attempt)
76
+ }
77
+
78
+ if (!event.rendered) return state.status === "pending" ? state : phase("pending", state.mode, attempts)
79
+
80
+ // A streaming answer renders again on the next delta, so it never waits for path checks.
81
+ if (state.mode === "streaming" || event.pendingChecks === 0)
82
+ return state.status === "ready" ? state : phase("ready", state.mode, attempts)
83
+
84
+ // A pass that kept every block started no check, so the running check or a reached `ready` still holds.
85
+ if (event.reused && state.status !== "pending") return state
86
+
87
+ return { status: "checking", mode: state.mode, attempt: attempts + 1 }
88
+ }
89
+
90
+ export function markdownMode(state: MarkdownPhaseState): MarkdownMode {
91
+ return state.status === "disposed" ? "static" : state.mode
92
+ }
93
+
94
+ export function markdownReady(state: MarkdownPhaseState) {
95
+ return state.status === "ready"
96
+ }
97
+
98
+ function phase(status: "pending" | "ready", mode: MarkdownMode, attempts: number): MarkdownPhaseState {
99
+ if (attempts === 0) return status === "pending" ? PENDING[mode] : READY[mode]
100
+
101
+ return { status, mode, attempts }
102
+ }
@@ -0,0 +1,13 @@
1
+ import type { Block, Projection } from "./markdown-stream"
2
+
3
+ export function completedProjection(text: string): Projection {
4
+ return { text, blocks: [{ raw: text, src: text, mode: "full" }] }
5
+ }
6
+
7
+ export function canReusePendingBlock(current: Pick<Block, "mode" | "raw"> | undefined, next: Block) {
8
+ if (!current || current.mode !== next.mode) return false
9
+
10
+ if (next.mode === "code" || next.mode === "live") return next.raw.startsWith(current.raw)
11
+
12
+ return current.raw === next.raw
13
+ }
@@ -0,0 +1,183 @@
1
+ import { parseSessionMention, sessionMentions, type SessionMention } from "@zyro-sec/util/session-mention"
2
+
3
+ export type SessionTitle = (id: string) => string | undefined
4
+
5
+ export function markSessionLinks(root: HTMLElement, title: SessionTitle) {
6
+ // Already-rendered references retain their source so renames, discovery and deletion are reactive.
7
+ root.querySelectorAll<HTMLElement>("[data-session-reference]").forEach((element) => {
8
+ const source = element.dataset.sessionReference!
9
+ const mention = parseSessionMention(source)
10
+
11
+ if (!mention) return
12
+ const label = title(mention.id)
13
+
14
+ if (
15
+ element.textContent === (label === undefined ? source : `@${label}`) &&
16
+ (element.tagName === "BUTTON") === (label !== undefined)
17
+ )
18
+ return
19
+ element.replaceWith(sessionReference(mention, source, label))
20
+ })
21
+
22
+ if (!root.textContent?.includes("ses_")) return
23
+
24
+ // The worker's escaped-raw fallback has no markdown elements; linking its text
25
+ // would turn IDs inside still-unparsed fenced code into buttons.
26
+ if (!root.querySelector("p, li, blockquote, td, th, h1, h2, h3, h4, h5, h6")) return
27
+
28
+ root.querySelectorAll("code").forEach((code) => {
29
+ if (code.closest("pre, a, button, [data-session-reference]")) return
30
+ const source = code.textContent ?? ""
31
+ const mention = parseSessionMention(source)
32
+
33
+ if (mention) code.replaceWith(sessionReference(mention, source, title(mention.id)))
34
+ })
35
+
36
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
37
+ const nodes: Text[] = []
38
+
39
+ while (walker.nextNode()) {
40
+ // SAFETY: SHOW_TEXT restricts this walk to Text nodes.
41
+ const node = walker.currentNode as Text
42
+
43
+ if (node.parentElement?.closest("a, button, code, pre, [data-session-reference]")) continue
44
+
45
+ if (node.data.includes("ses_")) nodes.push(node)
46
+ }
47
+
48
+ nodes.forEach((node) => {
49
+ node.replaceWith(sessionReferenceText(node.data, title))
50
+ })
51
+ }
52
+
53
+ /** Shared by plain user text and rendered assistant markdown. */
54
+ export function sessionReferenceText(text: string, title: SessionTitle) {
55
+ const fragment = document.createDocumentFragment()
56
+ let start = 0
57
+ sessionMentions(text).forEach((mention) => {
58
+ fragment.append(text.slice(start, mention.start), sessionReference(mention, mention.text, title(mention.id)))
59
+ start = mention.end
60
+ })
61
+ fragment.append(text.slice(start))
62
+
63
+ return fragment
64
+ }
65
+
66
+ function sessionReference(mention: SessionMention, source: string, title: string | undefined) {
67
+ if (title === undefined) {
68
+ const code = document.createElement("code")
69
+ code.className = "markdown-session-id"
70
+ code.dataset.sessionId = mention.id
71
+ code.dataset.sessionReference = source
72
+ code.textContent = source
73
+
74
+ return code
75
+ }
76
+
77
+ const button = document.createElement("button")
78
+ button.type = "button"
79
+ button.className = "markdown-session-link"
80
+ button.dataset.sessionId = mention.id
81
+ button.dataset.sessionReference = source
82
+ button.title = mention.id
83
+ button.textContent = `@${title}`
84
+
85
+ return button
86
+ }
87
+
88
+ export type SessionReferenceMenu = (input: { sessionID: string; x: number; y: number }) => void
89
+
90
+ export function setupSessionLinks(
91
+ root: HTMLElement,
92
+ open: () => ((id: string) => void) | undefined,
93
+ menu?: () => SessionReferenceMenu | undefined,
94
+ ) {
95
+ const click = (event: MouseEvent) => {
96
+ if (event.defaultPrevented || !(event.target instanceof Element)) return
97
+ const button = event.target.closest("button[data-session-id]")
98
+
99
+ if (!(button instanceof HTMLButtonElement) || !root.contains(button)) return
100
+ const handler = open()
101
+
102
+ if (!handler) return
103
+ event.stopPropagation()
104
+ handler(button.dataset.sessionId!)
105
+ }
106
+
107
+ const contextMenu = (event: MouseEvent) => {
108
+ const reference = sessionReferenceTarget(root, event.target)
109
+ const handler = menu?.()
110
+
111
+ if (event.defaultPrevented || !reference || !handler) return
112
+ event.preventDefault()
113
+ event.stopPropagation()
114
+ handler({ sessionID: reference.dataset.sessionId!, x: event.clientX, y: event.clientY })
115
+ }
116
+
117
+ const keyDown = (event: KeyboardEvent) => {
118
+ if (event.key !== "ContextMenu" && (event.key !== "F10" || !event.shiftKey)) return
119
+ const reference = sessionReferenceTarget(root, event.target)
120
+ const handler = menu?.()
121
+
122
+ if (event.defaultPrevented || !reference || !handler) return
123
+ const bounds = reference.getBoundingClientRect()
124
+ event.preventDefault()
125
+ handler({ sessionID: reference.dataset.sessionId!, x: bounds.left, y: bounds.bottom })
126
+ }
127
+
128
+ root.addEventListener("click", click)
129
+ root.addEventListener("contextmenu", contextMenu)
130
+ root.addEventListener("keydown", keyDown)
131
+
132
+ return () => {
133
+ root.removeEventListener("click", click)
134
+ root.removeEventListener("contextmenu", contextMenu)
135
+ root.removeEventListener("keydown", keyDown)
136
+ }
137
+ }
138
+
139
+ function sessionReferenceTarget(root: HTMLElement, target: EventTarget | null) {
140
+ if (!(target instanceof Element)) return
141
+ const reference = target.closest<HTMLElement>("[data-session-reference][data-session-id]")
142
+
143
+ return reference && root.contains(reference) ? reference : undefined
144
+ }
145
+
146
+ /** Undefined when the selection holds no session reference, so the caller keeps its usual copy. */
147
+ export function sessionReferenceClipboardText(root: HTMLElement, ranges: readonly Range[]) {
148
+ const references = Array.from(root.querySelectorAll("[data-session-reference]"))
149
+
150
+ if (!ranges.some((range) => references.some((reference) => range.intersectsNode(reference)))) return
151
+ const container = document.createElement("div")
152
+ container.style.cssText = "position:fixed;top:0;left:-100000px"
153
+ ranges.forEach((range) => container.append(sessionReferenceRange(range).cloneContents()))
154
+ container.querySelectorAll<HTMLElement>("[data-session-reference]").forEach((reference) => {
155
+ reference.replaceWith(reference.dataset.sessionReference ?? "")
156
+ })
157
+ // `innerText` needs layout to keep line breaks.
158
+ root.append(container)
159
+ const text = container.innerText
160
+ container.remove()
161
+
162
+ return text
163
+ }
164
+
165
+ /** References copy atomically even when the selection starts or ends inside their displayed title. */
166
+ export function sessionReferenceRange(range: Range) {
167
+ const start = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement
168
+
169
+ const end = range.endContainer instanceof Element ? range.endContainer : range.endContainer.parentElement
170
+
171
+ const first = start?.closest("[data-session-reference]")
172
+
173
+ const last = end?.closest("[data-session-reference]")
174
+
175
+ if (!first && !last) return range
176
+ const selection = range.cloneRange()
177
+
178
+ if (first) selection.setStartBefore(first)
179
+
180
+ if (last) selection.setEndAfter(last)
181
+
182
+ return selection
183
+ }
@@ -0,0 +1,92 @@
1
+ import { GlobalRegistrator } from "@happy-dom/global-registrator"
2
+ import { afterAll, beforeAll, expect, test } from "bun:test"
3
+ import { parseMarkdownNodes } from "./markdown-solid"
4
+
5
+ beforeAll(() => GlobalRegistrator.register())
6
+
7
+ afterAll(() => GlobalRegistrator.unregister())
8
+
9
+ function parse(html: string, words: boolean, animate?: boolean) {
10
+ const template = document.createElement("template")
11
+ template.innerHTML = html
12
+
13
+ return parseMarkdownNodes(template.content, words, animate)
14
+ }
15
+
16
+ test("assigns stable paths to elements and individual words", () => {
17
+ expect(parse('<p class="lead">Hello <strong>streaming</strong> world</p>', true)).toEqual([
18
+ {
19
+ key: "0",
20
+ type: "element",
21
+ tag: "p",
22
+ attributes: { class: "lead" },
23
+ children: [
24
+ { key: "0.0:0", type: "word", text: "Hello" },
25
+ { key: "0.0:1", type: "text", text: " " },
26
+ {
27
+ key: "0.1",
28
+ type: "element",
29
+ tag: "strong",
30
+ attributes: {},
31
+ children: [{ key: "0.1.0:0", type: "word", text: "streaming" }],
32
+ },
33
+ { key: "0.2:1", type: "text", text: " " },
34
+ { key: "0.2:2", type: "word", text: "world" },
35
+ ],
36
+ },
37
+ ])
38
+ })
39
+
40
+ test("keeps completed block text compact", () => {
41
+ expect(parse("<p>Hello world</p>", false)).toEqual([
42
+ {
43
+ key: "0",
44
+ type: "element",
45
+ tag: "p",
46
+ attributes: {},
47
+ children: [{ key: "0.0", type: "text", text: "Hello world" }],
48
+ },
49
+ ])
50
+ })
51
+
52
+ test("marks streamed inline code for animation", () => {
53
+ expect(parse("<p><code>file.ts:29-43</code></p>", true, true)).toEqual([
54
+ {
55
+ key: "0",
56
+ type: "element",
57
+ tag: "p",
58
+ attributes: {},
59
+ children: [
60
+ {
61
+ key: "0.0",
62
+ type: "element",
63
+ tag: "code",
64
+ attributes: {},
65
+ children: Array.from("file.ts:29-43", (text, index) => ({
66
+ key: `0.0.0:${index}`,
67
+ type: "word",
68
+ text,
69
+ animate: true,
70
+ })),
71
+ animate: true,
72
+ },
73
+ ],
74
+ },
75
+ ])
76
+ })
77
+
78
+ test("marks words for animation only when requested", () => {
79
+ expect(parse("<p>Hello</p>", true).flatMap((node) => (node.type === "element" ? node.children : [node]))[0]).toEqual({
80
+ key: "0.0:0",
81
+ type: "word",
82
+ text: "Hello",
83
+ })
84
+ expect(
85
+ parse("<p>Hello</p>", true, true).flatMap((node) => (node.type === "element" ? node.children : [node]))[0],
86
+ ).toEqual({
87
+ key: "0.0:0",
88
+ type: "word",
89
+ text: "Hello",
90
+ animate: true,
91
+ })
92
+ })
@@ -0,0 +1,113 @@
1
+ import { createMemo, For, onMount } from "solid-js"
2
+ import { createStore, reconcile } from "solid-js/store"
3
+ import { Dynamic, render } from "solid-js/web"
4
+
5
+ type MarkdownNode =
6
+ | {
7
+ key: string
8
+ type: "element"
9
+ tag: string
10
+ attributes: Record<string, string>
11
+ children: MarkdownNode[]
12
+ animate?: true
13
+ }
14
+ | { key: string; type: "text"; text: string }
15
+ | { key: string; type: "math"; element: MathMLElement }
16
+ | { key: string; type: "word"; text: string; animate?: true }
17
+
18
+ export function createMarkdownRenderer(root: HTMLDivElement, source: ParentNode, words: boolean) {
19
+ const [nodes, setNodes] = createStore(parseMarkdownNodes(source, words))
20
+ let ready = false
21
+
22
+ const dispose = render(
23
+ () => <For each={nodes}>{(node) => <MarkdownDomNode node={node} animate={() => ready} />}</For>,
24
+ root,
25
+ )
26
+
27
+ ready = true
28
+
29
+ return {
30
+ update(next: ParentNode, nextWords: boolean, animate = true) {
31
+ setNodes(reconcile(parseMarkdownNodes(next, nextWords, animate), { key: "key" }))
32
+ },
33
+ dispose,
34
+ }
35
+ }
36
+
37
+ function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean }) {
38
+ const node = props.node
39
+
40
+ if (node.type === "text") return node.text
41
+
42
+ if (node.type === "math") {
43
+ const math = createMemo(() => node.element, undefined, { equals: (a, b) => a.isEqualNode(b) })
44
+
45
+ return <>{math()}</>
46
+ }
47
+
48
+ if (node.type === "word") {
49
+ let ref: HTMLSpanElement | undefined
50
+ onMount(() => {
51
+ if (props.animate() && node.animate) ref?.setAttribute("data-markdown-enter", "")
52
+ })
53
+
54
+ return (
55
+ <span ref={ref} data-markdown-word="">
56
+ {node.text}
57
+ </span>
58
+ )
59
+ }
60
+
61
+ let ref: HTMLElement | undefined
62
+ onMount(() => {
63
+ if (props.animate() && node.animate) ref?.setAttribute("data-markdown-enter", "")
64
+ })
65
+
66
+ return (
67
+ <Dynamic component={node.tag} ref={ref} {...node.attributes}>
68
+ <For each={node.children}>{(node) => <MarkdownDomNode node={node} animate={props.animate} />}</For>
69
+ </Dynamic>
70
+ )
71
+ }
72
+
73
+ export function parseMarkdownNodes(source: ParentNode, words: boolean, animate = false) {
74
+ return Array.from(source.childNodes).flatMap((node, index) => parseNode(node, `${index}`, words, animate))
75
+ }
76
+
77
+ function parseNode(node: Node, key: string, words: boolean, animate: boolean, inlineCode = false): MarkdownNode[] {
78
+ if (node instanceof Text) {
79
+ if (!words) return [{ key, type: "text", text: node.data }]
80
+
81
+ return (inlineCode ? Array.from(node.data) : node.data.split(/(\s+)/)).flatMap((text, index): MarkdownNode[] => {
82
+ if (!text) return []
83
+
84
+ if (/^\s+$/.test(text)) return [{ key: `${key}:${index}`, type: "text", text }]
85
+ const word: Extract<MarkdownNode, { type: "word" }> = { key: `${key}:${index}`, type: "word", text }
86
+
87
+ if (animate) word.animate = true
88
+
89
+ return [word]
90
+ })
91
+ }
92
+
93
+ if (!(node instanceof Element)) return []
94
+
95
+ // Keep the MathML namespace: Dynamic would recreate its descendants as HTML elements.
96
+ if (node.localName === "math" && typeof MathMLElement !== "undefined" && node instanceof MathMLElement)
97
+ return [{ key: `${key}:math`, type: "math", element: node }]
98
+ const code = node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"
99
+
100
+ const element: Extract<MarkdownNode, { type: "element" }> = {
101
+ key,
102
+ type: "element",
103
+ tag: node.tagName.toLowerCase(),
104
+ attributes: Object.fromEntries(Array.from(node.attributes).map((attribute) => [attribute.name, attribute.value])),
105
+ children: Array.from(node.childNodes).flatMap((child, index) =>
106
+ parseNode(child, `${key}.${index}`, words, animate, inlineCode || code),
107
+ ),
108
+ }
109
+
110
+ if (words && animate && code) element.animate = true
111
+
112
+ return [element]
113
+ }
@@ -0,0 +1,95 @@
1
+ import { createMarkdownStream, type MarkdownBlock, type PatchmarkStream } from "@zyro-sec/patchmark"
2
+ import { isMathFence } from "@zyro-sec/ui/context/marked-parser"
3
+ import { completedProjection } from "./markdown-projection"
4
+
5
+ export type Block = {
6
+ raw: string
7
+ src: string
8
+ mode: "full" | "live" | "code"
9
+ language?: string
10
+ complete?: boolean
11
+ }
12
+
13
+ export type Projection = {
14
+ text: string
15
+ blocks: Block[]
16
+ }
17
+
18
+ const streams = new WeakMap<Projection, PatchmarkStream>()
19
+
20
+ const projectedBlocks = new WeakMap<MarkdownBlock, Block>()
21
+
22
+ function createStream() {
23
+ return createMarkdownStream({
24
+ gfm: true,
25
+ math: true,
26
+ heal: true,
27
+ holdPendingMarkers: false,
28
+ settleOnComplete: false,
29
+ groupHtmlBlocks: true,
30
+ renderHtml: false,
31
+ })
32
+ }
33
+
34
+ function toBlock(block: MarkdownBlock): Block {
35
+ const cached = projectedBlocks.get(block)
36
+
37
+ if (cached) return cached
38
+
39
+ // A closed math fence goes to the Markdown parser, which draws it as display math; while it streams it stays code.
40
+ const math = block.kind.type === "code" && block.kind.complete && isMathFence(block.kind.language)
41
+
42
+ if (!math && (block.kind.type === "code" || block.kind.type === "mermaid")) {
43
+ const item: Block = {
44
+ raw: block.raw,
45
+ src: block.kind.source,
46
+ mode: "code",
47
+ }
48
+
49
+ const language = block.kind.type === "mermaid" ? "mermaid" : block.kind.language
50
+
51
+ if (language) item.language = language
52
+
53
+ if (block.kind.complete || block.status === "settled") item.complete = true
54
+
55
+ projectedBlocks.set(block, item)
56
+
57
+ return item
58
+ }
59
+
60
+ const mode = math || block.status === "settled" ? "full" : "live"
61
+ const defs = block.defs ? `\n\n${block.defs}` : ""
62
+ const base = mode === "live" ? (block.liveRaw ?? block.raw) : block.raw
63
+
64
+ const item: Block = {
65
+ raw: block.raw,
66
+ src: base + defs,
67
+ mode,
68
+ }
69
+
70
+ projectedBlocks.set(block, item)
71
+
72
+ return item
73
+ }
74
+
75
+ export function stream(text: string, live: boolean): Block[] {
76
+ return project(undefined, text, live).blocks
77
+ }
78
+
79
+ export function project(previous: Projection | undefined, text: string, live: boolean): Projection {
80
+ if (!previous && !live) return completedProjection(text)
81
+
82
+ if (previous && live && previous.text === text) return previous
83
+
84
+ const instance = (previous ? streams.get(previous) : undefined) ?? createStream()
85
+ const blocks = instance.update(text, { streaming: live }).blocks.map(toBlock)
86
+
87
+ const next: Projection = {
88
+ text,
89
+ blocks: blocks.length === 0 ? [{ raw: text, src: text, mode: live ? "live" : "full" }] : blocks,
90
+ }
91
+
92
+ if (live) streams.set(next, instance)
93
+
94
+ return next
95
+ }