Skip to content

perf(threads): warm bounded web and desktop caches - #623

Merged
nixuuu merged 1 commit into
perf/background-thread-warmingfrom
perf/thread-cache-web
Nov 13, 2026
Merged

nixuuu merged 1 commit into
perf/background-thread-warmingfrom
perf/thread-cache-web

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Web and the desktop renderer now keep a bounded set of inactive thread tails current before navigation. The shell warms working threads, unseen results, pins and the top 12 recent sidebar roots, excluding the archive.

Recent roots follow the shared Last activity rule (last completed reply, falling back to creation), regardless of the displayed Created or Custom order. Project/search filters determine eligible roots; manual ranks and pin positions cannot displace recent roots. Working/unseen/pinned threads join independently within the shared cap. Polish performance docs describe this rule; a real-gateway test reorders threads and verifies all three display modes and filtering.

One cancelable job fetches only sequence deltas, with a two-second minimum between starts, coalesced heads and 30-second failure backoff. The LRU holds at most 32 entries / 32 MiB of encoded payload. Navigation cancels background work and reserves 500 ms for the visible view. Hidden/offline clients pause. Cached tails seed the first thread render, and the visible watch resumes their checkpoint.

Diagnostics adds current-state-visible timing, warm-cache hit ratio, background request counts and cache payload bytes within the fixed client metric registry. Polish performance/diagnostics docs describe the budgets and measurement limits. The benchmark supports isolated named containers and avoids removing a pre-existing colliding container.

Validation on the final stack: install, gen:check, full typecheck, lint, format:check and web build passed with nice. Focused check:tmp passed cache warming 6 tests / 41 assertions, linked mirrors 1/36, schema 23/85, sidebar ordering 5/22 and client diagnostics 9/70, with empty temp directories. Current-head CI static checks, web/Linux build and commitlint passed; all four test shards are still running. A previous local full attempt was stopped after 1,092 passing tests and green CI on the preceding stack; it is not a completed local full pass for these heads.

Browser evidence: isolated synthetic stack on the requested second machine, 1,000 turns and 500 sidebar rows. A loaded-route sample measured 1,689.5 ms without cache versus 461.1 ms with current cache. Cold Vite route compilation also produced 4–5 second openings; these are not comparable to the loaded-route sample. The one-frame tap-to-current target is not established. The first thread state is seeded from the cache without waiting for its message watch.

The final-stack loaded-route probe, after completing a synthetic answer while on the list, had current cache before navigation: first feed rAF 168.9 ms, second rAF 217.9 ms, with the completed answer visible and no skeleton. This is a single development-mode sample, not a percentile or a one-frame claim.

The final-stack probe warmed 12 entries with 12 startup reads and 278,630 encoded bytes. One synthetic streamed turn caused 5 additional background reads over 66.5 seconds, with 283,312 encoded bytes afterward. The request count then stayed at 17 for another 120 seconds (zero additional idle reads/minute), with 283,162 encoded bytes. The browser reported roughly 139 MB total JS heap (coarse, not the cache's incremental heap). Light/dark at desktop and phone width were inspected; the Electron application itself was not profiled. The private remote stack and preview were removed after measurement.

Stack 624 is based on dev cfb9846, including the merged sidebar-sorting stack and #628 citations. gh stack rebase completed and left no rebase state. Current head: 4ed7d54. Measurements above precede these rebases, the recency-selection adjustment and the offline-mirror fix. All PRs remain draft.

Copy audit (§8): four new diagnostic labels use sentence case and plain, distinct meanings: “Thread current state visible”, “Warm cache hit”, “Background thread requests”, “Thread cache payload”. They add no buttons, confirmations, empty states or humor; existing layouts were checked with long synthetic titles. No merge requested.

@nixuuu
nixuuu added this pull request to stack #624 November 13, 2026 09:37
@nixuuu
nixuuu force-pushed the perf/thread-cache-web branch 2 times, most recently from 53a7fd0 to 0e5159d Compare November 13, 2026 10:33
@nixuuu
nixuuu force-pushed the perf/thread-cache-web branch from 0e5159d to 4ed7d54 Compare November 13, 2026 10:44
@nixuuu
nixuuu marked this pull request as ready for review November 13, 2026 10:56
@nixuuu
nixuuu merged commit 14cdfb0 into dev Nov 13, 2026
11 checks passed
@nixuuu
nixuuu deleted the perf/thread-cache-web branch November 13, 2026 10:57
nixuuu added a commit that referenced this pull request Nov 13, 2026
## Projekt workspace'u — zaakceptowany układ v2

Podgląd plików przechodzi z modala do zakładek jednego wątku. Sygnet
projektu, skracany tytuł i karty dzielą rząd nagłówka, z aktywną kartą
zawsze widoczną i przełącznikiem overflow. Prawy rail obsługuje jeden
minimalny moduł. Bez modułu podsumowanie jest dokowane i widoczne; z
modułem jest zamkniętą domyślnie kartą pływającą. Na wąskich ekranach
obie powierzchnie używają arkuszy.

Użytkownik zaakceptował układ v2 i udzielił jawnej zgody na
implementację. Przyjęte decyzje: jeden zastępowalny czysty preview,
utrwalany przez Edit/Keep tab/dwuklik, zakres cwd/worktree wątku i
mobilna edycja natywna bez kolorów podczas pisania (kolory w viewerze i
Preview changes). Usunięto sekcję otwartych decyzji.

Dokument uwzględnia jeden przycisk menu wiersza (#608), zachowanie
treści PR przy odświeżaniu (#611), bounded warming/cache transkryptu
(#622/#623/#629), niezależne sortowanie sidebara (#617/#619/#626),
kompaktowy tekst stanów preview (#634), poprawne stany ChoiceControl
(#637), kolejkę kontynuacji (#630) i podsumowania jej wierszy (#633).
Nie dodaje pełnych snapshotów ani prefetch plików podczas warming.

Siedem kompletnych warstw będzie osobnym stosem z podstawą dev.
Wszystkie PR implementacyjne pozostaną draftami do ukończenia i
weryfikacji całości oraz wspólnego scalenia przez maintenera. Migracje
muszą zachować monotoniczność względem aktualnego dev. Dokumentacyjny PR
po zielonym CI jest gotowy do scalenia przez maintenera.

## Weryfikacja i ograniczenia

- Rebase na dev `1626a3e6b05494e7aec77942bd818950468a3b58` bez
konfliktów.
- `nice -n 10 bun run format` i `nice -n 10 bun run format:check`
przeszły. Konfiguracja pomija Markdown; dokument sprawdzono ręcznie.
`git diff --check` bez błędów po usunięciu pustej linii końcowej.
- Brak zmian kodu aplikacji i kontraktów; testy wykonania oraz pomiary
budżetów należą do stosu implementacyjnego.
- Samodzielna makieta v2 poza repozytorium, 32 435 bajtów, przezroczyste
html/body, trzy stany × trzy szerokości × dwa motywy. Poprzednio
wyrenderowana i obejrzana bez błędów konsoli.

## Copy audit (§8)

Brak zmian produkcyjnych etykiet. Projekt zachowuje `Thread`, `Keep
tab`, `Thread details`, `Open in tab`, `Collapse panel` / `Show panel`
oraz dostępne nazwy obu kontekstów `+`. Zachowuje jeden przycisk menu
wiersza i kompaktowy tekst statusów pliku. Krótkie i długie etykiety są
pokazane w makiecie; rzeczywiste powierzchnie i stany będą audytowane w
każdej warstwie UI.
nixuuu added a commit that referenced this pull request Nov 14, 2026
)

## Root cause

Since #623 the web cache held only a 128-item **tail** of each thread,
and the background warmer saved that tail over full in-memory snapshots
(web and mobile). Switching away dropped `ThreadState`, folds and the
virtual feed's measured heights; returning rebuilt everything from the
tail and then **replaced** it when the watch increment arrived. Older
turns first rendered as `input` + work loading rows, a turn cut by the
tail showed a gap that collapsed, row keys changed and "Worked for" rows
faded in, so the visible content moved (48 px, CLS 0.26–0.28 on every
reopen of a thread whose last turn exceeds a page — the "Landing page"
shape: one turn with 21 commands, 24 tool calls and 18 subagents).

Two rendering faults made it flash:
- `padBottom` mixed `layout.total` (committed a frame later) with the
live `index.offset`, leaving up to a few hundred px blank below the last
row for one frame (the 133 px / 413 px one-frame hop seen in the video
and the probe).
- A new feed got its footer height only from the first ResizeObserver
callback, so its first frame had no end reserve and a 32 px composer
backdrop (CLS 0.0207 on every switch).

## Fix (target architecture: keep what was loaded, sync only what is
missing)

- `threadViews` (web): recently opened threads keep their client state
in memory — `ThreadState` with loaded older pages, `WorkFolds`,
`FeedBuilder` and the `SizeIndex` of measured row heights. LRU 12
threads / 12 MiB encoded; the visible thread is never evicted. Leaving a
thread caches its checkpoint in idle time.
- A return renders that state synchronously; the watch resumes from the
stored cursor (incremental batches only) and patches rows in place.
"Show earlier messages" is never needed for pages already loaded.
- Background warming (existing overview heads, no new streams) applies
newer checkpoints to retained threads off screen. The shared
`ThreadWarmer` no longer cuts snapshots to a tail; the cache owns its
bounds. Web memory keeps whole snapshots (32 entries / 16 MiB encoded,
objects shared with retained views); Electron disk keeps the tail.
- `VirtualFeed` takes a caller-owned `SizeIndex`, measures its viewport
and footer on mount (rows are positioned before the first paint) and
reads both padding ends from the live index.
- Cold opens stay hidden while the mounted window still shows work
loading rows (bounded by the existing 2 s positioning limit), so gaps
never collapse under the reader.
- A thread reopened at a saved reading position starts with the compact
composer in its first frame; a first message saved below the top padding
is restored at its distance (offset may be negative, up to half a
viewport).
- Short threads that do not fill the viewport stay **top-aligned**
(unchanged, consistent: rows start under the header, composer at the
bottom; following starts once content overflows).

### Review follow-up (head b03e40f)

- **A far-moved thread keeps its pages.** When a retained thread
advances more than 256 records off screen, the background read gets a
fresh 24-turn window. The warmer now reports that it *replaced* its
base; such a window never replaces a retained view. The view stays
behind with its loaded pages and cursor, warming continues from the
cache copy (no repeated window reads), and opening resumes the view's
own cursor: the visible watch replays only the missing records.
- **Background refreshes respect the budget.** Each applied refresh
re-accounts the encoded size and trims the LRU in idle time; shown
threads are never evicted.
- Retention moved into `RetainedThreads` (`@canopy/domain`) so it is
tested with the real gateway; web `threadViews` wraps it.

## Measurements

Private bench stack (`scripts/bench/client-stack.ts`, now also seeding a
1-turn thread and a thread whose last turn exceeds the first page),
production builds of `dev` and this branch against the same gateway,
Chromium 1400×900, after-paint sampling (rAF → task; `layout-shift` does
not count scrollTop hops, plain rAF reads precede ResizeObserver
corrections). Host load 5–10.

| | dev | this PR |
|---|---|---|
| Reopen, long last turn: visible moves | 1–3 per open (44–48 px, plus
−21/+21 px flash) | 0 |
| Reopen, long last turn: CLS | 0.278–0.297 | 0.0000–0.0001 |
| Every switch: CLS (composer backdrop) | 0.0207 | 0.0001 |
| scrollTop writes after reveal (long last turn) | 4–5 | 0–1 |
| Return to a scrolled-up thread, row offset vs leave | 0 px; 1444 px
(anchor lost) on the long-last-turn thread | 0 px everywhere |
| Cold open, long last turn | 48 px move, CLS 0.278 | 0 moves, CLS
0.0001 (revealed after the missing page) |
| Switch → first visible frame, p50 / p90 (12 returns × 2 rounds) | 185
/ 219 ms, 216 / 342 ms | 155 / 190 ms, 197 / 276 ms |
| Switch → settled, p50 | 193 ms, 235 ms | equals first frame (155 ms,
197 ms) |
| Rapid switching (30 switches, 80 ms apart) | — | no errors, one feed,
final thread at its end |

Memory: about 1.9 MB encoded per 1000 loaded items; heap is roughly 4×
that (8 history pages of the 1000-turn fixture ≈ 8.7 MB heap). Bounded
by 12 MiB encoded for retained views (≈50 MB heap worst case, shared
with the 16 MiB snapshot cache). In the same scenario (8 pages loaded,
two switches away) total heap after GC was 71 MB vs 82 MB on `dev`.

## Mobile

Mobile already renders its in-memory full snapshot synchronously
(`peek`) and resumes from the cursor; it shared the root cause through
the warmer, which replaced that snapshot with a tail — fixed in
`@canopy/domain`. Gaps (device checks blocked; typecheck passes): a
background window after >256 records still replaces the mobile cache
entry (web keeps pages and resumes); manual fold choices reset when a
thread is reopened (`useMemo` keyed on the thread), and cell heights are
not retained across screens.

## Tests

- `thread-warming.test.ts`: warming a loaded thread keeps its older
pages (fails with the previous tail save).
- `thread-warming.test.ts` (real gateway): a retained thread with a
loaded older page advances 300 records off screen; the warm gets a fresh
window, the retained pages and cursor stay, and reopening resumes with
batches only (no snapshot), keeping the pages and reaching the head
(fails if a window replaces the view).
- `thread-scroll.test.ts`: anchor offsets below the top edge.

## Checks

`bun install`, `gen:check`, `typecheck`, `lint`, `format:check`, web
build — clean locally. `check:tmp`: see below.

Copy audit (docs/copy.md §8): no UI text changed.

Fixes: #623
Related: #672
nixuuu added a commit that referenced this pull request Nov 14, 2026
When an off-screen mobile thread advances beyond the warmer's 256-record
replay limit, its fresh window currently overwrites the reader's loaded
history. Returning then loses older pages and the reading anchor.

Mobile now uses the shared `RetainedThreads` for recently opened views.
Fresh warm windows advance a separate cache copy, while the retained
view keeps its pages, history boundary and cursor. Reopening renders
that view and resumes its own cursor with incremental batches. Ordinary
background deltas still update retained views. Retention is bounded to
12 views / 12 MiB encoded, with mounted screens protected; existing
memory/disk cache limits remain separate. Pairing cleanup clears
retention before disk work.

Manual work-fold and tool-group choices now belong to the retained view
and survive reopening. Cell heights remain owned by native `FlatList`:
reusing them across screens would require a wider list-layout change and
device verification, so this follow-up leaves them unchanged.

The shared retention also guards an idle-leave race: accounting an old
retained view after a warm fallback cannot overwrite the warmer's newer
cache checkpoint.

Validation:
- `bun install`, `bun run gen:check`, full `bun run typecheck`, `bun run
lint` (repository oxlint), `bun run format:check`: passed locally with
`nice`.
- Focused `check:tmp` for `thread-warming.test.ts` and
`mobile-thread-cache.test.ts`: 16 passed, 128 assertions, no failures,
empty temp directory. Includes real-gateway web/mobile replay after 300
off-screen records, retained pages and cursor, batches only on reopen,
retention count/byte limits, shown-screen protection, pairing cleanup
and delayed-leave cache isolation. No UI suites added.
- iOS and Android Hermes exports: passed. iOS bytecode: 11,760,257
bytes; asset directory: 6,506,870 bytes. Android bytecode: 11,751,871
bytes; asset directory: 6,506,484 bytes. Production-profile EAS
fingerprints are unchanged before/after: iOS
`6ddec9ef559ee0095ac33e94ff9418a942053b17`, Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`.
- Additional Expo ESLint has existing React Hooks failures (91 errors /
19 warnings across mobile). Comparing the affected files against `dev`
found the same existing errors and two fewer warnings; no new errors.
The required repository oxlint check passes.
- Full suite is left to CI because host load rose above 8 during checks.
Device checks are blocked: no device host. Exports do not establish
native anchor/frame-time behavior.

Copy audit (docs/copy.md §8): no UI text changed. Polish
mobile/performance documentation updated.

`git show` confirms #623 introduced web/desktop warming; mobile's direct
cache-replacement adapter was added by #629. This corrects that
pre-existing mobile behavior, not #687.

Fixes: #629
Related: #687
nixuuu added a commit that referenced this pull request Nov 15, 2026
## Change

Running many threads made each renderer fetch background history and
repeatedly reload panels and PR lists. The BFF now materializes
overview, thread metadata and settings from one owner/target-scoped
`WatchOverview`, shares loaded read models and pushes complete
projections over SSE. Ready-key lookup is O(1); response encoding and
list traversal still scale with response size.

- Move bounded history warming to the BFF and remove renderer `/warm`
requests and panel/PR polling. Visible history and older pages remain on
demand.
- Share and reactively refresh panels, PR lists, proxies, model
catalogs, bots and updates. Bound caches/queues and fence old results
across reconnects, sharing resets and target changes.
- Allow independent diagnostics sessions with browser/BFF submission
cooldown, accept GitHub avatar version hashes, and keep infinite
decorative animations out of composer transition controls.
- Update the affected Polish architecture, API, performance,
diagnostics, connector and GitHub docs.

## Verification

- After rebasing onto current `dev`: 17 real-gRPC BFF integration tests
/ 100 assertions passed through `check:tmp`; temporary directory clean.
Web and integration-package typechecks and test-shard ownership check
passed.
- Earlier focused checks passed for diagnostics, avatars/panels,
shared-query invalidation/projection races, gateway/mobile/domain
typechecks, and edited-file lint/formatting.
- Inspected light/dark at desktop and phone widths. Reconnect recovery
and rapid thread navigation worked without page errors.
- Isolated browser probe with 12 synthetic thread submissions: the
observed renderer issued 3 HTTP requests over 12.1 seconds, with no
`/warm`, panel or PR-list requests. This is a synthetic sample, not a
production percentile.
- No user-facing copy changed. Full generated-code checks,
repository-wide checks, remaining test shards and builds are left to CI.

Fixes: #623
Fixes: #569
Fixes: #756
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.

1 participant