Skip to content

Fix the multi-second composer freeze when a large blob is pasted - #4

Open
jjcm wants to merge 3 commits into
mainfrom
cursor/composer-large-paste-performance-6cdd
Open

jjcm wants to merge 3 commits into
mainfrom
cursor/composer-large-paste-performance-6cdd

Conversation

@jjcm

@jjcm jjcm commented Aug 18, 2026 •

Copy link
Copy Markdown
Owner

Pasting a large single-line payload into the composer — a minified JS bundle is the case that surfaced this — locks the tab up for seconds. With rich-text editing enabled, a 1 MB paste froze this build for 2.45 s; the freeze grows faster than the input, so it is much worse on bigger payloads and slower machines.

The cause is a Markdown parser that rescans the whole document per delimiter candidate and per emitted text run. On delimiter-dense input (minified JS is nothing but delimiters) that is quadratic. This PR makes the parse near-linear and takes four other full-document scans off the per-edit path.

Before / after

Same 1 MB paste, same build settings, side by side — main on the left, this branch on the right. The clock in each header is driven by requestAnimationFrame, so it only advances while that tab is responding: a frozen clock is the freeze.

Side-by-side 1 MB paste. On main the clock sticks at 0.00 s and the composer stays empty for seconds; on this branch the clock keeps ticking and the paste renders immediately.

One second after the paste, main has not moved and the composer is still showing "Ask anything", while this branch has already rendered the whole blob. Full-resolution MP4: paste-1mb-before-after.mp4. Both clips live in perf-clips-DELETE-BEFORE-MERGE/ (636 KB total) purely so they render for everyone who opens this PR — delete that directory before merging; nothing in the product references it.

Numbers

End-to-end in the real composer: production build, real bb server on localhost, headless Chromium 1280×720, fresh browser profile per run, 1,048,576-character single-line paste, medians of n=3. "Painted" is the first frame that shows the pasted text; "settled" is when three consecutive frames come in under 50 ms.

1 MB paste into the root composer main this branch Delta
rich-text editing on — painted 2,453 ms 530 ms −78%
rich-text editing on — settled 2,483 ms 567 ms −77%
rich-text editing off (default) — painted 509 ms 495 ms noise

The synchronous JS this removes, measured in isolation with the gated microbenchmark this PR adds (PROMPTBOX_PERF=1, Node 22 / Vitest, medians of 3 runs of medians):

Operation at 1 MB Before After
Rich-text Markdown parse (per paste / mount) 2,362 ms 11.9 ms
Typeahead trigger scan (per doc + selection update) 2.52 ms 0.002 ms
Controlled-value JSON.stringify (×2 per keystroke) 2.50 ms each removed
Draft serialization (per keystroke) 2.50 ms once per 250 ms flush
Decoration rule regex (per edit) 8.05 ms deferred above 100k positions

The parse is the row that matters. It is also the row whose shape changed: 78.8 → 2.8 ms at 128 KB, 404.7 → 5.3 ms at 512 KB, 2,362 → 11.9 ms at 1 MB. Before, four times the input cost thirty times the work; after, it tracks the input.

The clips above were recorded separately with headful Chrome on Xvfb under screen capture, which is slower for both arms: 5,598 ms on main versus 570 ms here.

What this does not fix

Being direct about the limits, because they change how much of a win this actually is:

The paste win needs rich-text editing turned on. That preference (Settings → rich-text editing) is off by default, and with it off the Markdown parser never runs, so a large paste already lands in ~500 ms on main. Everything else in this PR still removes real work from the input path with the preference off, but that work is currently invisible next to the problem below.

Typing after a large paste is still terrible, and this PR does not change it. Measured identically on both arms:

Text in the composer main this branch
32 KB 147 ms/keystroke 147 ms
64 KB 438 ms 443 ms
128 KB 1,512 ms 1,511 ms
256 KB 5,224 ms 5,191 ms
1 MB — 76,877 ms

A CPU profile of one keystroke at 256 KB puts 5,241 ms of the 5,323 ms in getClientRects, under this stack:

getClientRects
  coordsAtPos
  scrollToSelection
  EditorView.updateState
  dispatchTransaction

That is ProseMirror scrolling the selection into view on every transaction, which forces layout of one enormous wrapped line. It is pre-existing, it is not in our code, and it dominates everything this PR removes. It is the obvious next target — and once it is gone, the per-keystroke work removed here becomes the next thing you feel.

What changed

Six changes, all in the composer input path:

  • prompt-editor-serialization.ts — marker/mention containment now uses a sorted, merged range index with binary search instead of a linear scan per candidate, and the content walk uses monotonic sweeps for marks, boundaries and markers instead of rescanning from the top per emitted run. An early exit stops rescanning the tail once no usable closing delimiter remains. This is the change that produces the headline number.
  • find-active-trigger.ts — the typeahead scan looked at every character before the caret on every document and selection update. It now scans a 256-character window.
  • PromptBoxInternal.tsx — the controlled-value sync key was JSON.stringify of the whole prompt, computed on write and again when the value came back through React. It is now a structural compare that normally settles on pointer identity.
  • usePromptDraftStorage.ts — draft writes were already debounced by 250 ms, but serialization happened on every write. It moved to the persist boundary; the in-memory draft is authoritative while a flush is pending.
  • prompt-decoration-extension.ts — above 100,000 document positions an edit maps the existing decorations through the transaction and schedules a throttled rebuild, instead of re-serializing the document and running every rule over the full text synchronously. Decoration rules can come from plugins, so this path is unbounded by design.
  • ThreadDetailView.tsx — the view subscribed to draft state through usePromptDraftStorage but only writes quotes at event time, so the whole thread view re-rendered on every composer keystroke. It now uses the non-subscribing accessor that already existed for exactly this case.

Tradeoffs

  • Highlight lag on very large drafts. Above 100,000 positions, decoration additions and removals can trail an edit by up to 200 ms. Existing decorations map through the edit in the meantime, so nothing visibly detaches from its text.
  • Typeahead query cap. A @ or / query can now be at most 254 characters (boundary + trigger + query inside a 256-character window). Longer queries no longer open the menu; no menu has useful matches at that length.
  • Draft crash window unchanged. Serialization moved to the flush, but the flush cadence and the pagehide / hidden-document flushes are the same, so the pre-existing 250 ms crash-loss window is unchanged.
  • Parser readability. Sorted range indexes and monotonic sweeps are less obvious than repeated array scans. The behaviour is covered by the existing Markdown round-trip tests plus a new regression test that round-trips a large single line with thousands of delimiters.

How to verify

pnpm exec turbo run test --filter=@bb/app        # 349 files, 2,778 passed / 3 skipped
pnpm exec turbo run typecheck --filter=@bb/app   # clean
pnpm exec turbo run lint --filter=@bb/app        # 0 errors (145 pre-existing warnings)
node apps/app/scripts/check-bundle-budget.mjs    # 1664.0 KB raw / 436.8 KB brotli, 14 chunks — unchanged

The isolated numbers above, at 128 KB / 512 KB / 1 MB:

cd apps/app
PROMPTBOX_PERF=1 pnpm exec vitest run \
  src/components/promptbox/editor/prompt-paste-performance.test.ts

By hand: write the fixture out, paste it into the composer with rich-text editing enabled, and compare against main.

cd apps/app
PROMPTBOX_PERF=1 PROMPTBOX_PERF_FIXTURE_OUT=/tmp/minified-paste-fixture.js \
  pnpm exec vitest run \
  src/components/promptbox/editor/prompt-paste-performance.test.ts

The fixture is generated deterministically, so no megabyte blob is committed.

Environment, and what is still unmeasured

Everything above is Linux headless Chromium over localhost against a production build, on a shared cloud VM. The macOS desktop app was not measured — no Electron cold start, no Electron input latency, no macOS compositor behaviour. The isolated parser numbers are Node/Vitest and contain no DOM, layout or paint cost at all. Run-to-run spread on this rig is roughly ±10%, which is why every figure is a median and why the two arms were built from the same tree with only these commits between them.

For reference, an earlier run of this change on a macOS laptop (Playwright, 1,000,015 characters) reported the paste wait going from 28,051 ms to 462 ms. The 462 ms matches the 530 ms measured here closely; the 28,051 ms baseline is far above the 2,453 ms this rig produces and I could not reproduce it, so I am reporting my own numbers as the claim and that one as a separate data point.

Scope

This is the filtered product result of a broader performance investigation. Deliberately not included, because none of it beat noise on a metric a person can feel: the desktop wrapper comparison (Electron vs WebContentsView vs Tauri — no alternative won anything measured), the cold-load HUD attempts (three consecutive misses; a macOS run was a tie at 323 vs 322 ms), prefetching a lazy route chunk (−7 ms, indistinguishable from drift), and a zod module-evaluation stub (measured, never landed).

Also left out: making ThreadDetailView a lazy import. It was tried, and it cost 227 ms on the first thread opened in a session (469 → 242 ms when reverted), because a React.lazy suspend renders the largest view in the app at transition priority, sliced across thousands of scheduler tasks. main already imports it statically and should stay that way. Nothing in this PR touches it.

The lazy pierre/Shiki/KaTeX split and the idle plugin-frontend boot from the same investigation are not here either. They are a real boot-payload reduction (~2.25 MB raw off the workspace route's parse path), but the only metric that moved was a localhost route-ready marker, they cost ~1,600 lines of restructuring across the diff and file-preview components, and they raise the boot brotli budget. They deserve their own PR with their own evidence, not a ride along with a parser fix.

Please do not merge without a check on the macOS desktop build.

AGENT GENERATED: by Claude Opus 5

Open in Web Open in Cursor 

cursoragent and others added 3 commits August 18, 2026 04:41
Pasting a large single-line payload (a minified JS bundle is the case that
surfaced this) froze the composer for tens of seconds, and every keystroke
afterwards stayed expensive. The work was spread across five synchronous
paths, all of which scaled with the size of the whole document:

- Markdown parsing rescanned the full text per delimiter candidate and per
  emitted run, which is quadratic on delimiter-dense input. Marker/mention
  lookups now use a sorted range index and monotonic sweeps.
- The typeahead trigger scan rebuilt all text before the caret on every doc
  and selection update; it now scans a bounded window.
- The controlled-value sync key JSON-stringified the whole prompt twice per
  keystroke; it now compares structurally, normally on pointer identity.
- Draft storage serialized the full draft on every write even though the
  write itself was already debounced; serialization moved to the persist
  boundary.
- Decoration rebuilds serialized the document and ran every rule over the
  full text per edit; above 100k positions they now map through the edit and
  rebuild on a throttled timer.
- ThreadDetailView subscribed the whole thread view to draft state, so the
  timeline re-rendered per keystroke; it now uses the non-subscribing
  accessor it already had available.

Co-authored-by: Jacob Miller <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants