Repository navigation
fix(threads): keep opened threads in memory so opening never jumps - #687
Merged
Merged
Conversation
Reopening a thread rendered a 128-item cache tail, then replaced it when the watch increment arrived: older turns showed loading rows, a cut turn collapsed its gap, keys changed and rows faded in, so the feed moved under the reader. The warmer also overwrote full in-memory snapshots with that tail on web and mobile, dropping loaded history. Recently opened threads now keep their client state in memory (LRU 12 threads / 12 MiB encoded): items with loaded older pages, folds, the feed builder and measured row heights. A return renders that state in its first frame and syncs only the delta from its cursor; warming updates threads off screen in place. The web cache keeps whole snapshots (32 / 16 MiB); Electron disk keeps the tail. The feed measures its viewport and footer when it mounts, so retained rows are positioned before the first paint and the composer backdrop and end reserve are there at once. Bottom padding now reads the live size index, because a measurement not yet committed left a gap below the rows for a frame (the one-frame flash). A cold open stays hidden while its window still shows work loading rows. Saved anchors keep a first message's distance below the top edge, and the composer starts compact or expanded as the thread was left. Fixes: #623 Related: #672
A thread kept on the client that moved more than 256 records while off screen got a fresh 24-turn window from the background read, and the retained view took it wholesale: its loaded pages were gone and a saved anchor outside the window fell back to the end. Background refreshes also swapped snapshots without accounting their size, so warm threads could grow past the retained budget. Retention now lives in RetainedThreads (domain). The warmer reports when a read replaced its base; such a window never replaces a retained view. The view stays behind with its pages and cursor, warming goes on from the cache copy, and opening resumes the view's own cursor, which replays only the missing records. Every applied refresh re-accounts the size and trims the LRU; shown threads are never evicted.
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 14, 2026
When a connector notice arrives before the provider echoes a message, the web/desktop feed replaces the turn-input placeholder at the echo's later sequence position. Its entire work fold can then appear above the user's message, including messages with attachments. Place the echoed input immediately after its turn's start, before its work. Keep the echo's item identity and the sequence positions of steers, background work and notices. The same derivation repairs existing saved histories after reload. Inputs containing only attachments or quotes also retain their placeholder while their echo is unavailable. Gateway inspection confirmed that admission already persists the input and binds attachments atomically before dispatch; the draft path uses that same admission. Event `seq` correctly records arrival order and remains unchanged. Mobile already renders the persisted turn input before its body and excludes the initial echo from that body. The bug reproduces on current dev, including #673, #687, #689, #690 and the merged drafts stack. #670 introduced the connector acknowledgement before Codex `turn/start`, exposing the timeline's assumption that the input echo was the first element. #672 retained that assumption. Fixes: #670 Validation: - Added PostgreSQL/gRPC gateway regression: upload a PNG and Markdown file, send the message, publish an early connector notice and commentary, then publish the input echo. The test failed on the original dev feed (input row 3, work row 1). - Covers echoes with and without client IDs, placeholder replacement, open/closed work folds, steer chronology, completion, a fresh sequenced history subscription, and the mobile turn/body derivation. Both new cases and 27 existing feed checks pass under `check:tmp`; nothing remains in the test temp directory. - `nice` install, `gen:check`, typecheck, lint, `format:check` and web build pass with temp files under `/var/tmp`. Full suite left to CI because the shared 12-CPU host reached load 12.41 during verification. - No browser/device visual run; the change affects timeline derivation, with no component, styling or UI-copy changes. Copy audit: no changed UI text.
nixuuu
added a commit
that referenced
this pull request
Nov 14, 2026
Scrolling up a long thread could snap the view back to the end or jump it by hundreds of rows as older rows were measured. - Re-estimated rows above can shorten the scroll range below the reading position. The browser clamps to the new end; during a gesture that clamp counted as the reader reaching the end and turned following back on. A clamp is now layout: the anchor is restored. - A smooth scroll (wheel, Page Up) moves ahead of its scroll events. When settle took such a scroll in after a re-estimate, it recaptured the anchor from rows not yet corrected, often finding none. The anchor now moves by the reader's distance and settle corrects the rest in the same frame. Related: #687, #707
nixuuu
added a commit
that referenced
this pull request
Nov 14, 2026
…721) ## Problem Scrolling up a long thread sometimes moved the view by itself: it snapped back to the end, or jumped by hundreds of pixels to rows far above. It happened over the margin too, with no visuals (found while testing #707, reproducible on `dev`). ## Root cause Older rows are re-estimated as rows are measured (group averages). Two paths then lost the reading position: 1. **Clamp counted as the reader.** A re-estimate can shorten the scroll range by more than the reader's distance from the end. The browser clamps `scrollTop` to the new end. While a wheel/key gesture lease is active, `ScrollIntent` labelled that clamp `reader` with distance 0, so `followingAfterScroll` turned following back on and the view snapped to the end. 2. **Anchor recaptured from uncorrected rows.** A smooth scroll (wheel notch, Page Up) moves ahead of its `scroll` events. When `settle` (after `padTop` changed) took such a pending scroll in, `onscroll` recaptured the anchor from rows that the re-estimate had just moved, often by thousands of px. Often no row was on screen: the anchor was dropped, and the window then followed the estimate, about 165 rows away. ## Fix - `scrollOrigin` (`scroll.ts`): a position clamped to the end of a range that shrank below the last position is `unattributed` (layout). `settle` restores the anchor, in the same frame. - `followScroll` (`feed-anchor.ts`): a scroll taken in by `settle` (no event) moves the existing anchor by the reader's distance, instead of reading the rows on screen. `settleAnchor` then corrects the layout part in the same frame. Native scroll events still recapture as before. - #687 (cached threads, restored position) and #707 (scroll over visuals) logic is unchanged. A local check: scroll up, switch to another thread and back. The same row returns at the same offset. - Docs: `client-performance.md` has the measurement lessons (frames with no shared row are jumps; `layout-shift` also counts same-frame compensated corrections; check smooth wheel and Page Up). ## Measurements Private bench stack (`scripts/bench/client-stack.ts`), Chromium with smooth scrolling and `--site-per-process`. 120 steps per run, starting at the end. A probe samples every frame after paint (rAF, then a task) and compares the rows on screen with the previous frame. A **jump** is a frame where shared rows move against the scroll or further than one input step. A **teleport** is a frame with no shared row: a snap to the end or a leap to another part of the thread. `/dev/long-thread?turns=1000` (all 5000 rows loaded, mostly estimated): | Input (120 steps) | Width | `dev`: teleports (size) | This branch | | --- | --- | --- | --- | | Wheel −40 px | 1280 | 2 (−1188, −24060 px) | 0 | | Wheel −100 px | 1280 | 5 (−198 … −23980 px) | 0 | | Trackpad-like (4 × 8–32 px) | 1280 | 4 (−1196 … −24060 px) | 0 | | Page Up | 1280 | 30 teleports + 30 jumps (max 935 px) | 0 + 0 | | Wheel −40 px | 390 | 1 (−22155 px) | 0 | | Wheel −100 px | 390 | 2 (−22115, −2066 px) | 0 | | Trackpad-like | 390 | 2 | 0 | | Page Up | 390 | 33 teleports + 17 jumps (max 1262 px) | 0 + 0 | Seeded 1000-turn thread page (history paged in through the gateway): wheel and trackpad-like runs had no jumps on `dev` either. Paging keeps the estimated region small. Page Up had 5–6 teleports and 3–6 jumps (max 528–597 px) on `dev`, 0 and 0 on this branch, at both widths. With smooth scrolling off, `dev` Page Up had no jumps: the second path needs a smooth scroll. Real mouse wheels are smooth-animated on Linux and Windows, so the reported 360–400 px wheel jumps are likely this path. Synthetic CDP wheel events in headless Chromium are not animated, so they only reproduced the first path. `layout-shift` entries are not a jump metric here: a 3 px row growth with `scrollTop += 3` in the same frame also produces them on a plain test page, more during smooth scrolling. ## Browser check On a second machine with a fresh clone of this branch (own ports, own container, cleaned up afterwards), I ran the same 15-run matrix on both pages. It covered wheel −40 px and −100 px, trackpad-like and Page Up, at 1280 × 900 and 390 × 844. All runs had 0 teleports and 0 jumps, and visual travel matched input (e.g. 12000 of 12000 px). Page Up now travels about 75000 px over 120 presses, against 62000 on `dev` (the view no longer falls back). Cached threads (#687): scrolled up, switched to another thread and back. The same row returned at the same offset. No visual change, so no light/dark difference. After rebasing onto `dev` with #707, the same 16 runs (both pages, both widths, wheel −40 and −100 px, trackpad-like, Page Up) again had 0 teleports and 0 jumps. A clamp still wins over #707's hovered-frame attribution: a clamp is layout even while the pointer is over a visual. ## Checks `bun install`, `gen:check`, `typecheck`, `lint`, `format:check`, focused test (`tests/integration/thread-scroll.test.ts`, the clamp origin), web build. ## Copy audit (docs/copy.md §8) No UI text changed. Related: #687, #707
This was referenced Nov 16, 2026
nixuuu
added a commit
that referenced
this pull request
Nov 20, 2026
## Change - Web and desktop show the loaded timeline immediately. Scrolling up to a gap reads one older page. “Show earlier work” loads the selected turn, including turns that span several pages. On mobile, a gesture toward the history edge loads at most one page. - Web, desktop and mobile keep the live stream open when an older page covers the changes already received. If the stream advanced past the page, the client replays from the page checkpoint to recover concurrent edits and deletions. - Desktop persists a bounded history tail. Web and desktop limit inactive expanded content to 32 items and 8 MiB and cancel obsolete reads on reset. An oversized result stays available while in use. Clients reuse the measured size of an unchanged snapshot when leaving a conversation. - Header-only updates preserve the timeline rows. Unchanged controls and heartbeats still run validation and connection diagnostics while avoiding redundant view updates. ## Verification - Chromium on Linux, 2,160 items and 19 subagents. Opening the thread issued 0 older-page requests, down from 16 (453,590 response bytes). Checked scroll restoration, a multi-page turn, a quote, retry after a failed read and a timeline that fits on screen. Tested wide and narrow viewports in both themes. - Android emulator. A layout change after scrolling issued 0 history reads, down from 16. A gesture fetched one page on the existing stream. Twelve pairs of unchanged controls and heartbeats produced 0 React commits, down from 21. Sending a message and resuming from the background advanced and restored the live checkpoint. - With 4,608 synthetic items, 32 exits from an unchanged cached thread required 0 full encodings, down from 32. In a 10,000-item renderer probe, median header-update processing fell from 3.10 ms to 0.007 ms. Forty-eight expanded outputs of 512 KiB retained 7.5 MiB of inactive content, down from 24 MiB. - Targeted domain, history cache, gRPC replay, continuity, work-window and mobile synchronization checks passed, along with web, mobile and domain typechecks and repository lint on the edited files. The concurrent-deletion test compares a paged-and-resumed client with a continuously connected client. - Copy audit (§8) passed. The former idle “Loading earlier work…” label now reads “Show earlier work” and acts as a button. “Loading earlier work…” appears during a read and “Retry” after failure. The native equivalent uses the existing “Show earlier messages” button. - The Windows Electron and day-long Windows session remain unmeasured. Native testing used Android. Additional Expo ESLint reported pre-existing hook findings. Fixes: #300 Fixes: #302 Fixes: #541 Fixes: #556 Fixes: #672 Fixes: #687
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.
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 asinput+ 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:
padBottommixedlayout.total(committed a frame later) with the liveindex.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).Fix (target architecture: keep what was loaded, sync only what is missing)
threadViews(web): recently opened threads keep their client state in memory —ThreadStatewith loaded older pages,WorkFolds,FeedBuilderand theSizeIndexof measured row heights. LRU 12 threads / 12 MiB encoded; the visible thread is never evicted. Leaving a thread caches its checkpoint in idle time.ThreadWarmerno 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.VirtualFeedtakes a caller-ownedSizeIndex, measures its viewport and footer on mount (rows are positioned before the first paint) and reads both padding ends from the live index.Review follow-up (head b03e40f)
RetainedThreads(@canopy/domain) so it is tested with the real gateway; webthreadViewswraps 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 ofdevand this branch against the same gateway, Chromium 1400×900, after-paint sampling (rAF → task;layout-shiftdoes not count scrollTop hops, plain rAF reads precede ResizeObserver corrections). Host load 5–10.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 (useMemokeyed 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