Skip to content

The agent that grows with you

fix(desktop): reach the opening user turn when Show-earlier hits the top

Brooklyn Nicholson55102bbcbfc2
diff --git a/apps/desktop/src/app/chat/transcript-backfill.test.ts b/apps/desktop/src/app/chat/transcript-backfill.test.ts
index af84a07d341..ab1fef09cf8 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.test.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts
@@ -10,14 +10,16 @@ import {
extendRefreshPageToOverlap,
graftRefreshedTailOntoBackfill,
mergeOlderTranscriptPage,
- transcriptBackfillAvailable
+ transcriptBackfillAvailable,
+ unhideOpeningUserRows
} from './transcript-backfill'
vi.mock('@/hermes', () => ({
- getOlderSessionMessages: vi.fn()
+ getOlderSessionMessages: vi.fn(),
+ getSessionMessages: vi.fn()
}))
-const { getOlderSessionMessages } = await import('@/hermes')
+const { getOlderSessionMessages, getSessionMessages } = await import('@/hermes')
const chat = (id: string, rowId?: number): ChatMessage => ({
id,
@@ -305,6 +307,8 @@ describe('backfillOlderTranscriptPage', () => {
$transcriptTailBySessionId.set({})
_resetTranscriptBackfillForTests()
vi.mocked(getOlderSessionMessages).mockReset()
+ vi.mocked(getSessionMessages).mockReset()
+ vi.mocked(getSessionMessages).mockResolvedValue({ messages: [], session_id: 'stored-1' } as never)
})
afterEach(() => {
@@ -336,7 +340,8 @@ describe('backfillOlderTranscriptPage', () => {
expect(applied).toBe(true)
expect(getOlderSessionMessages).toHaveBeenCalledWith('stored-1', undefined, 120)
- expect(applyOlderPage).toHaveBeenCalledTimes(1)
+ // The exhausted tail also fetches the origin page (see the #96875 tests
+ // below), so assert the older page landed as the FIRST apply.
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)
@@ -574,4 +579,154 @@ describe('backfillOlderTranscriptPage', () => {
expect(applied).toBe(false)
expect(transcriptBackfillAvailable('stored-1')).toBe(true)
})
+
+ // #96875: paging can reach the true top while the opening USER turn is still
+ // missing — compaction projection stamps the durable opening row
+ // display_kind=hidden (hydration drops it) or the last `latest` page begins
+ // at the first assistant row. Once the tail bookkeeping reports the session
+ // fully loaded, the oldest display rows must be fetched once and the opening
+ // user turn prepended so "Show earlier" lands on the greeting.
+ it('fetches the oldest page once paging is exhausted and prepends the opening user turn', async () => {
+ truncatedTail()
+ // The last older page: full paging history ends at the first assistant row.
+ vi.mocked(getOlderSessionMessages).mockResolvedValue({
+ messages: [row(10, 'first-assistant')],
+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },
+ session_id: 'stored-1'
+ } as never)
+ // The oldest page (order=oldest, offset 0) holds the greeting, hidden.
+ vi.mocked(getSessionMessages).mockResolvedValue({
+ messages: [
+ {
+ id: 1,
+ role: 'user' as const,
+ content: 'opening greeting',
+ display_kind: 'hidden',
+ timestamp: 1
+ },
+ row(10, 'first-assistant')
+ ],
+ pagination: { limit: 20, offset: 0, order: 'oldest', returned: 2 },
+ session_id: 'stored-1'
+ } as never)
+
+ const applyOlderPage = vi.fn()
+
+ await backfillOlderTranscriptPage({
+ storedSessionId: 'stored-1',
+ isCurrent: () => true,
+ applyOlderPage
+ })
+
+ expect(getSessionMessages).toHaveBeenCalledWith('stored-1', undefined, {
+ includeCompacted: true,
+ limit: 20,
+ offset: 0,
+ order: 'oldest'
+ })
+ // First call: the regular older page. Second call: the origin page.
+ expect(applyOlderPage).toHaveBeenCalledTimes(2)
+ const originPage = applyOlderPage.mock.calls[1][0] as ChatMessage[]
+ expect(originPage[0].role).toBe('user')
+ expect(originPage[0].parts[0]).toMatchObject({ type: 'text', text: 'opening greeting' })
+ })
+
+ it('does not fetch the oldest page while older pages remain', 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(getSessionMessages).not.toHaveBeenCalled()
+ })
+
+ it('skips the origin prepend when the user switched sessions mid-flight', async () => {
+ truncatedTail()
+ vi.mocked(getOlderSessionMessages).mockResolvedValue({
+ messages: [row(10, 'first-assistant')],
+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },
+ session_id: 'stored-1'
+ } as never)
+
+ const applyOlderPage = vi.fn()
+
+ await backfillOlderTranscriptPage({
+ storedSessionId: 'stored-1',
+ isCurrent: () => false,
+ applyOlderPage
+ })
+
+ // The stale-response guard discards before any apply; no origin fetch ran.
+ expect(applyOlderPage).not.toHaveBeenCalled()
+ })
+
+ it('keeps the already-applied older page when the origin fetch fails', async () => {
+ truncatedTail()
+ vi.mocked(getOlderSessionMessages).mockResolvedValue({
+ messages: [row(10, 'first-assistant')],
+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },
+ session_id: 'stored-1'
+ } as never)
+ vi.mocked(getSessionMessages).mockRejectedValue(new Error('network down'))
+
+ const applyOlderPage = vi.fn()
+
+ const applied = await backfillOlderTranscriptPage({
+ storedSessionId: 'stored-1',
+ isCurrent: () => true,
+ applyOlderPage
+ })
+
+ expect(applied).toBe(true)
+ expect(applyOlderPage).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('unhideOpeningUserRows', () => {
+ it('clears hidden on the opening user row so hydration keeps the greeting', () => {
+ const messages = unhideOpeningUserRows([
+ {
+ id: 1,
+ role: 'user',
+ content: 'hello there',
+ display_kind: 'hidden',
+ timestamp: 1
+ }
+ ])
+
+ expect(messages[0].display_kind).toBeUndefined()
+ expect(messages[0].display_content).toBe('hello there')
+ })
+
+ it('leaves a visible opening user row untouched', () => {
+ const messages = unhideOpeningUserRows([row(1, 'plain greeting')])
+
+ expect(messages[0].display_kind).toBeUndefined()
+ expect(messages[0].display_content).toBeUndefined()
+ })
+
+ it('leaves hidden rows after the opening user turn alone', () => {
+ const messages = unhideOpeningUserRows([
+ row(1, 'greeting'),
+ { id: 2, role: 'user', content: 'scaffolding', display_kind: 'hidden', timestamp: 2 }
+ ])
+
+ expect(messages[1].display_kind).toBe('hidden')
+ })
+
+ it('leaves a hidden opening row without content hidden', () => {
+ const messages = unhideOpeningUserRows([
+ { id: 1, role: 'user', content: '', display_kind: 'hidden', timestamp: 1 }
+ ])
+
+ expect(messages[0].display_kind).toBe('hidden')
+ })
})
diff --git a/apps/desktop/src/app/chat/transcript-backfill.ts b/apps/desktop/src/app/chat/transcript-backfill.ts
index 72568a429c9..fa1835a9a6d 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.ts
@@ -15,7 +15,7 @@
* drift on the next page.
*/
-import { getOlderSessionMessages, type ProfileScope } from '@/hermes'
+import { getOlderSessionMessages, getSessionMessages, type ProfileScope } from '@/hermes'
import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
import {
recordTranscriptBackfillPage,
@@ -23,7 +23,51 @@ import {
type TranscriptProfileScope,
transcriptTailState
} from '@/store/transcript-tail'
-import type { SessionMessagesResponse } from '@/types/hermes'
+import type { SessionMessage, SessionMessagesResponse } from '@/types/hermes'
+
+/**
+ * Compaction projection can stamp the session's opening USER row
+ * `display_kind: hidden` (#96875): the durable store holds the greeting but
+ * hydration drops the row, so paging to the very top of a compacted session
+ * renders only the first assistant reply. When an older page carries the
+ * opening user turn, clear the hidden stamp (keeping the content as the
+ * display projection) so `toChatMessages` keeps it on screen. Only the
+ * FIRST user row with content is unhidden — later hidden rows stay hidden
+ * (model scaffolding, muted turns), and an opening row with no content
+ * was never a greeting.
+ */
+export function unhideOpeningUserRows(messages: SessionMessage[]): SessionMessage[] {
+ const openingIndex = messages.findIndex(message => message.role === 'user')
+
+ if (openingIndex < 0) {
+ return messages
+ }
+
+ const opening = messages[openingIndex]
+
+ if (opening.display_kind !== 'hidden') {
+ return messages
+ }
+
+ const content = opening.display_content ?? opening.content
+
+ if (content == null || content === '') {
+ return messages
+ }
+
+ return messages.map((message, index) => {
+ if (index !== openingIndex) {
+ return message
+ }
+
+ const { display_kind: _hidden, ...rest } = message
+
+ return {
+ ...rest,
+ display_content: typeof content === 'string' ? content : String(content)
+ }
+ })
+}
/** Older rows likely exist beyond what the in-memory store holds. */
export function transcriptBackfillAvailable(
@@ -488,7 +532,31 @@ export function backfillOlderTranscriptPage(request: BackfillRequest): Promise<b
// 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, profile)
- request.applyOlderPage(toChatMessages(page.messages))
+ request.applyOlderPage(toChatMessages(unhideOpeningUserRows(page.messages)))
+
+ // #96875: paging can reach the top while the opening USER turn is still
+ // missing — the durable row is compaction-projected to display_kind=hidden
+ // (dropped at hydration) or sits before the last reachable `latest` page.
+ // Once the tail bookkeeping reports the session fully loaded, fetch the
+ // oldest display rows once and prepend any opening user turn the store is
+ // still missing. Best-effort: a failure keeps the older page that already
+ // landed.
+ if (!transcriptTailState(storedSessionId, profile)?.possiblyTruncated) {
+ try {
+ const origin = await getSessionMessages(storedSessionId, tail.profile, {
+ includeCompacted: true,
+ limit: 20,
+ offset: 0,
+ order: 'oldest'
+ })
+
+ if (request.isCurrent()) {
+ request.applyOlderPage(toChatMessages(unhideOpeningUserRows(origin.messages)))
+ }
+ } catch {
+ // Origin fetch is best-effort; the already-applied older page stays.
+ }
+ }
return true
})().finally(() => {