From 04ef301030696197932df71be6bb0eb65d6c5ff7 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Sun, 25 Oct 2026 13:28:24 -0700 Subject: [PATCH] fix(client): only re-read loaded history after scrolling back --- packages/client/src/solid/data.ts | 15 ++++-- packages/client/test/solid-data.test.ts | 65 ++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/packages/client/src/solid/data.ts b/packages/client/src/solid/data.ts index aec48c69cfe..d4dd9f741b2 100644 --- a/packages/client/src/solid/data.ts +++ b/packages/client/src/solid/data.ts @@ -285,6 +285,8 @@ export function createData(config: CreateDataInput) { Object.values(store.session.info).toSorted((a, b) => b.time.updated - a.time.updated), ) const messageIndex = new Map>() + // Sessions whose transcript holds older pages the reader scrolled back to load. + const scrolledBack = new Set() const sync = createSync() let activeUpdates: Map | undefined const pendingUpdates = new Map>() @@ -588,6 +590,7 @@ export function createData(config: CreateDataInput) { sync.invalidate(`session.pending:${sessionID}`) sync.invalidate(`session.message:${sessionID}`) messageLoads.delete(sessionID) + scrolledBack.delete(sessionID) // Keep unacknowledged submissions until their echo or rollback settles them. const pending = store.session.pending[sessionID]?.filter((item) => outbox.has(item.id)) ?? [] const messages = store.session.message[sessionID]?.filter((item) => outbox.has(item.id)) ?? [] @@ -610,6 +613,7 @@ export function createData(config: CreateDataInput) { activeUpdates?.set(sessionID, undefined) store.session.pending[sessionID]?.forEach((item) => outbox.delete(item.id)) messageIndex.delete(sessionID) + scrolledBack.delete(sessionID) sync.invalidate(`session:${sessionID}`) sync.invalidate(`session.family:${sessionID}`) sync.invalidate(`session.pending:${sessionID}`) @@ -1712,12 +1716,14 @@ export function createData(config: CreateDataInput) { sync(sessionID: string) { return sync.run(`session.message:${sessionID}`, async () => { const limit = config.initialMessageLimit?.() ?? messagePageLimit - // A re-read covers the history already loaded, plus room for rows that arrived meanwhile, so a reconnect - // keeps the transcript's place. Deeper history collapses to the newest page the server allows. + // After scrolling back, a re-read covers the history already loaded, plus room for rows that arrived + // meanwhile, so a reconnect keeps the transcript's place. Deeper history collapses to the newest page the + // server allows. At the bottom it reads the newest window, since live rows alone are cheap to drop. + const grow = scrolledBack.has(sessionID) const loaded = store.session.message[sessionID]?.length ?? 0 const response = await api().message.list({ sessionID, - limit: loaded === 0 ? limit : Math.min(resyncMessageLimit, loaded + limit), + limit: grow ? Math.min(resyncMessageLimit, loaded + limit) : limit, order: "desc", }) const fetched = response.data.toReversed() @@ -1733,6 +1739,8 @@ export function createData(config: CreateDataInput) { (item) => !ids.has(item.id) && (outbox.has(item.id) || admitted.has(item.id)), ) const messages = local.length === 0 ? fetched : [...fetched, ...local] + // The newest window replaces any older page loaded while it was read. + if (!grow) scrolledBack.delete(sessionID) batch(() => { messageIndex.set(sessionID, new Map(messages.map((message, index) => [message.id, index]))) setStore("session", "message", sessionID, reconcile(messages)) @@ -1796,6 +1804,7 @@ export function createData(config: CreateDataInput) { const existing = store.session.message[sessionID] ?? [] const ids = new Set(existing.map((item) => item.id)) const messages = [...fetched.reverse().filter((item) => !ids.has(item.id)), ...existing] + scrolledBack.add(sessionID) batch(() => { options?.beforePublish?.() messageIndex.set(sessionID, new Map(messages.map((item, position) => [item.id, position]))) diff --git a/packages/client/test/solid-data.test.ts b/packages/client/test/solid-data.test.ts index 6d1fbb49727..c0cc60b77ea 100644 --- a/packages/client/test/solid-data.test.ts +++ b/packages/client/test/solid-data.test.ts @@ -1024,10 +1024,15 @@ function resyncFixture(length: number) { text: `Message ${index}`, time: { created: index }, })) + const reads: URL[] = [] + const gate = { sync: Promise.resolve() } + const listeners = new Set[0]>() const api = OpenCode.make({ baseUrl: "http://opencode.local", fetch: async (input, init) => { const url = new URL((input instanceof Request ? input : new Request(input, init)).url) + reads.push(url) + if (url.searchParams.has("order")) await gate.sync // Like the server, a cursor names the oldest message read, and any non-empty page has a next cursor. const cursor = url.searchParams.get("cursor") const end = cursor ? Math.max(0, history.findIndex((item) => item.id === cursor)) : history.length @@ -1039,12 +1044,36 @@ function resyncFixture(length: number) { const data = createData({ api: () => api, directory: "/project", - event: { on: () => () => {}, listen: () => () => {} }, + event: { + on: () => () => {}, + listen(handler) { + listeners.add(handler) + return () => listeners.delete(handler) + }, + }, }) return { data, history, + gate, dispose, + lastLimit: () => reads.at(-1)?.searchParams.get("limit"), + append(index: number) { + const id = `msg_${String(index).padStart(4, "0")}` + history.push({ id, type: "synthetic", text: id, time: { created: index } }) + listeners.forEach((listener) => + listener({ + name: "session.synthetic", + details: { + id: id.replace(/^msg_/, "evt_"), + type: "session.synthetic", + created: index, + durable: { aggregateID: sessionID, seq: index, version: 1 }, + data: { sessionID, text: id }, + } as OpenCodeEvent, + }), + ) + }, ids: () => data.session.message.list(sessionID).map((message) => message.id), sync: () => data.session.message.sync(sessionID), loadMore: () => data.session.message.loadMore(sessionID), @@ -1078,6 +1107,40 @@ test("a resync keeps loaded history and takes new and changed rows from the serv } }) +test("a resync at the bottom of a session re-reads only the newest window", async () => { + const setup = resyncFixture(100) + try { + await setup.sync() + for (let index = 100; index < 150; index++) setup.append(index) + expect(setup.ids()).toHaveLength(70) + await setup.resync() + expect(setup.lastLimit()).toBe("20") + expect(setup.ids()).toEqual(setup.history.slice(130).map((item) => item.id)) + } finally { + setup.dispose() + } +}) + +test("a resync stops keeping older pages once a sync collapses to the newest window", async () => { + const setup = resyncFixture(100) + try { + await setup.sync() + const release = Promise.withResolvers() + setup.gate.sync = release.promise + setup.data.session.message.invalidate("ses_resync") + const collapse = setup.sync() + await setup.loadMore() + release.resolve() + await collapse + expect(setup.ids()).toEqual(setup.history.slice(80).map((item) => item.id)) + + await setup.resync() + expect(setup.lastLimit()).toBe("20") + } finally { + setup.dispose() + } +}) + test("a resync takes history reverted past the oldest loaded row from the server", async () => { const setup = resyncFixture(100) try {