fix(app): drive the active message cursor with an explicit state machine (#61848)

This commit is contained in:
Luke Parker
2026-11-04 20:31:56 -06:00
committed by GitHub
Unverified
parent e38c009a90
commit 1e4ad07511
8 changed files with 749 additions and 361 deletions
@@ -502,6 +502,34 @@ test.describe("timeline history", () => {
await expect(editor).toBeFocused()
await expect(editor).toHaveText("keep this draft")
})
test("a message hash and message navigation keep the prompt in view and the hash in step", async ({ page }) => {
const messages = validateTimelineMessages([
...historyMessages(20),
userMessage(),
assistantMessage([textPart("prt_cursor_tail", "Latest answer")]),
])
const prompt = (index: number) => messages.filter((message) => message.type === "user")[index]!.id
const row = (index: number) => page.locator(`[data-timeline-row="UserMessage"][data-message-id="${prompt(index)}"]`)
const hash = () => page.evaluate(() => location.hash)
await setupTimeline(page, { sessionMessages: messages })
await expect(page.getByText("Latest answer", { exact: true })).toBeInViewport()
await page.evaluate((id) => (location.hash = `#message-${id}`), prompt(10))
await expect(row(10)).toBeInViewport()
await page.keyboard.press("Control+Alt+BracketLeft")
await expect.poll(hash).toBe(`#message-${prompt(9)}`)
await expect(row(9)).toBeInViewport()
await page.keyboard.press("Control+Alt+BracketRight")
await expect.poll(hash).toBe(`#message-${prompt(10)}`)
await expect(row(10)).toBeInViewport()
await page.getByRole("button", { name: "Jump to latest" }).click()
await expect.poll(hash).toBe("")
await expect(page.getByText("Latest answer", { exact: true })).toBeInViewport()
})
})
declare global {
@@ -0,0 +1,201 @@
import { describe, expect, test } from "bun:test"
import { messageIdFromHash } from "../message-id-from-hash"
import {
CLEAR_CURSOR_EVENT,
createTimelineCursorState,
CURSOR_SEEK_LIMIT,
cursorMessageID,
DISPOSED_CURSOR_EVENT,
freshCursorMessageID,
hasFreshCursorOrSeek,
LATEST_ADVANCED_EVENT,
pendingCursorMessageID,
SCROLL_MOVED_EVENT,
SESSION_CHANGED_EVENT,
transitionTimelineCursor,
type TimelineCursorEvent,
type TimelineCursorState,
} from "./cursor-machine"
const jump = (messageID: string): TimelineCursorEvent => ({ type: "message.jump", messageID, behavior: "auto" })
// Built the way the driver builds it from `location.hash`.
const hash = (value: string, initial = false, reveal = false): TimelineCursorEvent => ({
type: "hash.applied",
hash: value.slice(1),
messageID: messageIdFromHash(value.slice(1)),
initial,
reveal,
})
function replay(events: TimelineCursorEvent[], from = createTimelineCursorState()) {
return events.reduce((state, event) => transitionTimelineCursor(state, event).state, from)
}
function expectIgnored(state: TimelineCursorState, event: TimelineCursorEvent) {
const next = transitionTimelineCursor(state, event)
expect(next.state).toBe(state)
expect(next.effects).toEqual([])
}
const landed = (state: TimelineCursorState) => replay([{ type: "seek.landed", attempt: state.attempt }], state)
describe("cursor machine", () => {
test("jumping back to the same prompt after scrolling away makes it fresh again", () => {
const scrolled = replay([jump("msg_5"), SCROLL_MOVED_EVENT])
expect(freshCursorMessageID(scrolled)).toBeUndefined()
expect(cursorMessageID(scrolled)).toBe("msg_5")
const again = transitionTimelineCursor(scrolled, jump("msg_5"))
expect(freshCursorMessageID(again.state)).toBe("msg_5")
expect(again.effects).toEqual([
{ type: "follow.detach" },
{ type: "hash.set", messageID: "msg_5" },
{ type: "seek.start", attempt: again.state.attempt, messageID: "msg_5", behavior: "auto" },
])
})
test("a Find or tool reveal makes the cursor stale and cancels its seek", () => {
const seeking = replay([jump("msg_10")])
const moved = transitionTimelineCursor(seeking, SCROLL_MOVED_EVENT)
expect(moved.state).toEqual({
status: "selected",
messageID: "msg_10",
fresh: false,
attempt: seeking.attempt + 1,
echo: true,
})
expect(moved.effects).toEqual([{ type: "seek.cancel" }])
expectIgnored(moved.state, { type: "seek.missing", attempt: seeking.attempt })
expectIgnored(moved.state, { type: "seek.landed", attempt: seeking.attempt })
})
test("undo or redo while pinned does not leave a cursor behind", () => {
expectIgnored(createTimelineCursorState(), { type: "message.select", messageID: "msg_2", following: true })
const selected = replay([{ type: "message.select", messageID: "msg_2", following: false }])
expect(freshCursorMessageID(selected)).toBe("msg_2")
expect(replay([{ type: "message.select", messageID: "msg_3", following: true }], selected).status).toBe("none")
})
test("clearing its own hash does not scroll again, while Browser Back off a prompt returns to the end", () => {
const selected = landed(replay([jump("msg_5")]))
const cleared = transitionTimelineCursor(selected, CLEAR_CURSOR_EVENT)
expect(cleared.state.status).toBe("none")
expect(cleared.effects).toEqual([{ type: "hash.clear" }])
// The router echoes the cleared hash; a smooth return to the end must keep its course.
expectIgnored(cleared.state, hash(""))
const back = transitionTimelineCursor(selected, hash(""))
expect(back.state.status).toBe("none")
expect(back.effects).toEqual([{ type: "follow.end" }])
})
test("the router's echo of the cursor's own hash does not seek again, once", () => {
const seeking = replay([jump("msg_5")])
for (const state of [seeking, replay([SCROLL_MOVED_EVENT], seeking)]) {
const echoed = transitionTimelineCursor(state, hash("#message-msg_5"))
expect(echoed.state).toMatchObject({ status: "selected", messageID: "msg_5", echo: false })
expect(echoed.state.attempt).toBe(state.attempt)
expect(echoed.effects).toEqual([])
// Only the write echoes; the same hash applied again is a real navigation.
expect(transitionTimelineCursor(echoed.state, hash("#message-msg_5")).state.status).toBe("pending")
}
})
test("a link to the prompt undo, redo or rewind selected still navigates to it", () => {
const undone = replay([{ type: "message.select", messageID: "msg_3", following: false }])
const linked = transitionTimelineCursor(undone, hash("#message-msg_3"))
expect(pendingCursorMessageID(linked.state)).toBe("msg_3")
expect(linked.effects).toEqual([{ type: "follow.detach" }])
const loaded = transitionTimelineCursor(linked.state, { type: "target.loaded", messageID: "msg_3" })
expect(loaded.effects).toEqual([
{ type: "follow.detach" },
{ type: "seek.schedule", attempt: loaded.state.attempt, messageID: "msg_3", behavior: "auto" },
])
})
test("a hash target waits until its prompt loads, then seeks to it", () => {
const pending = transitionTimelineCursor(createTimelineCursorState(), hash("#message-msg_1", true))
expect(pendingCursorMessageID(pending.state)).toBe("msg_1")
expect(pending.effects).toEqual([{ type: "follow.detach" }])
expectIgnored(pending.state, { type: "target.loaded", messageID: "msg_2" })
const loaded = transitionTimelineCursor(pending.state, { type: "target.loaded", messageID: "msg_1" })
expect(freshCursorMessageID(loaded.state)).toBe("msg_1")
expect(loaded.effects).toEqual([
{ type: "follow.detach" },
{ type: "seek.schedule", attempt: loaded.state.attempt, messageID: "msg_1", behavior: "auto" },
])
})
test("a session switch drops the previous session's target and seek", () => {
const pending = replay([hash("#message-msg_a", true)])
expect(replay([SESSION_CHANGED_EVENT], pending)).toEqual({ status: "none", attempt: pending.attempt + 1 })
const seeking = replay([jump("msg_a")])
const switched = transitionTimelineCursor(seeking, SESSION_CHANGED_EVENT)
expect(switched.effects).toEqual([{ type: "seek.cancel" }])
expectIgnored(switched.state, { type: "seek.missing", attempt: seeking.attempt })
})
test("a seek retries for a bounded number of frames", () => {
const seeking = replay([jump("msg_5")])
const missing: TimelineCursorEvent = { type: "seek.missing", attempt: seeking.attempt }
const retried = Array.from({ length: CURSOR_SEEK_LIMIT }).reduce<TimelineCursorState>((state) => {
const next = transitionTimelineCursor(state, missing)
expect(next.effects).toEqual([
{ type: "seek.schedule", attempt: seeking.attempt, messageID: "msg_5", behavior: "auto" },
])
return next.state
}, seeking)
const settled = transitionTimelineCursor(retried, missing)
expect(settled.state).toEqual({
status: "selected",
messageID: "msg_5",
fresh: true,
attempt: seeking.attempt,
echo: true,
})
expect(settled.effects).toEqual([])
expect(hasFreshCursorOrSeek(settled.state)).toBe(true)
expect(landed(seeking)).toEqual(settled.state)
})
test("the first apply of an empty hash goes to the end unless the route reveals a tool", () => {
expect(transitionTimelineCursor(createTimelineCursorState(), hash("", true)).effects).toEqual([
{ type: "follow.end" },
])
expectIgnored(createTimelineCursorState(), hash("", true, true))
expect(transitionTimelineCursor(createTimelineCursorState(), hash("#section")).effects).toEqual([
{ type: "anchor.scroll", id: "section" },
])
})
test("a newer prompt clears the selection but keeps a pending target", () => {
expect(replay([jump("msg_1"), LATEST_ADVANCED_EVENT]).status).toBe("none")
expectIgnored(replay([hash("#message-msg_1")]), LATEST_ADVANCED_EVENT)
})
test("steady scrolling and disposal of an idle cursor keep the same state", () => {
const stale = replay([jump("msg_1"), SCROLL_MOVED_EVENT])
expectIgnored(createTimelineCursorState(), SCROLL_MOVED_EVENT)
expectIgnored(stale, SCROLL_MOVED_EVENT)
expectIgnored(createTimelineCursorState(), DISPOSED_CURSOR_EVENT)
expect(transitionTimelineCursor(replay([jump("msg_1")]), DISPOSED_CURSOR_EVENT).effects).toEqual([
{ type: "seek.cancel" },
])
})
})
@@ -0,0 +1,269 @@
// Frames a seek waits for the target prompt's virtualized row to mount.
export const CURSOR_SEEK_LIMIT = 4
export type CursorSeek = {
readonly behavior: ScrollBehavior
readonly retries: number
}
// `attempt` advances on every change of target or seek, so a seek result from an earlier one is ignored.
export type TimelineCursorState =
| { readonly status: "none"; readonly attempt: number }
/** A `#message-<id>` target that is not loaded yet; history pages toward it. */
| { readonly status: "pending"; readonly messageID: string; readonly attempt: number }
/**
* The active prompt. `fresh` until the reader scrolls, after which navigation steps from the prompt in view instead.
* `seek` while the view is still bringing the prompt in. `echo` after a jump wrote the prompt's hash, until the router
* repeats it once; any other `#message-<id>` for the prompt is a real navigation.
*/
| {
readonly status: "selected"
readonly messageID: string
readonly fresh: boolean
readonly attempt: number
readonly seek?: CursorSeek
readonly echo?: boolean
}
export type TimelineCursorEvent =
| { readonly type: "session.changed" }
/**
* The route hash, applied once the session's messages are ready (`initial`) and on every later change. `messageID` is
* the `#message-<id>` target. `reveal`: the route opens the session on a tool call instead.
*/
| {
readonly type: "hash.applied"
readonly hash: string
readonly messageID: string | undefined
readonly initial: boolean
readonly reveal: boolean
}
| { readonly type: "target.loaded"; readonly messageID: string }
/** Previous or next message. */
| { readonly type: "message.jump"; readonly messageID: string; readonly behavior: ScrollBehavior }
/** Undo, redo and rewind name the prompt navigation continues from. */
| { readonly type: "message.select"; readonly messageID: string | undefined; readonly following: boolean }
/** The reader scrolled the timeline, or Find or a tool reveal moved it. */
| { readonly type: "scroll.moved" }
/** Following resumed, or the reader jumped to the latest message. */
| { readonly type: "clear" }
| { readonly type: "latest.advanced" }
| { readonly type: "seek.landed"; readonly attempt: number }
| { readonly type: "seek.missing"; readonly attempt: number }
| { readonly type: "disposed" }
export type TimelineCursorEffect =
| { readonly type: "follow.detach" }
/** Follow the newest content again and scroll to it. */
| { readonly type: "follow.end" }
| { readonly type: "hash.set"; readonly messageID: string }
| { readonly type: "hash.clear" }
/** Scroll to the element a non-message hash names, or to the end when there is none. */
| { readonly type: "anchor.scroll"; readonly id: string }
/** Scroll now: a smooth jump glides to a mounted prompt, any other first asks the virtualizer to reveal it. */
| {
readonly type: "seek.start"
readonly attempt: number
readonly messageID: string
readonly behavior: ScrollBehavior
}
| {
readonly type: "seek.schedule"
readonly attempt: number
readonly messageID: string
readonly behavior: ScrollBehavior
}
| { readonly type: "seek.cancel" }
export type TimelineCursorTransition = {
readonly state: TimelineCursorState
readonly effects: readonly TimelineCursorEffect[]
}
type Selected = Extract<TimelineCursorState, { readonly status: "selected" }>
// Shared events for the frequent dispatches, so scrolling allocates nothing.
export const SCROLL_MOVED_EVENT: TimelineCursorEvent = Object.freeze({ type: "scroll.moved" })
export const CLEAR_CURSOR_EVENT: TimelineCursorEvent = Object.freeze({ type: "clear" })
export const LATEST_ADVANCED_EVENT: TimelineCursorEvent = Object.freeze({ type: "latest.advanced" })
export const SESSION_CHANGED_EVENT: TimelineCursorEvent = Object.freeze({ type: "session.changed" })
export const DISPOSED_CURSOR_EVENT: TimelineCursorEvent = Object.freeze({ type: "disposed" })
const NO_EFFECTS: readonly TimelineCursorEffect[] = Object.freeze([])
const SEEK_CANCEL: readonly TimelineCursorEffect[] = Object.freeze([{ type: "seek.cancel" }])
const FOLLOW_END: TimelineCursorEffect = Object.freeze({ type: "follow.end" })
const FOLLOW_DETACH: TimelineCursorEffect = Object.freeze({ type: "follow.detach" })
const HASH_CLEAR: TimelineCursorEffect = Object.freeze({ type: "hash.clear" })
export function createTimelineCursorState(): TimelineCursorState {
return { status: "none", attempt: 0 }
}
export function transitionTimelineCursor(
state: TimelineCursorState,
event: TimelineCursorEvent,
): TimelineCursorTransition {
if (event.type === "session.changed" || event.type === "disposed") return clear(state)
if (event.type === "hash.applied") return hashApplied(state, event)
if (event.type === "target.loaded") {
if (state.status !== "pending" || state.messageID !== event.messageID) return unchanged(state)
// The route already carries this hash, so nothing echoes.
return seek(state, event.messageID, "auto", [FOLLOW_DETACH], { now: false, echo: false })
}
if (event.type === "message.jump")
return seek(
state,
event.messageID,
event.behavior,
[...cancelSeek(state), FOLLOW_DETACH, { type: "hash.set", messageID: event.messageID }],
{ now: true, echo: true },
)
if (event.type === "message.select") {
// A pinned view shows the newest prompt; a remembered one would only send navigation elsewhere.
if (!event.messageID || event.following) return clear(state)
if (state.status === "selected" && state.messageID === event.messageID && state.fresh && !state.seek)
return unchanged(state)
return changed(
{ status: "selected", messageID: event.messageID, fresh: true, attempt: state.attempt + 1 },
cancelSeek(state),
)
}
if (event.type === "scroll.moved") {
if (state.status !== "selected" || !hasFreshCursorOrSeek(state)) return unchanged(state)
return changed(
{ status: "selected", messageID: state.messageID, fresh: false, attempt: state.attempt + 1, echo: state.echo },
cancelSeek(state),
)
}
if (event.type === "clear") {
const next = clear(state)
return changed(next.state, [...next.effects, HASH_CLEAR])
}
if (event.type === "latest.advanced") return state.status === "selected" ? clear(state) : unchanged(state)
if (state.status !== "selected" || !state.seek || state.attempt !== event.attempt) return unchanged(state)
if (event.type === "seek.landed" || state.seek.retries >= CURSOR_SEEK_LIMIT) return changed(settled(state))
return changed({ ...state, seek: { behavior: state.seek.behavior, retries: state.seek.retries + 1 } }, [
{ type: "seek.schedule", attempt: state.attempt, messageID: state.messageID, behavior: state.seek.behavior },
])
}
/** The prompt navigation steps from, while the reader has not scrolled since choosing it. */
export function freshCursorMessageID(state: TimelineCursorState) {
return state.status === "selected" && state.fresh ? state.messageID : undefined
}
/** The last chosen prompt, for when no prompt header is mounted in view. */
export function cursorMessageID(state: TimelineCursorState) {
return state.status === "selected" ? state.messageID : undefined
}
/** A target history pages toward until it loads. */
export function pendingCursorMessageID(state: TimelineCursorState) {
return state.status === "pending" ? state.messageID : undefined
}
/** Only a fresh cursor or a running seek cares about the reader's scroll, so steady scrolling skips the rest. */
export function hasFreshCursorOrSeek(state: TimelineCursorState) {
return state.status === "selected" && (state.fresh || !!state.seek)
}
function hashApplied(
state: TimelineCursorState,
event: Extract<TimelineCursorEvent, { type: "hash.applied" }>,
): TimelineCursorTransition {
if (event.messageID) {
// The hash this cursor wrote, repeated by the router: consumed once, so a later link to the prompt still navigates.
if (state.status === "selected" && state.echo && state.messageID === event.messageID)
return changed({ ...state, echo: false })
if (state.status === "pending" && state.messageID === event.messageID) return unchanged(state)
return changed({ status: "pending", messageID: event.messageID, attempt: state.attempt + 1 }, [
...cancelSeek(state),
FOLLOW_DETACH,
])
}
if (event.hash) {
const next = clear(state)
return changed(next.state, [...next.effects, { type: "anchor.scroll", id: event.hash }])
}
// A hash this cursor cleared itself leaves it at `none`, so the echo does not undo a smooth return to the end.
if (state.status === "none" && !event.initial) return unchanged(state)
const next = clear(state)
if (event.reveal) return next
return changed(next.state, [...next.effects, FOLLOW_END])
}
function seek(
state: TimelineCursorState,
messageID: string,
behavior: ScrollBehavior,
effects: readonly TimelineCursorEffect[],
options: { now: boolean; echo: boolean },
): TimelineCursorTransition {
const attempt = state.attempt + 1
return changed(
{ status: "selected", messageID, fresh: true, attempt, seek: { behavior, retries: 0 }, echo: options.echo },
[...effects, { type: options.now ? "seek.start" : "seek.schedule", attempt, messageID, behavior }],
)
}
function settled(state: Selected): TimelineCursorState {
return {
status: "selected",
messageID: state.messageID,
fresh: state.fresh,
attempt: state.attempt,
echo: state.echo,
}
}
function clear(state: TimelineCursorState): TimelineCursorTransition {
if (state.status === "none") return unchanged(state)
return changed({ status: "none", attempt: state.attempt + 1 }, cancelSeek(state))
}
function cancelSeek(state: TimelineCursorState) {
return state.status === "selected" && state.seek ? SEEK_CANCEL : NO_EFFECTS
}
function changed(
state: TimelineCursorState,
effects: readonly TimelineCursorEffect[] = NO_EFFECTS,
): TimelineCursorTransition {
return { state, effects }
}
function unchanged(state: TimelineCursorState): TimelineCursorTransition {
return { state, effects: NO_EFFECTS }
}
+202
View File
@@ -0,0 +1,202 @@
import type { SessionMessageUser } from "@opencode/client/promise"
import { useLocation, useNavigate } from "@solidjs/router"
import { createEffect, createSignal, on, onCleanup, onMount, untrack, type Accessor } from "solid-js"
import { messageIdFromHash } from "../message-id-from-hash"
import {
CLEAR_CURSOR_EVENT,
createTimelineCursorState,
DISPOSED_CURSOR_EVENT,
LATEST_ADVANCED_EVENT,
pendingCursorMessageID,
SESSION_CHANGED_EVENT,
transitionTimelineCursor,
type TimelineCursorEffect,
type TimelineCursorEvent,
} from "./cursor-machine"
/** The active prompt, the route's `#message-<id>` target, and the scroll that brings either into view. */
export function createTimelineCursor(input: {
sessionKey: Accessor<string>
sessionID: Accessor<string | undefined>
ready: Accessor<boolean>
following: Accessor<boolean>
visibleUserMessages: Accessor<SessionMessageUser[]>
scroller: () => HTMLDivElement | undefined
anchor: (id: string) => string
revealMessage: (id: string) => void
detach: () => void
toEnd: () => void
/** Whether history can page toward a pending target now; read tracked, so paging resumes after each page. */
historySeekable: Accessor<boolean>
seekHistory: () => void
}) {
const location = useLocation<{ reveal?: string }>()
const navigate = useNavigate()
const [cursorState, setCursorState] = createSignal(createTimelineCursorState())
let seekFrame: number | undefined
let applyFrame: { id: number; initial: boolean } | undefined
function dispatch(event: TimelineCursorEvent) {
untrack(() => {
const current = cursorState()
const next = transitionTimelineCursor(current, event)
if (next.state !== current) setCursorState(next.state)
next.effects.forEach(run)
})
}
function run(effect: TimelineCursorEffect) {
if (effect.type === "follow.detach") return input.detach()
if (effect.type === "follow.end") return input.toEnd()
if (effect.type === "hash.set") {
const hash = `#${input.anchor(effect.messageID)}`
if (location.hash !== hash) navigate(location.pathname + location.search + hash, { replace: true })
return
}
if (effect.type === "hash.clear") {
if (location.hash) navigate(location.pathname + location.search, { replace: true })
return
}
if (effect.type === "anchor.scroll") {
const target = document.getElementById(effect.id)
if (!target) return input.toEnd()
input.detach()
scrollToElement(target, "auto")
return
}
cancelSeek()
if (effect.type === "seek.cancel") return
if (effect.type === "seek.start") return dispatch(probe(effect, effect.behavior === "smooth"))
seekFrame = requestAnimationFrame(() => {
seekFrame = undefined
dispatch(probe(effect, false))
})
}
// A mounted prompt is close enough to glide to; any other is first brought in by the virtualizer.
function probe(
effect: { attempt: number; messageID: string; behavior: ScrollBehavior },
glide: boolean,
): TimelineCursorEvent {
const mounted = glide ? document.getElementById(input.anchor(effect.messageID)) : null
if (!mounted) input.revealMessage(effect.messageID)
const element = mounted ?? document.getElementById(input.anchor(effect.messageID))
if (!element || !scrollToElement(element, effect.behavior)) return { type: "seek.missing", attempt: effect.attempt }
return { type: "seek.landed", attempt: effect.attempt }
}
function scrollToElement(element: HTMLElement, behavior: ScrollBehavior) {
const root = input.scroller()
if (!root) return false
const sticky = root.querySelector("[data-session-title]")
const inset = sticky instanceof HTMLElement ? sticky.offsetHeight : 0
const top = element.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop - inset
root.scrollTo({ top: Math.max(0, top), behavior })
return true
}
function cancelSeek() {
if (seekFrame !== undefined) cancelAnimationFrame(seekFrame)
seekFrame = undefined
}
// Applies the hash a frame later, once the virtualizer has registered its navigation. A session switch that also
// changes the hash stays an initial apply.
function scheduleApply(initial: boolean) {
const merged = initial || (applyFrame?.initial ?? false)
if (applyFrame) cancelAnimationFrame(applyFrame.id)
applyFrame = {
initial: merged,
id: requestAnimationFrame(() => {
applyFrame = undefined
const hash = location.hash.slice(1)
dispatch({
type: "hash.applied",
hash,
messageID: messageIdFromHash(hash),
initial: merged,
reveal: !!location.state?.reveal,
})
}),
}
}
// Runs first on a session switch, so nothing below sees the previous session's cursor.
createEffect(on(input.sessionKey, () => dispatch(SESSION_CHANGED_EVENT), { defer: true }))
createEffect(
on(
() => (input.sessionID() && input.ready() ? input.sessionKey() : undefined),
(key) => {
if (key) scheduleApply(true)
},
),
)
createEffect(
on(
() => location.hash,
() => {
if (untrack(input.sessionID) && untrack(input.ready)) scheduleApply(false)
},
{ defer: true },
),
)
createEffect(() => {
const id = pendingCursorMessageID(cursorState())
if (!id || !input.sessionID() || !input.ready()) return
if (input.visibleUserMessages().some((message) => message.id === id))
return dispatch({ type: "target.loaded", messageID: id })
if (input.historySeekable()) input.seekHistory()
})
createEffect(
on(
() => input.visibleUserMessages().at(-1)?.id,
(lastID, previousID) => {
if (lastID && previousID && lastID > previousID) dispatch(LATEST_ADVANCED_EVENT)
},
{ defer: true },
),
)
createEffect(
on(
input.following,
(following) => {
if (following) dispatch(CLEAR_CURSOR_EVENT)
},
{ defer: true },
),
)
onMount(() => {
if ("scrollRestoration" in window.history) window.history.scrollRestoration = "manual"
})
onCleanup(() => {
if (applyFrame) cancelAnimationFrame(applyFrame.id)
dispatch(DISPOSED_CURSOR_EVENT)
})
return { state: cursorState, dispatch }
}
@@ -4,9 +4,15 @@ import { useLocation } from "@solidjs/router"
import { createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js"
import { createStore } from "solid-js/store"
import { frameLoop } from "@opencode/ui/motion"
import { useLayout } from "@/shell/state/layout"
import type { SessionModel } from "../model"
import { useSessionHashScroll } from "../use-session-hash-scroll"
import { createTimelineCursor } from "./cursor"
import {
CLEAR_CURSOR_EVENT,
cursorMessageID,
freshCursorMessageID,
hasFreshCursorOrSeek,
SCROLL_MOVED_EVENT,
} from "./cursor-machine"
import { createTimelineFollow } from "./follow"
import {
canRequestFillProbe,
@@ -27,13 +33,10 @@ import {
import { createTimelineModel } from "./model"
export function createSessionTimelineInteraction(session: SessionModel) {
const layout = useLayout()
const location = useLocation<{ reveal?: string }>()
const timeline = createTimelineModel({ session })
const [state, setState] = createStore<{
messageID: string | undefined
pendingMessage: string | undefined
scroll: { overflow: boolean; jump: boolean }
/** The composer region's height; the timeline scrolls on underneath it and fades out at its top. */
inset: number
@@ -43,8 +46,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
visible: HTMLDivElement | undefined
}
}>({
messageID: undefined,
pendingMessage: undefined,
scroll: {
overflow: false,
jump: false,
@@ -75,8 +76,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
let page = (_direction: 1 | -1) => {}
let scrollMark = 0
let messageMark = 0
let scrollStateFrame: (() => void) | undefined
let scrollStateTarget: HTMLDivElement | undefined
const [historyState, setHistoryState] = createSignal(createTimelineHistoryState())
@@ -88,8 +87,9 @@ export function createSessionTimelineInteraction(session: SessionModel) {
const visibleUserMessages = timeline.visibleUserMessages
const anchor = (id: string) => `message-${id}`
const cursor = () => {
if (!scroller) return state.messageID
// The prompt at the top of the view, or the last chosen one when no prompt header is mounted there.
const promptInView = () => {
if (!scroller) return cursorMessageID(untrack(cursor.state))
const box = scroller.getBoundingClientRect()
const line = box.top + 100
@@ -118,13 +118,11 @@ export function createSessionTimelineInteraction(session: SessionModel) {
if (near) return near.id
return list.filter((item) => item.top <= line).at(-1)?.id ?? list[0]?.id ?? state.messageID
return list.filter((item) => item.top <= line).at(-1)?.id ?? list[0]?.id ?? cursorMessageID(untrack(cursor.state))
}
const setActiveMessage = (message: SessionMessageUser | undefined) => {
messageMark = scrollMark
setState("messageID", message?.id)
}
const setActiveMessage = (message: SessionMessageUser | undefined) =>
cursor.dispatch({ type: "message.select", messageID: message?.id, following: untrack(follow.following) })
const jumpThreshold = (element: HTMLDivElement) => Math.max(400, element.clientHeight)
@@ -160,35 +158,30 @@ export function createSessionTimelineInteraction(session: SessionModel) {
)
}
const { clearMessageHash, scrollToMessage } = useSessionHashScroll({
const cursor = createTimelineCursor({
sessionKey: session.identity.sessionKey,
sessionID: () => session.identity.params.id,
messagesReady: timeline.ready,
ready: timeline.ready,
following: follow.following,
visibleUserMessages,
historySeekable: () => canSeekHistory(historyState()),
seekHistory: () => dispatchHistory(SEEK_REQUESTED_EVENT),
currentMessageId: () => state.messageID,
pendingMessage: () => state.pendingMessage,
setPendingMessage: (value) => setState("pendingMessage", value),
setActiveMessage,
follow: {
detach,
toBottom: () => {
follow.dispatch({ type: "follow" })
scrollToEnd()
},
},
scroller: () => scroller,
anchor,
revealMessage: (id) => revealMessage(id),
scheduleScrollState,
consumePendingMessage: (key) => layout.pendingMessage.consume(key),
detach,
toEnd: () => {
follow.dispatch({ type: "follow" })
scrollToEnd()
if (scroller) scheduleScrollState(scroller)
},
historySeekable: () => canSeekHistory(historyState()),
seekHistory: () => dispatchHistory(SEEK_REQUESTED_EVENT),
})
let resumeFrame: (() => void) | undefined
const resume = (behavior?: ScrollBehavior) => {
setState("messageID", undefined)
cursor.dispatch(CLEAR_CURSOR_EVENT)
const attempt = follow.beginReturn()
// Scrolls on the next frame, before it paints. A submit resumes from its key handler right after changing the
// DOM, where reading the scroll range would force a layout that the frame then repeats. Input that stops
@@ -203,7 +196,6 @@ export function createSessionTimelineInteraction(session: SessionModel) {
return false
})
clearMessageHash()
if (scroller) scheduleScrollState(scroller)
}
@@ -212,7 +204,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
const messages = visibleUserMessages()
if (messages.length === 0) return
const current = state.messageID && messageMark === scrollMark ? state.messageID : cursor()
const current = freshCursorMessageID(untrack(cursor.state)) ?? promptInView()
const base = current ? messages.findIndex((message) => message.id === current) : messages.length
const target = (base === -1 ? messages.length : base) + offset
@@ -224,18 +216,17 @@ export function createSessionTimelineInteraction(session: SessionModel) {
return
}
detach()
scrollToMessage(messages[target], "auto")
cursor.dispatch({ type: "message.jump", messageID: messages[target].id, behavior: "auto" })
}
// A gesture inside a nested scrollable region scrolls that region, not the timeline.
const markUserScroll = (target?: EventTarget | null) => {
if (!scroller) 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
scrollMark += 1
cursor.dispatch(SCROLL_MOVED_EVENT)
}
const setScrollRef = (element: HTMLDivElement | undefined) => {
@@ -366,46 +357,19 @@ export function createSessionTimelineInteraction(session: SessionModel) {
}
createEffect(
on(
() => visibleUserMessages().at(-1)?.id,
(lastID, previousID) => {
if (lastID && previousID && lastID > previousID) setState("messageID", undefined)
},
{ defer: true },
),
)
createEffect(
on(
session.identity.sessionKey,
() => {
setState("messageID", undefined)
setState("pendingMessage", undefined)
setState("scroll", { overflow: false, jump: false })
},
{ defer: true },
),
on(session.identity.sessionKey, () => setState("scroll", { overflow: false, jump: false }), { defer: true }),
)
createEffect(
on(
() => session.identity.params.id,
(id, previous) => {
if (!id || !previous || id === previous || state.messageID || state.pendingMessage || location.hash) return
// A switch resets the cursor, so only a `#message-<id>` or other hash can hold the new session elsewhere.
if (!id || !previous || id === previous || location.hash) return
follow.dispatch({ type: "follow" })
scrollToEnd()
},
),
)
createEffect(
on(
follow.following,
(value) => {
if (!value) return
setState("messageID", undefined)
clearMessageHash()
},
{ defer: true },
),
)
createEffect(() => {
const id = session.identity.params.id
@@ -454,8 +418,16 @@ export function createSessionTimelineInteraction(session: SessionModel) {
actions: {
navigateMessage,
page: (direction: 1 | -1) => page(direction),
revealMessage: (id: string, partID?: string) => revealMessage(id, partID),
revealPart: (target: string) => revealPart(target),
// 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) => {
cursor.dispatch(SCROLL_MOVED_EVENT)
revealMessage(id, partID)
},
revealPart: (target: string) => {
cursor.dispatch(SCROLL_MOVED_EVENT)
return revealPart(target)
},
resume,
setActiveMessage,
},
@@ -1,234 +0,0 @@
import type { SessionMessageUser } from "@opencode/client/promise"
import { useLocation, useNavigate } from "@solidjs/router"
import { createEffect, createMemo, onCleanup, onMount } from "solid-js"
import { messageIdFromHash } from "./message-id-from-hash"
export const useSessionHashScroll = (input: {
sessionKey: () => string
sessionID: () => string | undefined
messagesReady: () => boolean
visibleUserMessages: () => SessionMessageUser[]
historySeekable: () => boolean
seekHistory: () => void
currentMessageId: () => string | undefined
pendingMessage: () => string | undefined
setPendingMessage: (value: string | undefined) => void
setActiveMessage: (message: SessionMessageUser | undefined) => void
follow: { detach: () => void; toBottom: () => void }
scroller: () => HTMLDivElement | undefined
anchor: (id: string) => string
revealMessage?: (id: string) => void
scheduleScrollState: (el: HTMLDivElement) => void
consumePendingMessage: (key: string) => string | undefined
}) => {
const visibleUserMessages = createMemo(() => input.visibleUserMessages())
const messageById = createMemo(() => new Map(visibleUserMessages().map((m) => [m.id, m])))
let pendingKey = ""
let clearing = false
const location = useLocation<{ reveal?: string }>()
const navigate = useNavigate()
const frames = new Set<number>()
const queue = (fn: () => void) => {
const id = requestAnimationFrame(() => {
frames.delete(id)
fn()
})
frames.add(id)
}
const cancel = () => {
for (const id of frames) cancelAnimationFrame(id)
frames.clear()
}
const clearMessageHash = () => {
cancel()
input.consumePendingMessage(input.sessionKey())
if (input.pendingMessage()) input.setPendingMessage(undefined)
if (!location.hash) return
clearing = true
navigate(location.pathname + location.search, { replace: true })
}
const updateHash = (id: string) => {
const hash = `#${input.anchor(id)}`
if (location.hash === hash) return
clearing = false
navigate(location.pathname + location.search + hash, {
replace: true,
})
}
const scrollToElement = (el: HTMLElement, behavior: ScrollBehavior) => {
const root = input.scroller()
if (!root) return false
const a = el.getBoundingClientRect()
const b = root.getBoundingClientRect()
const sticky = root.querySelector("[data-session-title]")
const inset = sticky instanceof HTMLElement ? sticky.offsetHeight : 0
const top = Math.max(0, a.top - b.top + root.scrollTop - inset)
root.scrollTo({ top, behavior })
return true
}
const seek = (id: string, behavior: ScrollBehavior, left = 4): boolean => {
input.revealMessage?.(id)
const el = document.getElementById(input.anchor(id))
if (el) return scrollToElement(el, behavior)
if (left <= 0) return false
queue(() => {
seek(id, behavior, left - 1)
})
return false
}
const scrollToMessage = (message: SessionMessageUser, behavior: ScrollBehavior = "smooth") => {
cancel()
if (input.currentMessageId() !== message.id) input.setActiveMessage(message)
// A mounted prompt is close enough to glide to; any other is first brought in by the virtualizer.
const mounted = behavior === "smooth" ? document.getElementById(input.anchor(message.id)) : null
if (mounted) scrollToElement(mounted, behavior)
if (!mounted) {
input.revealMessage?.(message.id)
seek(message.id, behavior)
}
updateHash(message.id)
}
const applyHash = (behavior: ScrollBehavior) => {
const hash = location.hash.slice(1)
if (!hash) {
// A route that opens the session on a tool call leaves the scroll to the timeline, which reveals the call.
if (location.state?.reveal) return
input.follow.toBottom()
const el = input.scroller()
if (el) input.scheduleScrollState(el)
return
}
const messageId = messageIdFromHash(hash)
if (messageId) {
input.follow.detach()
const msg = messageById().get(messageId)
if (msg) {
scrollToMessage(msg, behavior)
return
}
return
}
const target = document.getElementById(hash)
if (target) {
input.follow.detach()
scrollToElement(target, behavior)
return
}
input.follow.toBottom()
const el = input.scroller()
if (el) input.scheduleScrollState(el)
}
createEffect(() => {
const hash = location.hash
if (!hash) clearing = false
if (!input.sessionID() || !input.messagesReady()) return
cancel()
queue(() => applyHash("auto"))
})
createEffect(() => {
if (!input.sessionID() || !input.messagesReady()) return
visibleUserMessages()
let targetId = input.pendingMessage()
if (!targetId) {
const key = input.sessionKey()
if (pendingKey !== key) {
pendingKey = key
const next = input.consumePendingMessage(key)
if (next) {
input.setPendingMessage(next)
targetId = next
}
}
}
if (!targetId && !clearing) targetId = messageIdFromHash(location.hash)
if (!targetId) return
const pending = input.pendingMessage() === targetId
const msg = messageById().get(targetId)
if (!msg) return
if (pending) input.setPendingMessage(undefined)
if (input.currentMessageId() === targetId && !pending) return
input.follow.detach()
cancel()
queue(() => scrollToMessage(msg, "auto"))
})
// Pages toward a target that is not loaded yet. History paging stops it once a page fails or history runs out.
createEffect(() => {
if (!input.sessionID() || !input.messagesReady()) return
let targetId = input.pendingMessage()
if (!targetId && !clearing) targetId = messageIdFromHash(location.hash)
if (!targetId || messageById().has(targetId) || !input.historySeekable()) return
input.seekHistory()
})
onMount(() => {
if (typeof window !== "undefined" && "scrollRestoration" in window.history) {
window.history.scrollRestoration = "manual"
}
})
onCleanup(cancel)
return {
clearMessageHash,
scrollToMessage,
applyHash,
}
}
+5 -5
View File
@@ -76,15 +76,15 @@ describe("layout persistence", () => {
expect(
decode({
sidebar: { workspaces: { good: true, bad: "bad" } },
sessionView: { [key]: { scroll, pendingMessage: "message" } },
sessionView: { [key]: { scroll, reviewFile: "src/app.ts" } },
}),
).toMatchObject({
sidebar: { workspaces: {} },
sessionView: { [key]: { scroll: {}, pendingMessage: "message" } },
sessionView: { [key]: { scroll: {}, reviewFile: "src/app.ts" } },
})
expect(
decode({ sessionView: { [key]: { scroll: { good: { x: 1, y: 2 } }, pendingMessage: 5 } } }).sessionView,
).toEqual({ [key]: { scroll: {} } })
expect(decode({ sessionView: { [key]: { scroll: { good: { x: 1, y: 2 } }, reviewFile: 5 } } }).sessionView).toEqual(
{ [key]: { scroll: {} } },
)
})
test("keeps scoped state and salvages valid tab entries", () => {
-50
View File
@@ -129,8 +129,6 @@ const sessionViewSchema = Persistence.struct({
reviewOpen: Schema.optional(Persistence.array(Schema.String)),
reviewMode: Schema.optional(Schema.Literals(["git", "branch", "turn"])),
reviewFile: Schema.optional(Schema.String),
pendingMessage: Schema.optional(Schema.String),
pendingMessageAt: Schema.optional(Schema.Finite),
})
export const layoutSchema = Persistence.struct({
@@ -313,7 +311,6 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
)
const MAX_SESSION_KEYS = 50
const PENDING_MESSAGE_TTL_MS = 2 * 60 * 1000
const usage: SessionKeyUsage = {
active: undefined,
@@ -519,53 +516,6 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
setStore("mobileSidebar", "opened", (x) => !x)
},
},
pendingMessage: {
set(sessionKey: string, messageID: string) {
const at = Date.now()
touch(sessionKey)
const current = store.sessionView[sessionKey]
if (!current) {
setStore("sessionView", sessionKey, {
scroll: {},
pendingMessage: messageID,
pendingMessageAt: at,
})
prune(usage.active ?? sessionKey)
return
}
setStore(
"sessionView",
sessionKey,
produce((draft) => {
draft.pendingMessage = messageID
draft.pendingMessageAt = at
}),
)
},
consume(sessionKey: string) {
const current = store.sessionView[sessionKey]
const message = current?.pendingMessage
const at = current?.pendingMessageAt
if (!message || !at) return
setStore(
"sessionView",
sessionKey,
produce((draft) => {
delete draft.pendingMessage
delete draft.pendingMessageAt
}),
)
if (Date.now() - at > PENDING_MESSAGE_TTL_MS) return
return message
},
},
/** The side region of a shell tab, and the session panel width beside it. */
view(sessionKey: string | Accessor<string>, regions: TabRegions) {
const key = createSessionKeyReader(sessionKey, ensureKey)