Skip to content

The agent that grows with you

fix(desktop): timeline rail index follows turns created after the session was opened

teknium1f71939403c10
diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
index c62d5181459..036626de45f 100644
--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
@@ -25,13 +25,19 @@ 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)
-/** One bounded metadata page per request; never fetch tool or assistant bodies. */
-export function fetchTimelineIndex(id: string, scope: ProfileScope): Promise<TimelineIndex> {
+/**
+ * One bounded metadata page per request; never fetch tool or assistant bodies.
+ * A complete index is final only up to the turns that existed when it was
+ * read: `beyondRowId` names a prompt the caller has seen (the live tail's
+ * newest, a jump anchor), and a complete index that does not reach it pages
+ * forward from its own cursor instead of answering from the cache.
+ */
+export function fetchTimelineIndex(id: string, scope: ProfileScope, beyondRowId?: number): Promise<TimelineIndex> {
const key = timelineIndexKey(id, scope)
const cached = cache.get(key)
const previous = cached?.complete && cached.expires <= Date.now() ? undefined : cached
- if (cached?.complete && cached.expires > Date.now()) {
+ if (cached?.complete && cached.expires > Date.now() && (beyondRowId === undefined || marksReach(cached.entries, beyondRowId))) {
return Promise.resolve(cached)
}
@@ -126,15 +132,20 @@ export async function previousPromptRowId(
}
let previous: number | null = null
+ let known = -1
for (let page = 0; page < MAX_INDEX_PAGES_PER_LOOKUP; page++) {
- const index = await fetchTimelineIndex(id, scope)
+ const index = await fetchTimelineIndex(id, scope, rowId)
previous = promptBefore(index.entries, rowId)
- if (previous === null || index.complete || marksReach(index.entries, rowId)) {
+ // A complete index that gained nothing cannot name the anchor (an unpersisted
+ // or non-prompt row); stop rather than re-read the tail page.
+ if (previous === null || marksReach(index.entries, rowId) || (index.complete && index.entries.length === known)) {
return previous
}
+
+ known = index.entries.length
}
return previous
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx
new file mode 100644
index 00000000000..de9512673ff
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx
@@ -0,0 +1,72 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { api, view } = vi.hoisted(() => ({
+ api: vi.fn(),
+ view: {
+ $storedId: { get: () => 'stored-a', listen: () => () => {} },
+ $runtimeId: { get: () => 'runtime-a', listen: () => () => {} },
+ $messages: undefined as unknown
+ }
+}))
+
+vi.mock('@/api/client', () => ({ capabilityScoped: (scope: object) => scope, hermesApi: api }))
+vi.mock('@/app/chat/session-view', () => ({ useSessionView: () => view }))
+vi.mock('@/store/profile', () => ({ $activeGatewayProfile: atom('default') }))
+vi.mock('@/store/session', () => ({ $connection: atom({ mode: 'local' }), getSessionOwnerHint: () => undefined }))
+vi.mock('@/store/transcript-tail', () => ({ transcriptTailState: () => undefined }))
+
+const page = (ids: number[], more = false) => ({
+ entries: ids.map(id => ({ row_id: id, preview: `Prompt ${id}` })),
+ pagination: { next_cursor: more ? ids.at(-1) : null, has_more: more }
+})
+
+beforeEach(() => {
+ vi.resetModules()
+ vi.useFakeTimers()
+ api.mockReset()
+})
+
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('timeline history index', () => {
+ it('follows prompts persisted after the complete index was read', async () => {
+ const $messages = atom<Array<{ id: string; role: string; rowId?: number }>>([
+ { id: 'u1', role: 'user', rowId: 1 },
+ { id: 'u2', role: 'user', rowId: 2 }
+ ])
+
+ view.$messages = $messages
+ api.mockResolvedValueOnce(page([1, 2])).mockResolvedValueOnce(page([1, 2, 3]))
+ const { useTimelineHistory } = await import('./use-timeline-history')
+ const { result } = renderHook(() => useTimelineHistory())
+
+ await act(async () => {
+ vi.advanceTimersByTime(200)
+ await Promise.resolve()
+ })
+ expect(result.current.complete).toBe(true)
+ expect(result.current.entries?.map(entry => entry.rowId)).toEqual([1, 2])
+ expect(api).toHaveBeenCalledTimes(1)
+
+ // A new turn lands in the live tail: the rail's index pages forward once,
+ // from its own cursor, without a timer.
+ await act(async () => {
+ $messages.set([...$messages.get(), { id: 'a2', role: 'assistant' }, { id: 'u3', role: 'user', rowId: 3 }])
+ await Promise.resolve()
+ })
+ expect(api).toHaveBeenCalledTimes(2)
+ expect(result.current.entries?.map(entry => entry.rowId)).toEqual([1, 2, 3])
+
+ // Streaming into the newest turn moves nothing: no further request.
+ await act(async () => {
+ $messages.set([...$messages.get(), { id: 'a3', role: 'assistant' }])
+ await Promise.resolve()
+ })
+ expect(api).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
index 2582e152338..fd51939c6a9 100644
--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
@@ -33,13 +33,13 @@ export function useTimelineHistory() {
const [index, setIndex] = useState<{ key: string; value: TimelineIndex } | null>(null)
const [failed, setFailed] = useState<string | null>(null)
- const loadMore = useCallback(async () => {
+ const loadMore = useCallback(async (beyondRowId?: number) => {
if (!storedId) {
return
}
try {
- const value = await fetchTimelineIndex(storedId, scope)
+ const value = await fetchTimelineIndex(storedId, scope, beyondRowId)
if (view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId) {
setIndex({ key, value })
@@ -67,5 +67,34 @@ export function useTimelineHistory() {
const value = index?.key === key ? index.value : cachedTimelineIndex(key)
+ // The newest persisted prompt in the live tail — a scalar, so streaming
+ // deltas never re-run this. Each new turn moves it once.
+ const newestPromptRowId = useStoreSelector(view.$messages, messages => {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i]!
+
+ if (message.role === 'user' && message.rowId !== undefined) {
+ return message.rowId
+ }
+ }
+
+ return undefined
+ })
+
+ // A complete index is a snapshot of the turns that existed when it was
+ // read. When the live tail grows past its last mark (entries are
+ // chronological), page it forward once per new prompt — no timer; an
+ // incomplete index still pages on demand.
+ const last = value?.entries.at(-1)?.rowId
+ const stale = value?.complete === true && newestPromptRowId !== undefined && (last === undefined || last < newestPromptRowId)
+
+ useEffect(() => {
+ if (!stale || failed === key) {
+ return
+ }
+
+ void loadMore(newestPromptRowId)
+ }, [stale, failed, key, loadMore, newestPromptRowId])
+
return { ...value, failed: failed === key, loadMore }
}