From 4e4cdae7762bc28330b599a39471fc15d9da2e4c Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Tue, 24 Nov 2026 16:35:29 +1000
Subject: [PATCH 1/6] fix(app): open a shell's call from its notice when the
call is on an older page
---
packages/app/AGENTS.md | 4 +
.../e2e/regression/timeline-history.spec.ts | 58 ++++++++++
.../app/src/session/timeline/interaction.ts | 63 ++++++++++-
.../src/session/timeline/message-timeline.tsx | 4 +-
.../session/timeline/reveal-machine.test.ts | 100 ++++++++++++++++++
.../src/session/timeline/reveal-machine.ts | 94 ++++++++++++++++
.../app/src/session/timeline/virtualizer.tsx | 27 ++++-
7 files changed, 339 insertions(+), 11 deletions(-)
create mode 100644 packages/app/src/session/timeline/reveal-machine.test.ts
create mode 100644 packages/app/src/session/timeline/reveal-machine.ts
diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md
index 4114409153796..0290c696c4f7f 100644
--- a/packages/app/AGENTS.md
+++ b/packages/app/AGENTS.md
@@ -128,6 +128,10 @@ This section is the single source for what may move or restyle the session timel
- A virtualized list therefore gives focus to its own viewport, without scrolling, before a row that holds focus unmounts. `VirtualRow`'s `onCleanup` in `src/session/timeline/virtualizer.tsx` does this. Keep it when you change how rows mount, and do the same in a new virtualized list.
- Keeper: "a focused control that scrolls out of the mounted rows leaves the timeline where it was scrolled" in `e2e/regression/session-timeline-accessibility.spec.ts`.
- To check by hand: click a tool header, a link and a notice in the timeline, then scroll up and down with the wheel. The timeline must follow the wheel.
+- A link can name content that is older than the loaded messages, such as the call of a shell whose notice the reader clicks. The timeline pages history toward it and moves once, when it loads (`src/session/timeline/reveal-machine.ts`).
+ - Page toward a target only while something says where it can be. A shell's call is older than the shell, and IDs ascend with creation, so the search ends once an assistant message older than the shell is loaded. Without that bound a target that does not exist loads the whole session: a shell that a Code Mode script started has no call, which was the case for 40 of 265 shell notices in four real sessions.
+ - The reader's scroll or press in the timeline ends the search. A move that lands after the reader has gone elsewhere is one they did not ask for.
+ - Keeper: "a shell notice opens its call from an older page, paging back only as far as the call" in `e2e/regression/timeline-history.spec.ts`.
### Scroll writes
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index b572e2bfa2df5..be892cd80dadb 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -14,6 +14,7 @@ import {
setupTimeline,
status,
textPart,
+ toolPart,
userID,
userMessage,
validateTimelineMessages,
@@ -126,6 +127,63 @@ test.describe("timeline history", () => {
expect(oldest).toBeGreaterThan(0)
})
+ test("a shell notice opens its call from an older page, paging back only as far as the call", async ({ page }) => {
+ const history = historyMessages(120)
+
+ // IDs ascend with creation, as the server makes them: the call's message, the shell it starts, then later turns.
+ const call = assistantMessage(
+ [
+ toolPart(
+ "prt_older_call",
+ "shell",
+ "completed",
+ { command: "bun serve.ts", background: true },
+ { output: "listening", metadata: { shellID: "sh_00079_history_d_shell", status: "running" } },
+ ),
+ ],
+ { id: "msg_00079_history_c_call", parentID: "msg_00079_history_a_user", created: 1690000792000 },
+ )
+
+ const messages: SessionMessageInfo[] = [
+ ...history.slice(0, 160),
+ call,
+ ...history.slice(160),
+ {
+ id: "msg_00120_shell_finished",
+ type: "synthetic",
+ text: '\nlistening\n',
+ description: "bun serve.ts",
+ metadata: { source: "shell", shellID: "sh_00079_history_d_shell", state: "completed" },
+ time: { created: 1690001200000 },
+ },
+ ]
+
+ let oldest = messages.length
+
+ await setupTimeline(page, {
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+ oldest = Math.min(oldest, start)
+
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ })
+
+ const scroller = timelineScroller(page)
+ const notice = scroller.getByRole("button", { name: /^Shell finished/ })
+ const trigger = scroller.locator('[data-timeline-part-id="prt_older_call"] [data-slot="collapsible-trigger"]')
+
+ await expect(notice).toBeInViewport()
+ await expect(trigger).toHaveCount(0)
+ await notice.click()
+
+ await expect(trigger).toHaveAttribute("aria-expanded", "true")
+ await expect(trigger).toBeInViewport()
+ expect(oldest).toBeGreaterThan(0)
+ })
+
test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => {
const id = "ses_history_restore"
const other = "ses_history_other"
diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts
index 3b7205a2dfb35..67fb52055f849 100644
--- a/packages/app/src/session/timeline/interaction.ts
+++ b/packages/app/src/session/timeline/interaction.ts
@@ -25,6 +25,13 @@ import {
} from "./history-machine"
import { createRouteRevealState, routeRevealTarget, transitionRouteReveal } from "./machine"
import { createTimelineModel } from "./model"
+import {
+ createRevealSeekState,
+ revealSeekTarget,
+ SEEK_CANCELLED_EVENT,
+ transitionRevealSeek,
+ type RevealSeekEvent,
+} from "./reveal-machine"
/** `visible`: the conversation is on screen, not behind another narrow-screen view. */
export function createSessionTimelineInteraction(session: SessionModel, visible: Accessor) {
@@ -65,9 +72,19 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
setRevealState((current) => transitionRouteReveal(current, event))
})
+ // Each session gets a fresh seek, as it gets a fresh follow state, so one never carries on in the session opened
+ // next.
+ const revealSeek = createMemo(() => {
+ session.identity.sessionKey()
+
+ return createSignal(createRevealSeekState())
+ })
+
// The active timeline's navigation, registered by its virtualizer.
let revealMessage = (_id: string, _partID?: string) => {}
+ let revealPart = (_target: string) => false
+
let scrollToEnd = (_behavior?: ScrollBehavior) => {}
let page = (_direction: 1 | -1) => {}
@@ -154,15 +171,21 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
)
}
+ const viewReady = createMemo(
+ () => !!session.identity.params.id && timeline.ready() && !!state.refs.scroller && visible(),
+ )
+
+ const historyStatus = createMemo(() => historySeekStatus(historyState()))
+
const cursor = createTimelineCursor({
sessionKey: session.identity.sessionKey,
- viewReady: createMemo(() => !!session.identity.params.id && timeline.ready() && !!state.refs.scroller && visible()),
+ viewReady,
following: follow.following,
visibleUserMessages,
syncing: () => timeline.resource.loading,
revertMessageID: session.data.revertMessageID,
oldestMessageID: oldestMessage,
- historyStatus: createMemo(() => historySeekStatus(historyState())),
+ historyStatus,
scroller: () => scroller,
anchor,
revealMessage: (id) => revealMessage(id),
@@ -221,14 +244,28 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
// A gesture inside a nested scrollable region scrolls that region, not the timeline.
const markUserScroll = (target?: EventTarget | null) => {
- if (!scroller || !hasFreshCursorOrSeek(untrack(cursor.state))) return
+ const seeking = revealSeekTarget(untrack(() => revealSeek()[0]())) !== undefined
+
+ if (!scroller || (!seeking && !hasFreshCursorOrSeek(untrack(cursor.state)))) return
const element = target instanceof Element ? target : undefined
const nested = element?.closest("[data-scrollable]")
if (nested && nested !== scroller) return
+
+ if (seeking) dispatchRevealSeek(SEEK_CANCELLED_EVENT)
cursor.dispatch(SCROLL_MOVED_EVENT)
}
+ function dispatchRevealSeek(event: RevealSeekEvent) {
+ untrack(() => {
+ const [current, setCurrent] = revealSeek()
+ const next = transitionRevealSeek(current(), event)
+
+ if (next.state !== current()) setCurrent(next.state)
+ next.effects.forEach(() => dispatchHistory(SEEK_REQUESTED_EVENT))
+ })
+ }
+
const setScrollRef = (element: HTMLDivElement | undefined) => {
scroller = element
setState("refs", "scroller", element)
@@ -382,6 +419,18 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
oldest: oldestMessage(),
})
})
+ // Looks for a sought call again once the timeline is on screen, when an older page lands and when paging changes
+ // phase. Reads the transcript only while a call is sought.
+ createEffect(() => {
+ const target = revealSeekTarget(revealSeek()[0]())
+
+ if (!target || !viewReady()) return
+ const oldestAssistantID = timeline.messages().find((message) => message.type === "assistant")?.id
+ const history = historyStatus()
+ untrack(() =>
+ dispatchRevealSeek({ type: "seek.synced", found: revealPart(target), oldestAssistantID, history }),
+ )
+ })
createResizeObserver(
() => state.refs.dock,
(_rect, _element, entry) => {
@@ -454,11 +503,17 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
setRevealMessage: (reveal: (id: string, partID?: string) => void) => {
revealMessage = reveal
},
- // The tool call the route opened the session on, attempted once per history entry.
+ // The tool call the route opened the session on, attempted once per history entry, and the search for a call
+ // that is older than the loaded messages.
reveal: {
pending: () => routeRevealTarget(untrack(revealState)),
consume: (entryKey: string) =>
setRevealState((current) => transitionRouteReveal(current, { type: "reveal.attempted", entryKey })),
+ attempted: (target: string, found: boolean) =>
+ dispatchRevealSeek({ type: "reveal.requested", target, found }),
+ register: (reveal: (target: string) => boolean) => {
+ revealPart = reveal
+ },
},
setScrollRef,
setScrollToEnd: (scroll: (behavior?: ScrollBehavior) => void) => {
diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx
index 7c48024b7f4be..988e5eafe77a4 100644
--- a/packages/app/src/session/timeline/message-timeline.tsx
+++ b/packages/app/src/session/timeline/message-timeline.tsx
@@ -23,7 +23,7 @@ import { createNextTimelineRowRenderer, laneGap, StatusLane, timelineStatus } fr
import { getReadyMarkdown, preloadMarkdown } from "@opencode/session-ui/markdown-cache"
import { createTimelineController, type TimelineController, type TimelineSessionSource } from "./controller"
import type { TimelineFollow } from "./follow"
-import { createTimelineVirtualizer, type TimelineRouteReveal } from "./virtualizer"
+import { createTimelineVirtualizer, type TimelineToolReveal } from "./virtualizer"
import { createSelectedEffect } from "./selected-effect"
import { containsDirectory } from "@opencode/util/path"
import { isWorkspaceDirectory } from "@/workspaces/paths"
@@ -100,7 +100,7 @@ type MessageTimelineProps = {
setRevealMessage?: (fn: (id: string, partID?: string) => void) => void
setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void
setPage?: (fn: (direction: 1 | -1) => void) => void
- reveal?: TimelineRouteReveal
+ reveal?: TimelineToolReveal
search?: JSX.Element
}
diff --git a/packages/app/src/session/timeline/reveal-machine.test.ts b/packages/app/src/session/timeline/reveal-machine.test.ts
new file mode 100644
index 0000000000000..9e1ddcb6082b2
--- /dev/null
+++ b/packages/app/src/session/timeline/reveal-machine.test.ts
@@ -0,0 +1,100 @@
+import { expect, test } from "bun:test"
+import type { HistorySeekStatus } from "./history-machine"
+import {
+ createRevealSeekState,
+ revealSeekTarget,
+ SEEK_CANCELLED_EVENT,
+ transitionRevealSeek,
+ type RevealSeekEffect,
+ type RevealSeekEvent,
+ type RevealSeekState,
+} from "./reveal-machine"
+
+// IDs as the server makes them: a prefix, then a part that ascends with creation.
+const shell = "sh_1e1dbe17b0010Bv53WdPWVw1ic"
+
+// The assistant message whose step started the shell, and the one of the step after it.
+const before = "msg_1e1dbb5d70016rDeImJAWn2Q0N"
+
+const after = "msg_1e1dbffc7001uxmmSBrKBNDabs"
+
+// A reveal that did not find its call, as the virtualizer reports it.
+const requested = (target = shell) => ({ type: "reveal.requested", target, found: false }) as const
+
+// Built the way the driver's effect builds it.
+const synced = (input: { found?: boolean; oldestAssistantID?: string; history?: HistorySeekStatus } = {}) =>
+ ({
+ type: "seek.synced",
+ found: input.found ?? false,
+ oldestAssistantID: "oldestAssistantID" in input ? input.oldestAssistantID : after,
+ history: input.history ?? "seekable",
+ }) satisfies RevealSeekEvent
+
+function replay(events: RevealSeekEvent[]) {
+ return events.reduce<{ state: RevealSeekState; effects: RevealSeekEffect[] }>(
+ (acc, event) => {
+ const next = transitionRevealSeek(acc.state, event)
+
+ return { state: next.state, effects: [...acc.effects, ...next.effects] }
+ },
+ { state: createRevealSeekState(), effects: [] },
+ )
+}
+
+test("a shell's call that is not loaded pages history until it is found", () => {
+ const seeking = replay([requested()])
+ expect(revealSeekTarget(seeking.state)).toBe(shell)
+
+ // One page per sync that finds history ready; none while the page loads.
+ const paged = replay([requested(), synced(), synced({ history: "loading" }), synced()])
+ expect(revealSeekTarget(paged.state)).toBe(shell)
+ expect(paged.effects).toEqual([{ type: "history.seek" }, { type: "history.seek" }])
+
+ const found = replay([requested(), synced(), synced({ found: true })])
+ expect(revealSeekTarget(found.state)).toBeUndefined()
+ expect(found.effects).toEqual([{ type: "history.seek" }])
+})
+
+test.each<{ name: string; event: RevealSeekEvent }>([
+ // A shell a Code Mode script started has no call: it used to page through the whole session.
+ { name: "an assistant message older than the shell is loaded", event: synced({ oldestAssistantID: before }) },
+ { name: "history ran out", event: synced({ history: "exhausted" }) },
+ { name: "a page failed", event: synced({ history: "failed" }) },
+ { name: "the reader scrolled", event: SEEK_CANCELLED_EVENT },
+])("a seek ends without another page once $name", (input) => {
+ const ended = replay([requested(), input.event])
+
+ expect(revealSeekTarget(ended.state)).toBeUndefined()
+ expect(ended.effects).toEqual([])
+})
+
+test("a seek waits while no assistant message is loaded", () => {
+ const next = replay([requested(), synced({ oldestAssistantID: undefined })])
+
+ expect(revealSeekTarget(next.state)).toBe(shell)
+ expect(next.effects).toEqual([{ type: "history.seek" }])
+})
+
+test("a call named by its own ID does not page history", () => {
+ expect(revealSeekTarget(replay([requested("toolu_0186aieMGq1P5bArLj3ErJdA")]).state)).toBeUndefined()
+})
+
+test("the reader's next reveal replaces a seek under way", () => {
+ const other = "sh_1dbbc79d1001QOMb3Do3RUuxd9"
+ expect(revealSeekTarget(replay([requested(), requested(other)]).state)).toBe(other)
+ // A call that was loaded is on screen now, so the earlier one must not take the view from it later.
+ expect(
+ revealSeekTarget(replay([requested(), { type: "reveal.requested", target: other, found: true }]).state),
+ ).toBeUndefined()
+})
+
+test("events that change nothing return the same state", () => {
+ const idle = createRevealSeekState()
+ expect(transitionRevealSeek(idle, synced()).state).toBe(idle)
+ expect(transitionRevealSeek(idle, SEEK_CANCELLED_EVENT).state).toBe(idle)
+
+ const seeking = replay([requested()]).state
+ expect(transitionRevealSeek(seeking, requested()).state).toBe(seeking)
+ expect(transitionRevealSeek(seeking, synced({ history: "loading" })).state).toBe(seeking)
+ expect(transitionRevealSeek(seeking, synced()).state).toBe(seeking)
+})
diff --git a/packages/app/src/session/timeline/reveal-machine.ts b/packages/app/src/session/timeline/reveal-machine.ts
new file mode 100644
index 0000000000000..565479bc5f329
--- /dev/null
+++ b/packages/app/src/session/timeline/reveal-machine.ts
@@ -0,0 +1,94 @@
+import type { HistorySeekStatus } from "./history-machine"
+
+const SHELL_PREFIX = "sh_"
+
+const MESSAGE_PREFIX = "msg_"
+
+/**
+ * The search for a shell's tool call that is older than the loaded messages. A route or a shell notice asked for it,
+ * and history pages toward it until it loads or the loaded messages reach back to where it would be.
+ */
+export type RevealSeekState =
+ | { readonly status: "idle" }
+ | { readonly status: "seeking"; readonly target: string }
+
+export type RevealSeekEvent =
+ /** The route or a row asked for `target`. `found`: it is among the loaded messages and now revealed. */
+ | { readonly type: "reveal.requested"; readonly target: string; readonly found: boolean }
+ /**
+ * The timeline looked again. `found`: the call is loaded and now revealed. Otherwise the oldest loaded assistant
+ * message and history paging decide whether an older page can still hold it.
+ */
+ | {
+ readonly type: "seek.synced"
+ readonly found: boolean
+ readonly oldestAssistantID: string | undefined
+ readonly history: HistorySeekStatus
+ }
+ /** The reader scrolled or pressed in the timeline, so a call found later would move the view against them. */
+ | { readonly type: "seek.cancelled" }
+
+/** Load the next older page toward the call. */
+export type RevealSeekEffect = { readonly type: "history.seek" }
+
+export type RevealSeekTransition = {
+ readonly state: RevealSeekState
+ readonly effects: readonly RevealSeekEffect[]
+}
+
+// Shared for the dispatch on every scroll gesture, so it allocates nothing.
+export const SEEK_CANCELLED_EVENT: RevealSeekEvent = Object.freeze({ type: "seek.cancelled" })
+
+const IDLE: RevealSeekState = Object.freeze({ status: "idle" })
+
+const NO_EFFECTS: readonly RevealSeekEffect[] = Object.freeze([])
+
+const HISTORY_SEEK: readonly RevealSeekEffect[] = Object.freeze([{ type: "history.seek" }])
+
+export function createRevealSeekState(): RevealSeekState {
+ return IDLE
+}
+
+export function transitionRevealSeek(state: RevealSeekState, event: RevealSeekEvent): RevealSeekTransition {
+ if (event.type === "reveal.requested") {
+ // A found call ends a seek for another one. A call named by its own ID is looked for among the loaded messages
+ // only: nothing says how far back it is, so one that does not exist would page through the whole session.
+ if (event.found || !event.target.startsWith(SHELL_PREFIX)) return settled(IDLE)
+
+ if (state.status === "seeking" && state.target === event.target) return settled(state)
+
+ return settled({ status: "seeking", target: event.target })
+ }
+
+ if (state.status === "idle") return settled(state)
+
+ if (event.type === "seek.cancelled" || event.found) return settled(IDLE)
+
+ if (reachesShell(event.oldestAssistantID, state.target)) return settled(IDLE)
+
+ if (event.history === "seekable") return { state, effects: HISTORY_SEEK }
+
+ if (event.history === "loading") return settled(state)
+
+ // History ran out or a page failed, so the call cannot load.
+ return settled(IDLE)
+}
+
+/** The call history pages toward, while one is sought. */
+export function revealSeekTarget(state: RevealSeekState) {
+ return state.status === "seeking" ? state.target : undefined
+}
+
+// A shell's call runs in the newest assistant message created before the shell, and IDs ascend with creation. Once an
+// assistant message older than the shell is loaded, the call is among the loaded messages or does not exist, as for
+// a shell that a Code Mode script started.
+function reachesShell(oldestAssistantID: string | undefined, shellID: string) {
+ return (
+ oldestAssistantID !== undefined &&
+ oldestAssistantID.slice(MESSAGE_PREFIX.length) < shellID.slice(SHELL_PREFIX.length)
+ )
+}
+
+function settled(state: RevealSeekState): RevealSeekTransition {
+ return { state, effects: NO_EFFECTS }
+}
diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx
index cac23b1f18eb2..8a64131437125 100644
--- a/packages/app/src/session/timeline/virtualizer.tsx
+++ b/packages/app/src/session/timeline/virtualizer.tsx
@@ -132,13 +132,19 @@ type Input = {
setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void
/** Pages the timeline for keys pressed outside it, such as PageUp in the composer. */
setPage?: (fn: (direction: 1 | -1) => void) => void
- reveal?: TimelineRouteReveal
+ reveal?: TimelineToolReveal
}
-/** A tool call the route asks this timeline to open on; `consume` marks its history entry attempted. */
-export type TimelineRouteReveal = {
+/**
+ * How this timeline opens on a tool call. `pending` is the one the route asks for, and `consume` marks its history
+ * entry attempted. `attempted` reports each reveal the route or a row asked for: older history is paged toward a
+ * call that was not among the loaded messages, and the reveal the timeline registers runs again as each page lands.
+ */
+export type TimelineToolReveal = {
pending: () => { readonly entryKey: string; readonly target: string } | undefined
consume: (entryKey: string) => void
+ attempted: (target: string, found: boolean) => void
+ register: (reveal: (target: string) => boolean) => void
}
type ViewProps = {
@@ -611,6 +617,15 @@ export function createTimelineVirtualizer(input: Input) {
return true
}
+ // A call older than the loaded messages is not in the list yet, so older history is paged toward it.
+ function revealOrSeekPart(target: string) {
+ const revealed = revealPart(target)
+
+ if (active()) input.reveal?.attempted(target, revealed)
+
+ return revealed
+ }
+
// Puts the anchored row's top edge at its scroll margin, just below the headers that stick above it. Its own
// growth extends downward, so only size changes at or above its row can move it; each of those calls this again.
function pinAnchor() {
@@ -707,7 +722,7 @@ export function createTimelineVirtualizer(input: Input) {
// A route can open this timeline on a tool call, e.g. a shell picked from inside a subagent, instead of its end.
// It is attempted once per history entry: a call that is not in the list is not looked for again on reattach.
const reveal = input.reveal?.pending()
- const revealed = !!reveal && revealPart(reveal.target)
+ const revealed = !!reveal && revealOrSeekPart(reveal.target)
if (reveal) input.reveal?.consume(reveal.entryKey)
@@ -716,6 +731,7 @@ export function createTimelineVirtualizer(input: Input) {
reportOffset?.(root.scrollTop, false)
dispatchCold(CHECK_REQUESTED)
})
+ input.reveal?.register(revealPart)
input.setRevealMessage?.((id, partID) => {
if (!active()) return
@@ -1388,6 +1404,7 @@ export function createTimelineVirtualizer(input: Input) {
if (active()) {
input.setScrollRef(undefined)
+ input.reveal?.register(() => false)
input.setRevealMessage?.(() => {})
input.setScrollToEnd?.(() => {})
input.setPage?.(() => {})
@@ -1404,7 +1421,7 @@ export function createTimelineVirtualizer(input: Input) {
setToolOpen(key, open)
},
},
- revealPart,
+ revealPart: revealOrSeekPart,
View,
}
}
From 4b6016f3ea47dd6e8a12f9154680dec7023ff3a3 Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Wed, 25 Nov 2026 01:34:31 +1000
Subject: [PATCH 2/6] fix(app): end the search for an older call when the
reader moves
The search ended only on input the timeline handles itself: the wheel, a touch, its scroll keys and a press. A drag of the scrollbar thumb, Ctrl+End or a page key on a focused button left it running, and the call then took the view from wherever the reader had gone.
It now ends on any movement the scroll event counts as the reader's, and on a request to go somewhere else.
---
packages/app/AGENTS.md | 5 +-
.../e2e/regression/timeline-history.spec.ts | 84 +++++++++++++++++++
.../app/src/session/timeline/interaction.ts | 19 ++++-
.../src/session/timeline/reveal-machine.ts | 7 +-
.../app/src/session/timeline/virtualizer.tsx | 4 +
5 files changed, 113 insertions(+), 6 deletions(-)
diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md
index 0290c696c4f7f..e7056313a2078 100644
--- a/packages/app/AGENTS.md
+++ b/packages/app/AGENTS.md
@@ -130,8 +130,9 @@ This section is the single source for what may move or restyle the session timel
- To check by hand: click a tool header, a link and a notice in the timeline, then scroll up and down with the wheel. The timeline must follow the wheel.
- A link can name content that is older than the loaded messages, such as the call of a shell whose notice the reader clicks. The timeline pages history toward it and moves once, when it loads (`src/session/timeline/reveal-machine.ts`).
- Page toward a target only while something says where it can be. A shell's call is older than the shell, and IDs ascend with creation, so the search ends once an assistant message older than the shell is loaded. Without that bound a target that does not exist loads the whole session: a shell that a Code Mode script started has no call, which was the case for 40 of 265 shell notices in four real sessions.
- - The reader's scroll or press in the timeline ends the search. A move that lands after the reader has gone elsewhere is one they did not ask for.
- - Keeper: "a shell notice opens its call from an older page, paging back only as far as the call" in `e2e/regression/timeline-history.spec.ts`.
+ - Any movement of the reader ends the search, and so does a request to go somewhere else (Jump to latest, a prompt, a Find hit). A move that lands after the reader has gone elsewhere is one they did not ask for.
+ - Take the reader's movement from the scroll event (`reader !== 0`, see "Following the end"), not from a list of inputs. The search once ended only on the wheel, a touch, the timeline's own scroll keys and a press. A drag of the scrollbar thumb, Ctrl+End or a page key on a focused button left it running, and the call then took the view 880 to 4,700 px from where the reader had gone.
+ - Keepers: "a shell notice opens its call from an older page, paging back only as far as the call" and "a reader who moves on while a shell's call is sought is not taken to it" in `e2e/regression/timeline-history.spec.ts`.
### Scroll writes
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index be892cd80dadb..0c82671924eb0 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -184,6 +184,90 @@ test.describe("timeline history", () => {
expect(oldest).toBeGreaterThan(0)
})
+ // The search for the call ended only on input the timeline handles itself. A native key or a drag of the scrollbar
+ // thumb left it running, and the call took the view from wherever the reader had gone.
+ test("a reader who moves on while a shell's call is sought is not taken to it", async ({ page }) => {
+ const history = historyMessages(120)
+ const text = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}.`).join("\n\n")
+
+ const call = assistantMessage(
+ [
+ toolPart(
+ "prt_sought_call",
+ "shell",
+ "completed",
+ { command: "bun serve.ts", background: true },
+ { output: "listening", metadata: { shellID: "sh_00109_history_d_shell", status: "running" } },
+ ),
+ ],
+ { id: "msg_00109_history_c_call", parentID: "msg_00109_history_a_user", created: 1690001092000 },
+ )
+
+ // The notice is on the newest page, above a long reply. Its call is on the page before.
+ const messages: SessionMessageInfo[] = [
+ ...history.slice(0, 220),
+ call,
+ ...history.slice(220),
+ {
+ id: "msg_00120_shell_finished",
+ type: "synthetic",
+ text: '\nlistening\n',
+ description: "bun serve.ts",
+ metadata: { source: "shell", shellID: "sh_00109_history_d_shell", state: "completed" },
+ time: { created: 1690001200000 },
+ },
+ userMessage([textPart("prt_sought_prompt", "Summarise the run")], {
+ id: "msg_00121_later_a_user",
+ created: 1690001210000,
+ }),
+ assistantMessage([textPart("prt_sought_reply", text)], {
+ id: "msg_00121_later_b_assistant",
+ parentID: "msg_00121_later_a_user",
+ created: 1690001211000,
+ }),
+ ]
+
+ const older = Promise.withResolvers()
+ const requests: { before?: string; phase: "start" | "end" }[] = []
+ await setupTimeline(page, {
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ beforeMessagesResponse: ({ before }) => (before ? older.promise : Promise.resolve()),
+ onMessages: (request) => requests.push(request),
+ })
+
+ const scroller = timelineScroller(page)
+ const notice = scroller.getByRole("button", { name: /^Shell finished/ })
+ const end = scroller.getByText("Paragraph 39.", { exact: true })
+ await expect(end).toBeInViewport()
+ await scroller.hover()
+ await expect(async () => {
+ await page.mouse.wheel(0, -200)
+ await expect(notice).toBeInViewport({ timeout: 1_000 })
+ }).toPass()
+ await notice.click()
+ await expect.poll(() => requests.some((request) => request.before && request.phase === "start")).toBe(true)
+
+ // A key the timeline leaves to the browser: the reader goes back to the end.
+ await page.keyboard.press("Control+End")
+ await expect(end).toBeInViewport()
+ const height = await scroller.evaluate((element) => element.scrollHeight)
+
+ older.resolve()
+ // The page with the call has landed above the reader.
+ await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
+ // Run the frames in which a reveal that was still to come would scroll.
+ await page.clock.install()
+ await page.clock.runFor(1_000)
+ await expect(end).toBeInViewport()
+ await expect(scroller.locator('[data-timeline-part-id="prt_sought_call"]')).not.toBeInViewport()
+ })
+
test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => {
const id = "ses_history_restore"
const other = "ses_history_other"
diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts
index 67fb52055f849..6ce7b8662b7b5 100644
--- a/packages/app/src/session/timeline/interaction.ts
+++ b/packages/app/src/session/timeline/interaction.ts
@@ -204,6 +204,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
let resumeFrame: (() => void) | undefined
const resume = (behavior?: ScrollBehavior) => {
+ endRevealSeek()
cursor.clear()
const attempt = follow.beginReturn()
// Scrolls on the next frame, before it paints. A submit resumes from its key handler right after changing the
@@ -239,12 +240,21 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
return
}
+ endRevealSeek()
cursor.jump(messages[target].id, "auto")
}
+ const seekingReveal = () => revealSeekTarget(untrack(() => revealSeek()[0]())) !== undefined
+
+ // The reader moved the view or asked to go somewhere else. A call that loads later would take the view from
+ // where they went, so the search for it ends. Runs on every scroll the reader makes, so it checks first.
+ function endRevealSeek() {
+ if (seekingReveal()) dispatchRevealSeek(SEEK_CANCELLED_EVENT)
+ }
+
// A gesture inside a nested scrollable region scrolls that region, not the timeline.
const markUserScroll = (target?: EventTarget | null) => {
- const seeking = revealSeekTarget(untrack(() => revealSeek()[0]())) !== undefined
+ const seeking = seekingReveal()
if (!scroller || (!seeking && !hasFreshCursorOrSeek(untrack(cursor.state)))) return
const element = target instanceof Element ? target : undefined
@@ -466,10 +476,14 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
return {
actions: {
navigateMessage,
- jumpToMessage: (id: string) => cursor.jump(id, "auto"),
+ jumpToMessage: (id: string) => {
+ endRevealSeek()
+ cursor.jump(id, "auto")
+ },
page: (direction: 1 | -1) => page(direction),
// Find and tool reveals move the view like a scroll, so the chosen prompt is no longer where navigation starts.
revealMessage: (id: string, partID?: string) => {
+ endRevealSeek()
cursor.dispatch(SCROLL_MOVED_EVENT)
revealMessage(id, partID)
},
@@ -514,6 +528,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
register: (reveal: (target: string) => boolean) => {
revealPart = reveal
},
+ readerMoved: endRevealSeek,
},
setScrollRef,
setScrollToEnd: (scroll: (behavior?: ScrollBehavior) => void) => {
diff --git a/packages/app/src/session/timeline/reveal-machine.ts b/packages/app/src/session/timeline/reveal-machine.ts
index 565479bc5f329..40fb27f7dfbcd 100644
--- a/packages/app/src/session/timeline/reveal-machine.ts
+++ b/packages/app/src/session/timeline/reveal-machine.ts
@@ -25,7 +25,10 @@ export type RevealSeekEvent =
readonly oldestAssistantID: string | undefined
readonly history: HistorySeekStatus
}
- /** The reader scrolled or pressed in the timeline, so a call found later would move the view against them. */
+ /**
+ * The reader moved the view by any input, pressed in the timeline, or asked to go somewhere else. A call found
+ * later would take the view from where they went.
+ */
| { readonly type: "seek.cancelled" }
/** Load the next older page toward the call. */
@@ -36,7 +39,7 @@ export type RevealSeekTransition = {
readonly effects: readonly RevealSeekEffect[]
}
-// Shared for the dispatch on every scroll gesture, so it allocates nothing.
+// Shared, so ending a seek allocates no event.
export const SEEK_CANCELLED_EVENT: RevealSeekEvent = Object.freeze({ type: "seek.cancelled" })
const IDLE: RevealSeekState = Object.freeze({ status: "idle" })
diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx
index 8a64131437125..ed24c875e91d2 100644
--- a/packages/app/src/session/timeline/virtualizer.tsx
+++ b/packages/app/src/session/timeline/virtualizer.tsx
@@ -145,6 +145,8 @@ export type TimelineToolReveal = {
consume: (entryKey: string) => void
attempted: (target: string, found: boolean) => void
register: (reveal: (target: string) => boolean) => void
+ /** The reader moved the view, by any input. A call that loads later must not take it from where they went. */
+ readerMoved: () => void
}
type ViewProps = {
@@ -1192,6 +1194,8 @@ export function createTimelineVirtualizer(input: Input) {
scrollEvent.maxScroll = maxScroll
scrollEvent.reader = seen.reader
seen.reader = 0
+
+ if (scrollEvent.reader !== 0) input.reveal?.readerMoved()
input.follow.dispatch(scrollEvent)
dispatchCold(CHECK_REQUESTED)
input.onScheduleScrollState(root)
From b7eee05cd159bde9dfdc20bee86a6facf0bee690 Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Wed, 25 Nov 2026 01:58:15 +1000
Subject: [PATCH 3/6] test(app): cover Ctrl+End and a thumb drag during the
search for a call
---
.../e2e/regression/timeline-history.spec.ts | 180 ++++++++++--------
1 file changed, 101 insertions(+), 79 deletions(-)
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index 0c82671924eb0..1a07053b7adb9 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -184,89 +184,111 @@ test.describe("timeline history", () => {
expect(oldest).toBeGreaterThan(0)
})
- // The search for the call ended only on input the timeline handles itself. A native key or a drag of the scrollbar
- // thumb left it running, and the call took the view from wherever the reader had gone.
- test("a reader who moves on while a shell's call is sought is not taken to it", async ({ page }) => {
- const history = historyMessages(120)
- const text = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}.`).join("\n\n")
-
- const call = assistantMessage(
- [
- toolPart(
- "prt_sought_call",
- "shell",
- "completed",
- { command: "bun serve.ts", background: true },
- { output: "listening", metadata: { shellID: "sh_00109_history_d_shell", status: "running" } },
- ),
- ],
- { id: "msg_00109_history_c_call", parentID: "msg_00109_history_a_user", created: 1690001092000 },
- )
-
- // The notice is on the newest page, above a long reply. Its call is on the page before.
- const messages: SessionMessageInfo[] = [
- ...history.slice(0, 220),
- call,
- ...history.slice(220),
- {
- id: "msg_00120_shell_finished",
- type: "synthetic",
- text: '\nlistening\n',
- description: "bun serve.ts",
- metadata: { source: "shell", shellID: "sh_00109_history_d_shell", state: "completed" },
- time: { created: 1690001200000 },
- },
- userMessage([textPart("prt_sought_prompt", "Summarise the run")], {
- id: "msg_00121_later_a_user",
- created: 1690001210000,
- }),
- assistantMessage([textPart("prt_sought_reply", text)], {
- id: "msg_00121_later_b_assistant",
- parentID: "msg_00121_later_a_user",
- created: 1690001211000,
- }),
- ]
-
- const older = Promise.withResolvers()
- const requests: { before?: string; phase: "start" | "end" }[] = []
- await setupTimeline(page, {
- sessionMessages: messages,
- pageMessages: (_, limit, before) => {
- const end = before ? messages.findIndex((message) => message.id === before) : messages.length
- const start = Math.max(0, end - Math.min(16, limit))
-
- return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ // The search for the call ended only on input the timeline handles itself: the wheel, a touch, its own scroll keys
+ // and a press. A key the browser handles or a drag of the scrollbar thumb left it running, and the call took the
+ // view from wherever the reader had gone.
+ for (const input of [
+ { name: "Ctrl+End", move: (page: Page) => page.keyboard.press("Control+End") },
+ {
+ name: "a drag of the scrollbar thumb",
+ move: async (page: Page) => {
+ const box = await page.locator('.scroll-view__thumb[data-orientation="vertical"]').boundingBox()
+
+ if (!box) throw new Error("The timeline has no scrollbar thumb")
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
+ await page.mouse.down()
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2 + 2_000, { steps: 8 })
+ await page.mouse.up()
},
- beforeMessagesResponse: ({ before }) => (before ? older.promise : Promise.resolve()),
- onMessages: (request) => requests.push(request),
- })
+ },
+ ])
+ test(`a reader who goes to the end with ${input.name} while a shell's call is sought is not taken to it`, async ({
+ page,
+ }) => {
+ const history = historyMessages(120)
+ const text = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}.`).join("\n\n")
+
+ const call = assistantMessage(
+ [
+ toolPart(
+ "prt_sought_call",
+ "shell",
+ "completed",
+ { command: "bun serve.ts", background: true },
+ { output: "listening", metadata: { shellID: "sh_00109_history_d_shell", status: "running" } },
+ ),
+ ],
+ { id: "msg_00109_history_c_call", parentID: "msg_00109_history_a_user", created: 1690001092000 },
+ )
- const scroller = timelineScroller(page)
- const notice = scroller.getByRole("button", { name: /^Shell finished/ })
- const end = scroller.getByText("Paragraph 39.", { exact: true })
- await expect(end).toBeInViewport()
- await scroller.hover()
- await expect(async () => {
- await page.mouse.wheel(0, -200)
- await expect(notice).toBeInViewport({ timeout: 1_000 })
- }).toPass()
- await notice.click()
- await expect.poll(() => requests.some((request) => request.before && request.phase === "start")).toBe(true)
+ // The notice is on the newest page, above a long reply. Its call is on the page before.
+ const messages: SessionMessageInfo[] = [
+ ...history.slice(0, 220),
+ call,
+ ...history.slice(220),
+ {
+ id: "msg_00120_shell_finished",
+ type: "synthetic",
+ text: '\nlistening\n',
+ description: "bun serve.ts",
+ metadata: { source: "shell", shellID: "sh_00109_history_d_shell", state: "completed" },
+ time: { created: 1690001200000 },
+ },
+ userMessage([textPart("prt_sought_prompt", "Summarise the run")], {
+ id: "msg_00121_later_a_user",
+ created: 1690001210000,
+ }),
+ assistantMessage([textPart("prt_sought_reply", text)], {
+ id: "msg_00121_later_b_assistant",
+ parentID: "msg_00121_later_a_user",
+ created: 1690001211000,
+ }),
+ ]
+
+ const older = Promise.withResolvers()
+ const requests: { before?: string; phase: "start" | "end" }[] = []
+ await setupTimeline(page, {
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
- // A key the timeline leaves to the browser: the reader goes back to the end.
- await page.keyboard.press("Control+End")
- await expect(end).toBeInViewport()
- const height = await scroller.evaluate((element) => element.scrollHeight)
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ beforeMessagesResponse: ({ before }) => (before ? older.promise : Promise.resolve()),
+ onMessages: (request) => requests.push(request),
+ })
- older.resolve()
- // The page with the call has landed above the reader.
- await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
- // Run the frames in which a reveal that was still to come would scroll.
- await page.clock.install()
- await page.clock.runFor(1_000)
- await expect(end).toBeInViewport()
- await expect(scroller.locator('[data-timeline-part-id="prt_sought_call"]')).not.toBeInViewport()
- })
+ const scroller = timelineScroller(page)
+ const notice = scroller.getByRole("button", { name: /^Shell finished/ })
+ const end = scroller.getByText("Paragraph 39.", { exact: true })
+
+ // How far the view is from the end of the transcript.
+ const away = () =>
+ scroller.evaluate((element) => Math.round(element.scrollHeight - element.clientHeight - element.scrollTop))
+
+ await expect(end).toBeInViewport()
+ await scroller.hover()
+ await expect(async () => {
+ await page.mouse.wheel(0, -200)
+ await expect(notice).toBeInViewport({ timeout: 1_000 })
+ }).toPass()
+ await notice.click()
+ await expect.poll(() => requests.some((request) => request.before && request.phase === "start")).toBe(true)
+
+ await input.move(page)
+ await expect.poll(away).toBe(0)
+ const height = await scroller.evaluate((element) => element.scrollHeight)
+
+ older.resolve()
+ // The page with the call has landed above the reader.
+ await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
+ // Run the frames in which a reveal that was still to come would scroll.
+ await page.clock.install()
+ await page.clock.runFor(1_000)
+ expect(await away()).toBe(0)
+ await expect(end).toBeInViewport()
+ })
test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => {
const id = "ses_history_restore"
From 78d104bd2957110463e96c7202ae77cb460b6b33 Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Wed, 25 Nov 2026 02:59:26 +1000
Subject: [PATCH 4/6] fix(app): keep the view on a call that a link in the New
timeline asked for
The link that asks for a shell's call keeps focus after the click. In the New timeline it sits inside an events row, which is built again when an older page lands. Focus then went to the link that took its place, and the browser scrolled the timeline back to it, away from the call.
The viewport takes focus, without scrolling, when the search for the call starts.
---
packages/app/AGENTS.md | 3 +-
.../e2e/regression/timeline-history.spec.ts | 58 +++++++++++++++++++
.../app/src/session/timeline/virtualizer.tsx | 5 ++
3 files changed, 65 insertions(+), 1 deletion(-)
diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md
index e7056313a2078..fb8f64aa3919d 100644
--- a/packages/app/AGENTS.md
+++ b/packages/app/AGENTS.md
@@ -132,7 +132,8 @@ This section is the single source for what may move or restyle the session timel
- Page toward a target only while something says where it can be. A shell's call is older than the shell, and IDs ascend with creation, so the search ends once an assistant message older than the shell is loaded. Without that bound a target that does not exist loads the whole session: a shell that a Code Mode script started has no call, which was the case for 40 of 265 shell notices in four real sessions.
- Any movement of the reader ends the search, and so does a request to go somewhere else (Jump to latest, a prompt, a Find hit). A move that lands after the reader has gone elsewhere is one they did not ask for.
- Take the reader's movement from the scroll event (`reader !== 0`, see "Following the end"), not from a list of inputs. The search once ended only on the wheel, a touch, the timeline's own scroll keys and a press. A drag of the scrollbar thumb, Ctrl+End or a page key on a focused button left it running, and the call then took the view 880 to 4,700 px from where the reader had gone.
- - Keepers: "a shell notice opens its call from an older page, paging back only as far as the call" and "a reader who moves on while a shell's call is sought is not taken to it" in `e2e/regression/timeline-history.spec.ts`.
+ - The control that asked must not keep focus while history pages. In the New timeline it is a link inside an events row, and a page that lands builds that row again. The focus rescue then focuses the link that takes its place, and the browser scrolls the timeline back to it: the call opened 3,700 px out of view. `revealOrSeekPart` gives focus to the viewport, without scrolling, when the search starts.
+ - Keepers in `e2e/regression/timeline-history.spec.ts`: "a shell notice opens its call from an older page, paging back only as far as the call", "a shell's link in the New timeline opens its call from an older page", and "a reader who goes to the end with … while a shell's call is sought is not taken to it" (Ctrl+End, a drag of the scrollbar thumb).
### Scroll writes
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index 1a07053b7adb9..d80478aef42d7 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -184,6 +184,64 @@ test.describe("timeline history", () => {
expect(oldest).toBeGreaterThan(0)
})
+ // In the New timeline the notice is a link inside an events row, and it keeps focus after the click. An older page
+ // that lands builds that row again: focus went to the link that took its place, and the browser scrolled the
+ // timeline back to it, away from the call.
+ test("a shell's link in the New timeline opens its call from an older page", async ({ page }) => {
+ const history = historyMessages(120)
+
+ const call = assistantMessage(
+ [
+ toolPart(
+ "prt_older_call",
+ "shell",
+ "completed",
+ { command: "bun serve.ts", background: true },
+ { output: "listening", metadata: { shellID: "sh_00079_history_d_shell", status: "running" } },
+ ),
+ ],
+ { id: "msg_00079_history_c_call", parentID: "msg_00079_history_a_user", created: 1690000792000 },
+ )
+
+ const messages: SessionMessageInfo[] = [
+ ...history.slice(0, 160),
+ call,
+ ...history.slice(160),
+ {
+ id: "msg_00120_shell_finished",
+ type: "synthetic",
+ text: '\nlistening\n',
+ description: "bun serve.ts",
+ metadata: { source: "shell", shellID: "sh_00079_history_d_shell", state: "completed" },
+ time: { created: 1690001200000 },
+ },
+ ]
+
+ await setupTimeline(page, {
+ settings: { newTimeline: true },
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ })
+
+ const scroller = timelineScroller(page)
+ const link = scroller.locator('[data-slot="timeline-event-item"][data-kind="shell"]')
+ const tool = scroller.locator('[data-timeline-part-id="prt_older_call"]')
+
+ await scroller.locator('[data-component="timeline-event-row"] [data-slot="collapsible-trigger"]').click()
+ await expect(tool).toHaveCount(0)
+ await link.click()
+ await expect(tool).toBeInViewport()
+ // Once every page the search asked for has landed, the call is still where the reader was taken.
+ await page.clock.install()
+ await page.clock.runFor(1_000)
+ await expect(tool).toBeInViewport()
+ })
+
// The search for the call ended only on input the timeline handles itself: the wheel, a touch, its own scroll keys
// and a press. A key the browser handles or a drag of the scrollbar thumb left it running, and the call took the
// view from wherever the reader had gone.
diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx
index ed24c875e91d2..146ea86dcaccb 100644
--- a/packages/app/src/session/timeline/virtualizer.tsx
+++ b/packages/app/src/session/timeline/virtualizer.tsx
@@ -622,6 +622,11 @@ export function createTimelineVirtualizer(input: Input) {
// A call older than the loaded messages is not in the list yet, so older history is paged toward it.
function revealOrSeekPart(target: string) {
const revealed = revealPart(target)
+ const root = listRoot()
+
+ // The control that asked keeps focus while history pages. A page that lands builds its row again, focus goes to
+ // the control that takes its place, and the browser scrolls the timeline back to that one.
+ if (!revealed && root?.contains(document.activeElement)) root.focus({ preventScroll: true })
if (active()) input.reveal?.attempted(target, revealed)
From 9dd48355072cb95ec49d9734c0a20f41876c18e0 Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Wed, 25 Nov 2026 07:35:53 +1000
Subject: [PATCH 5/6] fix(app): end the search for a call on the reader's
scroll input, also when the view cannot move
The search ended when the reader moved the view. At the end of the transcript Ctrl+End, a press on the scrollbar thumb and a page key on a button move nothing, so the search went on and the call then took the view: 1,737 px in the keeper, 4,719 and 4,787 px in a real session.
The scrollbar and the scroll keys now count as the reader's input when the ScrollView is about to act on them, and a page key that the browser handles on a button counts too. The search no longer ends inside markUserScroll, where Find's seek ends as well: each seek ends on its own condition. A scroll while the cold mount is hidden is not the reader's.
---
.../e2e/regression/timeline-history.spec.ts | 77 +++++++++++--------
.../app/src/session/timeline/interaction.ts | 37 +++++----
.../app/src/session/timeline/virtualizer.tsx | 37 +++++++--
3 files changed, 99 insertions(+), 52 deletions(-)
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index d80478aef42d7..8f53cc005ede1 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -244,25 +244,36 @@ test.describe("timeline history", () => {
// The search for the call ended only on input the timeline handles itself: the wheel, a touch, its own scroll keys
// and a press. A key the browser handles or a drag of the scrollbar thumb left it running, and the call took the
- // view from wherever the reader had gone.
+ // view from wherever the reader had gone. A press on the thumb that moves nothing, at the end of the transcript,
+ // left it running too: the thumb is outside the scroll view, so its press was not the timeline's.
+ const dragThumb = async (page: Page, distance: number) => {
+ const box = await page.locator('.scroll-view__thumb[data-orientation="vertical"]').boundingBox()
+
+ if (!box) throw new Error("The timeline has no scrollbar thumb")
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
+ await page.mouse.down()
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2 + distance, { steps: 8 })
+ await page.mouse.up()
+ }
+
for (const input of [
- { name: "Ctrl+End", move: (page: Page) => page.keyboard.press("Control+End") },
+ { name: "goes to the end with Ctrl+End", reply: true, move: (page: Page) => page.keyboard.press("Control+End") },
{
- name: "a drag of the scrollbar thumb",
- move: async (page: Page) => {
- const box = await page.locator('.scroll-view__thumb[data-orientation="vertical"]').boundingBox()
-
- if (!box) throw new Error("The timeline has no scrollbar thumb")
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
- await page.mouse.down()
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2 + 2_000, { steps: 8 })
- await page.mouse.up()
- },
+ name: "goes to the end with a drag of the scrollbar thumb",
+ reply: true,
+ move: (page: Page) => dragThumb(page, 2_000),
+ },
+ // The notice is the last row, so the view is at the end already and none of these moves it.
+ { name: "presses Ctrl+End at the end", reply: false, move: (page: Page) => page.keyboard.press("Control+End") },
+ { name: "presses the scrollbar thumb at the end", reply: false, move: (page: Page) => dragThumb(page, 200) },
+ {
+ // The browser handles a page key on a button, not the timeline.
+ name: "presses PageDown on a button at the end",
+ reply: false,
+ move: (page: Page) => timelineScroller(page).getByRole("button", { name: /^Shell finished/ }).press("PageDown"),
},
])
- test(`a reader who goes to the end with ${input.name} while a shell's call is sought is not taken to it`, async ({
- page,
- }) => {
+ test(`a reader who ${input.name} while a shell's call is sought is not taken to it`, async ({ page }) => {
const history = historyMessages(120)
const text = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}.`).join("\n\n")
@@ -279,7 +290,7 @@ test.describe("timeline history", () => {
{ id: "msg_00109_history_c_call", parentID: "msg_00109_history_a_user", created: 1690001092000 },
)
- // The notice is on the newest page, above a long reply. Its call is on the page before.
+ // The notice is on the newest page, above a long reply or as its last row. Its call is on the page before.
const messages: SessionMessageInfo[] = [
...history.slice(0, 220),
call,
@@ -292,15 +303,19 @@ test.describe("timeline history", () => {
metadata: { source: "shell", shellID: "sh_00109_history_d_shell", state: "completed" },
time: { created: 1690001200000 },
},
- userMessage([textPart("prt_sought_prompt", "Summarise the run")], {
- id: "msg_00121_later_a_user",
- created: 1690001210000,
- }),
- assistantMessage([textPart("prt_sought_reply", text)], {
- id: "msg_00121_later_b_assistant",
- parentID: "msg_00121_later_a_user",
- created: 1690001211000,
- }),
+ ...(input.reply
+ ? [
+ userMessage([textPart("prt_sought_prompt", "Summarise the run")], {
+ id: "msg_00121_later_a_user",
+ created: 1690001210000,
+ }),
+ assistantMessage([textPart("prt_sought_reply", text)], {
+ id: "msg_00121_later_b_assistant",
+ parentID: "msg_00121_later_a_user",
+ created: 1690001211000,
+ }),
+ ]
+ : []),
]
const older = Promise.withResolvers()
@@ -319,7 +334,7 @@ test.describe("timeline history", () => {
const scroller = timelineScroller(page)
const notice = scroller.getByRole("button", { name: /^Shell finished/ })
- const end = scroller.getByText("Paragraph 39.", { exact: true })
+ const end = input.reply ? scroller.getByText("Paragraph 39.", { exact: true }) : notice
// How far the view is from the end of the transcript.
const away = () =>
@@ -327,10 +342,12 @@ test.describe("timeline history", () => {
await expect(end).toBeInViewport()
await scroller.hover()
- await expect(async () => {
- await page.mouse.wheel(0, -200)
- await expect(notice).toBeInViewport({ timeout: 1_000 })
- }).toPass()
+
+ if (input.reply)
+ await expect(async () => {
+ await page.mouse.wheel(0, -200)
+ await expect(notice).toBeInViewport({ timeout: 1_000 })
+ }).toPass()
await notice.click()
await expect.poll(() => requests.some((request) => request.before && request.phase === "start")).toBe(true)
diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts
index 6ce7b8662b7b5..794dceaa15318 100644
--- a/packages/app/src/session/timeline/interaction.ts
+++ b/packages/app/src/session/timeline/interaction.ts
@@ -79,12 +79,12 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
return createSignal(createRevealSeekState())
})
+ // Opens a loaded part in the active timeline, registered by its virtualizer.
+ let revealPart = (_target: string) => false
// The active timeline's navigation, registered by its virtualizer.
let revealMessage = (_id: string, _partID?: string) => {}
- let revealPart = (_target: string) => false
-
let scrollToEnd = (_behavior?: ScrollBehavior) => {}
let page = (_direction: 1 | -1) => {}
@@ -244,28 +244,33 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
cursor.jump(messages[target].id, "auto")
}
- const seekingReveal = () => revealSeekTarget(untrack(() => revealSeek()[0]())) !== undefined
-
- // The reader moved the view or asked to go somewhere else. A call that loads later would take the view from
- // where they went, so the search for it ends. Runs on every scroll the reader makes, so it checks first.
- function endRevealSeek() {
- if (seekingReveal()) dispatchRevealSeek(SEEK_CANCELLED_EVENT)
- }
-
// A gesture inside a nested scrollable region scrolls that region, not the timeline.
const markUserScroll = (target?: EventTarget | null) => {
- const seeking = seekingReveal()
-
- if (!scroller || (!seeking && !hasFreshCursorOrSeek(untrack(cursor.state)))) return
+ if (!scroller || !hasFreshCursorOrSeek(untrack(cursor.state))) return
const element = target instanceof Element ? target : undefined
const nested = element?.closest("[data-scrollable]")
if (nested && nested !== scroller) return
-
- if (seeking) dispatchRevealSeek(SEEK_CANCELLED_EVENT)
cursor.dispatch(SCROLL_MOVED_EVENT)
}
+ // The reader's gesture also ends the search for an older call. It does so here and not inside `markUserScroll`:
+ // every seek ends on its own condition, and two that shared one function were merged onto one condition.
+ const markUserGesture = (target?: EventTarget | null) => {
+ const nested = target instanceof Element ? target.closest("[data-scrollable]") : undefined
+
+ if (scroller && (!nested || nested === scroller)) endRevealSeek()
+ markUserScroll(target)
+ }
+
+ const seekingReveal = () => revealSeekTarget(untrack(() => revealSeek()[0]())) !== undefined
+
+ // The reader moved the view, gave scroll input, or asked to go somewhere else. A call that loads later would take
+ // the view from where they are, so the search for it ends. Runs on every scroll the reader makes, so it checks first.
+ function endRevealSeek() {
+ if (seekingReveal()) dispatchRevealSeek(SEEK_CANCELLED_EVENT)
+ }
+
function dispatchRevealSeek(event: RevealSeekEvent) {
untrack(() => {
const [current, setCurrent] = revealSeek()
@@ -501,7 +506,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
follow,
view: {
anchor,
- markUserScroll,
+ markUserScroll: markUserGesture,
onHistoryScroll,
scheduleScrollState,
contentResized: () => {
diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx
index 146ea86dcaccb..952417f968a0b 100644
--- a/packages/app/src/session/timeline/virtualizer.tsx
+++ b/packages/app/src/session/timeline/virtualizer.tsx
@@ -66,6 +66,12 @@ const pendingMarkdown = '[data-component="markdown"]:not([data-markdown-ready])'
const upwardKeys = new Set(["up", "page-up", "home"])
+const pageKeyOnControl = (event: KeyboardEvent) =>
+ (event.key === "PageUp" || event.key === "PageDown") &&
+ event.target instanceof HTMLElement &&
+ !event.target.isContentEditable &&
+ !["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)
+
const settledEvent = { type: "scroll.settled", atReachableEnd: false } as const
const settledAtEndEvent = { type: "scroll.settled", atReachableEnd: true } as const
@@ -1144,6 +1150,17 @@ export function createTimelineVirtualizer(input: Input) {
input.follow.dispatch(pointerDownEvent)
}
+ // The ScrollView calls this before its scrollbar, or a scroll key, reads the geometry: a press and a drag of the
+ // thumb, the keys it scrolls by, and the ones it leaves to the browser, such as Ctrl+End. All of them are the
+ // reader's scroll input, also at the end of the transcript, where they move nothing. The thumb is portalled out of
+ // the ScrollView root, so its press does not reach `handleListPointerDown`.
+ const prepareReaderNavigation = () => {
+ const root = listRoot()
+
+ if (active() && root) input.onUserScroll(root)
+ prepareNavigation()
+ }
+
// A release only ends a pointer gesture, so every view may report it, including one that went inactive mid-press.
// On touch devices it also fires beside touchend, which owns the touch gesture.
const releasePointer = () => input.follow.dispatch(pointerUpEvent)
@@ -1180,9 +1197,15 @@ export function createTimelineVirtualizer(input: Input) {
if (!key) return
- if (!isScrollKeyTarget(event.target, key)) return
-
if (scrollKeyOwner(event.currentTarget, event.target, key) !== event.currentTarget) return
+
+ if (!isScrollKeyTarget(event.target, key)) {
+ // PageUp and PageDown on a button or a link in a row are left to the browser, which scrolls the timeline
+ // itself. They are the reader's scroll input all the same. A key in a text field is not.
+ if (pageKeyOnControl(event)) input.onUserScroll(event.currentTarget)
+
+ return
+ }
input.onUserScroll(event.currentTarget)
dispatchIntent(upwardKeys.has(key))
}
@@ -1199,12 +1222,14 @@ export function createTimelineVirtualizer(input: Input) {
scrollEvent.maxScroll = maxScroll
scrollEvent.reader = seen.reader
seen.reader = 0
-
- if (scrollEvent.reader !== 0) input.reveal?.readerMoved()
input.follow.dispatch(scrollEvent)
dispatchCold(CHECK_REQUESTED)
input.onScheduleScrollState(root)
input.onHistoryScroll()
+
+ // The reader moved the view, by whatever input. While the cold mount is hidden they see no rows and scroll none,
+ // whatever the offset does.
+ if (scrollEvent.reader !== 0 && !untrack(coldHidden)) input.reveal?.readerMoved()
}
function View(props: ViewProps) {
@@ -1336,7 +1361,7 @@ export function createTimelineVirtualizer(input: Input) {
viewportRef={bindListRoot}
thumbContainer={visibleArea()}
thumbHoverTarget={viewRoot()}
- onBeforeScroll={prepareNavigation}
+ onBeforeScroll={prepareReaderNavigation}
verticalScrollAdjustment={rendering.scrollAdjustment}
onWheel={handleListWheel}
onTouchStart={handleListTouchStart}
@@ -1412,8 +1437,8 @@ export function createTimelineVirtualizer(input: Input) {
dispatchCold(DISPOSED)
if (active()) {
- input.setScrollRef(undefined)
input.reveal?.register(() => false)
+ input.setScrollRef(undefined)
input.setRevealMessage?.(() => {})
input.setScrollToEnd?.(() => {})
input.setPage?.(() => {})
From 03db140ecbb1651770b67ccaf92105bd9ba8a7ce Mon Sep 17 00:00:00 2001
From: Luke Parker <10430890+Hona@users.noreply.github.com>
Date: Wed, 25 Nov 2026 08:32:31 +1000
Subject: [PATCH 6/6] fix(app): bound the search for a call by pages, not by
the order of two IDs
The search for a shell's call ended where the call would be, which it read from the order of a message's ID and the shell's ID as text. IDs do not sort in the transcript's order: a fork copies every message as msg__, which sorts after every shell that ran before the fork. There the search never ended, and a click on the notice of a shell without a call loaded the whole session.
The search now loads at most ten older pages, then stops, and the reader's next click searches ten more. Keepers cover a press on the scrollbar thumb, Ctrl+End and PageDown on a button at the end of the transcript, with an arm that gives no input and opens the call.
---
packages/app/AGENTS.md | 7 +-
.../e2e/regression/timeline-history.spec.ts | 119 ++++++++++++++++--
.../app/src/session/timeline/interaction.ts | 7 +-
.../session/timeline/reveal-machine.test.ts | 34 +++--
.../src/session/timeline/reveal-machine.ts | 52 ++++----
5 files changed, 152 insertions(+), 67 deletions(-)
diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md
index fb8f64aa3919d..7c292b596e29b 100644
--- a/packages/app/AGENTS.md
+++ b/packages/app/AGENTS.md
@@ -129,11 +129,14 @@ This section is the single source for what may move or restyle the session timel
- Keeper: "a focused control that scrolls out of the mounted rows leaves the timeline where it was scrolled" in `e2e/regression/session-timeline-accessibility.spec.ts`.
- To check by hand: click a tool header, a link and a notice in the timeline, then scroll up and down with the wheel. The timeline must follow the wheel.
- A link can name content that is older than the loaded messages, such as the call of a shell whose notice the reader clicks. The timeline pages history toward it and moves once, when it loads (`src/session/timeline/reveal-machine.ts`).
- - Page toward a target only while something says where it can be. A shell's call is older than the shell, and IDs ascend with creation, so the search ends once an assistant message older than the shell is loaded. Without that bound a target that does not exist loads the whole session: a shell that a Code Mode script started has no call, which was the case for 40 of 265 shell notices in four real sessions.
+ - Bound the search by pages, never by an ID. Order is the place in the transcript: IDs do not sort in it (a prompt gets its ID when it is sent, scheduled and automation IDs sort last, a fork's copies are `msg__` and sort after every shell that ran before the fork). The search loads at most ten older pages (`REVEAL_SEEK_PAGES` in `reveal-machine.ts`), then stops; the reader's next click searches ten more. Without a bound a target that does not exist loads the whole session: a shell that a Code Mode script started has no call, which was the case for 40 of 265 shell notices in four real sessions. Where a call exists it was a median 9 messages before its notice, and 672 at the 99th percentile.
- Any movement of the reader ends the search, and so does a request to go somewhere else (Jump to latest, a prompt, a Find hit). A move that lands after the reader has gone elsewhere is one they did not ask for.
- Take the reader's movement from the scroll event (`reader !== 0`, see "Following the end"), not from a list of inputs. The search once ended only on the wheel, a touch, the timeline's own scroll keys and a press. A drag of the scrollbar thumb, Ctrl+End or a page key on a focused button left it running, and the call then took the view 880 to 4,700 px from where the reader had gone.
- The control that asked must not keep focus while history pages. In the New timeline it is a link inside an events row, and a page that lands builds that row again. The focus rescue then focuses the link that takes its place, and the browser scrolls the timeline back to it: the call opened 3,700 px out of view. `revealOrSeekPart` gives focus to the viewport, without scrolling, when the search starts.
- - Keepers in `e2e/regression/timeline-history.spec.ts`: "a shell notice opens its call from an older page, paging back only as far as the call", "a shell's link in the New timeline opens its call from an older page", and "a reader who goes to the end with … while a shell's call is sought is not taken to it" (Ctrl+End, a drag of the scrollbar thumb).
+ - The search also ends on the reader's scroll input that moves nothing. At the end of the transcript Ctrl+End, a press on the scrollbar thumb and PageDown on a button leave the view where it is, so no movement reports them, and the call then took the view 4,719 to 4,787 px. The ScrollView's `onBeforeScroll` reports its scrollbar and its scroll keys, also the ones it leaves to the browser; `handleListKeyDown` reports a page key on a button or link.
+ - A seek ends on its own condition, in its own function. The search for a call and Find's seek both ended inside `markUserScroll`, and a merge put the two on one condition. The search ends in `markUserGesture`, which then calls `markUserScroll`.
+ - A scroll while the cold mount is hidden is not the reader's, whatever the offset does, and does not end the search.
+ - Keepers in `e2e/regression/timeline-history.spec.ts`: "a shell notice opens its call from an older page, paging back only as far as the call", "a shell notice without a call in a forked session loads ten older pages, not the session", "a shell's link in the New timeline opens its call from an older page", and "a reader who … while a shell's call is sought is not taken to it" (goes to the end with Ctrl+End or a drag of the scrollbar thumb; at the end, presses Ctrl+End, the thumb, or PageDown on a button), with "a reader who waits at the end … is taken to it" for the same held page.
### Scroll writes
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index 8f53cc005ede1..c4016b17fa779 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -167,7 +167,8 @@ test.describe("timeline history", () => {
const start = Math.max(0, end - Math.min(16, limit))
oldest = Math.min(oldest, start)
- return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ // A cursor with every page that holds a message, as the server gives it.
+ return { items: messages.slice(start, end), cursor: end > 0 ? messages[start]!.id : undefined }
},
})
@@ -184,6 +185,67 @@ test.describe("timeline history", () => {
expect(oldest).toBeGreaterThan(0)
})
+ // A shell that a Code Mode script started has a notice and no call. Where the call would be was read from the order
+ // of two IDs as text, and IDs do not sort in the transcript's order: a fork copies every message as
+ // `msg__`, which sorts after every shell that ran before the fork. The search then never ended, and
+ // one click on such a notice loaded the whole session.
+ test("a shell notice without a call in a forked session loads ten older pages, not the session", async ({ page }) => {
+ // Every page of 16 begins with a prompt, so no page is asked for to complete a turn.
+ const original: SessionMessageInfo[] = [
+ ...historyMessages(120),
+ userMessage([textPart("prt_fork_prompt", "Start the server")], {
+ id: "msg_00120_serve_a_user",
+ created: 1690001190000,
+ }),
+ {
+ id: "msg_00120_shell_finished",
+ type: "synthetic",
+ text: '\nlistening\n',
+ description: "bun serve.ts",
+ metadata: { source: "shell", shellID: "sh_1e1dbe17b0010Bv53WdPWVw1ic", state: "completed" },
+ time: { created: 1690001200000 },
+ },
+ ]
+
+ // The fork's copies, in the transcript's order. The fork came after the shell, so its event's ID is the higher.
+ const ids = new Map(original.map((message, index) => [message.id, `msg_1e2a41c7d001_${index + 1}`]))
+
+ const messages = original.map(
+ (message): SessionMessageInfo =>
+ message.type === "assistant" && message.parentID
+ ? { ...message, id: ids.get(message.id)!, parentID: ids.get(message.parentID) ?? message.parentID }
+ : { ...message, id: ids.get(message.id)! },
+ )
+
+ const requests: { before?: string; phase: "start" | "end" }[] = []
+ await setupTimeline(page, {
+ sessionMessages: messages,
+ // A cursor with every page that holds a message, as the server gives it.
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+
+ return { items: messages.slice(start, end), cursor: end > 0 ? messages[start]!.id : undefined }
+ },
+ onMessages: (request) => requests.push(request),
+ })
+
+ const older = (phase: "start" | "end") =>
+ requests.filter((request) => request.before && request.phase === phase).length
+
+ const notice = timelineScroller(page).getByRole("button", { name: /^Shell finished/ })
+
+ await expect(notice).toBeInViewport()
+ expect(older("start")).toBe(0)
+ await notice.click()
+ // Fifteen older pages hold messages.
+ await expect.poll(() => older("end")).toBe(10)
+ // Run the frames in which a search that went on would ask for the next page.
+ await page.clock.install()
+ await page.clock.runFor(1_000)
+ expect(older("start")).toBe(10)
+ })
+
// In the New timeline the notice is a link inside an events row, and it keeps focus after the click. An older page
// that lands builds that row again: focus went to the link that took its place, and the browser scrolled the
// timeline back to it, away from the call.
@@ -224,7 +286,8 @@ test.describe("timeline history", () => {
const end = before ? messages.findIndex((message) => message.id === before) : messages.length
const start = Math.max(0, end - Math.min(16, limit))
- return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ // A cursor with every page that holds a message, as the server gives it.
+ return { items: messages.slice(start, end), cursor: end > 0 ? messages[start]!.id : undefined }
},
})
@@ -246,34 +309,59 @@ test.describe("timeline history", () => {
// and a press. A key the browser handles or a drag of the scrollbar thumb left it running, and the call took the
// view from wherever the reader had gone. A press on the thumb that moves nothing, at the end of the transcript,
// left it running too: the thumb is outside the scroll view, so its press was not the timeline's.
- const dragThumb = async (page: Page, distance: number) => {
- const box = await page.locator('.scroll-view__thumb[data-orientation="vertical"]').boundingBox()
+ // A press on the thumb, and a drag when `distance` is not 0. The thumb reports the press itself.
+ const pressThumb = async (page: Page, distance: number) => {
+ const thumb = page.locator('.scroll-view__thumb[data-orientation="vertical"]')
+ const box = await thumb.boundingBox()
if (!box) throw new Error("The timeline has no scrollbar thumb")
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
await page.mouse.down()
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2 + distance, { steps: 8 })
+ await expect(thumb).toHaveAttribute("data-dragging", "true")
+
+ if (distance) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2 + distance, { steps: 8 })
await page.mouse.up()
}
for (const input of [
- { name: "goes to the end with Ctrl+End", reply: true, move: (page: Page) => page.keyboard.press("Control+End") },
+ {
+ name: "goes to the end with Ctrl+End",
+ reply: true,
+ taken: false,
+ move: (page: Page) => page.keyboard.press("Control+End"),
+ },
{
name: "goes to the end with a drag of the scrollbar thumb",
reply: true,
- move: (page: Page) => dragThumb(page, 2_000),
+ taken: false,
+ move: (page: Page) => pressThumb(page, 2_000),
+ },
+ // From here the notice is the last row: the view is at the end already, and no input below moves it.
+ {
+ name: "presses Ctrl+End at the end",
+ reply: false,
+ taken: false,
+ move: (page: Page) => page.keyboard.press("Control+End"),
+ },
+ {
+ name: "presses the scrollbar thumb at the end",
+ reply: false,
+ taken: false,
+ move: (page: Page) => pressThumb(page, 0),
},
- // The notice is the last row, so the view is at the end already and none of these moves it.
- { name: "presses Ctrl+End at the end", reply: false, move: (page: Page) => page.keyboard.press("Control+End") },
- { name: "presses the scrollbar thumb at the end", reply: false, move: (page: Page) => dragThumb(page, 200) },
{
// The browser handles a page key on a button, not the timeline.
name: "presses PageDown on a button at the end",
reply: false,
+ taken: false,
move: (page: Page) => timelineScroller(page).getByRole("button", { name: /^Shell finished/ }).press("PageDown"),
},
+ // The same held page opens the call for a reader who gives no input.
+ { name: "waits at the end", reply: false, taken: true, move: () => Promise.resolve() },
])
- test(`a reader who ${input.name} while a shell's call is sought is not taken to it`, async ({ page }) => {
+ test(`a reader who ${input.name} while a shell's call is sought is ${input.taken ? "" : "not "}taken to it`, async ({
+ page,
+ }) => {
const history = historyMessages(120)
const text = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}.`).join("\n\n")
@@ -326,7 +414,8 @@ test.describe("timeline history", () => {
const end = before ? messages.findIndex((message) => message.id === before) : messages.length
const start = Math.max(0, end - Math.min(16, limit))
- return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ // A cursor with every page that holds a message, as the server gives it.
+ return { items: messages.slice(start, end), cursor: end > 0 ? messages[start]!.id : undefined }
},
beforeMessagesResponse: ({ before }) => (before ? older.promise : Promise.resolve()),
onMessages: (request) => requests.push(request),
@@ -358,6 +447,12 @@ test.describe("timeline history", () => {
older.resolve()
// The page with the call has landed above the reader.
await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
+
+ if (input.taken) {
+ await expect(scroller.locator('[data-timeline-part-id="prt_sought_call"]')).toBeInViewport()
+
+ return
+ }
// Run the frames in which a reveal that was still to come would scroll.
await page.clock.install()
await page.clock.runFor(1_000)
diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts
index 794dceaa15318..c5d3dd0a7e5f8 100644
--- a/packages/app/src/session/timeline/interaction.ts
+++ b/packages/app/src/session/timeline/interaction.ts
@@ -440,11 +440,10 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
const target = revealSeekTarget(revealSeek()[0]())
if (!target || !viewReady()) return
- const oldestAssistantID = timeline.messages().find((message) => message.type === "assistant")?.id
+ // Read so that this runs again when an older page lands.
+ oldestMessage()
const history = historyStatus()
- untrack(() =>
- dispatchRevealSeek({ type: "seek.synced", found: revealPart(target), oldestAssistantID, history }),
- )
+ untrack(() => dispatchRevealSeek({ type: "seek.synced", found: revealPart(target), history }))
})
createResizeObserver(
() => state.refs.dock,
diff --git a/packages/app/src/session/timeline/reveal-machine.test.ts b/packages/app/src/session/timeline/reveal-machine.test.ts
index 9e1ddcb6082b2..fdc9ef76d7fd2 100644
--- a/packages/app/src/session/timeline/reveal-machine.test.ts
+++ b/packages/app/src/session/timeline/reveal-machine.test.ts
@@ -10,23 +10,16 @@ import {
type RevealSeekState,
} from "./reveal-machine"
-// IDs as the server makes them: a prefix, then a part that ascends with creation.
const shell = "sh_1e1dbe17b0010Bv53WdPWVw1ic"
-// The assistant message whose step started the shell, and the one of the step after it.
-const before = "msg_1e1dbb5d70016rDeImJAWn2Q0N"
-
-const after = "msg_1e1dbffc7001uxmmSBrKBNDabs"
-
// A reveal that did not find its call, as the virtualizer reports it.
const requested = (target = shell) => ({ type: "reveal.requested", target, found: false }) as const
// Built the way the driver's effect builds it.
-const synced = (input: { found?: boolean; oldestAssistantID?: string; history?: HistorySeekStatus } = {}) =>
+const synced = (input: { found?: boolean; history?: HistorySeekStatus } = {}) =>
({
type: "seek.synced",
found: input.found ?? false,
- oldestAssistantID: "oldestAssistantID" in input ? input.oldestAssistantID : after,
history: input.history ?? "seekable",
}) satisfies RevealSeekEvent
@@ -55,9 +48,22 @@ test("a shell's call that is not loaded pages history until it is found", () =>
expect(found.effects).toEqual([{ type: "history.seek" }])
})
+// A shell that a Code Mode script started has no call. Where its call would be was read from the order of two IDs,
+// which is not the transcript's order: the search could end before the call, or load the whole session.
+test("a search loads ten older pages and no more, wherever the call is", () => {
+ const pages = Array.from({ length: 13 }, () => synced())
+ const ended = replay([requested(), ...pages])
+
+ expect(revealSeekTarget(ended.state)).toBeUndefined()
+ expect(ended.effects).toHaveLength(10)
+
+ // The reader's next click searches again, from what is loaded by then.
+ const again = replay([requested(), ...pages, requested(), synced()])
+ expect(revealSeekTarget(again.state)).toBe(shell)
+ expect(again.effects).toHaveLength(11)
+})
+
test.each<{ name: string; event: RevealSeekEvent }>([
- // A shell a Code Mode script started has no call: it used to page through the whole session.
- { name: "an assistant message older than the shell is loaded", event: synced({ oldestAssistantID: before }) },
{ name: "history ran out", event: synced({ history: "exhausted" }) },
{ name: "a page failed", event: synced({ history: "failed" }) },
{ name: "the reader scrolled", event: SEEK_CANCELLED_EVENT },
@@ -68,13 +74,6 @@ test.each<{ name: string; event: RevealSeekEvent }>([
expect(ended.effects).toEqual([])
})
-test("a seek waits while no assistant message is loaded", () => {
- const next = replay([requested(), synced({ oldestAssistantID: undefined })])
-
- expect(revealSeekTarget(next.state)).toBe(shell)
- expect(next.effects).toEqual([{ type: "history.seek" }])
-})
-
test("a call named by its own ID does not page history", () => {
expect(revealSeekTarget(replay([requested("toolu_0186aieMGq1P5bArLj3ErJdA")]).state)).toBeUndefined()
})
@@ -96,5 +95,4 @@ test("events that change nothing return the same state", () => {
const seeking = replay([requested()]).state
expect(transitionRevealSeek(seeking, requested()).state).toBe(seeking)
expect(transitionRevealSeek(seeking, synced({ history: "loading" })).state).toBe(seeking)
- expect(transitionRevealSeek(seeking, synced()).state).toBe(seeking)
})
diff --git a/packages/app/src/session/timeline/reveal-machine.ts b/packages/app/src/session/timeline/reveal-machine.ts
index 40fb27f7dfbcd..a5512f72f6f95 100644
--- a/packages/app/src/session/timeline/reveal-machine.ts
+++ b/packages/app/src/session/timeline/reveal-machine.ts
@@ -2,32 +2,34 @@ import type { HistorySeekStatus } from "./history-machine"
const SHELL_PREFIX = "sh_"
-const MESSAGE_PREFIX = "msg_"
+/**
+ * The most older pages one search loads. A shell that a Code Mode script started has a notice but no call, and nothing
+ * in the transcript says where its call would be: an ID does not, because IDs do not sort in the transcript's order.
+ * Without a limit a click on such a notice would load the whole session. In four real sessions a call was a median 9
+ * messages before its notice and 672 at the 99th percentile; ten pages are 200 messages, and the reader's next click
+ * searches ten more.
+ */
+const REVEAL_SEEK_PAGES = 10
/**
* The search for a shell's tool call that is older than the loaded messages. A route or a shell notice asked for it,
- * and history pages toward it until it loads or the loaded messages reach back to where it would be.
+ * and history pages toward it until it loads, history ends, or the search has loaded its share of pages.
*/
export type RevealSeekState =
| { readonly status: "idle" }
- | { readonly status: "seeking"; readonly target: string }
+ | { readonly status: "seeking"; readonly target: string; /** Older pages asked for so far. */ readonly pages: number }
export type RevealSeekEvent =
/** The route or a row asked for `target`. `found`: it is among the loaded messages and now revealed. */
| { readonly type: "reveal.requested"; readonly target: string; readonly found: boolean }
/**
- * The timeline looked again. `found`: the call is loaded and now revealed. Otherwise the oldest loaded assistant
- * message and history paging decide whether an older page can still hold it.
+ * The timeline looked again. `found`: the call is loaded and now revealed. Otherwise history paging decides
+ * whether an older page can still hold it.
*/
- | {
- readonly type: "seek.synced"
- readonly found: boolean
- readonly oldestAssistantID: string | undefined
- readonly history: HistorySeekStatus
- }
+ | { readonly type: "seek.synced"; readonly found: boolean; readonly history: HistorySeekStatus }
/**
- * The reader moved the view by any input, pressed in the timeline, or asked to go somewhere else. A call found
- * later would take the view from where they went.
+ * The reader moved the view, gave scroll input, pressed in the timeline, or asked to go somewhere else. A call found
+ * later would take the view from where they are.
*/
| { readonly type: "seek.cancelled" }
@@ -55,26 +57,24 @@ export function createRevealSeekState(): RevealSeekState {
export function transitionRevealSeek(state: RevealSeekState, event: RevealSeekEvent): RevealSeekTransition {
if (event.type === "reveal.requested") {
// A found call ends a seek for another one. A call named by its own ID is looked for among the loaded messages
- // only: nothing says how far back it is, so one that does not exist would page through the whole session.
+ // only: no code path asks for one that is not loaded.
if (event.found || !event.target.startsWith(SHELL_PREFIX)) return settled(IDLE)
if (state.status === "seeking" && state.target === event.target) return settled(state)
- return settled({ status: "seeking", target: event.target })
+ return settled({ status: "seeking", target: event.target, pages: 0 })
}
if (state.status === "idle") return settled(state)
if (event.type === "seek.cancelled" || event.found) return settled(IDLE)
- if (reachesShell(event.oldestAssistantID, state.target)) return settled(IDLE)
-
- if (event.history === "seekable") return { state, effects: HISTORY_SEEK }
-
if (event.history === "loading") return settled(state)
- // History ran out or a page failed, so the call cannot load.
- return settled(IDLE)
+ // History ran out or a page failed, so the call cannot load; or this search has loaded its share.
+ if (event.history !== "seekable" || state.pages >= REVEAL_SEEK_PAGES) return settled(IDLE)
+
+ return { state: { status: "seeking", target: state.target, pages: state.pages + 1 }, effects: HISTORY_SEEK }
}
/** The call history pages toward, while one is sought. */
@@ -82,16 +82,6 @@ export function revealSeekTarget(state: RevealSeekState) {
return state.status === "seeking" ? state.target : undefined
}
-// A shell's call runs in the newest assistant message created before the shell, and IDs ascend with creation. Once an
-// assistant message older than the shell is loaded, the call is among the loaded messages or does not exist, as for
-// a shell that a Code Mode script started.
-function reachesShell(oldestAssistantID: string | undefined, shellID: string) {
- return (
- oldestAssistantID !== undefined &&
- oldestAssistantID.slice(MESSAGE_PREFIX.length) < shellID.slice(SHELL_PREFIX.length)
- )
-}
-
function settled(state: RevealSeekState): RevealSeekTransition {
return { state, effects: NO_EFFECTS }
}