The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): open history windows keep their earlier prompts reachable
finn76341ce41cda8d9
diff --git a/apps/desktop/src/app/chat/history-window.test.tsx b/apps/desktop/src/app/chat/history-window.test.tsxindex 0cb8f7b50b6..bdf4c29c344 100644--- a/apps/desktop/src/app/chat/history-window.test.tsx+++ b/apps/desktop/src/app/chat/history-window.test.tsx@@ -168,3 +168,59 @@ describe('bounded direct history runtime', () => {}})})++/** A complete metadata page: prompt marks are all the range a reader can walk. */+const index = (rowIds: number[]) => ({+ entries: rowIds.map(rowId => ({ row_id: rowId, preview: `prompt ${rowId}` })),+ pagination: { next_cursor: null, has_more: false }+})++describe('paging earlier from an open history window', () => {+ it('keeps earlier messages reachable after a jump to an older mark', async () => {+ const api = vi+ .spyOn(window.hermesDesktop, 'api')+ .mockResolvedValueOnce(page(4000))+ .mockResolvedValueOnce(index([3880, 4000]))+ .mockResolvedValueOnce({ ...page(3880), pagination: { ...page(3880).pagination, has_older: false } })+ const mounted = mount()+ const live = mounted.view.$messages.get()++ await act(async () => { await mounted.window.revealRow(4000, new AbortController().signal) })+ // The row was reached from the rail, but everything before it is still+ // back there: the transcript's own entry point must not retire.+ expect(mounted.window.olderAvailable).toBe(true)++ let grew = false+ await act(async () => { grew = (await mounted.window.expandWindow()) === true })+ expect(grew).toBe(true)++ const rows = mounted.window.currentMessages?.map(message => message.rowId) ?? []++ expect(rows[0]).toBe(3880)+ expect(rows).toHaveLength(240)+ expect(new Set(rows).size).toBe(240)+ // The prepended page started at the session's first prompt: now retire.+ expect(mounted.window.olderAvailable).toBe(false)+ expect(await mounted.window.expandWindow()).toBe(false)+ expect(mounted.view.$messages.get()).toBe(live)+ expect(api.mock.calls.map(call => call[0].path)).toEqual([+ expect.stringContaining('around?row_id=4000'),+ expect.stringContaining('/timeline?limit=500'),+ expect.stringContaining('around?row_id=3880')+ ])+ })++ it('still retires the entry point when the open window starts at the session top', async () => {+ const api = vi.spyOn(window.hermesDesktop, 'api').mockResolvedValue({+ ...page(1),+ pagination: { ...page(1).pagination, has_older: false }+ })+ const mounted = mount()++ await act(async () => { await mounted.window.revealRow(1, new AbortController().signal) })+ expect(mounted.window.olderAvailable).toBe(false)+ expect(await mounted.window.expandWindow()).toBe(false)+ // Nothing older to walk to: the lookup never even reaches the backend.+ expect(api).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/desktop/src/app/chat/history-window.ts b/apps/desktop/src/app/chat/history-window.tsindex 3874d1d7f32..b13b4ba79bd 100644--- a/apps/desktop/src/app/chat/history-window.ts+++ b/apps/desktop/src/app/chat/history-window.ts@@ -1,9 +1,12 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { capabilityScoped, hermesApi, type ProfileScope } from '@/api/client'+import { previousPromptRowId } from '@/components/assistant-ui/thread/timeline-index'import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'import type { SessionMessagesResponse } from '@/types/hermes'+import { mergeOlderTranscriptPage } from './transcript-backfill'+export const HISTORY_WINDOW_LIMIT = 120/** The around route is intentionally isolated from tail/backfill bookkeeping. */@@ -66,12 +69,13 @@ interface HistoryWindowOptions {/** A single replaceable display page, never merged into the live message store. */export function useHistoryWindow({ scopeKey, storedId, scope, isCurrent }: HistoryWindowOptions) {const lifetime = useMemo(() => ({ scopeKey }), [scopeKey])- const latest = useRef({ lifetime, storedId, scope, isCurrent })- latest.current = { lifetime, storedId, scope, isCurrent }+ const latest = useRef({ lifetime, page: null as HistoryPage | null, storedId, scope, isCurrent })const pending = useRef<AbortController | null>(null)const [selection, setSelection] = useState<{ lifetime: object; page: HistoryPage } | null>(null)const page = selection?.lifetime === lifetime ? selection.page : null+ latest.current = { lifetime, page, storedId, scope, isCurrent }+const cancel = useCallback(() => {pending.current?.abort()pending.current = null@@ -130,5 +134,63 @@ export function useHistoryWindow({ scopeKey, storedId, scope, isCurrent }: Histo}}, [cancel])- return { page, revealRow, returnToLatest }+ /**+ * Prepend the page before this window's first prompt. The anchor's+ * predecessor comes from the same prompt index the rail draws, so the+ * transcript's entry point and the rail page one range. `beforePrepend` is+ * spent in the same commit as the prepend, exactly like a live-page grow.+ */+ const revealOlder = useCallback(async (beforePrepend?: () => void): Promise<boolean> => {+ const captured = latest.current+ const current = captured.page++ // No older rows before this page's first row, or nothing to anchor on yet.+ if (!current?.olderAvailable || !captured.storedId || !captured.isCurrent()) {+ return false+ }++ const anchor = current.messages.find(message => message.role === 'user' && message.rowId !== undefined)?.rowId++ cancel()+ const controller = new AbortController()+ pending.current = controller++ try {+ const rowId = await previousPromptRowId(captured.storedId, captured.scope, anchor)++ if (rowId === null || controller.signal.aborted) {+ return false+ }++ const next = await fetchHistoryWindow(captured.storedId, rowId, captured.scope, controller.signal)+ const messages = mergeOlderTranscriptPage(current.messages, next.messages)++ // A window replaced while this one was in flight owns the display page.+ if (+ controller.signal.aborted ||+ messages === current.messages ||+ latest.current.lifetime !== captured.lifetime ||+ latest.current.page !== current+ ) {+ return false+ }++ beforePrepend?.()+ setSelection({+ lifetime: captured.lifetime,+ page: { messages, olderAvailable: next.olderAvailable, newerAvailable: current.newerAvailable }+ })++ return true+ } catch {+ // Missing/older backend, unreadable page, and an index that cannot name+ // the predecessor all leave the page untouched; the caller reports+ // failure and can retry explicitly.+ return false+ } finally {+ if (pending.current === controller) {pending.current = null}+ }+ }, [cancel])++ return { page, revealRow, returnToLatest, revealOlder }}diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 6c5da9fbb87..ca116f23c35 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -320,8 +320,9 @@ export function ChatRuntimeBoundary({const expandWindow = useCallback(async (beforePrepend?: () => void) => {- // A historical page is not the live tail: never backfill into its store.- if (history.page) {return false}+ // A historical page is not the live tail: its older neighbours come from+ // the prompt range the rail already draws, never from store backfill.+ if (history.page) {return history.revealOlder(beforePrepend)}// Network latency is not scroll intent. Capture at arrival, immediately// before the store prepend, and only grow a window that has a page to show.@@ -367,12 +368,14 @@ export function ChatRuntimeBoundary({return true},- [runtimeId, storedId, tailProfile, view, history.page]+ [runtimeId, storedId, tailProfile, view, history.page, history.revealOlder])- // Page navigation stays on the timeline while inspecting history; the- // existing prepend action is specifically a live-tail operation.- const olderAvailable = !history.page && (windowed || restBackfillAvailable)+ // An open history page carries its own reach: its first prompt is the anchor,+ // and the around window reports whether rows precede it. Reading that as+ // "nothing earlier" (the live-tail flags) retired every way back — the rail+ // still names older marks, so the entry point must stay live here too.+ const olderAvailable = history.page ? history.page.olderAvailable : windowed || restBackfillAvailableconst isHistorical = Boolean(history.page)const newerAvailable = history.page?.newerAvailable ?? falseconst { revealRow, returnToLatest } = historydiff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.tsindex 77fabe128bd..7529ce4e03b 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts@@ -65,4 +65,38 @@ describe('timeline metadata index', () => {await expect(fetchTimelineIndex('session', 'default')).rejects.toThrow('offline')expect((await fetchTimelineIndex('session', 'default')).complete).toBe(true)})++ it('names the mark before an anchor, paging the index once while it cannot cover it', async () => {+ api+ .mockResolvedValueOnce({+ entries: [{ row_id: 10, preview: 'Prompt 10' }, { row_id: 20, preview: 'Prompt 20' }],+ pagination: { next_cursor: 20, has_more: true }+ })+ .mockResolvedValueOnce({+ entries: [{ row_id: 30, preview: 'Prompt 30' }, { row_id: 40, preview: 'Prompt 40' }],+ pagination: { next_cursor: null, has_more: false }+ })+ const { previousPromptRowId } = await import('./timeline-index')++ // The anchor sits past the first page; the lookup advances the shared index.+ expect(await previousPromptRowId('session', 'default', 40)).toBe(30)+ expect(api).toHaveBeenCalledTimes(2)+ // Complete index: a mark before it needs no further request.+ expect(await previousPromptRowId('session', 'default', 20)).toBe(10)+ expect(api).toHaveBeenCalledTimes(2)+ // The oldest mark has nothing before it, and an unknown anchor is never guessed.+ expect(await previousPromptRowId('session', 'default', 10)).toBeNull()+ expect(await previousPromptRowId('session', 'default', undefined)).toBeNull()+ expect(api).toHaveBeenCalledTimes(2)+ })++ it('bounds how far one lookup pages a partially loaded index', async () => {+ api.mockResolvedValue(page(1, true))+ const { previousPromptRowId } = await import('./timeline-index')++ // The anchor is never covered and the index never completes: the lookup+ // stops at its per-lookup ceiling instead of walking the whole session.+ expect(await previousPromptRowId('session', 'default', 99_999)).toBe(1)+ expect(api).toHaveBeenCalledTimes(3)+ })})diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.tsindex ef20323905c..c62d5181459 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts@@ -19,6 +19,9 @@ const requests = new Map<string, Promise<TimelineIndex>>()const MAX_CACHED_SESSIONS = 12const TTL = 60_000+/** One lookup may advance a partially loaded index by this many pages. */+const MAX_INDEX_PAGES_PER_LOOKUP = 3+export const timelineIndexKey = (id: string, scope: ProfileScope) => JSON.stringify([id, scope])export const cachedTimelineIndex = (key: string) => cache.get(key)@@ -87,3 +90,52 @@ export function fetchTimelineIndex(id: string, scope: ProfileScope): Promise<Timreturn request}++/** Marks are chronological, so the greatest id below the anchor is its predecessor. */+function promptBefore(entries: readonly TimelineEntry[], rowId: number): number | null {+ let previous: number | null = null++ for (const entry of entries) {+ if (entry.rowId !== undefined && entry.rowId < rowId) {+ previous = entry.rowId+ }+ }++ return previous+}++/** Whether the loaded marks reach the anchor, i.e. `promptBefore` is its neighbour. */+const marksReach = (entries: readonly TimelineEntry[], rowId: number) =>+ entries.some(entry => entry.rowId !== undefined && entry.rowId >= rowId)++/**+ * The prompt mark immediately before `rowId` on the shared timeline range — the+ * same marks the rail draws, so "Show earlier" and the rail page one range+ * instead of each inventing its own reachability. Pages load oldest-first, so+ * an anchor past the loaded marks advances the index (cached, coalesced with+ * the rail's own loadMore) rather than guessing across the gap. Resolves null+ * only when nothing precedes the anchor, or when the index cannot name it.+ */+export async function previousPromptRowId(+ id: string,+ scope: ProfileScope,+ rowId: number | undefined+): Promise<number | null> {+ if (rowId === undefined || !Number.isSafeInteger(rowId) || rowId <= 0) {+ return null+ }++ let previous: number | null = null++ for (let page = 0; page < MAX_INDEX_PAGES_PER_LOOKUP; page++) {+ const index = await fetchTimelineIndex(id, scope)++ previous = promptBefore(index.entries, rowId)++ if (previous === null || index.complete || marksReach(index.entries, rowId)) {+ return previous+ }+ }++ return previous+}