Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Perf: rooms draw one bubble per delta; streamed lists and tables parse only their last piece (#6562)
Milind Soni585e6fcbac01
diff --git a/src/components/ChatMarkdown.renderers.test.ts b/src/components/ChatMarkdown.renderers.test.tsindex 38129a31f1..a03e28e6fb 100644--- a/src/components/ChatMarkdown.renderers.test.ts+++ b/src/components/ChatMarkdown.renderers.test.ts@@ -89,12 +89,12 @@ describe("ChatMarkdown normalization", () => {});it("remembers a bounded number of messages, newest kept", () => {- const oldest = "The oldest message.";+ const oldest = "The oldest message, $5.";markdownProps(before, oldest);- for (let i = 0; i < 1000; i++) markdownProps(before, `Message ${i}.`);+ for (let i = 0; i < 1000; i++) markdownProps(before, `Message ${i}, $5.`);vi.mocked(fromMarkdown).mockClear();- markdownProps(before, "Message 999.");+ markdownProps(before, "Message 999, $5.");expect(fromMarkdown).not.toHaveBeenCalled();markdownProps(before, oldest);expect(fromMarkdown).toHaveBeenCalledOnce();diff --git a/src/components/ChatMarkdown.stream-identity.test.ts b/src/components/ChatMarkdown.stream-identity.test.tsnew file mode 100644index 0000000000..6d65bafcdb--- /dev/null+++ b/src/components/ChatMarkdown.stream-identity.test.ts@@ -0,0 +1,225 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { setLocale } from "../lib/i18n";+import { StreamingReplyContext } from "@/state/live-reply";++const mode = vi.hoisted(() => ({ whole: false, pieces: 0 }));+vi.mock("@/lib/markdown-stream-blocks", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/lib/markdown-stream-blocks")>();+ return {+ ...actual,+ splitMarkdownBlocks: (text: string) => (mode.whole ? null : actual.splitMarkdownBlocks(text)),+ splitStreamPieces: (block: string) => {+ const pieces = mode.whole ? null : actual.splitStreamPieces(block);+ if (pieces) mode.pieces++;+ return pieces;+ },+ };+});+vi.mock("@/lib/interface-mode", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/lib/interface-mode")>(),+ useAdvancedMode: () => true,+ readAdvancedMode: () => true,+}));++const { ChatMarkdown, ensureChatKatex, normalizeMathDelimiters } = await import("./ChatMarkdown");+const { mayHoldMath } = await import("@/lib/markdown-stream-blocks");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const CORPUS: Record<string, string> = {+ "tight bullets": "- one\n- two with `code`\n- three **bold**\n- four\n\nAfter the list.",+ "tight ordered": "1. one\n2. two\n3. three\n10. ten\n11. eleven\n",+ "ordered from above one": "7. seven\n8. eight\n9. nine\n\nDone",+ "ordered with parens": "1) one\n2) two\n3) three",+ "loose bullets": "- one\n\n- two\n\n- three\n\nAfter",+ "loose ordered with bodies": "1. **First**\n\n The body of the first.\n\n2. **Second**\n\n The body of the second.\n\n3. **Third**\n\nEnd.",+ "tight then loose": "- one\n- two\n- three\n\n- four\n- five",+ "blank inside one item only": "- one\n\n more of one\n- two\n- three\n",+ "blank inside a nested list": "- one\n - a\n\n - b\n- two\n- three\n",+ "nested lists": "- one\n - a\n - b\n - deep\n- two\n 1. x\n 2. y\n- three",+ "ordered with nested bullets": "1. Title\n - sub a\n - sub b\n2. Next\n - sub c\n3. Last\n",+ "nested under ten": "9. nine\n - in nine\n10. ten\n - in ten\n - not in ten\n11. eleven",+ "under-indented child": "1. one\n - not nested\n2. two",+ "list with a fence": "- one\n ```js\n const a = 1;\n\n const b = 2;\n ```\n- two\n- three",+ "item opening with a fence": "- ```sh\n ls -la\n ```\n- two\n- ```\n wide\n ```\n- three",+ "fence broken by the next item": "- one\n ```\n code\n- two\n- three",+ "loose list with a fence": "1. Run it:\n\n ```sh\n pnpm test\n ```\n\n2. Read it.\n\n3. Ship it.",+ "list with a blockquote": "- one\n > quoted\n > more\n- two\n> outside\n- three",+ "list with indented code": "- one\n\n code\n\n- two\n- code first\n- three",+ "indented code before what cannot interrupt": " code\n\n2. item\n\n code\n\n-\n\n code\n\n> -\n\n code\n\n<br>\n\n code\n\n| a | b |\n|---|---|\n",+ "indented code inside a numbered list": "1. a\n\n code\n\n2. b\n\n3. c\n\n code\n\n4.\n5. e",+ "indented code inside bullets": "- a\n\n code\n\n-\n- c\n\n code\n\n- - \n- 2. x\n",+ "indented code inside a tight list": "- a\n code\n-\n- c\n1. x\n\n1. a\n code\n2. b\n3.\n",+ "task list": "- [ ] open\n- [x] done\n- [ ] another `one`\n- plain\n",+ "loose task list": "- [ ] open\n\n- [x] done\n\n- [ ] more",+ "marker changes": "- one\n- two\n* three\n* four\n+ five\n\n1. a\n2. b\n1) c\n2) d",+ "thematic breaks in a list": "- one\n- two\n- - -\n- three\n* * *\n* four\n---\n- five",+ "setext under an item": "- one\n---\n- two\n\nText\n-\n- three",+ "lazy continuation": "- one\nlazy line\n- two\n kept\nlazy again\n- three",+ "lazy digits": "1. one\n2. two\n12\n3. three\n4",+ "empty items": "- one\n-\n- three\n-\n filled later\n- \n- six\n-\n\n not in the item",+ "empty first item": "-\n- two\n- three\n\n1.\n2. two",+ "list after a paragraph": "Here are the steps:\n- one\n- two\n- three\n\nAnd numbered:\n1. a\n2. b",+ "numbers that do not start a list": "The year was\n2. not a list\n3. still text\n\nIt was\n1. a list\n2. indeed",+ "list after a heading": "## Steps\n- one\n- two\n\n### More\n1. a\n2. b\n",+ "list after other blocks": "> quote\n- one\n- two\n\n<div>\n- html\n- still\n\n| a | b |\n- x | y\n- z\n",+ "paragraph after a tight list": "- one\n- two\nnot an item\n\n- three\n kept\n\n kept too\n\n text\n",+ "list with pipes and at signs": "- run `a | b` for @sam\n- then `c || d`\n- x | y\n- | z |\n",+ "list with links and images": "- [docs](https://example.com) and \n- <https://example.com>\n- plain https://example.com/x\n",+ "list with right-to-left text": "- 123\n- 456\n- שלום עולם\n- more\n\n1. 1\n2. مرحبا\n",+ "list with html": "- one\n <!-- note\n\n still note -->\n- two\n- <b>three</b>\n",+ "long tight list": Array.from({ length: 12 }, (_, i) => `- item ${i} with **bold** and \`code\``).join("\n"),+ "table": "| a | b | c |\n|---|---|---|\n| 1 | 2 | 3 |\n| 4 | 5 | 6 |\n\nAfter",+ "table with alignment": "| left | mid | right |\n|:-----|:---:|------:|\n| 1 | 2 | 3 |\n| 4 | 5 | 6 |\n",+ "table with code and pipes": "| cmd | what |\n| --- | --- |\n| `a \\| b` | pipe |\n| `c` | x \\| y |\n| `d | e` | split |\n| **f** | [g](https://example.com) |\n",+ "table with ragged rows": "| a | b |\n|---|---|\n| 1 |\n| 1 | 2 | 3 |\n|\n| | |\n|| x |\n",+ "table header first": "| name | value |\n",+ "table with a growing delimiter": "| a | b | c |\n|---|---|\n| 1 | 2 |\n\n| a | b |\n|---|---|---|\n| 1 | 2 |\n",+ "table without outer pipes": "a | b\n--|--\n1 | 2\n3 | 4\n",+ "table rows without a leading pipe": "| a | b |\n|---|---|\n| 1 | 2 |\n3 | 4\nplain\n| 5 | 6 |\n",+ "table ended by other blocks": "| a | b |\n|---|---|\n| 1 | 2 |\n> quote\n\n| a | b |\n|---|---|\n| 1 | 2 |\n# Heading\n\n| a | b |\n|---|---|\n| 1 | 2 |\n```\ncode\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n- item\n",+ "table of one column": "| a |\n|---|\n| 1 |\n| x | y |---|---| z | w |\n| 2 |\n",+ "table needing repair": "Intro\n| a | b |\n|---|\n| 1 | 2 |\n\n| a | b | |---|---| | 1 | 2 | | 3 | 4 |\n",+ "table with right-to-left text": "| 1 | 2 |\n|---|---|\n| 3 | 4 |\n| שלום | 5 |\n",+ "table with breaks": "| a | b |\n|---|---|\n| one<br>two | x |\n| three | y<br/>z |\n",+ "table after an image": "\n\n| a | b |\n|---|\n| 1 | 2 |\n\n- one\n- two\n",+ "html block": "<details>\n<summary>More</summary>\n\nHidden **text**.\n\n</details>\n\nAfter\n\n<div>\n- not a list\n\n- a list\n",+ "html that runs past blank lines": "<pre>\nline\n\n- not a list\n</pre>\n\nAfter\n\n<!-- a\n\ncomment -->\n\nText\n\n<script>\n\nlet a;\n\n</script> tail\n\nEnd",+ "html left open": "Intro\n\n<!-- open\n\n- one\n\n# two\n\nthree",+ "html inside a paragraph": "Text\n<style>\n\np { color: red }\n\n</style>\n\nAfter <b>bold</b> text\n\n<?php\n\necho 1;\n\n?>\n\n<!DOCTYPE html>\n\nEnd",+ "display math": "Intro\n\n$$\nx^2 + y^2\n\n= z^2\n$$\n\nBetween\n\n$$a + b$$\n\nMore\n\n\\[\nc\n\\]\n\n\\[ d \\]\n\nEnd",+ "display math at the top": "$$x^2$$\n\nOne paragraph.\n\nAnother paragraph.\n\n- one\n- two\n",+ "display math left open": "Intro\n\n$$\nx\n\ny\n\n- z\n",+ "display math inside text": "The value $$x$$ is here.\n\nAnd more.\n\nA lone $$ sign.\n\nMore still.\n\n$$ closes it",+ "display math across paragraphs": "Start \\[ a\n\nb \\] end\n\nText $$ one\n\ntwo $$ three\n\nfour",+ "display math with a tag": "$$ meta\nx\n\ny\n\nz\n",+ "display math in a list": "1. First:\n $$\n x\n $$\n2. Second: $$y$$\n\nAfter\n\n3. Third",+ "inline math": "With \\(a + b\\) and $c$ inline.\n\nPrices: $5 and $10.\n\nOpen \\( here\n\nclosed \\) there\n\nEnd",+ "math and code": "Run `echo $$` now.\n\nThen `\\[` too.\n\n```sh\necho $$\n```\n\n$$\nx `y`\n$$\n\nEnd\n\n$$\n\n z $$\n\nEnd",+ "list with dollars": "- costs $5\n- and $6 here$\n- b y$ and $z w$\n",+ "footnotes": "A claim.[^1]\n\n- one\n- two\n\n[^1]: The source.\n\nAfter",+ "reference links": "See [the docs][1] and [more].\n\n- [x][1]\n- two\n\n[1]: https://example.com\n[more]: https://example.com/more\n",+ "container marks": "::: note\n\nbody\n\n:::\n\nAfter",+ "code fences": "Intro\n\n```js\nconst a = 1;\n\n- not a list\n```\n\n~~~\n| a | b |\n|---|---|\n~~~\n\n indented\n\n more\n\nEnd",+ "blank-looking lines": "one\n\u00a0\ntwo\n \t \nthree\n\n- a\n\u00a0\n- b\n",+ "mixed": "# Report\n\nSummary with **bold**, `code` and a [link](https://example.com).\n\n## Steps\n\n1. Install:\n\n ```sh\n pnpm install\n ```\n\n2. Run it.\n3. Done.\n\n| step | time |\n|------|-----:|\n| one | 1 s |\n| two | 2 s |\n\n> Note: this is quoted.\n\n- [x] shipped\n- [ ] verified\n\n<details>\n\nMore.\n\n</details>\n\n$$\nE = mc^2\n$$\n\nThe end.",+ "html directly above a list": "<div>\n- a\n- b\n\n<details>\n<summary>S</summary>\n- a\n- b\n</details>\n\n<br>\n- one\n\n</pre>\n1) p\n",+ "pipe line above a list": "a | b\n- | -\n- c\n",+ "item text opening with a marker": "Text\n- - \n\nText\n- 2. x\n\nPlain text here.\n1. **Title**\n2. next\n",+ "html named inline and in a fence": "Use `<script>` and `<!-- -->` in a line.\n\nNext\n\n- a\n- b\n\n```html\n<!doctype html>\n<script>\nlet a = 1;\n\nlet b = 2;\n</script>\n```\n\nAfter\n",+ "quoted comment": "> quote\n> <!-- note\n\nstill -->\n\nEnd",+ "right-to-left first letter in a later row": "| # | 1 |\n| - | - |\n| 2 | \u05e9\u05dc\u05d5\u05dd |\n",+ "long html opener inside a short html block": "</pre>\n<!X\n\n```\n+ plus\n</pre>\n<!X\n- [x] done\n</pre>\n\n|",+ "first item indented by one": " - a\n- b\n- c\n\n-\tx\n- b\n",+};++// A fence the text never closes keeps its actions hidden until the reply is finished.+const OPEN_AT_THE_END = ["item opening with a fence", "fence broken by the next item", "long html opener inside a short html block"];++const FRAGMENTS = [+ "- one", "- two `code`", "- three **bold**", "* star", "+ plus", "-", "- ", "- - -", "---", "***", "- [ ] task", "- [x] done",+ "1. first", "2. second", "3. third", "10. tenth", "1) paren", "2) paren", "1.", "7", "12",+ " - nested", "> -", "> 2. two", "- 2. x", "- - ", " more of it", " deeper text", " four in", " six in", " one in", " > quoted inside", " ```", " code", " ```",+ "| a | b |", "|---|---|", "|:--|--:|", "| 1 | 2 |", "| `x \\| y` | z |", "| 3 |", "|", "a | b", "--|--", "| a | b | c |", "|---|---|---|", "|---|",+ "Plain text here.", "Another line", "# Heading", "## Two", "> quote", "> - quoted item", "```", "```js", "~~~", "const a = 1;",+ "<div>", "</div>", "<details>", "<!-- note", "end -->", "<pre>", "</pre>", "<script>", "</script>", "<b>bold</b> text", "<?x", "?>", "<!X", "<br>",+ "$$", "$$x^2$$", "\\[", "\\]", "\\[ y \\]", "a $$ b", "\\(c\\) and $d$", "\\( open", "close \\)", "$5 and $6", "`echo $$`", "$$ meta", " $$",+ "1. **Title**", " body text", " - sub", " | a | b |", "> | a | b |", "| a | b | ", "\\| a", "text\\", "[x] not a task", "- [link](https://example.com)",+ "@sam and #thread", "https://example.com/path", "", "שלום", "123", "\u00a0", "=== ", "===", "text | with | pipes",+];++function random(seed: number): () => number {+ let state = seed;+ return () => {+ state = (state + 0x6d2b79f5) | 0;+ let t = Math.imul(state ^ (state >>> 15), 1 | state);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++function randomDocument(next: () => number): string {+ // Most documents draw from a few fragments, so lists and tables grow long enough to be cut.+ const pool = Array.from({ length: 2 + Math.floor(next() * 7) }, () => FRAGMENTS[Math.floor(next() * FRAGMENTS.length)]!);+ let text = "";+ for (let lines = 3 + Math.floor(next() * 14); lines > 0; lines--) {+ const from = next() < 0.75 ? pool : FRAGMENTS;+ text += from[Math.floor(next() * from.length)]! + (next() < 0.3 ? "\n\n" : "\n");+ }+ return next() < 0.5 ? text : text.trimEnd();+}++describe("a streamed reply drawn block by block and piece by piece", () => {+ let hosts: HTMLDivElement[];+ let streamed: Root;+ let whole: Root;+ const draw = (root: Root, text: string, streaming: boolean, asWhole: boolean) => {+ mode.whole = asWhole;+ act(() => root.render(createElement(StreamingReplyContext, { value: streaming }, createElement(ChatMarkdown, { text }))));+ mode.whole = false;+ };++ beforeAll(async () => {+ setLocale("en");+ await ensureChatKatex();+ hosts = [document.createElement("div"), document.createElement("div")];+ document.body.append(...hosts);+ streamed = createRoot(hosts[0]!);+ whole = createRoot(hosts[1]!);+ });+ afterAll(() => {+ act(() => { streamed.unmount(); whole.unmount(); });+ hosts.forEach((host) => host.remove());+ });++ /** The cut where drawing `text` in parts first differs from drawing it whole, or null. */+ const firstDifference = (text: string, cuts: number[]): string | null => {+ for (const cut of cuts) {+ const prefix = text.slice(0, cut);+ draw(streamed, prefix, true, false);+ draw(whole, prefix, true, true);+ const [parts, all] = [hosts[0]!.innerHTML, hosts[1]!.innerHTML];+ if (parts === all) continue;+ let at = 0;+ while (parts[at] === all[at]) at++;+ return `${JSON.stringify(prefix)} at ${at}\n parts: ${JSON.stringify(parts.slice(Math.max(0, at - 60), at + 120))}\n whole: ${JSON.stringify(all.slice(Math.max(0, at - 60), at + 120))}`;+ }+ return null;+ };++ // The cache is never cleared: a piece kept while drawing one document must also be right in every other.+ it.each(Object.entries(CORPUS))("%s: every prefix draws as the whole text does", (name, text) => {+ expect(firstDifference(text, Array.from({ length: text.length }, (_, index) => index + 1))).toBeNull();+ if (OPEN_AT_THE_END.includes(name)) return;+ draw(whole, text, false, true);+ expect(hosts[0]!.innerHTML, "the finished reply").toBe(hosts[1]!.innerHTML);+ });++ it("random documents: every sampled prefix draws as the whole text does", () => {+ const next = random(20261118);+ for (let index = 0; index < 150; index++) {+ const text = randomDocument(next);+ const cuts: number[] = [];+ for (let cut = 1; cut < text.length; cut += 1 + Math.floor(next() * 6)) cuts.push(cut);+ for (let at = text.indexOf("\n"); at >= 0; at = text.indexOf("\n", at + 1)) cuts.push(at, at + 1, at + 2);+ cuts.push(text.length);+ const ordered = [...new Set(cuts)].filter((cut) => cut >= 1 && cut <= text.length).sort((a, b) => a - b);+ expect(firstDifference(text, ordered), `document ${index}`).toBeNull();+ }+ }, 120_000);++ it("leaves text without math delimiters as it came when it is normalized in full", () => {+ const next = random(7);+ const texts = [...Object.values(CORPUS), ...Array.from({ length: 600 }, () => randomDocument(next))].filter((text) => !mayHoldMath(text));+ expect(texts.length).toBeGreaterThan(200);+ // An image map turns the shortcut off, so this is the full normalization the shortcut stands in for.+ for (const text of texts) expect(normalizeMathDelimiters(text, new Map()), text).toBe(text);+ });++ it("cuts lists and tables into pieces along the way", () => {+ expect(mode.pieces).toBeGreaterThan(1000);+ });+});diff --git a/src/components/ChatMarkdown.streaming.test.ts b/src/components/ChatMarkdown.streaming.test.tsindex 299668ef16..b2445ad54e 100644--- a/src/components/ChatMarkdown.streaming.test.ts+++ b/src/components/ChatMarkdown.streaming.test.ts@@ -16,13 +16,24 @@ vi.mock("react-markdown", async (importOriginal) => {},};});+const preParsed = vi.hoisted(() => [] as string[]);+vi.mock("mdast-util-from-markdown", async (importOriginal) => {+ const actual = await importOriginal<typeof import("mdast-util-from-markdown")>();+ return {+ ...actual,+ fromMarkdown: (...args: Parameters<typeof actual.fromMarkdown>) => {+ preParsed.push(String(args[0]));+ return actual.fromMarkdown(...args);+ },+ };+});vi.mock("@/lib/interface-mode", async (importOriginal) => ({...await importOriginal<typeof import("@/lib/interface-mode")>(),useAdvancedMode: () => true,readAdvancedMode: () => true,}));-const { ChatMarkdown, clearChatMarkdownCache } = await import("./ChatMarkdown");+const { ChatMarkdown, clearChatMarkdownCache, normalizeMathDelimiters } = await import("./ChatMarkdown");(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -37,6 +48,7 @@ describe("a reply's Markdown while it streams", () => {setLocale("en");clearChatMarkdownCache();parsed.length = 0;+ preParsed.length = 0;host = document.createElement("div");document.body.append(host);root = createRoot(host);@@ -102,4 +114,83 @@ describe("a reply's Markdown while it streams", () => {draw("Text right above\n```py\nprint(1)\n```", true);expect(host.querySelector(".chat-code-actions")!.hasAttribute("inert")).toBe(false);});++ /** Streams `text` in deltas of `step` characters and returns the characters handed to each parser along the way. */+ const stream = (text: string, step: number) => {+ for (let end = step; end < text.length + step; end += step) draw(text.slice(0, end), true);+ const chars = (sources: string[]) => sources.reduce((sum, source) => sum + source.length, 0);+ return { parsed: chars(parsed), longest: Math.max(...parsed.map((source) => source.length)), preParsed: chars(preParsed) };+ };+ const whole = (text: string) => {+ const streamed = markup();+ draw(text, false);+ expect(streamed).toBe(markup());+ };++ it("parses only the item being written of a long list", () => {+ const text = Array.from({ length: 150 }, (_, index) => `- item ${index} with **bold** and \`code\`\n`).join("");+ const work = stream(text, 13);+ expect(work.parsed, "each item is parsed a few times, never the list again").toBeLessThan(text.length * 5);+ expect(work.longest).toBeLessThan(80);+ expect(work.preParsed, "nothing is parsed to normalize or repair").toBe(0);+ expect(host.querySelectorAll("ul").length).toBe(1);+ expect(host.querySelectorAll("li").length).toBe(150);+ whole(text);+ });++ it("parses only the item being written of a long loose list under a lead line", () => {+ const text = `Steps:\n${Array.from({ length: 100 }, (_, index) => `${index + 1}. **Step ${index}**\n\n${" ".repeat(`${index + 1}. `.length)}Its body text.\n\n`).join("")}`;+ const work = stream(text, 13);+ expect(work.parsed).toBeLessThan(text.length * 5);+ expect(work.longest).toBeLessThan(80);+ expect(work.preParsed).toBe(0);+ expect(host.querySelectorAll("ol").length).toBe(1);+ expect(host.querySelectorAll("li > p").length).toBe(200);+ whole(text);+ });++ it("parses only the row being written of a long table", () => {+ const head = "| name | value | note |\n|------|------:|:-----|\n";+ const text = head + Array.from({ length: 150 }, (_, index) => `| row ${index} | ${index * 7} | some \`code\` |\n`).join("");+ const work = stream(text, 13);+ // Each row is parsed under the header, so a parse is three lines long.+ expect(work.parsed).toBeLessThan(text.length * 5 + 150 * 5 * head.length);+ expect(work.longest).toBeLessThan(head.length + 60);+ expect(work.preParsed, "only the header is checked for repair while it arrives").toBeLessThan(head.length * 10);+ expect(host.querySelector("table")!.getAttribute("aria-rowcount")).toBe("151");+ whole(text);+ });++ it("keeps parsing block by block under an HTML line and after display math", () => {+ const prose = Array.from({ length: 60 }, (_, index) => `Paragraph ${index} with **bold** words that keep flowing along.\n\n`).join("");+ for (const text of [`<details>\n\n${prose}`, `$$x^2$$\n\n${prose}`, `Intro\n\n$$\na + b\n$$\n\n${prose}\\[\nc\n\\]\n\n${prose}`]) {+ clearChatMarkdownCache();+ parsed.length = 0;+ preParsed.length = 0;+ const work = stream(text, 13);+ expect(work.parsed, text.slice(0, 12)).toBeLessThan(text.length * 5);+ expect(work.longest, text.slice(0, 12)).toBeLessThan(120);+ whole(text);+ }+ });++ it("normalizes text without math delimiters without parsing it, to the same result", () => {+ const plain = [+ "Plain **bold** and `code` with [a link](https://example.com) and .",+ "- one\n- two (with parens) [and brackets]\n\n```sh\nls\n```\n\n| a | b |\n|---|---|\n",+ "Backslashes \\\\ and \\* and a\\b, 100% and #1.",+ "",+ ];+ for (const text of plain) {+ expect(normalizeMathDelimiters(text), text).toBe(text);+ expect(preParsed, text).toEqual([]);+ // With an image map the text is always parsed: the full normalization gives the same text back.+ expect(normalizeMathDelimiters(text, new Map()), text).toBe(text);+ expect(preParsed.splice(0), text).toEqual([text]);+ }+ for (const text of ["Costs $5.", "Inline \\(x\\).", "Display \\[x\\].", "a\u0000b"]) {+ normalizeMathDelimiters(text);+ expect(preParsed.splice(0), text).toEqual([text]);+ }+ });});diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsxindex 1ee823865c..5717ad2ae2 100644--- a/src/components/ChatMarkdown.tsx+++ b/src/components/ChatMarkdown.tsx@@ -1,5 +1,5 @@// Security: model output never reaches the DOM as raw HTML (no rehype-raw); Shiki's output is generator-escaped.-import { createContext, Fragment, memo, use, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react";+import { createContext, Fragment, memo, use, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactElement, type ReactNode } from "react";import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Options as MarkdownOptions } from "react-markdown";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";@@ -11,7 +11,8 @@ import { cn } from "@/lib/cn";import { useAdvancedMode } from "@/lib/interface-mode";import { remarkMentions, sameMentionPerson, type MentionPeer, type MentionPerson } from "@/lib/mentions";import { createMarkdownRenderCache } from "@/lib/markdown-render-cache";-import { closedFence, openFence, splitMarkdownBlocks } from "@/lib/markdown-stream-blocks";+import { closedFence, mayHoldMath, openFence, splitMarkdownBlocks, splitStreamPieces, type StreamPieces } from "@/lib/markdown-stream-blocks";+import { drawStreamPieces, type ItemScope, type ParsePiece } from "@/lib/markdown-stream-pieces";import { StreamingReplyContext } from "@/state/live-reply";import { parseFenceInfo } from "../lib/code-block";@@ -479,6 +480,7 @@ function escapeLiteralDollars(text: string): string {}export function normalizeMathDelimiters(text: string, imageOffsets?: Map<number, number>): string {+ if (!imageOffsets && !mayHoldMath(text)) return text;const protectedCode: Array<{ value: string; sourceOffset: number }> = [];const protect = (value: string, sourceOffset: number): string => {const token = `\u0000OMB_CODE_${protectedCode.length}\u0000`;@@ -530,20 +532,22 @@ export function normalizeMathDelimiters(text: string, imageOffsets?: Map<number,const normalizedCache = new Map<string, Pick<MessageScope, "imageOffsets"> & { source: string }>();const NORMALIZED_CACHE_MAX = TRANSCRIPT_WINDOW_SIZE * 2;-function normalizeMarkdown(text: string) {+/** Tables are repaired only in a message without images; `repair` carries that choice to a block of the message. */+function normalizeMarkdown(text: string, repair = !text.includes(MARKDOWN_IMAGE)) {const imageOffsets = text.includes(MARKDOWN_IMAGE) ? new Map<number, number>() : undefined;- return { source: normalizeMathDelimiters(imageOffsets ? text : repairMarkdownTables(text), imageOffsets), imageOffsets };+ return { source: normalizeMathDelimiters(repair ? repairMarkdownTables(text) : text, imageOffsets), imageOffsets };}-function normalizeMessageMarkdown(text: string) {- const cached = normalizedCache.get(text);+function normalizeMessageMarkdown(text: string, repair = !text.includes(MARKDOWN_IMAGE)) {+ const key = repair ? text : `\u0000${text}`;+ const cached = normalizedCache.get(key);if (cached) return cached;- const normalized = normalizeMarkdown(text);+ const normalized = normalizeMarkdown(text, repair);if (normalizedCache.size >= NORMALIZED_CACHE_MAX) {const first = normalizedCache.keys().next().value;if (first !== undefined) normalizedCache.delete(first);}- normalizedCache.set(text, normalized);+ normalizedCache.set(key, normalized);return normalized;}@@ -804,6 +808,16 @@ interface MarkdownPart {finished: boolean;/** A code fence still being written, drawn without parsing. */fence?: { lang: string; wrap: boolean; code: string };+ /** A list or table still being written, of which only the last piece is parsed again. */+ pieces?: StreamPieces;+ /** Whether the message repairs tables. */+ repair?: boolean;+}++function remarkLooseList() {+ return (tree: { children: { type: string; spread?: boolean }[] }) => {+ if (tree.children[0]?.type === "list") tree.children[0].spread = true;+ };}/** A finished message is one part. A streaming one is its blocks: the finished ones are parsed once and kept, and only@@ -811,10 +825,13 @@ interface MarkdownPart {function markdownParts(text: string, streaming: boolean): MarkdownPart[] {if (!streaming) return [{ text, ...normalizeMessageMarkdown(text), finished: true }];const blocks = splitMarkdownBlocks(text) ?? [text];+ const repair = !text.includes(MARKDOWN_IMAGE);return blocks.map((block, index): MarkdownPart => {- if (index < blocks.length - 1) return { text: block, ...normalizeMessageMarkdown(block), finished: true };+ if (index < blocks.length - 1) return { text: block, ...normalizeMessageMarkdown(block, repair), finished: true, repair };const fence = openFence(block);- if (!fence) return { text: block, ...normalizeMarkdown(block), finished: false };+ const pieces = fence ? null : splitStreamPieces(block);+ if (pieces) return { text: block, source: block, finished: false, pieces, repair };+ if (!fence) return { text: block, ...normalizeMarkdown(block, repair), finished: false };const [info = "", ...meta] = fence.info.split(/\s+/);return { text: block, source: block, finished: false, fence: { ...parseFenceInfo(info, meta.join(" ")), code: fence.code } };});@@ -830,7 +847,8 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,const { threads, currentBotId } = MAY_LINK_THREAD.test(text) ? use(ThreadRefsContext) : NO_THREAD_REFS;const streaming = use(StreamingReplyContext);const parts = useMemo(() => markdownParts(text, streaming), [text, streaming]);- const needsMath = parts.some((part) => !part.fence && normalizedSourceHasMath(part.source));+ // One answer for the whole text, as a finished message gets: a block alone may hold half of a pair.+ const needsMath = useMemo(() => normalizedSourceHasMath(parts.length === 1 ? parts[0]!.source : parts.map((part) => part.source).join("")), [parts]);const [katexReady, setKatexReady] = useState(() => katexPlugin !== null);useEffect(() => {if (!needsMath) return;@@ -849,7 +867,7 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,}, [needsMath]);const mathPlugin = needsMath && katexReady ? katexPlugin : null;const linksThreads = threads.length > 0;- const draw = ({ text: partText, source, finished }: MarkdownPart) => {+ const parse = (source: string, cacheKey: string | null, loose = false, joined?: () => ReactElement | null) => {const mentions = source.includes("@");const variant = `${mathPlugin ? "math" : ""}\u0003${mentions ? `${peerSignature(mentionPeers)}\u0001${everyone ? 1 : 0}\u0001${mentionPerson?.profileName ?? ""}` : ""}\u0003${linksThreads ? `${threadListId(threads)}\u0001${currentBotId ?? ""}` : ""}`;// Markdown is a plain function of its options (no hooks), so its elements can be kept and drawn again.@@ -857,10 +875,26 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,const remarkPlugins = [...BASE_REMARK_PLUGINS];if (mentions) remarkPlugins.push([remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }]);if (linksThreads) remarkPlugins.push(remarkThreadRefs(threads, currentBotId));- return Markdown({ children: source, remarkPlugins, rehypePlugins: rehypePluginsFor(mathPlugin), urlTransform: chatUrlTransform, components: MARKDOWN_COMPONENTS });+ if (loose) remarkPlugins.push(remarkLooseList);+ return joined?.() ?? Markdown({ children: source, remarkPlugins, rehypePlugins: rehypePluginsFor(mathPlugin), urlTransform: chatUrlTransform, components: MARKDOWN_COMPONENTS });};// Streamed text grows each render; keeping its drawing would only fill the cache with prefixes.- return finished ? markdownCache.render(partText, variant, render) : <StreamSourceContext value={source}>{render()}</StreamSourceContext>;+ return cacheKey === null ? render() : markdownCache.render(cacheKey, variant, render);+ };+ const piece: ParsePiece = (source, cacheKey, loose) => parse(source, cacheKey, loose);+ const itemScope: ItemScope = (nodes, index, open) => <StreamSourceContext key={index} value={open}>{nodes}</StreamSourceContext>;+ const draw = ({ text: partText, source, finished, pieces, repair }: MarkdownPart): ReactNode => {+ if (finished) {+ return parse(source, partText, false, () => {+ const split = splitStreamPieces(partText);+ const joined = split && drawStreamPieces(split, false, piece, itemScope);+ return joined ? <>{joined}</> : null;+ });+ }+ const joined = pieces && drawStreamPieces(pieces, true, piece, itemScope);+ if (joined) return joined;+ const whole = pieces ? normalizeMarkdown(partText, repair).source : source;+ return <StreamSourceContext value={whole}>{parse(whole, null)}</StreamSourceContext>;};// A message still streaming has no saved files to fetch yet.const scope = { message: streaming ? undefined : message, imageOffsets: streaming ? undefined : parts[0]?.imageOffsets, threads, currentBotId, delivered, originals };diff --git a/src/components/GroupView.render-count.test.ts b/src/components/GroupView.render-count.test.tsnew file mode 100644index 0000000000..fa56f6adf2--- /dev/null+++ b/src/components/GroupView.render-count.test.ts@@ -0,0 +1,187 @@+// @vitest-environment happy-dom+// The real provider and live stream with a room of 120 messages on screen: a streamed delta draws only the bubble it+// grows, and a store change the bubbles do not show draws none.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Action, BotAnnouncement, InstanceInfo, Message } from "@/state/store";+import type { RuntimeEvent } from "../../shared/runtime-events";+import { setLocale } from "@/lib/i18n";++const renders = vi.hoisted(() => ({ bubbles: 0, chips: 0 }));+vi.mock("./ToolActivity", async (importOriginal) => {+ const original = await importOriginal<typeof import("./ToolActivity")>();+ return { ...original, ToolActivity: (props: Parameters<typeof original.ToolActivity>[0]) => { renders.chips++; return original.ToolActivity(props); } };+});+// A text bubble asks for its pin action once each time it is drawn.+vi.mock("./message-menu", async (importOriginal) => {+ const original = await importOriginal<typeof import("./message-menu")>();+ return { ...original, roomPin: (...args: Parameters<typeof original.roomPin>) => { renders.bubbles++; return original.roomPin(...args); } };+});+vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useCanWriteIn: () => true, useReactor: () => "user" }));++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const announced = (id: string, name: string): BotAnnouncement => ({+ id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" },+ tasks: [{ threadId: `${id}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }],+});+const at = Date.UTC(2026, 10, 11, 12);+const history: Message[] = Array.from({ length: 120 }, (_, i) => i % 2 === 0+ ? { id: `m${i}`, role: "user", kind: "text", at: at + i, text: `Question ${i}` } as Message+ : { id: `m${i}`, role: "bot", kind: "text", at: at + i, text: `Answer **${i}** with a [link](https://example.com).`, from: { botId: i % 4 === 1 ? "a" : "b", name: i % 4 === 1 ? "Ada" : "Bea", color: "green" } } as Message);+const room = {+ id: "room", threadId: "room-thread", name: "Planning", memberIds: ["a", "b"], defaultResponder: { kind: "member", botId: "a" },+ bulletin: "", unread: false, createdAt: 1, messages: history, setupCompletedAt: 1,+ tasks: [{ threadId: "room-thread", title: "Chat", createdAt: 1 }],+};+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" }, models: { options: [{ id: "m", label: "Model" }] } } as unknown as InstanceInfo] },+ "/api/config": { features: { showToolCalls: true } },+ "/api/routines": { routines: [], runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+};++const { StoreProvider, useStore } = await import("@/state/store");+const { useStoreSelector } = await import("@/state/store-select");+const { GroupView } = await import("./GroupView");+const { noteLiveReplyEvent } = await import("@/state/live-reply");+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;++let dispatch!: (action: Action) => void;+function Shown() {+ dispatch = useStore().dispatch;+ return null;+}+function Shell() {+ const group = useStoreSelector((state) => state.groups.find((candidate) => candidate.id === "room"));+ return group ? createElement(GroupView, { group }) : null;+}++let root: Root;+let cursor = 0;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 6; i++) await task(); };+const stream = () => FixtureEventSource.opened[0]!;+const send = async (frame: object) => { stream().send(frame, `run:${++cursor}`); await settle(); };+let seq = 0;+const delta = (text: string) => flushSync(() => noteLiveReplyEvent({+ eventId: `d${++seq}`, provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t1", itemId: "x",+ type: "content.delta", streamKind: "assistant_text", delta: text, botId: "a",+} as RuntimeEvent));++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?")+ ? json({ bots: [announced("a", "Ada"), announced("b", "Bea"), announced("c", "Cy")].map((bot) => ({ ...bot, messages: [] })), groups: [room] })+ : json(answers[path.replace(/\?.*$/, "")] ?? {}));+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Shown), createElement(Shell))));+ await settle();+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "room" }));+ await settle();+});+afterAll(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++describe("a room on screen", () => {+ it("draws every bubble once", () => {+ expect(document.querySelectorAll("[data-mid]")).toHaveLength(120);+ expect(renders.bubbles).toBeGreaterThanOrEqual(120);+ });++ it("draws only the streaming bubble for each delta", async () => {+ flushSync(() => noteLiveReplyEvent({ eventId: "ts", provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t1", type: "turn.started" } as RuntimeEvent));+ delta("Starting ");+ await settle();+ expect(document.querySelector('[data-mid^="live:"]')?.textContent).toContain("Starting");+ const before = renders.bubbles;+ for (let i = 0; i < 20; i++) delta(`word${i} `);+ await settle();+ expect(renders.bubbles - before).toBe(20);+ expect(document.querySelector('[data-mid^="live:"]')?.textContent).toContain("word19");+ });++ it("draws no bubble for a store change none of them shows", async () => {+ const before = renders.bubbles;+ flushSync(() => dispatch({ type: "connected", value: false }));+ flushSync(() => dispatch({ type: "connected", value: true }));+ await send({ kind: "bot", bot: { ...announced("c", "Cy"), busy: true, activity: "working" } });+ await send({ kind: "message", threadId: "c-thread", message: { id: "c1", at: ++cursor, role: "bot", kind: "text", text: "c1" } });+ await send({ kind: "message", threadId: "a-thread", message: { id: "a1", at: ++cursor, role: "bot", kind: "text", text: "a1" } });+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: true, activity: "working" } });+ expect(renders.bubbles).toBe(before);+ });++ it("draws only the newest bubbles for a message saved in the room", async () => {+ const before = renders.bubbles;+ await send({ kind: "message", threadId: "room-thread", message: { id: "saved-1", at: at + ++cursor, role: "bot", kind: "text", text: "Saved", from: { botId: "b", name: "Bea", color: "green" } } });+ expect(document.querySelector('[data-mid="saved-1"]')).not.toBeNull();+ expect(renders.bubbles - before).toBeLessThanOrEqual(3);+ });++ it("draws no bubble again for a tool step saved in the room", async () => {+ const before = renders.bubbles;+ await send({ kind: "message", threadId: "room-thread", message: { id: "step-1", at: at + ++cursor, role: "bot", kind: "activity", tool: { name: "Read file" }, from: { botId: "a", name: "Ada", color: "green" } } });+ expect(document.querySelector('[data-mid="step-1"]')).not.toBeNull();+ expect(renders.bubbles - before).toBe(0);+ });++ it("draws no tool chip again for a delta or a store change it does not show", async () => {+ const chips = renders.chips;+ expect(chips).toBeGreaterThan(0);+ flushSync(() => noteLiveReplyEvent({ eventId: "ts2", provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t2", type: "turn.started" } as RuntimeEvent));+ for (let i = 0; i < 5; i++) flushSync(() => noteLiveReplyEvent({+ eventId: `d2-${i}`, provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t2", itemId: "y",+ type: "content.delta", streamKind: "assistant_text", delta: `more${i} `, botId: "a",+ } as RuntimeEvent));+ flushSync(() => dispatch({ type: "connected", value: false }));+ flushSync(() => dispatch({ type: "connected", value: true }));+ await settle();+ expect(document.querySelector('[data-mid^="live:"]')?.textContent).toContain("more4");+ expect(renders.chips).toBe(chips);+ });++ it("draws every bubble and tool chip again in a new language", async () => {+ const before = renders.bubbles, chips = renders.chips;+ setLocale("de");+ try {+ flushSync(() => dispatch({ type: "connected", value: false }));+ await settle();+ expect(renders.bubbles - before).toBeGreaterThanOrEqual(120);+ expect(renders.chips).toBeGreaterThan(chips);+ } finally {+ setLocale("en");+ flushSync(() => dispatch({ type: "connected", value: true }));+ await settle();+ }+ });++ it("draws every bubble again when a member's name changes, which @-mentions show", async () => {+ const before = renders.bubbles;+ await send({ kind: "bot", bot: { ...announced("a", "Ada Lovelace"), busy: true, activity: "working" } });+ expect(renders.bubbles - before).toBeGreaterThanOrEqual(120);+ });+});diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex eb7243205c..a2aee39b88 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -1,9 +1,6 @@import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { formattedReplyWidth, isFormattedReply, splitReplyBlocks } from "@/lib/formatted-reply";-import { activeLocale, intlLocale, t } from "@/lib/i18n";+import { activeLocale, t } from "@/lib/i18n";import { useShowThreads } from "@/lib/thread-preferences";-import { useReactor } from "@/lib/cloud-guest";-import { otherSpeaker } from "@/lib/own-profile";import { Check, ChevronDown, FolderOpen, Loader2, Square } from "lucide-react";import {api,@@ -16,53 +13,42 @@ import {type GroupDefaultResponder,type Message,} from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useStoreRef } from "@/state/store-ref"; import { localSystemVoiceActive } from "@/lib/local-voice";+import { RoomTextMessage } from "./RoomTextMessage";import { BotAvatar } from "./Avatar";import { ScreenFrame } from "./ScreenFrame";import { RoomHoldsBanner } from "./RoomHoldsBanner";import { ThreadChip } from "./ThreadChip";import { ToolActivity } from "./ToolActivity";-import { ThreadRefText } from "./ThreadRefs";import { TurnPresence } from "./TurnPresence";import { showToolCallsEnabled } from "@/lib/feature-flags";import { CompactionChip, DigestChip } from "./DigestChip";import { roomActivityVisible } from "@/lib/room-activity";-import { StatusActivityRow } from "@/components/StatusActivityRow"; import { BugReportNote } from "@/components/BugReportNote";+import { StatusActivityRow } from "@/components/StatusActivityRow";import { normalizeState } from "@/lib/mascot";import { botTextShowsSpeaker, laterTextOwns, runShowsSpeaker } from "@/lib/room-speaker"; import { roomAddressees } from "@/lib/room-addressees";import { defaultResponderName, groupResponseHint, jevRoomRoutingOn } from "@/lib/group-routing";-import { ChatMarkdown } from "./ChatMarkdown";import { FailedTurnRow, MessageBoundary } from "./ChatView";-import { SIMPLE_BOT_BUBBLE, SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT, SIMPLE_USER_BUBBLE } from "./chat-bubble";-import { ReplyBlocks } from "./ReplyBlocks";import { useAdvancedMode } from "@/lib/interface-mode";-import { CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction } from "./MessageActions";-import { ReactAction, ReactionChips, useCanReact } from "./Reactions";+import { useCanReact } from "./Reactions";import { ClusterLabel } from "./RoomClusterLabel";-import { replyAndCopy, roomPin, useBotMessageMenu, userMessageMenu } from "./message-menu";-import { forkMessageItem, ForkLinks } from "./ForkMessage";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";-import { RawMarkdownView, RawToggleAction } from "./RawMarkdownToggle";-import { SpeakButton, speakReady } from "./SpeakButton";-import { useSpeech } from "@/lib/tts/useSpeech";-import { localSystemVoiceActive } from "@/lib/local-voice";import { CancelledTurnRow } from "./CancelledTurnRow";import { isCancelledTranscriptRow } from "../../shared/client-cancel";import { roomRetryRequest } from "@/lib/room-retry";import { botEngine, failedTurnCause } from "@/lib/failed-turn";-import { CitationSelectionToolbar, SentCitations } from "./CitationUI";+import { CitationSelectionToolbar } from "./CitationUI";import { RoomComposer } from "./bot-access/RoomComposer";import { ChatErrorBanner, ChatNotice } from "./ChatErrorBanner";import { RoomContextWarnings } from "./ContextWarning"; import { RoomChiefAbsent } from "./RoomChiefAbsent";import { ChatFindBar } from "./ChatFindBar";-import { isPureLeakedSystemHarnessMessage, stripLeakedSystemHarnessMessages } from "../../shared/system-message-guard.ts";-import { ReplyQuote } from "./ReplyQuote";+import { isPureLeakedSystemHarnessMessage } from "../../shared/system-message-guard.ts";import { ConnectorCard } from "./ConnectorCard";import { SecretRequestCard } from "./SecretRequestCard";import { SignInRequestCard } from "./SignInRequestCard";import { hasRoutineExecutionTask, RoutineRunCard } from "./RoutineRunCard";import { GoalRunCard } from "./GoalRunCard";-import { AttachmentGallery, MessageAttachmentGallery, replyAttachmentGroup } from "./AttachmentGallery";-import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";import { OptionCard } from "./OptionCard";import { GroupCallOverlay } from "./GroupCallView";@@ -79,22 +65,19 @@ import { roomNeedsSetup, setupResponderMode, type RoomResponderMode } from "@/liimport { useComposerDockPad } from "@/lib/composer-dock";import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";import { awaitedMemberId, showWorkingDots } from "@/lib/turn-tail";-import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useLiveTranscript } from "@/state/live-reply";-import { splitTranscriptAttachments } from "@/lib/composer-attachments";+import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, useLiveTranscript } from "@/state/live-reply";import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { staysInView } from "../../shared/person-wait";import { useUnreadDivider } from "@/hooks/use-unread-divider";import { unreadMessageIds } from "@/lib/unread-divider";import { NewMessagesDivider } from "./NewMessagesDivider";import { appendDraftAttachments, useReplyDraft } from "@/lib/drafts";-import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";-import { highlightCitationSource } from "@/lib/citations-dom";import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";import { pendingApprovals } from "./PendingApproval";-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { RoomRichRow, UserLineNote } from "./RichMessageRow";+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { RoomRichRow } from "./RichMessageRow";import { TranscriptAnnouncer } from "./TranscriptAnnouncer";import { dayLabel, localDay } from "@/lib/transcript-derivations";import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";-import { RoomQueueList, RoutedByLine } from "./RoomQueueList";+import { RoomQueueList } from "./RoomQueueList";import { JumpToLatestButton } from "./JumpToLatestButton";import { HandoffChip } from "./HandoffReply"; import { TeammateChip } from "./TeammateChip"; import { useTeammates } from "@/state/team-people";import { RoomWorkingFolder } from "./RoomWorkingFolder";@@ -103,17 +86,17 @@ import { RoomHeader } from "./RoomHeader";import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";import { simpleRoomHeader } from "@/lib/room-panel";-export function RoomToolChip({ message, roomId, threadId, live = false }: { message: Message; roomId?: string; threadId?: string; live?: boolean }) {- const { state, dispatch } = useStore();+export const RoomToolChip = memo(function RoomToolChip({ message, roomId, threadId, live = false }: { message: Message; roomId?: string; threadId?: string; live?: boolean; /** Drawn again in a new language. */ locale?: string }) {+ const bots = useStoreSelector((s) => s.bots), instances = useStoreSelector((s) => s.instances), dispatch = useStoreDispatch(), store = useStoreRef();const tool = message.tool;if (!tool) return null;if (message.threadRef) return <ThreadChip message={message} threadId={threadId} />; if (message.relay) return <TeammateChip message={message} />;if (failedTurnCause(tool.name) !== null) {- return <FailedTurnRow tool={tool} engine={botEngine(state.bots.find((b) => b.id === message.from?.botId), state.instances)} botId={message.from?.botId} messageAt={message.at} />;+ return <FailedTurnRow tool={tool} engine={botEngine(bots.find((b) => b.id === message.from?.botId), instances)} botId={message.from?.botId} messageAt={message.at} />;}const comm = message.comm;if (comm && comm.groupId !== roomId) {- return <HandoffChip message={message} bots={state.bots} threadId={threadId} title={t("room.openBot", { name: comm.withName })} onClick={() => openRoomThread(dispatch, comm, state.groups)} />;+ return <HandoffChip message={message} bots={bots} threadId={threadId} title={t("room.openBot", { name: comm.withName })} onClick={() => openRoomThread(dispatch, comm, store.state().groups)} />;}if (!comm) return <ToolActivity tool={tool} live={live} source={threadId ? { threadId, messageId: message.id } : undefined} />;return (@@ -124,196 +107,17 @@ export function RoomToolChip({ message, roomId, threadId, live = false }: { messtool.ok === false && "text-danger",)}>- {comm && <BotAvatar bot={state.bots.find(b => b.id === comm.withBotId) ?? { name: comm.withName, color: comm.withColor }} state="happy" size={16} animated={false} />}+ {comm && <BotAvatar bot={bots.find(b => b.id === comm.withBotId) ?? { name: comm.withName, color: comm.withColor }} state="happy" size={16} animated={false} />}<span className={cn("max-w-[480px] truncate", !comm && "font-mono")}>{tool.name}</span></div></div>);-}--const USER_COLLAPSE_CHARS = 600;-const USER_COLLAPSE_LINES = 8;--function RoomTextMessage({- group,- message: m,- members,- transcript,- emerging,- eager,- onReply,- canReact,- phone,-}: {- group: Group;- message: Message;- members: Bot[];- transcript: Message[];- emerging: boolean;- eager: boolean;- onReply: (message: Message) => void;- canReact: boolean;- phone: boolean;-}) {- const { state, dispatch } = useStore();- const user = m.role === "user";- const reactor = useReactor();- const speaker = otherSpeaker(m, reactor !== "user" ? reactor : null);- const rawText = user ? (m.text ?? "") : stripLeakedSystemHarnessMessages(m.text ?? "");- const cited = user && m.text ? splitTranscriptCitations(m.text) : null;- const attachments = user && m.text ? splitTranscriptAttachments(cited?.display ?? m.text) : null;- const display = attachments?.display ?? rawText;- const [expanded, setExpanded] = useState(false);- const [viewRaw, setViewRaw] = useState(false);- const speech = useSpeech();- const speaking = speech.messageId === m.id && speech.status !== "idle";- const focus = state.focusMessage;- const focusedSearch = focus?.messageId === m.id && Boolean(focus.matchText) && focus.threadId === group.threadId;- const collapsible = user && !expanded && (display.length > USER_COLLAPSE_CHARS || display.split("\n").length > USER_COLLAPSE_LINES);- useEffect(() => { if (focusedSearch && collapsible) setExpanded(true); }, [focusedSearch, collapsible, focus?.nonce]);- const simple = !useAdvancedMode();- const speakerBot = members.find((member) => member.id === m.from?.botId);- const botText = rawText; const teammates = useTeammates(); const peers = useMemo(() => [...members, ...teammates.peers], [members, teammates]);- const pin = roomPin(group, m, dispatch);- const forkAction = !phone && !group.dm && m.kind === "text" && !m.id.startsWith("optimistic-")- ? [forkMessageItem({ kind: "group", ownerId: group.id, threadId: group.threadId, messageId: m.id }, dispatch, roomThreadWorking(group, group.threadId))] : [];- const botMenu = useBotMessageMenu({- text: botText,- botId: speakerBot?.id,- messageId: m.id,- voiceId: speakerBot?.voice,- tts: state.config?.tts,- localVoice: localSystemVoiceActive(),- canSpeak: true,- viewRaw,- onToggleRaw: () => setViewRaw((raw) => !raw),- pin,- });- const replyGroup = useMemo(() => !user && !isLiveReply(m) && botText.trim() ? replyAttachmentGroup(botText, m.attachments) : null, [user, m, botText]);- const blocks = useMemo(() => simple && !user && !viewRaw && botText.trim() ? splitReplyBlocks(botText) : null, [simple, user, viewRaw, botText]);- const tabled = Boolean(blocks?.some((block) => block.kind === "table"));- const botActions = !user && (- <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={[...botMenu, ...forkAction]} contextItems={replyAndCopy(() => onReply(m), botText)}>- <ReplyAction onReply={() => onReply(m)} />- {canReact && m.from && <ReactAction threadId={group.threadId} message={m} />}- {botText && <CopyButton text={botText} className={messageActionClass} />}- {botText && viewRaw && <RawToggleAction active onToggle={() => setViewRaw(false)} className={messageActionClass} />}- {botText && (speaking || speakReady(state.config?.tts, speakerBot?.voice, localSystemVoiceActive())) && <SpeakButton text={botText} botId={speakerBot?.id} messageId={m.id} voiceId={speakerBot?.voice} tts={state.config?.tts} localVoice={localSystemVoiceActive()} className={cn(messageActionClass, speaking && "text-accent")} />}- </MessageActions>- );- return (- <div {...{ [MESSAGE_ROW]: "" }} data-look={user ? "message-user" : "message-bot"} className={cn("group flex w-full flex-col", user ? "items-end" : "items-start")}>- {speaker && <div className="mb-0.5 px-1 text-right text-[13px] [overflow-wrap:anywhere] font-semibold text-ink-secondary">{speaker}</div>}- <div className={cn("flex w-full items-end gap-1.5", user ? "justify-end" : "justify-start")}>- {user && (- <MessageActions side="user" menu={[...userMessageMenu({ messageId: m.id, pin }), ...forkAction]} contextItems={replyAndCopy(() => onReply(m), display)}>- <ReplyAction onReply={() => onReply(m)} />- {Boolean(display.trim()) && <CopyButton text={display} className={messageActionClass} />}- </MessageActions>- )}- <div- data-chat-bubble={simple ? "simple" : ""} data-look={user ? "user-bubble" : "bot-bubble"}- className={cn(- tabled ? "w-full" : "w-fit",- simple ? cn(!tabled && SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT) : "max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-2xl text-[15px] leading-relaxed",- !user && emerging && !streamedReply(m.id) && "turn-answer",- tabled || (!user && !m.text?.trim() && !m.replyToId && m.attachments?.length)- ? "text-ink"- : !simple && !user && isFormattedReply(m.text ?? "")- ? cn(formattedReplyWidth(m.text ?? ""), "px-1 text-ink")- : user- ? cn("chat-text whitespace-pre-wrap [overflow-wrap:anywhere] text-ink", simple ? SIMPLE_USER_BUBBLE : "bg-bubble-user px-4 py-2.5")- : simple ? SIMPLE_BOT_BUBBLE : "bg-card px-4 py-2.5 text-ink",- )}- title={new Date(m.at).toLocaleString(intlLocale())}- >- {m.replyToId && (() => {- const target = transcript.find((candidate) => candidate.id === m.replyToId);- return target ? (- <div className="mb-2">- <ReplyQuote- message={target}- fallbackName={t("room.fallbackBot")}- compact- onJump={() =>- dispatch({ type: "focusMessage", threadId: group.threadId, messageId: target.id })- }- />- </div>- ) : null;- })()}- {user ? (- <>- {attachments && <AttachmentGallery images={attachments.images} files={attachments.files} message={{ threadId: group.threadId, messageId: m.id }} eager={eager} className={!attachments.display ? "mb-0" : undefined} />}- <div- className={cn(collapsible && "max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)]")}- data-citation-source={m.id}- data-citation-owner-type="group"- data-citation-owner={group.id}- data-citation-thread={group.threadId}- >- <ThreadRefText text={display} peers={peers} everyone={!group.dm} />- </div>{m.bugReport ? <BugReportNote report={m.bugReport} /> : m.pointed?.length ? <UserLineNote message={m} /> : null}- {cited && <SentCitations- citations={cited.citations}- onNavigate={async (citation: CitationAttachment) => {- if (citation.source.ownerType !== "group" || !group.messages.some((candidate) => candidate.id === citation.source.messageId)) return false;- dispatch({ type: "focusMessage", threadId: group.threadId, messageId: citation.source.messageId });- return highlightCitationSource(citation);- }}- />}- {m.via === "api" && (- <div className="mt-1 text-[11px] text-ink-secondary">{t("room.viaApi")}</div>- )}- {collapsible && (- <button type="button" onClick={() => setExpanded(true)} className="mt-1 text-[13px] text-ink-secondary hover:text-ink">- {t("chat.showFull")}- </button>- )}- {expanded && (- <button type="button" onClick={() => setExpanded(false)} className="mt-1 text-[13px] text-ink-secondary hover:text-ink">- {t("chat.showLess")}- </button>- )}- </>- ) : (- <MessageBoundary key={viewRaw ? "raw" : "rendered"} fallbackText={botText || t("chat.generatedImage")}>- {(m.attachments ?? []).some((attachment) => attachment.kind === "audio") && (- <div className={cn("flex flex-col", (m.text || (m.attachments ?? []).some((attachment) => attachment.kind === "image")) && "mb-2")}>- {m.attachments!.filter((attachment): attachment is VoiceNoteAttachment => attachment.kind === "audio").map((note) => (- <VoiceNoteBubble key={note.path} attachment={note} />- ))}- </div>- )}- {!botText.trim() && <MessageAttachmentGallery text={botText} attachments={m.attachments} message={{ threadId: group.threadId, messageId: m.id }} className={m.text ? undefined : "mb-0"} eager={eager} />}- {viewRaw && botText ? (- <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><RawMarkdownView text={botText} /></div>- ) : tabled && blocks ? (- <ReplyBlocks blocks={blocks} tray={botActions} citation={{ messageId: m.id, ownerType: "group", ownerId: group.id, threadId: group.threadId }}- render={(block) => <ChatMarkdown text={block} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} />} />- ) : botText ? (- <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><ChatMarkdown text={botText} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} /></div>- ) : null}- {replyGroup && <AttachmentGallery images={replyGroup.images} files={replyGroup.files} originals={replyGroup.originals} message={{ threadId: group.threadId, messageId: m.id }} eager={eager} beneath />}- </MessageBoundary>- )}- </div>- {!tabled && botActions}- <span className="self-end pb-1 text-[11px] tabular-nums text-ink-tertiary opacity-0 transition-opacity group-hover:opacity-100">- {formatTime(m.at)}- </span>- </div>- <ReactionChips threadId={group.threadId} message={m} bots={members} align={user ? "end" : "start"} canReact={canReact} />- <ForkLinks kind="group" ownerId={group.id} threadId={group.threadId} messageId={m.id} phone={phone} />- {!user && m.routedBy && <RoutedByLine routedBy={m.routedBy} />}- </div>- );-}+});export const Transcript = memo(function Transcript({group,members,- locale,+ locale, localVoice = false,messages: saved,transcript,emergingId,@@ -323,7 +127,7 @@ export const Transcript = memo(function Transcript({}: {group: Group;members: Bot[];- locale: string;+ locale: string; localVoice?: boolean;messages: Message[];transcript: Message[];emergingId?: string | null;@@ -331,10 +135,10 @@ export const Transcript = memo(function Transcript({unreadDividerFading?: boolean;onReply: (message: Message) => void;}) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch(), store = useStoreRef(), config = useStoreSelector((s) => s.config), focus = useStoreSelector((s) => s.focusMessage);const phone = useMediaQuery(PHONE_LAYOUT);const showThreads = useShowThreads();- const showToolCalls = showToolCallsEnabled(state.config);+ const showToolCalls = showToolCallsEnabled(config);const canReact = useCanReact(group.threadId); const teammatePeers = useTeammates().peers;const memberOf = (id?: string) => members.find((b) => b.id === id); const messages = useLiveTranscript(group.threadId, saved, transcript, members, roomThreadSpeakerId(group, group.threadId));const folds = useMemo(() => roomTurnFolds(messages), [messages, locale]);@@ -370,8 +174,13 @@ export const Transcript = memo(function Transcript({...(retryRequest.replyToId ? { replyToId: retryRequest.replyToId } : {}),});}, [dispatch, group.id, group.threadId, retryRequest, roomBusy]);- const focus = state.focusMessage;const focusedId = focus && !focus.consumed && focus.threadId === group.threadId ? focus.messageId : null;+ const byId = useMemo(() => new Map(transcript.map((message) => [message.id, message])), [transcript]);+ const textRow = (message: Message, emerging: boolean, eager: boolean) => (+ <RoomTextMessage groupId={group.id} threadId={group.threadId} dm={Boolean(group.dm)} pinned={group.pinnedMessageId === message.id} working={roomBusy}+ message={message} members={members} replyTarget={message.replyToId ? byId.get(message.replyToId) : undefined}+ emerging={emerging} eager={eager} onReply={onReply} canReact={canReact} phone={phone} locale={locale} localVoice={localVoice} />+ );const unreadIds = useMemo(() => unreadMessageIds(messages, unreadDividerId), [messages, unreadDividerId]);let dividerPlaced = false;const dividerAbove = (rows: readonly Message[]) => {@@ -404,7 +213,7 @@ export const Transcript = memo(function Transcript({<ActivityRun messages={item.messages} forceOpen={item.messages.some((step) => step.id === focusedId)}>{item.messages.map((step) => (<div key={step.id} className="contents" data-mid={step.id}>- <RoomToolChip message={step} threadId={group.threadId} live={liveTools.has(step.id)} />+ <RoomToolChip message={step} threadId={group.threadId} live={liveTools.has(step.id)} locale={locale} /></div>))}</ActivityRun>@@ -456,13 +265,13 @@ export const Transcript = memo(function Transcript({<RoutineRunCardmessage={m}onOpen={routineTarget- ? () => openThread(dispatch, routineTarget, state, showThreads)+ ? () => openThread(dispatch, routineTarget, store.state(), showThreads): undefined}/></div>) : m.kind === "activity" && m.tool ? (roomActivityVisible(m, showToolCalls) ? (- m.dataResult ? <DataResultChip message={m} /> : isStatusActivity(m) ? <StatusActivityRow message={m} /> : <RoomToolChip message={m} roomId={group.id} threadId={group.threadId} live={liveTools.has(m.id)} />+ m.dataResult ? <DataResultChip message={m} /> : isStatusActivity(m) ? <StatusActivityRow message={m} /> : <RoomToolChip message={m} roomId={group.id} threadId={group.threadId} live={liveTools.has(m.id)} locale={locale} />) : null) : m.kind === "screen" ? (<ScreenFrame threadId={group.threadId} message={m} />@@ -472,17 +281,7 @@ export const Transcript = memo(function Transcript({showToolCalls ? <DigestChip message={m} /> : null) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.template ? <TemplateChatCard message={m} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length) ? (!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length ? null : (- <RoomTextMessage- group={group}- message={m}- members={members}- transcript={transcript}- emerging={m.id === emergingId}- eager={m.id === newestMessageId || m.id === newestUserMessageId}- onReply={onReply}- canReact={canReact}- phone={phone}- />+ textRow(m, m.id === emergingId, m.id === newestMessageId || m.id === newestUserMessageId))) : null;if (!row) return divider && <div key={m.id} className="contents">{divider}</div>;@@ -507,19 +306,7 @@ export const Transcript = memo(function Transcript({forceOpen={fold.messages.some((note) => note.id === focusedId)}>{fold.messages.map((note) => (- <div key={note.id} className="contents" data-mid={note.id}>- <RoomTextMessage- group={group}- message={note}- members={members}- transcript={transcript}- emerging={false}- eager={false}- onReply={onReply}- canReact={canReact}- phone={phone}- />- </div>+ <div key={note.id} className="contents" data-mid={note.id}>{textRow(note, false, false)}</div>))}</TurnNarrationRun>)}@@ -1099,7 +886,7 @@ export function GroupView({ group, inForkPanel = false }: { group: Group; inFork<Transcriptgroup={group}members={members}- locale={activeLocale()}+ locale={activeLocale()} localVoice={localSystemVoiceActive()}messages={windowedMessages}transcript={group.messages}emergingId={popping?.id}diff --git a/src/components/RoomTextMessage.tsx b/src/components/RoomTextMessage.tsxnew file mode 100644index 0000000000..566ab96891--- /dev/null+++ b/src/components/RoomTextMessage.tsx@@ -0,0 +1,243 @@+import { memo, useEffect, useMemo, useState } from "react";+import { formattedReplyWidth, isFormattedReply, splitReplyBlocks } from "@/lib/formatted-reply";+import { intlLocale, t } from "@/lib/i18n";+import { useReactor } from "@/lib/cloud-guest";+import { otherSpeaker } from "@/lib/own-profile";+import { sameDrawnBots } from "@/lib/drawn-bots";+import { useAdvancedMode } from "@/lib/interface-mode";+import { useSpeech } from "@/lib/tts/useSpeech";+import { splitTranscriptAttachments } from "@/lib/composer-attachments";+import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";+import { highlightCitationSource } from "@/lib/citations-dom";+import { cn } from "@/lib/cn";+import { formatTime, type Bot, type Message } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useStoreRef } from "@/state/store-ref";+import { isLiveReply, streamedReply } from "@/state/live-reply";+import { useTeammates } from "@/state/team-people";+import { stripLeakedSystemHarnessMessages } from "../../shared/system-message-guard.ts";+import { ThreadRefText } from "./ThreadRefs";+import { BugReportNote } from "./BugReportNote";+import { ChatMarkdown } from "./ChatMarkdown";+import { MessageBoundary } from "./ChatView";+import { SIMPLE_BOT_BUBBLE, SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT, SIMPLE_USER_BUBBLE } from "./chat-bubble";+import { ReplyBlocks } from "./ReplyBlocks";+import { CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction } from "./MessageActions";+import { ReactAction, ReactionChips } from "./Reactions";+import { replyAndCopy, roomPin, useBotMessageMenu, userMessageMenu } from "./message-menu";+import { forkMessageItem, ForkLinks } from "./ForkMessage";+import { RawMarkdownView, RawToggleAction } from "./RawMarkdownToggle";+import { SpeakButton, speakReady } from "./SpeakButton";+import { SentCitations } from "./CitationUI";+import { ReplyQuote } from "./ReplyQuote";+import { AttachmentGallery, MessageAttachmentGallery, replyAttachmentGroup } from "./AttachmentGallery";+import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";+import { UserLineNote } from "./RichMessageRow";+import { RoutedByLine } from "./RoomQueueList";++const USER_COLLAPSE_CHARS = 600;+const USER_COLLAPSE_LINES = 8;++interface RoomTextMessageProps {+ groupId: string;+ threadId: string;+ dm: boolean;+ pinned: boolean;+ /** The room's conversation is working. */+ working: boolean;+ message: Message;+ members: Bot[];+ replyTarget?: Message;+ emerging: boolean;+ eager: boolean;+ onReply: (message: Message) => void;+ canReact: boolean;+ phone: boolean;+ /** Drawn again in a new language. */+ locale: string;+ localVoice: boolean;+}++/** Members are drawn by name and look, and spoken in their voice. */+const sameMembers = (a: readonly Bot[], b: readonly Bot[]) => a === b || (sameDrawnBots(a, b) && a.every((bot, index) => bot.voice === b[index]!.voice));++function sameRow(previous: RoomTextMessageProps, next: RoomTextMessageProps): boolean {+ const keys = Object.keys(next) as (keyof RoomTextMessageProps)[];+ return keys.length === Object.keys(previous).length && keys.every((key) => key === "members" ? sameMembers(previous.members, next.members) : Object.is(previous[key], next[key]));+}++/** One text message in a room: drawn again only when its own props or the store slices it shows change. */+export const RoomTextMessage = memo(function RoomTextMessage({+ groupId,+ threadId,+ dm,+ pinned,+ working,+ message: m,+ members,+ replyTarget,+ emerging,+ eager,+ onReply,+ canReact,+ phone,+ localVoice,+}: RoomTextMessageProps) {+ const dispatch = useStoreDispatch(), store = useStoreRef();+ const focusNonce = useStoreSelector((state) => {+ const focus = state.focusMessage;+ return focus?.messageId === m.id && focus.matchText && focus.threadId === threadId ? focus.nonce : null;+ });+ const tts = useStoreSelector((state) => state.config?.tts);+ const profileName = useStoreSelector((state) => state.config?.profile?.name);+ const mentionPerson = useMemo(() => ({ profileName }), [profileName]);+ const user = m.role === "user";+ const reactor = useReactor();+ const speaker = otherSpeaker(m, reactor !== "user" ? reactor : null);+ const rawText = user ? (m.text ?? "") : stripLeakedSystemHarnessMessages(m.text ?? "");+ const cited = user && m.text ? splitTranscriptCitations(m.text) : null;+ const attachments = user && m.text ? splitTranscriptAttachments(cited?.display ?? m.text) : null;+ const display = attachments?.display ?? rawText;+ const [expanded, setExpanded] = useState(false);+ const [viewRaw, setViewRaw] = useState(false);+ const speech = useSpeech();+ const speaking = speech.messageId === m.id && speech.status !== "idle";+ const focusedSearch = focusNonce !== null;+ const collapsible = user && !expanded && (display.length > USER_COLLAPSE_CHARS || display.split("\n").length > USER_COLLAPSE_LINES);+ useEffect(() => { if (focusedSearch && collapsible) setExpanded(true); }, [focusedSearch, collapsible, focusNonce]);+ const simple = !useAdvancedMode();+ const speakerBot = members.find((member) => member.id === m.from?.botId);+ const botText = rawText; const teammates = useTeammates(); const peers = useMemo(() => [...members, ...teammates.peers], [members, teammates]);+ const pin = roomPin({ id: groupId, pinnedMessageId: pinned ? m.id : undefined }, m, dispatch);+ const forkAction = !phone && !dm && m.kind === "text" && !m.id.startsWith("optimistic-")+ ? [forkMessageItem({ kind: "group", ownerId: groupId, threadId, messageId: m.id }, dispatch, working)] : [];+ const botMenu = useBotMessageMenu({+ text: botText,+ botId: speakerBot?.id,+ messageId: m.id,+ voiceId: speakerBot?.voice,+ tts,+ localVoice,+ canSpeak: true,+ viewRaw,+ onToggleRaw: () => setViewRaw((raw) => !raw),+ pin,+ });+ const replyGroup = useMemo(() => !user && !isLiveReply(m) && botText.trim() ? replyAttachmentGroup(botText, m.attachments) : null, [user, m, botText]);+ const blocks = useMemo(() => simple && !user && !viewRaw && botText.trim() ? splitReplyBlocks(botText) : null, [simple, user, viewRaw, botText]);+ const tabled = Boolean(blocks?.some((block) => block.kind === "table"));+ const botActions = !user && (+ <MessageActions side="bot" forceOpen={viewRaw || speaking} menu={[...botMenu, ...forkAction]} contextItems={replyAndCopy(() => onReply(m), botText)}>+ <ReplyAction onReply={() => onReply(m)} />+ {canReact && m.from && <ReactAction threadId={threadId} message={m} />}+ {botText && <CopyButton text={botText} className={messageActionClass} />}+ {botText && viewRaw && <RawToggleAction active onToggle={() => setViewRaw(false)} className={messageActionClass} />}+ {botText && (speaking || speakReady(tts, speakerBot?.voice, localVoice)) && <SpeakButton text={botText} botId={speakerBot?.id} messageId={m.id} voiceId={speakerBot?.voice} tts={tts} localVoice={localVoice} className={cn(messageActionClass, speaking && "text-accent")} />}+ </MessageActions>+ );+ return (+ <div {...{ [MESSAGE_ROW]: "" }} data-look={user ? "message-user" : "message-bot"} className={cn("group flex w-full flex-col", user ? "items-end" : "items-start")}>+ {speaker && <div className="mb-0.5 px-1 text-right text-[13px] [overflow-wrap:anywhere] font-semibold text-ink-secondary">{speaker}</div>}+ <div className={cn("flex w-full items-end gap-1.5", user ? "justify-end" : "justify-start")}>+ {user && (+ <MessageActions side="user" menu={[...userMessageMenu({ messageId: m.id, pin }), ...forkAction]} contextItems={replyAndCopy(() => onReply(m), display)}>+ <ReplyAction onReply={() => onReply(m)} />+ {Boolean(display.trim()) && <CopyButton text={display} className={messageActionClass} />}+ </MessageActions>+ )}+ <div+ data-chat-bubble={simple ? "simple" : ""} data-look={user ? "user-bubble" : "bot-bubble"}+ className={cn(+ tabled ? "w-full" : "w-fit",+ simple ? cn(!tabled && SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT) : "max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-2xl text-[15px] leading-relaxed",+ !user && emerging && !streamedReply(m.id) && "turn-answer",+ tabled || (!user && !m.text?.trim() && !m.replyToId && m.attachments?.length)+ ? "text-ink"+ : !simple && !user && isFormattedReply(m.text ?? "")+ ? cn(formattedReplyWidth(m.text ?? ""), "px-1 text-ink")+ : user+ ? cn("chat-text whitespace-pre-wrap [overflow-wrap:anywhere] text-ink", simple ? SIMPLE_USER_BUBBLE : "bg-bubble-user px-4 py-2.5")+ : simple ? SIMPLE_BOT_BUBBLE : "bg-card px-4 py-2.5 text-ink",+ )}+ title={new Date(m.at).toLocaleString(intlLocale())}+ >+ {replyTarget && (+ <div className="mb-2">+ <ReplyQuote+ message={replyTarget}+ fallbackName={t("room.fallbackBot")}+ compact+ onJump={() =>+ dispatch({ type: "focusMessage", threadId, messageId: replyTarget.id })+ }+ />+ </div>+ )}+ {user ? (+ <>+ {attachments && <AttachmentGallery images={attachments.images} files={attachments.files} message={{ threadId, messageId: m.id }} eager={eager} className={!attachments.display ? "mb-0" : undefined} />}+ <div+ className={cn(collapsible && "max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)]")}+ data-citation-source={m.id}+ data-citation-owner-type="group"+ data-citation-owner={groupId}+ data-citation-thread={threadId}+ >+ <ThreadRefText text={display} peers={peers} everyone={!dm} />+ </div>{m.bugReport ? <BugReportNote report={m.bugReport} /> : m.pointed?.length ? <UserLineNote message={m} /> : null}+ {cited && <SentCitations+ citations={cited.citations}+ onNavigate={async (citation: CitationAttachment) => {+ const messages = store.state().groups.find((room) => room.id === groupId)?.messages ?? [];+ if (citation.source.ownerType !== "group" || !messages.some((candidate) => candidate.id === citation.source.messageId)) return false;+ dispatch({ type: "focusMessage", threadId, messageId: citation.source.messageId });+ return highlightCitationSource(citation);+ }}+ />}+ {m.via === "api" && (+ <div className="mt-1 text-[11px] text-ink-secondary">{t("room.viaApi")}</div>+ )}+ {collapsible && (+ <button type="button" onClick={() => setExpanded(true)} className="mt-1 text-[13px] text-ink-secondary hover:text-ink">+ {t("chat.showFull")}+ </button>+ )}+ {expanded && (+ <button type="button" onClick={() => setExpanded(false)} className="mt-1 text-[13px] text-ink-secondary hover:text-ink">+ {t("chat.showLess")}+ </button>+ )}+ </>+ ) : (+ <MessageBoundary key={viewRaw ? "raw" : "rendered"} fallbackText={botText || t("chat.generatedImage")}>+ {(m.attachments ?? []).some((attachment) => attachment.kind === "audio") && (+ <div className={cn("flex flex-col", (m.text || (m.attachments ?? []).some((attachment) => attachment.kind === "image")) && "mb-2")}>+ {m.attachments!.filter((attachment): attachment is VoiceNoteAttachment => attachment.kind === "audio").map((note) => (+ <VoiceNoteBubble key={note.path} attachment={note} />+ ))}+ </div>+ )}+ {!botText.trim() && <MessageAttachmentGallery text={botText} attachments={m.attachments} message={{ threadId, messageId: m.id }} className={m.text ? undefined : "mb-0"} eager={eager} />}+ {viewRaw && botText ? (+ <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={groupId} data-citation-thread={threadId}><RawMarkdownView text={botText} /></div>+ ) : tabled && blocks ? (+ <ReplyBlocks blocks={blocks} tray={botActions} citation={{ messageId: m.id, ownerType: "group", ownerId: groupId, threadId }}+ render={(block) => <ChatMarkdown text={block} mentionPeers={peers} everyone={!dm} mentionPerson={mentionPerson} message={{ threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} />} />+ ) : botText ? (+ <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={groupId} data-citation-thread={threadId}><ChatMarkdown text={botText} mentionPeers={peers} everyone={!dm} mentionPerson={mentionPerson} message={{ threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} /></div>+ ) : null}+ {replyGroup && <AttachmentGallery images={replyGroup.images} files={replyGroup.files} originals={replyGroup.originals} message={{ threadId, messageId: m.id }} eager={eager} beneath />}+ </MessageBoundary>+ )}+ </div>+ {!tabled && botActions}+ <span className="self-end pb-1 text-[11px] tabular-nums text-ink-tertiary opacity-0 transition-opacity group-hover:opacity-100">+ {formatTime(m.at)}+ </span>+ </div>+ <ReactionChips threadId={threadId} message={m} bots={members} align={user ? "end" : "start"} canReact={canReact} />+ <ForkLinks kind="group" ownerId={groupId} threadId={threadId} messageId={m.id} phone={phone} />+ {!user && m.routedBy && <RoutedByLine routedBy={m.routedBy} />}+ </div>+ );+}, sameRow);diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsxindex 332d8510ad..95b9e26425 100644--- a/src/components/message-menu.tsx+++ b/src/components/message-menu.tsx@@ -16,7 +16,7 @@ export function replyAndCopy(onReply: () => void, text: string): MessageMenuItem];}-export function roomPin(group: Group, message: Message, dispatch: ReturnType<typeof useStore>["dispatch"]): PinAction | undefined {+export function roomPin(group: Pick<Group, "id" | "pinnedMessageId">, message: Message, dispatch: ReturnType<typeof useStore>["dispatch"]): PinAction | undefined {if (window.ogb?.remoteClient?.active) return undefined;const pinned = group.pinnedMessageId === message.id;return {diff --git a/src/components/touch-actions.test.ts b/src/components/touch-actions.test.tsindex c933162dd5..1ceb08f4c8 100644--- a/src/components/touch-actions.test.ts+++ b/src/components/touch-actions.test.ts@@ -15,7 +15,7 @@ const styles = readFileSync(stylesPath, "utf8");// Keyed by file and a class-string snippet, so a stale entry fails instead of silently widening.const notActions: Array<{ file: string; snippet: string; why: string }> = [{ file: "components/ChatView.tsx", snippet: "self-end pb-1 text-[11px] tabular-nums", why: "message timestamp, informational" },- { file: "components/GroupView.tsx", snippet: "self-end pb-1 text-[11px] tabular-nums", why: "message timestamp, informational" },+ { file: "components/RoomTextMessage.tsx", snippet: "self-end pb-1 text-[11px] tabular-nums", why: "message timestamp, informational" },{ file: "components/ScreenFrame.tsx", snippet: "group-hover/image:opacity-100", why: "aria-hidden zoom hint; the whole image is the tap target" },{ file: "components/AttachmentPreview.tsx", snippet: "group-hover/image:opacity-100", why: "zoom hint; the whole image is the tap target" },{ file: "components/remote-desktop-panel.tsx", snippet: "bg-black/65 py-2", why: "caption; the whole preview is the tap target" },diff --git a/src/lib/markdown-stream-blocks.test.ts b/src/lib/markdown-stream-blocks.test.tsindex e19e1af5bc..9a1c4e5cf7 100644--- a/src/lib/markdown-stream-blocks.test.ts+++ b/src/lib/markdown-stream-blocks.test.ts@@ -1,16 +1,56 @@import { describe, expect, it } from "vitest";-import { closedFence, openFence, splitMarkdownBlocks } from "./markdown-stream-blocks";+import { closedFence, mayHoldMath, openFence, splitMarkdownBlocks, splitStreamPieces } from "./markdown-stream-blocks";describe("splitting streamed Markdown into blocks", () => {it("cuts at blank lines that close every block, and the pieces join back to the text", () => {- // A list marker after a blank line may still belong to what is above it, so it never starts a block.const text = "# Plan\n\nFirst paragraph\nstill first.\n\n- one\n- two\n\nLast";const blocks = splitMarkdownBlocks(text)!;- expect(blocks).toEqual(["# Plan\n\n", "First paragraph\nstill first.\n\n- one\n- two\n\n", "Last"]);+ expect(blocks).toEqual(["# Plan\n\n", "First paragraph\nstill first.\n\n", "- one\n- two\n\n", "Last"]);expect(blocks.join("")).toBe(text);});+ it("starts a block at a list marker only when nothing above it can still hold a list", () => {+ expect(splitMarkdownBlocks("Text\n\n1. one\n\n2. two")).toEqual(["Text\n\n", "1. one\n\n2. two"]);+ expect(splitMarkdownBlocks("Text\n- one\n\n- two")).toEqual(["Text\n- one\n\n- two"]);+ expect(splitMarkdownBlocks("Text\n\n indented\n\n- two")).toEqual(["Text\n\n indented\n\n- two"]);+ });++ it("treats only spaces and tabs as a blank line", () => {+ expect(splitMarkdownBlocks("one\n\u00a0\ntwo\n \t\nthree")).toEqual(["one\n\u00a0\ntwo\n \t\n", "three"]);+ });++ it("does not cut after indented code before a line it would be read as interrupting", () => {+ expect(splitMarkdownBlocks(" code\n\n> -\n\nText")).toEqual([" code\n\n> -\n\n", "Text"]);+ expect(splitMarkdownBlocks(" code\n\nText")).toEqual([" code\n\n", "Text"]);+ });++ it("cuts around HTML that ends at a blank line, and keeps HTML that runs past them whole", () => {+ expect(splitMarkdownBlocks("<details>\n\nhidden\n\n</details>\n\nAfter")).toEqual(["<details>\n\n", "hidden\n\n", "</details>\n\n", "After"]);+ expect(splitMarkdownBlocks("<pre>\na\n\nb\n</pre>\n\nAfter")).toEqual(["<pre>\na\n\nb\n</pre>\n\n", "After"]);+ expect(splitMarkdownBlocks("Text\n<!-- a\n\nb -->\n\nAfter")).toEqual(["Text\n<!-- a\n\nb -->\n\n", "After"]);+ expect(splitMarkdownBlocks("<!DOCTYPE html>\n\n<?x ?>\n\nAfter")).toEqual(["<!DOCTYPE html>\n\n", "<?x ?>\n\n", "After"]);+ expect(splitMarkdownBlocks("One\n\n<script>\n\nnever closed\n\nmore")).toEqual(["One\n\n", "<script>\n\nnever closed\n\nmore"]);+ // Inside an HTML block a fence line is text, so the fence it seems to open cannot be trusted.+ expect(splitMarkdownBlocks("One\n\n<br>\n~~~\n\ncode\n~~~\n\nmore")).toEqual(["One\n\n", "<br>\n~~~\n\ncode\n~~~\n\nmore"]);+ });++ it("cuts around display math that stands alone, and stops cutting at any other display delimiter", () => {+ expect(splitMarkdownBlocks("One\n\n$$\nx\n\ny\n$$\n\nTwo\n\n\\[\nz\n\\]\n\nThree")).toEqual(["One\n\n", "$$\nx\n\ny\n$$\n\n", "Two\n\n", "\\[\nz\n\\]\n\n", "Three"]);+ expect(splitMarkdownBlocks("$$x^2$$\n\nOne\n\n\\[ y \\]\n\nTwo")).toEqual(["$$x^2$$\n\n", "One\n\n", "\\[ y \\]\n\n", "Two"]);+ expect(splitMarkdownBlocks("With \\(a\\) inline\n\nand $b$\n\nEnd")).toEqual(["With \\(a\\) inline\n\n", "and $b$\n\n", "End"]);+ for (const [text, kept] of [+ ["One\n\n$$\nx\n\nnever closed\n\nmore", "$$\nx\n\nnever closed\n\nmore"],+ ["One\n\nValue $$x\n\ny$$ here\n\nmore", "Value $$x\n\ny$$ here\n\nmore"],+ ["One\n\nOpen \\( a\n\nb \\) closed\n\nmore", "Open \\( a\n\nb \\) closed\n\nmore"],+ ["One\n\n$$ meta\nx\n\nmore", "$$ meta\nx\n\nmore"],+ ["One\n\n- item\n $$\n x\n $$\n\nmore", "- item\n $$\n x\n $$\n\nmore"],+ ["One\n\n$$\nx `y`\n$$\n\nmore", "$$\nx `y`\n$$\n\nmore"],+ ["One\n\nRun `echo $$` now\n\nmore", "Run `echo $$` now\n\nmore"],+ ] as const) expect(splitMarkdownBlocks(text), text).toEqual(["One\n\n", kept]);+ expect(splitMarkdownBlocks("```sh\necho $$\n```\n\nOne\n\nTwo"), "a fence hides its delimiters").toEqual(["```sh\necho $$\n```\n\n", "One\n\n", "Two"]);+ });+it("keeps a loose list and indented content in one block", () => {const text = "- one\n\n- two\n\n more of two\n\nAfter";expect(splitMarkdownBlocks(text)).toEqual(["- one\n\n- two\n\n more of two\n\n", "After"]);@@ -34,15 +74,67 @@ describe("splitting streamed Markdown into blocks", () => {for (const text of ["See [the docs][1].\n\n[1]: https://example.com","A claim.[^1]\n\n[^1]: The source.",- "<details>\n\nhidden\n\n</details>",- "$$\nx^2\n\n$$",- "\\[\na\n\\]",- "::: note\n\nbody\n:::","Line\r\n\r\nother",]) expect(splitMarkdownBlocks(text), text).toBeNull();});});+describe("cutting a streamed list or table into pieces", () => {+ const list = (items: string[], loose = false, lead = "") => ({ kind: "list", lead, items, loose });++ it("cuts a tight list at its top-level items", () => {+ expect(splitStreamPieces("- one\n- two\n - nested\n more\n- thr")).toEqual(list(["- one\n", "- two\n - nested\n more\n", "- thr"]));+ expect(splitStreamPieces("7. one\n8. two\n\n")).toEqual(list(["7. one\n", "8. two\n\n"]));+ expect(splitStreamPieces("- one\n ```\n a\n\n b\n ```\n- two")).toEqual(list(["- one\n ```\n a\n\n b\n ```\n", "- two"]));+ });++ it("marks a list loose once a blank line separates two items", () => {+ expect(splitStreamPieces("1. one\n\n body\n\n2. two")).toEqual(list(["1. one\n\n body\n\n", "2. two"], true));+ expect(splitStreamPieces("- one\n- two\n\n- three")).toEqual(list(["- one\n", "- two\n\n", "- three"], true));+ });++ it("leaves a list whole when a blank line may make it loose without separating items", () => {+ expect(splitStreamPieces("- one\n\n body\n- two")).toBeNull();+ expect(splitStreamPieces("- one\n - a\n\n - b\n- two")).toBeNull();+ });++ it("keeps a paragraph line above the list as its lead", () => {+ expect(splitStreamPieces("Steps:\n- one\n- two")).toEqual(list(["- one\n", "- two"], false, "Steps:\n"));+ expect(splitStreamPieces("Steps:\n1. one\n2. two")).toEqual(list(["1. one\n", "2. two"], false, "Steps:\n"));+ for (const text of ["Year\n2. two\n3. three", "Text\n-\n- two", "Text\n- - x\n- two", "<div>\n- one\n- two", "a | b\n- | -\n- x"]) expect(splitStreamPieces(text), text).toBeNull();+ });++ it("lets digits that may become the next marker stay with the last item", () => {+ expect(splitStreamPieces("1. one\n2. two\n12")).toEqual(list(["1. one\n", "2. two\n12"]));+ expect(splitStreamPieces("- one\n- two\n12")).toBeNull();+ });++ it("leaves a list whole when a line is not plainly an item or inside one", () => {+ for (const text of [+ "- one\n* two", "1. one\n2) two", "- one\n- - -\n- two", "- one\n---\n- two", "- one\nlazy\n- two", "1. one\n - under-indented\n2. two",+ "- one\n ```\n code\n- two", "-\n\n not inside\n- two", "- one\n <div>\n- two", "- one\n\t- tab\n- two", "- costs $5\n- two", "- \\(x\\)\n- two",+ ]) expect(splitStreamPieces(text), text).toBeNull();+ });++ it("cuts a table into its header and rows", () => {+ expect(splitStreamPieces("| a | b |\n|---|:-:|\n| 1 | 2 |\n| 3 |")).toEqual({ kind: "table", head: "| a | b |\n|---|:-:|\n", rows: ["| 1 | 2 |\n", "| 3 |"] });+ expect(splitStreamPieces("| a | b |\n|---|---|\n| 1 | 2 |\n\n")).toEqual({ kind: "table", head: "| a | b |\n|---|---|\n", rows: ["| 1 | 2 |\n\n"] });+ expect(splitStreamPieces("| a | b |\n|---|---|")).toEqual({ kind: "table", head: "| a | b |\n|---|---|", rows: [] });+ });++ it("leaves a table whole until its header is certain and while a row may not be one", () => {+ for (const text of [+ "| a | b |", "| a | b |\n|---|", "| a | b |\n|---|---|---|", "| a |\n|---|\n| 1 |", "| `a` | b |\n|---|---|\n| 1 | 2 |", "a | b\n--|--\n1 | 2",+ "| a | b |\n|---|---|\n| 1 | 2 |\n3 | 4", "| a | b |\n|---|---|\n| 1 | 2 |\n> quote", "| a | b |\n|---|---|\n| $1 | 2 |",+ ]) expect(splitStreamPieces(text), text).toBeNull();+ });++ it("knows which text math normalization leaves alone", () => {+ expect(["plain `code` | text", "a (b) [c]"].map(mayHoldMath)).toEqual([false, false]);+ expect(["$5", "\\(x\\)", "\\[x\\]", "a\u0000b"].map(mayHoldMath)).toEqual([true, true, true, true]);+ });+});+describe("a fence still being written", () => {it("is read without parsing while it has no closing line", () => {expect(openFence("```ts wrap\nconst a = 1;\nconst b")).toEqual({ info: "ts wrap", code: "const a = 1;\nconst b" });diff --git a/src/lib/markdown-stream-blocks.ts b/src/lib/markdown-stream-blocks.tsindex 870c4b06e6..594ed52a31 100644--- a/src/lib/markdown-stream-blocks.ts+++ b/src/lib/markdown-stream-blocks.ts@@ -1,12 +1,30 @@-// Definitions, footnotes, raw HTML, container directives and display math can tie blocks together.-const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$|\\\[)|\[\^/m;+// Reference definitions and footnotes are resolved across the whole text.+const DOCUMENT_WIDE_SYNTAX = /^ {0,3}\[[^\]\n]+\]:|\[\^/m;const FENCE_OPENER = /^ {0,3}(`{3,}|~{3,})/;-// After a blank line these still continue the previous block: a list item or indented content.-const CONTINUATION = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;+const LIST_MARKER = /^(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)/;+const BLANK = /^[ \t]*$/;+// CommonMark 0.31 HTML blocks of kinds 1 to 5 run past blank lines until their own end marker.+const LONG_HTML = /^ {0,3}<(?:(script|pre|style|textarea)(?=[\s>]|$)|(!--)|(\?)|(!\[CDATA\[)|(![A-Za-z]))/i;+const LONG_HTML_ENDS = [/<\/(?:script|pre|style|textarea)>/i, /-->/, /\?>/, /\]\]>/, />/];+const SHORT_HTML = /^ {0,3}<[A-Za-z/]/;+const MATH_DELIMITER = /\$\$|\\[[\]()]/;+const MATH_UNSAFE = /\$\$|\\[[\]()]|`|~~~|\]\(/;+const ONE_LINE_MATH = /^(?:\$\$(?!\$)(.+)(?<!\$)\$\$|\\\[(.+)\\\])$/;++/** Whether math normalization could change `text`: without these it is returned as it came. */+export function mayHoldMath(text: string): boolean {+ return text.includes("$") || text.includes("\\(") || text.includes("\\[") || text.includes("\u0000");+}++/** A line whose only math delimiters are `\(…\)` pairs that open and close on it. */+function inlineMathOnly(line: string): boolean {+ return !/\$\$|\\[[\]]|`|\]\(/.test(line) && !/\\[()]/.test(line.replace(/\\\(.*?\\\)/g, ""));+}/*** Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it would inside the whole- * text. Null when the text uses syntax that spans blocks.+ * text. Null when the text uses syntax that spans blocks. Display math is cut around only when it stands alone from+ * column one (`$$` or `\[` lines, or one line holding both ends); after any other display delimiter nothing is cut.*/export function splitMarkdownBlocks(text: string): string[] | null {if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;@@ -15,23 +33,60 @@ export function splitMarkdownBlocks(text: string): string[] | null {let lineStart = 0;let fence: string | null = null;let fenceIndent = 0;- let afterBlankLine = false;+ let htmlEnd: RegExp | null = null;+ let mathEnd: string | null = null;+ let afterBlankLine = true;+ let listLike = false;+ let maybeHtml = false;+ let afterCode = false;for (const line of text.split("\n")) {const opener = FENCE_OPENER.exec(line)?.[1];if (fence !== null) {// A line left of an indented fence may end the list item holding it, which is not tracked.if (/\S/.test(line.slice(0, fenceIndent))) break;if (opener && opener[0] === fence[0] && opener.length >= fence.length && line.trim() === opener) fence = null;- } else if (line.trim() === "") {+ } else if (mathEnd !== null) {+ if (line === mathEnd) mathEnd = null;+ else if (MATH_UNSAFE.test(line)) break;+ } else if (htmlEnd !== null) {+ if (MATH_DELIMITER.test(line)) break;+ if (htmlEnd.test(line)) htmlEnd = null;+ } else if (BLANK.test(line)) {afterBlankLine = true;+ maybeHtml = false;} else {- if (afterBlankLine && lineStart > blockStart && !CONTINUATION.test(line)) {+ // Up to its blank line an HTML block holds fence lines as text, and whether a tag opens one is not tracked.+ // A tag line inside an HTML block is its text, not the start of one that runs past blank lines.+ if (maybeHtml && LONG_HTML.test(line)) break;+ maybeHtml ||= SHORT_HTML.test(line);+ if (maybeHtml && opener) break;+ const marker = LIST_MARKER.test(line);+ // micromark 4 reads the line after indented code as interrupting it, which changes what a quote, a tag or a+ // table row there opens.+ const continues = marker ? listLike : /^[ \t]/.test(line) || (afterCode && /^>|[<|]/.test(line));+ if (afterBlankLine && lineStart > blockStart && !continues) {blocks.push(text.slice(blockStart, lineStart));blockStart = lineStart;+ listLike = false;}+ if (MATH_DELIMITER.test(line)) {+ const opensBlock = afterBlankLine && lineStart === blockStart;+ if (opensBlock && (line === "$$" || line === "\\[")) mathEnd = line === "$$" ? "$$" : "\\]";+ else if (opensBlock && ONE_LINE_MATH.test(line)) {+ const inner = ONE_LINE_MATH.exec(line)!;+ if (MATH_UNSAFE.test(inner[1] ?? inner[2]!)) break;+ } else if (!inlineMathOnly(line)) break;+ }+ listLike ||= marker || /^[ \t]/.test(line);+ afterCode = /^(?: {4}|\t)/.test(line);afterBlankLine = false;fence = opener ?? null;if (opener) fenceIndent = line.indexOf(opener);+ const html = fence === null && mathEnd === null ? LONG_HTML.exec(line) : null;+ if (html) {+ const end = LONG_HTML_ENDS[html.slice(1).findIndex((kind) => kind !== undefined)]!;+ if (!end.test(line.slice(html[0].length))) htmlEnd = end;+ }}lineStart += line.length + 1;}@@ -39,6 +94,114 @@ export function splitMarkdownBlocks(text: string): string[] | null {return blocks;}+/** A streamed block that is one list or one table, cut so that only its last piece is still being written. */+export type StreamPieces =+ | { kind: "list"; lead: string; items: string[]; loose: boolean }+ | { kind: "table"; head: string; rows: string[] };++const TABLE_HEADER = /^\|[^`\\]*\| *$/;+const TABLE_DELIMITER = /^\|(?: *:?-+:? *\|)+ *$/;+const pipes = (line: string) => line.split("|").length - 1;++function tablePieces(lines: string[]): StreamPieces | null {+ const [header, delimiter] = lines;+ if (delimiter === undefined || !TABLE_HEADER.test(header!) || !TABLE_DELIMITER.test(delimiter)) return null;+ // One column is left whole: table repair rewrites some of its rows.+ if (pipes(header!) < 3 || pipes(header!) !== pipes(delimiter)) return null;+ const rows: string[] = [];+ for (let index = 2; index < lines.length; index++) {+ const line = lines[index]!;+ if (line.startsWith("|")) rows.push(index < lines.length - 1 ? `${line}\n` : line);+ else if (BLANK.test(line) && lines.slice(index).every((rest) => BLANK.test(rest))) {+ const tail = lines.slice(index).join("\n");+ if (rows.length === 0) return null;+ rows[rows.length - 1] += tail;+ break;+ } else return null;+ }+ return { kind: "table", head: lines.length > 2 ? `${header}\n${delimiter}\n` : `${header}\n${delimiter}`, rows };+}++const ITEM = /^([-*+]|\d{1,9}([.)]))(?:( +)(.*))?$/;+const THEMATIC_BREAK = /^([-*_])(?: *\1){2,} *$/;+const ANY_FENCE = /^( *)(`{3,}|~{3,})/;+const LEAD_UNSAFE = /^[ <>|`~]|\|/;+const LEAD_ITEM = /^[\p{L}\p{N}*_`[("']/u;++function listPieces(text: string, lines: string[]): StreamPieces | null {+ const first = lines.findIndex((line) => ITEM.test(line));+ if (first < 0) return null;+ const opening = ITEM.exec(lines[first]!)!;+ const kind = opening[2] ?? opening[1]!;+ if (first > 0) {+ // Below a paragraph only a bullet with text, or "1" with text, starts a list, and what that text may open differs.+ if (lines.slice(0, first).some((line) => BLANK.test(line) || LEAD_UNSAFE.test(line))) return null;+ if (opening[2] !== undefined && opening[1] !== `1${opening[2]}`) return null;+ if ((opening[3] ?? "").length > 4 || !LEAD_ITEM.test(opening[4] ?? "") || ITEM.test(opening[4]!)) return null;+ }+ const starts: number[] = [];+ let offset = 0;+ let at = 0;+ let fence: { mark: string; indent: number } | null = null;+ let blank = false;+ let blankInside = false;+ let blankBetween = false;+ for (const [index, line] of lines.entries()) {+ const lineStart = at;+ at += line.length + 1;+ if (index < first) continue;+ if (fence) {+ if (/\S/.test(line.slice(0, fence.indent))) return null;+ const closer = ANY_FENCE.exec(line)?.[2];+ if (closer && closer[0] === fence.mark[0] && closer.length >= fence.mark.length && line.trim() === closer) fence = null;+ continue;+ }+ if (BLANK.test(line)) {+ blank = true;+ continue;+ }+ let body = line;+ if (line[0] !== " ") {+ const item = ITEM.exec(line);+ if (item && (item[2] ?? item[1]) === kind && !THEMATIC_BREAK.test(line)) {+ if (blank) blankBetween = true;+ starts.push(lineStart);+ const content = item[4] ?? "";+ const gap = item[3]?.length ?? 0;+ const code = content !== "" && gap > 4;+ offset = item[1]!.length + (content === "" || code ? 1 : gap);+ body = code ? "" : " ".repeat(offset) + content;+ // An item that opens with an empty line holds only what follows that line directly.+ if (content === "" && BLANK.test(lines[index + 1] ?? "x") && lines.slice(index + 2).find((rest) => !BLANK.test(rest))?.[0] === " ") return null;+ } else if (!(index === lines.length - 1 && !blank && opening[2] !== undefined && /^\d{1,9}$/.test(line))) {+ // Only digits that may yet become this list's next marker are let through as a last line.+ return null;+ }+ } else {+ if (line.length - line.trimStart().length < offset) return null;+ if (blank) blankInside = true;+ }+ blank = false;+ // An HTML block inside an item holds fence lines as text, which the fence tracking here would misread.+ if (body.trimStart().startsWith("<")) return null;+ const opener = ANY_FENCE.exec(body);+ if (opener) fence = { mark: opener[2]!, indent: opener[1]!.length };+ }+ if (blankInside && !blankBetween) return null;+ return { kind: "list", lead: text.slice(0, starts[0]), items: starts.map((start, index) => text.slice(start, starts[index + 1])), loose: blankBetween };+}++/**+ * Cuts a block that is one list into its top-level items, or one table into its header and rows, when each piece+ * parsed alone gives what it gives inside the block. Null for anything else, and for text that normalization or table+ * repair could rewrite.+ */+export function splitStreamPieces(block: string): StreamPieces | null {+ if (mayHoldMath(block) || /[\t\r]/.test(block)) return null;+ const lines = block.split("\n");+ return block.startsWith("|") ? tablePieces(lines) : listPieces(block, lines);+}+/** A block that is one code fence still being written, from its first column: its info string and code so far. */export function openFence(block: string): { info: string; code: string } | null {const newline = block.indexOf("\n");diff --git a/src/lib/markdown-stream-pieces.ts b/src/lib/markdown-stream-pieces.tsnew file mode 100644index 0000000000..eea4f47971--- /dev/null+++ b/src/lib/markdown-stream-pieces.ts@@ -0,0 +1,86 @@+import { cloneElement, createElement, Fragment, isValidElement, type ReactElement, type ReactNode } from "react";++import type { StreamPieces } from "./markdown-stream-blocks";++interface HastElement {+ type: "element";+ tagName: string;+ children: unknown[];+}++type Parsed = ReactElement<{ children?: ReactNode; node?: HastElement }>;++/** Parses one piece of Markdown; a cache key keeps the result, and `loose` draws its list as a loose one. */+export type ParsePiece = (source: string, cacheKey: string | null, loose?: boolean) => ReactElement;++/** Wraps the nodes of the list item at `index`; `source` is that item's Markdown while its list is still being written. */+export type ItemScope = (nodes: ReactNode[], index: number, source: string | null) => ReactNode;++const KEY = "\u0004";++const nodes = (children: ReactNode): ReactNode[] => (children === undefined || children === null ? [] : Array.isArray(children) ? children : [children]);+const elements = (children: ReactNode): Parsed[] => nodes(children).filter((child): child is Parsed => isValidElement(child));++/** The one top-level element a piece parsed to, when it is a `tags` element. */+function only(parsed: ReactElement, tags: readonly string[]): Parsed | null {+ const top = nodes((parsed as Parsed).props.children);+ const element = top.length === 1 && isValidElement(top[0]) ? (top[0] as Parsed) : null;+ return element?.props.node && tags.includes(element.props.node.tagName) ? element : null;+}++const merged = (tagName: string, children: unknown[]): HastElement => ({ type: "element", tagName, children });++function joinList(lead: ReactElement | null, items: ReactElement[], sources: string[] | null, scope: ItemScope): ReactNode | null {+ const lists = items.map((item) => only(item, ["ul", "ol"]));+ const first = lists[0];+ if (!first?.props.node) return null;+ const tagName = first.props.node.tagName;+ const children: ReactNode[] = [];+ for (const [index, list] of lists.entries()) {+ const inner = list?.props.node?.tagName === tagName ? nodes(list.props.children) : [];+ if (inner[0] !== "\n" || elements(inner).length !== 1) return null;+ children.push(scope(index === 0 ? inner : inner.slice(1), index, sources?.[index] ?? null));+ }+ const list = cloneElement(first, { node: merged(tagName, lists.map((each) => each!.props.node)) }, children);+ return lead ? createElement(Fragment, null, lead, "\n", list) : list;+}++function joinTable(head: ReactElement, rows: ReactElement[]): ReactNode | null {+ const table = only(head, ["table"]);+ if (!table?.props.node || elements(table.props.children).some((section) => section.type !== "thead")) return null;+ if (rows.length === 0) return head;+ const bodies: Parsed[] = [];+ const bodyNodes: unknown[] = [];+ for (const row of rows) {+ const node = only(row, ["table"])?.props.node;+ const body = elements(only(row, ["table"])?.props.children).find((section) => section.type === "tbody");+ const bodyNode = node?.children.find((child) => (child as HastElement).tagName === "tbody");+ if (!body || !bodyNode || elements(body.props.children).length !== 1) return null;+ bodies.push(body);+ bodyNodes.push(bodyNode);+ }+ const body = cloneElement(bodies[0]!, {}, bodies.map((each) => nodes(each.props.children)));+ return cloneElement(table, { node: merged("table", [table.props.node, ...bodyNodes]) }, [...nodes(table.props.children), body]);+}++/**+ * Draws a list or table from its pieces: every piece but the one still being written comes from the cache, and the+ * result is the element the whole block would parse to. Null when a piece did not parse to the shape its cut assumed.+ */+export function drawStreamPieces(pieces: StreamPieces, open: boolean, parse: ParsePiece, scope: ItemScope): ReactNode | null {+ if (pieces.kind === "table") {+ const last = open ? pieces.rows.length - 1 : -1;+ return joinTable(+ parse(pieces.head, open && last < 0 ? null : `${KEY}head${KEY}${pieces.head}`),+ pieces.rows.map((row, index) => parse(pieces.head + row, index === last ? null : `${KEY}row${KEY}${pieces.head}${row}`)),+ );+ }+ const last = open ? pieces.items.length - 1 : -1;+ const kind = pieces.loose ? "loose" : "tight";+ return joinList(+ pieces.lead ? parse(pieces.lead, `${KEY}lead${KEY}${pieces.lead}`) : null,+ pieces.items.map((item, index) => parse(item, index === last ? null : `${KEY}${kind}${KEY}${item}`, pieces.loose)),+ open ? pieces.items : null,+ scope,+ );+}