The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): never adopt a page from a backend that ignored order=latest (#124815)
Austin Pickett2a27f12110b0
diff --git a/apps/desktop/src/api/session-transcript-paging.test.ts b/apps/desktop/src/api/session-transcript-paging.test.tsindex 4dbe26976e3..e56a64dd739 100644--- a/apps/desktop/src/api/session-transcript-paging.test.ts+++ b/apps/desktop/src/api/session-transcript-paging.test.ts@@ -82,6 +82,79 @@ describe('session transcript pagination ownership', () => {})+ it('reads the whole transcript instead of adopting the oldest page from a backend that ignores order', async () => {+ setApiRequestConnection(null)+ const owner = { connectionId: 'local', profile: 'default' }+ const oldest = Array.from({ length: LATEST_SESSION_MESSAGES_LIMIT }, (_, index) => row(index + 1))+ // A backend built before the `order` param: FastAPI drops the unknown query+ // param, the handler pages from the OLDEST row, and the response still+ // carries `{limit, offset, returned}` — with no honoured-order echo.+ api.mockResolvedValueOnce({+ session_id: 'stored-session',+ messages: oldest,+ pagination: { limit: LATEST_SESSION_MESSAGES_LIMIT, offset: 0, returned: oldest.length }+ })+ const all = Array.from({ length: 400 }, (_, index) => row(index + 1))+ // The full history that backend does serve (oldest-first paging).+ api.mockResolvedValueOnce({+ session_id: 'stored-session',+ messages: all,+ pagination: { limit: 500, offset: 0, returned: all.length }+ })++ const authoritative = await getLatestSessionMessages('stored-session')++ // The oldest page is NOT the tail: the desktop reads the complete+ // transcript instead, and drops `pagination` so nothing arms a backfill+ // that would prepend rows counted from the oldest end.+ expect(authoritative.messages.map(message => message.id)).toEqual(all.map(message => message.id))+ expect(authoritative.pagination).toBeUndefined()+ expect(transcriptBackfillAvailable('stored-session', owner)).toBe(false)+ expect(api).toHaveBeenLastCalledWith({+ path: '/api/sessions/stored-session/messages?limit=500&offset=0&order=oldest&include_compacted=true'+ })+ })++ it('keeps a passive read passive when it falls back to the complete transcript', async () => {+ setApiRequestConnection(null)+ const oldest = Array.from({ length: LATEST_SESSION_MESSAGES_LIMIT }, (_, index) => row(index + 1))+ api.mockResolvedValueOnce({+ session_id: 'stored-session',+ messages: oldest,+ pagination: { limit: LATEST_SESSION_MESSAGES_LIMIT, offset: 0, returned: oldest.length }+ })+ api.mockResolvedValueOnce({ session_id: 'stored-session', messages: oldest })++ await getLatestSessionMessages('stored-session', undefined, { passive: true })++ // A hidden tile's refresh must never cold-start or hold a backend+ // (#103375); the compatibility read inherits that.+ expect(api).toHaveBeenCalledTimes(2)+ expect(api).toHaveBeenLastCalledWith({+ path: '/api/sessions/stored-session/messages?limit=500&offset=0&order=oldest&include_compacted=true',+ passive: true+ })+ })++ it.each([+ ['a short orderless page', { limit: LATEST_SESSION_MESSAGES_LIMIT, offset: 0, returned: 3 }],+ ['a page without pagination metadata', undefined]+ ])('adopts %s as the complete transcript without a second read', async (_label, pagination) => {+ setApiRequestConnection(null)+ const owner = { connectionId: 'local', profile: 'default' }+ const all = [row(1), row(2), row(3)]+ // Served from the oldest row at offset 0 and fewer rows than the limit:+ // this already is every row, so nothing is gained by paging again.+ api.mockResolvedValueOnce({ session_id: 'stored-session', messages: all, ...(pagination ? { pagination } : {}) })++ const authoritative = await getLatestSessionMessages('stored-session')++ expect(api).toHaveBeenCalledTimes(1)+ expect(authoritative.messages.map(message => message.id)).toEqual([1, 2, 3])+ expect(authoritative.pagination).toBeUndefined()+ expect(transcriptBackfillAvailable('stored-session', owner)).toBe(false)+ })+it('coalesces spellings against a backend that predates the profile field', async () => {setApiRequestConnection(null)const owner = { connectionId: 'local', profile: 'default' }diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.tsindex feb260f9b56..7290459d53d 100644--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import type { SidebarSessionsResponse } from './sessions'vi.mock('@/lib/gateway-rpc', () => ({ isMissingRestEndpoint: () => false }))-vi.mock('@/store/transcript-tail', () => ({ recordTranscriptTail: vi.fn() }))+vi.mock('@/store/transcript-tail', () => ({ pageHonorsLatestOrder: () => true, recordTranscriptTail: vi.fn() }))vi.mock('./client', () => ({capabilityScoped: vi.fn(),getApiRequestConnection: vi.fn(() => 'prometheus'),diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.tsindex 95648be43eb..02a791205cd 100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@ -1,7 +1,7 @@import { isMissingRestEndpoint } from '@/lib/gateway-rpc'import { maybeBackfillLegacySessionOwners } from '@/lib/legacy-session-owner-backfill'import { stampRowsWithOwningConnection } from '@/lib/session-owner-stamp'-import { recordTranscriptTail } from '@/store/transcript-tail'+import { pageHonorsLatestOrder, recordTranscriptTail } from '@/store/transcript-tail'import type {PaginatedSessions,SessionInfo,@@ -521,7 +521,19 @@ export function getLatestSessionMessages(includeCompacted: true},options- ).then(page => {+ ).then(async page => {+ // Order-echo guard. A backend built before the `order` param silently drops+ // it (FastAPI ignores unknown query params) and serves the OLDEST page+ // while still answering with a `pagination` object — so a full page looked+ // like a truncated tail and the transcript silently became its first N+ // rows, with "Show earlier" then prepending rows N..2N counted from the+ // oldest end. Only a page that echoes `order: 'latest'` may be adopted as+ // the tail; anything else is read as the complete transcript instead, which+ // is the one paging contract both backend generations honour.+ const authoritativePage = pageHonorsLatestOrder(page)+ ? page+ : await completeTranscriptForOrderlessBackend(id, profile, page, options)+// 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@@ -534,16 +546,45 @@ export function getLatestSessionMessages(profile: route.profile || page.profile || ambientProfile}- recordTranscriptTail(id, page, route, owner)+ recordTranscriptTail(id, authoritativePage, route, owner)- if (page.session_id && page.session_id !== id) {- recordTranscriptTail(page.session_id, page, route, owner)+ if (authoritativePage.session_id && authoritativePage.session_id !== id) {+ recordTranscriptTail(authoritativePage.session_id, authoritativePage, route, owner)}- return page+ return authoritativePage})}+/**+ * Complete chronological transcript for a backend that did not honour+ * `order=latest` (#92508).+ *+ * A page with no `pagination` at all (the pre-paging generation) or an+ * orderless page that came back SHORT already holds every row: both were+ * served from the oldest row at offset 0. Only a full orderless page needs+ * the paged read. `getAllSessionMessages` pages with `order: 'oldest'`: the+ * newer generation honours that explicitly and the older one drops the param+ * and always paged from the start, so both return the same full history. The+ * result carries NO `pagination`, the established "this is everything" signal+ * (`tailStateFromPage`), so nothing arms a REST backfill against the wrong end+ * of the transcript.+ */+async function completeTranscriptForOrderlessBackend(+ id: string,+ profile: ProfileScope | undefined,+ page: SessionMessagesResponse,+ options: { passive?: boolean }+): Promise<SessionMessagesResponse> {+ const { pagination, ...complete } = page++ if (!pagination || page.messages.length < pagination.limit) {+ return complete+ }++ return { ...complete, messages: (await getAllSessionMessages(id, profile, options)).messages }+}+/*** READ-ONLY stored-transcript lookup that never routes a live session* (#94724 no-owner recovery). Tries the ambient/primary store first, then@@ -606,7 +647,7 @@ export function getOlderSessionMessages(export async function getAllSessionMessages(id: string,profile?: ProfileScope,- options: { maxJsonChars?: number } = {}+ options: { maxJsonChars?: number; passive?: boolean } = {}): Promise<SessionMessagesResponse> {const messages: SessionMessage[] = []const pageSize = 500@@ -616,12 +657,17 @@ export async function getAllSessionMessages(let resolvedSessionId = idwhile (true) {- const page = await getSessionMessages(id, profile, {- limit: pageSize,- offset,- order: 'oldest',- includeCompacted: true- })+ const page = await getSessionMessages(+ id,+ profile,+ {+ limit: pageSize,+ offset,+ order: 'oldest',+ includeCompacted: true+ },+ { passive: options.passive }+ )resolvedSessionId = page.session_idjsonChars += (JSON.stringify(page.messages) ?? '').lengthdiff --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.tsxindex de9512673ff..41f2cd24413 100644--- 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@@ -15,7 +15,7 @@ vi.mock('@/api/client', () => ({ capabilityScoped: (scope: object) => scope, hervi.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 }))+vi.mock('@/store/transcript-tail', () => ({ pageHonorsLatestOrder: () => true, transcriptTailState: () => undefined }))const page = (ids: number[], more = false) => ({entries: ids.map(id => ({ row_id: id, preview: `Prompt ${id}` })),diff --git a/apps/desktop/src/store/transcript-tail.test.ts b/apps/desktop/src/store/transcript-tail.test.tsindex cd201f71efb..b41c0ec4296 100644--- a/apps/desktop/src/store/transcript-tail.test.ts+++ b/apps/desktop/src/store/transcript-tail.test.ts@@ -11,7 +11,16 @@ import {const page = (count: number, limit = 10) =>({messages: Array.from({ length: count }, (_, i) => ({ id: `m${i}` })),- pagination: { limit, offset: 0 }+ pagination: { limit, offset: 0, order: 'latest' as const }+ }) as never++/** A page from a backend that predates the `order` param: it dropped the+ * unknown query param, answered from the OLDEST row, and still returned a+ * `pagination` object — without the honoured-order echo. */+const orderlessPage = (count: number, limit = 10) =>+ ({+ messages: Array.from({ length: count }, (_, i) => ({ id: `m${i}` })),+ pagination: { limit, offset: 0, returned: count }}) as neverdescribe('recordTranscriptTail no-op suppression', () => {@@ -155,3 +164,32 @@ describe('recordTranscriptTail with an empty page', () => {expect(transcriptTailState('s1')).toMatchObject({ nextOffset: 10, possiblyTruncated: true })})})++describe('order-echo guard (#92508)', () => {+ beforeEach(() => {+ clearTranscriptTailPaging()+ })++ it('never adopts an orderless page as a truncated tail', () => {+ recordTranscriptTail('s1', orderlessPage(10))++ // The rows are the transcript's OLDEST page, so nothing may be counted+ // back from them and no backfill may arm.+ expect(transcriptTailState('s1')).toMatchObject({ nextOffset: 10, possiblyTruncated: false })+ })++ it("never adopts a page stamped with the order it really served ('oldest')", () => {+ recordTranscriptTail('s1', {+ messages: Array.from({ length: 10 }, (_, i) => ({ id: `m${i}` })),+ pagination: { limit: 10, offset: 0, order: 'oldest', returned: 10 }+ } as never)++ expect(transcriptTailState('s1')).toMatchObject({ nextOffset: 10, possiblyTruncated: false })+ })++ it('still arms a real tail when the page echoes order=latest', () => {+ recordTranscriptTail('s1', page(10))++ expect(transcriptTailState('s1')).toMatchObject({ nextOffset: 10, possiblyTruncated: true })+ })+})diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.tsindex 2bbb262005c..abb831b3b0d 100644--- a/apps/desktop/src/store/transcript-tail.ts+++ b/apps/desktop/src/store/transcript-tail.ts@@ -110,6 +110,24 @@ function resolveTailEntry(return matches.length === 1 ? matches[0] : undefined}+/**+ * True when a page PROVES the backend honoured the `order: 'latest'` request.+ *+ * The server stamps the order it actually applied back onto+ * `pagination.order`. A backend built before that param silently drops the+ * unknown query param (FastAPI ignores it) and pages from the OLDEST row while+ * still returning a `pagination` object — just without the echo. Adopting such+ * a page as the tail shows only the transcript's first N rows, and it then arms+ * `getOlderSessionMessages(N)` to prepend rows counted from the oldest end.+ *+ * A MISSING echo counts as "not honoured": a page that simply omits the field+ * is indistinguishable from the legacy response, and the fallback for both (a+ * full chronological read) is correct for either.+ */+export function pageHonorsLatestOrder(page: TailPage): boolean {+ return page.pagination?.order === 'latest'+}+/** Paging state after `page`: the next older offset and whether older rows may exist. */export function tailStateFromPage(page: TailPage, profile?: TranscriptProfileScope): TranscriptTailState {const pagination = page.pagination@@ -120,6 +138,13 @@ export function tailStateFromPage(page: TailPage, profile?: TranscriptProfileScoreturn { nextOffset: page.messages.length, possiblyTruncated: false, profile }}+ // A page with metadata but no honoured-order echo came from a backend that+ // dropped `order` and paged from the OLDEST row (#92508). It is not a tail:+ // arm no backfill, or "Show earlier" prepends the wrong prefix.+ if (!pageHonorsLatestOrder(page)) {+ return { nextOffset: page.messages.length, possiblyTruncated: false, profile }+ }+return {nextOffset: pagination.offset + page.messages.length,possiblyTruncated: page.messages.length >= pagination.limit,diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 366da0f8c42..f90a74b9208 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -713,7 +713,11 @@ export interface SessionMessagesResponse {pagination?: {limit: numberoffset: number- order: 'latest' | 'oldest'+ /** Order the backend actually applied, echoed back from the request.+ * Absent on backends that predate the `order` param: they answered from+ * the OLDEST row while still returning this object, so a page may only be+ * read as a tail when this is `'latest'` (see `pageHonorsLatestOrder`). */+ order?: 'latest' | 'oldest'returned: number}session_id: string