The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(desktop): hydrate transcripts with a small tail page + on-demand older-page backfill
Teknium577093def22c
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 9f77e4f6177..1a8f60f74d5 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -43,6 +43,8 @@ import {sessionPinId,shouldMigrateComposerScope} from '@/store/session'+import { sessionTileDelegate } from '@/store/session-states'+import { $transcriptTailBySessionId } from '@/store/transcript-tail'import { isAuxiliaryWindow, isWatchWindow } from '@/store/windows'import type { ModelOptionsResponse } from '@/types/hermes'@@ -65,6 +67,7 @@ import { ScrollToBottomButton } from './scroll-to-bottom-button'import { useSessionView } from './session-view'import { SessionActionsMenu } from './sidebar/session-actions-menu'import { threadLoadingState } from './thread-loading'+import { backfillOlderTranscriptPage, mergeOlderTranscriptPage, transcriptBackfillAvailable } from './transcript-backfill'import { advanceTranscriptWindow, type TranscriptWindowState } from './transcript-window'interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {@@ -253,9 +256,42 @@ function ChatRuntimeBoundary({const runtimeMessageRepository = useRuntimeMessageRepository(windowedMessages)- const expandWindow = useCallback(() => setWindowPages(pages => pages + 1), [])+ const storedId = useStore(view.$storedId)+ // Subscribed (not read imperatively) so the "Show earlier" affordance+ // appears/retires as tail hydrations and backfill pages record their state.+ const transcriptTailStates = useStore($transcriptTailBySessionId)+ const restBackfillAvailable = Boolean(storedId && transcriptTailStates[storedId]?.possiblyTruncated)++ const expandWindow = useCallback(() => {+ // The store window still holds older messages: growing pages is enough.+ // Otherwise the whole in-memory transcript is already materialized — if+ // the REST tail hydration was truncated, fetch the next older page and+ // PREPEND it to the session store before growing, so the grown window has+ // something older to show. Fire-and-forget: the prepend lands through the+ // session-state write path and re-renders this boundary.+ if (!windowStateRef.current?.window.windowed && runtimeId && storedId && transcriptBackfillAvailable(storedId)) {+ void backfillOlderTranscriptPage({+ storedSessionId: storedId,+ // Stale-response guard: a session switch remounts/re-keys this view;+ // checking the live atoms (not captured props) discards a page that+ // resolves after the user moved on — same pattern as isCurrentResume.+ isCurrent: () => view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId,+ applyOlderPage: olderPage => {+ sessionTileDelegate()?.updateSession(runtimeId, state => {+ const merged = mergeOlderTranscriptPage(state.messages, olderPage)++ return merged === state.messages ? state : { ...state, messages: merged }+ })+ }+ })+ }++ setWindowPages(pages => pages + 1)+ }, [runtimeId, storedId, view])++ const olderAvailable = windowed || restBackfillAvailable- const transcriptWindow = useMemo(() => ({ olderAvailable: windowed, expandWindow }), [expandWindow, windowed])+ const transcriptWindow = useMemo(() => ({ olderAvailable, expandWindow }), [expandWindow, olderAvailable])const runtime = useIncrementalExternalStoreRuntime<ThreadMessage>({messageRepository: runtimeMessageRepository,diff --git a/apps/desktop/src/app/chat/transcript-backfill.test.ts b/apps/desktop/src/app/chat/transcript-backfill.test.tsnew file mode 100644index 00000000000..2864c27192f--- /dev/null+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts@@ -0,0 +1,285 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { ChatMessage } from '@/lib/chat-messages'+import {+ $transcriptTailBySessionId,+ recordTranscriptTail,+ transcriptTailState+} from '@/store/transcript-tail'++import {+ _resetTranscriptBackfillForTests,+ backfillOlderTranscriptPage,+ graftRefreshedTailOntoBackfill,+ mergeOlderTranscriptPage,+ transcriptBackfillAvailable+} from './transcript-backfill'++vi.mock('@/hermes', () => ({+ getOlderSessionMessages: vi.fn()+}))++const { getOlderSessionMessages } = await import('@/hermes')++const chat = (id: string, rowId?: number): ChatMessage => ({+ id,+ role: 'user',+ parts: [{ type: 'text', text: id }],+ ...(rowId !== undefined ? { rowId } : {})+})++// A stored SessionMessage row: distinct timestamps keep toChatMessages ids+// unique and the row id survives as ChatMessage.rowId.+const row = (rowId: number, text: string) => ({+ id: rowId,+ role: 'user' as const,+ content: text,+ timestamp: 1_000 + rowId+})++describe('transcript tail bookkeeping', () => {+ beforeEach(() => {+ $transcriptTailBySessionId.set({})+ })++ it('marks a full page as possibly truncated with the next offset', () => {+ recordTranscriptTail(+ 'stored-1',+ {+ messages: Array.from({ length: 120 }, (_, index) => row(index + 500, `m${index}`)),+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 120 }+ },+ 'work'+ )++ expect(transcriptTailState('stored-1')).toEqual({ nextOffset: 120, possiblyTruncated: true, profile: 'work' })+ expect(transcriptBackfillAvailable('stored-1')).toBe(true)+ })++ it('marks a short page as complete', () => {+ recordTranscriptTail('stored-1', {+ messages: [row(1, 'only')],+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 1 }+ })++ expect(transcriptBackfillAvailable('stored-1')).toBe(false)+ })++ it('treats a legacy response without pagination metadata as complete', () => {+ recordTranscriptTail('stored-1', {+ messages: Array.from({ length: 700 }, (_, index) => row(index, `m${index}`))+ })++ expect(transcriptBackfillAvailable('stored-1')).toBe(false)+ })+})++describe('mergeOlderTranscriptPage', () => {+ it('prepends the older page and preserves chronological order', () => {+ const existing = [chat('c', 3), chat('d', 4)]+ const older = [chat('a', 1), chat('b', 2)]++ expect(mergeOlderTranscriptPage(existing, older).map(m => m.id)).toEqual(['a', 'b', 'c', 'd'])+ })++ it('dedupes rows the store already holds by durable row id', () => {+ const existing = [chat('b', 2), chat('c', 3)]+ // Offset drift: the fetched page overlaps one row we already have.+ const older = [chat('a', 1), chat('b-refetched', 2)]++ expect(mergeOlderTranscriptPage(existing, older).map(m => m.rowId)).toEqual([1, 2, 3])+ })++ it('keeps reference identity when every older row is already present', () => {+ const existing = [chat('a', 1), chat('b', 2)]+ const older = [chat('a', 1)]++ expect(mergeOlderTranscriptPage(existing, older)).toBe(existing)+ })++ it('refuses to paint an older page as the whole transcript', () => {+ const existing: ChatMessage[] = []++ expect(mergeOlderTranscriptPage(existing, [chat('a', 1)])).toBe(existing)+ })+})++describe('graftRefreshedTailOntoBackfill', () => {+ it('keeps the backfilled prefix when the refreshed tail anchors inside it', () => {+ const previous = [chat('a', 1), chat('b', 2), chat('c', 3)]+ const refreshed = [chat('b', 2), chat('c', 3), chat('d', 4)]++ expect(graftRefreshedTailOntoBackfill(refreshed, previous).map(m => m.rowId)).toEqual([1, 2, 3, 4])+ })++ it('returns the refreshed tail unchanged when no anchor is found', () => {+ const previous = [chat('x', 90), chat('y', 91), chat('z', 92)]+ const refreshed = [chat('p', 200), chat('q', 201)]++ expect(graftRefreshedTailOntoBackfill(refreshed, previous)).toBe(refreshed)+ })++ it('returns the refreshed tail when it is not shorter than the previous transcript', () => {+ const previous = [chat('a', 1)]+ const refreshed = [chat('a', 1), chat('b', 2)]++ expect(graftRefreshedTailOntoBackfill(refreshed, previous)).toBe(refreshed)+ })+})++describe('backfillOlderTranscriptPage', () => {+ beforeEach(() => {+ $transcriptTailBySessionId.set({})+ _resetTranscriptBackfillForTests()+ vi.mocked(getOlderSessionMessages).mockReset()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ const truncatedTail = (nextOffset = 120) => {+ recordTranscriptTail('stored-1', {+ messages: Array.from({ length: 120 }, (_, index) => row(index + nextOffset, `tail${index}`)),+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 120 }+ })+ }++ it('fetches the recorded next offset and applies the converted page', async () => {+ truncatedTail()+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: [row(1, 'older-1'), row(2, 'older-2')],+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 2 },+ session_id: 'stored-1'+ } as never)++ const applyOlderPage = vi.fn()++ const applied = await backfillOlderTranscriptPage({+ storedSessionId: 'stored-1',+ isCurrent: () => true,+ applyOlderPage+ })++ expect(applied).toBe(true)+ expect(getOlderSessionMessages).toHaveBeenCalledWith('stored-1', undefined, 120)+ expect(applyOlderPage).toHaveBeenCalledTimes(1)+ expect(applyOlderPage.mock.calls[0][0].map((m: ChatMessage) => m.rowId)).toEqual([1, 2])+ // A short older page means the transcript is now fully loaded.+ expect(transcriptBackfillAvailable('stored-1')).toBe(false)+ })++ it('keeps backfill available while pages keep coming back full', async () => {+ truncatedTail()+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: Array.from({ length: 120 }, (_, index) => row(index, `older${index}`)),+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 120 },+ session_id: 'stored-1'+ } as never)++ await backfillOlderTranscriptPage({ storedSessionId: 'stored-1', isCurrent: () => true, applyOlderPage: vi.fn() })++ expect(transcriptTailState('stored-1')).toMatchObject({ nextOffset: 240, possiblyTruncated: true })+ })++ it('falls back to the full transcript when a legacy backend returns no pagination metadata', async () => {+ truncatedTail()+ // Legacy backend: ignores limit/offset/order and one-shots everything.+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: Array.from({ length: 700 }, (_, index) => row(index, `full${index}`)),+ session_id: 'stored-1'+ } as never)++ const applyOlderPage = vi.fn()++ const applied = await backfillOlderTranscriptPage({+ storedSessionId: 'stored-1',+ isCurrent: () => true,+ applyOlderPage+ })++ expect(applied).toBe(true)+ expect(applyOlderPage.mock.calls[0][0]).toHaveLength(700)+ // One-shot full transcript: the REST action retires.+ expect(transcriptBackfillAvailable('stored-1')).toBe(false)+ })++ it('discards a stale response after a session switch', async () => {+ truncatedTail()+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: [row(1, 'older-1')],+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },+ session_id: 'stored-1'+ } as never)++ const applyOlderPage = vi.fn()++ const applied = await backfillOlderTranscriptPage({+ storedSessionId: 'stored-1',+ // The user switched sessions while the page was in flight.+ isCurrent: () => false,+ applyOlderPage+ })++ expect(applied).toBe(false)+ expect(applyOlderPage).not.toHaveBeenCalled()+ // Bookkeeping untouched: the next visit re-records the tail anyway.+ expect(transcriptTailState('stored-1')).toMatchObject({ nextOffset: 120, possiblyTruncated: true })+ })++ it('shares one in-flight fetch per stored session', async () => {+ truncatedTail()++ let resolvePage: (value: unknown) => void = () => {}++ vi.mocked(getOlderSessionMessages).mockReturnValue(+ new Promise(resolve => {+ resolvePage = resolve+ }) as never+ )++ const first = backfillOlderTranscriptPage({ storedSessionId: 'stored-1', isCurrent: () => true, applyOlderPage: vi.fn() })+ const second = backfillOlderTranscriptPage({ storedSessionId: 'stored-1', isCurrent: () => true, applyOlderPage: vi.fn() })++ expect(second).toBe(first)+ expect(getOlderSessionMessages).toHaveBeenCalledTimes(1)++ resolvePage({+ messages: [row(1, 'older-1')],+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },+ session_id: 'stored-1'+ })++ await first+ })++ it('resolves false without fetching when the tail is not truncated', async () => {+ recordTranscriptTail('stored-1', {+ messages: [row(1, 'only')],+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 1 }+ })++ const applied = await backfillOlderTranscriptPage({+ storedSessionId: 'stored-1',+ isCurrent: () => true,+ applyOlderPage: vi.fn()+ })++ expect(applied).toBe(false)+ expect(getOlderSessionMessages).not.toHaveBeenCalled()+ })++ it('survives a fetch failure and leaves the action retryable', async () => {+ truncatedTail()+ vi.mocked(getOlderSessionMessages).mockRejectedValue(new Error('network down'))++ const applied = await backfillOlderTranscriptPage({+ storedSessionId: 'stored-1',+ isCurrent: () => true,+ applyOlderPage: vi.fn()+ })++ expect(applied).toBe(false)+ expect(transcriptBackfillAvailable('stored-1')).toBe(true)+ })+})diff --git a/apps/desktop/src/app/chat/transcript-backfill.ts b/apps/desktop/src/app/chat/transcript-backfill.tsnew file mode 100644index 00000000000..82205b61af5--- /dev/null+++ b/apps/desktop/src/app/chat/transcript-backfill.ts@@ -0,0 +1,165 @@+/**+ * ON-DEMAND OLDER-PAGE BACKFILL for the transcript window.+ *+ * Tail hydration (`getLatestSessionMessages`) loads only the newest page of a+ * session. "Show earlier" first pages the DOM budget, then the in-memory store+ * window — and when the whole in-memory transcript is materialized but the+ * REST hydration was truncated (`transcript-tail` bookkeeping), this module+ * fetches the next older page and prepends it to the session store.+ *+ * Offsets follow the backend's `order: 'latest'` semantics: measured back+ * from the NEWEST persisted row. Rows persisted after hydration shift that+ * origin, so a fetched page can overlap rows we already hold — the prepend+ * dedupes by durable row id (falling back to the rendered message id) and+ * the offset still advances by the fetched count, which self-corrects the+ * drift on the next page.+ */++import { getOlderSessionMessages } from '@/hermes'+import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'+import { recordTranscriptBackfillPage, transcriptTailState } from '@/store/transcript-tail'++/** Older rows likely exist beyond what the in-memory store holds. */+export function transcriptBackfillAvailable(storedSessionId: null | string | undefined): boolean {+ return Boolean(transcriptTailState(storedSessionId)?.possiblyTruncated)+}++/**+ * Prepend an older page onto the in-memory transcript, deduplicating rows the+ * store already holds (offset drift makes overlap normal — see module doc).+ * Preserves reference identity when nothing changes: handing React a fresh+ * array of the same messages re-renders the runtime for nothing.+ */+export function mergeOlderTranscriptPage(existing: ChatMessage[], olderPage: ChatMessage[]): ChatMessage[] {+ // Backfill only makes sense under an already-hydrated tail. An empty store+ // here means the session was swapped or wiped mid-fetch; prepending would+ // paint the older page as the whole conversation.+ if (existing.length === 0 || olderPage.length === 0) {+ return existing+ }++ const existingRowIds = new Set<number>()+ const existingIds = new Set<string>()++ for (const message of existing) {+ if (message.rowId !== undefined) {+ existingRowIds.add(message.rowId)+ }++ existingIds.add(message.id)+ }++ const fresh = olderPage.filter(+ message => !(message.rowId !== undefined && existingRowIds.has(message.rowId)) && !existingIds.has(message.id)+ )++ if (fresh.length === 0) {+ return existing+ }++ return [...fresh, ...existing]+}++/**+ * Re-anchor a refreshed TAIL onto a transcript that has backfilled older+ * pages. Background refreshes and post-turn rehydrates re-read only the+ * newest page; replacing the store with that page outright would silently+ * drop everything "Show earlier" already loaded. Find where the refreshed+ * tail begins inside the previous transcript and keep the older prefix.+ * When no anchor is found (compaction rewrite, different session), the+ * refreshed tail is authoritative — same behavior as before backfill existed.+ */+export function graftRefreshedTailOntoBackfill(refreshedTail: ChatMessage[], previous: ChatMessage[]): ChatMessage[] {+ if (refreshedTail.length === 0 || previous.length === 0) {+ return refreshedTail+ }++ const first = refreshedTail[0]+ const anchor = previous.findIndex(+ message =>+ (first.rowId !== undefined && message.rowId !== undefined && message.rowId === first.rowId) ||+ message.id === first.id+ )++ if (anchor <= 0) {+ return refreshedTail+ }++ return [...previous.slice(0, anchor), ...refreshedTail]+}++export interface BackfillRequest {+ /** Durable stored session id — the tail bookkeeping key. */+ storedSessionId: string+ /** Stale-response guard: called after the fetch resolves; when it reports+ * false (the user switched sessions mid-flight) the page is discarded and+ * the bookkeeping is left untouched, mirroring the isCurrentResume()+ * pattern in use-session-actions. */+ isCurrent: () => boolean+ /** Apply the converted older page to the session's message store. The+ * callback owns WHERE the messages live (session-state cache vs the global+ * draft atom) and must merge via `mergeOlderTranscriptPage`. */+ applyOlderPage: (olderPage: ChatMessage[]) => void+}++// One fetch per stored session at a time. Keyed by stored id (not runtime id)+// so a mid-fetch runtime rebind cannot double-fetch the same page.+const inflightByStoredSessionId = new Map<string, Promise<boolean>>()++/** Test-only: drop in-flight guards between cases. */+export function _resetTranscriptBackfillForTests(): void {+ inflightByStoredSessionId.clear()+}++/**+ * Fetch the next older page for a session and prepend it via+ * `applyOlderPage`. Resolves true when a page was applied. Concurrent calls+ * for the same session share one fetch.+ */+export function backfillOlderTranscriptPage(request: BackfillRequest): Promise<boolean> {+ const { storedSessionId } = request+ const inflight = inflightByStoredSessionId.get(storedSessionId)++ if (inflight) {+ return inflight+ }++ const run = (async () => {+ const tail = transcriptTailState(storedSessionId)++ if (!tail?.possiblyTruncated) {+ return false+ }++ let page++ try {+ page = await getOlderSessionMessages(storedSessionId, tail.profile, tail.nextOffset)+ } catch {+ // Non-fatal: the action stays available and the next click retries.+ return false+ }++ // Session switched while the page was in flight: discard it entirely.+ // The bookkeeping stays untouched so a later re-visit (which re-records+ // the tail on hydration anyway) starts from consistent state.+ if (!request.isCurrent()) {+ return false+ }++ // A response without pagination metadata is a legacy backend that ignored+ // the paging query and returned the FULL transcript one-shot. The merge+ // below prepends whatever prefix the store is missing, and the recorded+ // state marks the session fully loaded so the REST action retires.+ recordTranscriptBackfillPage(storedSessionId, page)+ request.applyOlderPage(toChatMessages(page.messages))++ return true+ })().finally(() => {+ inflightByStoredSessionId.delete(storedSessionId)+ })++ inflightByStoredSessionId.set(storedSessionId, run)++ return run+}diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 2239ea527d2..0db1ef4debb 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -1,6 +1,7 @@import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'import { getLatestSessionMessages } from '@/hermes'import { preserveLocalAssistantErrors, sealOpenToolParts, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'@@ -104,7 +105,13 @@ export async function reconcileActiveTranscript({updateSessionState(runtimeSessionId,- state => ({ ...state, messages: preserveLocalAssistantErrors(messages, state.messages) }),+ state => ({+ ...state,+ // The refresh re-reads only the newest tail page; graft it onto any+ // older pages "Show earlier" already backfilled instead of clobbering+ // them (see transcript-backfill).+ messages: preserveLocalAssistantErrors(graftRefreshedTailOntoBackfill(messages, state.messages), state.messages)+ }),storedSessionId)} catch {diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex d2a6ead87a4..2ad4456c129 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -13,6 +13,7 @@ import { useQueryClient } from '@tanstack/react-query'import { type CSSProperties, lazy, type ReactNode, Suspense, useCallback, useEffect, useMemo, useRef } from 'react'import { useLocation, useNavigate } from 'react-router'+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'import { formatRefValue } from '@/components/assistant-ui/directive-text'import { BootFailureOverlay } from '@/components/boot-failure-overlay'import { DesktopInstallOverlay } from '@/components/desktop-install-overlay'@@ -355,7 +356,15 @@ export function ContribWiring({ children }: { children: ReactNode }) {const messages = toChatMessages(latest.messages)updateSessionState(runtimeSessionId,- state => ({ ...state, messages: preserveLocalAssistantErrors(messages, state.messages) }),+ state => ({+ ...state,+ // Post-turn rehydrate reads only the newest tail page — graft it+ // onto any backfilled older pages instead of dropping them.+ messages: preserveLocalAssistantErrors(+ graftRefreshedTailOntoBackfill(messages, state.messages),+ state.messages+ )+ }),storedSessionId)diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex ee7869f6971..ccdadffcadb 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'import type { NavigateFunction } from 'react-router'+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'import { revealTreePane } from '@/components/pane-shell/tree/store'import { deleteSession, getAllSessionMessages, getLatestSessionMessages, setSessionArchived } from '@/hermes'import { useI18n } from '@/i18n'@@ -889,7 +890,13 @@ export function useSessionActions({persistedMatchesActivatedSession &&(persisted.messages.length || !activatedMessages.length)) {- const persistedMessages = toChatMessages(persisted.messages)+ // The REST hydration is a newest-tail page; graft it onto any+ // older pages the previous view already backfilled so+ // re-activating a scrolled-back session keeps its history.+ const persistedMessages = graftRefreshedTailOntoBackfill(+ toChatMessages(persisted.messages),+ cachedViewState.messages+ )const runtimeMessages = toChatMessages(activated.messages)const previousMessages = removeRepresentedLocalLiveProjection(cachedViewState.messages, activated)@@ -1075,8 +1082,14 @@ export function useSessionActions({? preserveLocalPendingTurnMessages($messages.get(), resumeStartMessages): $messages.get()- prefetchedTranscriptMessages = toChatMessages(prefetchedResult.messages)- localSnapshot = reconcileAuthoritativeChatMessages(prefetchedTranscriptMessages, previousMessages)+ // Tail page + previously backfilled prefix (same-session re-resume).+ const graftedPrefetch = graftRefreshedTailOntoBackfill(+ toChatMessages(prefetchedResult.messages),+ previousMessages+ )++ prefetchedTranscriptMessages = graftedPrefetch+ localSnapshot = reconcileAuthoritativeChatMessages(graftedPrefetch, previousMessages)prefetchApplied = trueprefetchedStoredSessionId = prefetchedResult.session_id || storedSessionId}diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.tsindex de02dacc473..f2ea9899ff6 100644--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@ -13,9 +13,12 @@ import {getGlobalModelOptions,getHermesConfig,getHermesConfigDefaults,+ getLatestSessionMessages,+ getOlderSessionMessages,getProfiles,getSessionMessages,getStatus,+ LATEST_SESSION_MESSAGES_LIMIT,listAllProfileSessions,listSessions,listSidebarSessions,@@ -26,6 +29,7 @@ import {triggerCronJob} from './hermes'import { refreshActiveProfile } from './store/profile'+import { $transcriptTailBySessionId, transcriptTailState } from './store/transcript-tail'const emptySessionsResponse = {limit: 0,@@ -350,6 +354,47 @@ describe('Hermes REST helpers', () => {})})+ it('hydrates the latest transcript with a small tail page (120, latest, compacted rows included)', async () => {+ api.mockResolvedValue({+ messages: [],+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 0 },+ session_id: 'session-1'+ })++ await getLatestSessionMessages('session-1', 'xiaoxuxu')++ expect(LATEST_SESSION_MESSAGES_LIMIT).toBe(120)+ expect(api).toHaveBeenCalledWith({+ path: '/api/sessions/session-1/messages?profile=xiaoxuxu&limit=120&order=latest&include_compacted=true',+ profile: 'xiaoxuxu'+ })+ })++ it('records tail truncation state under the requested and resolved session ids', async () => {+ $transcriptTailBySessionId.set({})+ api.mockResolvedValue({+ messages: Array.from({ length: 120 }, (_, index) => ({ content: `m${index}`, id: index, role: 'user' })),+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 120 },+ session_id: 'resolved-1'+ })++ await getLatestSessionMessages('prefix-1')++ expect(transcriptTailState('prefix-1')).toMatchObject({ nextOffset: 120, possiblyTruncated: true })+ expect(transcriptTailState('resolved-1')).toMatchObject({ nextOffset: 120, possiblyTruncated: true })+ })++ it('requests older pages backwards from the newest message', async () => {+ api.mockResolvedValue({ messages: [], session_id: 'session-1' })++ await getOlderSessionMessages('session-1', 'xiaoxuxu', 240)++ expect(api).toHaveBeenCalledWith({+ path: '/api/sessions/session-1/messages?profile=xiaoxuxu&limit=120&offset=240&order=latest&include_compacted=true',+ profile: 'xiaoxuxu'+ })+ })+it('passes bounded transcript pagination through to the backend', async () => {api.mockResolvedValue({ messages: [], session_id: 'session-1' })diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 8234860c9d3..3273dd7188b 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -1,6 +1,7 @@import { JsonRpcGatewayClient } from '@hermes/shared'import { reconnectBackoffDelayMs } from '@/lib/reconnect-backoff'+import { recordTranscriptTail } from '@/store/transcript-tail'import type {ActionResponse,ActionStatusResponse,@@ -729,11 +730,58 @@ export function getSessionMessages(})}+/**+ * The initial hydration page: enough tail to fill the transcript window a few+ * times over, small enough that opening a long session doesn't ship (and+ * convert) hundreds of rows nobody has scrolled to. Older rows load on demand+ * via `getOlderSessionMessages` when "Show earlier" exhausts the in-memory+ * store (see app/chat/transcript-backfill).+ */+export const LATEST_SESSION_MESSAGES_LIMIT = 120+export function getLatestSessionMessages(id: string, profile?: string | null): Promise<SessionMessagesResponse> {// includeCompacted: durable display history must include rows preserved by// in-place compaction (active=0, compacted=1); without them the transcript// silently ends at the compaction boundary and earlier turns are unreachable.- return getSessionMessages(id, profile, { limit: 500, order: 'latest', includeCompacted: true })+ return getSessionMessages(id, profile, {+ limit: LATEST_SESSION_MESSAGES_LIMIT,+ order: 'latest',+ includeCompacted: true+ }).then(page => {+ // Record whether the tail was truncated (page came back full) and where+ // the next older page starts, so "Show earlier" can backfill over REST+ // (app/chat/transcript-backfill). Keyed under both the requested id and+ // the resolved id — callers hold either.+ recordTranscriptTail(id, page, profile)++ if (page.session_id && page.session_id !== id) {+ recordTranscriptTail(page.session_id, page, profile)+ }++ return page+ })+}++/**+ * One page of messages OLDER than the `offset` newest rows.+ *+ * Backend semantics (`_handle_session_messages` → `SessionDB.get_messages`+ * with `latest=True`): the offset is measured back from the NEWEST message+ * and the selected page is returned in chronological order. So after a tail+ * hydration of N rows, `getOlderSessionMessages(id, profile, N)` returns the+ * page immediately preceding it, ready to prepend.+ *+ * Legacy backends without pagination support return the full transcript and+ * no `pagination` metadata — callers detect that via the missing field and+ * treat the response as the complete history (see transcript-backfill).+ */+export function getOlderSessionMessages(+ id: string,+ profile: string | null | undefined,+ offset: number,+ limit: number = LATEST_SESSION_MESSAGES_LIMIT+): Promise<SessionMessagesResponse> {+ return getSessionMessages(id, profile, { includeCompacted: true, limit, offset, order: 'latest' })}export async function getAllSessionMessages(diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.tsnew file mode 100644index 00000000000..fc1794743ac--- /dev/null+++ b/apps/desktop/src/store/transcript-tail.ts@@ -0,0 +1,84 @@+/**+ * REST TAIL-HYDRATION BOOKKEEPING — keyed by STORED session id.+ *+ * `getLatestSessionMessages` loads a small newest-first page instead of a+ * fixed 500-row transcript. When that page comes back full (returned ===+ * limit), older rows likely exist on the backend; this store records that+ * fact plus the offset the next older page starts at, so the transcript+ * window's "Show earlier" action knows to backfill over REST once the+ * in-memory store is fully materialized (see app/chat/transcript-backfill).+ *+ * Offsets use the backend's `order: 'latest'` semantics: measured back from+ * the NEWEST row, with each page returned in chronological order — so the+ * page immediately older than N already-loaded tail rows starts at offset N.+ */++import { atom } from 'nanostores'++import type { SessionMessagesResponse } from '@/types/hermes'++export interface TranscriptTailState {+ /** Offset (back from the newest row) where the next older page starts. */+ nextOffset: number+ /** The last hydration page was exactly the page limit, so older rows+ * likely exist beyond what the in-memory store holds. */+ possiblyTruncated: boolean+ /** Owning profile captured at hydration time, so a later backfill routes+ * its REST read to the same backend that served the tail. */+ profile?: null | string+}++export const $transcriptTailBySessionId = atom<Record<string, TranscriptTailState>>({})++type TailPage = Pick<SessionMessagesResponse, 'messages' | 'pagination'>++function tailStateFromPage(page: TailPage, profile?: null | string): TranscriptTailState {+ const pagination = page.pagination++ // No pagination metadata is a legacy backend that ignored the paging query+ // and returned the full transcript: nothing is truncated.+ if (!pagination || pagination.limit <= 0) {+ return { nextOffset: page.messages.length, possiblyTruncated: false, profile }+ }++ return {+ nextOffset: pagination.offset + page.messages.length,+ possiblyTruncated: page.messages.length >= pagination.limit,+ profile+ }+}++/** Record the outcome of a tail hydration (`getLatestSessionMessages`). */+export function recordTranscriptTail(storedSessionId: string, page: TailPage, profile?: null | string): void {+ if (!storedSessionId) {+ return+ }++ const current = $transcriptTailBySessionId.get()+ $transcriptTailBySessionId.set({ ...current, [storedSessionId]: tailStateFromPage(page, profile) })+}++/** Advance the bookkeeping after one older backfill page landed. */+export function recordTranscriptBackfillPage(storedSessionId: string, page: TailPage): void {+ const current = $transcriptTailBySessionId.get()+ const previous = current[storedSessionId]+ $transcriptTailBySessionId.set({+ ...current,+ [storedSessionId]: tailStateFromPage(page, previous?.profile)+ })+}++export function transcriptTailState(storedSessionId: null | string | undefined): TranscriptTailState | undefined {+ return storedSessionId ? $transcriptTailBySessionId.get()[storedSessionId] : undefined+}++export function clearTranscriptTail(storedSessionId: string): void {+ const current = $transcriptTailBySessionId.get()++ if (!(storedSessionId in current)) {+ return+ }++ const { [storedSessionId]: _dropped, ...rest } = current+ $transcriptTailBySessionId.set(rest)+}