# Chat transcript follow

One React-owned policy for the App and browser: opening a conversation and sending both land on the latest; model output only keeps a reader who is already there.

## What latest means

1. **Last content** User bubble, pending indicator, streaming assistant, queued rows
2. **Gap** `24px`: the same in every window and composer height
3. **Overlay** Floats over the pad
4. **Padding edge** `latestScrollTop` lands here

|  | Main | Peer |
| --- | --- | --- |
| Pad | `--main-composer-height` + 24 | `--peer-composer-h` = overlay + 24 |
| Overlay | `--main-composer-height`, the measured composer | Composer root, measured |

`latestScrollTop = max(0, scrollHeight - clientHeight)`. The pad follows the composer as it grows or shrinks, so the room under the last row is one size on every visit.

### Three distances

| Distance from the latest | Meaning |
| --- | --- |
| ≤ 2 px (`AT_LATEST_PX`) | The bottom itself: the view follows from here and nowhere else |
| ≤ 70 px (`JUMP_HIDE_DISTANCE_PX`) | Jump is hidden. The view is not moved |
| 70 to 240 px | Jump keeps what it had: a small move up shows nothing, and it does not blink at one edge |
| > 240 px (`JUMP_SHOW_DISTANCE_PX`) | Jump shows, unless the view is following |

All are fixed pixels; a distance derived from the pad moved with the window and the composer (32 to about 190 px).

70 and 240 decide the button only. Following starts at the bottom itself, so a reader who stops a little short of it is not pulled the rest of the way; `use-stick-to-bottom` reattaches within 70 px, which reads as the view snapping.

## Who writes the scroll position

| Owner | Job |
| --- | --- |
| `useChatAreaStick` | The only follow writer: main and peer placement, send, Jump, attached state, per-viewport pending latest load |
| `chat-scroll.ts` | Geometry, the follow and Jump decisions (`followAfterScroll`, `followAfterGrowth`, `jumpVisible`), take-latest notes, Jump animation |
| `history-viewport.ts` | Anchor restoration when a history window is replaced; the one other scroll writer, not a follow policy |
| `useHistoryWindow`, `history-autoload.ts` | Bounded pagination and prefetch. Its one scroll write puts a reader in history back on their row after a fresh read of the conversation in view |
| `loadSessionHistoryWindow` | Publishes rows and window metadata; never places latest |
| WebSocket handlers | Never scroll and never write a note |

## What moves the viewport

| Entry | Attached | Motion |
| --- | --- | --- |
| Send: composer submit, first welcome send, queue drain that calls `sendChatMessage`, accepted queue or steer, slash or builtin submit | True at once on the latest window. On an older window: stays false, Jump stays, true after latest loads | Instant snap, [latched](#send-latch). Jump hides at the snap, not while waiting |
| Jump to latest (main: portal on `#chatView`; peer: header button, no portal or live bars) | True once latest is verified on screen | Awaits latest, then a 480 ms eased ride driven frame by frame, starting at most 1.5 screens above the latest; instant with reduced motion. [Completion](#jump-completion) |
| Wheel, pointer, scroll keys, a seek to a message | The top moving up detaches. Reaching the bottom reattaches; stopping short of it leaves the view where it is. A wheel event with no vertical movement is ignored | None. Cancels [pending work](#lifecycle) |
| Growth: stream, tool, KaTeX, row measuring and recycling, a page of older rows above, pad or composer resize, a window made shorter | Never detaches. The one exception is growth the reader caused: with the pointer held, or within 600 ms of a click, an upward wheel or an up key, growth that leaves the latest more than 240 px below detaches (a block opened by hand) | Pin to latest while attached, on the latest window and outside a Jump; not during that reader input |
| Opening a conversation (`chatKey` change, or shown again) | True: see [opening](#bottom-restoration) | Instant snap to the latest, latched like a send. A pending note moves only to this draft's adopted session |
| History window load, not from send or Jump | False while `after` is set. A page in flight changes nothing: older rows arriving above a reader at the latest are growth | Attached: pinned to the latest. Detached: [per-area anchor restoration](#history-ownership) |
| Remote `local_command`, compaction, status, follow-up, `chat_response` | Unchanged | Only via growth while attached |

Parking a queued row is not a send. Loading or failed attachments are rejected before queue creation, draft clearing and note publication; the existing note and its generation stay.

## Send latch

| Moment | What happens |
| --- | --- |
| Submit | The submit path appends the local turn, then calls `noteTakeLatest({sessionId, scrollerKey, turnSeed})`. The key comes from the captured session and `background`, never from live `activeChatKey`; `send-queue.ts` is unaware of it |
| Hook notified | The hook whose `chatKey` equals `scrollerKey` sees a generation newer than its last applied one. Publishing notifies it even if no row changed |
| `after` or `loading` set | Stay detached, keep Jump, leave the stale page alone, await a verified latest window outside the layout effect |
| On latest | Attach regardless of recent reader input or current geometry, then `snapToLatest` |
| Next column resize of this operation | Snaps once more for late row height, unless the view moved up in between (a seek to a message). After that, ordinary growth rules apply |
| Welcome overflow lock lifts (main only) | One retry |
| Ack appends the assistant placeholder | Does not detach |

## Follow operation lifetime

A note identifies a send; it is not permission to scroll forever. Every async completion, resize snap, welcome retry and animation callback first checks session, scroller key, generation and interaction epoch.

| Event | Result |
| --- | --- |
| Newer send | Replaces the older operation for that scroller |
| Jump during a pending send | Replaces it |
| Send during Jump | Stops the ride, then instant placement |
| Wheel, touch or pointer scroll, scroll key | Invalidates pending work and retries; the [distances](#distances) decide attached. Programmatic scroll events do not cancel |
| Key change or real unmount | Invalidates the outgoing operation; no completed or cancelled note is replayed |
| Strict Mode cleanup | Cancels that effect's resources; setup resumes a still-valid operation with no second send, lost retry or orphaned request |
| Request in flight, `after` not set yet | `after \|\| loading` enters the wait. A cancelled or failed request leaves no retry and cannot hide Jump; an older completion cannot clear a newer gesture |
| First welcome send before the transcript shows | The pending handoff survives to its view, retries once, and keeps its identity through provisional-to-real binding: only this draft's adopted session, not any `local_*` key |
| Session delete, draft drop | Forgets that session's notes |

**Note storage**

- Stored per `(sessionId, scrollerKey)`, so main and peer in one session stay independent.
- Never deleted on read. Completion and cancellation are recorded separately, with per-view applied generations; starting a latest request does not complete one.
- Idle completed notes with no viewport are capped at 32; waiting notes are kept. Releasing a viewport prunes after the current turn, so a same-tick remount retains it.
- `turnSeed` is the accepted optimistic turn, not the last row after ack.
- A newest page nobody asked for (renewal, retry) becomes a note for each viewport with no follow lock.

## Jump completion

- The ride lasts 480 ms whatever the distance (sine ease-in-out). Chromium's own smooth scroll grows with distance, up to about 1.5 s, and cannot be timed: a timeout cut it short and covered the rest in one frame.
- A longer distance first moves to 1.5 screens above the latest, so each frame moves a readable amount (at most about 80 px on an 800 px view).
- Every frame reads the target again, so a streaming reply or a page that arrives during the ride is absorbed and the ride ends on the current latest with no correction; resize does not pin meanwhile.
- Jump hides only after that, if the operation is still current. Reduced motion uses the same check.
- Cancel (pointer, wheel, scroll key, send) stops the ride at the current frame, and no cancelled operation corrects.

## Opening a conversation

| Situation | Opens at |
| --- | --- |
| First opening, switching to it, a reload, a tab or pane shown again | The latest, followed through delayed layout and file-card growth. No reading position is kept from one opening to the next |
| The cached window is an older one (`after` set) | The newest page is requested; the view attaches and snaps when it is published. Jump stays hidden while it loads and shows only if the load fails |
| A fresh read of the conversation in view (reconnect, renewed snapshot) | A reader in history stays on the row they were on, remembered in memory by that view only; a reader at the latest stays at the latest |
| Arriving at one message: a message link, a search hit, the navigation rail, a parent return, a branch checkout | That message. The view lands on the latest first and is then taken up to the message, which detaches it like any move up |

A tab that was only hidden is an opening like the others: hiding unmounts its rows, and a remembered pixel offset no longer matches them once they are measured again. Restoring it would put a returning reader at a different height on each visit.

**Details**

- A reader's own gesture cancels pending following.
- An empty transcript keeps latest intent: rows that commit before ResizeObserver delivery keep the follow state. Height growth is not a reading gesture.
- The ResizeObserver watches the scroll area as well as the column: a window made only shorter changes neither the column's box nor `scrollTop`, and the latest would slide under the composer with nothing to pin it or show Jump.
- The first render of a conversation mounts its last screen of rows, not the rows at the scroll offset the previous conversation left.
- Rows keep their height after layout: a task block or step that mounts open is drawn open, with the opening transition kept for a change made after mount, and the file-summary probe of a reply takes no room.
- A pending welcome send survives activation until its view is ready.

**Legacy file-change summaries**

- Loaded only near the viewport, then kept in the session message store. A remounted card renders the result at once, including a confirmed empty one.
- Errors stay retryable. Aborted or stale responses never update another session.
- History preflight stays fresh and undo authorization stays server-side; a summary is a description, not permission to undo.

## History windows

- Older, newer and around replacement: each registered area captures its own anchor, top and height before the update, and restores after `flushSync` only if still registered for the same session and `chatKey`. Height caches use that area's key.
- A registered area that lost registration is not restored. The unregistered `#chatArea` fallback applies only when nothing was registered at capture and the node is still the live main scroller; being connected is not enough.
- Restoration skips a viewport holding a follow lock.
- Rows shared by main and peer: each non-requesting pane keeps its anchor. If eviction removed it, the reader keeps the distance from the surviving end. A negative result (an expired snapshot renewed to the newest page) shows the end of the new window, not the top.

### Prefetch

| Rule | Value |
| --- | --- |
| Minimum distance | `max(1600px, 2 × viewport height)`, per edge |
| Cap | `12000px` |
| Velocity | Only motion toward an edge extends it, with the latency estimate × 1.5. Zero velocity keeps the minimum, so short content still fills |
| `scrollHeight` changed | Velocity resets to zero: layout shifts, including virtualized shrink at latest, are not reader motion |
| Both edges qualify | Existing direction selection |

Selects when to request; never writes `scrollTop`. Serialization, cursor and generation validation, retry backoff, snapshot renewal, hidden-view suppression, recovery and disposal are separate.

## Failure and limits

| Case | Behaviour |
| --- | --- |
| Latest load fails or goes stale | Detached, Jump visible, stale page untouched; a failure settles the note |
| Storage write fails | Swallowed |
| Virtualization | Recycling keeps measured placeholders so `scrollHeight` stays honest; pin after recycling. No virtual-list library |
| Width change | Measured heights stay as estimates, so the list is not re-rendered. While changing, the area has `data-width-settling` and off-screen rows use `content-visibility: auto`. After 120 ms still, the first visible row keeps its place unless the view is pinned at the bottom |
| KaTeX | `typesetMath` on the observed column, inside the pin path; no document scan |

Not followed: DAG strip expand, compaction fold `easeScrollBy` / `pinWhile`, parent-return `scrollIntoView`, message-rail seek, task-block seek (from outside the area it announces itself with `chat-reader-seek`, handled like a wheel), branch checkout `_postCheckoutScrollTo`. The CLI `ScrollBox` is separate. No backend protocol change, and occupancy, queue admission and ack pairing are unaffected.

**Interfaces**

```
latestScrollTop(area: ScrollMetrics): number
snapToLatest(area: HTMLElement): void
animateJumpToLatest(area, onDone?, {getTarget?, reducedMotion?}): () => void
readComposerOverlay(area, composerRoot?): number

type TakeLatestNote = {
  sessionId: string
  scrollerKey: string  // background ? `peer:${sessionId}` : sessionId
  turnSeed: string
  generation: number   // monotonic
}
noteTakeLatest(note: Omit<TakeLatestNote, "generation">): TakeLatestNote
peekTakeLatest(sessionId, scrollerKey): TakeLatestNote | null
settleTakeLatest(sessionId, scrollerKey, generation): void
relocateTakeLatest(fromSession, fromKey, toSession, toKey): TakeLatestNote | null
subscribeTakeLatest(listener): () => void
```

- `useChatAreaStick` returns `{ detached, showJump, jumpToLatest }`: `detached` is the follow state, `showJump` draws the button.
- Main `chatKey` is the session id. Peer panes use `peer:`. Panes of different sessions never share a latch; peer panes of one session share `peer:${sessionId}` and may answer the same note, by design: there is no pane instance id.

**Comparison with other agents**

Product rules, not pixels. All three products treat send as an implicit jump to latest and model tokens as not one.

| Surface | Send while scrolled up | Growth | Re-attach | Session |
| --- | --- | --- | --- | --- |
| ChatGPT web | New turn in the live band | Follows at the live edge; up detaches, near edge reattaches | Down-arrow, with a live variant | Aims at latest |
| Claude.ai, Claude Code web | Turn lands in view | Follows at the live edge; manual up holds | Jump when away | Restores that conversation |
| Cursor Composer | Prompt in the composer band | Follows while pinned | Explicit jump | Per thread |
| CLI `ScrollBox` | `scrollToBottom()` sets sticky | While sticky; `scrollTo` and `scrollBy` clear it | `scrollToBottom` | TUI only |
| shadcn MessageScroller | Can anchor the turn near the top | `autoScroll` at bottom | `MessageScrollerButton` | — |
| `use-stick-to-bottom` | — | Follows until the reader scrolls up; growth never detaches | Within 70 px of the bottom | — |

Codex and Atlas have no transcript-follow material in this repository; their notes cover [queue and steer](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/turn-lifecycle/send-queue-reliability.html) only.

**Rejected**

| Option | Why not |
| --- | --- |
| Last message + 16 px as target | Measures against the visible bottom, under the overlay, and ignores the pad |
| A pad of `max(25vh, overlay + 24)` | The room under the last row becomes 25vh less the composer: 24 px in a short window, about 180 px in a tall one, and different again with each composer row |
| A reattach distance of pad − overlay + 8 | It moves with the window and the composer, and one number decides both following and the button, so a stream that outruns it shows Jump at the end |
| Geometry deciding the follow state after growth, or a page in flight counting as not latest | Streaming under a resting finger, inertia or an older page loading detaches a reader who has not moved |
| Restoring the reading position for an hour | Readers expect a conversation to open at its end; saved pixels land at a different height each time once rows are measured again |
| Consume-once boolean, or `lastRole` | Lost to Strict Mode and two hook instances; wrong after ack |
| Send as smooth animation | Send is 0 ms feedback |
| `--peer-composer-h` as overlay | It already includes the 24 px pad |
| Handlers calling a scroller, global stick flag | Frame type is not a scroll signal |
| Follow state outliving the view | Every opening starts at the latest |
| Virtual-list or message-scroller library, CLI `ScrollBox` in the web bundle | Not needed; the attached flag is the idea borrowed |
| Previous reply anchored at top as a second mode | One landing rule: the latest, 24 px above the composer |
| Follow on every DAG expand; send and ack protocol rewrite | Out of scope |

**Acceptance**

| Entry | Setup | Observed |
| --- | --- | --- |
| Composer submit | Far up on latest window | User bubble (and pending indicator) above the composer at 0 ms after append; instant; attached; Jump hides at the snap |
| Composer submit | Attached | Same; the stream stays pinned |
| Welcome first send | Overflow locked | Welcome hides at 0 ms; after unlock the first row is in the live band |
| Queue drain | Another session focused | Same as send, key from captured session; enqueue alone does not move |
| Jump | Detached on an older window | Awaits latest, smooth; visible until settled; pointer or wheel cancels |
| Scroll | Up 100 px, then 300 px | Detached at once and later deltas keep `scrollTop`; Jump appears past 240 px |
| Scroll | Back within 70 px, then to the bottom | Jump hides and the view stays put; at the bottom it reattaches and growth pins |
| Stream deltas | Attached, KaTeX or recycling | Pinned |
| Agent row, no note | Detached | `scrollTop` unchanged |
| Session switch, reload | Any earlier position | Lands on the latest with 24 px under the last row, no Jump, no later move |
| Stream, older page loading | At the latest, finger resting or inertia | Stays pinned, Jump never shows |
| Send on older window | `after` set | No snap, Jump stays, attaches after load; failure stays detached |
| Peer send | Peer Y, pane X open | Only Y moves; focused-shell flags untouched |
| Ack | Placeholder last | Stays attached |
| Scroll, send within 600 ms | Pointer on area | Still snaps and pins |

**Test matrix**

| ID | Required observation |
| --- | --- |
| F01 | Empty, short and overflow geometry; the 2, 70 and 240 px decisions; pad of composer + 24 in main and peer |
| F02 | Independent main and peer notes in one session; increasing generations; subscription fires with no row update |
| F03 | Enter and Send far up: user row above the overlay before ack; placeholder and stream keep following |
| F04 | Scroll then send inside 600 ms; delayed growth follows once. Send then scroll up: no snap back |
| F05 | Detached growth keeps top; only the bottom reattaches; growth, an older page and wheel inertia never detach or show Jump |
| F06 | `after` send: no stale write, Jump visible, success snaps; failure and cancellation stay detached |
| F07 | Send during older or around load with no `after`: settle, then fetch latest; stale responses never beat newer gestures |
| F08 | Strict Mode send and latest cleanup: no lost intent, duplicate send or stranded pending state |
| F09 | Send, detach, switch away and back: lands on the latest with no replay; switching mid-request leaves the incoming chat alone |
| F10 | Welcome send before readiness and provisional binding; one valid retry; a cancelled retry writes nothing |
| F11 | Peer Y sends, X detached: only Y moves; same-session notes independent; shared peer key affects matching peers |
| F12 | Enqueue does not move; drain uses captured session; closed socket, throw or duplicate first send writes no note |
| F13 | Slash submit follows with no new row; remote frames while detached do not |
| F14 | Older-window Jump loads then rides, no pre-snap; button stays until verified |
| F15 | Growth during Jump: the ride ends on the current latest with no final jump, then the button hides |
| F16 | Pointer, wheel or key cancels with no later correction; send during Jump wins; reduced motion is instant |
| F17 | Two areas restore their own anchors and fallback deltas; latest has no loader pin |
| F18 | No global follow listener; no stored reading position; a view taken to a message after landing is not pulled back |

- F03–F17 use real React hooks in a browser with real submit and queue entries and controlled WebSocket responses, asserting geometry, button visibility, request order and cleanup. Strict Mode runs explicitly. Isolated test state, with no real messages or model calls. These do not establish installed-App acceptance.
- Fixtures: first-activation cases supply the latest response; rejected admission compares the exact note before and after.
- Prefetch: test opposite motion, virtual shrink at latest, both thresholds, short-content fill via the real controller. Automatic history: no initial older request, scroll-triggered loading, in-flight movement kept within 3 px after prepend, recycling, no duplicates.
- Summaries and opening: remount with no second request, delayed growth to latest, return to the latest, manual cancel, older first open ignoring a stale completion.

```
node --no-warnings --experimental-strip-types --test \
  apps/web/tests/chat/messages/list/chat-scroll-follow.test.mjs \
  apps/web/tests/chat/messages/list/jump-latest.test.mjs \
  apps/web/tests/chat/messages/list/chat-activation.test.mjs \
  apps/web/tests/chat/composer/submit/send-chat-message-latency.test.mjs
node apps/web/scripts/chat/check-chat-ui.mjs
uv run --locked --extra dev --extra browser python -m pytest -q -m browser \
  tests/e2e/web/chat/test_chat_transcript_follow.py \
  tests/e2e/web/chat/test_chat_history_interactions.py \
  tests/e2e/web/chat/test_automatic_chat_history.py \
  tests/e2e/web/chat/test_scalable_chat_history.py
```

## Implementation status

Implemented on the web renderer, with no feature flag; undoing it is a code revert, not a protocol change. Open: installed-App acceptance of geometry-aware prefetch.

[Send queue reliability](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/turn-lifecycle/send-queue-reliability.html)
