Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Draw each finished message from one Markdown rendering (#4171)

Milind Soni47b66e041410
diff --git a/scripts/bench-desktop.ts b/scripts/bench-desktop.ts
index 33786f4317..d9a7c59762 100644
--- a/scripts/bench-desktop.ts
+++ b/scripts/bench-desktop.ts
@@ -649,7 +649,12 @@ async function main() {
await sleep(1_000);
const back = await switchTo(seeded.bigBotId, seeded.bigLastMessageId);
await sleep(1_000);
- big.switchConversation = { toSmall: away, backToBig: back };
+ const awayAgain = await switchTo(seeded.otherBotId, null);
+ await sleep(1_000);
+ const backAgain = await switchTo(seeded.bigBotId, seeded.bigLastMessageId);
+ await sleep(1_000);
+ // The first visit draws the conversation for the first time; the second is what a return to it costs.
+ big.switchConversation = { toSmall: away, backToBig: back, toSmallAgain: awayAgain, backToBigAgain: backAgain };
const memoryBefore = await page.metrics();
const box = await page.evaluate<{ x: number; y: number; rows: number; nodes: number; top: number; height: number } | null>(TRANSCRIPT_BOX);
if (!box) big.scroll = { error: "no scrolling transcript" };
@@ -693,6 +698,7 @@ async function main() {
await slice("CSS animations paused and no animation frames", "window.requestAnimationFrame = () => 0"),
];
await page.close();
+ log("big workspace: profiling build");
const preview = await serveDist(profileDist, fixture.url);
const profiled = await chrome.newPage({ storage: STORAGE });
await pageLoad(profiled, preview.url);
@@ -711,9 +717,12 @@ async function main() {
groups: componentGroups({ ...snapshot.renders, ...Object.fromEntries(Object.entries(snapshot.mounts).map(([name, n]) => [name, n + (snapshot.renders[name] ?? 0)])) }, snapshot.selfMs),
topSelfMs: Object.fromEntries(topSelf.map(([name, ms]) => [name, Math.round(ms)])), longestTaskMs: Math.max(0, ...snapshot.longTasks.map((task) => task[1])) };
};
+ log("big workspace: switching conversations");
const awayProfiled = await profiledSwitch(seeded.otherBotId, null);
const backProfiled = await profiledSwitch(seeded.bigBotId, seeded.bigLastMessageId);
- big.switchProfiled = { toSmall: awayProfiled, backToBig: backProfiled };
+ const awayAgainProfiled = await profiledSwitch(seeded.otherBotId, null);
+ const backAgainProfiled = await profiledSwitch(seeded.bigBotId, seeded.bigLastMessageId);
+ big.switchProfiled = { toSmall: awayProfiled, backToBig: backProfiled, toSmallAgain: awayAgainProfiled, backToBigAgain: backAgainProfiled };
log("streaming a reply, big workspace");
big.stream = await streamTurn(chrome, profiled, fixture, seeded.bigBotId);
await profiled.close();
diff --git a/scripts/testing/bench-desktop-page.ts b/scripts/testing/bench-desktop-page.ts
index fcea6441c6..8560afd854 100644
--- a/scripts/testing/bench-desktop-page.ts
+++ b/scripts/testing/bench-desktop-page.ts
@@ -10,6 +10,7 @@ import { join } from "node:path";
import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";
type Params = Record<string, unknown>;
+const CDP_ANSWER_MS = 120_000;
class Cdp {
private nextId = 0;
@@ -18,6 +19,10 @@ class Cdp {
private socket: WebSocket;
constructor(socket: WebSocket) {
this.socket = socket;
+ socket.addEventListener("close", () => {
+ for (const waiter of this.pending.values()) waiter.reject(new Error(`${waiter.method}: Chrome closed the connection`));
+ this.pending.clear();
+ });
socket.addEventListener("message", (event) => {
const message = JSON.parse(String(event.data)) as { id?: number; result?: Params; error?: { message: string }; method?: string; params?: Params; sessionId?: string };
if (message.id !== undefined) {
@@ -33,7 +38,12 @@ class Cdp {
send(method: string, params: Params = {}, sessionId?: string): Promise<Params> {
const id = (this.nextId += 1);
return new Promise((resolve, reject) => {
- this.pending.set(id, { resolve, reject, method });
+ // A page stuck in a loop never answers: fail by name rather than wait forever.
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`${method}: no answer in ${CDP_ANSWER_MS / 1000} s`));
+ }, CDP_ANSWER_MS);
+ this.pending.set(id, { resolve: (value) => { clearTimeout(timer); resolve(value); }, reject: (error) => { clearTimeout(timer); reject(error); }, method });
this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
});
}
diff --git a/src/components/ChatMarkdown.renderers.test.ts b/src/components/ChatMarkdown.renderers.test.ts
index f812fb6779..38129a31f1 100644
--- a/src/components/ChatMarkdown.renderers.test.ts
+++ b/src/components/ChatMarkdown.renderers.test.ts
@@ -19,7 +19,7 @@ vi.mock("mdast-util-from-markdown", async (importOriginal) => {
});
import { fromMarkdown } from "mdast-util-from-markdown";
-import { ChatMarkdown } from "./ChatMarkdown";
+import { ChatMarkdown, clearChatMarkdownCache } from "./ChatMarkdown";
import { ThreadRefsContext, type ThreadRefsValue } from "./ThreadRefs";
const qa = { botId: "scout", botName: "Scout", threadId: "qa-245", title: "QA PR 245", activeAt: 1 };
@@ -30,6 +30,7 @@ const after: ThreadRefsValue = {
};
function markdownProps(refs: ThreadRefsValue, text: string): Record<string, unknown> {
+ clearChatMarkdownCache();
captured.length = 0;
renderToStaticMarkup(createElement(ThreadRefsContext.Provider, { value: refs },
createElement(ChatMarkdown, { text, message: { threadId: "t", messageId: "m" } })));
@@ -99,3 +100,42 @@ describe("ChatMarkdown normalization", () => {
expect(fromMarkdown).toHaveBeenCalledOnce();
});
});
+
+describe("ChatMarkdown rendered once per message", () => {
+ const draw = (text: string, extra: Record<string, unknown> = {}, refs: ThreadRefsValue = before) => {
+ renderToStaticMarkup(createElement(ThreadRefsContext.Provider, { value: refs },
+ createElement(ChatMarkdown, { text, message: { threadId: "t", messageId: "m" }, ...extra })));
+ };
+ const parses = (run: () => void) => {
+ captured.length = 0;
+ run();
+ return captured.length;
+ };
+ beforeEach(() => clearChatMarkdownCache());
+
+ it("draws a message again from its first rendering", () => {
+ const text = "## Plan\n\n- one\n- two with `code`";
+ expect(parses(() => draw(text))).toBe(1);
+ expect(parses(() => { draw(text); draw(text); })).toBe(0);
+ expect(parses(() => draw(`${text}\n- three`))).toBe(1);
+ });
+
+ it("renders a message again only when what its plugins read changes", () => {
+ const plain = "No names in this one.";
+ const named = "Ask @Atlas about it.";
+ expect(parses(() => { draw(plain, { mentionPeers: [{ name: "Atlas" }] }); draw(named, { mentionPeers: [{ name: "Atlas" }] }); })).toBe(2);
+ // A new peer list with the same names is the same rendering; a renamed or recoloured peer is not.
+ expect(parses(() => { draw(plain, { mentionPeers: [{ name: "Juno" }] }); draw(named, { mentionPeers: [{ name: "Atlas" }] }); })).toBe(0);
+ expect(parses(() => draw(named, { mentionPeers: [{ name: "Atlas", color: "red" }] }))).toBe(1);
+ expect(parses(() => draw(named, { mentionPeers: [{ name: "Atlas", color: "red" }], everyone: true }))).toBe(1);
+ });
+
+ it("renders a message that may link a thread again when the thread list changes", () => {
+ const text = "Tracked in #QA PR 245.";
+ expect(parses(() => draw(text, {}, before))).toBe(1);
+ expect(parses(() => draw(text, {}, before))).toBe(0);
+ expect(parses(() => draw(text, {}, after))).toBe(1);
+ expect(parses(() => draw("Nothing to link.", {}, before))).toBe(1);
+ expect(parses(() => draw("Nothing to link.", {}, after))).toBe(0);
+ });
+});
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index f72e7c6f7f..2c4a914be0 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -1,6 +1,6 @@
// Security: model output never reaches the DOM as raw HTML (no rehype-raw); Shiki's output is generator-escaped.
import { createContext, memo, use, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react";
-import Markdown, { defaultUrlTransform, type Components, type ExtraProps } from "react-markdown";
+import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Options as MarkdownOptions } from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { fromMarkdown, type Options as MarkdownParseOptions } from "mdast-util-from-markdown";
@@ -10,6 +10,7 @@ import { t } from "@/lib/i18n";
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 { parseFenceInfo } from "../lib/code-block";
import { markdownImageName, markdownImageOpenUrl } from "../lib/markdown-image";
@@ -716,6 +717,41 @@ const MARKDOWN_COMPONENTS: Components = {
const MAY_LINK_THREAD = /#[^\s#]|openmausbot/i;
const NO_THREAD_REFS: ThreadRefsValue = { threads: [] };
+// One plugin list for everything every message shares; a message adds mentions only when it has an "@" and thread
+// links only when it may name one, so most messages render the same way whatever the bot list holds.
+const BASE_REMARK_PLUGINS: NonNullable<MarkdownOptions["remarkPlugins"]> = [remarkGfm, remarkMath, remarkWindowsPathDestinations, unwrapLinkedImages, remarkSoftBreaks, remarkGithubRefs];
+const NO_REHYPE_PLUGINS: NonNullable<MarkdownOptions["rehypePlugins"]> = [];
+let katexPlugins: { plugin: KatexPlugin; list: NonNullable<MarkdownOptions["rehypePlugins"]> } | null = null;
+const rehypePluginsFor = (math: KatexPlugin | null) => {
+ if (!math) return NO_REHYPE_PLUGINS;
+ if (katexPlugins?.plugin !== math) katexPlugins = { plugin: math, list: [math] };
+ return katexPlugins.list;
+};
+
+const markdownCache = createMarkdownRenderCache();
+const peerSignatures = new WeakMap<readonly MentionPeer[], string>();
+const peerSignature = (peers: readonly MentionPeer[]) => {
+ let signature = peerSignatures.get(peers);
+ if (signature === undefined) {
+ signature = peers.map((peer) => `${peer.name}\u0001${peer.hidden ? 1 : 0}${peer.person ? 1 : 0}${peer.color ?? ""}`).join("\u0002");
+ peerSignatures.set(peers, signature);
+ }
+ return signature;
+};
+// The thread list keeps its identity while its contents hold (ThreadRefsProvider), so a number per list stands for it.
+const threadListIds = new WeakMap<object, number>();
+let threadListCount = 0;
+const threadListId = (threads: object) => {
+ let id = threadListIds.get(threads);
+ if (id === undefined) threadListIds.set(threads, (id = ++threadListCount));
+ return id;
+};
+
+/** Test seam: drops every cached message. */
+export function clearChatMarkdownCache(): void {
+ markdownCache.clear();
+}
+
function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS, everyone = false, mentionPerson, delivered }: {
text: string; message?: MessageAttachmentContext;
mentionPeers?: readonly MentionPeer[]; everyone?: boolean; mentionPerson?: MentionPerson;
@@ -742,18 +778,18 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
};
}, [needsMath]);
const mathPlugin = needsMath && katexReady ? katexPlugin : null;
+ const mentions = source.includes("@"), linksThreads = threads.length > 0;
+ 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.
+ const markdown = markdownCache.render(text, variant, () => {
+ 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 });
+ });
return (
<MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered }}>
- <div className="chat-md min-w-0 [&>*+*]:mt-2">
- <Markdown
- remarkPlugins={[remarkGfm, remarkMath, remarkWindowsPathDestinations, unwrapLinkedImages, remarkSoftBreaks, remarkGithubRefs, [remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }], remarkThreadRefs(threads, currentBotId)]}
- rehypePlugins={mathPlugin ? [mathPlugin] : []}
- urlTransform={chatUrlTransform}
- components={MARKDOWN_COMPONENTS}
- >
- {source}
- </Markdown>
- </div>
+ <div className="chat-md min-w-0 [&>*+*]:mt-2">{markdown}</div>
</MessageScopeContext.Provider>
);
}
diff --git a/src/lib/markdown-render-cache.test.ts b/src/lib/markdown-render-cache.test.ts
new file mode 100644
index 0000000000..5bea52b7ab
--- /dev/null
+++ b/src/lib/markdown-render-cache.test.ts
@@ -0,0 +1,45 @@
+import { createElement } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { createMarkdownRenderCache, MARKDOWN_BYTES_PER_CHAR } from "./markdown-render-cache";
+
+const element = (text: string) => createElement("p", null, text);
+
+describe("markdown render cache", () => {
+ it("keeps a rendering per text and variant", () => {
+ const cache = createMarkdownRenderCache();
+ const render = vi.fn(() => element("a"));
+ const first = cache.render("a", "v1", render);
+ expect(cache.render("a", "v1", render)).toBe(first);
+ expect(render).toHaveBeenCalledTimes(1);
+ const other = cache.render("a", "v2", render);
+ expect(other).not.toBe(first);
+ expect(render).toHaveBeenCalledTimes(2);
+ expect(cache.size).toBe(1);
+ expect(cache.bytes).toBe(MARKDOWN_BYTES_PER_CHAR);
+ });
+
+ it("lets the least recently drawn text go first when the budget is spent", () => {
+ const cache = createMarkdownRenderCache(30 * MARKDOWN_BYTES_PER_CHAR);
+ const text = (name: string) => name.repeat(10);
+ for (const name of ["a", "b", "c"]) cache.render(text(name), "", () => element(name));
+ cache.render(text("a"), "", () => element("again"));
+ cache.render(text("d"), "", () => element("d"));
+ expect(cache.size).toBe(3);
+ expect(cache.bytes).toBe(30 * MARKDOWN_BYTES_PER_CHAR);
+ const render = vi.fn(() => element("fresh"));
+ cache.render(text("a"), "", render);
+ expect(render).not.toHaveBeenCalled();
+ cache.render(text("b"), "", render);
+ expect(render).toHaveBeenCalledOnce();
+ });
+
+ it("does not hold a text over the size limit", () => {
+ const cache = createMarkdownRenderCache(1_000_000, 100);
+ const render = vi.fn(() => element("big"));
+ cache.render("x".repeat(101), "", render);
+ cache.render("x".repeat(101), "", render);
+ expect(render).toHaveBeenCalledTimes(2);
+ expect(cache.size).toBe(0);
+ expect(cache.bytes).toBe(0);
+ });
+});
diff --git a/src/lib/markdown-render-cache.ts b/src/lib/markdown-render-cache.ts
new file mode 100644
index 0000000000..2c2a948072
--- /dev/null
+++ b/src/lib/markdown-render-cache.ts
@@ -0,0 +1,64 @@
+// Rendered Markdown kept per message text: a message drawn again (a conversation switched back to, rows scrolled back
+// into the window, a bubble that re-renders) reuses the React elements it already produced instead of parsing again.
+// An entry is only reused while everything the plugins read still matches (`variant`: mention names, thread links,
+// math); the cache holds an estimate of the memory its element trees take and lets the least recently drawn go first.
+import type { ReactElement } from "react";
+
+/** The estimated memory all cached element trees may hold. */
+export const MARKDOWN_CACHE_BYTES = 10 * 1024 * 1024;
+/** A longer text is parsed each time it is drawn rather than pinning its element tree. */
+export const MARKDOWN_CACHE_MAX_CHARS = 200_000;
+/** What one source character holds as an HTML syntax tree plus React elements: 57 bytes of V8 heap measured over 2,000
+ * replies of prose, lists, code and tables, so 10 MB is about 170,000 characters of Markdown. */
+export const MARKDOWN_BYTES_PER_CHAR = 60;
+
+interface Entry {
+ variant: string;
+ element: ReactElement;
+ bytes: number;
+}
+
+export interface MarkdownRenderCache {
+ /** The cached element for `text` drawn as `variant`, or `render()`'s, which is kept for next time. */
+ render(text: string, variant: string, render: () => ReactElement): ReactElement;
+ readonly size: number;
+ readonly bytes: number;
+ clear(): void;
+}
+
+export function createMarkdownRenderCache(limit = MARKDOWN_CACHE_BYTES, maxChars = MARKDOWN_CACHE_MAX_CHARS): MarkdownRenderCache {
+ const entries = new Map<string, Entry>();
+ let held = 0;
+ const drop = (text: string, entry: Entry) => {
+ entries.delete(text);
+ held -= entry.bytes;
+ };
+ return {
+ render(text, variant, render) {
+ const cached = entries.get(text);
+ if (cached && cached.variant === variant) {
+ // Most recently drawn moves to the back of the eviction order.
+ entries.delete(text);
+ entries.set(text, cached);
+ return cached.element;
+ }
+ if (cached) drop(text, cached);
+ const element = render();
+ const bytes = text.length * MARKDOWN_BYTES_PER_CHAR;
+ if (text.length > maxChars || bytes > limit) return element;
+ entries.set(text, { variant, element, bytes });
+ held += bytes;
+ for (const [oldest, entry] of entries) {
+ if (held <= limit) break;
+ drop(oldest, entry);
+ }
+ return element;
+ },
+ get size() { return entries.size; },
+ get bytes() { return held; },
+ clear() {
+ entries.clear();
+ held = 0;
+ },
+ };
+}