Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Morph the streaming answer DOM instead of replacing innerHTML each tick

rcourtman332fce866e8a
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 800e4d1c11..8632ca5d19 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -2314,6 +2314,20 @@ markdown) on every content delta. Positional keying is correct here precisely
because the list is append-only; a list that could reorder or key by identity
must not use `<Index>`.
+The streaming answer block itself renders by morphing the DOM, not by replacing
+`innerHTML` on every tick. `renderMarkdown` re-parses the full (DOMPurify-
+sanitized) answer on each paced reveal; assigning that to `innerHTML` rebuilds
+the entire prose subtree, so a multi-paragraph or list/table answer flickers and
+reflows every earlier line as it streams. `AssistantMarkdownBlock` instead feeds
+the sanitized HTML to `morphMarkdownInto`
+(`frontend-modern/src/components/AI/Chat/markdownMorph.ts`), which reconciles old
+and new trees in place: structurally-identical nodes are left untouched, same-tag
+nodes are morphed (recursing into children so a growing `<ol>`/`<table>` keeps
+its earlier `<li>`/`<tr>` and only the last one updates), and the growing tail
+block updates its text node rather than being rebuilt. The morph is a rendering
+optimization only — `renderMarkdown` remains the sole sanitization gate and the
+morph must never be fed unsanitized HTML.
+
Assistant slash-command availability is part of the command runtime contract,
not only visual polish. The OpenCode reference at fetched `origin/dev` commit
`c495635` filters prompt slash commands through the registered command catalog
diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
index 139f2688a2..555ebb9471 100644
--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx
+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
@@ -19,6 +19,7 @@ import RotateCcwIcon from 'lucide-solid/icons/rotate-ccw';
import SparklesIcon from 'lucide-solid/icons/sparkles';
import XIcon from 'lucide-solid/icons/x';
import { renderMarkdown } from '../aiChatUtils';
+import { morphMarkdownInto } from './markdownMorph';
import { PendingToolBlock, ToolCancellationBlock, ToolExecutionBlock } from './ToolExecutionBlock';
import { ApprovalCard } from './ApprovalCard';
import { QuestionCard } from './QuestionCard';
@@ -214,14 +215,17 @@ const AssistantMarkdownBlock: Component<{
() => props.paceKey,
);
- return (
- <div
- class={markdownClass}
- aria-live={props.streaming ? 'polite' : undefined}
- // eslint-disable-next-line solid/no-innerhtml
- innerHTML={renderMarkdown(visibleText())}
- />
- );
+ let container: HTMLDivElement | undefined;
+ // Morph the rendered markdown into the container instead of replacing
+ // innerHTML each tick. renderMarkdown already sanitizes (DOMPurify); the morph
+ // keeps the stable prefix of blocks so a streaming answer doesn't rebuild and
+ // reflow every earlier paragraph on every delta. See markdownMorph.ts.
+ createEffect(() => {
+ const html = renderMarkdown(visibleText());
+ if (container) morphMarkdownInto(container, html);
+ });
+
+ return <div ref={container} class={markdownClass} aria-live={props.streaming ? 'polite' : undefined} />;
};
/**
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.test.ts
new file mode 100644
index 0000000000..b251039718
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+import { morphMarkdownInto } from '../markdownMorph';
+
+const make = (html: string): HTMLDivElement => {
+ const el = document.createElement('div');
+ morphMarkdownInto(el, html);
+ return el;
+};
+
+describe('morphMarkdownInto', () => {
+ it('renders the html into the container', () => {
+ const el = make('<p>hello</p>');
+ expect(el.innerHTML).toBe('<p>hello</p>');
+ });
+
+ it('preserves the DOM identity of unchanged leading blocks as the answer grows', () => {
+ const el = make('<p>first</p><p>second</p>');
+ const firstBefore = el.children[0];
+ const secondBefore = el.children[1];
+
+ // A streaming tick: a third paragraph appears, the earlier two are unchanged.
+ morphMarkdownInto(el, '<p>first</p><p>second</p><p>third</p>');
+
+ expect(el.children).toHaveLength(3);
+ // Earlier blocks are the SAME nodes — not rebuilt — so they don't repaint.
+ expect(el.children[0]).toBe(firstBefore);
+ expect(el.children[1]).toBe(secondBefore);
+ expect(el.children[2].textContent).toBe('third');
+ });
+
+ it('morphs a growing block in place, keeping its node identity and the prefix', () => {
+ const el = make('<p>intro</p><p>par</p>');
+ const introBefore = el.children[0];
+ const tailBefore = el.children[1];
+
+ // The last block grows; the intro is untouched and the growing <p> keeps its
+ // node (only its text node updates), so nothing earlier repaints.
+ morphMarkdownInto(el, '<p>intro</p><p>paragraph</p>');
+
+ expect(el.children[0]).toBe(introBefore); // prefix kept
+ expect(el.children[1]).toBe(tailBefore); // same <p>, text updated in place
+ expect(el.children[1].textContent).toBe('paragraph');
+ });
+
+ it('morphs a changed earlier container in place and leaves following blocks alone', () => {
+ const el = make('<ul><li>a</li></ul><p>after</p>');
+ const listBefore = el.children[0];
+ const afterBefore = el.children[1];
+
+ // The list gained an item: the <ul> is morphed in place (new <li> appended),
+ // and the unchanged <p> after it keeps its node.
+ morphMarkdownInto(el, '<ul><li>a</li><li>b</li></ul><p>after</p>');
+
+ expect(el.children[0]).toBe(listBefore); // <ul> morphed in place
+ expect(el.querySelectorAll('li')).toHaveLength(2);
+ expect(el.children[1]).toBe(afterBefore); // following block untouched
+ });
+
+ it('empties the container when the html is empty', () => {
+ const el = make('<p>something</p>');
+ morphMarkdownInto(el, '');
+ expect(el.childNodes).toHaveLength(0);
+ });
+
+ it('preserves earlier list items as a streaming list grows (recurses into <ol>)', () => {
+ const el = make('<ol><li>one</li><li>two</li></ol>');
+ const olBefore = el.children[0];
+ const li1Before = olBefore.children[0];
+ const li2Before = olBefore.children[1];
+
+ // A new list item streams in. The <ol> is the same node, and the first two
+ // <li> are untouched — only the third is added.
+ morphMarkdownInto(el, '<ol><li>one</li><li>two</li><li>three</li></ol>');
+
+ expect(el.children[0]).toBe(olBefore); // same <ol>, morphed in place
+ expect(olBefore.children).toHaveLength(3);
+ expect(olBefore.children[0]).toBe(li1Before);
+ expect(olBefore.children[1]).toBe(li2Before);
+ expect(olBefore.children[2].textContent).toBe('three');
+ });
+
+ it('morphs the growing last list item in place, keeping earlier ones', () => {
+ const el = make('<ul><li>alpha</li><li>be</li></ul>');
+ const li1Before = el.querySelectorAll('li')[0];
+ const li2Before = el.querySelectorAll('li')[1];
+
+ morphMarkdownInto(el, '<ul><li>alpha</li><li>beta</li></ul>');
+
+ const lis = el.querySelectorAll('li');
+ expect(lis[0]).toBe(li1Before); // earlier item untouched
+ expect(lis[1]).toBe(li2Before); // same <li>, text updated in place
+ expect(lis[1].textContent).toBe('beta');
+ });
+
+ it('updates attributes in place without replacing the element', () => {
+ const el = make('<a href="http://a.example">link</a>');
+ const anchorBefore = el.children[0];
+
+ morphMarkdownInto(el, '<a href="http://b.example" rel="noopener">link</a>');
+
+ expect(el.children[0]).toBe(anchorBefore); // same node, attributes synced
+ expect(anchorBefore.getAttribute('href')).toBe('http://b.example');
+ expect(anchorBefore.getAttribute('rel')).toBe('noopener');
+ });
+
+ it('replaces a node when its tag changes (structure shifted)', () => {
+ const el = make('<p>maybe a heading</p>');
+ const pBefore = el.children[0];
+
+ morphMarkdownInto(el, '<h2>maybe a heading</h2>');
+
+ expect(el.children[0]).not.toBe(pBefore);
+ expect(el.children[0].tagName).toBe('H2');
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/markdownMorph.ts b/frontend-modern/src/components/AI/Chat/markdownMorph.ts
new file mode 100644
index 0000000000..ed514f0020
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/markdownMorph.ts
@@ -0,0 +1,83 @@
+// Apply already-sanitized markdown HTML to a live container by morphing the DOM
+// in place instead of replacing innerHTML wholesale.
+//
+// Streaming markdown grows append-mostly: on each paced render tick only the
+// trailing content actually changes, while every earlier paragraph, list item,
+// and table row stays identical. Setting `innerHTML` rebuilds the entire prose
+// subtree every tick, so the whole answer flickers and reflows as it streams.
+//
+// This walks old and new trees in parallel and only touches what changed:
+// identical nodes are left alone (no repaint), same-tag nodes are morphed in
+// place (recursing into their children, so a growing <ol>/<table> keeps its
+// earlier <li>/<tr> and only rebuilds the last one), and genuinely different
+// nodes are replaced. The result is that a streaming answer rebuilds the last
+// block instead of the whole document.
+//
+// SECURITY: `html` MUST already be sanitized (renderMarkdown runs DOMPurify).
+// This helper only parses that trusted-by-construction HTML into an inert
+// <template> and reconciles the resulting nodes into the DOM — it performs no
+// sanitization of its own and must not be fed raw model/user HTML.
+export function morphMarkdownInto(container: HTMLElement, html: string): void {
+ const template = document.createElement('template');
+ template.innerHTML = html;
+ morphChildren(container, Array.from(template.content.childNodes));
+}
+
+// Reconcile `parent`'s children against `newNodes` (a snapshot taken before any
+// mutation, since moving a node into the live tree removes it from the template).
+function morphChildren(parent: Node, newNodes: Node[]): void {
+ for (let i = 0; i < newNodes.length; i++) {
+ const newNode = newNodes[i];
+ const oldNode = parent.childNodes[i];
+
+ if (!oldNode) {
+ parent.appendChild(newNode);
+ continue;
+ }
+ if (oldNode.isEqualNode(newNode)) {
+ continue; // structurally identical — keep the existing node untouched
+ }
+ if (canMorphInPlace(oldNode, newNode)) {
+ morphNode(oldNode, newNode);
+ } else {
+ parent.replaceChild(newNode, oldNode);
+ }
+ }
+
+ // Drop any trailing old nodes the new render no longer has.
+ while (parent.childNodes.length > newNodes.length) {
+ parent.removeChild(parent.childNodes[parent.childNodes.length - 1]);
+ }
+}
+
+// A node can be updated in place (rather than wholesale replaced) when it is the
+// same kind of node — same element tag, or both character data (text/comment).
+function canMorphInPlace(oldNode: Node, newNode: Node): boolean {
+ if (oldNode.nodeType !== newNode.nodeType) return false;
+ if (oldNode.nodeType === Node.ELEMENT_NODE) {
+ return (oldNode as Element).tagName === (newNode as Element).tagName;
+ }
+ return oldNode.nodeType === Node.TEXT_NODE || oldNode.nodeType === Node.COMMENT_NODE;
+}
+
+function morphNode(oldNode: Node, newNode: Node): void {
+ if (oldNode.nodeType !== Node.ELEMENT_NODE) {
+ if (oldNode.nodeValue !== newNode.nodeValue) {
+ oldNode.nodeValue = newNode.nodeValue;
+ }
+ return;
+ }
+ syncAttributes(oldNode as Element, newNode as Element);
+ morphChildren(oldNode, Array.from(newNode.childNodes));
+}
+
+function syncAttributes(oldEl: Element, newEl: Element): void {
+ for (const attr of Array.from(oldEl.attributes)) {
+ if (!newEl.hasAttribute(attr.name)) oldEl.removeAttribute(attr.name);
+ }
+ for (const attr of Array.from(newEl.attributes)) {
+ if (oldEl.getAttribute(attr.name) !== attr.value) {
+ oldEl.setAttribute(attr.name, attr.value);
+ }
+ }
+}