The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): list every profile's sessions over native per-profile grants
unsupportedpastels105b098dac21
diff --git a/apps/desktop/e2e/legacy-desktop-history.spec.ts b/apps/desktop/e2e/legacy-desktop-history.spec.tsnew file mode 100644index 00000000000..a601823e985--- /dev/null+++ b/apps/desktop/e2e/legacy-desktop-history.spec.ts@@ -0,0 +1,169 @@+import { spawnSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+import { startMockServer } from '../../../tests-js/scripts/mock-server'+import { buildAppEnv, createSandbox, launchDesktop } from './fixtures'+import { expect, test } from './test'++// Pre-cutover Desktop rows as main writes them (source='desktop', profile stamped, optional+// Nous user_id), on an install with a second profile that has history of its own. A native+// HTTP grant covers one profile, so every cross-profile session list must still list them.+const ROWS = [+ { id: 'legacy-desktop-anon', source: 'desktop', userId: null },+ { id: 'legacy-desktop-nous', source: 'desktop', userId: 'nous:e2e-user' },+ { id: 'legacy-tui-control', source: 'tui', userId: null }+]++const NAMED_ROW = 'legacy-developer-desktop'++test('pre-cutover Desktop conversations remain visible and open across profiles', async () => {+ test.setTimeout(300_000)+ const sandbox = createSandbox('legacy-desktop-history')+ const mock = await startMockServer()+ const python = process.env.HERMES_DESKTOP_PYTHON!+ const root = path.resolve(import.meta.dirname, '../../..')+ const env = buildAppEnv(sandbox, { HERMES_DESKTOP_PYTHON: python, TIRITH_ENABLED: 'false' })+ const multiplex = process.env.E2E_MULTIPLEX === '1'+ writeMockProviderConfig(sandbox.hermesHome, mock.url, undefined, multiplex ? 'gateway:\n multiplex_profiles: true\n' : undefined)+ writeEnvFile(sandbox.hermesHome)+ const named = path.join(sandbox.hermesHome, 'profiles', 'developer')+ fs.mkdirSync(named, { recursive: true })+ writeMockProviderConfig(named, mock.url)+ writeEnvFile(named)+ const seed = spawnSync(python, ['-c', `+import json, os, sys+from pathlib import Path+from hermes_state import SessionDB++def seed(db_path, rows, profile):+ with SessionDB(db_path=db_path) as db:+ for r in rows:+ db.create_session(r['id'], source=r['source'], model='e2e-mock', cwd=os.environ['HOME'], user_id=r['userId'])+ db.set_session_title(r['id'], 'Retained ' + r['id'])+ db.append_message(r['id'], 'user', 'Historical question ' + r['id'])+ db.append_message(r['id'], 'assistant', 'Historical answer ' + r['id'])+ db._conn.execute('UPDATE sessions SET profile_name=? WHERE id=?', (profile, r['id']))+ db._conn.commit()++home = Path(os.environ['HERMES_HOME'])+seed(home / 'state.db', json.loads(sys.argv[1]), 'default')+seed(home / 'profiles' / 'developer' / 'state.db', [{'id': sys.argv[2], 'source': 'desktop', 'userId': None}], 'developer')+`, JSON.stringify(ROWS), NAMED_ROW], { cwd: root, env: { ...env, PYTHONPATH: root }, encoding: 'utf8' })+ expect(seed.status, seed.stderr).toBe(0)+ // An existing install has a startup profile; without one the first-launch migration guesses+ // from the newest state.db, which here is the named profile's.+ fs.writeFileSync(path.join(sandbox.userDataDir, 'active-profile.json'), JSON.stringify({ profile: 'default' }))+ let app: Awaited<ReturnType<typeof launchDesktop>>['app'] | undefined+ const evidence = process.env.HERMES_E2E_EVIDENCE || path.join(sandbox.root, 'evidence')+ fs.mkdirSync(evidence, { recursive: true })+ const results: Record<string, { listed: boolean; opened: boolean; error?: string }> = {}+ let probes: Record<string, unknown> = {}++ try {+ const launched = await launchDesktop(env)+ app = launched.app+ const page = launched.page+ const sidebar = page.locator('[data-slot="sidebar"]')++ try {+ await expect(page.getByRole('button', { name: /developer/ }).first()).toBeVisible({ timeout: 90_000 })++ // The cross-profile lists the sidebar and Sessions view read, through main's transport.+ probes = await page.evaluate(async () => {+ const api = (window as any).hermesDesktop.api+ const out: Record<string, unknown> = {}+ const q = 'limit=40&offset=0&min_messages=1&archived=exclude&order=recent'+ const calls: Record<string, string> = {+ 'sidebar:default': '/api/profiles/sessions/sidebar?recents_profile=default&recents_limit=40&cron_limit=5&messaging_limit=5',+ 'sidebar:developer': '/api/profiles/sessions/sidebar?recents_profile=developer&recents_limit=40&cron_limit=5&messaging_limit=5',+ 'sidebar:all': '/api/profiles/sessions/sidebar?recents_profile=all&recents_limit=40&cron_limit=5&messaging_limit=5',+ 'sessions:all': `/api/profiles/sessions?${q}&profile=all`+ }++ for (const [name, path] of Object.entries(calls)) {+ try {+ const r = await api({ path })+ const rows = r?.recents ? r.recents.sessions : r?.sessions+ out[name] = { ids: (rows ?? []).map((x: any) => `${x.profile}:${x.id}`).sort(), errors: r?.errors ?? [] }+ } catch (e) {+ out[name] = 'ERR ' + String((e as Error)?.message ?? e).slice(0, 200)+ }+ }++ return out+ })+ console.log('API_PROBES: ' + JSON.stringify(probes))++ await expect(sidebar.getByText(/Retained legacy-/).first()).toBeVisible({ timeout: 30_000 }).catch(() => undefined)+ await page.screenshot({ path: path.join(evidence, 'sidebar.png') })++ for (const row of [...ROWS, { id: NAMED_ROW }]) {+ if (row.id === NAMED_ROW) {+ await page.getByRole('button', { name: /developer/ }).first().click()+ }++ const entry = sidebar.getByText('Retained ' + row.id, { exact: true })+ await entry.waitFor({ state: 'visible', timeout: 30_000 }).catch(() => undefined)+ const listed = await entry.isVisible()+ results[row.id] = { listed, opened: false }++ if (!listed) {+ continue+ }++ await entry.click()+ const answer = page.locator('[data-slot="aui_thread-viewport"]').getByText('Historical answer ' + row.id)+ const failure = page.getByText("Couldn't open this session")+ await expect(answer.or(failure).first()).toBeVisible({ timeout: 45_000 }).catch(() => undefined)+ results[row.id].opened = await answer.isVisible()++ if (!results[row.id].opened) {+ results[row.id].error = (await page.locator('body').innerText()).match(/Couldn't open this session\s*\n?\s*(\S+)/)?.[1] ?? 'no transcript'+ }++ await page.screenshot({ path: path.join(evidence, `open-${row.id}.png`) })+ }+ } finally {+ console.log('LEGACY_DESKTOP_RESULTS: ' + JSON.stringify(results))+ fs.writeFileSync(path.join(evidence, 'results.json'), JSON.stringify({ results, probes }, null, 2))++ for (const name of ['gateway.log', 'errors.log', 'desktop.log']) {+ const log = path.join(sandbox.hermesHome, 'logs', name)++ if (fs.existsSync(log)) {+ fs.copyFileSync(log, path.join(evidence, name))+ }+ }+ }+ } finally {+ await app?.close().catch(() => undefined)+ await mock.close()+ spawnSync(python, ['-c', `+import psutil,sys,os+home=sys.argv[1]+owned=[]+for p in psutil.process_iter():+ if p.pid==os.getpid(): continue+ try:+ if p.environ().get('HERMES_HOME')==home:+ owned.append(p);p.terminate()+ except (psutil.NoSuchProcess,psutil.AccessDenied): pass+_,alive=psutil.wait_procs(owned,timeout=5)+for p in alive:+ try:p.kill()+ except psutil.NoSuchProcess:pass+`, sandbox.hermesHome], { encoding: 'utf8', env: process.env })+ sandbox.cleanup()+ }++ const everyRow = [...ROWS.map(r => `default:${r.id}`), `developer:${NAMED_ROW}`].sort()+ expect.soft(probes['sidebar:all'], 'sidebar:all').toEqual({ ids: everyRow, errors: [] })+ expect.soft(probes['sessions:all'], 'sessions:all').toEqual({ ids: everyRow, errors: [] })+ expect.soft(probes['sidebar:default'], 'sidebar:default').toEqual({ ids: ROWS.map(r => `default:${r.id}`).sort(), errors: [] })+ expect.soft(probes['sidebar:developer'], 'sidebar:developer').toEqual({ ids: [`developer:${NAMED_ROW}`], errors: [] })++ for (const row of [...ROWS, { id: NAMED_ROW }]) {+ expect.soft(results[row.id], row.id).toEqual({ listed: true, opened: true })+ }+})diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex e8998cb8092..8b87704c6f6 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -415,6 +415,16 @@ test('a ?profile= request on the shared host descriptor mints for the sibling prexpect(() => routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/x?profile=../evil', path.resolve('hermes-home'))).toThrow('Invalid profile route')})+// The batched sidebar names its owner in `recents_profile`; a grant for the window's own profile+// is refused there (profile_scope_mismatch) and the sidebar drops that profile's sessions.+test('a sidebar read mints for the profile its recents_profile names', () => {+ const endpoint = { profile_id: path.resolve('hermes-home', 'profiles', 'p2'), instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: path.resolve('hermes-home') }+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=default&recents_limit=40', path.resolve('hermes-home'))).toMatchObject({ profile_id: path.resolve('hermes-home') })+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=p2', path.resolve('hermes-home'))).toBe(endpoint)+ // `profile` is not the sidebar's selector.+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/profiles/sessions/sidebar?profile=default&recents_profile=p2', path.resolve('hermes-home'))).toBe(endpoint)+})+// A native gateway grant is minted only by main's shared transport (fetchJsonForBackend), which// also carries the descriptor's configured headers; a call site that hands fetchJson a// gatewayDescriptor itself silently drops them. Source guard over the one module that issues them.diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex 0236677874a..7978e9dd68b 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -312,11 +312,17 @@ function shellQuote(file: string): string {return `'${file.replace(/'/g, `'\\''`)}'`}+/** The batched sidebar names its owner in `recents_profile` (the gateway checks that selector);+ * every other profile-scoped route uses `profile`. */+function scopedProfileOf(url: URL): null | string {+ return url.searchParams.get(url.pathname.replace(/\/+$/, '') === '/api/profiles/sessions/sidebar' ? 'recents_profile' : 'profile')+}+/** The endpoint a `?profile=<name>` request is scoped to on a shared host descriptor: the same* daemon, ticket minted for the sibling profile's home (`profiles/<name>` under the launch root).* The gateway refuses a ticket whose profile it does not serve, so a bad name fails closed. */export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, _launchHome: string): GatewayEndpoint {- const profile = (/^[a-z]+:\/\//.test(urlOrProfile) ? new URL(urlOrProfile).searchParams.get('profile') : urlOrProfile)?.trim()+ const profile = (/^[a-z]+:\/\//.test(urlOrProfile) ? scopedProfileOf(new URL(urlOrProfile)) : urlOrProfile)?.trim()if (!profile || profile === 'current') {return endpoint}const own = path.basename(endpoint.profile_id)diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 8f12c6a2aac..3abf73578e5 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -463,6 +463,7 @@ import {assembleSidebarSessionSlices,buildSidebarSessionSliceParams,composeUnifiedSessionResponse,+ fetchAllProfilesSessionsPerProfile,fetchPrimaryProfileSessions,fetchRegistrySessionRows,fetchRemoteProfileSessions,@@ -15587,6 +15588,20 @@ async function fetchJsonForBackend() {const url = `${descriptor.baseUrl}${path}`+ // A native grant names one profile and the gateway refuses `all`: assemble the unified+ // session lists from one read per profile, each carrying that profile's own grant.+ if (descriptor.gatewayEndpoint && isAllProfilesSessionListRequest(opts.method, path)) {+ const listing = (await fetchJsonForBackend(descriptor, '/api/profiles', { timeoutMs: opts.timeoutMs })) as any++ const profiles = (Array.isArray(listing?.profiles) ? listing.profiles : [])+ .map(profile => profile?.name)+ .filter(name => typeof name === 'string' && name)++ return fetchAllProfilesSessionsPerProfile(path, profiles, (_profile, scoped) =>+ fetchJsonForBackend(descriptor, scoped, { timeoutMs: opts.timeoutMs })+ )+ }+if (descriptor.authMode === 'oauth') {// The OAuth cookie path rides electron.net with JSON headers; multipart// isn't wired there. Fail loudly rather than corrupting the upload.diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.tsindex c6367dfdc55..4f083bdb395 100644--- a/apps/desktop/electron/profile-session-routing.test.ts+++ b/apps/desktop/electron/profile-session-routing.test.ts@@ -5,6 +5,7 @@ import { test } from 'vitest'import {assembleSidebarSessionSlices,buildSidebarSessionSliceParams,+ fetchAllProfilesSessionsPerProfile,fetchPrimaryProfileSessions,fetchRegistrySessionRows,fetchRemoteProfileSessions,@@ -829,3 +830,170 @@ test('remoteProfileQueryScope resolves the wire scope for a profile override', (assert.equal(remoteProfileQueryScope('default', 'dixie'), 'dixie')assert.equal(remoteProfileQueryScope(''), '')})++// A native gateway grant names one profile and the gateway refuses `all`, so a local native+// backend's unified lists are read profile by profile and merged like the backend's own scan.+test('all-profiles session list is merged from one read per profile', async () => {+ const reads: string[] = []++ const pages: Record<string, unknown> = {+ default: {+ sessions: [+ { id: 'd-new', profile: 'default', last_active: 30 },+ { id: 'd-old', profile: 'default', last_active: 10 },+ { id: 'd-pin', profile: 'default', last_active: 1, pinned: true }+ ],+ total: 3,+ profile_totals: { default: 3 },+ errors: [],+ storage: {}+ },+ work: {+ sessions: [{ id: 'w-mid', profile: 'work', last_active: 20 }],+ total: 1,+ profile_totals: { work: 1 },+ errors: [],+ storage: { work: 'corrupt' }+ }+ }++ const result = (await fetchAllProfilesSessionsPerProfile(+ '/api/profiles/sessions?limit=2&offset=0&min_messages=1&profile=all',+ ['default', 'work', 'gone'],+ async (profile, path) => {+ reads.push(path)++ if (!(profile in pages)) {+ throw new Error('403: profile_scope_mismatch')+ }++ return pages[profile]+ }+ )) as any++ assert.deepEqual(reads.sort(), [+ '/api/profiles/sessions?limit=2&offset=0&min_messages=1&profile=default',+ '/api/profiles/sessions?limit=2&offset=0&min_messages=1&profile=gone',+ '/api/profiles/sessions?limit=2&offset=0&min_messages=1&profile=work'+ ])+ // Recency across profiles, window of 2, pinned rows past the window back-filled.+ assert.deepEqual(result.sessions.map((s: any) => s.id), ['d-new', 'w-mid', 'd-pin'])+ assert.equal(result.total, 4)+ assert.deepEqual(result.profile_totals, { default: 3, work: 1 })+ assert.deepEqual(result.storage, { work: 'corrupt' })+ // A profile that cannot be read is a named failure, never a silent empty list.+ assert.deepEqual(result.errors, [{ profile: 'gone', error: '403: profile_scope_mismatch' }])+})++test('all-profiles session list over-fetches each profile for a later page', async () => {+ const reads: string[] = []++ await fetchAllProfilesSessionsPerProfile('/api/profiles/sessions?limit=20&offset=40&order=created', ['default'], async (_p, path) => {+ reads.push(path)++ return { sessions: [], total: 0, profile_totals: {} }+ })++ assert.deepEqual(reads, ['/api/profiles/sessions?limit=60&offset=0&order=created&profile=default'])+})++test('all-profiles sidebar is merged from one batched read per profile', async () => {+ const pages: Record<string, unknown> = {+ default: {+ recents: {+ sessions: [{ id: 'd1', profile: 'default', last_active: 5 }],+ profiles_truncated: { default: false },+ profiles_usage: { default: { cost_usd: 1, tokens: 10 } }+ },+ cron: { sessions: [{ id: 'dc', profile: 'default', started_at: 3 }] },+ messaging: { sessions: [{ id: 'dm', profile: 'default', last_active: 2 }], total: 1 },+ errors: [],+ storage: {}+ },+ work: {+ recents: {+ sessions: [{ id: 'w1', profile: 'work', last_active: 9 }],+ profiles_truncated: { work: true },+ profiles_usage: { work: { cost_usd: 2, tokens: 20 } }+ },+ cron: { sessions: [] },+ messaging: { sessions: [{ id: 'wm', profile: 'work', last_active: 4 }], total: 3 },+ errors: [],+ storage: {}+ },+ broken: {+ recents: { failed: true, retry: true, errors: [{ profile: 'broken', error: 'database is locked' }] },+ cron: { failed: true, retry: true, errors: [{ profile: 'broken', error: 'database is locked' }] },+ messaging: { failed: true, retry: true, errors: [{ profile: 'broken', error: 'database is locked' }], total: 0 },+ errors: [{ profile: 'broken', error: 'database is locked' }],+ storage: {}+ }+ }++ const reads: string[] = []++ const result = (await fetchAllProfilesSessionsPerProfile(+ '/api/profiles/sessions/sidebar?recents_profile=all&recents_limit=40&cron_limit=5&messaging_limit=5',+ ['default', 'work', 'broken'],+ async (profile, path) => {+ reads.push(path)++ return pages[profile]+ }+ )) as any++ assert.ok(reads.includes('/api/profiles/sessions/sidebar?recents_profile=work&recents_limit=40&cron_limit=5&messaging_limit=5'))+ assert.deepEqual(result.recents.sessions.map((s: any) => s.id), ['w1', 'd1'])+ assert.deepEqual(result.cron.sessions.map((s: any) => s.id), ['dc'])+ assert.deepEqual(result.messaging.sessions.map((s: any) => s.id), ['wm', 'dm'])+ assert.equal(result.messaging.total, 4)+ assert.deepEqual(result.recents.profiles_truncated, { default: false, work: true })+ assert.deepEqual(result.recents.profiles_usage, {+ default: { cost_usd: 1, tokens: 10 },+ work: { cost_usd: 2, tokens: 20 }+ })+ // The failed profile keeps Retry while its siblings' rows still render.+ const failed = { broken: { failed: true, retry: true, error: 'database is locked' } }+ assert.deepEqual(result.profiles_failed, failed)+ assert.deepEqual(result.recents.profiles_failed, failed)+ assert.deepEqual(result.errors, [{ profile: 'broken', error: 'database is locked' }])+})++test('all-profiles sidebar reports a failed load when every profile fails', async () => {+ const result = (await fetchAllProfilesSessionsPerProfile(+ '/api/profiles/sessions/sidebar?recents_profile=all',+ ['default'],+ async () => {+ throw new Error('Gateway ticket bootstrap failed')+ }+ )) as any++ assert.equal(result.recents.failed, true)+ assert.equal('sessions' in result.recents, false)+ assert.deepEqual(result.errors, [{ profile: 'default', error: 'Gateway ticket bootstrap failed' }])+})++test('all-profiles session list pages a deep per-profile read under the backend cap', async () => {+ const reads: string[] = []++ const result = (await fetchAllProfilesSessionsPerProfile('/api/profiles/sessions?limit=200&offset=400', ['default'], async (_p, path) => {+ reads.push(path)+ const params = new URL(path, 'http://x').searchParams+ const start = Number(params.get('offset'))+ const count = Math.min(Number(params.get('limit')), 650 - start)++ return {+ sessions: Array.from({ length: count }, (_, i) => ({ id: `s${start + i}`, profile: 'default', last_active: 1000 - start - i })),+ total: 650,+ profile_totals: { default: 650 }+ }+ })) as any++ assert.deepEqual(reads, [+ '/api/profiles/sessions?limit=500&offset=0&profile=default',+ '/api/profiles/sessions?limit=100&offset=500&profile=default'+ ])+ assert.equal(result.sessions.length, 200)+ assert.equal(result.sessions[0].id, 's400')+ assert.equal(result.total, 650)+})diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.tsindex 645ac7a33cb..1fa7490ee48 100644--- a/apps/desktop/electron/profile-session-routing.ts+++ b/apps/desktop/electron/profile-session-routing.ts@@ -920,3 +920,222 @@ export async function findRemoteOwnerProfileForSession(return matches.find(profile => profile !== null) ?? null}++// The backend's `/api/profiles/sessions` page cap (FastAPI `le=500`).+const PROFILE_SESSION_PAGE_CAP = 500++const SIDEBAR_SLICES = ['recents', 'cron', 'messaging'] as const++type FetchProfilePage = (profile: string, path: string) => Promise<unknown>++type ProfileRead = { profile: string; data: any } | { profile: string; error: string }++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++function recencyOf(row: any): number {+ return Number(row?.last_active || row?.started_at || 0)+}++function sortedWindow(rows: unknown[], key: (row: any) => number, offset: number, limit: number): unknown[] {+ return mergeProfileSessionWindow([...rows].sort((a, b) => key(b) - key(a)), offset, limit)+}++function failedProfiles(errors: SessionScanError[]): Record<string, { failed: true; retry: true; error: string }> {+ return Object.fromEntries(+ errors.filter(err => err.profile).map(err => [err.profile, { failed: true, retry: true, error: err.error || '' }])+ )+}++async function readEachProfile(+ profiles: readonly string[],+ read: (profile: string) => Promise<unknown>+): Promise<ProfileRead[]> {+ return Promise.all(+ profiles.map(async profile => {+ try {+ return { profile, data: (await read(profile)) as any }+ } catch (error) {+ return { profile, error: errorMessage(error) }+ }+ })+ )+}++/** One profile's rows from offset 0 through `want`, in pages the backend accepts. The first+ * page carries the profile's totals. */+async function readProfileSessionRows(url: URL, profile: string, want: number, fetchPage: FetchProfilePage) {+ let first: any+ const rows: unknown[] = []++ for (let offset = 0; ; ) {+ const params = new URLSearchParams(url.searchParams)+ const limit = Math.min(PROFILE_SESSION_PAGE_CAP, Math.max(0, want - offset))+ params.set('limit', String(limit))+ params.set('offset', String(offset))+ params.set('profile', profile)++ const page = (await fetchPage(profile, `${url.pathname}?${params}`)) as any+ const pageRows = rowsOf(page)+ first ??= page+ rows.push(...pageRows)+ offset += limit++ if (offset >= want || pageRows.length < limit) {+ return { ...first, sessions: rows }+ }+ }+}++async function allProfilesSessionList(url: URL, profiles: readonly string[], fetchPage: FetchProfilePage) {+ const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 20) || 0)+ const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0)+ const created = url.searchParams.get('order') === 'created'+ const reads = await readEachProfile(profiles, profile => readProfileSessionRows(url, profile, limit + offset, fetchPage))++ const rows: unknown[] = []+ const totals: Record<string, number> = {}+ const errors: SessionScanError[] = []+ const storage: Record<string, unknown> = {}++ for (const read of reads) {+ if ('error' in read) {+ errors.push({ profile: read.profile, error: read.error })++ continue+ }++ rows.push(...rowsOf(read.data))+ Object.assign(totals, read.data?.profile_totals)+ Object.assign(storage, read.data?.storage)+ errors.push(...(errorsOf(read.data) ?? []))+ }++ const key = created ? (row: any) => Number(row?.started_at || 0) : recencyOf++ return {+ sessions: sortedWindow(rows, key, offset, limit),+ total: Object.values(totals).reduce((sum, n) => sum + (Number(n) || 0), 0),+ profile_totals: totals,+ limit,+ offset,+ errors,+ storage+ }+}++async function allProfilesSidebar(url: URL, profiles: readonly string[], fetchPage: FetchProfilePage) {+ const cap = (key: string, fallback: number) =>+ Math.min(Math.max(Number(url.searchParams.get(key)) || fallback, 1), PROFILE_SESSION_PAGE_CAP)++ const caps = { recents: cap('recents_limit', 20), cron: cap('cron_limit', 50), messaging: cap('messaging_limit', 100) }++ const reads = await readEachProfile(profiles, profile => {+ const params = new URLSearchParams(url.searchParams)+ params.set('recents_profile', profile)++ return fetchPage(profile, `${url.pathname}?${params}`)+ })++ const rows: Record<(typeof SIDEBAR_SLICES)[number], unknown[]> = { recents: [], cron: [], messaging: [] }+ const truncated: Record<string, boolean> = {}+ const usage: Record<string, unknown> = {}+ const errors: SessionScanError[] = []+ const storage: Record<string, unknown> = {}+ const failed: SessionScanError[] = []+ let messagingTotal = 0+ let contributed = false++ for (const read of reads) {+ if ('error' in read) {+ errors.push({ profile: read.profile, error: read.error })+ failed.push({ profile: read.profile, error: read.error })++ continue+ }++ const data = read.data+ Object.assign(storage, data?.storage)+ errors.push(...(errorsOf(data) ?? []))++ // A failed slice has no `sessions` key: the profile's scan failed, it is not empty.+ if (data?.recents?.failed) {+ failed.push(...(errorsOf(data.recents) ?? [{ profile: read.profile, error: '' }]))++ continue+ }++ for (const err of Object.entries(data?.profiles_failed ?? {})) {+ failed.push({ profile: err[0], error: String((err[1] as any)?.error ?? '') })+ }++ for (const key of SIDEBAR_SLICES) {+ rows[key].push(...rowsOf(data?.[key]))+ }++ contributed ||= SIDEBAR_SLICES.some(key => rowsOf(data?.[key]).length > 0)+ Object.assign(truncated, data?.recents?.profiles_truncated)+ Object.assign(usage, data?.recents?.profiles_usage)+ messagingTotal += Number(data?.messaging?.total) || rowsOf(data?.messaging).length+ }++ const live = profiles.filter(profile => !(profile in storage))++ if (live.length && !contributed && live.every(profile => failed.some(err => err.profile === profile))) {+ const failedSlice = (extra = {}) => ({ failed: true, retry: true, errors: failed.map(err => ({ ...err })), ...extra })++ return {+ recents: failedSlice({ profiles_truncated: {}, profiles_usage: {} }),+ cron: failedSlice(),+ messaging: failedSlice({ total: 0 }),+ errors,+ storage+ }+ }++ const body: Record<string, any> = {+ recents: {+ sessions: sortedWindow(rows.recents, recencyOf, 0, caps.recents),+ profiles_truncated: truncated,+ profiles_usage: usage+ },+ cron: { sessions: sortedWindow(rows.cron, recencyOf, 0, caps.cron) },+ messaging: { sessions: sortedWindow(rows.messaging, recencyOf, 0, caps.messaging), total: messagingTotal },+ errors,+ storage+ }++ const profilesFailed = failedProfiles(failed)++ if (Object.keys(profilesFailed).length) {+ body.profiles_failed = profilesFailed++ for (const key of SIDEBAR_SLICES) {+ body[key].profiles_failed = profilesFailed+ body[key].errors = failed.map(err => ({ ...err }))+ }+ }++ return body+}++/** An all-profiles session list (`/api/profiles/sessions` or the batched sidebar) assembled+ * from one read per profile.+ *+ * A native gateway grant names ONE profile and the gateway refuses `all`, so a local native+ * backend cannot answer the unified list in one request. Each profile is read with its own+ * grant (`fetchPage` scopes the path to it) and merged the way the backend merges its own+ * per-profile scans: recency order, pinned back-fill, per-profile totals, and a profile that+ * cannot be read reported as a failed profile rather than as an empty one. */+export async function fetchAllProfilesSessionsPerProfile(+ path: string,+ profiles: readonly string[],+ fetchPage: FetchProfilePage+): Promise<unknown> {+ const url = new URL(path, 'http://desktop.local')++ return url.pathname.replace(/\/+$/, '') === '/api/profiles/sessions/sidebar'+ ? allProfilesSidebar(url, profiles, fetchPage)+ : allProfilesSessionList(url, profiles, fetchPage)+}