fix(app): drive older-history paging with an explicit state machine (#61844)

This commit is contained in:
Luke Parker
2026-11-04 20:07:07 -06:00
committed by GitHub
Unverified
parent a4b754e740
commit c5105b8d81
6 changed files with 738 additions and 161 deletions
@@ -0,0 +1,294 @@
import { describe, expect, test } from "bun:test"
import {
canRequestFillProbe,
canRequestScrollPage,
canSeekHistory,
createTimelineHistoryState,
DISPOSED_HISTORY_EVENT,
FILL_REQUESTED_EVENT,
SCROLL_TOP_EVENT,
SEEK_REQUESTED_EVENT,
transitionTimelineHistory,
type HistoryTarget,
type TimelineHistoryEffect,
type TimelineHistoryEvent,
type TimelineHistoryState,
} from "./history-machine"
const sessionA: HistoryTarget = { sessionKey: "dir:ses_a", sessionID: "ses_a" }
const sessionB: HistoryTarget = { sessionKey: "dir:ses_b", sessionID: "ses_b" }
// The oldest message of the newest page, before any older page loads.
const newestPage = "msg_0020"
// Built the way the driver's sync effect builds it.
const sync = (
input: { target?: HistoryTarget; more?: boolean; following?: boolean; ready?: boolean; oldest?: string } = {},
) =>
({
type: "sync",
target: input.target ?? sessionA,
ready: input.ready ?? true,
more: input.more ?? true,
following: input.following ?? false,
oldest: input.oldest ?? newestPage,
}) satisfies TimelineHistoryEvent
function replay(events: TimelineHistoryEvent[], from = createTimelineHistoryState()) {
return events.reduce<{ state: TimelineHistoryState; effects: TimelineHistoryEffect[] }>(
(acc, event) => {
const next = transitionTimelineHistory(acc.state, event)
return { state: next.state, effects: [...acc.effects, ...next.effects] }
},
{ state: from, effects: [] },
)
}
const attempt = (state: TimelineHistoryState) => state.attempt
// `oldest` is the oldest loaded message once the page settles; the newest page's is the one before it.
const loaded = (state: TimelineHistoryState, oldest: string, more = true, following = false) =>
({
type: "page.loaded",
attempt: attempt(state),
previous: newestPage,
oldest,
more,
following,
}) satisfies TimelineHistoryEvent
const cooldownSettled = (state: TimelineHistoryState, following = false) =>
({ type: "cooldown.settled", attempt: attempt(state), following }) satisfies TimelineHistoryEvent
// A following session whose short transcript starts loading through the fill probe.
function fillLoading() {
const entered = replay([sync({ following: true })]).state
return transitionTimelineHistory(entered, { type: "probe.settled", attempt: attempt(entered), load: true })
}
function failedFill() {
const loading = fillLoading().state
return transitionTimelineHistory(loading, { type: "page.failed", attempt: attempt(loading) }).state
}
function expectIgnored(state: TimelineHistoryState, event: TimelineHistoryEvent) {
const next = transitionTimelineHistory(state, event)
expect(next.state).toBe(state)
expect(next.effects).toEqual([])
}
describe("history machine", () => {
test("a failed page stops the fill and seek loops and cools down scroll retries", () => {
const loading = fillLoading()
expect(loading.state.status).toBe("loading")
expect(loading.effects).toEqual([{ type: "load.start", sessionID: "ses_a", attempt: attempt(loading.state) }])
const failed = transitionTimelineHistory(loading.state, { type: "page.failed", attempt: attempt(loading.state) })
expect(failed.state).toMatchObject({ status: "failed", coolingDown: true })
expect(failed.effects).toEqual([{ type: "cooldown.start", attempt: attempt(failed.state) }])
// The store's loading flag flips back while its cursor stays; that used to request the page again at once.
for (const event of [sync({ following: true }), FILL_REQUESTED_EVENT, SEEK_REQUESTED_EVENT, SCROLL_TOP_EVENT])
expectIgnored(failed.state, event)
// The reader scrolled away meanwhile, so only their next scroll retries.
const cooled = transitionTimelineHistory(failed.state, cooldownSettled(failed.state))
expect(cooled.state).toMatchObject({ status: "failed", coolingDown: false })
expect(cooled.effects).toEqual([])
expectIgnored(cooled.state, SEEK_REQUESTED_EVENT)
expectIgnored(cooled.state, sync())
const retried = transitionTimelineHistory(cooled.state, SCROLL_TOP_EVENT)
expect(retried.state.status).toBe("loading")
expect(retried.effects).toEqual([{ type: "load.start", sessionID: "ses_a", attempt: attempt(retried.state) }])
})
test("a short, following view checks its fill once the cooldown ends, without a content change", () => {
const failed = failedFill()
const cooled = transitionTimelineHistory(failed, cooldownSettled(failed, true))
expect(cooled.state).toMatchObject({ status: "idle", probe: "fill" })
expect(cooled.effects).toEqual([{ type: "probe.schedule", probe: "fill", attempt: attempt(cooled.state) }])
const retried = transitionTimelineHistory(cooled.state, {
type: "probe.settled",
attempt: attempt(cooled.state),
load: true,
})
expect(retried.effects).toEqual([{ type: "load.start", sessionID: "ses_a", attempt: attempt(retried.state) }])
})
test("a content change retries a cooled-down failure through one fill probe", () => {
const failed = failedFill()
const cooled = transitionTimelineHistory(failed, cooldownSettled(failed)).state
const probing = transitionTimelineHistory(cooled, FILL_REQUESTED_EVENT)
expect(probing.state).toMatchObject({ status: "idle", probe: "fill" })
expect(probing.effects).toEqual([{ type: "probe.schedule", probe: "fill", attempt: attempt(probing.state) }])
expect(canRequestFillProbe(probing.state)).toBe(false)
})
test("a page that adds nothing while the cursor stays stops paging", () => {
const loading = fillLoading().state
const stalled = transitionTimelineHistory(loading, loaded(loading, newestPage, true, true))
expect(stalled.state).toMatchObject({ status: "exhausted", stalled: { oldest: newestPage } })
expect(stalled.effects).toEqual([])
for (const event of [sync({ following: true }), FILL_REQUESTED_EVENT, SEEK_REQUESTED_EVENT, SCROLL_TOP_EVENT])
expectIgnored(stalled.state, event)
})
test("a resync or reload after a stalled page starts paging again", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const stalled = transitionTimelineHistory(loading, loaded(loading, newestPage)).state
// The resynced newest page starts at a newer message, with a cursor again.
const resynced = transitionTimelineHistory(stalled, sync({ oldest: "msg_0040" }))
expect(resynced.state).toEqual({ status: "idle", target: sessionA, attempt: attempt(stalled) + 1 })
expect(transitionTimelineHistory(resynced.state, SCROLL_TOP_EVENT).state.status).toBe("loading")
const following = transitionTimelineHistory(stalled, sync({ oldest: "msg_0040", following: true }))
expect(following.effects).toEqual([{ type: "probe.schedule", probe: "fill", attempt: attempt(following.state) }])
})
test("a resync that replaces the transcript during a load counts as progress, not a stall", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const replaced = transitionTimelineHistory(loading, loaded(loading, "msg_0040"))
expect(replaced.state).toMatchObject({ status: "idle", probe: "top" })
})
test("a session switch aborts the previous load and ignores its late results", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const switched = transitionTimelineHistory(loading, sync({ target: sessionB }))
expect(switched.state).toEqual({ status: "idle", target: sessionB, attempt: attempt(loading) + 1 })
expect(switched.effects).toEqual([{ type: "load.abort" }])
expectIgnored(switched.state, loaded(loading, "msg_0000"))
expectIgnored(switched.state, { type: "page.failed", attempt: attempt(loading) })
expectIgnored(switched.state, { type: "page.timed-out", attempt: attempt(loading) })
})
test("a session switch cancels a pending probe and drops its result", () => {
const probing = replay([sync({ following: true })]).state
const switched = transitionTimelineHistory(probing, sync({ target: sessionB, following: true }))
expect(switched.effects).toEqual([
{ type: "probe.cancel" },
{ type: "probe.schedule", probe: "fill", attempt: attempt(switched.state) },
])
expectIgnored(switched.state, { type: "probe.settled", attempt: attempt(probing), load: true })
})
test("scrolling to the top while another load is in flight still requests a page", () => {
// The store reports loading while the leading-turn backfill runs; the machine does not read it.
const idle = replay([sync()]).state
const loading = transitionTimelineHistory(idle, SCROLL_TOP_EVENT)
expect(loading.state.status).toBe("loading")
expect(loading.effects).toEqual([{ type: "load.start", sessionID: "ses_a", attempt: attempt(loading.state) }])
})
test("a prepend keeps paging while the detached view is still near the top", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const prepended = transitionTimelineHistory(loading, loaded(loading, "msg_0000"))
expect(prepended.state).toMatchObject({ status: "idle", probe: "top" })
expect(prepended.effects).toEqual([{ type: "probe.schedule", probe: "top", attempt: attempt(prepended.state) }])
const settled = (load: boolean) =>
transitionTimelineHistory(prepended.state, { type: "probe.settled", attempt: attempt(prepended.state), load })
expect(settled(true).state.status).toBe("loading")
const rested = settled(false)
expect(rested.state).toEqual({ status: "idle", target: sessionA, attempt: attempt(prepended.state) })
expect(rested.effects).toEqual([])
})
test("a following view probes the fill again after a prepend", () => {
const loading = fillLoading().state
const prepended = transitionTimelineHistory(loading, loaded(loading, "msg_0000", true, true))
expect(prepended.effects).toEqual([{ type: "probe.schedule", probe: "fill", attempt: attempt(prepended.state) }])
})
test("a page that hangs times out, aborts and ignores its late result", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const timedOut = transitionTimelineHistory(loading, { type: "page.timed-out", attempt: attempt(loading) })
expect(timedOut.state).toMatchObject({ status: "failed", coolingDown: true })
expect(timedOut.effects).toEqual([
{ type: "load.abort" },
{ type: "cooldown.start", attempt: attempt(timedOut.state) },
])
expectIgnored(timedOut.state, loaded(loading, "msg_0000"))
})
test("the last page exhausts history until the transcript has a cursor again", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const exhausted = transitionTimelineHistory(loading, loaded(loading, "msg_0000", false))
expect(exhausted.state).toEqual({ status: "exhausted", target: sessionA, attempt: attempt(loading) + 1 })
expectIgnored(exhausted.state, SCROLL_TOP_EVENT)
expectIgnored(exhausted.state, sync({ more: false }))
const reloaded = transitionTimelineHistory(exhausted.state, sync({ following: true }))
expect(reloaded.state).toMatchObject({ status: "idle", probe: "fill" })
expect(reloaded.effects).toEqual([{ type: "probe.schedule", probe: "fill", attempt: attempt(reloaded.state) }])
})
test("a session without older messages starts exhausted", () => {
const entered = transitionTimelineHistory(createTimelineHistoryState(), sync({ more: false, following: true }))
expect(entered.state).toEqual({ status: "exhausted", target: sessionA, attempt: 1 })
expect(entered.effects).toEqual([])
})
test("steady scroll and unchanged syncs keep the same state", () => {
const idle = replay([sync()]).state
expectIgnored(idle, sync())
const loading = transitionTimelineHistory(idle, SCROLL_TOP_EVENT).state
expectIgnored(loading, SCROLL_TOP_EVENT)
expectIgnored(loading, SEEK_REQUESTED_EVENT)
expectIgnored(loading, FILL_REQUESTED_EVENT)
expectIgnored(loading, sync({ following: true }))
})
test("leaving the session or disposing releases the active work", () => {
const loading = replay([sync(), SCROLL_TOP_EVENT]).state
const left = transitionTimelineHistory(loading, sync({ ready: false }))
expect(left.state).toEqual({ status: "inactive", attempt: attempt(loading) + 1 })
expect(left.effects).toEqual([{ type: "load.abort" }])
expectIgnored(left.state, SCROLL_TOP_EVENT)
expectIgnored(left.state, DISPOSED_HISTORY_EVENT)
const failed = transitionTimelineHistory(loading, { type: "page.failed", attempt: attempt(loading) }).state
const disposed = transitionTimelineHistory(failed, DISPOSED_HISTORY_EVENT)
expect(disposed.state.status).toBe("inactive")
expect(disposed.effects).toEqual([{ type: "cooldown.cancel" }])
expectIgnored(disposed.state, cooldownSettled(failed, true))
const probing = replay([sync({ following: true })]).state
expect(transitionTimelineHistory(probing, DISPOSED_HISTORY_EVENT).effects).toEqual([{ type: "probe.cancel" }])
})
test("selectors gate the scroll, fill and seek requests by phase", () => {
const idle = replay([sync()]).state
const loading = transitionTimelineHistory(idle, SCROLL_TOP_EVENT).state
const failed = transitionTimelineHistory(loading, { type: "page.failed", attempt: attempt(loading) }).state
expect([idle, loading, failed].map(canRequestScrollPage)).toEqual([true, false, false])
expect([idle, loading, failed].map(canRequestFillProbe)).toEqual([true, false, false])
expect([idle, loading, failed].map(canSeekHistory)).toEqual([true, false, false])
})
})
@@ -0,0 +1,285 @@
// A detached reader within this distance of the top loads the next older page.
export const HISTORY_SCROLL_THRESHOLD = 200
// A page that never settles fails, so paging cannot stay "loading" forever.
export const HISTORY_LOAD_TIMEOUT_MS = 30_000
// After a failed page, scrolling near the top waits this long before it retries.
export const HISTORY_RETRY_COOLDOWN_MS = 2_000
export type HistoryTarget = {
readonly sessionKey: string
readonly sessionID: string
}
/**
* A layout check queued for the next frame. `fill`: a following view whose content does not overflow loads more.
* `top`: a detached view still near the top after a prepend loads more.
*/
export type HistoryProbe = "fill" | "top"
// `attempt` advances on every change of phase, so a probe, page or cooldown result from an earlier one is ignored.
export type TimelineHistoryState =
/** No session, or its first messages are not loaded yet. */
| { readonly status: "inactive"; readonly attempt: number }
| {
readonly status: "idle"
readonly target: HistoryTarget
readonly attempt: number
readonly probe?: HistoryProbe
}
| { readonly status: "loading"; readonly target: HistoryTarget; readonly attempt: number }
/**
* The last page failed. Once `coolingDown` ends, the reader's own scroll retries it, and a following view checks its
* fill once; a hash target does not, so a detached view does not poll a broken server.
*/
| {
readonly status: "failed"
readonly target: HistoryTarget
readonly attempt: number
readonly coolingDown: boolean
}
/**
* `stalled`: the store still has a cursor, but the last page added nothing, so paging stops instead of looping. It
* holds the oldest loaded message then; a resync or reload that replaces the transcript changes it and starts again.
*/
| {
readonly status: "exhausted"
readonly target: HistoryTarget
readonly attempt: number
readonly stalled?: { readonly oldest: string | undefined }
}
export type TimelineHistoryEvent =
| {
readonly type: "sync"
readonly target: HistoryTarget | undefined
readonly ready: boolean
readonly more: boolean
readonly following: boolean
/** The oldest loaded message. */
readonly oldest: string | undefined
}
/** A detached reader scrolled near the top. */
| { readonly type: "scroll.top" }
/** The content or the view changed size while following. */
| { readonly type: "fill.requested" }
/** A hash or pending message target is not loaded yet. */
| { readonly type: "seek.requested" }
| { readonly type: "probe.settled"; readonly attempt: number; readonly load: boolean }
/** A page made progress when the oldest loaded message changed: an older page landed, or the transcript resynced. */
| {
readonly type: "page.loaded"
readonly attempt: number
readonly previous: string | undefined
readonly oldest: string | undefined
readonly more: boolean
readonly following: boolean
}
| { readonly type: "page.failed"; readonly attempt: number }
| { readonly type: "page.timed-out"; readonly attempt: number }
| { readonly type: "cooldown.settled"; readonly attempt: number; readonly following: boolean }
| { readonly type: "disposed" }
export type TimelineHistoryEffect =
| { readonly type: "probe.schedule"; readonly probe: HistoryProbe; readonly attempt: number }
| { readonly type: "probe.cancel" }
| { readonly type: "load.start"; readonly sessionID: string; readonly attempt: number }
| { readonly type: "load.abort" }
| { readonly type: "cooldown.start"; readonly attempt: number }
| { readonly type: "cooldown.cancel" }
export type TimelineHistoryTransition = {
readonly state: TimelineHistoryState
readonly effects: readonly TimelineHistoryEffect[]
}
type Active = Exclude<TimelineHistoryState, { readonly status: "inactive" }>
// Shared events for the frequent dispatches, so scrolling and resizing allocate nothing.
export const SCROLL_TOP_EVENT: TimelineHistoryEvent = Object.freeze({ type: "scroll.top" })
export const FILL_REQUESTED_EVENT: TimelineHistoryEvent = Object.freeze({ type: "fill.requested" })
export const SEEK_REQUESTED_EVENT: TimelineHistoryEvent = Object.freeze({ type: "seek.requested" })
export const DISPOSED_HISTORY_EVENT: TimelineHistoryEvent = Object.freeze({ type: "disposed" })
const NO_EFFECTS: readonly TimelineHistoryEffect[] = Object.freeze([])
const PROBE_CANCEL: readonly TimelineHistoryEffect[] = Object.freeze([{ type: "probe.cancel" }])
const LOAD_ABORT: readonly TimelineHistoryEffect[] = Object.freeze([{ type: "load.abort" }])
const COOLDOWN_CANCEL: readonly TimelineHistoryEffect[] = Object.freeze([{ type: "cooldown.cancel" }])
export function createTimelineHistoryState(): TimelineHistoryState {
return { status: "inactive", attempt: 0 }
}
export function transitionTimelineHistory(
state: TimelineHistoryState,
event: TimelineHistoryEvent,
): TimelineHistoryTransition {
if (event.type === "disposed") return deactivate(state)
if (event.type === "sync") return synced(state, event)
if (state.status === "inactive") return unchanged(state)
if (event.type === "scroll.top") return canRequestScrollPage(state) ? load(state) : unchanged(state)
if (event.type === "seek.requested") return canSeekHistory(state) ? load(state) : unchanged(state)
if (event.type === "fill.requested")
return canRequestFillProbe(state) ? probe(state.target, state.attempt + 1, "fill", cancel(state)) : unchanged(state)
if (event.type === "probe.settled") {
if (state.status !== "idle" || !state.probe || state.attempt !== event.attempt) return unchanged(state)
// The probe already ran, so there is nothing to cancel.
if (event.load) return load(state, NO_EFFECTS)
return changed({ status: "idle", target: state.target, attempt: state.attempt })
}
if (event.type === "cooldown.settled") {
if (state.status !== "failed" || !state.coolingDown || state.attempt !== event.attempt) return unchanged(state)
// A short, following view cannot scroll to retry, so it checks the fill once per cooldown.
if (event.following) return probe(state.target, state.attempt + 1, "fill", NO_EFFECTS)
return changed({ ...state, coolingDown: false })
}
if (state.status !== "loading" || state.attempt !== event.attempt) return unchanged(state)
const attempt = state.attempt + 1
if (event.type === "page.loaded") {
if (!event.more) return changed({ status: "exhausted", target: state.target, attempt })
if (event.oldest === event.previous)
return changed({ status: "exhausted", target: state.target, attempt, stalled: { oldest: event.oldest } })
return probe(state.target, attempt, event.following ? "fill" : "top", NO_EFFECTS)
}
return changed({ status: "failed", target: state.target, attempt, coolingDown: true }, [
...(event.type === "page.timed-out" ? LOAD_ABORT : NO_EFFECTS),
{ type: "cooldown.start", attempt },
])
}
/** A detached reader near the top may request the next page. */
export function canRequestScrollPage(state: TimelineHistoryState) {
return state.status === "idle" || (state.status === "failed" && !state.coolingDown)
}
/** A following view may check whether its content still leaves room for older messages. */
export function canRequestFillProbe(state: TimelineHistoryState) {
return (state.status === "idle" && state.probe !== "fill") || (state.status === "failed" && !state.coolingDown)
}
/** A target that is not loaded yet may page through history only while nothing failed, ran out or is loading. */
export function canSeekHistory(state: TimelineHistoryState) {
return state.status === "idle"
}
function synced(
state: TimelineHistoryState,
event: Extract<TimelineHistoryEvent, { type: "sync" }>,
): TimelineHistoryTransition {
if (!event.target || !event.ready) return deactivate(state)
if (state.status === "inactive" || !sameTarget(state.target, event.target))
return enter(event.target, state.attempt + 1, event, cancel(state))
// The store publishes the page, and its cursor, before the request settles; `page.loaded` reads both.
if (state.status === "loading") return unchanged(state)
if (state.status === "exhausted") {
if (!event.more)
return state.stalled
? changed({ status: "exhausted", target: state.target, attempt: state.attempt })
: unchanged(state)
// A reloaded or resynced transcript has a cursor again, or a different oldest message than the stalled page left.
if (!state.stalled || state.stalled.oldest !== event.oldest)
return enter(state.target, state.attempt + 1, event, NO_EFFECTS)
return unchanged(state)
}
if (!event.more)
return changed({ status: "exhausted", target: state.target, attempt: state.attempt + 1 }, cancel(state))
if (state.status === "failed" || !event.following || state.probe === "fill") return unchanged(state)
return probe(state.target, state.attempt + 1, "fill", cancel(state))
}
function enter(
target: HistoryTarget,
attempt: number,
event: Extract<TimelineHistoryEvent, { type: "sync" }>,
effects: readonly TimelineHistoryEffect[],
): TimelineHistoryTransition {
if (!event.more) return changed({ status: "exhausted", target, attempt }, effects)
if (event.following) return probe(target, attempt, "fill", effects)
return changed({ status: "idle", target, attempt }, effects)
}
function load(state: Active, released = cancel(state)): TimelineHistoryTransition {
const attempt = state.attempt + 1
return changed({ status: "loading", target: state.target, attempt }, [
...released,
{ type: "load.start", sessionID: state.target.sessionID, attempt },
])
}
function probe(
target: HistoryTarget,
attempt: number,
kind: HistoryProbe,
effects: readonly TimelineHistoryEffect[],
): TimelineHistoryTransition {
return changed({ status: "idle", target, attempt, probe: kind }, [
...effects,
{ type: "probe.schedule", probe: kind, attempt },
])
}
function deactivate(state: TimelineHistoryState): TimelineHistoryTransition {
if (state.status === "inactive") return unchanged(state)
return changed({ status: "inactive", attempt: state.attempt + 1 }, cancel(state))
}
// Releases the work the state being left owns.
function cancel(state: TimelineHistoryState) {
if (state.status === "idle" && state.probe) return PROBE_CANCEL
if (state.status === "loading") return LOAD_ABORT
if (state.status === "failed" && state.coolingDown) return COOLDOWN_CANCEL
return NO_EFFECTS
}
function sameTarget(left: HistoryTarget, right: HistoryTarget) {
return left.sessionKey === right.sessionKey && left.sessionID === right.sessionID
}
function changed(
state: TimelineHistoryState,
effects: readonly TimelineHistoryEffect[] = NO_EFFECTS,
): TimelineHistoryTransition {
return { state, effects }
}
function unchanged(state: TimelineHistoryState): TimelineHistoryTransition {
return { state, effects: NO_EFFECTS }
}
+148 -79
View File
@@ -1,13 +1,29 @@
import type { SessionMessageUser } from "@opencode/client/promise"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { useLocation } from "@solidjs/router"
import { createEffect, on, onCleanup } from "solid-js"
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 { createTimelineFollow } from "./follow"
import {
canRequestFillProbe,
canRequestScrollPage,
canSeekHistory,
createTimelineHistoryState,
DISPOSED_HISTORY_EVENT,
FILL_REQUESTED_EVENT,
HISTORY_LOAD_TIMEOUT_MS,
HISTORY_RETRY_COOLDOWN_MS,
HISTORY_SCROLL_THRESHOLD,
SCROLL_TOP_EVENT,
SEEK_REQUESTED_EVENT,
transitionTimelineHistory,
type TimelineHistoryEffect,
type TimelineHistoryEvent,
} from "./history-machine"
import { createTimelineModel } from "./model"
export function createSessionTimelineInteraction(session: SessionModel) {
@@ -63,9 +79,12 @@ export function createSessionTimelineInteraction(session: SessionModel) {
let messageMark = 0
let scrollStateFrame: (() => void) | undefined
let scrollStateTarget: HTMLDivElement | undefined
let fillFrame: (() => void) | undefined
let historyContinuationFrame: number | undefined
const historyRequests = new Set<string>()
const [historyState, setHistoryState] = createSignal(createTimelineHistoryState())
let historyProbe: (() => void) | undefined
let historyLoad: { controller: AbortController; timer: ReturnType<typeof setTimeout> } | undefined
let historyCooldown: ReturnType<typeof setTimeout> | undefined
// Changes only when an older page lands or the transcript is replaced, not while a reply streams.
const oldestMessage = createMemo(() => timeline.messages()[0]?.id)
const visibleUserMessages = timeline.visibleUserMessages
const anchor = (id: string) => `message-${id}`
@@ -146,9 +165,8 @@ export function createSessionTimelineInteraction(session: SessionModel) {
sessionID: () => session.identity.params.id,
messagesReady: timeline.ready,
visibleUserMessages,
historyMore: timeline.history.more,
historyLoading: timeline.history.loading,
loadMore: loadOlder,
historySeekable: () => canSeekHistory(historyState()),
seekHistory: () => dispatchHistory(SEEK_REQUESTED_EVENT),
currentMessageId: () => state.messageID,
pendingMessage: () => state.pendingMessage,
setPendingMessage: (value) => setState("pendingMessage", value),
@@ -226,67 +244,125 @@ export function createSessionTimelineInteraction(session: SessionModel) {
if (!element) return
scheduleScrollState(element)
fill()
}
async function loadOlder() {
const owner = session.ownership.capture()
if (timeline.history.loading() || historyRequests.has(owner.key)) return
historyRequests.add(owner.key)
const before = timeline.messages().length
try {
await timeline.history.loadOlder()
} finally {
historyRequests.delete(owner.key)
}
if (!owner.current() || timeline.messages().length <= before) return
if (follow.following() || !scroller || scroller.scrollTop >= 200 || !timeline.history.more()) return
if (historyContinuationFrame !== undefined) cancelAnimationFrame(historyContinuationFrame)
historyContinuationFrame = requestAnimationFrame(() => {
historyContinuationFrame = undefined
owner.run(onHistoryScroll)
})
requestFill()
}
const onHistoryScroll = () => {
if (
historyRequests.has(session.ownership.key()) ||
timeline.history.loading() ||
follow.following() ||
!scroller ||
scroller.scrollTop >= 200
scroller.scrollTop >= HISTORY_SCROLL_THRESHOLD ||
!canRequestScrollPage(untrack(historyState)) ||
untrack(follow.following)
)
return
void loadOlder()
dispatchHistory(SCROLL_TOP_EVENT)
}
// Like the scroll state, measures in the shared frame loop's read phase.
const fill = () => {
if (fillFrame !== undefined) return
let short = false
fillFrame = frameLoop.addMeasured(
() => {
short =
!!session.identity.params.id &&
timeline.ready() &&
follow.following() &&
!timeline.history.loading() &&
!!scroller &&
scroller.scrollHeight <= scroller.clientHeight + 1
},
() => {
fillFrame = undefined
// Runs inside the virtualizer's ref and resize effects, so it reads untracked: they must not rerun on each phase.
const requestFill = () => {
if (!canRequestFillProbe(untrack(historyState)) || !untrack(follow.following)) return
dispatchHistory(FILL_REQUESTED_EVENT)
}
if (short && timeline.history.more()) void loadOlder()
function dispatchHistory(event: TimelineHistoryEvent) {
untrack(() => {
const current = historyState()
const next = transitionTimelineHistory(current, event)
return false
},
)
if (next.state !== current) setHistoryState(next.state)
next.effects.forEach(runHistory)
})
}
function runHistory(effect: TimelineHistoryEffect) {
if (effect.type === "probe.schedule") {
historyProbe?.()
let load = false
// Like the scroll state, measures in the shared frame loop's read phase.
historyProbe = frameLoop.addMeasured(
() => {
load =
!!scroller &&
(effect.probe === "fill"
? follow.following() && scroller.scrollHeight <= scroller.clientHeight + 1
: !follow.following() && scroller.scrollTop < HISTORY_SCROLL_THRESHOLD)
},
() => {
historyProbe = undefined
dispatchHistory({ type: "probe.settled", attempt: effect.attempt, load })
return false
},
)
return
}
if (effect.type === "probe.cancel") {
historyProbe?.()
historyProbe = undefined
return
}
if (effect.type === "load.start") {
abortHistoryLoad()
const previous = oldestMessage()
const load = {
controller: new AbortController(),
timer: setTimeout(
() => dispatchHistory({ type: "page.timed-out", attempt: effect.attempt }),
HISTORY_LOAD_TIMEOUT_MS,
),
}
// Every outcome settles in the machine, which drops a result whose attempt is no longer current.
const settle = (event: TimelineHistoryEvent) => {
clearTimeout(load.timer)
if (historyLoad === load) historyLoad = undefined
dispatchHistory(event)
}
historyLoad = load
timeline.history.loadMore(effect.sessionID, load.controller.signal).then(
() =>
settle({
type: "page.loaded",
attempt: effect.attempt,
previous,
oldest: oldestMessage(),
more: timeline.history.more(),
following: follow.following(),
}),
() => settle({ type: "page.failed", attempt: effect.attempt }),
)
return
}
if (effect.type === "load.abort") {
abortHistoryLoad()
return
}
clearTimeout(historyCooldown)
historyCooldown = undefined
if (effect.type === "cooldown.cancel") return
historyCooldown = setTimeout(() => {
historyCooldown = undefined
dispatchHistory({ type: "cooldown.settled", attempt: effect.attempt, following: follow.following() })
}, HISTORY_RETRY_COOLDOWN_MS)
}
function abortHistoryLoad() {
if (!historyLoad) return
clearTimeout(historyLoad.timer)
historyLoad.controller.abort()
historyLoad = undefined
}
createEffect(
@@ -330,23 +406,18 @@ export function createSessionTimelineInteraction(session: SessionModel) {
{ defer: true },
),
)
createEffect(
on(
() =>
[
session.identity.params.id,
timeline.ready(),
timeline.history.more(),
timeline.history.loading(),
follow.following(),
visibleUserMessages().length,
] as const,
([id, ready, more, loading, following]) => {
if (id && ready && more && !loading && following) fill()
},
{ defer: true },
),
)
createEffect(() => {
const id = session.identity.params.id
dispatchHistory({
type: "sync",
target: id ? { sessionKey: session.identity.sessionKey(), sessionID: id } : undefined,
ready: timeline.ready(),
more: timeline.history.more(),
following: follow.following(),
oldest: oldestMessage(),
})
})
createResizeObserver(
() => state.refs.dock,
(_rect, _element, entry) => {
@@ -368,17 +439,15 @@ export function createSessionTimelineInteraction(session: SessionModel) {
if (stick) scrollToEnd()
if (scroller) scheduleScrollState(scroller)
fill()
requestFill()
},
)
onCleanup(() => {
if (historyContinuationFrame !== undefined) cancelAnimationFrame(historyContinuationFrame)
dispatchHistory(DISPOSED_HISTORY_EVENT)
resumeFrame?.()
scrollStateFrame?.()
fillFrame?.()
})
return {
@@ -406,7 +475,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
scheduleScrollState,
contentResized: () => {
if (scroller) scheduleScrollState(scroller)
fill()
requestFill()
},
setDockRef: (element: HTMLDivElement | undefined) => {
setState("refs", "dock", element)
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise"
import { enrichLeadingTurn, loadOlderTimeline } from "./model"
import { enrichLeadingTurn } from "./model"
const user = (id: string): SessionMessageUser => ({ id, type: "user", text: id, time: { created: 1 } })
@@ -130,32 +130,6 @@ describe("timeline model", () => {
expect(loads).toBe(2)
})
test.each([
["restores the anchor after one opaque cursor page", "ok", ["before", "load", "after", true]],
["does not restore an anchor after the session changes", "switch", ["before", "load"]],
["releases the anchor when loading history fails", "fail", ["before", "load", "after", true, "history failed"]],
] as const)("%s", async (_name, outcome, expected) => {
let sessionID = "ses_old"
const calls: Array<string | boolean> = []
await loadOlderTimeline({
sessionID: () => sessionID,
more: () => true,
loading: () => false,
loadMore: async () => {
calls.push("load")
if (outcome === "switch") sessionID = "ses_new"
if (outcome === "fail") throw new Error("history failed")
},
before: () => calls.push("before"),
after: (done) => calls.push("after", done),
}).catch((error: Error) => calls.push(error.message))
expect(calls).toEqual([...expected])
})
test.each([
["caps background pages when the parent remains outside the window", [assistant("msg_latest")], 3],
["does not load before a leading user turn", [user("msg_user"), assistant("msg_latest")], 0],
+4 -40
View File
@@ -54,25 +54,11 @@ export function createTimelineModel(input: { session: Pick<SessionModel, "identi
return id ? data.session.message.more(id) : false
}
const loading = () => {
const id = input.session.identity.sessionID()
return id ? data.session.message.loading(id) : false
}
const loadOlder = async (options?: { before?: () => void; after?: (done: boolean) => void }) => {
return loadOlderTimeline({
sessionID: input.session.identity.sessionID,
more,
loading,
loadMore: (id) => data.session.message.loadMore(id),
before: options?.before,
after: options?.after,
})
}
return {
history: { loadOlder, loading, more },
history: {
loadMore: (id: string, signal: AbortSignal) => data.session.message.loadMore(id, { signal }),
more,
},
lastUserMessage: input.session.history.lastUserMessage,
messages: input.session.history.messages,
ready,
@@ -128,25 +114,3 @@ function leadingTurnNeedsParent(messages: SessionMessageInfo[], id: string) {
return boundary === -1 || assistant < boundary
}
export async function loadOlderTimeline(input: {
sessionID: Accessor<string | undefined>
more: Accessor<boolean>
loading: Accessor<boolean>
loadMore: (sessionID: string) => Promise<void>
before?: () => void
after?: (done: boolean) => void
}) {
const id = input.sessionID()
if (!id || !input.more() || input.loading()) return
input.before?.()
await input.loadMore(id).catch((error) => {
if (input.sessionID() === id) input.after?.(true)
throw error
})
if (input.sessionID() !== id) return
input.after?.(true)
}
@@ -8,9 +8,8 @@ export const useSessionHashScroll = (input: {
sessionID: () => string | undefined
messagesReady: () => boolean
visibleUserMessages: () => SessionMessageUser[]
historyMore: () => boolean
historyLoading: () => boolean
loadMore: (sessionID: string) => Promise<void>
historySeekable: () => boolean
seekHistory: () => void
currentMessageId: () => string | undefined
pendingMessage: () => string | undefined
setPendingMessage: (value: string | undefined) => void
@@ -207,24 +206,16 @@ export const useSessionHashScroll = (input: {
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(() => {
const sessionID = input.sessionID()
if (!sessionID || !input.messagesReady()) return
visibleUserMessages()
if (!input.sessionID() || !input.messagesReady()) return
let targetId = input.pendingMessage()
if (!targetId && !clearing) targetId = messageIdFromHash(location.hash)
if (!targetId) return
if (messageById().has(targetId)) return
if (!input.historyMore() || input.historyLoading()) return
void input.loadMore(sessionID)
if (!targetId || messageById().has(targetId) || !input.historySeekable()) return
input.seekHistory()
})
onMount(() => {