@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,556 @@
1
+ import { checksum } from "@zyro-sec/util/encode"
2
+ import { parseSmallMarkdown } from "@zyro-sec/ui/context/marked-base"
3
+ import DOMPurify from "dompurify"
4
+ import {
5
+ INITIAL_MARKDOWN_CACHE_STATE,
6
+ transitionMarkdownCache,
7
+ type MarkdownCacheEffect,
8
+ type MarkdownCacheEntry,
9
+ type MarkdownCacheEvent,
10
+ } from "./markdown-cache-machine"
11
+ import { abortParseMarkdown, markdownWorkerDisposed, startParseMarkdown } from "./markdown-worker"
12
+ import { localImagePath, localLinkPath } from "./markdown-image"
13
+ import type { MarkdownHTML } from "./markdown-worker-protocol"
14
+
15
+ export type { MarkdownCacheEntry } from "./markdown-cache-machine"
16
+
17
+ const max = 200
18
+
19
+ // Completed entries in LRU order, oldest first.
20
+ const cache = new Map<string, MarkdownCacheEntry>()
21
+
22
+ let state = INITIAL_MARKDOWN_CACHE_STATE
23
+
24
+ const queue: MarkdownCacheEvent[] = []
25
+
26
+ // Consumer ids travel in `render.requested`, so a request queued behind another still settles its own waiter.
27
+ let consumers = 0
28
+
29
+ const waiters = new Map<
30
+ number,
31
+ {
32
+ resolve: (entry: MarkdownCacheEntry) => void
33
+ reject: (error: Error) => void
34
+ signal: AbortSignal | undefined
35
+ cancel: () => void
36
+ }
37
+ >()
38
+
39
+ // The worker request id of each running job, so an abandoned parse can be cancelled.
40
+ const workerIds = new Map<number, number>()
41
+
42
+ // A private instance keeps this hook set separate from other DOMPurify users.
43
+ const purifier = typeof window !== "undefined" ? DOMPurify(window) : DOMPurify
44
+
45
+ const rendered = typeof window !== "undefined" ? DOMPurify(window) : DOMPurify
46
+
47
+ // Sanitized renderer output by its source HTML, most recently used last.
48
+ const renderedFragments = new Map<string, Node>()
49
+
50
+ if (typeof window !== "undefined" && purifier.isSupported) {
51
+ const appLinks = new WeakMap<HTMLAnchorElement, string>()
52
+ const files = new WeakMap<HTMLAnchorElement, string>()
53
+ const images = new WeakMap<HTMLImageElement, string>()
54
+
55
+ const prose = new Set(
56
+ "a abbr b bdi bdo blockquote br caption center cite code col colgroup data dd del details dfn div dl dt em figcaption figure h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark ol p pre q rp rt ruby s samp small span strong sub summary sup table tbody td tfoot th thead time tr u ul var wbr".split(
57
+ " ",
58
+ ),
59
+ )
60
+
61
+ // The rest of what the chat rendered before this allow-list: legacy, sectioning and media markup. Outside `prose`,
62
+ // each is marked for paint containment, so none can lay itself out over the app.
63
+ const contained = "acronym address article aside audio big blink dir font footer header hgroup main marquee menu nav nobr picture search section source spacer strike track tt video".split(" ")
64
+
65
+ const paint = [
66
+ "fill",
67
+ "fill-opacity",
68
+ "stroke",
69
+ "stroke-width",
70
+ "stroke-opacity",
71
+ "stroke-linecap",
72
+ "stroke-linejoin",
73
+ "stroke-miterlimit",
74
+ "stroke-dasharray",
75
+ "stroke-dashoffset",
76
+ "opacity",
77
+ ]
78
+
79
+ const style = document.createElement("span").style
80
+ const allowedStyle = document.createElement("span").style
81
+
82
+ // A config passed to sanitize() rebuilds every allow-list on each call; set once, every call reuses them.
83
+ const config = {
84
+ SANITIZE_NAMED_PROPS: true,
85
+ FORBID_TAGS: ["style", "dialog"],
86
+ FORBID_ATTR: [
87
+ "popover",
88
+ "popovertarget",
89
+ "popovertargetaction",
90
+ "command",
91
+ "commandfor",
92
+ "data-floating-overlay",
93
+ "data-markdown-renderer",
94
+ ],
95
+ FORBID_CONTENTS: ["style", "script"],
96
+ ADD_TAGS: ["svg", "path"],
97
+ ADD_ATTR: ["d", "viewBox", "preserveAspectRatio", "xmlns", "target"],
98
+ }
99
+
100
+ purifier.setConfig({
101
+ ...config,
102
+ ALLOW_DATA_ATTR: false,
103
+ ALLOW_ARIA_ATTR: false,
104
+ RETURN_DOM_FRAGMENT: true,
105
+ ADD_ATTR: [...config.ADD_ATTR, "aria-label", "aria-hidden"],
106
+ ALLOWED_TAGS: [
107
+ ...prose,
108
+ ...contained,
109
+ ..."math mrow mi mn mo ms mtext mspace mfrac msqrt mroot msub msup msubsup munder mover munderover mtable mtr mtd mmultiscripts mprescripts none menclose merror mfenced mpadded mphantom mstyle semantics annotation".split(
110
+ " ",
111
+ ),
112
+ ],
113
+ })
114
+ // These fragments still pass DOMPurify's structural/URI checks, but their renderer owns their inline geometry.
115
+ rendered.setConfig({ ...config, USE_PROFILES: { html: true, mathMl: true }, RETURN_DOM_FRAGMENT: true })
116
+ purifier.addHook("uponSanitizeElement", (node) => {
117
+ // `a`, `use`, `image` and `foreignObject` inside SVG would link, reference or embed; drop them with their contents.
118
+ if (node instanceof SVGElement && node.localName !== "svg" && node.localName !== "path") node.remove()
119
+ })
120
+ purifier.addHook("uponSanitizeAttribute", (node, attr) => {
121
+ // Never import identifiers from the app's styling, focus, shortcut, form or plugin protocols. This allowlist
122
+ // is for document content only. DOMPurify still validates every value and namespaces id and name.
123
+ const tag = node.localName
124
+ const name = attr.attrName
125
+
126
+ if (node instanceof SVGElement && paint.includes(name)) {
127
+ attr.keepAttr = svgPaint(name, attr.attrValue)
128
+
129
+ return
130
+ }
131
+
132
+ const allowed =
133
+ /^(style|id|dir|lang|title|align)$/.test(name) ||
134
+ ((tag === "a" || tag === "img") && name === "aria-label") ||
135
+ (tag === "a" &&
136
+ (name === "href" ||
137
+ name === "download" ||
138
+ name === "name" ||
139
+ name === "rel" ||
140
+ (name === "target" && attr.attrValue === "_blank"))) ||
141
+ (tag === "img" && /^(src|alt|height|width)$/.test(name)) ||
142
+ (/^(q|blockquote|ins|del)$/.test(tag) && name === "cite") ||
143
+ (/^(time|ins|del)$/.test(tag) && name === "datetime") ||
144
+ (tag === "data" && name === "value") ||
145
+ (tag === "font" && /^(color|face|size)$/.test(name)) ||
146
+ (/^(video|audio)$/.test(tag) && /^(src|controls|loop|muted|preload|autoplay)$/.test(name)) ||
147
+ (tag === "video" && /^(poster|playsinline|width|height)$/.test(name)) ||
148
+ (tag === "source" && /^(src|type|srcset|sizes|media)$/.test(name)) ||
149
+ (tag === "track" && /^(src|kind|srclang|label|default)$/.test(name)) ||
150
+ (/^(table|col|th|td)$/.test(tag) && /^(width|colspan|rowspan|scope)$/.test(name)) ||
151
+ (tag === "ol" && /^(start|reversed|type)$/.test(name)) ||
152
+ (tag === "li" && name === "value") ||
153
+ (tag === "details" && name === "open") ||
154
+ (tag === "svg" && /^(viewbox|preserveaspectratio|xmlns|width|height)$/.test(name)) ||
155
+ (tag === "svg" && name === "aria-hidden" && /^(true|false)$/.test(attr.attrValue)) ||
156
+ (tag === "path" && name === "d")
157
+
158
+ if (!allowed) {
159
+ attr.keepAttr = false
160
+
161
+ return
162
+ }
163
+
164
+ const sized = /^(?:img|table|th|td|col|svg|video)$/.test(tag)
165
+
166
+ if ((name === "width" || (tag === "svg" && name === "height")) && sized) {
167
+ const width = contentWidth(attr.attrValue, true)
168
+ attr.keepAttr = !!width
169
+ attr.attrValue = width
170
+
171
+ return
172
+ }
173
+
174
+ if (attr.attrName !== "style") return
175
+ style.cssText = attr.attrValue
176
+ allowedStyle.cssText = ""
177
+
178
+ for (const property of [
179
+ "color",
180
+ "background-color",
181
+ "font-weight",
182
+ "font-style",
183
+ "text-decoration-line",
184
+ "text-align",
185
+ ]) {
186
+ allowedStyle.setProperty(property, style.getPropertyValue(property))
187
+ }
188
+
189
+ if (sized) allowedStyle.width = contentWidth(style.width, false)
190
+
191
+ attr.attrValue = allowedStyle.cssText
192
+ attr.keepAttr = !!attr.attrValue
193
+ })
194
+ purifier.addHook("beforeSanitizeAttributes", (node) => {
195
+ // Removing `is` does not clear Chromium's internal customized-built-in name; serialization can put it back.
196
+ if (node instanceof Element && node.hasAttribute("is"))
197
+ return node.replaceWith(node.ownerDocument.createTextNode(node.textContent ?? ""))
198
+
199
+ if (node instanceof HTMLAnchorElement) {
200
+ // Local file links never navigate the document; the host decides how to open them.
201
+ const href = node.getAttribute("href") ?? ""
202
+ const path = localLinkPath(href)
203
+
204
+ const protocol = URL.parse(href)?.protocol
205
+
206
+ if (protocol && !path && !/^(https?|file):$/.test(protocol)) {
207
+ // Chromium navigates a `download` link it cannot fetch. Only web and file links download; another app's
208
+ // address takes the review like every other.
209
+ node.removeAttribute("download")
210
+
211
+ if (href.length > 2048 || /[<>\x00-\x1f\x7f-\x9f]/.test(href)) return node.removeAttribute("href")
212
+ node.removeAttribute("style")
213
+ node.removeAttribute("class")
214
+
215
+ // A card, an entire paragraph or a display formula (its slot is still empty here, so the worker marks it) is
216
+ // not a link label. Keep its contents, but don't arm that hit area.
217
+ if (node.querySelector(":not(b,i,em,strong,s,span,code), [data-display]")) return node.removeAttribute("href")
218
+
219
+ appLinks.set(node, href)
220
+ }
221
+
222
+ if (!path) return
223
+ files.set(node, path)
224
+ node.removeAttribute("href")
225
+ node.removeAttribute("target")
226
+
227
+ return
228
+ }
229
+
230
+ if (!(node instanceof HTMLImageElement)) return
231
+ // Local paths are not browser URLs. Keep them inert until the host reads them.
232
+ const path = localImagePath(node.getAttribute("src") ?? "")
233
+
234
+ if (!path) return
235
+ images.set(node, path)
236
+ node.removeAttribute("src")
237
+ node.removeAttribute("srcset")
238
+ })
239
+ purifier.addHook("afterSanitizeAttributes", (node: Element) => {
240
+ // This application-owned marker only adds containment. Renderer fragments never pass through this hook.
241
+ if (
242
+ node instanceof Element &&
243
+ node.localName !== "body" &&
244
+ (!prose.has(node.localName) || node.hasAttribute("id") || node.hasAttribute("name"))
245
+ )
246
+ node.setAttribute("data-markdown-contain", "")
247
+
248
+ if (node instanceof HTMLImageElement) {
249
+ const path = images.get(node)
250
+
251
+ if (path) node.dataset.localImage = path
252
+ }
253
+
254
+ if (!(node instanceof HTMLAnchorElement)) return
255
+ const file = files.get(node)
256
+
257
+ if (file) {
258
+ node.dataset.localLink = file
259
+ node.setAttribute("role", "link")
260
+ node.tabIndex = 0
261
+ }
262
+
263
+ const href = appLinks.get(node)
264
+
265
+ // Never restore a stripped href. Preserve the original as inert text, including characters DOMPurify or the
266
+ // URL parser might trim: the desktop policy checks exactly what the author wrote.
267
+ if (href !== undefined) {
268
+ node.dataset.appLink = href
269
+
270
+ // Strip authored inline styling from the label, but retain inert renderer slots; they contain no author HTML.
271
+ for (const child of Array.from(node.querySelectorAll("*")).reverse()) {
272
+ if (child.localName === "span" && /^[0-9a-f]{32}$/.test(child.id) && !child.hasChildNodes()) continue
273
+ child.replaceWith(...child.childNodes)
274
+ }
275
+
276
+ if (!node.hasAttribute("href")) {
277
+ node.removeAttribute("tabindex")
278
+ node.removeAttribute("role")
279
+ }
280
+ }
281
+
282
+ if (node.target !== "_blank") return
283
+
284
+ if (/^https?:$/.test(node.protocol)) node.classList.add("external-link")
285
+
286
+ const rel = node.getAttribute("rel") ?? ""
287
+ const set = new Set(rel.split(/\s+/).filter(Boolean))
288
+ set.add("noopener")
289
+ set.add("noreferrer")
290
+ node.setAttribute("rel", Array.from(set).join(" "))
291
+ })
292
+ }
293
+
294
+ function contentWidth(value: string, attribute: boolean) {
295
+ const match = /^(\d+(?:\.\d+)?)(px|%)?$/i.exec(value.trim())
296
+
297
+ if (!match) return ""
298
+ const unit = match[2] === "%" ? "%" : attribute ? "" : "px"
299
+
300
+ return `${Math.min(Number(match[1]), unit === "%" ? 100 : 2048)}${unit}`
301
+ }
302
+
303
+ // Colors and plain numbers only: a paint value can reference another element (`url(#id)`), which may be outside the message.
304
+ function svgPaint(name: string, value: string) {
305
+ if (name === "fill" || name === "stroke")
306
+ return /^(?:[a-z]+|#[\da-f]{3,8}|(?:rgba?|hsla?)\([\d.%, /+-]{1,64}\))$/i.test(value)
307
+
308
+ if (name === "stroke-linecap" || name === "stroke-linejoin") return /^(?:butt|round|square|bevel|miter)$/.test(value)
309
+
310
+ if (name === "stroke-dasharray" || name === "stroke-dashoffset") return /^(?:none|[\d., -]{1,128})$/.test(value)
311
+
312
+ return /^\d*\.?\d+$/.test(value) && Number(value) <= (name.endsWith("opacity") ? 1 : 64)
313
+ }
314
+
315
+ export function sanitizeMarkdown(html: MarkdownHTML) {
316
+ if (!purifier.isSupported) return ""
317
+ const template = document.createElement("template")
318
+ // SAFETY: MarkdownHTML is the worker's typed union; strings have no out-of-band fragments.
319
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- see SAFETY above
320
+ const plain = typeof html === "string"
321
+ template.content.append(purifier.sanitize(plain ? html : html.html, { RETURN_DOM_FRAGMENT: true }))
322
+
323
+ if (plain) return template.innerHTML
324
+
325
+ for (const [key, output] of html.fragments) {
326
+ // Replace the complete slot, never bless it or its children. Author input cannot populate the worker's map.
327
+ const slot = template.content.getElementById(`user-content-${key}`)
328
+
329
+ if (!slot) continue
330
+ slot.replaceWith(rendererFragment(output))
331
+ }
332
+
333
+ return template.innerHTML
334
+ }
335
+
336
+ // A streamed block is sanitized again on every delta while its formulas and code stay the same.
337
+ function rendererFragment(output: string) {
338
+ const kept = renderedFragments.get(output)
339
+
340
+ if (kept) {
341
+ renderedFragments.delete(output)
342
+ renderedFragments.set(output, kept)
343
+
344
+ return kept.cloneNode(true)
345
+ }
346
+
347
+ const fragment = rendered.sanitize(output, { RETURN_DOM_FRAGMENT: true })
348
+ renderedFragments.set(output, fragment.cloneNode(true))
349
+
350
+ if (renderedFragments.size > 64) renderedFragments.delete(renderedFragments.keys().next().value ?? "")
351
+
352
+ return fragment
353
+ }
354
+
355
+ /** Only the desktop session installs a reviewer for inert application targets. */
356
+ export function enableMarkdownAppLinks(source: ParentNode) {
357
+ source.querySelectorAll<HTMLAnchorElement>("a[data-app-link]").forEach((anchor) => {
358
+ anchor.setAttribute("role", "link")
359
+ anchor.tabIndex = 0
360
+ })
361
+ }
362
+
363
+ export function getCachedMarkdown(key: string) {
364
+ return cache.get(key)
365
+ }
366
+
367
+ export function touchCachedMarkdown(key: string, value: MarkdownCacheEntry) {
368
+ remember(key, value)
369
+ dispatch({ type: "cache.touched", key, src: value.src ?? value.raw })
370
+ }
371
+
372
+ export async function preloadMarkdown(text: string, cacheKey: string, signal?: AbortSignal) {
373
+ if (signal?.aborted) throw markdownWorkerDisposed
374
+ const block = { raw: text, src: text }
375
+ const key = `${cacheKey}:0:full`
376
+
377
+ if (getReadyMarkdown(block, key)) return
378
+ await renderCachedMarkdown(block, key, signal)
379
+ }
380
+
381
+ export function getReadyMarkdown(block: { raw: string; src: string }, key?: string) {
382
+ const cached = key ? getCachedMarkdown(key) : undefined
383
+
384
+ if (key && cached && (cached.src ?? cached.raw) === block.src) {
385
+ touchCachedMarkdown(key, cached)
386
+
387
+ return cached
388
+ }
389
+
390
+ if (!purifier.isSupported) return
391
+
392
+ try {
393
+ const html = parseSmallMarkdown(block.src)
394
+
395
+ if (html === undefined) return
396
+ const hash = checksum(block.src)
397
+ const result = { raw: block.raw, src: block.src, hash: hash ?? "", html: sanitizeMarkdown(html) }
398
+
399
+ if (key && hash) touchCachedMarkdown(key, result)
400
+
401
+ return result
402
+ } catch {
403
+ // Keep parser failures on the normal worker/escaped-text fallback path.
404
+ return
405
+ }
406
+ }
407
+
408
+ /** Joins a running parse of the same key and source; a hit costs no new promise beyond `Promise.resolve`. */
409
+ export function renderCachedMarkdown(
410
+ block: { raw: string; src: string },
411
+ key?: string,
412
+ signal?: AbortSignal,
413
+ ): Promise<MarkdownCacheEntry> {
414
+ if (signal?.aborted) return Promise.reject(markdownWorkerDisposed)
415
+
416
+ if (!key) return renderUnkeyed(block, signal)
417
+ const cached = getCachedMarkdown(key)
418
+
419
+ if (cached && (cached.src ?? cached.raw) === block.src) {
420
+ touchCachedMarkdown(key, cached)
421
+
422
+ return Promise.resolve(cached)
423
+ }
424
+
425
+ return new Promise<MarkdownCacheEntry>((resolve, reject) => {
426
+ const consumerId = ++consumers
427
+ const cancel = () => dispatch({ type: "consumer.aborted", consumerId })
428
+ signal?.addEventListener("abort", cancel, { once: true })
429
+ waiters.set(consumerId, { resolve, reject, signal, cancel })
430
+ dispatch({ type: "render.requested", consumerId, key, raw: block.raw, src: block.src })
431
+ })
432
+ }
433
+
434
+ function renderUnkeyed(block: { raw: string; src: string }, signal: AbortSignal | undefined) {
435
+ return new Promise<MarkdownCacheEntry>((resolve, reject) => {
436
+ const cancel = () => abortParseMarkdown(id)
437
+ signal?.addEventListener("abort", cancel, { once: true })
438
+
439
+ const id = startParseMarkdown(block.src, {
440
+ resolve: (html) => {
441
+ signal?.removeEventListener("abort", cancel)
442
+ const event = parsed(0, block.raw, block.src, html)
443
+
444
+ if (event.type === "parse.succeeded") return resolve(event.entry)
445
+ reject(event.error)
446
+ },
447
+ reject: (error) => {
448
+ signal?.removeEventListener("abort", cancel)
449
+ reject(error)
450
+ },
451
+ })
452
+ })
453
+ }
454
+
455
+ function dispatch(event: MarkdownCacheEvent) {
456
+ queue.push(event)
457
+
458
+ // A worker that rejects at once settles a parse while its start effect runs; the outer loop drains it next.
459
+ if (queue.length > 1) return
460
+
461
+ while (queue.length > 0) {
462
+ try {
463
+ const next = transitionMarkdownCache(state, queue[0]!)
464
+ state = next.state
465
+ next.effects.forEach(run)
466
+ } catch (error) {
467
+ console.error("Markdown cache transition failed", error)
468
+ } finally {
469
+ queue.shift()
470
+ }
471
+ }
472
+ }
473
+
474
+ function run(effect: MarkdownCacheEffect) {
475
+ try {
476
+ perform(effect)
477
+ } catch (error) {
478
+ console.error("Markdown cache effect failed", error)
479
+ }
480
+ }
481
+
482
+ function perform(effect: MarkdownCacheEffect) {
483
+ if (effect.type === "start-parse") {
484
+ let settled = false
485
+
486
+ const id = startParseMarkdown(effect.src, {
487
+ resolve: (html) => {
488
+ settled = true
489
+ workerIds.delete(effect.jobId)
490
+ dispatch(parsed(effect.jobId, effect.raw, effect.src, html))
491
+ },
492
+ reject: (error) => {
493
+ settled = true
494
+ workerIds.delete(effect.jobId)
495
+ dispatch({ type: "parse.failed", jobId: effect.jobId, error })
496
+ },
497
+ })
498
+
499
+ if (!settled) workerIds.set(effect.jobId, id)
500
+
501
+ return
502
+ }
503
+
504
+ if (effect.type === "abort-parse") {
505
+ const id = workerIds.get(effect.jobId)
506
+ workerIds.delete(effect.jobId)
507
+
508
+ if (id !== undefined) abortParseMarkdown(id)
509
+
510
+ return
511
+ }
512
+
513
+ if (effect.type === "store") return remember(effect.key, effect.entry)
514
+
515
+ const error =
516
+ effect.type === "reject-consumers" && effect.reason.kind === "error" ? effect.reason.error : markdownWorkerDisposed
517
+
518
+ effect.consumerIds.forEach((id) => {
519
+ const waiter = waiters.get(id)
520
+
521
+ if (!waiter) return
522
+ waiters.delete(id)
523
+ waiter.signal?.removeEventListener("abort", waiter.cancel)
524
+
525
+ if (effect.type === "resolve-consumers") return waiter.resolve(effect.entry)
526
+ waiter.reject(error)
527
+ })
528
+ }
529
+
530
+ // Sanitizing runs inside the worker's settle callback, where a throw would leave every consumer waiting.
531
+ function parsed(
532
+ jobId: number,
533
+ raw: string,
534
+ src: string,
535
+ html: MarkdownHTML,
536
+ ): Extract<MarkdownCacheEvent, { type: "parse.succeeded" | "parse.failed" }> {
537
+ try {
538
+ const hash = checksum(src)
539
+
540
+ return { type: "parse.succeeded", jobId, entry: { raw, src, hash: hash ?? "", html: sanitizeMarkdown(html) } }
541
+ } catch (error) {
542
+ return { type: "parse.failed", jobId, error: error instanceof Error ? error : new Error(String(error)) }
543
+ }
544
+ }
545
+
546
+ function remember(key: string, value: MarkdownCacheEntry) {
547
+ cache.delete(key)
548
+ cache.set(key, value)
549
+
550
+ if (cache.size <= max) return
551
+
552
+ const first = cache.keys().next().value
553
+
554
+ if (first === undefined) return
555
+ cache.delete(first)
556
+ }
@@ -0,0 +1,101 @@
1
+ import { sessionReferenceRange } from "./markdown-session-links"
2
+
3
+ // Chromium's default copy inlines computed styles, so text copied from a dark theme pastes as light text on the
4
+ // destination's white page. Copied HTML keeps only semantic markup and lets the destination style it.
5
+
6
+ const removedSelector = [
7
+ "button",
8
+ "input",
9
+ "textarea",
10
+ "select",
11
+ "script",
12
+ "style",
13
+ "template",
14
+ "svg",
15
+ '[aria-hidden="true"]',
16
+ ".sr-only",
17
+ '[data-slot="markdown-copy-button"]',
18
+ '[data-slot="markdown-code-toolbar"]',
19
+ ].join(", ")
20
+
21
+ // Ancestors that give a partial selection its meaning, such as a phrase inside bold text or a line inside a code block.
22
+ const semanticTags = new Set([
23
+ "A",
24
+ "B",
25
+ "BLOCKQUOTE",
26
+ "CODE",
27
+ "DEL",
28
+ "EM",
29
+ "H1",
30
+ "H2",
31
+ "H3",
32
+ "H4",
33
+ "H5",
34
+ "H6",
35
+ "I",
36
+ "KBD",
37
+ "LI",
38
+ "OL",
39
+ "P",
40
+ "PRE",
41
+ "S",
42
+ "STRONG",
43
+ "TABLE",
44
+ "TBODY",
45
+ "TD",
46
+ "TH",
47
+ "THEAD",
48
+ "TR",
49
+ "UL",
50
+ ])
51
+
52
+ const keptAttributes = new Set(["alt", "colspan", "rowspan", "start"])
53
+
54
+ const linkProtocols = new Set(["http:", "https:", "mailto:"])
55
+
56
+ const webProtocols = new Set(["http:", "https:"])
57
+
58
+ function sanitizeAttributes(element: Element) {
59
+ for (const attribute of Array.from(element.attributes)) {
60
+ if (keptAttributes.has(attribute.name)) continue
61
+
62
+ if (attribute.name === "href" && element.tagName === "A" && hasProtocol(attribute.value, linkProtocols)) continue
63
+
64
+ if (attribute.name === "src" && element.tagName === "IMG" && hasProtocol(attribute.value, webProtocols)) continue
65
+ element.removeAttribute(attribute.name)
66
+ }
67
+ }
68
+
69
+ function hasProtocol(value: string, protocols: Set<string>) {
70
+ return URL.canParse(value) && protocols.has(new URL(value).protocol)
71
+ }
72
+
73
+ export function markdownClipboardHtml(root: Element, range: Range) {
74
+ const selection = sessionReferenceRange(range)
75
+
76
+ const ancestor = selection.commonAncestorContainer
77
+ let content: Node = selection.cloneContents()
78
+
79
+ for (
80
+ let element = ancestor instanceof Element ? ancestor : ancestor.parentElement;
81
+ element && element !== root && root.contains(element);
82
+ element = element.parentElement
83
+ ) {
84
+ if (!semanticTags.has(element.tagName)) continue
85
+ const wrapper = element.cloneNode(false)
86
+ wrapper.appendChild(content)
87
+ content = wrapper
88
+ }
89
+
90
+ const container = document.createElement("div")
91
+ container.appendChild(content)
92
+ container.querySelectorAll<HTMLElement>("[data-session-reference]").forEach((reference) => {
93
+ const code = document.createElement("code")
94
+ code.textContent = reference.dataset.sessionReference ?? ""
95
+ reference.replaceWith(code)
96
+ })
97
+ container.querySelectorAll(removedSelector).forEach((element) => element.remove())
98
+ container.querySelectorAll("*").forEach(sanitizeAttributes)
99
+
100
+ return container.innerHTML
101
+ }