Repository navigation
Speed up large composer paste and per-keystroke work on big drafts - #1857
Conversation
A 1 MB single-line paste into the composer with rich-text Markdown on took ~2.4 s to parse because collectMarkdownMarkRanges rescanned every earlier marker range per delimiter candidate and the inline content builder rescanned markers/mentions per emitted run. Both are now linear (isolated parse: 2362 ms -> 11.9 ms). Per-keystroke work with a large draft in the box also shrinks: - find-active-trigger: scan the last 256 positions before the caret instead of the whole document. - PromptBoxInternal: compare the controlled value structurally instead of JSON.stringify-ing the whole prompt twice per keystroke. - usePromptDraftStorage: serialize the localStorage draft on the 250 ms flush, not on every write. - prompt-decoration-extension: above 100k positions, map existing decorations through the edit and rebuild on a 200 ms throttle. - SplitThreadArea: document why ThreadDetailView stays a static import (measured 469 ms lazy vs 242 ms static for the first thread open). Ported from #1853 without the committed perf-clips binaries. Co-authored-by: Jacob Miller <[email protected]> Co-Authored-By: Claude <[email protected]>
- prompt-decoration-extension: the throttled large-doc rebuild used the same transaction meta as an explicit refresh, so it bumped `revision` and re-ran every draft observer (a full-doc serialization) once per rebuild. It now carries its own meta and leaves `revision` alone. The observer debounce also skips serializing the doc when no observer is registered. - PromptBoxInternal: build the initial editor content once per editor instance instead of on every render; TipTap only reads `content` when it (re)creates the editor. The value it was built from is what onCreate records as last synced, so newer props still flow through setContent. - usePromptDraftStorage: when localStorage rejects the write (quota with a multi-megabyte draft, or storage disabled) keep the in-memory draft authoritative instead of letting the next read revert the composer to the stale stored value. - Move the minified-JS paste fixture generator to src/test/fixtures and fix the perf harness run instructions (the repo vitest config silences console output unless --silent=false --disableConsoleIntercept is passed). Co-Authored-By: Claude <[email protected]>
| const selection = editor.state.selection; | ||
| if (!selection.empty) return null; | ||
|
|
||
| const scanStart = Math.max(0, selection.from - TRIGGER_SCAN_WINDOW); |
There was a problem hiding this comment.
🚨 slopcop/review — The scan window drops a valid 255-character query.
At 255 query characters, scanStart removes the boundary before the trigger. The windowed pattern then returns null.
The command contracts do not set the same length limit. Long valid command or mention queries therefore close the selection menu.
Please define a shared query limit and scan the boundary, trigger, and full accepted query. Add a real ProseMirror boundary test.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
Plain English summary: This change keeps the message composer responsive after a very large paste. It removes repeated whole-draft work from key presses. It also makes Markdown parsing scale with the draft size.
I found one non-blocking issue.
- Medium: A valid 255-character command or mention query closes the selection menu. I left an inline comment on the scan window.
I found no security or abuse regression. Clipboard HTML stays inert, and mention data still uses schema checks.
I found no useful duplicate code or required architecture change. The new range indexes and sweeps belong with the editor parser.
Verification was strong:
- The full app suite passed: 362 files and 2,876 tests. Three optional tests did not run.
- The app Turbo typecheck passed.
- All GitHub checks passed.
- Differential fuzz tests compared 460,000 old and new parser results. All results matched.
- A 1 MB differential benchmark measured about a 202 times speed increase. The new parser stayed linear through 2 MB.
- The repository performance benchmark passed.
The browser composer mounted without errors. The automated 1 MB paste exceeded 30 seconds and then crashed that Chromium page. This result is inconclusive, so I did not treat it as a finding. No prompt was sent.
The final GPT-5.6 review gate returned APPROVE. I posted only a comment, as required.
…rompt area (C6-C13, D2, D4, E9, E11, E12, H8) (#1898) ## What was wrong Several client-side amplifiers made phones re-render far more than the data changed: - The plugin slot store rebuilt all 14 slot arrays per plugin activation and emitted once per bundle at boot (~18 app-wide passes; every markdown body re-parsed once directives existed). - `useNavigate()` under `<BrowserRouter>` rebuilds per pathname, so the thread-actions context, the fork handler in the timeline static context, and every sidebar row (`useThreadRowSplitDrag`, `useCreateThreadInWorktree`, environment archive) re-rendered on every navigation. - `MessageActionBar` mounted the hidden desktop tooltip bar on touch phones in addition to the mobile popover. - Every `ConversationRow` re-rendered per new message via the latest-actionable id contexts, and React Compiler skipped it (a ref-callback passed as `ref` typed the edit object as a ref). - Title-mention resource maps were rebuilt twice (AppLayout + ProjectList) per sidebar refetch and provided twice. - Sidebar rows subscribed to `splitLayoutAtom` on compact viewports where splits are off. - Draft presence re-read localStorage for every thread per keystroke and per sidebar render. - `useChildThreadPendingAttention` returned a fresh array per render, invalidating the memoized prompt stack. - `ThreadDetailPromptArea` failed React Compiler compilation (try/finally, render-time ref writes, ref-typed closures). - Workflow/todo/background cards mounted collapsed bodies with per-row 1 s timers. - `experimental_useSidebarThreads` remapped every entry into a fresh DTO per update. - Page header and retained secondary panel re-rendered on every SidebarContext commit for one boolean. ## What changed - Plugin slot store: per-kind structural sharing, per-plugin flattened slot cache, and a bounded notification batch (150 ms) around reconcile. - `useRouteNavigate()` from `RouteNavigationProvider` (ref-held navigate, stable identity, no location subscription) used by rows, ThreadActionsProvider, fork handler and plugin sidebar hooks; fork handler reads the thread from a ref. - Mobile branch in MessageActionBar (popover or plain inline buttons); desktop unchanged. - `ConversationRow` = thin context reader + `memo(ConversationRowContent)`; `InlineMessageEditorHost` isolates the ref callback so both compile. - `buildThreadTitleMentionResources` with value retention; one provider (AppLayout); ProjectList reads the context. - Split indicator subscribes to a null atom when compact/disabled. - Presence store caches bits, re-reads only the changed key, stays silent when presence does not flip. - Module-level `combine` + frozen empty array for child attention. - ThreadDetailPromptArea compiler bailouts removed (`runWhileFollowUpShortcutSending`, `useLatestRef`, layout-effect ref write, module-level composer-host accessors). - Shared `AnimatedBody` (realize on first expand, retain) for the three cards; `useSecondTick` shared ticker. - WeakMap DTO memo for plugin sidebar threads; SDK docs note the uncapped array and windowing expectation. - `SidebarShowingContext` boolean for `useIsSidebarShowing`/`useOptionalIsSidebarShowing`. ## How you verified - `pnpm exec turbo run typecheck --filter=@bb/app --filter=@get-bb/plugin-sdk --filter=@bb/plugin-build`: pass. - `pnpm exec turbo run lint --filter=@bb/app`: 0 errors (pre-existing compiler warnings only). - `pnpm exec turbo run test --filter=@bb/app`: 370 files, 2910 passed, 3 skipped. `@get-bb/plugin-sdk` tests: 103 passed. `@bb/plugin-build` tests: 20 passed. - New tests fail before / pass after: plugin-slots structural sharing + batching, ThreadActionsProvider.navigation (stable context and useRouteNavigate reader across a MemoryRouter navigation), useForkThreadFromMessage identity, MessageActionBar mobile branch, ThreadTimelineRows.row-isolation, ThreadTitleMentions.resources retention, paneContentSplitIndicator compact gating, usePromptDraftStorage presence reads/renders, child-thread-pending-interactions.hook identity, AnimatedBody realize/retain + shared interval, plugin-sidebar-hooks DTO identity, sidebar showing-bit isolation. - [email protected] run over ThreadDetailPromptArea.tsx and ThreadTimelineRows.tsx: `ThreadDetailPromptArea` (452 slots), `ConversationRow`, `ConversationRowContent` now CompileSuccess. Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 19 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/plugin-host-slots` (#1897). - Next layer: `bb/mobile-perf/markdown-streaming-and-containment` (#1899). - Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s). - Deliberately not done here: D6: already implemented on the base commit dde6cdd (#1857 memoizes initialEditorContent on [richTextEditing]); verified, no change needed - Partial: E12: only the showing-bit context was split out (page header + retained ThreadSecondaryPanel); the full actions/state split of SidebarContext was left as a foll; E11: compact gating only; the optional desktop per-content derived-atom refinement and the SplitThreadArea reconcile short-circuit were not done - Reviewer notes / follow-ups: C6 batching: while a slot batch is open (<=150 ms) a component that re-renders for unrelated reasons reads the fresh snapshot via getPluginSlotSnapshot() while un-rendered subscrib | E12 is a partial split (only the sidebar-showing boolean got its own context); the actions/state split from the audit remains a follow-up as the implementer stated. | C7 test is a hook-identity test rather than the Profiler-through-ThreadDetailView test the audit suggested; the row-isolation test in ThreadTimelineRows.row-isolation.test.tsx cove | apps/app/.ladle is not covered by tsc/lint; the RouteNavigationProvider addition there was checked by inspection only. - Wire/contract: None. No server/daemon wire, host RPC, or protocol changes; HOST_DAEMON_PROTOCOL_VERSION untouched. Public plugin SDK: only doc comments on the existing experimental_useSidebarThreads member (bundled-types regenerated); no new API members. Internal app contract: PluginFrontendReconcileDeps gained a required beginSlotBatch dep (test doubles updated). > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) --------- Co-authored-by: Claude <[email protected]>
Ports #1853 by @jjcm (co-authored on the first commit) into an in-repo branch so CI runs, drops the committed
perf-clips/*binaries, and applies the cleanups from the review of that PR.What was wrong
A 1 MB single-line paste into the composer with rich-text Markdown on took ~2.4 s before it painted.
collectMarkdownMarkRangesrescanned every earlier marker range for each delimiter candidate, and the inline content builder rescanned all markers and mentions for each emitted text run, so a minified-JS-shaped paste (thousands of`/_/*) was quadratic. With a large draft in the box, each keystroke also paid for a full-document trigger scan, twoJSON.stringifycalls of the whole prompt for the controlled-value compare, a full draft serialization, and a synchronous decoration rebuild.What changed
From #1853 (measured there: isolated 1 MB parse 2362 ms → 11.9 ms; paste-to-paint 2453 ms → 530 ms; clips in that PR):
prompt-editor-serialization.ts: linear Markdown parse (sorted, merged range index with binary search; monotonic sweeps for marks, boundaries and marker lookup; early exit when no closing marker exists). Verified equivalent to the old parser by fuzzing 100k random inputs (delimiters, lists, quotes, newlines, overlapping mentions, rich on/off) with zero differences.find-active-trigger.ts: scan the last 256 positions before the caret; the^alternative is disabled for a windowed scan. Queries ≥ 254 chars no longer open a menu.PromptBoxInternal.tsx: structuralarePromptEditorValuesEqualinstead of a JSON key.usePromptDraftStorage.ts: serialize the draft on the 250 ms flush, not per write.prompt-decoration-extension.ts: above 100k positions, map decorations through the edit and rebuild on a 200 ms throttle. Highlights can lag an edit by up to that interval on very large drafts.SplitThreadArea.tsx: comment only.ThreadDetailViewis already a static import onmain; the comment pins the measurement (469 ms lazy vs 242 ms static for the first thread open) so nobody adds aReact.lazyboundary later. This row in Speed up large composer paste and first thread open #1853's table is not a shipped change.Cleanups on top (second commit):
refreshPromptDecorations, so it bumpedrevisionand re-ran every draft observer (a full-doc serialization) once per rebuild. It now carries its own meta. The observer debounce also skips serializing the doc when no observer is registered.useEditor({ content })was rebuilt on every render even though TipTap reads it only when it creates the editor (~7 ms per render for a 1 MB rich-text draft, ~2.3 s before the parser fix). It is now built once per editor instance; the value it was built from is whatonCreaterecords as last synced, so newer props still flow throughsetContent.localStorage.setItemfailures (quota with a multi-megabyte draft, or storage disabled) no longer let the next read revert the composer to the stale stored value; the in-memory draft stays authoritative and a warning is logged.src/test/fixtures/; the perf harness header now documents the flags needed to see its output under the repo vitest config.perf-clips/binaries in the tree.How you verified
prompt-editor-serialization.test.ts; large-doc window and window-edge^cases infind-active-trigger.test.ts; structural compare inPromptBoxInternal.test.tsx; deferred persist / immediate override / pagehide flush / quota rejection inusePromptDraftStorage.test.tsx; deferred rebuild mapping, explicit refresh cancel, and observer quiet-on-rebuild inprompt-decoration-extension.test.ts.pnpm exec turbo run typecheck --filter=@bb/apppasses; ESLint clean on changed files;vitest run src/components/promptbox src/hooks/usePromptDraftStorage.test.tsx— 34 files, 352 tests pass.PROMPTBOX_PERF=1 pnpm exec vitest run --silent=false --disableConsoleIntercept src/components/promptbox/editor/prompt-paste-performance.test.ts(1 MB rich-text parse ≈ 7 ms locally).Closes #1853