Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9634 fix(editor): stop every editor's Markdown tokenizers piling up on the global marked (#10961)

Multica Evee293fca0d3b7
diff --git a/e2e/perf/README.md b/e2e/perf/README.md
index cd3f2d2521..6743b558c4 100644
--- a/e2e/perf/README.md
+++ b/e2e/perf/README.md
@@ -327,6 +327,25 @@ make up C=api,desktop ARGS="--ephemeral --cdp"
make env-exec ARGS="-- node scripts/perf-desktop.mjs --attach --scenarios desktop-memory --out $PWD/perf/dev"
```
+## Retained memory while switching Inbox rows
+
+`desktop-memory` says whether the app grows; `inbox-heap.spec.ts` says what
+is kept. It drives the same Work-panel switches on the web build (or the
+Desktop renderer with `PERF_PLATFORM=desktop`) and, at each switch count in
+`PERF_HEAP_CHECKPOINTS` (default `0,40,80,160,320`), forces GC and records
+the JS heap, DOM nodes and event listeners. A count that keeps rising with
+the switches is a leak; caches level off. `PERF_HEAP_SNAPSHOT_DIR` also writes
+a heap snapshot at each checkpoint, to diff two counts in DevTools.
+
+```bash
+PERF_SCENARIO=inbox-heap PLAYWRIGHT_BASE_URL=http://localhost:3000 \
+ make env-exec ARGS="-- pnpm exec playwright test --config=playwright.perf.config.ts inbox-heap.spec.ts"
+```
+
+MUL-9634 found this way that every editor's Markdown tokenizers stayed on the
+global `marked`, with the unmounted issue behind them: ~1,000 DOM nodes per
+switch, until each editor got its own instance.
+
## Inbox jump
`inbox-jump.spec.ts` opens a notification about a reply deep in a long issue
diff --git a/e2e/perf/inbox-heap.spec.ts b/e2e/perf/inbox-heap.spec.ts
new file mode 100644
index 0000000000..91c203cc97
--- /dev/null
+++ b/e2e/perf/inbox-heap.spec.ts
@@ -0,0 +1,95 @@
+/**
+ * Inbox heap growth (MUL-9634): click through the Work panel's twenty Inbox
+ * rows, round and round, as `desktop-memory` does, and read the JS heap after
+ * a forced GC at checkpoints. Retained memory that grows with the number of
+ * switches is a leak; a heap that levels off is caches filling.
+ *
+ * Runs on the web build (default) or the Desktop renderer (PERF_PLATFORM=
+ * desktop). PERF_HEAP_CHECKPOINTS lists switch counts (default
+ * 0,40,80,160,320); PERF_HEAP_SNAPSHOT_DIR also writes a heap snapshot at each
+ * checkpoint for offline diffing.
+ */
+import { expect, test } from "@playwright/test";
+import { createWriteStream, mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import type { CDPSession } from "@playwright/test";
+import { settle } from "./lib/frame-metrics";
+import { ensureDataset, perfApi, resetInbox, type Manifest } from "./lib/core-dataset";
+import { inboxStorage, openInbox, switchTo } from "./lib/core-steps";
+import { perfTarget, PLATFORM, type Target } from "./lib/perf-target";
+
+const enabled = process.env.PERF_SCENARIO === "inbox-heap";
+const CHECKPOINTS = (process.env.PERF_HEAP_CHECKPOINTS ?? "0,40,80,160,320").split(",").map(Number);
+const SNAPSHOT_DIR = process.env.PERF_HEAP_SNAPSHOT_DIR;
+const SWITCH_DWELL_MS = 1000;
+const VIEWPORT = { width: 1440, height: 900 };
+
+let manifest: Manifest;
+let token: string;
+let target: Target;
+
+test.beforeAll(async ({ browser }) => {
+ test.skip(!enabled, "set PERF_SCENARIO=inbox-heap");
+ expect(process.env.MULTICA_DEV_PROFILE, "run through `make env-exec` against an isolated environment").toMatch(/^dev-/);
+ test.setTimeout(900_000);
+ const api = await perfApi();
+ token = api.getToken()!;
+ manifest = await ensureDataset(api);
+ target = await perfTarget(browser, token);
+});
+
+async function gcHeap(cdp: CDPSession) {
+ for (let i = 0; i < 3; i++) await cdp.send("HeapProfiler.collectGarbage");
+ const metrics = (await cdp.send("Performance.getMetrics")).metrics;
+ const get = (name: string) => metrics.find((m) => m.name === name)?.value ?? 0;
+ const dom = await cdp.send("Memory.getDOMCounters");
+ return {
+ js_heap_mb: Math.round(get("JSHeapUsedSize") / 1e5) / 10,
+ nodes: dom.nodes,
+ documents: dom.documents,
+ listeners: dom.jsEventListeners,
+ };
+}
+
+async function snapshot(cdp: CDPSession, path: string) {
+ mkdirSync(dirname(path), { recursive: true });
+ const out = createWriteStream(path);
+ const onChunk = ({ chunk }: { chunk: string }) => out.write(chunk);
+ cdp.on("HeapProfiler.addHeapSnapshotChunk", onChunk);
+ await cdp.send("HeapProfiler.takeHeapSnapshot", { reportProgress: false });
+ cdp.off("HeapProfiler.addHeapSnapshotChunk", onChunk);
+ await new Promise<void>((done) => out.end(done));
+}
+
+test("heap while switching Inbox rows", async () => {
+ test.setTimeout(3_600_000);
+ await resetInbox(manifest);
+ const sample = await target.newSample({ token, viewport: VIEWPORT, cpuThrottle: 1, storage: inboxStorage(manifest.workspace.slug) });
+ const { page, cdp } = sample;
+ try {
+ await cdp.send("HeapProfiler.enable");
+ const rows = await openInbox(sample, manifest, "20");
+ const order = manifest.inbox.slice(0, 20).map((n) => manifest.issues[n.key]!);
+ const points: Record<string, unknown>[] = [];
+ const last = Math.max(...CHECKPOINTS);
+ for (let i = 0; i <= last; i++) {
+ if (CHECKPOINTS.includes(i)) {
+ await settle(page, 1500);
+ const point = { switches: i, ...(await gcHeap(cdp)) };
+ points.push(point);
+ console.log(JSON.stringify(point));
+ if (SNAPSHOT_DIR) await snapshot(cdp, join(SNAPSHOT_DIR, `${PLATFORM}-${i}.heapsnapshot`));
+ }
+ if (i === last) break;
+ const issue = order[i % order.length]!;
+ await switchTo(page, rows, issue, "in-view");
+ await settle(page, SWITCH_DWELL_MS);
+ }
+ if (process.env.PERF_REPORT_PATH) {
+ mkdirSync(dirname(process.env.PERF_REPORT_PATH), { recursive: true });
+ writeFileSync(process.env.PERF_REPORT_PATH, JSON.stringify({ platform: PLATFORM, ref: process.env.PERF_REF ?? null, points }, null, 2));
+ }
+ } finally {
+ await sample.close();
+ }
+});
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index f947f1e10e..34411f2a86 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -32,6 +32,7 @@ import TableCell from "@tiptap/extension-table-cell";
import { Table } from "@tiptap/extension-table";
import { TaskList } from "@tiptap/extension-list";
import { Markdown } from "@tiptap/markdown";
+import { Marked, type marked } from "marked";
import { ReactNodeViewRenderer } from "@tiptap/react";
import type { AnyExtension } from "@tiptap/core";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
@@ -268,7 +269,18 @@ export function createEditorExtensions(
InlineMathExtension,
HighlightExtension,
// 3-space indent so nested ordered lists survive CommonMark in ReadonlyContent.
- Markdown.configure({ indentation: { style: "space", size: 3 } }),
+ // Each editor gets its own marked instance. Without one, @tiptap/markdown
+ // registers every editor's tokenizers on the global `marked` with `use()`
+ // and never removes them: the list grows by one editor's worth per mount,
+ // every inline parse runs all of them, and each tokenizer keeps its editor,
+ // the React refs its extensions close over and the unmounted DOM alive
+ // (MUL-9634: ~1,000 DOM nodes retained per issue opened).
+ Markdown.configure({
+ indentation: { style: "space", size: 3 },
+ // A Marked instance has every member MarkdownManager uses (use, Lexer,
+ // defaults, lexer, setOptions); the option is typed as the global's.
+ marked: new Marked() as unknown as typeof marked,
+ }),
// Make Cmd+C / Cmd+X / drag write Markdown source to clipboard text/plain
// so users can copy rich content out as the original Markdown.
createMarkdownCopyExtension(),
diff --git a/packages/views/editor/extensions/markdown-instance.test.ts b/packages/views/editor/extensions/markdown-instance.test.ts
new file mode 100644
index 0000000000..173e8a1ef0
--- /dev/null
+++ b/packages/views/editor/extensions/markdown-instance.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import { marked } from "marked";
+import { createEditorExtensions } from ".";
+
+/**
+ * Without a marked instance of its own, @tiptap/markdown registers each
+ * editor's tokenizers on the global `marked` and never removes them. Every
+ * editor that ever mounted then stayed reachable from that global, with its
+ * React refs and DOM, and every parse ran all of their tokenizers: switching
+ * issues in the Inbox grew memory by ~200 MB a minute (MUL-9634).
+ */
+
+/** Two syntaxes parsed by tokenizers the editor registers: highlight and display math. */
+const SOURCE = "Text with ==highlight==\n\n$$\nx^2\n$$";
+const editors: Editor[] = [];
+
+afterEach(() => {
+ for (const editor of editors.splice(0)) editor.destroy();
+ document.body.innerHTML = "";
+});
+
+function mountEditor(markdown: string): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const editor = new Editor({
+ element,
+ content: markdown,
+ contentType: "markdown",
+ extensions: createEditorExtensions({
+ placeholder: "",
+ disableMentions: true,
+ enableSlashCommands: false,
+ onUploadFileRef: { current: undefined },
+ }),
+ });
+ editors.push(editor);
+ return editor;
+}
+
+function globalTokenizerCount(): number {
+ const extensions = marked.defaults.extensions;
+ return (extensions?.inline?.length ?? 0) + (extensions?.block?.length ?? 0);
+}
+
+describe("editor markdown parser", () => {
+ it("leaves the global marked untouched, however many editors mount", () => {
+ const before = globalTokenizerCount();
+ for (let i = 0; i < 5; i++) mountEditor(SOURCE);
+ expect(globalTokenizerCount()).toBe(before);
+ });
+
+ it("keeps each editor's own tokenizers", () => {
+ const editor = mountEditor(SOURCE);
+ const json = JSON.stringify(editor.getJSON());
+ expect(json).toContain('"type":"highlight"');
+ expect(json).toContain('"type":"blockMath"');
+ expect(editor.getMarkdown().trim()).toBe(SOURCE);
+ });
+});
diff --git a/packages/views/package.json b/packages/views/package.json
index 9598fe8db9..06f4aff215 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -125,6 +125,7 @@
"hast-util-to-html": "^9.0.5",
"katex": "catalog:",
"lowlight": "^3.3.0",
+ "marked": "^17.0.1",
"mdast-util-from-markdown": "catalog:",
"mdast-util-gfm-table": "^2.0.0",
"mdast-util-math": "^3.0.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 475fb3a8cf..5483a13f21 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1287,6 +1287,9 @@ importers:
lowlight:
specifier: ^3.3.0
version: 3.3.0
+ marked:
+ specifier: ^17.0.1
+ version: 17.0.5
mdast-util-from-markdown:
specifier: 'catalog:'
version: 2.0.3