From b41b9293e99a0cc876990cbb425e46d5c9ecf174 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Mon, 14 Sep 2026 09:07:14 +0800 Subject: [PATCH] fix(web): render cold sessions from a small initial page (#1809) * fix(web): speed up cold session first paint * test(web): update pagination fixtures for cold page * test(web): wait for cold page before loading history * feat(native): match cold session pagination * test(native): cover cached re-entry page size --- .github/workflows/test.yml | 2 +- .../app/hapi/data/store/MessageWindowStore.kt | 8 ++- .../hapi/data/store/MessageWindowStoreTest.kt | 33 ++++++++++ .../protocol/window/MessageWindowState.kt | 2 + docs/api/client-contract/pagination.md | 10 ++- e2e/cold-initial-tail.spec.ts | 32 ++++++++++ .../Stores/MessageWindowController.swift | 5 +- .../Window/MessageWindowState.swift | 4 +- .../MessageWindowControllerTests.swift | 63 +++++++++++++++++++ .../cancel-too-late-ingests-invoked-row.json | 2 +- .../pagination/fetch-older-before-cursor.json | 2 +- .../latest-page-then-sse-ingest.json | 2 +- .../messages-consumed-stamps-invoked-at.json | 2 +- .../older-page-epoch-mismatch-resets.json | 2 +- ...ed-state-reconciliation-drops-deleted.json | 2 +- ...easoning-snapshots-collapse-to-newest.json | 2 +- .../reset-latest-preserves-optimistic.json | 2 +- .../sse-hidden-rows-advance-cursor-only.json | 2 +- ...reserves-queued-and-recomputes-cursor.json | 2 +- web/e2e-fixtures/history-load-fixture.tsx | 24 +++++-- web/src/lib/message-window-store.test.ts | 44 +++++++++++++ web/src/lib/message-window-store.ts | 10 ++- 22 files changed, 235 insertions(+), 22 deletions(-) create mode 100644 e2e/cold-initial-tail.spec.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index daf0eb48..09de87f9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,7 @@ jobs: - run: bun install --frozen-lockfile - run: bun typecheck - run: bunx playwright install --with-deps chromium - - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts + - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts - run: bun run test # Serial runner-integration suite: starts real detached runner/session diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt index f58057eb..66601ba1 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt @@ -9,6 +9,7 @@ import app.hapi.protocol.window.MessageWindowLogic import app.hapi.protocol.window.HISTORY_WINDOW_SIZE import app.hapi.protocol.window.MessageWindowState import app.hapi.protocol.window.OlderLoadOutcome +import app.hapi.protocol.window.INITIAL_PAGE_SIZE import app.hapi.protocol.window.PAGE_SIZE import app.hapi.protocol.window.WindowMessage import app.hapi.protocol.window.asWindowMessage @@ -206,7 +207,12 @@ class MessageWindowStore( if (!canIncrement) { val requestBaseline = baseline() - val response = api.getMessages(sessionId, MessagesQuery.Latest(limit = PAGE_SIZE)) + val latestPageSize = if (initial.requiresLatestReset || initialCursor != null) { + PAGE_SIZE + } else { + INITIAL_PAGE_SIZE + } + val response = api.getMessages(sessionId, MessagesQuery.Latest(limit = latestPageSize)) if (!isCurrentTailSync(generation)) return update { previous -> if (previous.syncGeneration != generation) return@update previous diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt index acb73144..86b22529 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt @@ -9,6 +9,8 @@ import app.hapi.protocol.window.MessageViewMode import app.hapi.protocol.window.MessagePosition import app.hapi.protocol.window.OlderLoadOutcome import app.hapi.protocol.window.PersistedMessageWindow +import app.hapi.protocol.window.INITIAL_PAGE_SIZE +import app.hapi.protocol.window.PAGE_SIZE import app.hapi.protocol.window.asWindowMessage import app.hapi.protocol.window.buildOptimisticMessage import app.hapi.protocol.wire.DecryptedMessage @@ -236,6 +238,37 @@ class MessageWindowStoreTest { assertEquals(false, store.state.value.isLoadingMore) } + @Test + fun `cold sync requests the initial page size`() = runTest { + val api = GatedMessagesApi() + val store = MessageWindowStore("s", api, backgroundScope) + + val sync = launch { store.syncTail() } + runCurrent() + assertEquals(1, api.requests.size) + assertTrue(api.requests.single() is MessagesQuery.Latest) + assertEquals(INITIAL_PAGE_SIZE, (api.requests.single() as MessagesQuery.Latest).limit) + + api.release(latestPage(listOf(agentRow("a-1", 1, 1000)), epoch = 0)) + sync.join() + } + + @Test + fun `reset sync keeps the full latest page size`() = runTest { + val api = GatedMessagesApi() + val initial = MessageWindowLogic.createState("s").copy(requiresLatestReset = true) + val store = MessageWindowStore("s", api, backgroundScope, initialState = initial) + + val sync = launch { store.syncTail() } + runCurrent() + assertEquals(1, api.requests.size) + assertTrue(api.requests.single() is MessagesQuery.Latest) + assertEquals(PAGE_SIZE, (api.requests.single() as MessagesQuery.Latest).limit) + + api.release(latestPage(listOf(agentRow("a-1", 1, 1000)), epoch = 1)) + sync.join() + } + @Test fun `concurrent syncTail calls coalesce into a single run`() = runTest { val api = GatedMessagesApi() diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt index 06df5ded..fd63ef1d 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt @@ -16,6 +16,8 @@ const val HISTORY_WINDOW_SIZE: Int = 600 const val OLDER_LOAD_WINDOW_SIZE: Int = 800 const val AGENT_RUN_WINDOW_SIZE: Int = 800 const val PAGE_SIZE: Int = 200 +/** Request size for a genuinely cold latest page, prioritizing first paint. */ +const val INITIAL_PAGE_SIZE: Int = 20 enum class MessageViewMode(val wire: String) { /** Following the live bottom; trims from the top. */ diff --git a/docs/api/client-contract/pagination.md b/docs/api/client-contract/pagination.md index 03e0a721..f8f6e194 100644 --- a/docs/api/client-contract/pagination.md +++ b/docs/api/client-contract/pagination.md @@ -98,7 +98,10 @@ Client contract: Run after connect, after an SSE `resume: 'gap'` handshake, on session open, and when told to (`messages-invalidated`). Reference: `runTailSync` in `web/src/lib/message-window-store.ts`. -1. **No usable state** (no newest cursor, no cached epoch, or a reset is pending): `GET …/messages?limit=200` (latest), replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. +1. **No usable state** (no newest cursor, no cached epoch, or a reset is pending): + - For a genuinely cold window with no cursor and no pending structural reset, request `GET …/messages?limit=20` (latest) so the newest usable conversation content can paint quickly. + - For a pending structural reset, request the normal full latest page with `limit=200`. + - Replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. 2. **Have cursor + epoch**: loop - `GET …/messages?afterSeq&afterAt&epoch[&untilSeq&untilAt]&limit=200`, where `after` starts at your newest cursor and `until` is the `snapshotHead*` captured from the **first** response of the loop (fixes the target so the loop terminates). - `page.reset` or `direction: 'latest'` ⇒ replace the window with this page; stop. @@ -115,7 +118,8 @@ Constants from the web reference (`web/src/lib/message-window-store.ts`): | Constant | Value | Meaning | |---|---|---| -| `PAGE_SIZE` | 200 | Request size for every page fetch. | +| `INITIAL_PAGE_SIZE` | 20 | Request size for the cold latest page used to prioritize first paint. | +| `PAGE_SIZE` | 200 | Request size for ordinary latest/reset, forward, and older-page fetches. | | `VISIBLE_WINDOW_SIZE` | 400 | Max regular rows kept in **tail** mode (following live bottom). | | `HISTORY_WINDOW_SIZE` | 600 | Max regular rows kept in **history** mode (user scrolled back). | | `OLDER_LOAD_WINDOW_SIZE` | 800 | Temporary cap while an older page is being merged (prepend). | @@ -126,7 +130,7 @@ Rules: - **Tail mode** trims from the top (oldest dropped). Dropping rows ⇒ set `hasMore: true` and recompute the older-page cursor from the oldest kept row. - **History mode** trims from the bottom (newest dropped). Dropping newest rows means your window no longer reaches the tail ⇒ flag "latest reset required": on returning to tail mode, discard cursors and fetch a fresh latest page rather than trusting stale ones. - **Queued rows are never trimmed** (user messages with `invokedAt === null`, see below) — they are re-merged after every trim. -- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; on re-activation with a persisted cursor, still fetch a fresh latest page first (another client may have advanced the session by many pages) and reconcile. +- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; a genuinely cold window requests a small latest page for first paint, while structural resets and re-activation with a persisted cursor use the ordinary full latest page and reconcile. Another client may have advanced the session by many pages. --- diff --git a/e2e/cold-initial-tail.spec.ts b/e2e/cold-initial-tail.spec.ts new file mode 100644 index 00000000..41ee115a --- /dev/null +++ b/e2e/cold-initial-tail.spec.ts @@ -0,0 +1,32 @@ +import { expect, test } from '@playwright/test' + +test('cold sessions request a small latest page and keep older loads at 200', async ({ page }) => { + await page.goto('/e2e-fixtures/history-load-fixture.html?coldInitial=1') + const viewport = page.locator('.app-scroll-y') + await expect(viewport).toBeVisible() + + await expect.poll(async () => await page.evaluate(() => window.__probe.requests.length)).toBeGreaterThan(0) + await expect.poll(async () => await page.evaluate(() => ({ + direction: window.__probe.requests[0]?.direction ?? null, + limit: window.__probe.requests[0]?.limit ?? null, + childCount: document.querySelector('.happy-thread-messages')?.childElementCount ?? 0 + }))).toEqual({ + direction: 'latest', + limit: 20, + childCount: expect.any(Number) + }) + + await expect.poll(async () => await page.evaluate(() => window.__probe.windowState().messageCount)).toBe(20) + await expect(page.getByText('Fixture message 1200', { exact: true })).toBeVisible() + + // Call the same loadMore callback that the top sentinel invokes. The + // dedicated history-load suite covers pointer/scroll gesture detection; + // this regression should isolate the page-size contract without relying + // on IntersectionObserver timing. + await page.evaluate(() => window.__probe.loadMore()) + + await expect.poll(async () => await page.evaluate(() => { + const older = window.__probe.requests.filter((request) => request.direction === 'before') + return older[0]?.limit ?? null + })).toBe(200) +}) diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift index c92d587c..fbddf6ab 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift @@ -242,9 +242,12 @@ public actor MessageWindowController { if !canIncrement { let requestBaseline = baseline() + let latestPageSize = initial.requiresLatestReset || initialCursor != nil + ? MessageWindowConstants.pageSize + : MessageWindowConstants.initialPageSize let response = try await provider.messages( sessionId: sessionId, - query: .latest(limit: MessageWindowConstants.pageSize) + query: .latest(limit: latestPageSize) ) guard isCurrentTailSync(generation) else { return } // A replay gap may have hidden messages-invalidated. Keep a diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift index 93dd9926..b3148d8b 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift @@ -19,8 +19,10 @@ public enum MessageWindowConstants { /// Separate trim bucket for codex `agent-run-*` rows so background-agent /// traces don't evict chat. public static let agentRunWindowSize = 800 - /// Request size for every page fetch. + /// Request size for ordinary latest/reset, forward, and older-page fetches. public static let pageSize = 200 + /// Request size for a genuinely cold latest page, prioritizing first paint. + public static let initialPageSize = 20 } public enum MessageViewMode: String, Sendable { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift index 0e4ef84f..2587b2ac 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift @@ -81,6 +81,69 @@ struct MessageWindowControllerTests { // MARK: - Tail sync + @Test func coldSyncRequestsTheInitialPageSize() async { + let provider = GatedMessagesProvider() + let controller = MessageWindowController(sessionId: "s", provider: provider) + + let sync = Task { await controller.syncTail() } + await provider.waitForRequests(1) + + let requests = await provider.requests + guard case .latest(let limit) = requests[0] else { + Issue.record("cold sync should request the latest page, got \(requests[0])") + return + } + #expect(limit == MessageWindowConstants.initialPageSize) + + await provider.release(latestPage([agentRow(id: "a-1", seq: 1, at: 1000)], epoch: 0)) + await sync.value + } + + @Test func resetAndCachedCursorSyncsKeepTheFullPageSize() async { + let provider = GatedMessagesProvider() + + var resetState = MessageWindowState(sessionId: "reset") + resetState.requiresLatestReset = true + let resetController = MessageWindowController( + sessionId: "reset", + provider: provider, + initialState: resetState + ) + let resetSync = Task { await resetController.syncTail() } + await provider.waitForRequests(1) + let resetRequests = await provider.requests + guard case .latest(let resetLimit) = resetRequests[0] else { + Issue.record("reset sync should request the latest page, got \(resetRequests[0])") + return + } + #expect(resetLimit == MessageWindowConstants.pageSize) + await provider.release(latestPage([agentRow(id: "reset-1", seq: 1, at: 1000)], epoch: 1)) + await resetSync.value + + var cachedState = MessageWindowState(sessionId: "cached") + cachedState.messages = [WindowMessage(wire: agentRow(id: "cached-1", seq: 1, at: 1000))] + cachedState.hasMore = true + cachedState.epoch = 1 + cachedState.oldestPosition = MessagePosition(at: 1000, seq: 1) + cachedState.newestPosition = MessagePosition(at: 1000, seq: 1) + cachedState.preferLatestOnActivation = true + let cachedController = MessageWindowController( + sessionId: "cached", + provider: provider, + initialState: cachedState + ) + let cachedSync = Task { await cachedController.syncTail() } + await provider.waitForRequests(2) + let cachedRequests = await provider.requests + guard case .latest(let cachedLimit) = cachedRequests[1] else { + Issue.record("cached re-entry should request the latest page, got \(cachedRequests[1])") + return + } + #expect(cachedLimit == MessageWindowConstants.pageSize) + await provider.release(latestPage([agentRow(id: "cached-2", seq: 2, at: 2000)], epoch: 1)) + await cachedSync.value + } + @Test func cancellingHistoryDoesNotPublishAnOfflineWarning() async { let provider = GatedMessagesProvider() var initial = MessageWindowState(sessionId: "history") diff --git a/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json b/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json index 93965dd0..fcc105ed 100644 --- a/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json +++ b/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json @@ -31,7 +31,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/fetch-older-before-cursor.json b/shared/fixtures/pagination/fetch-older-before-cursor.json index 2994a5a9..45e78fd6 100644 --- a/shared/fixtures/pagination/fetch-older-before-cursor.json +++ b/shared/fixtures/pagination/fetch-older-before-cursor.json @@ -39,7 +39,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/latest-page-then-sse-ingest.json b/shared/fixtures/pagination/latest-page-then-sse-ingest.json index 3293a500..17f4f2a7 100644 --- a/shared/fixtures/pagination/latest-page-then-sse-ingest.json +++ b/shared/fixtures/pagination/latest-page-then-sse-ingest.json @@ -48,7 +48,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json b/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json index 88afbe11..b3554e56 100644 --- a/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json +++ b/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json b/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json index c9ceeef6..b8978f8e 100644 --- a/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json +++ b/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json @@ -30,7 +30,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json b/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json index 0c571ae9..c5666797 100644 --- a/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json +++ b/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json b/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json index 1b9b20a5..26ce4562 100644 --- a/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json +++ b/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json @@ -66,7 +66,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/reset-latest-preserves-optimistic.json b/shared/fixtures/pagination/reset-latest-preserves-optimistic.json index 63fdd4b2..6146cf08 100644 --- a/shared/fixtures/pagination/reset-latest-preserves-optimistic.json +++ b/shared/fixtures/pagination/reset-latest-preserves-optimistic.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json b/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json index c50a3e08..689be3fc 100644 --- a/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json +++ b/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json @@ -39,7 +39,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json b/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json index f6363cab..863895ad 100644 --- a/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json +++ b/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json @@ -3621,7 +3621,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/web/e2e-fixtures/history-load-fixture.tsx b/web/e2e-fixtures/history-load-fixture.tsx index dccb7ba4..29379e3c 100644 --- a/web/e2e-fixtures/history-load-fixture.tsx +++ b/web/e2e-fixtures/history-load-fixture.tsx @@ -1,6 +1,7 @@ import { useMemo, useRef } from 'react' import ReactDOM from 'react-dom/client' import { AssistantRuntimeProvider } from '@assistant-ui/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import '../src/index.css' import type { ApiClient } from '../src/api/client' import type { DecryptedMessage, MessagesResponse, Session } from '../src/types/api' @@ -27,6 +28,7 @@ const BASE_AT = 1_700_000_000_000 type Probe = { requests: { direction: string; beforeSeq: number | null; limit: number | undefined; at: number }[] + loadMore: () => Promise refetch: () => Promise windowState: () => { messageCount: number; oldestSeq: number | null; newestSeq: number | null } } @@ -39,6 +41,7 @@ declare global { window.__probe = { requests: [], + loadMore: async () => {}, refetch: async () => {}, windowState: () => { const state = getMessageWindowState(SESSION_ID) @@ -62,6 +65,8 @@ window.__probe = { // - ?epochBump=1 — `before` responses carry a newer epoch than the tail, so // every older-page request hits the store's deliberate epoch-mismatch stop // (reset + tail resync, typed terminal stop). +// - ?coldInitial=1 — honor the production cold-open latest-page size instead +// of returning the legacy full 200-row page used by this fixture by default. // - ?slowBefore=1 — delay older-page responses long enough for a normal tail // synchronization to invalidate an in-flight request. const fixtureParams = new URLSearchParams(window.location.search) @@ -69,6 +74,7 @@ const shortPages = fixtureParams.has('shortPages') const failBeforeCount = Number(fixtureParams.get('failBefore') ?? '0') const filteredOlder = fixtureParams.has('filteredOlder') const epochBump = fixtureParams.has('epochBump') +const coldInitial = fixtureParams.has('coldInitial') const slowBefore = fixtureParams.has('slowBefore') let beforeAttempts = 0 @@ -118,10 +124,11 @@ const fakeApi = { afterAt?: number | null afterSeq?: number | null }): Promise => { - const limit = query.limit ?? 200 + const requestedLimit = query.limit ?? 200 let direction = 'latest' if (query.beforeSeq != null || query.beforeAt != null) direction = 'before' else if (query.afterSeq != null || query.afterAt != null) direction = 'after' + const limit = direction === 'latest' && !coldInitial ? 200 : requestedLimit window.__probe.requests.push({ direction, beforeSeq: query.beforeSeq ?? null, @@ -216,6 +223,7 @@ function FixtureThread() { setViewMode } = useMessages(fakeApi, SESSION_ID) + window.__probe.loadMore = loadMore window.__probe.refetch = refetch const blocksByIdRef = useRef>(new Map()) @@ -285,8 +293,16 @@ function FixtureThread() { ) } +const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false } + } +}) + ReactDOM.createRoot(document.getElementById('root')!).render( - - - + + + + + ) diff --git a/web/src/lib/message-window-store.test.ts b/web/src/lib/message-window-store.test.ts index 713546f8..fb2b721e 100644 --- a/web/src/lib/message-window-store.test.ts +++ b/web/src/lib/message-window-store.test.ts @@ -3,6 +3,7 @@ import type { ApiClient } from '@/api/client' import type { DecryptedMessage, MessagesResponse } from '@/types/api' import { HISTORY_WINDOW_SIZE, + INITIAL_PAGE_SIZE, VISIBLE_WINDOW_SIZE, activateMessageWindow, appendOptimisticMessage, @@ -249,6 +250,49 @@ afterEach(() => { }) describe('message tail synchronization', () => { + it('uses a small cold latest page while keeping older loads at full page size', async () => { + const id = sessionId('cold-initial-page') + const latestMessages = Array.from({ length: INITIAL_PAGE_SIZE }, (_, index) => + makeAgentMessage({ + id: `latest-${index + 1}`, + seq: index + 1, + at: (index + 1) * 1_000 + }) + ) + const older = makeAgentMessage({ id: 'older', seq: 0, at: 0 }) + const getMessages = vi.fn() + .mockResolvedValueOnce(latestResponse(latestMessages, { + epoch: 1, + hasMore: true, + nextBeforeAt: 1_000, + nextBeforeSeq: 1 + })) + .mockResolvedValueOnce(beforeResponse([older], { + epoch: 1, + hasMore: false, + nextBeforeAt: 0, + nextBeforeSeq: 0 + })) + const api = createApi(getMessages) + + await syncTailMessages(api, id) + + expect(getMessages).toHaveBeenCalledWith(id, { limit: INITIAL_PAGE_SIZE }) + expect(getMessageWindowState(id).messages).toHaveLength(INITIAL_PAGE_SIZE) + + await fetchOlderMessages(api, id) + + expect(getMessages).toHaveBeenLastCalledWith(id, { + beforeAt: 1_000, + beforeSeq: 1, + limit: 200 + }) + expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual([ + 'older', + ...latestMessages.map((message) => message.id) + ]) + }) + it('removes the rewound suffix immediately and applies duplicate invalidations once', async () => { const id = sessionId('rewind-suffix') const prefix = makeAgentMessage({ id: 'prefix', seq: 1, at: 1_000 }) diff --git a/web/src/lib/message-window-store.ts b/web/src/lib/message-window-store.ts index 6f6b3a2a..912d4e11 100644 --- a/web/src/lib/message-window-store.ts +++ b/web/src/lib/message-window-store.ts @@ -40,6 +40,7 @@ export type MessageWindowState = { export const VISIBLE_WINDOW_SIZE = 400 export const HISTORY_WINDOW_SIZE = 600 +export const INITIAL_PAGE_SIZE = 20 const AGENT_RUN_WINDOW_SIZE = 800 const OLDER_LOAD_WINDOW_SIZE = 800 const PAGE_SIZE = 200 @@ -693,7 +694,14 @@ async function runTailSync(api: ApiClient, sessionId: string): Promise { if (!canIncrement) { const requestBaseline = new Map(getState(sessionId).messages.map((message) => [message.id, message])) - const response = await api.getMessages(sessionId, { limit: PAGE_SIZE }) + // A cold window has no server cursor yet, so prioritize the latest + // usable messages for first paint. Structural resets and cached + // re-entry keep the full page so their authoritative replacement + // remains unchanged; user-driven older loads still use PAGE_SIZE. + const latestPageSize = initial.requiresLatestReset || initialCursor !== null + ? PAGE_SIZE + : INITIAL_PAGE_SIZE + const response = await api.getMessages(sessionId, { limit: latestPageSize }) if (!isCurrentTailSync(sessionId, generation)) return updateState(sessionId, (previous) => { if (previous.syncGeneration !== generation) return previous