Skip to content

The agent that grows with you

fix(desktop): keep all profile sessions across paged merges

David Dudok de Wit4a6521e293a8
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 24244a37d7c..afb2ef865e3 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -461,19 +461,18 @@ import {
fetchAllProfilesAggregatePerProfile,
fetchAllProfilesSessionsPerProfile,
fetchPrimaryProfileSessions,
- fetchRegistrySessionRows,
fetchRemoteProfileSessions,
findRemoteOwnerProfileForSession,
hasPinnedRegistrySessionSource,
isAllProfilesAggregateRequest,
isAllProfilesSessionListRequest,
isRemoteSessionRequestPath,
+ mergeRegistrySessionRows,
type RegistrySessionSource,
remoteOwnerRoutePath,
remoteProfileQueryScope,
settleRemoteProfileSessions,
shouldIncludeLocalRegistrySessionSource,
- spliceRegistrySessionRows,
tagRegistrySessionResponse,
tagRemoteSessionRows
} from './profile-session-routing'
@@ -16214,7 +16213,7 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const offset = Math.max(0, Number(searchParams.get('offset')) || 0)
const order = searchParams.get('order') === 'created' ? 'started_at' : 'last_active'
- const base = (await fetchPrimaryProfileSessions(searchParams, fetchJsonForProfile)) as any
+ const base = (await fetchPrimaryProfileSessions(searchParams, fetchJsonForProfile, { prefixForMerge: true })) as any
// Over-fetch each remote from offset 0 (limit+offset rows) so the merged window
// is correct for this page — mirrors the primary's per-profile over-fetch.
@@ -16256,12 +16255,13 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const registrySources = registrySourcesOverride || (await pooledRegistrySessionSources())
if (registrySources.length) {
- const registryRows = await fetchRegistrySessionRows(registrySources, remoteParams, (descriptor, path) =>
- getJsonForBackend(descriptor, path, { timeoutMs: 10_000 })
+ total += await mergeRegistrySessionRows(
+ registrySources,
+ remoteParams,
+ (descriptor, path) => getJsonForBackend(descriptor, path, { timeoutMs: 10_000 }),
+ merged,
+ profileTotals
)
-
- const { added } = spliceRegistrySessionRows(merged, registryRows, profileTotals)
- total += added
}
const recency = s => s?.[order] ?? s?.started_at ?? 0
diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.ts
index 18660ad2496..244a9586ea3 100644
--- a/apps/desktop/electron/profile-session-routing.test.ts
+++ b/apps/desktop/electron/profile-session-routing.test.ts
@@ -3,8 +3,10 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
import {
+ applyRegistrySessionTotals,
assembleSidebarSessionSlices,
buildSidebarSessionSliceParams,
+ composeUnifiedSessionResponse,
fetchAllProfilesAggregatePerProfile,
fetchAllProfilesSessionsPerProfile,
fetchPrimaryProfileSessions,
@@ -188,6 +190,56 @@ test('a failed unified primary read names the whole aggregate', async () => {
assert.deepEqual(result.errors, [{ profile: 'all', error: 'timed out' }])
})
+test('a primary aggregate supplies the full prefix before Desktop applies a later merged window', async () => {
+ const calls: string[] = []
+
+ const rows = Array.from({ length: 650 }, (_, index) => ({
+ id: `s${index}`,
+ profile: 'default',
+ last_active: 1000 - index
+ }))
+
+ const params = new URLSearchParams({ profile: 'all', limit: '200', offset: '400', archived: 'only' })
+
+ const base = await fetchPrimaryProfileSessions(
+ params,
+ async (_profile, path) => {
+ calls.push(path)
+ const page = new URL(path, 'http://x').searchParams
+ const offset = Number(page.get('offset'))
+ const limit = Number(page.get('limit'))
+
+ return {
+ sessions: rows.slice(offset, offset + limit),
+ total: rows.length,
+ profile_totals: { default: rows.length },
+ limit,
+ offset
+ }
+ },
+ { prefixForMerge: true }
+ )
+
+ const merged = composeUnifiedSessionResponse(base, base.sessions, 400, 200, base.total, base.profile_totals, [])
+
+ assert.deepEqual(
+ merged.sessions.map((row: any) => row.id),
+ rows.slice(400, 600).map(row => row.id)
+ )
+ assert.equal(merged.limit, 200)
+ assert.equal(merged.offset, 400)
+ assert.deepEqual(
+ calls.map(path => [
+ Number(new URL(path, 'http://x').searchParams.get('limit')),
+ Number(new URL(path, 'http://x').searchParams.get('offset'))
+ ]),
+ [
+ [500, 0],
+ [100, 500]
+ ]
+ )
+})
+
test('reassembled sidebar slices keep each slice errors', () => {
const failed = [{ profile: 'default', error: 'timed out' }]
@@ -366,6 +418,132 @@ test('merged profile windows retain pinned rows outside the recency window', ()
assert.deepEqual(mergeProfileSessionWindow(rows, 0, 3), [rows[0], rows[1], rows[2], rows[3], rows[4]])
})
+test('registry paging uses the backend total instead of its fetched prefix or pinned backfill', async () => {
+ const rows = Array.from({ length: 650 }, (_, index) => ({
+ id: `s${index}`,
+ profile: 'work',
+ started_at: 650 - index,
+ pinned: index === 550 || index === 625
+ }))
+
+ const reported = new Map<string, number>()
+
+ const fetched = await fetchRegistrySessionRows(
+ [{ connectionId: 'gw', kind: 'remote', backends: [{ descriptor: 'remote', profileLabel: null }] }],
+ new URLSearchParams({ limit: '600', offset: '0', archived: 'exclude' }),
+ async (_descriptor, path) => {
+ const params = new URL(path, 'http://x').searchParams
+ const start = Number(params.get('offset'))
+ const limit = Number(params.get('limit'))
+ const window = rows.slice(start, start + limit)
+ const ids = new Set(window.map(row => row.id))
+
+ return {
+ sessions: [...window, ...rows.filter(row => row.pinned && !ids.has(row.id))],
+ total: 650,
+ profile_totals: { work: 650 }
+ }
+ },
+ reported
+ )
+
+ const merged: unknown[] = []
+ const profileTotals: Record<string, number> = {}
+ const { added } = spliceRegistrySessionRows(merged, fetched, profileTotals)
+
+ assert.equal(fetched.length, 601)
+ assert.equal(added, 601)
+ assert.equal(applyRegistrySessionTotals(fetched, merged, reported, profileTotals), 650)
+ assert.equal(profileTotals.work, 650)
+})
+
+test('a failed later registry page does not contribute a stale first-page total', async () => {
+ const reported = new Map<string, number>()
+
+ const rows = await fetchRegistrySessionRows(
+ [{ connectionId: 'gw', kind: 'remote', backends: [{ descriptor: 'remote', profileLabel: null }] }],
+ new URLSearchParams({ limit: '150', offset: '0' }),
+ async (_descriptor, path) => {
+ if (path.startsWith('/api/profiles/sessions') && path.includes('offset=0')) {
+ return {
+ sessions: Array.from({ length: 100 }, (_, i) => ({ id: `s${i}`, profile: 'work' })),
+ total: 150,
+ profile_totals: { work: 150 }
+ }
+ }
+
+ throw new Error('remote page unavailable')
+ },
+ reported
+ )
+
+ assert.deepEqual(rows, [])
+ assert.equal(reported.size, 0)
+})
+
+test('archived merged pages reach every archived row from older and current backends', async () => {
+ const archived = Array.from({ length: 400 }, (_, index) => ({
+ id: `a${index}`,
+ profile: 'default',
+ archived: true,
+ pinned: false,
+ last_active: 1000 - index
+ }))
+
+ const pins = ['p0', 'p1'].map((id, index) => ({
+ id,
+ profile: 'default',
+ archived: false,
+ pinned: true,
+ last_active: 2000 - index
+ }))
+
+ // An older backend windows archived rows and live pins together; the current
+ // one windows archived rows only and appends the pins.
+ const backends = {
+ older: (offset: number, limit: number) => {
+ const rows = [...pins, ...archived]
+ const window = rows.slice(offset, offset + limit)
+
+ return [...window, ...rows.slice(offset + limit).filter(row => row.pinned)]
+ },
+ current: (offset: number, limit: number) => [...archived.slice(offset, offset + limit), ...pins]
+ }
+
+ for (const [name, page] of Object.entries(backends)) {
+ const seen = new Set<string>()
+
+ for (const offset of [0, 200, 400]) {
+ const params = new URLSearchParams({ profile: 'all', limit: '200', offset: String(offset), archived: 'only' })
+
+ const base = await fetchPrimaryProfileSessions(
+ params,
+ async (_profile, path) => {
+ const query = new URL(path, 'http://x').searchParams
+
+ return {
+ sessions: page(Number(query.get('offset')), Number(query.get('limit'))),
+ total: archived.length,
+ profile_totals: { default: archived.length }
+ }
+ },
+ { prefixForMerge: true }
+ )
+
+ const merged = [...base.sessions].sort((a: any, b: any) => b.last_active - a.last_active)
+ const response = composeUnifiedSessionResponse(base, merged, offset, 200, base.total, base.profile_totals, [])
+
+ for (const row of response.sessions as typeof archived) {
+ if (row.archived) {
+ seen.add(row.id)
+ }
+ }
+ }
+
+ assert.equal(seen.size, archived.length, name)
+ }
+})
+
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 }
@@ -527,6 +705,34 @@ test('registry sources: large aggregate reads stay within the backend page cap',
assert.equal(result.length, rows.length)
})
+test('registry paging and splicing keep same-id sessions from different profiles', async () => {
+ const rows = Array.from({ length: 249 }, (_, index) => ({ id: `r-${index}`, profile: 'default' }))
+ rows.push({ id: 'shared', profile: 'default' }, { id: 'shared', profile: 'work' })
+
+ const fetched = await fetchRegistrySessionRows(
+ [{ connectionId: 'gw-cloud', kind: 'remote', backends: [{ descriptor: 'cloud-desc', profileLabel: null }] }],
+ new URLSearchParams({ limit: String(rows.length), offset: '0' }),
+ async (_descriptor, path) => {
+ const params = new URL(path, 'http://x').searchParams
+ const offset = Number(params.get('offset'))
+ const limit = Number(params.get('limit'))
+
+ return { sessions: rows.slice(offset, offset + limit), total: rows.length }
+ }
+ )
+
+ assert.equal(fetched.filter((row: any) => row.id === 'shared').length, 2)
+
+ const merged: unknown[] = [{ id: 'shared', profile: 'default', connection_id: 'gw-cloud' }]
+ const totals = { default: 1, work: 0 }
+ const { added } = spliceRegistrySessionRows(merged, fetched, totals)
+ assert.equal(added, rows.length - 1)
+ assert.deepEqual(
+ merged.filter((row: any) => row.id === 'shared').map((row: any) => row.profile),
+ ['default', 'work']
+ )
+})
+
test('registry-pinned session responses retain their owning connection', () => {
const sidebar = tagRegistrySessionResponse(
'/api/profiles/sessions/sidebar?recents_profile=default',
@@ -1046,6 +1252,38 @@ test('all-profiles session list pages a deep per-profile read under the backend
assert.equal(result.total, 650)
})
+test('all-profiles paging keeps every row once when pinned rows backfill across pages', async () => {
+ const rows = Array.from({ length: 650 }, (_, index) => ({
+ id: `s${index}`,
+ profile: 'default',
+ last_active: 1000 - index,
+ pinned: index === 550 || index === 625
+ }))
+
+ const result = (await fetchAllProfilesSessionsPerProfile(
+ '/api/profiles/sessions?limit=200&offset=400',
+ ['default'],
+ async (_p, path) => {
+ const params = new URL(path, 'http://x').searchParams
+ const offset = Number(params.get('offset'))
+ const limit = Number(params.get('limit'))
+ const window = rows.slice(offset, offset + limit)
+ const windowIds = new Set(window.map(row => row.id))
+
+ return {
+ sessions: [...window, ...rows.filter(row => row.pinned && !windowIds.has(row.id))],
+ total: rows.length,
+ profile_totals: { default: rows.length }
+ }
+ }
+ )) as any
+
+ assert.deepEqual(
+ result.sessions.map((row: { id: string }) => row.id),
+ [...rows.slice(400, 600).map(row => row.id), 's625']
+ )
+})
+
test('the project tree and PR scan are all-profiles reads whatever route scope they carry', () => {
assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/projects/tree?preview_limit=3'), true)
assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/projects/tree?preview_limit=3&profile=default'), true)
diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.ts
index 2e52d887fc0..5368492bde4 100644
--- a/apps/desktop/electron/profile-session-routing.ts
+++ b/apps/desktop/electron/profile-session-routing.ts
@@ -221,15 +221,27 @@ function errorsOf(data: unknown): SessionScanError[] | undefined {
return Array.isArray(errors) && errors.length ? (errors as SessionScanError[]) : undefined
}
-/** Fetch the primary backend's profile-aware session slice. A failed read is
- * still an empty page, but it carries `errors` naming the requested scope
- * (`all` for the unified list), like the backend's failed profile scan, so the
+/** Fetch the primary backend's profile-aware session slice. The unified merge
+ * needs the prefix through offset + limit because it sorts and windows again.
+ * A failed read is still an empty page with `errors` naming the scope, so the
* renderer keeps the rows it could not re-read instead of clearing them. */
export async function fetchPrimaryProfileSessions(
searchParams: URLSearchParams,
- fetchJsonForProfile: FetchJsonForProfile
+ fetchJsonForProfile: FetchJsonForProfile,
+ options: { prefixForMerge?: boolean } = {}
): Promise<ProfileSessionsResponse> {
try {
+ if (options.prefixForMerge) {
+ const url = new URL(`/api/profiles/sessions?${searchParams}`, 'http://desktop.local')
+ const limit = Math.max(1, Number(searchParams.get('limit')) || 20)
+ const offset = Math.max(0, Number(searchParams.get('offset')) || 0)
+ const profile = (searchParams.get('profile') || 'all').trim() || 'all'
+
+ return (await readProfileSessionRows(url, profile, limit + offset, (_profile, path) =>
+ fetchJsonForProfile(null, path)
+ )) as ProfileSessionsResponse
+ }
+
return (await fetchJsonForProfile(null, `/api/profiles/sessions?${searchParams}`)) as ProfileSessionsResponse
} catch (error) {
const profile = (searchParams.get('profile') || '').trim() || 'all'
@@ -342,7 +354,8 @@ type GetJsonForDescriptor = (descriptor: unknown, path: string) => Promise<unkno
async function fetchSessionRowsInPages(
basePath: string,
searchParams: URLSearchParams,
- getPage: (path: string) => Promise<unknown>
+ getPage: (path: string) => Promise<unknown>,
+ onFirstPage?: (page: unknown) => void
): Promise<unknown[] | null> {
const requestedLimit = Number(searchParams.get('limit'))
const requestedOffset = Number(searchParams.get('offset') || '0')
@@ -355,7 +368,10 @@ async function fetchSessionRowsInPages(
try {
if (!needsPaging) {
- return rowsOf(await getPage(`${basePath}?${searchParams}`))
+ const page = await getPage(`${basePath}?${searchParams}`)
+ onFirstPage?.(page)
+
+ return rowsOf(page)
}
const sessions: unknown[] = []
@@ -372,6 +388,8 @@ async function fetchSessionRowsInPages(
pageParams.set('offset', String(pageOffset))
const page = await getPage(`${basePath}?${pageParams}`)
+ onFirstPage?.(page)
+ onFirstPage = undefined
const pageRows = rowsOf(page)
const total = nonNegativeNumber(page && typeof page === 'object' ? (page as { total?: unknown }).total : null)
@@ -380,7 +398,7 @@ async function fetchSessionRowsInPages(
total !== null ? Math.min(pageLimit, Math.max(0, total - pageOffset)) : Math.min(pageLimit, pageRows.length)
for (const row of pageRows.slice(0, windowedCount)) {
- const id = sessionId(row)
+ const id = profileSessionId(row)
if (id && seenIds.has(id)) {
continue
@@ -395,7 +413,7 @@ async function fetchSessionRowsInPages(
}
for (const row of pageRows.slice(windowedCount)) {
- const id = sessionId(row)
+ const id = profileSessionId(row)
if ((id && seenIds.has(id)) || (id && backfilledIds.has(id))) {
continue
@@ -416,7 +434,7 @@ async function fetchSessionRowsInPages(
}
for (const row of backfilled) {
- const id = sessionId(row)
+ const id = profileSessionId(row)
if (id && seenIds.has(id)) {
continue
@@ -452,10 +470,42 @@ async function fetchSessionRowsInPages(
export async function fetchRegistrySessionRows(
sources: RegistrySessionSource[],
searchParams: URLSearchParams,
- getJson: GetJsonForDescriptor
+ getJson: GetJsonForDescriptor,
+ reportedTotals?: Map<string, number>
): Promise<unknown[]> {
const rows: unknown[] = []
+ const recordTotals = (page: unknown, connectionId: string, profileLabel: null | string) => {
+ if (!reportedTotals || !page || typeof page !== 'object') {
+ return
+ }
+
+ const data = page as { total?: unknown; profile_totals?: unknown }
+ const totals = data.profile_totals
+
+ if (profileLabel === null) {
+ // An older aggregate without profile_totals keeps its existing row-count fallback;
+ // assigning its grand total to "default" would double-count named profile rows.
+ if (totals && typeof totals === 'object' && !Array.isArray(totals)) {
+ for (const [profile, value] of Object.entries(totals)) {
+ const count = nonNegativeNumber(value)
+
+ if (count !== null) {
+ reportedTotals.set(`${connectionId}\0${profile}`, count)
+ }
+ }
+ }
+
+ return
+ }
+
+ const count = nonNegativeNumber(data.total)
+
+ if (count !== null) {
+ reportedTotals.set(`${connectionId}\0${profileLabel || 'default'}`, count)
+ }
+ }
+
const tag = (sourceRows: unknown[], connectionId: string, profileLabel: null | string) => {
for (const row of sourceRows) {
if (!row || typeof row !== 'object') {
@@ -485,10 +535,19 @@ export async function fetchRegistrySessionRows(
source.backends.map(async ({ descriptor, profileLabel }) => {
const params = new URLSearchParams(searchParams)
params.delete('profile')
-
- const sourceRows = await fetchSessionRowsInPages('/api/sessions', params, path => getJson(descriptor, path))
+ let firstPage: unknown
+
+ const sourceRows = await fetchSessionRowsInPages(
+ '/api/sessions',
+ params,
+ path => getJson(descriptor, path),
+ page => {
+ firstPage = page
+ }
+ )
if (sourceRows) {
+ recordTotals(firstPage, source.connectionId, profileLabel || 'default')
tag(sourceRows, source.connectionId, profileLabel || 'default')
}
})
@@ -507,19 +566,36 @@ export async function fetchRegistrySessionRows(
const params = new URLSearchParams(searchParams)
params.set('profile', 'all')
-
- let sourceRows = await fetchSessionRowsInPages('/api/profiles/sessions', params, path =>
- getJson(shared.descriptor, path)
+ let firstPage: unknown
+ let aggregate = true
+
+ let sourceRows = await fetchSessionRowsInPages(
+ '/api/profiles/sessions',
+ params,
+ path => getJson(shared.descriptor, path),
+ page => {
+ firstPage = page
+ }
)
if (!sourceRows) {
// Older remote without the aggregator: its own default-profile list.
const flat = new URLSearchParams(searchParams)
flat.delete('profile')
- sourceRows = await fetchSessionRowsInPages('/api/sessions', flat, path => getJson(shared.descriptor, path))
+ firstPage = undefined
+ aggregate = false
+ sourceRows = await fetchSessionRowsInPages(
+ '/api/sessions',
+ flat,
+ path => getJson(shared.descriptor, path),
+ page => {
+ firstPage = page
+ }
+ )
}
if (sourceRows) {
+ recordTotals(firstPage, source.connectionId, aggregate ? null : 'default')
tag(sourceRows, source.connectionId, null)
}
})
@@ -529,7 +605,7 @@ export async function fetchRegistrySessionRows(
}
/** Splice registry-gateway rows into an already-merged unified list: dedupe by
- * session id (a v1 remote-override splice may already carry a row), keep the
+ * profile + session id (a v1 remote-override splice may already carry a row), keep the
* recency sort, and extend the per-profile totals so truncation flags stay
* honest. Mutates and returns `merged`/`profileTotals` the way the v1 splice
* does. */
@@ -538,11 +614,11 @@ export function spliceRegistrySessionRows(
registryRows: unknown[],
profileTotals: Record<string, number>
): { added: number } {
- const seen = new Set(merged.map(sessionId).filter((id): id is string => id !== null))
+ const seen = new Set(merged.map(profileSessionId).filter((id): id is string => id !== null))
let added = 0
for (const row of registryRows) {
- const id = sessionId(row)
+ const id = profileSessionId(row)
if (id && seen.has(id)) {
continue
@@ -566,6 +642,65 @@ export function spliceRegistrySessionRows(
return { added }
}
+/** Report full registry totals, minus rows already supplied by the primary/override path.
+ * The fetched prefix can be shorter than the backend's total and can include pins outside
+ * the ordinary cursor, so counting only its rows undercounts deep pages or overcounts pins. */
+export function applyRegistrySessionTotals(
+ fetchedRows: unknown[],
+ addedRows: unknown[],
+ reportedTotals: Map<string, number>,
+ profileTotals: Record<string, number>
+): number {
+ const counts = (rows: unknown[]) => {
+ const perScope = new Map<string, number>()
+
+ for (const row of rows) {
+ if (!row || typeof row !== 'object') {
+ continue
+ }
+
+ const session = row as Record<string, unknown>
+ const connection = typeof session.connection_id === 'string' ? session.connection_id : ''
+ const profile = typeof session.profile === 'string' && session.profile ? session.profile : 'default'
+ const key = `${connection}\0${profile}`
+ perScope.set(key, (perScope.get(key) || 0) + 1)
+ }
+
+ return perScope
+ }
+
+ const fetched = counts(fetchedRows)
+ const added = counts(addedRows)
+ let contribution = 0
+
+ for (const key of new Set([...fetched.keys(), ...reportedTotals.keys()])) {
+ const addedCount = added.get(key) || 0
+ const duplicates = (fetched.get(key) || 0) - addedCount
+ const count = reportedTotals.has(key) ? Math.max(0, reportedTotals.get(key)! - duplicates) : addedCount
+ const profile = key.slice(key.indexOf('\0') + 1)
+ profileTotals[profile] = (profileTotals[profile] || 0) + count - addedCount
+ contribution += count
+ }
+
+ return contribution
+}
+
+/** Fetch and merge one registry scan, retaining its backend totals for deep pages. */
+export async function mergeRegistrySessionRows(
+ sources: RegistrySessionSource[],
+ searchParams: URLSearchParams,
+ getJson: GetJsonForDescriptor,
+ merged: unknown[],
+ profileTotals: Record<string, number>
+): Promise<number> {
+ const reportedTotals = new Map<string, number>()
+ const registryRows = await fetchRegistrySessionRows(sources, searchParams, getJson, reportedTotals)
+ const before = merged.length
+ spliceRegistrySessionRows(merged, registryRows, profileTotals)
+
+ return applyRegistrySessionTotals(registryRows, merged.slice(before), reportedTotals, profileTotals)
+}
+
/**
* The remote-profile query scope for a per-profile override read: the remote
* alias when the override is a managed SSH connection with a configured
@@ -881,7 +1016,10 @@ export function applyRemoteProfileSessionOutcomes(
/** Compose the unified aggregate's response (#75712): failures ride the
* payload, not the void — base scan errors and each dead remote's named
* error entry are merged into `errors` so a failed remote profile is
- * identifiable. */
+ * identifiable. The window counts every merged row, live pins included, even
+ * on an archived-only page: an older backend's page lets a live pin take an
+ * archived position, so a window over archived rows alone would skip the
+ * archived rows that pin pushed past this source's prefix. */
export function composeUnifiedSessionResponse(
base: unknown,
merged: unknown[],
@@ -902,6 +1040,8 @@ export function composeUnifiedSessionResponse(
sessions: mergeProfileSessionWindow(merged, offset, limit),
total,
profile_totals: profileTotals,
+ limit,
+ offset,
...(scanErrors.length ? { errors: scanErrors } : {})
}
}
@@ -981,11 +1121,13 @@ async function readEachProfile(
)
}
-/** One profile's rows from offset 0 through `want`, in pages the backend accepts. The first
- * page carries the profile's totals. */
+/** One scope's rows from offset 0 through `want`, in backend-sized pages.
+ * Pinned backfill repeats across pages; keep one row per profile/session before
+ * the merged list is sorted and windowed. The first page carries totals. */
async function readProfileSessionRows(url: URL, profile: string, want: number, fetchPage: FetchProfilePage) {
let first: any
const rows: unknown[] = []
+ const seen = new Set<string>()
for (let offset = 0; ; ) {
const params = new URLSearchParams(url.searchParams)
@@ -997,7 +1139,21 @@ async function readProfileSessionRows(url: URL, profile: string, want: number, f
const page = (await fetchPage(profile, `${url.pathname}?${params}`)) as any
const pageRows = rowsOf(page)
first ??= page
- rows.push(...pageRows)
+
+ for (const row of pageRows) {
+ const id = profileSessionId(row)
+
+ if (id && seen.has(id)) {
+ continue
+ }
+
+ rows.push(row)
+
+ if (id) {
+ seen.add(id)
+ }
+ }
+
offset += limit
if (offset >= want || pageRows.length < limit) {
diff --git a/apps/desktop/src/store/sidebar-archive.test.ts b/apps/desktop/src/store/sidebar-archive.test.ts
index ed81768396f..f15fc2ab193 100644
--- a/apps/desktop/src/store/sidebar-archive.test.ts
+++ b/apps/desktop/src/store/sidebar-archive.test.ts
@@ -49,6 +49,22 @@ beforeEach(() => {
})
describe('loadArchivedSessions', () => {
+ it('keeps same-id archived sessions from different profiles across pages', async () => {
+ listAllProfileSessions
+ .mockResolvedValueOnce({
+ sessions: [row('same', { profile: 'default' }), ...page(1, PAGE_SIZE - 1)],
+ total: PAGE_SIZE + 1
+ })
+ .mockResolvedValueOnce({ sessions: [row('same', { profile: 'work' })], total: PAGE_SIZE + 1 })
+
+ const sessions = await listEveryArchivedSession()
+
+ expect(sessions.filter(session => session.id === 'same').map(session => session.profile)).toEqual([
+ 'default',
+ 'work'
+ ])
+ })
+
it('keeps the last successful result when a refresh fails', async () => {
const existing = { id: 'archived-1', title: 'Keep me' } as SessionInfo
$archivedSessions.set([existing])
@@ -155,6 +171,37 @@ describe('loadArchivedSessions', () => {
})
describe('listEveryArchivedSession', () => {
+ it('keeps paging when a live pin displaced the last archived row', async () => {
+ listAllProfileSessions
+ .mockResolvedValueOnce({ sessions: [pinnedRow('pin-x'), ...page(0, PAGE_SIZE - 1)], total: PAGE_SIZE })
+ .mockResolvedValueOnce({ sessions: [row(`a-${PAGE_SIZE - 1}`), pinnedRow('pin-x')], total: PAGE_SIZE })
+
+ const sessions = await listEveryArchivedSession()
+
+ expect(sessions.filter(session => session.archived)).toHaveLength(PAGE_SIZE)
+ expect(sessions.filter(session => session.id === 'pin-x')).toHaveLength(1)
+ expect(listAllProfileSessions).toHaveBeenCalledTimes(2)
+ })
+
+ it('stops past the total when only live pins arrive', async () => {
+ // A row archived mid-load behind the cursor leaves the count one short,
+ // and the backend still back-fills the live pin past the end.
+ listAllProfileSessions.mockImplementation(async (...args: unknown[]) => {
+ const offset = args[6] as number
+
+ if (offset > 4 * PAGE_SIZE) {
+ throw new Error('archived paging did not stop')
+ }
+
+ return { sessions: [...page(offset, Math.max(0, PAGE_SIZE - offset)), pinnedRow('pin-x')], total: PAGE_SIZE + 1 }
+ })
+
+ const sessions = await listEveryArchivedSession()
+
+ expect(sessions.filter(session => session.archived)).toHaveLength(PAGE_SIZE)
+ expect(listAllProfileSessions).toHaveBeenCalledTimes(2)
+ })
+
it('paginates until the backend total is loaded', async () => {
const firstPage = Array.from({ length: 200 }, (_, i) => row(`a${i}`))
diff --git a/apps/desktop/src/store/sidebar-archive.ts b/apps/desktop/src/store/sidebar-archive.ts
index 4c54cba9f1a..8457442f5e5 100644
--- a/apps/desktop/src/store/sidebar-archive.ts
+++ b/apps/desktop/src/store/sidebar-archive.ts
@@ -22,32 +22,46 @@ const ARCHIVED_FETCH_PAGE_SIZE = 200
* cursor the server's pagination contract guarantees.
*
* Back-filled pins can repeat across pages (a pinned row past the window is
- * re-appended by every page whose window covers it), so rows dedupe by id on
- * the way in. Termination: `page.total` counts only archived rows (the pin
- * back-fill can't inflate it), so once the cursor has consumed `total`
- * positions every archived row has been requested. An empty page also stops
- * the loop — the server returns one only past the end (or when profiles
- * changed under us mid-pagination), never mid-list.
+ * re-appended by every page whose window covers it), so rows dedupe by owner
+ * and id on the way in. Termination: `page.total` counts only archived rows, so stop
+ * after that many distinct archived rows have arrived. Older backends can
+ * let a live pin displace an archived row from a page; cursor >= total would
+ * leave that final row unread. An empty page also stops the loop. Live pins
+ * can ride along even past the end, so once the cursor has covered `total`,
+ * a page with no new archived row stops it too: a row archived or reordered
+ * mid-load can leave the distinct count short for good.
*/
export async function listEveryArchivedSession(): Promise<SessionInfo[]> {
const sessions: SessionInfo[] = []
const seen = new Set<string>()
+ let archivedCount = 0
let offset = 0
while (true) {
const page = await listAllProfileSessions(ARCHIVED_FETCH_PAGE_SIZE, 0, 'only', 'recent', 'all', {}, offset)
+ const archivedBefore = archivedCount
for (const session of page.sessions) {
- if (!seen.has(session.id)) {
- seen.add(session.id)
+ const identity = `${session.connection_id || ''}\0${session.profile || 'default'}\0${session.id}`
+
+ if (!seen.has(identity)) {
+ seen.add(identity)
sessions.push(session)
+
+ if (session.archived) {
+ archivedCount += 1
+ }
}
}
offset += ARCHIVED_FETCH_PAGE_SIZE
- if (page.sessions.length === 0 || offset >= page.total) {
+ if (
+ page.sessions.length === 0 ||
+ archivedCount >= page.total ||
+ (offset >= page.total && archivedCount === archivedBefore)
+ ) {
return sessions
}
}
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index d55f37a86d7..8c60f23c4c5 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -503,7 +503,14 @@ def get_profiles_sessions(
sort_key = "last_active" if order == "recent" else "started_at"
merged.sort(key=lambda s: s.get(sort_key) or s.get("started_at") or 0, reverse=True)
- window = _pinned_window(merged, offset, limit)
+ if archived == "only":
+ # Pinned live chats back-fill this view, but cannot consume positions
+ # in its archived-only cursor (whose total counts only archived rows).
+ window = _pinned_window([s for s in merged if s.get("archived")], offset, limit)
+ # Keep backfill after the window: clients retain only limit rows plus pins.
+ window.extend(s for s in merged if s.get("pinned") and not s.get("archived"))
+ else:
+ window = _pinned_window(merged, offset, limit)
if not full:
_strip_session_list_rows(window)
return {"sessions": window, "total": sum(totals.values()), "profile_totals": totals,
diff --git a/tests/hermes_cli/test_profiles_session_archived_pages.py b/tests/hermes_cli/test_profiles_session_archived_pages.py
new file mode 100644
index 00000000000..5528892665b
--- /dev/null
+++ b/tests/hermes_cli/test_profiles_session_archived_pages.py
@@ -0,0 +1,36 @@
+"""Archived profile pages count archived rows even when live pins back-fill."""
+
+from starlette.testclient import TestClient
+
+
+def test_archived_profiles_pages_do_not_lose_rows_to_non_archived_pins(_isolate_hermes_home, monkeypatch):
+ import hermes_state
+ from hermes_constants import get_hermes_home
+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
+ from hermes_state import SessionDB
+
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
+ client = TestClient(app)
+ client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+
+ db = SessionDB()
+ try:
+ for sid in ("archive-a", "archive-b"):
+ db.create_session(session_id=sid, source="cli")
+ db.append_message(session_id=sid, role="user", content="hi")
+ db.set_session_archived(sid, True)
+ db.create_session(session_id="live-pin", source="cli")
+ db.append_message(session_id="live-pin", role="user", content="hi")
+ db.set_session_pinned("live-pin", True)
+ finally:
+ db.close()
+
+ for route in ("/api/profiles/sessions?profile=default", "/api/sessions?profile=default"):
+ pages = [client.get(f"{route}&limit=1&offset={offset}&archived=only") for offset in (0, 1)]
+ assert all(response.status_code == 200 for response in pages)
+ assert [response.json()["total"] for response in pages] == [2, 2]
+ assert {row["id"] for response in pages for row in response.json()["sessions"] if row["archived"]} == {"archive-a", "archive-b"}
+ # Desktop keeps the first limit rows plus pins. Backfill must follow
+ # the archived window or that trim discards an archived row forever.
+ assert all(response.json()["sessions"][0]["archived"] for response in pages)
+ assert all(any(row["id"] == "live-pin" for row in response.json()["sessions"]) for response in pages)