The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): preserve older history pagination across scopes
Robin Fernandesd45842d20624
diff --git a/apps/desktop/src/api/session-transcript-paging.test.ts b/apps/desktop/src/api/session-transcript-paging.test.tsnew file mode 100644index 00000000000..716f6d059ad--- /dev/null+++ b/apps/desktop/src/api/session-transcript-paging.test.ts@@ -0,0 +1,185 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import {+ backfillOlderTranscriptPage,+ mergeOlderTranscriptPage,+ transcriptBackfillAvailable+} from '@/app/chat/transcript-backfill'+import { toChatMessages } from '@/lib/chat-messages'+import { $connection } from '@/store/session'+import { $transcriptTailBySessionId, transcriptTailState } from '@/store/transcript-tail'+import type { SessionMessagesResponse } from '@/types/hermes'++import { setApiRequestConnection, setApiRequestProfile } from './client'+import { getLatestSessionMessages, LATEST_SESSION_MESSAGES_LIMIT } from './sessions'++const row = (id: number) => ({ id, role: 'user' as const, content: `message ${id}`, timestamp: id })++const page = (messages: ReturnType<typeof row>[], offset = 0): SessionMessagesResponse => ({+ session_id: 'stored-session',+ profile: 'default',+ messages,+ pagination: { limit: LATEST_SESSION_MESSAGES_LIMIT, offset, order: 'latest', returned: messages.length }+})++describe('session transcript pagination ownership', () => {+ const api = vi.fn()++ beforeEach(() => {+ api.mockReset()+ $transcriptTailBySessionId.set({})+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })+ setApiRequestProfile('default')+ $connection.set({ mode: 'local' } as NonNullable<ReturnType<typeof $connection.get>>)+ })++ afterEach(() => {+ $connection.set(null)+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ Reflect.deleteProperty(window, 'hermesDesktop')+ })++ it.each(['local', null])(+ 'keeps older history reachable across scope spellings on connection %s',+ async connectionId => {+ setApiRequestConnection(connectionId)+ const owner = { connectionId: 'local', profile: 'default' }+ const older = Array.from({ length: 79 }, (_, index) => row(index + 1))+ const tail = Array.from({ length: LATEST_SESSION_MESSAGES_LIMIT }, (_, index) => row(older.length + index + 1))+ api.mockResolvedValue(page(tail))++ // Resume, post-turn hydration, and background refresh use different scope+ // spellings, but all three requests go to the same owning backend.+ for (const scope of [owner, 'default', undefined]) {+ await getLatestSessionMessages('stored-session', scope)+ }++ expect(Object.keys($transcriptTailBySessionId.get())).toHaveLength(1)+ expect(transcriptBackfillAvailable('stored-session', owner)).toBe(true)+ expect(transcriptBackfillAvailable('stored-session')).toBe(true)++ let messages = toChatMessages(tail)+ api.mockResolvedValueOnce(page(older, tail.length))+ expect(+ await backfillOlderTranscriptPage({+ storedSessionId: 'stored-session',+ profile: owner,+ isCurrent: () => true,+ applyOlderPage: earlier => {+ messages = mergeOlderTranscriptPage(messages, earlier)+ }+ })+ ).toBe(true)++ // Resolve the owner for lookup, but replay the exact ambient read route.+ expect(api).toHaveBeenLastCalledWith({+ ...(connectionId ? { connectionId } : {}),+ path: `/api/sessions/stored-session/messages?limit=${LATEST_SESSION_MESSAGES_LIMIT}&offset=${tail.length}&order=latest&include_compacted=true`+ })+ expect(messages.map(message => message.rowId)).toEqual([...older, ...tail].map(message => message.id))+ expect(transcriptBackfillAvailable('stored-session', owner)).toBe(false)+ }+ )++ it('preserves legacy named-profile routing while the foreground is local', async () => {+ setApiRequestConnection(null)+ const profile = 'remote-alias'+ const owner = { connectionId: 'local', profile }+ const tail = Array.from({ length: LATEST_SESSION_MESSAGES_LIMIT }, (_, index) => row(index + 2))+ api.mockResolvedValueOnce({ ...page(tail), profile: 'work' })++ await getLatestSessionMessages('stored-session', profile)++ // An explicit local pin would bypass Electron's per-profile remote override.+ expect.soft(api).toHaveBeenLastCalledWith({+ profile,+ path: `/api/sessions/stored-session/messages?profile=${profile}&limit=${LATEST_SESSION_MESSAGES_LIMIT}&order=latest&include_compacted=true`+ })+ expect(transcriptBackfillAvailable('stored-session', owner)).toBe(true)++ const applyOlderPage = vi.fn()+ api.mockResolvedValueOnce({ ...page([row(1)], tail.length), profile: 'work' })+ expect(+ await backfillOlderTranscriptPage({+ storedSessionId: 'stored-session',+ profile: owner,+ isCurrent: () => true,+ applyOlderPage+ })+ ).toBe(true)++ expect(api).toHaveBeenLastCalledWith({+ profile,+ path: `/api/sessions/stored-session/messages?profile=${profile}&limit=${LATEST_SESSION_MESSAGES_LIMIT}&offset=${tail.length}&order=latest&include_compacted=true`+ })+ expect(applyOlderPage).toHaveBeenCalledWith(toChatMessages([row(1)]))+ expect(transcriptTailState('stored-session', owner)).toMatchObject({+ nextOffset: tail.length + 1,+ possiblyTruncated: false,+ profile: { profile }+ })+ })++ it.each(['work', null])(+ 'isolates an ambient %s profile across explicit reads and gateway switches',+ async servingProfile => {+ setApiRequestConnection('source-a')+ const tail = page(Array.from({ length: LATEST_SESSION_MESSAGES_LIMIT }, (_, index) => row(index + 1)))+ let resolve!: (value: SessionMessagesResponse) => void+ api.mockReturnValueOnce(+ new Promise<SessionMessagesResponse>(done => {+ resolve = done+ })+ )+ const pending = getLatestSessionMessages('stored-session')+ api.mockResolvedValueOnce(page([row(1)]))+ await getLatestSessionMessages('stored-session', { connectionId: 'source-a', profile: 'default' })++ setApiRequestConnection('source-b')+ api.mockResolvedValueOnce(page([row(1)]))+ await getLatestSessionMessages('stored-session', { connectionId: 'source-b', profile: 'default' })+ resolve({ ...tail, profile: servingProfile })+ await pending++ const ownerA = { connectionId: 'source-a', profile: servingProfile || undefined }+ const ownerB = { connectionId: 'source-b', profile: 'default' }+ expect(transcriptTailState('stored-session', ownerA)).toMatchObject({+ possiblyTruncated: true,+ profile: { connectionId: 'source-a' }+ })+ expect(transcriptTailState('stored-session', { connectionId: 'source-a', profile: 'default' })).toMatchObject({+ possiblyTruncated: false+ })+ expect(transcriptTailState('stored-session', ownerB)).toMatchObject({ possiblyTruncated: false, profile: ownerB })+ expect(transcriptTailState('stored-session')).toBeUndefined()++ const defaultA = transcriptTailState('stored-session', { connectionId: 'source-a', profile: 'default' })+ const defaultB = transcriptTailState('stored-session', ownerB)+ const applyOlderPage = vi.fn()+ api.mockResolvedValueOnce({ ...page([row(0)], tail.messages.length), profile: servingProfile })+ expect(+ await backfillOlderTranscriptPage({+ storedSessionId: 'stored-session',+ profile: ownerA,+ isCurrent: () => true,+ applyOlderPage+ })+ ).toBe(true)++ // Serving-profile metadata selects the cache entry, not the request route.+ expect(api).toHaveBeenLastCalledWith({+ connectionId: 'source-a',+ path: `/api/sessions/stored-session/messages?limit=${LATEST_SESSION_MESSAGES_LIMIT}&offset=${tail.messages.length}&order=latest&include_compacted=true`+ })+ expect(applyOlderPage).toHaveBeenCalledWith(toChatMessages([row(0)]))+ expect(transcriptTailState('stored-session', ownerA)).toEqual({+ nextOffset: tail.messages.length + 1,+ possiblyTruncated: false,+ profile: { connectionId: 'source-a' }+ })+ expect(transcriptTailState('stored-session', { connectionId: 'source-a', profile: 'default' })).toBe(defaultA)+ expect(transcriptTailState('stored-session', ownerB)).toBe(defaultB)+ }+ )+})diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.tsindex 99a0ddbb70f..2ebbf445bf1 100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@ -1,6 +1,7 @@import { isMissingRestEndpoint } from '@/lib/gateway-rpc'import { maybeBackfillLegacySessionOwners } from '@/lib/legacy-session-owner-backfill'import { stampRowsWithOwningConnection } from '@/lib/session-owner-stamp'+import { $connection } from '@/store/session'import { recordTranscriptTail } from '@/store/transcript-tail'import type {PaginatedSessions,@@ -10,7 +11,14 @@ import type {SessionSearchResponse} from '@/types/hermes'-import { capabilityScoped, getApiRequestConnection, hermesApi, type ProfileScope, profileScoped } from './client'+import {+ capabilityScoped,+ connectionScoped,+ getApiRequestConnection,+ hermesApi,+ type ProfileScope,+ profileScoped+} from './client'const SESSION_LIST_REQUEST_TIMEOUT_MS = 60_000@@ -446,6 +454,19 @@ export function getLatestSessionMessages(profile?: ProfileScope,options: { passive?: boolean } = {}): Promise<SessionMessagesResponse> {+ // Key pagination by the effective request owner, not the caller's spelling+ // (ambient, profile string, or explicit pin). Otherwise refreshes create+ // duplicate tail entries and "Show earlier" cannot resolve the loaded tail.+ // Capture before awaiting: the active gateway may change during the read.+ const tailScope = { ...connectionScoped(), ...sessionScoped(profile) }+ const ownerScope = { ...tailScope }++ // Normalize only the lookup key: a local request pin would bypass Electron's+ // legacy per-profile remote overrides. Backfill must retain the original route.+ if (!ownerScope.connectionId && $connection.get()?.mode === 'local') {+ ownerScope.connectionId = 'local'+ }+// 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.@@ -463,10 +484,11 @@ export function getLatestSessionMessages(// 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)+ const resolvedOwnerScope = { ...ownerScope, profile: ownerScope.profile || page.profile || undefined }+ recordTranscriptTail(id, page, tailScope, resolvedOwnerScope)if (page.session_id && page.session_id !== id) {- recordTranscriptTail(page.session_id, page, profile)+ recordTranscriptTail(page.session_id, page, tailScope, resolvedOwnerScope)}return pagediff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.tsindex 8f18ed67c41..fec325dcdb0 100644--- a/apps/desktop/src/store/transcript-tail.ts+++ b/apps/desktop/src/store/transcript-tail.ts@@ -53,7 +53,8 @@ function normalizedScope(profile?: TranscriptProfileScope): { connectionId: strireturn {connectionId: String(profile.connectionId || '').trim(),- profile: String(profile.profile || '').trim() || 'default'+ // An omitted profile targets the serving process, not necessarily default.+ profile: String(profile.profile || '').trim()}}@@ -115,12 +116,19 @@ function setTranscriptTailEntry(key: string, state: TranscriptTailState): void {}/** Record the outcome of a tail hydration (`getLatestSessionMessages`). */-export function recordTranscriptTail(storedSessionId: string, page: TailPage, profile?: TranscriptProfileScope): void {+export function recordTranscriptTail(+ storedSessionId: string,+ page: TailPage,+ profile?: TranscriptProfileScope,+ ownerScope: TranscriptProfileScope | undefined = profile+): void {if (!storedSessionId) {return}- const key = transcriptTailKey(storedSessionId, profile)+ // Keep request routing separate from the resolved owner used for lookup:+ // backfill must replay an ambient read even when the server names its profile.+ const key = transcriptTailKey(storedSessionId, ownerScope)setTranscriptTailEntry(key, tailStateFromPage(page, profile))}diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex bcabdaa5dfe..98365b0e521 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -699,6 +699,8 @@ export interface SessionMessage {}export interface SessionMessagesResponse {+ /** Serving profile for unscoped reads; null for a custom HERMES_HOME. */+ profile?: null | stringmessages: SessionMessage[]pagination?: {limit: numberdiff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex eb4450c0ccb..0e921845350 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -551,9 +551,14 @@ async def get_session_messages(if result is None:raise HTTPException(status_code=404, detail=_NOT_FOUND)sid, _limit, messages = result+ from hermes_cli.profiles import get_active_profile_name++ serving_profile = _serving_profile(profile) if profile else get_active_profile_name()projected_messages = _project_for_display(messages)return {"session_id": sid,+ # Unscoped reads use this process's DB, which may be a named profile.+ "profile": None if serving_profile == "custom" else serving_profile,"messages": projected_messages,"pagination": {"limit": _limit, "offset": offset,diff --git a/tests/hermes_cli/test_session_message_page_owner.py b/tests/hermes_cli/test_session_message_page_owner.pynew file mode 100644index 00000000000..5fd8b6e833c--- /dev/null+++ b/tests/hermes_cli/test_session_message_page_owner.py@@ -0,0 +1,49 @@+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++[email protected]("serving_profile", ["work", None])+def test_message_pages_identify_the_serving_profile(tmp_path, monkeypatch, serving_profile):+ from hermes_state import SessionDB++ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ default_home = tmp_path / ".hermes"+ work_home = default_home / "profiles" / "work" if serving_profile else default_home / "custom-home"+ default_home.mkdir(parents=True)+ work_home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(work_home))+ # conftest redirects this legacy override independently of HERMES_HOME.+ monkeypatch.setattr("hermes_state.DEFAULT_DB_PATH", work_home / "state.db")++ for home, count in ((default_home, 1), (work_home, 199)):+ db = SessionDB(db_path=home / "state.db")+ try:+ db.create_session(session_id="same-id", source="desktop")+ db.append_messages_batch("same-id", [+ {"role": "user", "content": f"message-{index}"}+ for index in range(count)+ ])+ finally:+ db.close()++ from hermes_cli.web_routers.sessions import manage_router++ app = FastAPI()+ app.include_router(manage_router)+ with TestClient(app) as client:+ query = "limit=120&order=latest&include_compacted=true"+ tail = client.get(f"/api/sessions/same-id/messages?{query}").json()+ older = client.get(f"/api/sessions/same-id/messages?{query}&offset=120").json()+ default = client.get(f"/api/sessions/same-id/messages?{query}&profile=default").json()++ assert tail["profile"] == older["profile"] == serving_profile+ assert default["profile"] == "default"+ assert len(tail["messages"]) == 120+ assert len(older["messages"]) == 79+ assert len(default["messages"]) == 1+ assert [row["content"] for row in older["messages"] + tail["messages"]] == [+ f"message-{index}" for index in range(199)+ ]