Skip to content

refactor(ui): give the transcript scroller a single position authority #4099

Closed

Description

@Astro-Han

Problem

Three mechanisms own the scroll position of the same element (chatLayout.scrollContainerRef):

  1. Astryx ChatLayout's built-in useChatStreamScroll.
  2. useChatScroll -> createArrivalBottomPin, which exists only to override (1). Its own doc comment states why: Astryx positions the first fill of a scroller instantly and springs every later growth, and that one-shot is spent on whichever session was open at boot, so every later switch is "later growth".
  3. useTurnVirtualizer, which observes every turn with a ResizeObserver, captures and restores its own scroll anchor, and bumps geometryRevision.

Five call sites write scrollTop: chat-scroll-anchor.ts:75, arrival-bottom-pin.ts:120, use-chat-scroll.ts:74, use-chat-scroll.ts:115, plus the scrollIntoView at use-turn-virtualizer.ts:195.

Why this is hard to change today

A session switch starts all three. The pin sets scrollTop = scrollHeight; the virtualizer restores an anchor; use-chat-scroll gates turnWindow='ready' behind document.fonts.ready, then up to 50 x 100 ms of polling for .maka-markdown-pending, then a double requestAnimationFrame.

Timing is what keeps the three from colliding, so each new arrival condition tends to add another gate rather than remove one. That is the maintenance cost this issue is about.

Measurements, and what they do not yet show

On a dev build, five consecutive session switches produced 9 long tasks (67, 51, 78, 65, 65, 109, 102, 51, 129 ms), 717 ms total, and a CLS of 0.55.

These numbers were observed on the same path but are not yet attributed. Three authorities fighting over one scroller is a plausible source of layout shift, but no discriminating measurement has been run, so this issue does not claim them as the cause. Root-causing that jank is separate work; this issue stands on the duplicated authority alone.

Decision needed

Who owns transcript scroll position.

  • Astryx owns it - delete arrival-bottom-pin.ts (237 lines) and the positioning half of use-chat-scroll. Cost: ChatLayout must reset its first-fill one-shot per conversationKey, which needs either an upstream change or a remount by key; otherwise switches animate instead of arriving.
  • Maka owns it - disable Astryx's path explicitly and merge useChatScroll with useTurnVirtualizer. The virtualizer already holds the full geometry, so bottom-pinning becomes a window state rather than a separate mechanism.
  • Status quo - keep three authorities separated by timing.

No current architecture document assigns this ownership.

Non-goals

No visual or copy change. Prompt-anchor-rail navigation and earlier-history loading keep their current behavior.

Activity

  1. Astro-Han commented on Aug 28, 2026

    @Astro-Han
    ContributorAuthor

    Root cause found, and it narrows this issue

    Follow-up measurement on the transcript scroller. All numbers are within-instance A/B (alternating configs in one running app, 3 repetitions each). Cross-instance comparison turned out to be unusable: the same build measures CLS 0.000 and 0.511 for the same session across restarts, while within one instance σ ≈ 0.02.

    What causes the shift

    A single requestIdleCallback(prefetch, { timeout: 250 }) at use-chat-scroll.ts:157. It is the only idle callback registered during a session switch. It fires ~150 ms after the switch and calls requestEarlier(), which loads earlier history and inserts turns above the current scroll position.

    #0 #2 #8 #12 mean
    idle normal 0.854 0.499 0.560 0.238 0.538
    idle blocked 0.090 0.033 0.046 0.200 0.092

    83% of measured CLS. Dose-response holds: session #0's prefetch pulls in a turn carrying 51 tool-activity blocks (CLS 0.854); session #12's pulls in one carrying a single block (CLS 0.238, and blocking barely moves it).

    What was ruled out, each by controlled test

    Hypothesis Verdict
    Astryx scroll spring forcing reflow prefers-reduced-motion: reduce removed 89% of its layout reads; CLS unchanged
    DEFAULT_TURN_ESTIMATED_HEIGHT = 280 being wrong switched to 2000 at runtime: byte-identical CLS
    INITIAL_TURN_WINDOW_SIZE = 2 switched to 30: near-identical
    Virtualization itself fully disabled: CLS same or slightly worse; #8 and #12 byte-identical
    Height-index cache cold vs warm identical
    Eager tooltip popovers forcing style recalc real (~93 ms CPU per switch) but produces no layout shift
    Transcript arriving over IPC zero window.maka.* calls during a switch

    Why this narrows rather than widens the issue

    The browser already does the job the hand-rolled anchor does. Measured on the live scroller:

    overflow-anchor: auto        (scroller and message list; set to none nowhere in Maka or Astryx)
    
    insert 1500px above viewport, scrolled to middle
      -> browser compensates exactly 1500px, visual shift 0px
    insert 1500px above viewport at scrollTop === 0
      -> no compensation, content jumps 1500px   (known Chromium limitation)
    

    Native scroll anchoring is not merely available — it is active and working on this element. chat-scroll-anchor.ts (129 lines) reimplements it, and use-chat-scroll.ts:74 adds a fallback that applies the full height delta on top of the browser's already-applied compensation whenever restoreChatScrollAnchor fails to relocate its article:

    const scrollHeight = root.scrollHeight;          // before load
    ...
    window.requestAnimationFrame(() => {             // one frame later; the browser has already anchored
      if (... && !restoreChatScrollAnchor(root, anchor)) {
        root.scrollTop += root.scrollHeight - scrollHeight;   // full delta again
      }
    });

    Observed consistent with double compensation: scrollHeight 1491 → 5349 (+3858) in the same frame as scrollTop 582 → 4440 (+3858).

    The ownership question this issue opened is already answered in-tree

    chat-surface-layout.tsx states it:

    Astryx owns scrolling, new-message following, the bottom dock, and the scroll-to-bottom affordance. Maka supplies only transcript and composer content through the published ChatLayout slots.

    Against that, the current code holds a second implementation. Maka never calls useChatStreamScroll; it takes only scrollContainerRef off useChatLayoutContext() while Astryx's own controller runs on that same element. Astryx already provides what the parallel implementation hand-rolls:

    Maka today Astryx equivalent
    arrival-bottom-pin pinned/released + data-arrival-pin isLocked / lock() / unlock()
    pin() on content resize scrollIfLocked()
    use-chat-scroll.ts:115 scrollTop = scrollHeight scrollToBottom({ behavior: 'instant' }) — documented for "opening a conversation, restoring a session"
    target-turn scrollIntoView effect scrollToMessage(el)
    chat-scroll-anchor.ts the browser's overflow-anchor

    The seam for reaching them already exists and is already used: patches/@astryxdesign+core+0.5.0.patch widens ChatLayoutContextValue with unlockAutoFollow: scroll.unlock, consumed at chat-view.tsx:675. Exposing the rest of UseChatStreamScrollReturn through that same context is the established path, and is upstreamable.

    So the transcript carries exactly two scroll facts: "am I following the bottom" (Astryx owns it, and is already running) and "content was inserted above me, don't move" (the browser owns it, verified). Everything else in this area is a third implementation of the first or a redundant copy of the second.

    Disappearance surface

    • chat-scroll-anchor.ts (129 lines) + chat-scroll-anchor.test.ts; call sites at use-chat-scroll.ts:60,72 and use-turn-virtualizer.ts:153,187,239 including the pendingAnchor ref
    • the root.scrollTop += root.scrollHeight - scrollHeight fallback — actively harmful, not merely redundant
    • arrival-bottom-pin.ts (200 lines) once bottom-lock is read from Astryx
    • data-arrival-pin — written at use-chat-scroll.ts:121, read nowhere in the repository

    Capability given up: the scrollTop === 0 case, where native anchoring does not engage. That is one known constant, not a mechanism to maintain.

    Still open

    • Whether the arrival prefetch should exist at all. Under the ownership above it stops causing shift, so this becomes a product question about warm history rather than a correctness one. Deleting it also deletes requestEarlierRef, an effect exporting a mutable callback so a different effect can invoke it.
    • data-turn-window="ready" is produced by a fonts.ready → up to 50 × 100 ms .maka-markdown-pending poll → double-rAF chain whose only consumer is apps/desktop/e2e/prompt-rail.spec.ts. That chain is also where the prefetch is scheduled.

    Measurements were taken with temporary runtime switches on a local build; the working tree is unmodified.

  2. Astro-Han commented on Aug 28, 2026

    @Astro-Han
    ContributorAuthor

    Provenance: the parallel implementation was never a counter-decision

    Correcting something in my previous comment. I leaned on the ownership statement in chat-surface-layout.tsx as authority. A file comment is not authority on its own, so I traced why the parallel implementation exists.

    arrival-bottom-pin.ts comes from #2239 ("land a switched-to session at its latest turn instead of flying there"). Its reasoning is explicit and was correct at the time:

    Astryx's useChatStreamScroll positions the FIRST fill of its scroller instantly and springs every later growth. That one-shot lives on the hook instance, and ChatSurfaceLayout mounts once for the whole app shell, so it is spent on whichever session was open at boot.

    I assumed the capability to fix that arrived in a later Astryx release. It did not. Unpacking @astryxdesign/[email protected], the version in the tree at #2239, the controller surface is identical to today's 0.5.0:

    UseChatStreamScrollReturn (0.2.0)
      isScrolledUp, isLocked
      scrollToBottom(options?: ChatScrollToBottomOptions)   // behavior: 'instant' | 'spring'
      scrollToMessage(el), lock(), unlock(), scrollIfLocked(), scrollToLastMessage()
    

    What was missing was reachability, not capability. ChatLayoutContextValue in 0.2.0 exposed exactly two members:

    scrollContainerRef
    contentRef
    

    useChatStreamScroll runs inside ChatLayout; Maka's transcript code lives in ChatView, a descendant. The controller was not reachable from where the fix had to go, so the only available lever was scrollTop on scrollContainerRef — which is what the pin writes, from a ResizeObserver. The pin is a hand-rolled lock() + scrollIfLocked() + unlock().

    That constraint was removed later, by Maka, for a different feature. #2923 patched ChatLayoutContextValue to add unlockAutoFollow: scroll.unlock, consumed today at chat-view.tsx:675. Piping one controller method through the context is established and in production; the pin was never revisited against it.

    conversationKey has the same shape — absent from 0.2.0, added by Maka's patch, still carried in patches/@astryxdesign+core+0.5.0.patch rather than upstream.

    #2239's supports today

    Support in #2239 State
    Astryx controller unreachable from ChatView Removed by #2923's context seam
    The content-visibility warm-up inflates every placeholder Gone; the only content-visibility left is unrelated code-block styling
    Frame-sampling E2E: fails on parent at maxDistance=11267, passes at 0 Not in the repository; no e2e references arrival
    data-arrival-pin published "so a test can wait on the real boundary" Zero readers repository-wide
    Transcript arrives in pieces (progressive mount, idle chunks filling the prefix) Still true — and those idle chunks are the requestIdleCallback prefetch measured above

    The last row closes a loop worth naming: the pin exists to absorb growth the prefetch produces, and that growth is the measured source of 83% of the layout shift. Each mechanism is part of the other's justification.

    So the ownership statement is not stale and the parallel implementation is not a rejection of it. The workaround outlived its constraint by one PR.

    The real cost of converging

    Not "can Astryx do this" — it could in 0.2.0. It is whether Astryx's unlock heuristics are equivalent. #2239 spent six review rounds on exactly that: gestures must originate inside the transcript element, a horizontal wheel reports deltaY === 0 and is not the reader leaving, and the synthetic scroll Chromium fires for a resize must not be read as reader intent. Those semantics are currently held by arrival-bottom-pin.test.ts.

    Those cases should be retargeted at the Astryx-backed behavior rather than deleted with the pin. That is the one place where converging costs real work.

  3. Astro-Han commented on Aug 28, 2026

    @Astro-Han
    ContributorAuthor

    One more independent signal that the transcript scroll boundary remains timing-sensitive:

    PR #4090 failed on exact head 89f8a9d89e839afb51c8710e54e03486e7efca45 in the prompt-rail eviction journey:

    https://github.com/apache/maka/actions/runs/33195433169/job/98931236633

    After the test set the transcript to the bottom, explicitly dispatched a scroll event, and waited two painted frames, turn-prompt-rail-120 was still absent for the full 10-second assertion timeout. This is the same failure previously tracked in #3862, despite its synchronization fix having merged in #3863.

    The fixture is 120 plain completed turns and does not exercise #4090's aborted-turn path. This run therefore does not establish that #4090 caused the failure. It also does not identify which scroll owner won the race. What it does establish is that the existing event-plus-two-frames test barrier does not make the virtualizer's tail window deterministic while the current ownership model remains in place.

    #4105 already removes the competing ownership paths and retargets the prompt-rail readiness checks. Its hosted prompt-rail result should also be treated as regression evidence for this exact recurrence, not only for the session-switch CLS symptom.

    Posted with Codex assistance; @Astro-Han verified the linked run and diagnosis.

  4. added
    help wanted
    on Aug 29, 2026
  5. added theissue type on Aug 29, 2026
  6. Phoenix500526 commented on Aug 29, 2026

    @Phoenix500526
    Contributor

    take

  7. Astro-Han commented on Aug 29, 2026

    @Astro-Han
    ContributorAuthor

    Closed by #4105 (afc1a750b).

    Decision: Maka owns it. Worth recording that "Astryx owns it" was the branch's first answer, not a rejected option — d061bdba3 handed following the tail back and deleted arrival-bottom-pin.ts outright. Reading Astryx's controller, it already covered what six review rounds had put into that pin: resize-synthetic scroll events excluded by comparing scrollHeight and offsetHeight, horizontal wheels excluded by requiring deltaY < 0, gestures scoped by binding to the scroller rather than by testing pointer position.

    Three fixes later it was clear the ownership could not sit there, and the deciding one is not an Astryx defect. Astryx decides "the reader left the tail" from a gesture, and gestures bubble. The transcript is self-scrolling, so its scroller is the whole ChatLayout root — with a tool output body, a pty terminal, the composer and the graph panel inside it, each scrolling on its own. A wheel one of those consumes never moves the outer scroller, so no scroll and no scrollend follow and the re-lock can never run: following is off, distance to the bottom is still zero so the affordance stays hidden, and the reader has no way back. That is a modelling assumption (no self-scrolling descendants) that this DOM does not satisfy, not a bug upstream.

    So the predicate changed from gesture to position. scroll does not bubble, which is what makes a gesture a nested scroller consumed physically unable to reach the authority. One genuine upstream defect did surface on the way — under prefers-reduced-motion the spring never runs, so both of Astryx's gesture releases are dead code — and it was reported rather than worked around.

    Taken slightly differently from the option as worded here: rather than merging useChatScroll into useTurnVirtualizer, the authority is its own module and the virtualizer keeps only its height index. Same ownership answer; the virtualizer's geometry turned out to be the wrong home, because the transcript renders content outside the turn wrappers it observes.

    All five scrollTop writers named above are gone or subordinate: chat-scroll-anchor.ts and arrival-bottom-pin.ts deleted outright, the two in use-chat-scroll now one-shot commands that release the pin first, the virtualizer's scrollIntoView likewise. The document.fonts.ready gate, the 50×100 ms markdown polling and the double requestAnimationFrame are all removed. Non-goals held: rail navigation and earlier-history loading behave as before.

    Not done here, deliberately: the long tasks and CLS 0.55 in the Measurements section stay unattributed, as this issue said they would. CLS did fall from 0.481–0.521 to 0.089, but that came from removing the speculative prefetch, not from the ownership change — a post-merge A/B against the merge-base showed the streaming and scrolled-up cases identical on both sides. Root-causing the jank remains separate work.

    🤖 Posted by Claude Code

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

Metadata

Metadata

Assignees

Labels

good first issuehelp wanted

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions