From d762e659dc08d4dee4bb848cf237afc91bac050b Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 19 Oct 2026 00:15:42 -0700 Subject: [PATCH] fix(session-ui): dispose live markdown renderer when blocks settle --- .../component-tests/markdown.fixture.tsx | 4 +- .../component-tests/markdown.spec.ts | 106 ++++++++++++++-- .../src/components/markdown-solid.test.tsx | 87 ++++++++++++- .../src/components/markdown-solid.tsx | 118 ++++++++++++++---- .../session-ui/src/components/markdown.tsx | 28 ++++- 5 files changed, 303 insertions(+), 40 deletions(-) diff --git a/packages/session-ui/component-tests/markdown.fixture.tsx b/packages/session-ui/component-tests/markdown.fixture.tsx index 24f1adebba9..c13072f8930 100644 --- a/packages/session-ui/component-tests/markdown.fixture.tsx +++ b/packages/session-ui/component-tests/markdown.fixture.tsx @@ -1,12 +1,14 @@ import { createSignal, Show } from "solid-js" import { render } from "solid-js/web" import { DialogProvider } from "@opencode/ui/context/dialog" -import { Markdown } from "../src/components/markdown" +import { hasLiveMarkdownRenderer, Markdown } from "../src/components/markdown" import { preloadMarkdown } from "../src/components/markdown-cache" import { MarkdownProvider } from "../src/context/markdown" import { OpenCode } from "@opencode/client/promise" import { readLocalImage } from "../../app/src/runtime/server/image" +export { hasLiveMarkdownRenderer } + export { getCachedMarkdown, renderCachedMarkdown, diff --git a/packages/session-ui/component-tests/markdown.spec.ts b/packages/session-ui/component-tests/markdown.spec.ts index fc7a2c04d38..cea7c5511d7 100644 --- a/packages/session-ui/component-tests/markdown.spec.ts +++ b/packages/session-ui/component-tests/markdown.spec.ts @@ -492,25 +492,37 @@ story("renders the trailing chunk while the stream is paused", async ({ page }) await expect(harness.getByLabel("Streaming")).toBeChecked() }) -story("keeps live elements and selection when a stream completes and later changes", async ({ page }) => { +story("disposes live renderers and word spans on settle while preserving selection", async ({ page }) => { await page.evaluate(async (fixture) => { const { mountMarkdown } = await import(fixture) await mountMarkdown({ text: "Hello **world**", streaming: true }) }, fixture) const harness = page.getByTestId("markdown-fixture") const markdown = harness.locator('[data-component="markdown"]') - const paragraph = markdown.locator("p") + const block = markdown.locator("[data-markdown-block]").first() + const paragraph = markdown.locator("p").first() await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2) + await block.evaluate((element) => element.setAttribute("data-retained", "true")) await paragraph.evaluate((element) => element.setAttribute("data-retained", "true")) await harness.getByLabel("Markdown text").fill("Hello **world** again") await expect(markdown.locator("[data-markdown-word]")).toHaveCount(3) await expect(paragraph).toHaveAttribute("data-retained", "true") await expect(markdown.locator("[data-markdown-enter]")).not.toHaveCount(0) + expect( + await page.evaluate(async (fixture) => { + const { hasLiveMarkdownRenderer } = await import(fixture) + + const element = document.querySelector( + '[data-testid="markdown-fixture"] [data-markdown-block]', + )! + + return hasLiveMarkdownRenderer(element) + }, fixture), + ).toBe(true) await paragraph.evaluate((element) => { - const range = document.createRange() - range.selectNodeContents(element.querySelector("strong")!) - window.getSelection()!.removeAllRanges() - window.getSelection()!.addRange(range) + const [hello, world] = Array.from(element.querySelectorAll("[data-markdown-word]"), (span) => span.firstChild!) + // Select backward from inside "world" to inside "Hello", as a right-to-left drag would. + window.getSelection()!.setBaseAndExtent(world, 3, hello, 2) // Change the control without moving browser focus or selection. const input = document.querySelector('[data-testid="markdown-fixture"] input')! input.checked = false @@ -518,16 +530,94 @@ story("keeps live elements and selection when a stream completes and later chang }) await expect(harness.getByLabel("Streaming")).not.toBeChecked() await expect(markdown).toHaveAttribute("data-markdown-ready", "") + await expect(block).toHaveAttribute("data-retained", "true") await expect(paragraph).toHaveAttribute("data-retained", "true") - expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("world") + await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0) + expect( + await page.evaluate(async (fixture) => { + const { hasLiveMarkdownRenderer } = await import(fixture) + + const element = document.querySelector( + '[data-testid="markdown-fixture"] [data-markdown-block]', + )! + + return hasLiveMarkdownRenderer(element) + }, fixture), + ).toBe(false) + expect( + await paragraph.evaluate((element) => { + const selection = window.getSelection()! + + return { + text: selection.toString(), + backward: selection.getRangeAt(0).endContainer === selection.anchorNode, + // In-app Find matches within a single text node, so each run of words is one node again. + nodes: Array.from(element.childNodes, (node) => node.textContent), + } + }), + ).toEqual({ text: "llo wor", backward: true, nodes: ["Hello ", "world", " again"] }) await harness.getByLabel("Markdown text").fill("Changed **content**") await expect(paragraph).toHaveText("Changed content") - await expect(paragraph).toHaveAttribute("data-retained", "true") + await expect(block).toHaveAttribute("data-retained", "true") await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0) await harness.getByRole("button", { name: "Toggle Markdown" }).click() await expect(markdown).toHaveCount(0) }) +story("settles a live block in place when its final update also changes its content", async ({ page }) => { + await page.evaluate(async (fixture) => { + const { mountMarkdown } = await import(fixture) + await mountMarkdown({ text: "Hello **world**", streaming: true }) + }, fixture) + const harness = page.getByTestId("markdown-fixture") + const markdown = harness.locator('[data-component="markdown"]') + const paragraph = markdown.locator("p").first() + await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2) + await paragraph.evaluate((element) => element.setAttribute("data-retained", "true")) + await page.evaluate(() => { + const textarea = document.querySelector('[data-testid="markdown-fixture"] textarea')! + const input = document.querySelector('[data-testid="markdown-fixture"] input')! + textarea.value = "Hello **world** again" + textarea.dispatchEvent(new Event("input", { bubbles: true })) + input.checked = false + input.dispatchEvent(new Event("change", { bubbles: true })) + }) + await expect(markdown).toHaveAttribute("data-markdown-ready", "") + await expect(paragraph).toHaveText("Hello world again") + await expect(paragraph).toHaveAttribute("data-retained", "true") + await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0) + expect( + await page.evaluate(async (fixture) => { + const { hasLiveMarkdownRenderer } = await import(fixture) + + return hasLiveMarkdownRenderer( + document.querySelector('[data-testid="markdown-fixture"] [data-markdown-block]')!, + ) + }, fixture), + ).toBe(false) +}) + +story("settles cache-keyed live blocks in place under their settled key", async ({ page }) => { + await page.evaluate(async (fixture) => { + const { mountMarkdown } = await import(fixture) + await mountMarkdown({ text: "Hello **world**", streaming: true, cached: true }) + }, fixture) + const harness = page.getByTestId("markdown-fixture") + const markdown = harness.locator('[data-component="markdown"]') + const paragraph = markdown.locator("p").first() + await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2) + await paragraph.evaluate((element) => element.setAttribute("data-retained", "true")) + await harness.getByLabel("Streaming").uncheck() + await expect(markdown).toHaveAttribute("data-markdown-ready", "") + await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0) + expect( + await markdown.evaluate((element) => ({ + key: element.querySelector("[data-markdown-block]")?.getAttribute("data-markdown-key"), + retained: element.querySelector("p")?.getAttribute("data-retained"), + })), + ).toEqual({ key: expect.stringMatching(/:markdown-test:0:full$/), retained: "true" }) +}) + story("replaces completed DOM before live rendering and retains streamed code copy actions", async ({ page }) => { await page.evaluate(async (fixture) => { const { mountMarkdown } = await import(fixture) diff --git a/packages/session-ui/src/components/markdown-solid.test.tsx b/packages/session-ui/src/components/markdown-solid.test.tsx index 0711b79e7a8..35c01182b14 100644 --- a/packages/session-ui/src/components/markdown-solid.test.tsx +++ b/packages/session-ui/src/components/markdown-solid.test.tsx @@ -1,6 +1,6 @@ import { GlobalRegistrator } from "@happy-dom/global-registrator" import { afterAll, beforeAll, expect, test } from "bun:test" -import { parseMarkdownNodes } from "./markdown-solid" +import { parseMarkdownNodes, settleMarkdownWords, unwrapMarkdownWords } from "./markdown-solid" beforeAll(() => GlobalRegistrator.register()) @@ -87,3 +87,88 @@ test("marks words for animation only when requested", () => { animate: true, }) }) + +test("unwraps word spans in place while retaining elements and selection", () => { + const container = document.createElement("div") + container.innerHTML = + '

Earlier block

Hello world again

' + document.body.appendChild(container) + + const settledText = container.querySelector("#settled p")!.firstChild! + const block = container.querySelector("#live")! + const paragraph = block.querySelector("p")! + const strong = block.querySelector("strong")! + const wordSpan = strong.querySelector("[data-markdown-word]")! + const range = document.createRange() + range.selectNodeContents(wordSpan) + const selection = window.getSelection()! + selection.removeAllRanges() + selection.addRange(range) + expect(selection.toString()).toBe("world") + + unwrapMarkdownWords(block) + + expect(block.querySelector("p")).toBe(paragraph) + expect(block.querySelector("strong")).toBe(strong) + expect(block.querySelectorAll("[data-markdown-word]").length).toBe(0) + expect(block.querySelectorAll("[data-markdown-enter]").length).toBe(0) + expect(window.getSelection()?.toString()).toBe("world") + + // Cross-block selection anchored in Text nodes also survives unwrapping. + block.innerHTML = + '

Hello world

' + const crossRange = document.createRange() + crossRange.setStart(settledText, 8) + crossRange.setEnd(block.querySelector("strong [data-markdown-word]")!.firstChild!, 3) + selection.removeAllRanges() + selection.addRange(crossRange) + const expectedCross = selection.toString() + unwrapMarkdownWords(block) + expect(window.getSelection()?.toString()).toBe(expectedCross) + + // A backward selection keeps its anchor after the focus. (happy-dom doesn't move ranges through + // normalize(), so the words sit in separate elements here; the Chromium spec covers merged text.) + block.innerHTML = + '

Hello world

' + const [hello, world] = Array.from(block.querySelectorAll("[data-markdown-word]"), (span) => span.firstChild!) + selection.setBaseAndExtent(world, 3, hello, 1) + unwrapMarkdownWords(block) + expect(selection.toString()).toBe("ello wor") + expect([selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset]).toEqual([ + world, + 3, + hello, + 1, + ]) + + // Without an active selection inside the block, unwrapped text nodes are normalized. + selection.removeAllRanges() + block.innerHTML = '

Hello world

' + unwrapMarkdownWords(block) + expect(block.querySelector("p")?.childNodes.length).toBe(1) + container.remove() +}) + +test("waits for running enter animations before unwrapping word spans", async () => { + const block = document.createElement("div") + block.dataset.markdownHash = "1" + block.dataset.markdownMode = "full" + block.innerHTML = '

Hello

' + document.body.appendChild(block) + + const { promise: finished, resolve: finish } = Promise.withResolvers() + const enter = block.querySelector("[data-markdown-enter]")! + + Object.defineProperty(enter, "getAnimations", { + value: () => [{ playState: "running", finished }], + }) + + settleMarkdownWords(block) + expect(block.querySelectorAll("[data-markdown-word]").length).toBe(1) + + finish() + await finished + await Promise.resolve() + expect(block.querySelectorAll("[data-markdown-word]").length).toBe(0) + block.remove() +}) diff --git a/packages/session-ui/src/components/markdown-solid.tsx b/packages/session-ui/src/components/markdown-solid.tsx index a11b2e29773..73ad5f42660 100644 --- a/packages/session-ui/src/components/markdown-solid.tsx +++ b/packages/session-ui/src/components/markdown-solid.tsx @@ -1,6 +1,6 @@ -import { For, onMount } from "solid-js" +import { createRoot, For, onMount } from "solid-js" import { createStore, reconcile } from "solid-js/store" -import { Dynamic, render } from "solid-js/web" +import { Dynamic, insert } from "solid-js/web" type MarkdownNode = | { @@ -18,10 +18,14 @@ export function createMarkdownRenderer(root: HTMLDivElement, html: string, words const [nodes, setNodes] = createStore(parseMarkdownNodes(html, words)) let ready = false - const dispose = render( - () => {(node) => ready} />}, - root, - ) + const dispose = createRoot((dispose) => { + insert( + root, + {(node) => ready} />}, + ) + + return dispose + }) ready = true @@ -79,30 +83,92 @@ function parseNode(node: Node, key: string, words: boolean, animate: boolean, in if (/^\s+$/.test(text)) return [{ key: `${key}:${index}`, type: "text", text }] - return [{ key: `${key}:${index}`, type: "word", text, ...(animate ? { animate: true as const } : {}) }] + const item: MarkdownNode = { key: `${key}:${index}`, type: "word", text } + + if (animate) item.animate = true + + return [item] }) } if (!(node instanceof Element)) return [] - return [ - { - key, - type: "element", - tag: node.tagName.toLowerCase(), - attributes: Object.fromEntries(Array.from(node.attributes).map((attribute) => [attribute.name, attribute.value])), - children: Array.from(node.childNodes).flatMap((child, index) => - parseNode( - child, - `${key}.${index}`, - words, - animate, - inlineCode || (node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"), - ), + const element: Extract = { + key, + type: "element", + tag: node.tagName.toLowerCase(), + attributes: Object.fromEntries(Array.from(node.attributes).map((attribute) => [attribute.name, attribute.value])), + children: Array.from(node.childNodes).flatMap((child, index) => + parseNode( + child, + `${key}.${index}`, + words, + animate, + inlineCode || (node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"), ), - ...(words && animate && node.tagName === "CODE" && node.parentElement?.tagName !== "PRE" - ? { animate: true as const } - : {}), - }, - ] + ), + } + + if (words && animate && node.tagName === "CODE" && node.parentElement?.tagName !== "PRE") { + element.animate = true + } + + return [element] +} + +function resolveBoundary(node: Node, offset: number): [Node, number] { + if (node instanceof HTMLElement && node.hasAttribute("data-markdown-word") && node.firstChild instanceof Text) { + return [node.firstChild, offset === 0 ? 0 : node.firstChild.data.length] + } + + return [node, offset] +} + +export function unwrapMarkdownWords(root: HTMLElement) { + for (const node of root.querySelectorAll("[data-markdown-enter]")) { + node.removeAttribute("data-markdown-enter") + } + + const spans = root.querySelectorAll("[data-markdown-word]") + + if (spans.length === 0) return + const selection = window.getSelection?.() + + const inside = + !!selection?.anchorNode && + !!selection.focusNode && + !selection.isCollapsed && + (root.contains(selection.anchorNode) || root.contains(selection.focusNode)) + + const anchor = inside ? resolveBoundary(selection.anchorNode, selection.anchorOffset) : undefined + const focus = inside ? resolveBoundary(selection.focusNode, selection.focusOffset) : undefined + + for (const span of spans) { + span.replaceWith(...span.childNodes) + } + + // Restoring base and extent keeps backward and in-progress drags anchored where they started. + if (selection && anchor && focus) selection.setBaseAndExtent(anchor[0], anchor[1], focus[0], focus[1]) + + // Live ranges, including the selection, follow merged text nodes through normalize(). + root.normalize() +} + +export function settleMarkdownWords(root: HTMLElement) { + const hash = root.dataset.markdownHash + + const running = Array.from(root.querySelectorAll("[data-markdown-enter]")).flatMap((node) => + (node.getAnimations?.() ?? []).filter((animation) => animation.playState === "running"), + ) + + if (running.length === 0) { + unwrapMarkdownWords(root) + + return + } + + void Promise.allSettled(running.map((animation) => animation.finished)).then(() => { + if (!root.isConnected || root.dataset.markdownMode === "live" || root.dataset.markdownHash !== hash) return + unwrapMarkdownWords(root) + }) } diff --git a/packages/session-ui/src/components/markdown.tsx b/packages/session-ui/src/components/markdown.tsx index befb96daa01..1d1f102fb30 100644 --- a/packages/session-ui/src/components/markdown.tsx +++ b/packages/session-ui/src/components/markdown.tsx @@ -36,7 +36,7 @@ import { } from "./markdown-cache" import { inlineCodeKind } from "./markdown-inline-code-kind" import { renderMermaidSvg } from "./markdown-mermaid" -import { createMarkdownRenderer } from "./markdown-solid" +import { createMarkdownRenderer, settleMarkdownWords } from "./markdown-solid" import { useMarkdown, type OpenMarkdownLocalFile, @@ -74,6 +74,10 @@ const renderedMarkdown = new WeakMap< { renderer: ReturnType; raw: string } >() +export function hasLiveMarkdownRenderer(block: HTMLDivElement) { + return renderedMarkdown.has(block) +} + function escape(text: string) { return text .replace(/&/g, "&") @@ -889,14 +893,20 @@ function updateBlock( } const existing = - current instanceof HTMLDivElement && current.dataset.markdownKey === block.key && !renderedCodeTokens.has(current) + current instanceof HTMLDivElement && + !renderedCodeTokens.has(current) && + // Block keys include the mode, so a live block that settles keeps its element under its new key. + (current.dataset.markdownKey === block.key || (renderedMarkdown.has(current) && block.mode !== "live")) ? current : undefined if (existing?.dataset.markdownHash === block.hash) { // A block that finishes streaming keeps its DOM and the user's selection; only its file paths get checked now. if (existing.dataset.markdownMode === "live" && block.mode !== "live") { + existing.dataset.markdownKey = block.key existing.dataset.markdownMode = block.mode + disposeRenderedMarkdown(existing) + settleMarkdownWords(existing) markInlineCode(existing, existing, false, localFileExists) } @@ -909,8 +919,8 @@ function updateBlock( next.dataset.markdownHash = block.hash next.dataset.markdownMode = block.mode next.style.display = "contents" + const rendered = renderedMarkdown.get(next) - // Keep live renderers in control of their DOM, including after completion. const source = rendered || block.mode === "live" ? document.createElement("div") : next if (source === next) disposeCopyButtons(next) @@ -922,9 +932,19 @@ function updateBlock( markExternalLinkFavicons(source) if (rendered) { - rendered.renderer.update(source.innerHTML, block.mode === "live", rendered.raw !== block.raw) + rendered.renderer.update(source.innerHTML, true, rendered.raw !== block.raw) rendered.raw = block.raw + if (block.mode === "live") return + + // A block that settles with new content gets one last live patch, which Solid applies after this + // effect, then settles in place. + queueMicrotask(() => { + if (renderedMarkdown.get(next) !== rendered || next.dataset.markdownMode === "live") return + disposeRenderedMarkdown(next) + settleMarkdownWords(next) + }) + return }