Repository navigation
Render resize-measured layout in the same frame as the resize - #7635
Merged
Merged
Conversation
ymichael
force-pushed
the
bb/measured-layout-same-frame
branch
from
November 17, 2026 04:13
f14df6d to
1157b61
Compare
A ResizeObserver callback runs before paint, but a plain setState from it renders in a later task, so layout derived from a measured size painted one frame late. Route every observer through observeSharedResize (now in @bb/shared-ui), which applies all writes of a batch inside one flushSync and runs each registration once per batch. Add useMeasuredValue for the simple ref-to-value case and the bb/no-raw-resize-observer lint rule so new code cannot reintroduce a raw observer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/measured-layout-same-frame
branch
from
November 17, 2026 04:19
1157b61 to
2907d70
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 17, 2026
## Human comments ## What was wrong The React Compiler silently skipped 95 functions in `apps/app` and 6 in `packages/shared-ui`, among them the hot paths: `ThreadTimelineRowsForTimelineView`, `TimelineWindowedItems`, `ThreadDetailViewInternal`, `useComposerRendererHostApi`, `AppLayout`, `SidebarNavigationModel` and shared-ui `question-form`. Most of the skips were refs read or written during render. The rest were syntax the compiler can't handle yet: `try`/`finally`, `??=`, getters in object literals, and hooks passed around as values. Nothing stopped new skips: - The compiler lint rules were set to `warn` (228 warnings in apps/app). - The compiler's "Todo" bailouts (try/finally and friends) aren't reported by lint at all. - `vitest` ran without the compiler, so render tests measured code that never ships. (The audit's counter missed files directly under `src/` and missed `packages/query-tags`, which the app build also compiles. The corrected count has no skips left.) ## What changed **Skips fixed (0 remain in app, shared-ui or query-tags source)**, with no `"use no memo"` or lint disables. The two existing `set-state-in-effect` disables were removed too. The patterns used: - Latest-value refs are written in layout or insertion effects. `useLatestRef` writes in `useInsertionEffect`, and `useEffectEvent` is used where a ref only fed an effect. - Ref caches that kept identity across renders became render-phase state, React's "storing information from previous renders" pattern. This covers `useStableReadonlySet`, terminal-row accumulation, sidebar navigation items, thread-title mention resources and others. - Hooks that return objects holding refs are destructured at the call (`useDisclosureFocusHandoff`). - `try`/`finally` procedures moved to module-level functions with the same error and early-return paths. - The two `@tanstack/react-virtual` call sites use a new `hooks/useCompilerSafeVirtualizer.ts`, which owns a `Virtualizer` and publishes snapshots through `useSyncExternalStore`. - Plugin `useVisible`/`useData` hooks run inside one cached wrapper component per slot. - `AppLayout` calls `useCorePageTitle` directly and feeds the same `PageTitleProvider`. **Guards** - `.oxlintrc.json`: `refs`, `immutability`, `preserve-manual-memoization`, `unsupported-syntax`, `incompatible-library`, `purity` and `set-state-in-effect` are now `error` for `apps/app/**` and `packages/shared-ui/**`. All their findings are fixed. - `apps/app/vite-react-compiler.ts`: - The app build (and the dev server, which shares the config) now uses `panicThreshold: "all_errors"`, so any skip fails the build. That includes the "Todo" bailouts lint can't see. - Errors now name the module (`React Compiler could not compile <path>: …`). - `testReactCompiler()` runs the same compiler in `apps/app/vitest.config.ts` for every test environment. Without that, node-environment tests were not compiled. It excludes `plugins/`, which ship without the compiler. - `packages/shared-ui/vitest.config.ts` runs the compiler too; this adds three devDependencies. **Real bugs that the compiled tests exposed (already live in production builds)** - `ThreadTitleMentions`: raw-thread mention titles read the query cache during render, so a title that arrived later never replaced the `thr_…` id. Now read through `useSyncExternalStore`, which subscribes to the query cache only when the markdown actually contains thread IDs. - `system-queries` `useKnownProviderModelCatalogScope`: read `getQueriesData` during render and never re-resolved to the host scope. - `PluginComposerActions`: a plugin plus/send menu row's `disabled(composer)` was cached against the stable composer handle and went stale. Now evaluated as a store snapshot. - `BbSourceCode`: the counter it bumped to force a re-render did nothing once compiled, so worker highlighting went stale. The pool version is now state. **Boot bundle budget:** `maxBootBrotliBytes` rose 3 KiB (425,055 → 428,127). About 100 newly compiled functions now carry memo caches; the boot payload measures 417.2 KB brotli. The raw limit is unchanged, and the reason is recorded in `bundle-budget.json`. **Plugin SDK bump** to 0.6.149. The SDK bundles `query-tags`, whose `useQuerySelection` cache moved into a module-level getter factory, so its published files changed. **Tests that faked updates** by mutating mocks and calling `rerender()` with identical props now deliver updates through reactive mocks (`useSyncExternalStore`). This covers composer-contract, PluginNewThreadComposer, SidebarUpdatesBadge, PluginTabs, CommandPalette, ThreadTableOfContents, MachineAccessSettings, PromptBoxInternal and ThreadSecondaryPanel.markdown-scroll. `ProjectDetailSettingsView` now waits for the lazily loaded remote browser's listing before saving. It raced that dynamic import, and the slower compiled transform exposed the race. Tests that called `experimental_use*` as members use `use*` aliases. **Small visible changes** (no others intended): - `InfoRowTime` relative times now tick once a minute while on screen. Before, they only refreshed when a parent happened to re-render, which compiled parents no longer do. - Message timestamp labels and a few pickers take "now" at mount or when they reopen, instead of on every re-render. - The voice-input "supported" flag is correct on the first render. **Rule workaround left in place:** `useAgentSignIns` resolves pending sign-in exits in an effect, through the file's existing latest-callback ref. The effect does real side effects when provider states settle (telemetry, closing terminals). A cleaner version would resolve from the refetch promise, which changes that contract. **Rebase onto main:** "Keep main's new handoff, split-layout and timeline code compilable" moves the `/handoff` `try`/`finally` into a module-level helper, records `SplitThreadArea`'s layout reconciliation during render instead of in an effect, and replaces a `??=` in `TimelineWindowedItems`. "Render timeline items without a per-item wrapper component" keeps the measurement revision counter in a `WeakMap` beside the measurements map, so `renderItem` is called directly as on main and finished timeline rows no longer re-render on a streaming push. Main's same-frame resize work (#7635) arrived after this PR; its new `useMeasuredValue` keeps the element in a ref so its pre-paint measurement satisfies `set-state-in-effect`, and the table of contents' visibility check now uses it. ## How you verified **Compiler coverage:** a counter runs the compiler over every git-tracked `.ts`/`.tsx` source. Source skips: apps/app 95 → 0, shared-ui 6 → 0, query-tags 1 → 0. The production profiling build passes with `panicThreshold: "all_errors"`. Before the query-tags fix, the panic caught that skip and failed the build. **Static checks:** `pnpm exec turbo run typecheck lint --filter=@bb/app --filter=@bb/shared-ui --filter=@bb/query-tags --filter=@bb/plugin-registry` passes, and `oxlint apps/app/src packages/shared-ui/src` reports 0 problems. **Targeted tests:** I ran the tests for every changed module with the compiler on in vitest, and they pass. That includes PluginNewThreadComposer 64/64, the composer-contract suites, sidebar navigation, ThreadDetailPromptArea 72/72, TimelineWindowedItems, query-tags, react-compiler-cache, and shared-ui 65/65. CI runs the full suites. **Render counts on the real built app.** Profiling build (react-dom/profiling plus a fiber-counting DevTools hook), the same dev server and fixture for both builds (a 122-item thread and 15 sidebar threads), and the same Chromium. Before is origin/main `da3e60b81d`. | Scenario | Before | After | |---|---|---| | Type 20 chars in the composer | 5,689 renders, 37.0 ms | 4,952 renders, 26.7 ms | | Title change on another thread | 1,713 renders, 7.9 ms | 1,674 renders, 6.4 ms | | Another thread runs a turn (per WS push) | 415 renders, 1.53 ms | 348 renders, 1.26 ms | | Open thread streams (per WS push) | 156 renders, 1.19 ms | 109 renders, 0.87 ms | | Wheel-scroll the timeline to the top / back down | 16,546 / 13,670 renders | 14,482 / 12,232 renders | | Idle 10 s | 0 | 0 | The remaining fan-out comes from context-held collections (sidebar entries, sender metadata, the composer `api`, plugin slots). Other threads own those. **Smoke test on the built app, before and after:** - Loaded the long thread and wheel-scrolled to step 1 and back to the bottom. - Typed into the composer and cleared it. - Navigated to a sidebar thread and back. - Streamed a new turn. Both builds behaved the same, with no page errors. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
smsunarto
added a commit
to smsunarto/bb-plugins
that referenced
this pull request
Nov 18, 2026
…BBP-14) (#184) * fix(t3-composer): size the empty composer editor to one line * fix(t3-composer): inset the Project and Environment search field from the sheet's top Monokai now draws bb's picker search row as a bordered field. T3 Composer's older rule zeroed its top margin, so the field touched the sheet's edge. Inset it 4px like the rows, size the field rather than the input so it no longer overflows the border, and give phones a 44px field with 16px text. * feat(t3-composer): open the desktop composer two lines tall The empty editor's minimum grows from one 20px line to two (48px). Touch screens keep their one-line 32px minimum. * fix(t3-composer): stop text typed after a mention pill from gluing onto it Port of get-bb/bb#6581 (38c939c85). Serialization adds a space between a pill and an adjacent word or pill, so the agent sees /review Also, not /reviewAlso. * fix(t3-composer): close a multiword @ query once it settles with no matches Port of get-bb/bb#7002 (631a62619). Typing on after an unmatched @query ("@see you later") no longer keeps an empty menu over the prose. Shortening the query back reopens it, shown again only once something matches. typeahead.test.tsx covers it in the mounted composer, since upstream's tests live in bb's app. * fix(t3-composer): cap the editor by the visible shell height Port of get-bb/bb#7061 (9519ec685). On iOS dvh ignores the software keyboard, so a long draft pushed the composer under the header. The caps now read BB's --bb-shell-height (bb 0.49 defines it), including the plugin's own !important thread-composer rule in app.css, which would otherwise keep the old 50dvh cap. * fix(t3-composer): keep slash command names visible when an argument hint is long Port of get-bb/bb#7565 (dafe34edc). A long argument hint, such as Claude Code's code-review, collapsed the command name and pushed the / menu sideways on phones. Description, then hint, now give way before the name. Uses gap-1, not upstream's gap-1.5, to stay on the plugin's 4px grid; the Storybook story is skipped since Storybook was removed here. * feat(t3-composer): run a built-in / command when its row is clicked Port of the composer part of get-bb/bb#7480 (1983b0dfb): a click on a built-in command now sends it, as Enter already did. The plugin's own /handoff stays excluded, so a draft before it is not sent with the handoff. #7480's host-side /handoff is not in bb 0.49 and the plugin keeps its own; its pill-delete cancel was already ported (a9aada1). * perf(t3-composer): share one resize observer and read before writing Port of get-bb/bb#7635 (2d04779a1). The composer's height tracker, editor cap and typeahead max-height observe through one shared ResizeObserver that runs every read before any write. lib/shared-resize-observer.ts is vendored from packages/shared-ui with its tests, less the case for useMeasuredValue, which this plugin does not have. bb 0.49's plugin runtime exposes the full react-dom namespace, so its flushSync resolves. * docs(t3-composer): record the upstream sync base and held changes The fork base d4fa9cb is not on get-bb/bb's main; its content matches 21d5db72c. The plugin is now synced through 2d04779a1. Also corrects the stated BB and SDK requirement to match package.json. * fix(t3-composer): clear the last 4 frozen lint errors Bare oxlint on the plugin now exits 0. Each is a reasoned suppression with precedent elsewhere in the repo: attachment videos carry no captions, the form delegates its children's keys and presses, the test fake mirrors BB's role-based picker DOM, and an object URL is created and revoked as one effect pair. Removes their lint-baseline entries.
smsunarto
added a commit
to smsunarto/bb-plugins
that referenced
this pull request
Nov 19, 2026
…3) (#187) * fix(scott-tasks): return a saved comment before agent delivery finishes Port of upstream get-bb/bb#4679. The app's createComment waited for the thread lookup and send before answering, so a slow or stuck worker held the composer. The app now returns the saved comment at once and delivers in the background; the CLI still waits so it can report the notified count. * feat(scott-tasks): move a task and its sub-tasks to another project Port of the server and CLI half of upstream get-bb/bb#4100. A moved task gets a fresh number in the target project, lands at the end of its status column, and keeps its old key as an alias, so mentions and agent instructions that name the old key still resolve. Labels are remapped by name and created when missing. A sub-task moved on its own leaves its parent. New: moveTaskToProject RPC and bb tasks move. * feat(scott-tasks): move tasks from the detail page and the list's context menu The UI half of upstream get-bb/bb#4100. The properties rail and inline chips get a project picker, and a list row's context menu gets Move to project. Opening a task by a key it had before a move asks the server and follows the task to its current key. * feat(scott-tasks): keep New task drafts and cap the dialog's height The dialog half of upstream get-bb/bb#4100. Title, description and attributes save to localStorage as they change, so an outside click, Escape or reload no longer throws a long task away; Discard draft clears it. The dialog is capped at 85dvh with the description scrolling, so Create task stays reachable. * fix(scott-tasks): port upstream touch, embed and download fixes - get-bb/bb#5097: label and preset row actions stay visible on screens without hover, such as a 13-inch iPad. - get-bb/bb#5157: a narrow desktop pane keeps the compact topbar; only touch screens get the taller one. - get-bb/bb#5903: the whole task embed card opens the task, and a loading card no longer highlights on hover. - get-bb/bb#5508: attachment downloads go through bb's saveFile, which the iOS shell implements with WebKit's native download. * docs(scott-tasks): document bb tasks move; drop unused hono and cron-parser hono 4.11.9 was a vulnerable pin that nothing imports; cron-parser is unused too. * feat(scott-tasks): delegate as a child thread from a chosen base branch bb tasks delegate takes --parent-thread, --parent-notifications auto|stuck|off and --base-branch, passed to threads.spawn. An orchestrating agent dispatches its crew as children so bb reports their turns to it, and starts each worktree from its own branch. --base-branch always means a new worktree, whatever the preset names, and leaves the preset unchanged. * fix(scott-tasks): let the attachment preview's img own its object URL Attachment chips set state in an effect to hold the preview URL; the <img> ref callback now creates and revokes it. Clears a react(set-state-in-effect) lint error. * feat(scott-tasks): owned fields, crew snapshot and parent wakes for Captain - defineField/setField: typed fields only the owning plugin may write; a write bumps the task's updated_at. - crewSnapshot({threadIds, changedSince}): one read of task, parent, fields, preset, live status and the last notifying comment with its delivery state. - bb tasks comment --notify-parent sends a one-line wake to the commenting thread's parent and retries from the database (1, 2, 5, 15 min; 6 attempts), then marks it undeliverable; --attach puts files on the comment first. - delegate takes reportContract and drops its built-in contract under stuck; taskThreadsAttach keeps presetName; plugin callers may author comments. - Task threads get an archived live status that unarchive reverses. * perf(scott-tasks): drop unused toolbar and command exports Cuts 10 KB of app.css that Tailwind generated for components nothing imports. * fix(scott-tasks): let the list's empty state fill the scroller Port of get-bb/bb#7613's Tasks part: the list's size container moves inside the scroller, and the empty state grows to fill it. * fix(scott-tasks): resolve CLI file paths with the target host's path rules Port of get-bb/bb#6760: file flags resolve with the SDK's host-path parser, so Windows drive and UNC paths from a remote thread resolve on that machine instead of with the server's node:path. * refactor(scott-tasks): drop store inputs nothing passes Port of the Tasks part of get-bb/bb#4606: create inputs no longer take an id, comment updates take only notifiedCount, attachment updates only blobPath, and new comments rely on the column's 0 default. The tie-break test sets its ids with SQL, as upstream's does. Skipped: upstream blanking the is_image migration (it already ran here), and displayWidth and the description saver's schedule option, which fork tests still use. * test(scott-tasks): cover list scope switches while reads are pending Ports get-bb/bb#7056's regression tests. Upstream fixed a list stuck behind placeholders when it switched scope to a cached list; the fork's collection-backed list already passes them, so no code change was needed. All shows every task the shared collection holds, so the All step checks no absent row. * fix(scott-tasks): apply resize-measured layout in the resize frame Port of get-bb/bb#7635's Tasks part. The board-width check and the list's row window read their size in a shared ResizeObserver and write it inside flushSync, so a resize never paints one frame of the old layout. lib/shared-resize-observer.ts is vendored from upstream's registry, which the desktop-v0.49.0 pin predates. The row window measures through a plain function of the element so the mount read stays a ref-derived layout measurement. * docs(scott-tasks): record the upstream sync to get-bb/bb 48c3a78 Names the new upstream base and every change the fork holds, with the reason for each. * fix(scott-tasks): settle the list's scroll scope during render, not from a ref ListView read settledScope.current during render, the one oxlint error left in scott-tasks (react(refs)), so bunx oxlint on the plugin failed. The settled scope is now state set during render, like the saved preference above it, and settles in the same render its rows finish loading. * fix(scott-tasks): stop an expired wake attempt from sending after a retry Promise.race ended the 30s wait but not the attempt, so a stalled thread lookup could resume after a retry had delivered and wake the parent twice. The deadline now aborts the attempt's signal, and the attempt re-checks right before threads.send (and before recording a target) that it is unexpired and still the latest claim on a pending record. Review's deterministic repro is the regression test; it fails on the old code. * chore(scripts): prune the resolved scott-tasks list refs baseline entry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
A
ResizeObservercallback runs after layout and before paint, but React applies a plainsetStatefrom that callback in a later task, after the browser has painted. Any layout derived from a measured size therefore painted one frame with the old layout at the new size. #7497 (context card), #5067 and #6488 (composer prompt stack) each fixed one instance by hand withflushSync. A survey found about 30 more sites with the same pattern: TOC show/hide, header action overflow, message action row count, "Show more" toggles, File Preview header buttons, panel size limits, resource toolbar, overflow fades, and others acrossapps/app,shared-ui, plugins andapps/web.Measured in headless Chrome, crossing a width threshold 10 times:
setStatein the observerflushSyncuseSyncExternalStoreWhat changed
observeSharedResizemoved fromapps/app/src/libto@bb/shared-ui/lib/shared-resize-observer, which also makes it a component-registry item for forkable plugins. It keeps the one-flushSync-per-batch writes andsettleAfterSharedResizeWritesthat Mount timeline rows without forcing layout from the scroll handler #7612 added, so React state from a resize renders before paint. It now also:ResizeObserveris missing.useMeasuredValue(target, read, initial)in@bb/shared-ui/hooks/use-measured-valuefor the simple ref-to-value case. It replaces usehooks-tsuseResizeObserverin the git plugin.bb/no-raw-resize-observerinscripts/oxlint-plugin.mjsrejectsnew ResizeObserverand usehooks-tsuseResizeObserveroutside the shared module, apart from tests and stories. Two files are exempt in.oxlintrc.jsonbecause their own callback batching only writes the DOM and doesn't set React state:scroll-position-keeper.ts: the timeline engine's own observer, which reconciles once per batch.apps/web.apps/app,shared-ui, 13 plugins andapps/webnow use the shared path. Read steps only read layout; write steps write the DOM and set state.flushSyncworkarounds in the sidebar header slot and context card are gone.flushSync, becausepositionKeeper.remeasure()must run after the new height commits.useIsOverflowing, markdown table geometry) import the moved scheduler.ThreadDetailHeaderkeeps a narrow/wide flag instead of the pane width, so a divider drag no longer re-renders the header every frame.shared-resize-observeritem, and expandable-text, question-form, resource-pagination and resource-toolbar now depend on it.No wire, CLI or user-facing configuration changes.
How you verified
packages/shared-ui/src/lib/shared-resize-observer.test.tsx:useMeasuredValuemeasures on mount and on each resize;flushSyncbatching removed.PluginThreadContextCard.tsx:371(Lay out the thread context card in the same frame as a resize #7497),FollowUpPromptBox.tsx:668(Fix timeline drift when thread context banner loads #5067) andFollowUpPromptBox.tsx:685(Keep the timeline still when a prompt banner appears #6488).pnpm exec turbo run typecheck lint --filter='...[origin/main]': 180/180 passed.pnpm exec turbo run teston every affected package passed after the fixes below:@bb/apptests failed because theirResizeObserverstubs called the callback without entries; I fixed the stubs.bb-plugin-connectconnect.test.ts(72/72)@bb/serverfiles (131/131)CommandPalette.test.tsxmarketplace-exposure.test.tsxplugin-guide.test.tsfailed because an interrupted bundling run had left a gitignoredplugins/.bundled-stage-*copy of navigation. Removing it made it pass.pnpm start:worktree, the experiment on and the context card pinned, I recorded every resize frame while opening and closing the right panel twice at 1440, 1600 and 2560px:🤖 Generated with Claude Code