diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 4114409153796..7c292b596e29b 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -128,6 +128,15 @@ 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`). + - 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. + - 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 b572e2bfa2df5..c4016b17fa779 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,339 @@ 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) + + // 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 } + }, + }) + + 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) + }) + + // 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. + 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)) + + // 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 } + }, + }) + + 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. 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. + // 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 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, + taken: false, + move: (page: Page) => page.keyboard.press("Control+End"), + }, + { + name: "goes to the end with a drag of the scrollbar thumb", + reply: true, + 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 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 ${input.taken ? "" : "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 or as its last row. 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 }, + }, + ...(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() + 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 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), + }) + + const scroller = timelineScroller(page) + const notice = scroller.getByRole("button", { name: /^Shell finished/ }) + const end = input.reply ? scroller.getByText("Paragraph 39.", { exact: true }) : notice + + // 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() + + 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) + + 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) + + 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) + 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" 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..c5d3dd0a7e5f8 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,6 +72,16 @@ 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()) + }) + // 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) => {} @@ -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), @@ -181,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 @@ -216,6 +240,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: return } + endRevealSeek() cursor.jump(messages[target].id, "auto") } @@ -229,6 +254,33 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: 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() + 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 +434,17 @@ 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 + // Read so that this runs again when an older page lands. + oldestMessage() + const history = historyStatus() + untrack(() => dispatchRevealSeek({ type: "seek.synced", found: revealPart(target), history })) + }) createResizeObserver( () => state.refs.dock, (_rect, _element, entry) => { @@ -417,10 +480,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) }, @@ -438,7 +505,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible: follow, view: { anchor, - markUserScroll, + markUserScroll: markUserGesture, onHistoryScroll, scheduleScrollState, contentResized: () => { @@ -454,11 +521,18 @@ 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 + }, + readerMoved: endRevealSeek, }, 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..fdc9ef76d7fd2 --- /dev/null +++ b/packages/app/src/session/timeline/reveal-machine.test.ts @@ -0,0 +1,98 @@ +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" + +const shell = "sh_1e1dbe17b0010Bv53WdPWVw1ic" + +// 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; history?: HistorySeekStatus } = {}) => + ({ + type: "seek.synced", + found: input.found ?? false, + 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" }]) +}) + +// 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 }>([ + { 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 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) +}) 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..a5512f72f6f95 --- /dev/null +++ b/packages/app/src/session/timeline/reveal-machine.ts @@ -0,0 +1,87 @@ +import type { HistorySeekStatus } from "./history-machine" + +const SHELL_PREFIX = "sh_" + +/** + * 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, history ends, or the search has loaded its share of pages. + */ +export type RevealSeekState = + | { readonly status: "idle" } + | { 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 history paging decides + * whether an older page can still hold it. + */ + | { readonly type: "seek.synced"; readonly found: boolean; readonly history: HistorySeekStatus } + /** + * 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" } + +/** 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, 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" }) + +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: 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, pages: 0 }) + } + + if (state.status === "idle") return settled(state) + + if (event.type === "seek.cancelled" || event.found) return settled(IDLE) + + if (event.history === "loading") return settled(state) + + // 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. */ +export function revealSeekTarget(state: RevealSeekState) { + return state.status === "seeking" ? state.target : undefined +} + +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..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 @@ -132,13 +138,21 @@ 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 + /** 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 = { @@ -611,6 +625,20 @@ 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) + 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) + + 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 +735,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 +744,7 @@ export function createTimelineVirtualizer(input: Input) { reportOffset?.(root.scrollTop, false) dispatchCold(CHECK_REQUESTED) }) + input.reveal?.register(revealPart) input.setRevealMessage?.((id, partID) => { if (!active()) return @@ -1121,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) @@ -1157,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)) } @@ -1180,6 +1226,10 @@ export function createTimelineVirtualizer(input: Input) { 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) { @@ -1311,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} @@ -1387,6 +1437,7 @@ export function createTimelineVirtualizer(input: Input) { dispatchCold(DISPOSED) if (active()) { + input.reveal?.register(() => false) input.setScrollRef(undefined) input.setRevealMessage?.(() => {}) input.setScrollToEnd?.(() => {}) @@ -1404,7 +1455,7 @@ export function createTimelineVirtualizer(input: Input) { setToolOpen(key, open) }, }, - revealPart, + revealPart: revealOrSeekPart, View, } }