The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): page remote profile session reads
Jakub Wolniewicz21b57c61f4be
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 6fd8a0dba83..b66faf6b821 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -186,7 +186,11 @@ import { createKeepAwake } from './power-save'import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'import { rehomePrimaryConnection } from './primary-connection-rehome'import { decideProfileDeleteAction, profileNameFromDeleteRequest, resolveRouteProfile } from './profile-delete-routing'-import { fetchPrimaryProfileSessions } from './profile-session-routing'+import {+ fetchPrimaryProfileSessions,+ fetchRemoteProfileSessions,+ mergeProfileSessionWindow+} from './profile-session-routing'import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry'import { type ActiveWork, mergeActiveWork, normalizeActiveWork, quitPromptFor } from './quit-guard'import * as remoteLifecycle from './remote-lifecycle'@@ -11212,9 +11216,7 @@ const rowsOf = data => (Array.isArray(data?.sessions) ? data.sessions : [])// A remote profile's session list, read from its remote host and tagged with the// desktop-facing profile name (the remote's /api/sessions doesn't know it).async function remoteSessionList(profile, searchParams) {- const qs = new URLSearchParams(searchParams)- qs.delete('profile') // remote serves its own db; no cross-profile read there- const data = await fetchJsonForProfile(profile, `/api/sessions?${qs}`)+ const data = await fetchRemoteProfileSessions(profile, searchParams, fetchJsonForProfile)for (const s of rowsOf(data)) {s.profile = profile@@ -11286,7 +11288,12 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles) {const recency = s => s?.[order] ?? s?.started_at ?? 0merged.sort((a, b) => recency(b) - recency(a))- return { ...(base as any), sessions: merged.slice(offset, offset + limit), total, profile_totals: profileTotals }+ return {+ ...(base as any),+ sessions: mergeProfileSessionWindow(merged, offset, limit),+ total,+ profile_totals: profileTotals+ }}ipcMain.handle('hermes:api', async (_event, request) => {diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.tsindex 199740519bd..a96c84d062f 100644--- a/apps/desktop/electron/profile-session-routing.test.ts+++ b/apps/desktop/electron/profile-session-routing.test.ts@@ -2,7 +2,11 @@ import assert from 'node:assert/strict'import { test } from 'vitest'-import { fetchPrimaryProfileSessions } from './profile-session-routing'+import {+ fetchPrimaryProfileSessions,+ fetchRemoteProfileSessions,+ mergeProfileSessionWindow+} from './profile-session-routing'test('primary session reads use the profile-aware request path', async () => {const calls: Array<{ profile: string | null; path: string }> = []@@ -28,3 +32,146 @@ test('primary session reads preserve the empty-list fallback', async () => {assert.deepEqual(result, { sessions: [], total: 0, profile_totals: {} })})++test('remote session reads split oversized sidebar windows into API-safe pages', async () => {+ const calls: Array<{ profile: string | null; path: string }> = []+ const rows = Array.from({ length: 250 }, (_, index) => ({ id: `session-${index}` }))++ const result = await fetchRemoteProfileSessions(+ 'remote-work',+ new URLSearchParams({ profile: 'remote-work', limit: '300', offset: '0', order: 'updated' }),+ async (profile, path) => {+ calls.push({ profile, path })+ const url = new URL(path, 'http://desktop.test')+ const limit = Number(url.searchParams.get('limit'))+ const offset = Number(url.searchParams.get('offset'))++ if (limit > 100) {+ throw new Error(`remote /api/sessions rejects limit ${limit}`)+ }++ return {+ sessions: rows.slice(offset, offset + limit),+ total: rows.length,+ limit,+ offset+ }+ }+ )++ assert.deepEqual(calls, [+ { profile: 'remote-work', path: '/api/sessions?limit=100&offset=0&order=updated' },+ { profile: 'remote-work', path: '/api/sessions?limit=100&offset=100&order=updated' },+ { profile: 'remote-work', path: '/api/sessions?limit=50&offset=200&order=updated' }+ ])+ assert.equal(result.sessions.length, 250)+ assert.equal(result.total, 250)+ assert.equal(result.limit, 300)+ assert.equal(result.offset, 0)+ assert.deepEqual(+ result.sessions.map(row => (row as { id: string }).id),+ rows.map(row => row.id)+ )+})++test('remote paging preserves offsets and deduplicates pinned backfill rows', async () => {+ const calls: string[] = []++ const rows = Array.from({ length: 240 }, (_, index) => ({+ id: `session-${index}`,+ pinned: index === 20 || index === 200+ }))++ const pinned = rows.filter(row => row.pinned)++ const result = await fetchRemoteProfileSessions(+ 'remote-work',+ new URLSearchParams({ profile: 'remote-work', limit: '150', offset: '80' }),+ async (_profile, path) => {+ calls.push(path)+ const url = new URL(path, 'http://desktop.test')+ const limit = Number(url.searchParams.get('limit'))+ const offset = Number(url.searchParams.get('offset'))+ const window = rows.slice(offset, offset + limit)+ const windowIds = new Set(window.map(row => row.id))++ return {+ sessions: [...window, ...pinned.filter(row => !windowIds.has(row.id))],+ total: rows.length,+ limit,+ offset+ }+ }+ )++ assert.deepEqual(calls, ['/api/sessions?limit=100&offset=80', '/api/sessions?limit=50&offset=180'])+ assert.deepEqual(+ result.sessions.map(row => (row as { id: string }).id),+ [...rows.slice(80, 230).map(row => row.id), 'session-20']+ )+})++test('remote paging treats malformed totals as unknown instead of truncating the result', async () => {+ const rows = Array.from({ length: 250 }, (_, index) => ({ id: `session-${index}` }))++ for (const malformedTotal of [null, '', false, 100.5]) {+ const calls: string[] = []++ const result = await fetchRemoteProfileSessions(+ 'remote-work',+ new URLSearchParams({ limit: '300', offset: '0' }),+ async (_profile, path) => {+ calls.push(path)+ const url = new URL(path, 'http://desktop.test')+ const limit = Number(url.searchParams.get('limit'))+ const offset = Number(url.searchParams.get('offset'))++ return {+ sessions: rows.slice(offset, offset + limit),+ total: malformedTotal,+ limit,+ offset+ }+ }+ )++ assert.deepEqual(calls, [+ '/api/sessions?limit=100&offset=0',+ '/api/sessions?limit=100&offset=100',+ '/api/sessions?limit=100&offset=200'+ ])+ assert.equal(result.sessions.length, 250)+ assert.equal(result.total, 250)+ }+})++test('merged profile windows retain pinned rows outside the recency window', () => {+ const rows = [+ { id: 'recent-default', profile: 'default', pinned: false },+ { id: 'shared-id', profile: 'default', pinned: false },+ { id: 'recent-remote', profile: 'remote-work', pinned: false },+ { id: 'shared-id', profile: 'remote-work', pinned: true },+ { id: 'old-remote', profile: 'remote-work', pinned: true },+ { id: 'old-unpinned', profile: 'remote-work', pinned: false }+ ]++ assert.deepEqual(mergeProfileSessionWindow(rows, 0, 3), [rows[0], rows[1], rows[2], rows[3], rows[4]])+})++test('remote session reads keep small requests on one call', async () => {+ const calls: Array<{ profile: string | null; path: string }> = []+ const expected = { sessions: [{ id: 'session-1' }], total: 1, limit: 20, offset: 0 }++ const result = await fetchRemoteProfileSessions(+ 'remote-work',+ new URLSearchParams({ profile: 'remote-work', limit: '20', offset: '0' }),+ async (profile, path) => {+ calls.push({ profile, path })++ return expected+ }+ )++ assert.deepEqual(calls, [{ profile: 'remote-work', path: '/api/sessions?limit=20&offset=0' }])+ assert.equal(result, expected)+})diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.tsindex f31e22ca52a..dada65a7615 100644--- a/apps/desktop/electron/profile-session-routing.ts+++ b/apps/desktop/electron/profile-session-routing.ts@@ -1,12 +1,82 @@-export interface ProfileSessionsResponse {+interface SessionListResponse {sessions: unknown[]total: number- profile_totals: Record<string, number>[key: string]: unknown}+export interface ProfileSessionsResponse extends SessionListResponse {+ profile_totals: Record<string, number>+}+type FetchJsonForProfile = (profile: string | null, path: string) => Promise<unknown>+const REMOTE_SESSION_PAGE_LIMIT = 100++function rowsOf(data: unknown): unknown[] {+ if (!data || typeof data !== 'object' || !('sessions' in data)) {+ return []+ }++ return Array.isArray(data.sessions) ? data.sessions : []+}++function sessionId(row: unknown): string | null {+ if (!row || typeof row !== 'object' || !('id' in row)) {+ return null+ }++ return typeof row.id === 'string' ? row.id : null+}++function nonNegativeNumber(value: unknown): number | null {+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : null+}++function isPinned(row: unknown): boolean {+ return Boolean(row && typeof row === 'object' && 'pinned' in row && row.pinned)+}++function profileSessionId(row: unknown): string | null {+ const id = sessionId(row)++ if (!id) {+ return null+ }++ const profile =+ row && typeof row === 'object' && 'profile' in row && typeof row.profile === 'string' ? row.profile : ''++ return `${profile}\0${id}`+}++export function mergeProfileSessionWindow(rows: unknown[], offset: number, limit: number): unknown[] {+ const window = rows.slice(offset, offset + limit)+ const seenRows = new Set(window)+ const seenIds = new Set(window.map(profileSessionId).filter((id): id is string => id !== null))++ for (const row of rows.slice(offset + limit)) {+ if (!isPinned(row)) {+ continue+ }++ const id = profileSessionId(row)++ if ((id && seenIds.has(id)) || (!id && seenRows.has(row))) {+ continue+ }++ if (id) {+ seenIds.add(id)+ } else {+ seenRows.add(row)+ }++ window.push(row)+ }++ return window+}+export async function fetchPrimaryProfileSessions(searchParams: URLSearchParams,fetchJsonForProfile: FetchJsonForProfile@@ -17,3 +87,105 @@ export async function fetchPrimaryProfileSessions(return { sessions: [], total: 0, profile_totals: {} }}}++export async function fetchRemoteProfileSessions(+ profile: string,+ searchParams: URLSearchParams,+ fetchJsonForProfile: FetchJsonForProfile+): Promise<SessionListResponse> {+ const params = new URLSearchParams(searchParams)+ params.delete('profile') // the remote serves its own database++ const requestedLimit = Number(params.get('limit'))+ const requestedOffset = Number(params.get('offset') || '0')++ const needsPaging =+ Number.isInteger(requestedLimit) &&+ requestedLimit > REMOTE_SESSION_PAGE_LIMIT &&+ Number.isInteger(requestedOffset) &&+ requestedOffset >= 0++ if (!needsPaging) {+ return (await fetchJsonForProfile(profile, `/api/sessions?${params}`)) as SessionListResponse+ }++ const sessions: unknown[] = []+ const backfilled: unknown[] = []+ const seenIds = new Set<string>()+ const backfilledIds = new Set<string>()+ let firstPage: SessionListResponse | null = null+ let pageOffset = requestedOffset+ let targetOffset = requestedOffset + requestedLimit++ while (pageOffset < targetOffset) {+ const pageParams = new URLSearchParams(params)+ const pageLimit = Math.min(REMOTE_SESSION_PAGE_LIMIT, targetOffset - pageOffset)+ pageParams.set('limit', String(pageLimit))+ pageParams.set('offset', String(pageOffset))++ const page = (await fetchJsonForProfile(profile, `/api/sessions?${pageParams}`)) as SessionListResponse+ firstPage ??= page++ const total = nonNegativeNumber(page.total)+ const pageRows = rowsOf(page)++ const windowedCount =+ total !== null ? Math.min(pageLimit, Math.max(0, total - pageOffset)) : Math.min(pageLimit, pageRows.length)++ // /api/sessions appends pinned rows that fall outside the requested+ // window. Keep those aside until all ordinary pages have been joined so+ // pagination preserves the same order as one larger request.+ for (const row of pageRows.slice(0, windowedCount)) {+ const id = sessionId(row)++ if (id && seenIds.has(id)) {+ continue+ }++ if (id) {+ seenIds.add(id)+ backfilledIds.delete(id)+ }++ sessions.push(row)+ }++ for (const row of pageRows.slice(windowedCount)) {+ const id = sessionId(row)++ if ((id && seenIds.has(id)) || (id && backfilledIds.has(id))) {+ continue+ }++ if (id) {+ backfilledIds.add(id)+ }++ backfilled.push(row)+ }++ if (total !== null) {+ targetOffset = Math.min(targetOffset, total)+ }++ pageOffset += pageLimit+ }++ for (const row of backfilled) {+ const id = sessionId(row)++ if (!id || backfilledIds.has(id)) {+ sessions.push(row)+ }+ }++ const total = nonNegativeNumber(firstPage?.total)++ return {+ ...(firstPage || {}),+ sessions,+ total: total ?? sessions.length,+ limit: requestedLimit,+ offset: requestedOffset+ }+}