fix(app): keep a reader's row across a long reconnect

This commit is contained in:
Luke Parker 2026-11-25 03:23:58 +10:00
parent c73a4d4c4d
commit 05043402a8
7 changed files with 230 additions and 75 deletions

View file

@ -139,9 +139,11 @@ This section is the single source for what may move or restyle the session timel
- The reader keeps their place only while the rows in view stay in the transcript. `session.message.sync` (`packages/client/src/solid/data.ts`) reads the newest page again on every reconnect of the event stream, and when a turn ends with a tool still running. It once replaced the transcript with that page: a reader further back than the page jumped 3,400 to 8,100 px, and the older pages were gone.
- A new read of the newest page keeps the loaded messages before it and their cursor. When the page does not reach the loaded messages, it reads older pages until they meet; after a long absence it gives up and keeps the newest messages only.
- How far the read goes back depends on the reader. At the end, it stops 200 messages before the newest page: the reader gains nothing from more. A reader who left the end holds the loaded history (`session.message.hold`, from `src/session/timeline/interaction.ts`), and the read goes back 1,000 messages, about a night of a busy session. Reading 1,000 messages costs 9 requests and one frame of 100 to 150 ms; 3,000 cost a frame of 350 to 450 ms.
- When the read gives up, the rows the reader was on are gone. The timeline then goes to the end, as it does when a session opens. It must not rest on other rows at the old scroll offset: nothing tells the reader that the rows changed.
- Never join a page to messages it does not adjoin. A transcript that skips messages is worse than a lost place, and nothing shows the reader that messages are missing. `loadMore` drops an older page when a newer read replaced the transcript the page continued.
- A message counts as loaded history only where the server put it. The row of a waiting input sits where the input was admitted until its delivery moves it, so it cannot tell where a page meets the history.
- Keepers: "reading the newest page again keeps the loaded history" and the cases after it in `packages/client/test/solid-data.test.ts`, and "a reconnect of the event stream keeps a reader in older history where they were" in `e2e/regression/timeline-history.spec.ts`.
- Keepers: "reading the newest page again keeps the loaded history" and the cases after it in `packages/client/test/solid-data.test.ts`, and the three "a reconnect …" cases in `e2e/regression/timeline-history.spec.ts`: one missed turn, 300 missed messages, and more than a read goes back for.
- To check by hand: scroll several screens back in a long session, then run `window.dispatchEvent(new Event("online"))` in DevTools. The app drops the event stream and reads the transcript again. The rows in view must not move.
### `:has()` selectors

View file

@ -296,83 +296,27 @@ test.describe("timeline history", () => {
})
test("a reconnect of the event stream keeps a reader in older history where they were", async ({ page }) => {
const messages: SessionMessageInfo[] = historyMessages(30)
const reader = await missTurnsInOlderHistory(page, 1)
const timeline = 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 - limit)
await expect.poll(reader.positions).toEqual(reader.before)
})
return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
},
})
test("a reconnect after 300 missed messages keeps a reader in older history where they were", async ({ page }) => {
const reader = await missTurnsInOlderHistory(page, 150)
const scroller = timelineScroller(page)
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible")
await expect.poll(reader.positions).toEqual(reader.before)
})
// Load the older page, then rest at its start: further back than the newest page reaches.
const top = () =>
scroller.evaluate((element) => {
element.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1 }))
element.scrollTop = 0
})
test("a reconnect that cannot keep a reader's place in older history takes them to the end", async ({ page }) => {
// More messages than a read goes back for: the newest page and 1,000 older ones.
const reader = await missTurnsInOlderHistory(page, 560)
await top()
await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(200)
await top()
await expect(scroller.getByText(/^Historical response 0\./)).toBeInViewport()
await expect(scroller.getByText(/^Historical response 1\./)).toBeInViewport()
const keys = await scroller.evaluate((element) => {
const view = element.getBoundingClientRect()
return [...element.querySelectorAll<HTMLElement>("[data-timeline-part-id]")]
.filter((row) => {
const rect = row.getBoundingClientRect()
return rect.bottom > view.top && rect.top < view.bottom
})
.flatMap((row) => (row.dataset.timelinePartId ? [row.dataset.timelinePartId] : []))
.slice(0, 3)
})
expect(keys).toHaveLength(3)
const positions = () =>
scroller.evaluate((element, keys) => {
const top = element.getBoundingClientRect().top
return keys.map((key) => {
const row = element.querySelector<HTMLElement>(`[data-timeline-part-id="${key}"]`)
if (!row) return undefined
return Math.round((row.getBoundingClientRect().top - top) * devicePixelRatio) / devicePixelRatio
})
}, keys)
const before = await positions()
const height = await scroller.evaluate((element) => element.scrollHeight)
const connection = await timeline.transport.waitForConnection()
// The client gets no event for this turn, so it hears of it only when the reconnect reads the newest page again.
messages.push(
userMessage([textPart("prt_missed_prompt", "Ship it")], {
id: "msg_09000_missed_a_user",
created: 1700000000000,
}),
assistantMessage([textPart("prt_missed_reply", "Shipped.")], {
id: "msg_09000_missed_b_assistant",
parentID: "msg_09000_missed_a_user",
created: 1700000001000,
}),
)
await timeline.transport.disconnect()
await timeline.transport.waitForConnection({ after: connection.id })
// The newest page was read again: the missed turn makes the transcript taller.
await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
await expect.poll(positions).toEqual(before)
await expect(reader.scroller.getByText("Missed reply 559.")).toBeInViewport()
await expect
.poll(() =>
reader.scroller.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop),
)
.toBeLessThan(2)
})
test("mounts every part once and in order while paging to the start", async ({ page }) => {
@ -837,6 +781,95 @@ async function openStressTarget(page: Page, input: Parameters<typeof mockStressT
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible")
}
// A reader at the start of the loaded history, further back than the newest page reaches, whose client then misses
// `turns` turns and reconnects.
async function missTurnsInOlderHistory(page: Page, turns: number) {
const messages: SessionMessageInfo[] = historyMessages(30)
const timeline = 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 - limit)
return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
},
})
const scroller = timelineScroller(page)
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible")
// Load the older page, then rest at its start.
const top = () =>
scroller.evaluate((element) => {
element.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1 }))
element.scrollTop = 0
})
await top()
await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(200)
await top()
await expect(scroller.getByText(/^Historical response 0\./)).toBeInViewport()
await expect(scroller.getByText(/^Historical response 1\./)).toBeInViewport()
const keys = await scroller.evaluate((element) => {
const view = element.getBoundingClientRect()
return [...element.querySelectorAll<HTMLElement>("[data-timeline-part-id]")]
.filter((row) => {
const rect = row.getBoundingClientRect()
return rect.bottom > view.top && rect.top < view.bottom
})
.flatMap((row) => (row.dataset.timelinePartId ? [row.dataset.timelinePartId] : []))
.slice(0, 3)
})
expect(keys).toHaveLength(3)
const positions = () =>
scroller.evaluate((element, keys) => {
const top = element.getBoundingClientRect().top
return keys.map((key) => {
const row = element.querySelector<HTMLElement>(`[data-timeline-part-id="${key}"]`)
if (!row) return undefined
return Math.round((row.getBoundingClientRect().top - top) * devicePixelRatio) / devicePixelRatio
})
}, keys)
const before = await positions()
const height = await scroller.evaluate((element) => element.scrollHeight)
const connection = await timeline.transport.waitForConnection()
// The client gets no event for these turns, so it hears of them only when the reconnect reads the newest page again.
messages.push(
...Array.from({ length: turns }, (_, index) => {
const value = String(index).padStart(4, "0")
return [
userMessage([textPart(`prt_1${value}_missed_prompt`, `Missed prompt ${index}`)], {
id: `msg_1${value}_missed_a_user`,
created: 1700000000000 + index * 10_000,
}),
assistantMessage([textPart(`prt_1${value}_missed_reply`, `Missed reply ${index}.`)], {
id: `msg_1${value}_missed_b_assistant`,
parentID: `msg_1${value}_missed_a_user`,
created: 1700000001000 + index * 10_000,
}),
]
}).flat(),
)
await timeline.transport.disconnect()
await timeline.transport.waitForConnection({ after: connection.id })
// The newest page was read again: the missed turns make the transcript taller.
await expect.poll(() => scroller.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height)
return { scroller, before, positions }
}
function timelineScroller(page: Page) {
return page.locator(".scroll-view__viewport", { has: page.locator("[data-timeline-row]") })
}

View file

@ -370,6 +370,24 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
},
),
)
// A reader who left the end holds their place in the loaded history across a new read of the transcript.
createEffect(() => {
const id = session.identity.params.id
if (!id || follow.following()) return
onCleanup(timeline.history.hold(id))
})
// A read that could not keep that history left only the newest messages. The rows the reader was on are gone, so
// the view goes to the end, as it does when the session opens.
createEffect(
on([() => session.identity.params.id, oldestMessage], ([id, oldest], previous) => {
if (!oldest || !previous?.[1] || previous[0] !== id || untrack(follow.following)) return
if (untrack(timeline.messages).some((message) => message.id === previous[1])) return
follow.dispatch({ type: "follow" })
scrollToEnd()
}),
)
createEffect(() => {
const id = session.identity.params.id

View file

@ -183,6 +183,7 @@ export function createTimelineModel(input: { session: Pick<SessionModel, "identi
history: {
loadMore: (id: string, signal: AbortSignal) => data.session.message.loadMore(id, { signal }),
more,
hold: (id: string) => data.session.message.hold(id),
},
lastUserMessage: input.session.history.lastUserMessage,
messages: input.session.history.messages,

View file

@ -4,7 +4,8 @@
admitted (`packages/client/src/solid/data.ts`, `message.sync`). When the page starts inside the loaded transcript,
the loaded messages before it stay, with their cursor, and those that were still running are read again. When the
page does not reach the loaded transcript, up to three older pages (20, 40 and 140 messages) are read to reach it;
past that, the pages replace the transcript. A row after the start of the page that the page lacks is dropped: when the read started before a
past that, the pages replace the transcript. While a view holds the loaded transcript for a reader who is not at its
end (`message.hold`), four more pages of 200 are read, and the newest page is then read once more. A row after the start of the page that the page lacks is dropped: when the read started before a
step, the `session.step.started` row and its text are gone once the page lands, and later deltas for that message
are dropped because the row is not loaded. The reply reappears only after another invalidation. Events create rows for
any session, also one the store found missing (`message.update` does `draft[sessionID] ??= []`).

View file

@ -95,6 +95,9 @@ const messagePageLimit = 20
// Sizes of the older pages that a new read of the newest page may read to reach the loaded history. They grow: a
// short gap costs one small page, and the longest gap that is closed costs three requests.
const bridgePageLimits = [20, 40, 140]
// The same while a reader holds a place in the loaded history: the read goes on in the largest pages the server
// gives, to about 1,000 messages back.
const heldBridgePageLimits = [...bridgePageLimits, 200, 200, 200, 200]
// Trailing window for event bursts that each ask for the same refetch.
export const settleMs = 150
@ -418,6 +421,8 @@ export function createData(config: CreateDataInput) {
// Inputs by session that an inbox read stopped listing: delivered or cancelled while the event was missed. Their
// rows stay where they were admitted until a transcript read places or drops them.
const stranded = new Map<string, Set<string>>()
// Sessions whose reader holds a place in the loaded history, with the number of holds.
const held = new Map<string, number>()
const omitFiles = () =>
typeof config.omitToolFileData === "function" ? config.omitToolFileData() : config.omitToolFileData === true
const stored = (message: SessionMessageInfo) => (omitFiles() ? omitMessageFileData(message) : message)
@ -2073,7 +2078,7 @@ export function createData(config: CreateDataInput) {
// More than one page arrived while its events were missed, so messages lie between the newest page and
// the loaded history. Older pages close the gap. After a longer absence only the newest messages stay,
// as on a first read: the transcript never skips messages.
for (const limit of bridgePageLimits) {
for (const limit of held.has(sessionID) ? heldBridgePageLimits : bridgePageLimits) {
const next = pages.at(-1)?.cursor.next
if (!next || !apart(history(), read())) break
pages.push(await api().message.list({ sessionID, limit, cursor: next }).catch(evictMissing))
@ -2124,8 +2129,24 @@ export function createData(config: CreateDataInput) {
// Kept pages keep the cursor to the page before them.
if (!kept) setStore("session", "messageCursor", sessionID, pages.at(-1)?.cursor.next ?? undefined)
})
// A read that long lets events overtake its newest page, so that page is read once more.
if (pages.length <= bridgePageLimits.length + 1) return
sync.invalidate(`session.message:${sessionID}`)
refresh(() => result.session.message.sync(sessionID))
})
},
/**
* Says that a reader is somewhere in the session's loaded history, until the returned function is called. A
* new read of the transcript then reads further back to keep that history.
*/
hold(sessionID: string) {
held.set(sessionID, (held.get(sessionID) ?? 0) + 1)
return () => {
const holds = (held.get(sessionID) ?? 1) - 1
if (holds > 0) held.set(sessionID, holds)
else held.delete(sessionID)
}
},
more(sessionID: string) {
return store.session.messageCursor[sessionID] !== undefined
},

View file

@ -1688,6 +1688,85 @@ test("a newest page too far ahead of the loaded history replaces it, and the old
}
})
test("a reader's hold keeps the loaded history across a longer absence, until it is released", async () => {
const setup = transcript(notes(1, 40))
try {
await setup.data.session.message.sync("ses_refresh")
await setup.data.session.message.loadMore("ses_refresh", { all: true })
setup.data.session.message.hold("ses_refresh")()
setup.server.messages = notes(1, 340)
setup.data.session.message.invalidate("ses_refresh")
await setup.data.session.message.sync("ses_refresh")
expect(setup.ids()).toEqual(notes(121, 340).map((message) => message.id))
setup.data.session.message.hold("ses_refresh")
// A second hold that is released leaves the first.
setup.data.session.message.hold("ses_refresh")()
setup.server.messages = notes(1, 640)
// A message arrives while the read is far back, so the newest page, which was read first, lacks it.
setup.server.hold = (request) => {
if (request.endsWith("limit=200&cursor=msg_421")) setup.server.messages = notes(1, 641)
return undefined
}
setup.data.session.message.invalidate("ses_refresh")
await setup.data.session.message.sync("ses_refresh")
// Joins the read of the newest page that follows a far read.
await setup.data.session.message.sync("ses_refresh")
expect(setup.ids()).toEqual(notes(121, 641).map((message) => message.id))
expect(setup.server.requests.slice(3)).toEqual([
"message?limit=20&order=desc",
"message?limit=20&cursor=msg_321",
"message?limit=40&cursor=msg_301",
"message?limit=140&cursor=msg_261",
"message?limit=20&order=desc",
"message?limit=20&cursor=msg_621",
"message?limit=40&cursor=msg_601",
"message?limit=140&cursor=msg_561",
"message?limit=200&cursor=msg_421",
// Only a read that went further back than three pages reads the newest page once more.
"message?limit=20&order=desc",
])
// The kept messages keep the cursor to the page before them.
await setup.data.session.message.loadMore("ses_refresh")
expect(setup.ids()).toEqual(notes(101, 641).map((message) => message.id))
} finally {
setup.dispose()
}
})
test("a held history further back than a read reaches is replaced", async () => {
const setup = transcript(notes(1, 40))
try {
await setup.data.session.message.sync("ses_refresh")
await setup.data.session.message.loadMore("ses_refresh", { all: true })
setup.data.session.message.hold("ses_refresh")
setup.server.messages = notes(1, 1400)
setup.server.requests.length = 0
setup.data.session.message.invalidate("ses_refresh")
await setup.data.session.message.sync("ses_refresh")
await setup.data.session.message.sync("ses_refresh")
// The newest page and 1,000 older messages: messages 41 to 380 were never read.
expect(setup.ids()).toEqual(notes(381, 1400).map((message) => message.id))
expect(setup.server.requests.map((request) => request.replace(/&cursor.*/, ""))).toEqual([
"message?limit=20&order=desc",
"message?limit=20",
"message?limit=40",
"message?limit=140",
"message?limit=200",
"message?limit=200",
"message?limit=200",
"message?limit=200",
"message?limit=20&order=desc",
])
} finally {
setup.dispose()
}
})
test("a kept message that was still running is read again", async () => {
const tool = (state: object): SessionMessageInfo =>
({