Repository navigation
perf(web): reduce feed allocations and defer bot settings - #416
Merged
Merged
Conversation
nixuuu
force-pushed
the
perf/client-4
branch
3 times, most recently
from
November 9, 2026 16:50
71d9640 to
416ab15
Compare
nixuuu
marked this pull request as ready for review
November 9, 2026 16:54
nixuuu
added a commit
that referenced
this pull request
Nov 9, 2026
### Rebase verification — 2026-11-09 The five-layer stack is rebased onto `dev` at `2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and #421–#426. All PRs remain ready for review. The measurements below describe the original baseline; this section records the current integration verification. The attachment route now passes `If-None-Match` through #421's shared response helper. Gateway authorization/read succeeds before a 304 is possible; qualified IDs, thumbnail fallback, bounded preview/truncation, sanitized public failures and `no-store` errors are retained. Mobile image caching retains public error messages and reconnect retries. Session startup, replacement pairing, unpair and revocation retain all four caches: transcript, bot, archived sidebar and images. The branch/worktree panel, channel identity and sheet gesture changes remain intact. Passed on the rebased top branch: `bun install`, `bun run gen:check`, full `bun run typecheck`, root `bun run lint`, `bun run format:check` and the production web build. Final focused `check:tmp`: **27 passed, 0 failed, 334 assertions across 7 files**, no temp leftovers (images, immutable HTTP, transcript/archive/bot caches, two-gateway linked previews and composer choices). Coverage includes a matching old ETag returning 404 after ownership changes and 409 while the home is unavailable, with `no-store` and no ETag; image/archive caches are wiped together and late callbacks cannot restore them. EAS CLI **27.4.1**, production profile, before/after the image-cache and preparation layers and on the final top branch: **unchanged relative to the latest dev baseline**: - iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e` - Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae` These differ from the original measurement hashes below because #424 already changed native branding/configuration on dev. This stack adds no native dependency/configuration change. Final production Hermes exports passed sequentially with one Metro worker: iOS **9,971,620 B**, Android **9,961,323 B**. These include the newly merged client features; the earlier performance comparisons below retain their original baseline. Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict files reports the same pre-existing `react-hooks/set-state-in-effect` finding in `useImage.ts` on both this head and unmodified `origin/dev`; session cleanup has no Expo ESLint findings. The required root oxlint check passes. No full local test run was started, as requested for the overloaded shared machine. The earlier full-run timeout below is historical; **GitHub CI is the current full-suite merge gate**. No native builds, EAS builds, OTA publication or UI test suites were added. Previous on-device profiling gaps remain. --- Reuses prepared timeline entries for unchanged turns, makes sibling item grouping linear, and avoids encoding/writing an identical immutable snapshot repeatedly. New snapshot revisions still serialize and persist; failed writes remain retryable, eviction allows a later resave, and unpair/close fences remain intact. | Metric | Before | After | Method / environment | |---|---:|---:|---| | Prepare 5,000 sibling items, median / p95 | 39.198 / 43.052 ms | 1.954 / 3.728 ms | Bun 1.4.4, 10 samples after 5 warmups | | Save the same immutable 14,085,915-byte snapshot, median | 30.218 ms | <0.001 ms | Warm duplicates; in-memory storage adapter, no disk | | Save a new immutable snapshot, median | 28.767 ms | 28.841 ms | Same adapter; serialization still required | | Cold cache load/decode, median | 21.348 ms | 20.932 ms | New cache per sample, same encoded bytes; no disk | | iOS Hermes bundle | 9,900,217 B | 9,901,992 B | Sequential `expo export --platform ios` | | Android Hermes bundle | 9,889,662 B | 9,891,426 B | Sequential `expo export --platform android` | CPU harness: deterministic 1,000-turn / 7,099-item snapshot on Linux x86_64, Ryzen 5 5600X, shared 15.5 GiB machine. The before and after control runs were consecutive while repository checks ran; this is not an exclusive-CPU lab result. The grouping instrumentation retains 999/1,000 group arrays after one item changes. That is reference retention, not a measured React render count. Native fingerprints, EAS CLI 27.4.1, production profile, before = after: - iOS: `2a0ef03a2a0fda8e7fad2e3df8609803d2edbda3` - Android: `c5c880ae8d0f5d7bc867fcbaf8f756b2ca56a07d` Only JS/TS changes; no native build, dependency, EAS build or OTA publication. The exports establish bundle sizes, not runtime FPS. Validation: durable bounded mobile cache integration cases passed (4 tests, 34 assertions), including retry, concurrent duplicate saves, disk eviction/resave and close fencing. Whole-stack checks are recorded on the top PR. No UI tests or changed UI copy. Additional Expo ESLint check: 18 errors and 1 warning on both the frozen baseline and this branch, all in unchanged files (effects/ref rules and Expo Updates namespace imports). The required root oxlint check is clean. These existing Expo lint findings were not suppressed or folded into this performance change. The table records the isolated preparation change measured before the image-cache layer was added. Original cumulative final Hermes sizes, including that layer: iOS 9,927,705 B and Android 9,917,398 B; both native fingerprints were identical to that baseline. The image-cache measurements and limitations are in #419. Original full-suite status is recorded on #416: one unchanged composer-shell timeout remained unresolved at that handoff. On-device work remains: React Native commit/render counts, Hermes JS/UI frame times, real filesystem read/write latency, variable-height FlatList window tuning, and native bitmap/process memory after repeated image-viewer visits. `docs/client-performance.md` gives the workload and profiling procedure. This layer leaves FlatList settings and image viewer behavior unchanged relative to #419.
nixuuu
added a commit
that referenced
this pull request
Nov 10, 2026
Busy threads used to repaint shimmering labels and synchronously measure the virtual feed while streaming. Running-work decorations now use compositor transforms/opacity, visible elapsed labels share one clock, and unchanged history/indexes stay out of the streaming update path. The soft highlight, spinners, durations, disclosure motion and reduced-motion behavior are preserved. ### Changes - Replace background-position shimmer with a static text raster, a translating soft mask and counter-translating highlight. Chromium identifies both layers as active accelerated transform animations; no blanket `will-change`. - Share elapsed/relative clocks; second ticks update only a text component. One IntersectionObserver pauses clocks/decorations outside the viewport and document visibility stops hidden-page work. Mobile uses foreground/viewport guards, one elapsed clock and non-interactive native animation loops. - Cache independent completed feed prefixes with conservative invalidation for edits, late results/notices, fold preferences, nesting and cross-turn background work. Retain structural row metadata so text deltas do not rebuild size indexes/entrances. - Batch clipped-text reads, retain motion tokens until root appearance changes, and let ResizeObserver handle content growth instead of forcing scrollHeight reads on every delta. Contain layout/style in virtual rows and layout/paint in capped code surfaces. - Add Polish rules to `docs/client-performance.md` and pure data/index regression coverage. No UI test suite or diagnostic artifacts are committed. ### Maintainer trace Read-only analysis of the supplied 20.254 s trace (120 Hz recording): | Event | Count | Main-thread time | | --- | ---: | ---: | | Style recalculation | 2,271 | 4,528.43 ms | | Layout | 273 | 142.18 ms | | Paint | 2,108 | 404.09 ms | | Pre-paint | 2,397 | 999.48 ms | | Layerize | 1,874 | 1,077.97 ms | | Commit | 1,875 | 168.06 ms | 1. Renderer main was busy **49.94%** of the recording. There were **27 long tasks** (79.98/min), maximum **213.57 ms**, and **557/2,431 dropped-frame deadline markers (22.91%)**. The recording is 120 Hz; these are not 60 Hz rAF estimates. 2. Long-task self samples point to `VirtualFeed.svelte/settle` (`Me`, `n4KsTDu5.js:42:17016`, approximately **931 ms**), native `getPropertyValue` under `motion.ts/rootToken` (**650 ms**), `AgentMessageBubble.svelte`'s resize measurement (`n4KsTDu5.js:3:1049`, **224 ms**), native `offsetWidth` (**165 ms**) and `clipped.ts/measure` (`B-CkncHS.js:1:286`, **127 ms**). Embedded compiled source was read to map these sites. Sample weights are estimates, not additive inclusive timings. **206 invalidation-followed-by-script layouts** cost **122.08 ms**; **36 tasks** contained multiple layouts. 3. The original CSS shimmer animates background-position and needs main-thread paint. Repeated animation observations include **916 transform-acceleration failure flags** (763 × 1024 and 153 × 132096), **38 moving-pixel filter flags** (4096), and **15 observations with the unsupported-CSS-property bit** (8192). These are state observations, not distinct animations. A partial start record identifies an `ARTICLE.t-unfold`; without a complete DOM/CSS snapshot and starts for pre-existing animations, the full target inventory and `will-change` count cannot be recovered. The live baseline inventory below supplies steady counts. Spins/pings use CSS transforms/opacity; there is no JS spinner rAF loop in the inspected components. Flag meanings follow Chromium's `CompositorAnimations::FailureReason` enum; unidentified/one-shot effects are not assumed to be the shimmer. 4. **11 newly installed one-second repeating fold timers**, **30 token-cache rAF requests**, and **225 rAF callbacks / 460.64 ms** occur in the trace. Some persistent timers were installed before recording. Code inspection confirms per-fold/per-background-task one-second clocks and a shared slower relative clock. The synthetic trace additionally exposes whole-history rebuilding per delta: long-task self samples include **887 ms** of feed shallow comparison, **597 ms** of row reconstruction and **505 ms** in `buildTimeline`, besides **1,219 ms** in `settle`. 5. GC is secondary in the maintainer recording: **19 top-level pauses / 56.82 ms**, largest **10.53 ms**. Used JS heap grows **53.62 → 66.13 MB** (peak **78.61 MB**); DOM counters include detached nodes and do not prove a leak. The supplied recording has frame markers and renderer Layerize/Commit, but no timed compositor/Viz draw stages recognized by the analyser; GPU/compositor totals are unavailable, not zero. The local trace separately records compositor prepare/draw and Viz draw time, which must not be added to nested main-thread stages. ### Reproducible comparison Linux / AMD Ryzen 5 5600X / Chromium 155 / Bun 1.4.4; 1512 × 949, dark theme, warm Vite fixture. Baseline is `8b6492d84a0c38e4df08f0d6b2e344e99cc4439c`. Both runs load all 1,000 turns, four expanded running subagents and their tray, six running sidebar rows alongside the seeded 500-thread sidebar, four elapsed headers, and four expanded commands. A 40 ms interval applies an agent text delta plus a round-robin tool-output delta through the real ThreadState and production components. Requested load is identical; an overloaded baseline delivers fewer ticks. No builds/checks ran alongside these two-minute recordings. | Metric | Before | After | | --- | ---: | ---: | | Recorded window | 120.035 s | 120.022 s | | Main-thread busy | 97.26% | **54.17%** | | Long tasks/min (> 50 ms) | 77.48 (155 total) | **2.00 (4 total)** | | Dropped-frame deadlines | 39.91% (2,874/7,202) | **4.86% (350/7,202)** | | Average rAF frame gap | 27.85 ms | **16.72 ms** | | p95 rAF frame gap | 50.10 ms | **16.70 ms** | | Style + layout / second | 113.44 ms | 115.33 ms | | Delivered streaming ticks (target 25/s) | 2,546 (21.21/s) | **2,998 (24.98/s)** | | Style + layout / delivered tick | 5.35 ms | **4.62 ms** | | Script-forced layouts | 2,586 / 8,971 ms | **35 / 32.39 ms** | | Paint time | 20,880 ms | **16,426 ms** | | GC pauses | 655 / 1,911 ms | **121 / 255 ms** | | Trace used heap, first → last | 113.49 → 340.67 MB | **129.27 → 134.03 MB** | | Trace peak used heap | 482.86 MB | **201.96 MB** | | Follow-end gap after two minutes | 0 px | **0 px** | The after run processes **17.8% more streaming ticks**. Absolute style/layout per second is essentially unchanged; cost per delivered update is lower. **The stressed developer build is still 54% busy and misses about 5% of compositor deadlines, so this does not demonstrate fully idle main-thread usage or flawless 60 fps.** It removes sustained rAF jank and most long tasks while preserving follow-end. The remaining cost includes growing output layout/paint, the real sidebar feed and tracing/dev instrumentation. Busy % is the union of renderer-main RunTask wall intervals inside explicit measurement marks. Long tasks are RunTask > 50 ms; dropped % counts trace BeginFrame/DroppedFrame deadlines. Average frame gap comes from rAF, not compositor presentation. Heap is used heap, not retained heap after GC; it includes a growing transcript and dev tooling, so these readings do not establish a leak. This synthetic Linux developer build is not a repeat of the maintainer's macOS desktop workload. The steady live baseline has **23 CSS animations** (5 background-position shimmers, 14 spins, 4 pings), versus **28** after (the 5 shimmers each use two transforms, plus the same spins/pings). There are **0 transitions and 0 `will-change` elements** in both steady inventories. The inspected after shimmer/spinner layers report **“Has an active accelerated transform animation or transition.”** Paused offscreen nodes remain mounted and can retain a layer, but their animations stop advancing. An isolated five-second decoration/clock recording paints only **0.51 ms total**, with no dropped deadlines; it includes the still-connected dev application and is not a clean CPU-idle benchmark. The after browser run checks that it starts at the end, then records **0 px end gap** and **0 px reader-anchor drift** during a subsequent three-second stream after a real wheel gesture. Light/dark, 1512 px desktop and 390 px phone screenshots, long-label truncation, offscreen pause and reduced motion were inspected. Headless Chromium kept both tabs visible: hidden-page lifecycle was verified with a simulated `document.hidden`/visibility event, and the clock did not advance until resume. Native mobile visuals/runtime profiling and the macOS Electron renderer were not run. ### Validation - `bun install`; `bun run typecheck`; `bun run lint`; `bun run format:check`; `bun run --filter @canopy/web build` — passed. - `bun test apps/web/test/feed-prefix.test.ts apps/web/test/feed-rows.test.ts apps/web/test/work-fold-state.test.ts` — **12 passed, 82 assertions**. These exercise pure feed/index state, not UI components. No UI/E2E suite or full integration/temp suite was run. - iOS and Android JS/Hermes exports — passed. Native project generation/build/publication was not performed. - `bunx [email protected] fingerprint:generate --platform <ios|android> --build-profile production --json --non-interactive` — before/after identical: iOS `6ddec9ef559ee0095ac33e94ff9418a942053b17`; Android `5f6eae3ab278f1cd543e9ed763f923a319b65ec9`. Copy audit (§8): visible copy is unchanged (`Working`, `Working for …`, `Thinking`, durations and unavailable-time placeholders). Existing duration accessibility labels and truncation are retained. Checked short/typical/long labels at desktop and phone widths in light/dark. No new glossary terms, controls, errors or empty states. Artifacts are outside the repository in `/var/tmp/canopy-anim-perf/`: `analyse.py`, `measure.mjs`, `qa.mjs`, `fixture.patch`, `maintainer-report.json`, `before-final-{trace,report,metrics,inventory,layers}.json`, `verified-final-{trace,report,metrics,inventory,layers,anchor}.json`, `isolated-animations-{trace,report}.json`, `qa.json`, screenshots and check logs. Earlier exploratory traces are retained separately; the table uses only `before-final` and `verified-final`. The scratch runner temporarily exposes the fixture ThreadState using `fixture.patch`; that exposure is removed from the submitted code. The analyser reconstructs X/B/E spans, merges nested timing intervals, samples ProfileChunks, correlates invalidations/script layouts, inventories timer/rAF callers and extracts embedded source text without executing it. Related: #413, #414, #415, #416, #417, #418, #419
This was referenced Nov 13, 2026
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.
Rebase verification — 2026-11-09
The five-layer stack is rebased onto
devat2580ed75cdfc162e98e125b7c4d0b24eb81901b7, including #418 and #421–#426. All PRs remain ready for review. The measurements below describe the original baseline; this section records the current integration verification.The attachment route now passes
If-None-Matchthrough #421's shared response helper. Gateway authorization/read succeeds before a 304 is possible; qualified IDs, thumbnail fallback, bounded preview/truncation, sanitized public failures andno-storeerrors are retained. Mobile image caching retains public error messages and reconnect retries. Session startup, replacement pairing, unpair and revocation retain all four caches: transcript, bot, archived sidebar and images. The branch/worktree panel, channel identity and sheet gesture changes remain intact.Passed on the rebased top branch:
bun install,bun run gen:check, fullbun run typecheck, rootbun run lint,bun run format:checkand the production web build. Final focusedcheck:tmp: 27 passed, 0 failed, 334 assertions across 7 files, no temp leftovers (images, immutable HTTP, transcript/archive/bot caches, two-gateway linked previews and composer choices). Coverage includes a matching old ETag returning 404 after ownership changes and 409 while the home is unavailable, withno-storeand no ETag; image/archive caches are wiped together and late callbacks cannot restore them.EAS CLI 27.4.1, production profile, before/after the image-cache and preparation layers and on the final top branch: unchanged relative to the latest dev baseline:
bf3156a1bd878e10c0b0be25d4c194a837fb1b7ed638e5f7b7fa87f54ccc0715c5fe150b8c0ad3aeThese differ from the original measurement hashes below because #424 already changed native branding/configuration on dev. This stack adds no native dependency/configuration change. Final production Hermes exports passed sequentially with one Metro worker: iOS 9,971,620 B, Android 9,961,323 B. These include the newly merged client features; the earlier performance comparisons below retain their original baseline. Expo Doctor: 20/20. An additional Expo ESLint check of the conflict files reports the same pre-existing
react-hooks/set-state-in-effectfinding inuseImage.tson both this head and unmodifiedorigin/dev; session cleanup has no Expo ESLint findings. The required root oxlint check passes.No full local test run was started, as requested for the overloaded shared machine. The earlier full-run timeout below is historical; GitHub CI is the current full-suite merge gate. No native builds, EAS builds, OTA publication or UI test suites were added. Previous on-device profiling gaps remain.
Reduces allocations while retaining unchanged feed rows and loads the bot settings editor only when it is first opened. Provider discovery and the dynamic import run concurrently; the existing loading/error dialog, generation fence and close animation remain in place. Web and the Electron renderer share this build.
/threads/[threadId], shell + layouts + page, deduplicated/settings/general, same accounting/bots/[botId], same accountingEnvironment: Bun 1.4.4, Linux x86_64, Ryzen 5 5600X, shared 15.5 GiB memory, Chromium 156 at 1280×800. JS data: 1,000 turns, 7,099 items, 14,085,915 protobuf bytes. CPU comparisons use identical deterministic input; no exclusive-CPU claim. Dynamic imports and highlighter grammars are excluded from initial static closure totals.
The browser samples are descriptive measurements on a shared machine, not statistically significant navigation or SSE speedup claims. BFF coalescing delivered 49 delta messages before and 36 after in the sampled network turns. The SSE reducer was not optimized here. Initial real snapshots were 24-turn pages, not all 1,000 turns; their sampled payloads differ after synthetic turns, so no snapshot speedup is claimed.
Visual verification: real seeded thread with a 64× long answer, desktop 1280×800 and phone 390×844, light and dark, streaming, anchored composer, lazy bot editor initial open/close/reopen and error display. No horizontal document overflow observed. A visible completed answer retained exactly the same viewport y coordinate (-465.664 px) throughout a subsequent 8.2-second streamed turn while reading history. The fixture stayed at zero bottom gap after streaming. Motion code and tokens are unchanged; reduced-motion emulation was not available through the shared browser tool and was not runtime-verified.
The existing timeline virtualizer limits mounted articles, but a single huge answer still creates all its Markdown DOM and the 500-row sidebar eventually mounts in full (26,215 total elements in the settled seeded production page). The isolated fixture's mounted element count was 164 before / 114 after at sampled positions; variable visible rows make this unsuitable as a DOM-reduction claim. These are remaining candidates, not fixed problems in this PR.
Original validation:
bun install,gen:check, fulltypecheck, rootlint,format:check, production web build and both Expo exports passed. The original final fullcheck:tmpfinished with 1,919 pass / 161 skip / 1 fail, 22,240 assertions, 1,050.58 seconds, no temp leftovers. The unchanged composer-shell test “Stop during a shell steer kills its group and persists the failed delivery” hit a 10-second RPC cancellation in both original final full runs; its focused retry passed. At that handoff, the full gate was unresolved and the stack was draft. No timeout, assertion or backend changes were made to obtain a pass. No UI test suite was added.The long run was worse under its recorded conditions; it is not evidence of a performance win. The concurrent suite took 1,580 seconds versus 1,029 seconds in the earlier successful run, confirming substantially different observed runtime conditions without proving the cause of either result. Heap counter growth cannot establish retained memory or the absence of leaks; a DevTools memory profile with controlled GC remains necessary. No memory improvement is claimed.
A subsequent short control without the full suite, using the same 1,000-turn fixture (after first, then before), recorded:
The short control did not reproduce the long-task regression and does not establish long-session memory stability. A controlled CPU/memory profile remains open before claiming an overall long-session improvement. The paired Bun harness and bundle accounting are the primary evidence for this change.
Failure follow-up: unchanged ask-user, composer-shell and thread-mirror-deltas files passed together (42 tests, 226 assertions, 0 failures, clean temp directory, 38.70 seconds). The subsequent full run passed ask-user and mirror cases but repeated the composer-shell timeout. This does not establish the cause or make the full gate green.
The final stack includes the focused image-cache layer #419. Browser validation on that final stack: 20 real thumbnails, 803,816 body bytes on first pass, zero additional network requests/body bytes on a second pass or reopening the thread. Existing web immutable caching already provided repeat reuse; no additional web transfer improvement is claimed. ETag/304, distinct variants and no-store 404 were observed. Mobile final Hermes bundles are iOS 9,927,705 B / Android 9,917,398 B, with unchanged production fingerprints. Final route bundle accounting is identical to the table above.
The five focused cache and immutable HTTP checks passed (39 assertions), including in the final full run. Expo Doctor passed 20/20 checks. All owned benchmark servers and browser tabs were closed before the final full checks.
Copy audit: no changed application UI text. No UI test suite was added. Polish documentation records row equality, lazy loading and the measurement method. This does not change FlatList tuning, markdown parsing, native image memory, Electron main-process caches or synchronization semantics.