Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(web): composer serializes each draft doc once per keystroke #26720

Mergedhieu-lee(GitHub profile, opens in a new tab)merged 1 commit intomain fromrefs/pull/26720/headmerged by maria-rcks View on GitHub

Problem

The composer turns its whole ProseMirror doc into markdown plus a run table on every edit (serializeEditorDoc). I instrumented the function in a Chromium browser test and counted the calls. One typed character serialized the same immutable doc 3 times: the marker-decoration plugin's state apply, then Tiptap's onUpdate and onSelectionUpdate, which both run handleEditorChange. An arrow key serialized it 2 times even though the doc had not changed. For a long draft each call costs about 0.45 ms and allocates about 4 MB.

Fix

  • serializeEditorDoc caches its result per doc node in a module-level WeakMap. ProseMirror nodes are immutable and every edit produces a new doc object, so the doc fully determines the result. The old body moved unchanged into serializeDoc. Docs are held weakly, so the cache keeps nothing alive.
  • Callers now share the result, so RichDocMap's fields are readonly. Typecheck shows no caller mutated the map. The two places that hand contextIds out of the editor (handleEditorChange → onChange, and readSnapshot) copy the array, so consumers still get a fresh string[] as before.

After this, typing serializes once per keystroke and an arrow key does not serialize at all. Output is unchanged.

Measurements

Harness: a temporary Vitest file (node pool, --expose-gc, not committed) that imports the real composer-rich-text-doc.ts with the schema setup from composer-rich-text-doc.test.ts. The draft is about 24 KB of markdown: 150 paragraphs with bold, italic, inline code and file mentions, plus headings, bullet lists and fenced code blocks. One keystroke is state.apply(tr.insertText("x")) followed by three serializeEditorDoc(state.doc) calls, which is what the editor does per typed character. Each run takes the median of 9 × 100 keystrokes after a 300-keystroke warmup. Allocation is the heapUsed delta of one keystroke after gc(), kept only when no GC ran, median of 30. Before and after ran interleaved, 5 runs each, on an Apple Silicon Mac.

before (median of 5)after (median of 5)change
time per keystroke, 24 KB draft1.338 ms0.488 ms2.74× faster
allocated per keystroke12.86 MB4.29 MB−67%

At about 98 KB (600 paragraphs) the original took 5.9 ms and allocated 51 MB per keystroke. That scales linearly, and the change cuts it by the same factor.

What limits the new number: the one remaining serialization. appendInlineRuns allocates about 1.7 KB per run in closures and short-lived arrays, which is roughly 4 MB for this draft. Speeding up the walk itself is a separate change.

Harness (temporary Vitest file)
// apps/web/src/zzperf-composer.test.ts (not committed). The schema setup is copied from composer-rich-text-doc.test.ts.
it("perf", async () => {
  const para = (i: number) => `Paragraph ${i} with **bold text**, \`inline code\`, _italic_ words and a link to @src/components/file${i}.tsx plus more plain prose to make it realistic.`;
  const SIZE = Number(process.env.PARAS ?? 150);
  const parts: string[] = [];
  for (let i = 0; i < SIZE; i++) {
    if (i % 10 === 0) parts.push(`## Heading ${i}`);
    if (i % 7 === 0) parts.push(`- item one ${i}\n- item **two** ${i}\n- item three ${i}`);
    if (i % 13 === 0) parts.push("```ts\nconst x = " + i + ";\nfunction f() { return x; }\n```");
    parts.push(para(i));
  }
  const value = parts.join("\n\n");
  const doc0 = ProseMirrorNode.fromJSON(schema, buildDocJson(value, (name) => ({ label: name, description: null })));
  let state = EditorState.create({ schema, doc: doc0 });
  const pos = Math.floor(doc0.content.size / 2);
  // One keystroke: the doc changes, then the marker plugin, onUpdate and onSelectionUpdate each serialize it.
  const keystroke = () => {
    state = state.apply(state.tr.insertText("x", pos));
    let sink = 0;
    for (let k = 0; k < 3; k++) sink += serializeEditorDoc(state.doc).runs.length;
    return sink;
  };
  for (let i = 0; i < 300; i++) keystroke();
  state = EditorState.create({ schema, doc: doc0 });
  const KEYS = 100, times: number[] = [];
  for (let r = 0; r < 9; r++) { const t0 = performance.now(); for (let i = 0; i < KEYS; i++) keystroke(); times.push((performance.now() - t0) / KEYS); state = EditorState.create({ schema, doc: doc0 }); }
  let gcs = 0;
  new PerformanceObserver((l) => (gcs += l.getEntries().length)).observe({ entryTypes: ["gc"] });
  const allocs: number[] = [];
  for (let i = 0; i < 30; i++) {
    (globalThis as { gc?: () => void }).gc?.(); await new Promise((r) => setTimeout(r, 5));
    const g0 = gcs, h0 = process.memoryUsage().heapUsed; keystroke(); const h1 = process.memoryUsage().heapUsed;
    await new Promise((r) => setTimeout(r, 5));
    if (gcs === g0) allocs.push((h1 - h0) / 1e3);
  }
  const med = (a: number[]) => [...a].sort((x, y) => x - y)[a.length >> 1]!;
  console.log("RESULT", JSON.stringify({ chars: value.length, msPerKeystroke: med(times).toFixed(3), allocKBPerKeystroke: med(allocs)?.toFixed(0), allocSamples: allocs.length }));
}, 600_000);

Counting calls: a temporary browser test mounted ComposerPromptEditorTiptap, typed with userEvent.keyboard, and read a counter that a temporary line in serializeEditorDoc incremented. Typing y produced 3 calls and {ArrowLeft} produced 2.

Validation

  • vp run check:changed passes (format, lint, knip, typecheck, tests).
  • vp test run src/composer*: 476 tests pass.
  • Composer browser tests pass in Chromium (18): ComposerPromptEditorTiptap.input, ComposerPromptEditorTiptap.citationDraft, composer-list-split.
  • No differential test was needed: the cached value comes from the unchanged serializer, and the readonly types rule out callers mutating the shared result.

Not checked: an end-to-end pass in a running client. Subagents in this run do not launch dev servers.

Authored with Claude Opus 5.5 via the Claude Code harness in T3 Code.

🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. Approvability

      Verdict: Approved at 85638d9

      Macroscope's review found this PR approvable — The composer reuses serialized results for the same immutable document instead of repeating work across callbacks. Serialization behavior remains unchanged, with readonly cached results and copied context-ID arrays protecting snapshot boundaries.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. Review in Change Stack →

      No actionable comments were generated in the recent review.

      Recent review info
      Run configuration
      Commits

      Reviewing files that changed from the base of the PR and between e34067edef2eba03c1e40bca7d2b2d933ae12b85 and 85638d9f958cc9bc2958c371b4fbf49cf9d7cee4.

      Files selected for processing: 2
      • apps/web/src/components/ComposerPromptEditorTiptap.tsx
      • apps/web/src/composer-rich-text-doc.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

      Walkthrough

      The serialized rich-text document map now has readonly fields and is cached by document. The editor copies its context ID array when storing editor changes and snapshots.

      Changes: Rich document map

      Layer / File(s)Summary
      Readonly map and serialization cache
      apps/web/src/composer-rich-text-doc.ts
      RichDocMap fields and run values are readonly. serializeEditorDoc returns a cached map or serializes and caches the document.
      Editor context ID snapshots
      apps/web/src/components/ComposerPromptEditorTiptap.tsx
      handleEditorChange and readSnapshot store copies of map.contextIds. Literal-text mode still stores an empty array.
      Priority: Low

      Estimated code review effort: 2 (Simple) | ~10 minutes

      Change: Refactor

      Suggested reviewers: macroscopeapp

      Merge Risk: Minimal · up to 85638

      No actionable regression introduced by this change was established; the PR is mergeable with normal checks.

      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: caching composer serialization so each draft document is serialized once per keystroke.
      Description checkPassedThe description gives detailed problem, implementation, measurements, verification results, and limitations. It does not include the required Scope and approval section or an explicit approval link/ex…
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Description check

      Explanation

      The description gives detailed problem, implementation, measurements, verification results, and limitations. It does not include the required Scope and approval section or an explicit approval link/exemption rationale, but it is otherwise complete and directly relevant.

      Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Comment `@coderabbitai help` to get the list of available commands.
    4. @juliusmarminge ready for review. The composer serialized the same unchanged doc 3 times per typed character (2 per arrow key). serializeEditorDoc now caches per doc, so typing serializes once and an arrow key not at all: 24 KB draft 1.34 ms to 0.49 ms per keystroke (about 2.7x), 12.9 MB to 4.3 MB allocated (-67%). The result type is now readonly so callers cannot mutate the shared copy. 476 unit and 18 composer browser tests pass. I also typed, moved the cursor, and reloaded in a browser on a merge of this and #26717: text, cursor position and draft restore behaved correctly. CI workflows on this fork PR show action_required, so they are waiting on a maintainer to approve the run. CodeRabbit and Macroscope have no open findings.

    5. maria-rckscommented

      Note

      Written by gpt-6.1-sol on behalf of Maria

      Verified in a real dev environment

      verified unchanged head 85638d9f958cc9bc2958c371b4fbf49cf9d7cee4 against github/main at 5732bbee39 on linux. installed both checkouts with vp i, ran one dev server at a time, and drove the actual web app with repository playwright and /usr/bin/google-chrome. created projects and threads through the app with fresh isolated state. real codex gpt-6.1-sol turns completed on both revisions through the local proxy.

      browser-only instrumentation measured the actual composer serializer during keyboard input in a matching 24,938-character draft. no source changes or mocked provider responses:

      • 30 typed keys: main performed 120 full document walks; the pr performed 30.
      • 30 arrow keys: main performed 90 full walks; the pr performed zero.
      • total serializer time in this capture: typing 32.20 ms to 14.90 ms; arrows 32.40 ms to 0.10 ms. these are single-capture serializer timings, not end-to-end latency or allocation measurements. current main's callbacks differ from the older pr description.

      selection replacement and undo preserved the draft. rich markdown clipboard output matched exactly before and after reload. file autocomplete inserted a real apps/mobile/README.md mention; the mention survived reload and submission, and codex returned COMPOSER_CONTEXT_OK. ordinary submission returned COMPOSER_BASELINE_OK.

      blacksmith passed 239 existing serializer tests and 18 existing composer browser tests covering input, citation drafts, and list splitting. the browser worker initially lacked chromium; installed it and reran successfully. no code changes were needed.

      main: repeated serialization during actual typing and cursor movement

      pr: one full walk per typed key and zero for cursor movement

      main then pr: actual typing and cursor movement with measured serializer time

      real codex response after restored file mention submission

      command and runtime transcript

      Not verified

      native ios/android and electron shells, macos/windows, other providers, and remote/relay/tunnel connections were not exercised on this linux web pass. allocation reduction and production-build latency were not measured. screenshots were inspected; the uploaded 14-second recording played through and seeking worked in the t3 player.

    6. maria-rcks merged this0da2bb6

    7. maria-rcks closed this

Sign in to join this conversation.