Skip to content

Transcript re-pins to the bottom when content grows after the hold window #397

Closed
3 of 3 issues completed

Description

@omridevk

Parent: #381. Blocked by: none — can start immediately.

What to build

The transcript stops yanking itself to the bottom while the user is reading something higher up.

Mechanism. use-thread-auto-scroll observes the viewport subtree for class / data-state changes and
resizes, and routes them to chased() in thread-follow-machine. That function decides whether to re-pin
using state.atBottom — the last published value, not a fresh measurement — so any height change while
that stale flag is still true instantly scrolls to the bottom. CollapsibleCard covers the deliberate case
with holdPosition() for 350ms, which comfortably covers the 200ms open animation. Anything that changes
height outside that window is unprotected.

Tool cards now add exactly that: captures resolve asynchronously and mount a fixed-height preview frame in
many cards at once long after any hold; the frame's class then transitions loading → ready → or the failed
state which collapses it back to zero; and the ready transition is gated on an in-iframe font load with no
bound. Each is a separate unheld resize, and each re-pins if atBottom was last published true.

Fix: recompute rather than trust — chased() should ask whether the viewport is at the bottom now
(the helper already exists in that module) instead of reading the stale flag. Then a resize only re-pins
when the user really is at the bottom, and content growing above the fold stops dragging them down.

Do not fix this by lengthening the position-hold window or wrapping the preview in another hold. The
iframe font load has no bounded duration to hold for, and that direction adds a timing constant that will
be wrong on the next slow machine.

The latch is pre-existing on main; this branch supplies the new triggers. An RCA drove the page for ~10s
across several interaction patterns and could not reproduce it on a settled transcript — the loaded
session had zero previews on screen, so the mechanism above is derived from code and the branch diff, not
from a live repro. Expect to need a streaming run with captures to reproduce.

Acceptance criteria

  • With the viewport parked mid-transcript, content growing below it after the hold window expires does
    not move the reading position
  • Scroll-to-bottom still follows new content when the user is actually at the bottom
  • A browser test covers the parked-viewport case, asserted by screenshot rather than scrollTop — this
    is layout, and there is no test today where content grows after the hold window

Sub-issues

Sub-issues

3 of 3 Issues completed
Loading 3 sub-issues

Activity

  1. added
    ready-for-agent
    on Aug 10, 2026
  2. omridevk commented on Aug 11, 2026

    @omridevk
    ContributorAuthor

    Research findings: our scroll/collapse UX vs assistant-ui, AI Elements, CopilotKit

    We surveyed three reference implementations (assistant-ui from the local clone, Vercel AI Elements + its use-stick-to-bottom dependency, CopilotKit v1/v2) against our ui-kit-chat plumbing. Three separate defects fell out; this issue owns the first one. Findings below so the mechanism and the reference patterns are on record.

    1. The re-pin bug (this issue) — mechanism confirmed, fix validated

    Confirmed in code exactly as described above:

    • thread-follow-machine.ts:44 already has the fresh helper (isAtBottomNow: |scrollHeight − scrollTop − clientHeight| ≤ 1, or shorter-than-frame).
    • chased() (thread-follow-machine.ts:110) instead consults state.atBottom, which is only refreshed by published() on scroll-derived paths. Any resize arriving before the next scroll event lands sees a stale true and re-pins.
    • onResized (thread-follow-machine.ts:124) also short-circuits when dimensions are unchanged, so nothing between scroll events ever re-evaluates the flag.

    Every reference library does what the fix prescribes:

    • assistant-ui (packages/react/src/primitives/thread/useThreadViewportAutoScroll.ts) recomputes at-bottom from the live DOM on every scroll/resize; there is no cached flag consulted at decision time. It additionally treats an upward scrollTop move as user intent only when scrollHeight is unchanged, so content reflow above the viewport is never misread as a user scroll.
    • use-stick-to-bottom (used by AI Elements' Conversation and CopilotKit v2) gates the resize-driven scroll inside the animation loop itself: if (!state.isAtBottom) { state.animation = undefined; return false }. Growth only chases when genuinely pinned.

    So: chased() recomputes isAtBottomNow(at) from the measurement onResized already receives, instead of reading state.atBottom. No new timing constants — consistent with the issue's "do not lengthen the hold window" constraint.

    Hardening candidates the references suggest (follow-ups, not blockers for this fix):

    • Shrink vs growth asymmetry (use-stick-to-bottom): when content shrinks and the viewport is near-bottom, it silently re-locks rather than scrolling — a collapsing panel never yanks a reader. Our machine treats all resizes alike.
    • Immediate escape hatches: use-stick-to-bottom escapes the pin on wheel with deltaY < 0 immediately (before any scroll event) and while text selection is active; assistant-ui cancels pending scroll intent on pointerdown. We listen on wheel/touchmove/keydown but a scrollbar-thumb drag or selection during streaming still races the observers.

    2. Adjacent finding: chain-of-thought/reasoning auto-collapse flapping (not this issue — proposing a sibling ticket)

    This is the likely mechanism behind the "cards snap shut / reopen weirdly while streaming" complaint:

    • Ours: open = userOpen() ?? streaming (chain-of-thought.tsx:26, same shape in styled/reasoning.tsx:8), where streaming is wired as thread.isRunning && message.isLast() && isLastSegment(segmentIndex) (styled/thread.tsx:113,133). The moment any new segment is appended (reasoning → tool → reasoning, or trailing reply text), the previous card's streaming flips false and it collapses instantly mid-read — no grace, no latch. Each flap also re-arms a 350ms holdPosition() window (two call sites: collapsible-card.tsx:118, chain-of-thought.tsx:69), so during active streaming the viewport freezes/thaws in lockstep with cards silently closing.
    • AI Elements (reasoning.tsx): auto-open on stream start; auto-close fires once, 1s after the part's own stream ends, latched by hasAutoClosed — never re-arms, and a user toggle suppresses it.
    • CopilotKit v2 (CopilotChatReasoningMessage.tsx): same shape with an explicit userToggledRef; closes on the part's own isStreaming → false, one-shot.
    • assistant-ui (reasoning.tsx): open while the part streams, first manual toggle wins permanently; plus a useScrollLock that pins the nearest scrollable ancestor for the duration of the collapse animation so open/close never shifts the page.

    The shared pattern: auto-close keys on the reasoning content's own completion, fires once through a latch, and user interaction wins permanently. Our trigger ("am I still the last segment") flips repeatedly and instantly during a normal turn — that's the defect, and it's the same class of stale/wrong-signal bug as the scroll flag: commit 9397c6e removed the settle-delay timer (correctly), but the replacement signal is unstable.

    Also found: the collapsed-preview pane's own auto-scroll (styled/chain-of-thought.tsx:48) force-pins scrollTop = scrollHeight on every resize regardless of the outer thread's follow state — a second, independent pin that fights a detached reader.

    3. Adjacent finding: streaming render cost (not this issue — proposing a sibling ticket)

    Perceived sluggishness has a measurable mechanism:

    • Every streamed chunk replaces the whole messages array through a plain signal (@tanstack/ai-solid use-chat: setMessages(newMessages)), then coalesceTurns and groupSegments rebuild every turn/segment array from scratch (grouping.ts:20,36) — fresh wrapper objects for turns that didn't change, which defeats the <Index> reference-equality memoization in thread.tsx:71,127 and message.tsx:65. The MutationObserver/ResizeObserver pair then walks the entire mounted transcript per mutation.
    • References bound both the blast radius and the commit rate: assistant-ui scopes each message part to its own derived store so a token only notifies that part's subtree, and buffers text commits through a rAF animator (useSmooth); Streamdown (AI Elements/CopilotKit) memoizes markdown per block so only the trailing block re-parses; CopilotKit additionally virtualizes the message list with @tanstack/react-virtual.
    • Solid gives us cheaper equivalents than React memo games: keyed incremental grouping (rebuild only the streaming turn, keep settled turns referentially stable) is the first-order fix; commit batching second; virtualization likely unnecessary at our transcript sizes.

    Plan

    1. This issue: chased() (and any other decision point in thread-follow-machine that consults state.atBottom against a fresh measurement it already holds) recomputes via isAtBottomNow. Browser test per acceptance criteria: parked viewport, content growth after the hold window, screenshot assertion. Off main, independent of the tool-cards stack.
    2. Sibling ticket (proposed): reasoning/chain-of-thought open-close contract — auto-close keyed on the segment's own completion with a one-shot latch, sticky user override kept, no hold re-arming from programmatic open changes, and the preview pane's inner pin gated on the outer follow state.
    3. Sibling ticket (proposed): streaming render cost — incremental turn/segment grouping with stable references for settled turns, then commit batching if still needed.
    4. Backlog: scroll hardening from §1 (shrink re-lock, wheel/selection/pointerdown escape).

    Fixing (1) alone removes the yank; (2) removes the visible flapping that makes the transcript feel buggy; (3) addresses raw sluggishness.

  3. omridevk commented on Aug 11, 2026

    @omridevk
    ContributorAuthor

    Status: fix implemented on fix/397-transcript-repin (worktree branch, PR to follow after the series)

    Commit 093af74: chased() now receives a freshly-derived wasAtBottom instead of reading state.atBottom.

    Implementation note — the literal "recompute isAtBottomNow(at)" turned out wrong: a resize measurement mixes the NEW scrollHeight with the OLD scrollTop, so after genuine growth-while-pinned the pure-now check always reads "not at bottom" and would kill the follow feature. The landed shape computes freshness as live scrollTop against the PRIOR dimensions (state.resized before this event): "had the user actually left the old bottom before this growth". Growth-while-pinned still chases; a reader mid-scroll no longer gets yanked. All 30 existing machine tests pass unchanged; the regression test for the stale-flag race plus the screenshot-asserted browser test from the acceptance criteria land in the series-end test pass.

    New finding under RCA (reported live): near-bottom yank while a tool runs

    With the above fix live, parking NEAR (not at) the bottom while a tool executes still snaps the viewport to the bottom. scrollToBottomOnRunStart is ruled out — no consumer enables it. Prime suspect: capture-preview churn (element-preview.tsx frames transition loading → ready/failed; the failed state collapses the frame) shrinks content so the reader lands within the at-bottom threshold of the new bottom → the #432 shrink re-lock flags them "following" → the next growth legitimately chases. If confirmed, the shrink re-lock needs a "was already pinned before the shrink" guard. RCA method: Playwright against the dev host with scrollTo/scrollTop-setter stack instrumentation to name the exact caller before any fix.

  4. omridevk commented on Aug 11, 2026

    @omridevk
    ContributorAuthor

    RCA result: the near-bottom yank — confirmed mechanism, with instrumented evidence

    Playwright drove the real widget (real Claude harness, real tool turns) with every programmatic scroll entry point instrumented (scrollTo/scrollBy/scrollIntoView/scrollTop setter patched with stack capture). Two clean reproductions, parked ~40px above bottom while a reasoning turn streamed.

    No JS scroll write fires at the jump instant — the ring buffer is empty both times. The mechanism:

    1. The chain-of-thought/reasoning collapsible auto-closes (its content region hits height 0 — captured in a DOM snapshot at the clamp instant) and the transcript scrollHeight shrinks by more than the reader's distance from the bottom (87px shrink at 40px headroom: scrollTop 655→608, scrollHeight 1025→938; second repro 62px at 40px: 683→660, 1053→991).
    2. The browser natively clamps scrollTop to the new max — pure reflow side effect, invisible to scroll-write instrumentation.
    3. The shrink re-lock branch (onResized: contentShrank && isAtBottomNow(at) → relockedToBottom) reads the clamped position as proof of "at bottom" and silently flips the user's detached state to following.
    4. The next content growth chases to the bottom — legitimately, per the re-armed state.

    Ruled out with direct exercise: run-start/thread-switch effects, tool-card auto-open, scrollIntoView from focus — the detached guard blocked all of them across many runs.

    Consequences:

    • The guilty decision is trusting a post-shrink position measurement without knowing whether the user was detached before the shrink. (Upstream use-stick-to-bottom has the same re-lock-on-shrink shape; the difference is philosophical — after a native clamp your old position no longer exists — but the felt bug is real.)
    • The felt yank is the clamp itself, and no scroll machinery can prevent it once the DOM shrinks past the reader's headroom. The zero-movement auto-close therefore requires deferring the collapse while the viewport is not at bottom — close only when the reader returns to the bottom or was pinned all along. Planned as a follow-up on createAutoCollapse after the scroll-owner replacement lands.

    Repro scripts + raw logs preserved in the session scratchpad (repro2.mjs, run11.log, run15.log).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ready-for-agent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions