Skip to content

The agent that grows with you

feat(desktop): unified Sessions list shows every connected gateway's chats (#88880)

Tekniumd354af5e1290
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 712162a4b09..cc6d656cdd4 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -260,8 +260,11 @@ import { prepareProfileRenameLifecycle, profileRenameFromRequest } from './profi
import {
buildSidebarSessionSliceParams,
fetchPrimaryProfileSessions,
+ fetchRegistrySessionRows,
fetchRemoteProfileSessions,
- mergeProfileSessionWindow
+ mergeProfileSessionWindow,
+ type RegistrySessionSource,
+ spliceRegistrySessionRows
} from './profile-session-routing'
import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry'
import { type ActiveWork, mergeActiveWork, normalizeActiveWork, quitPromptFor } from './quit-guard'
@@ -13275,9 +13278,10 @@ async function interceptSessionRequestForRemote(request) {
if (method === 'GET' && pathname === '/api/profiles/sessions') {
const remoteProfiles = configuredRemoteProfileNames()
+ const registrySources = await pooledRegistrySessionSources()
- if (remoteProfiles.length === 0) {
- return undefined // no remote profiles → local fast path
+ if (remoteProfiles.length === 0 && registrySources.length === 0) {
+ return undefined // no remote profiles and no connected registry gateways → local fast path
}
const requested = (searchParams.get('profile') || 'all').trim() || 'all'
@@ -13297,8 +13301,9 @@ async function interceptSessionRequestForRemote(request) {
// remote correctness is preserved.
if (method === 'GET' && pathname === '/api/profiles/sessions/sidebar') {
const remoteProfiles = configuredRemoteProfileNames()
+ const registrySources = await pooledRegistrySessionSources()
- if (remoteProfiles.length === 0) {
+ if (remoteProfiles.length === 0 && registrySources.length === 0) {
return undefined // local fast path → batched endpoint's single DB open
}
@@ -13416,7 +13421,9 @@ async function fetchProfilesSessionSlice(searchParams, remoteProfiles) {
// Unified list: primary's local aggregate, with each remote profile's stale local
// rows/totals swapped for the remote's real ones, re-sorted by recency and
// re-windowed to the requested page. A dead remote contributes nothing rather
-// than breaking the sidebar.
+// than breaking the sidebar. Connected registry gateways' sessions are spliced
+// in too (#88880) — the unified Sessions list shows EVERY connected gateway's
+// chats, tagged with connection_id + profile so opens route correctly.
async function mergeRemoteProfileSessions(searchParams, remoteProfiles) {
const limit = Math.max(1, Number(searchParams.get('limit')) || 20)
const offset = Math.max(0, Number(searchParams.get('offset')) || 0)
@@ -13453,6 +13460,22 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles) {
})
)
+ // Registry gateways (v2 connections): splice every CONNECTED gateway's rows
+ // into the unified list. Only already-pooled backends are read — a sidebar
+ // refresh must never dial or spawn a backend (the Bot Mode roster-respawn
+ // trap). Reads omit include_hidden, so Bot Mode's hidden canonical chats
+ // stay out of the global list, same as local sessions.
+ const registrySources = await pooledRegistrySessionSources()
+
+ if (registrySources.length) {
+ const registryRows = await fetchRegistrySessionRows(registrySources, remoteParams, (descriptor, path) =>
+ getJsonForBackend(descriptor, path, { timeoutMs: 10_000 })
+ )
+
+ const { added } = spliceRegistrySessionRows(merged, registryRows, profileTotals)
+ total += added
+ }
+
const recency = s => s?.[order] ?? s?.started_at ?? 0
merged.sort((a, b) => recency(b) - recency(a))
@@ -13464,6 +13487,59 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles) {
}
}
+// Every CONNECTED registry gateway as a session source: resolved descriptors
+// straight from the backend pool, never dialing. SSH sources contribute one
+// backend per pooled (connection, profile) scope; remote/cloud sources are one
+// shared host (any pooled scope's descriptor serves the cross-profile read).
+// The primary local connection is excluded — the primary aggregate already
+// carries local rows.
+async function pooledRegistrySessionSources(): Promise<RegistrySessionSource[]> {
+ const registry = readDesktopConnectionsRegistry()
+ const sources: RegistrySessionSource[] = []
+
+ for (const connection of registry.connections) {
+ if (connection.kind === 'local') {
+ continue
+ }
+
+ const prefix = backendScopePrefix(connection.id)
+
+ const pooled = [...backendPool.entries()].filter(
+ ([key, entry]) => key.startsWith(prefix) && entry.connectionPromise
+ )
+
+ if (pooled.length === 0) {
+ continue
+ }
+
+ const backends: Array<{ descriptor: unknown; profileLabel: null | string }> = []
+
+ for (const [key, entry] of connection.kind === 'ssh' ? pooled : pooled.slice(0, 1)) {
+ try {
+ // Already-resolved for a connected backend; a still-dialing entry is
+ // skipped via the timeout guard rather than blocking the sidebar.
+ const descriptor = await Promise.race([
+ entry.connectionPromise,
+ new Promise((_, reject) => setTimeout(() => reject(new Error('pending')), 2_000))
+ ])
+
+ backends.push({
+ descriptor,
+ profileLabel: connection.kind === 'ssh' ? key.slice(prefix.length) || 'default' : null
+ })
+ } catch {
+ // Dead or still-connecting backend — contributes nothing this refresh.
+ }
+ }
+
+ if (backends.length) {
+ sources.push({ backends, connectionId: connection.id, kind: connection.kind })
+ }
+ }
+
+ return sources
+}
+
async function handleHermesApiRequest(request) {
// Registry-pinned request (request.connectionId): the renderer is working
// against a REGISTERED gateway connection, so the data — cron jobs and their
diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.ts
index 69f3c88e499..d9dd79869c0 100644
--- a/apps/desktop/electron/profile-session-routing.test.ts
+++ b/apps/desktop/electron/profile-session-routing.test.ts
@@ -5,8 +5,10 @@ import { test } from 'vitest'
import {
buildSidebarSessionSliceParams,
fetchPrimaryProfileSessions,
+ fetchRegistrySessionRows,
fetchRemoteProfileSessions,
- mergeProfileSessionWindow
+ mergeProfileSessionWindow,
+ spliceRegistrySessionRows
} from './profile-session-routing'
test('remote sidebar slices all follow the selected profile', () => {
@@ -219,3 +221,155 @@ test('remote session reads keep small requests on one call', async () => {
assert.deepEqual(calls, [{ profile: 'remote-work', path: '/api/sessions?limit=20&offset=0' }])
assert.equal(result, expected)
})
+
+test('registry sources: ssh backends are read natively and rows tagged with connection + profile', async () => {
+ const calls: Array<{ descriptor: unknown; path: string }> = []
+
+ const rows = await fetchRegistrySessionRows(
+ [
+ {
+ connectionId: 'gw-spark',
+ kind: 'ssh',
+ backends: [
+ { descriptor: 'spark-desc', profileLabel: 'research' },
+ { descriptor: 'spark-desc-2', profileLabel: '' }
+ ]
+ }
+ ],
+ new URLSearchParams({ limit: '20', offset: '0', profile: 'all' }),
+ async (descriptor, path) => {
+ calls.push({ descriptor, path })
+
+ return { sessions: [{ id: `s-${descriptor}`, message_count: 3 }], total: 1 }
+ }
+ )
+
+ assert.equal(calls.length, 2)
+ // The remote serves its own state.db: no profile param forwarded.
+ assert.ok(calls.every(({ path }) => path.startsWith('/api/sessions?') && !path.includes('profile=')))
+ // Hidden Bot Mode chats must stay hidden — include_hidden is never requested.
+ assert.ok(calls.every(({ path }) => !path.includes('include_hidden')))
+
+ assert.deepEqual(
+ rows.map(row => [(row as any).id, (row as any).connection_id, (row as any).profile]),
+ [
+ ['s-spark-desc', 'gw-spark', 'research'],
+ ['s-spark-desc-2', 'gw-spark', 'default']
+ ]
+ )
+ assert.ok(rows.every(row => (row as any).is_default_profile === false))
+})
+
+test('registry sources: shared remote hosts read the cross-profile aggregate once', async () => {
+ const calls: string[] = []
+
+ const rows = await fetchRegistrySessionRows(
+ [
+ {
+ connectionId: 'gw-cloud',
+ kind: 'remote',
+ backends: [{ descriptor: 'cloud-desc', profileLabel: null }]
+ }
+ ],
+ new URLSearchParams({ limit: '20', offset: '0' }),
+ async (_descriptor, path) => {
+ calls.push(path)
+
+ return {
+ sessions: [
+ { id: 'r-1', profile: 'hermes-claude' },
+ { id: 'r-2', profile: '' }
+ ],
+ total: 2
+ }
+ }
+ )
+
+ assert.equal(calls.length, 1)
+ assert.ok(calls[0].startsWith('/api/profiles/sessions?'))
+ assert.ok(calls[0].includes('profile=all'))
+ assert.ok(!calls[0].includes('include_hidden'))
+
+ // The remote's own profile stamps survive; missing stamps get 'default'.
+ assert.deepEqual(
+ rows.map(row => [(row as any).id, (row as any).profile, (row as any).connection_id]),
+ [
+ ['r-1', 'hermes-claude', 'gw-cloud'],
+ ['r-2', 'default', 'gw-cloud']
+ ]
+ )
+})
+
+test('registry sources: an older shared host without the aggregator falls back to its flat list', async () => {
+ const calls: string[] = []
+
+ const rows = await fetchRegistrySessionRows(
+ [{ connectionId: 'gw-old', kind: 'remote', backends: [{ descriptor: 'old-desc', profileLabel: null }] }],
+ new URLSearchParams({ limit: '20' }),
+ async (_descriptor, path) => {
+ calls.push(path)
+
+ if (path.startsWith('/api/profiles/sessions')) {
+ throw new Error('404: No such API endpoint')
+ }
+
+ return { sessions: [{ id: 'legacy-1' }], total: 1 }
+ }
+ )
+
+ assert.equal(calls.length, 2)
+ assert.ok(calls[1].startsWith('/api/sessions?'))
+ assert.deepEqual(
+ rows.map(row => [(row as any).id, (row as any).profile]),
+ [['legacy-1', 'default']]
+ )
+})
+
+test('registry sources: a dead gateway contributes nothing instead of breaking the list', async () => {
+ const rows = await fetchRegistrySessionRows(
+ [
+ { connectionId: 'gw-dead', kind: 'ssh', backends: [{ descriptor: 'dead', profileLabel: 'x' }] },
+ { connectionId: 'gw-live', kind: 'ssh', backends: [{ descriptor: 'live', profileLabel: 'y' }] }
+ ],
+ new URLSearchParams({ limit: '10' }),
+ async descriptor => {
+ if (descriptor === 'dead') {
+ throw new Error('ECONNREFUSED')
+ }
+
+ return { sessions: [{ id: 'ok-1' }], total: 1 }
+ }
+ )
+
+ assert.deepEqual(
+ rows.map(row => (row as any).id),
+ ['ok-1']
+ )
+})
+
+test('splice: registry rows dedupe by id and extend per-profile totals', () => {
+ const merged: unknown[] = [
+ { id: 'local-1', profile: 'default', last_active: 100 },
+ { id: 'dupe', profile: 'work', last_active: 90 }
+ ]
+ const totals: Record<string, number> = { default: 1, work: 1 }
+
+ const { added } = spliceRegistrySessionRows(
+ merged,
+ [
+ { id: 'dupe', profile: 'work', connection_id: 'gw-1', last_active: 95 },
+ { id: 'remote-1', profile: 'hermes-claude', connection_id: 'gw-1', last_active: 120 },
+ { id: 'remote-2', connection_id: 'gw-1', last_active: 110 }
+ ],
+ totals
+ )
+
+ assert.equal(added, 2)
+ assert.deepEqual(
+ merged.map(row => (row as any).id),
+ ['local-1', 'dupe', 'remote-1', 'remote-2']
+ )
+ assert.equal(totals['hermes-claude'], 1)
+ assert.equal(totals.default, 2) // untagged registry row counts under default
+ assert.equal(totals.work, 1) // deduped row does not double-count
+})
diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.ts
index 29b20e3a4c7..e096b7324d2 100644
--- a/apps/desktop/electron/profile-session-routing.ts
+++ b/apps/desktop/electron/profile-session-routing.ts
@@ -130,6 +130,149 @@ export async function fetchPrimaryProfileSessions(
}
}
+/** One CONNECTED (already-pooled) registry gateway whose sessions belong in the
+ * unified list. `backends` carries the resolved descriptors: one per pooled
+ * (connection, profile) pair for ssh-scoped sources, a single shared host for
+ * remote/cloud. The caller resolves descriptors — this module only fetches,
+ * tags, and dedupes, so it stays unit-testable. */
+export interface RegistrySessionSource {
+ connectionId: string
+ /** 'ssh' backends each run AS one remote profile; anything else is a shared
+ * host serving every profile via ?profile=. */
+ kind: string
+ backends: Array<{ descriptor: unknown; profileLabel: null | string }>
+}
+
+type GetJsonForDescriptor = (descriptor: unknown, path: string) => Promise<unknown>
+
+/**
+ * Every connected registry gateway's session rows for the unified Sessions
+ * list (#88880), tagged with the owning `connection_id` + remote `profile` so
+ * the renderer can route an open through the connection-scoped gateway.
+ *
+ * Hidden rows stay hidden: these reads NEVER pass `include_hidden`, so the
+ * backend's default `hidden = 0` filter applies — Bot Mode canonical chats
+ * (persisted hidden) are excluded from the global list exactly as local ones
+ * are. Do not add include_hidden here; the Bots view has its own scoped
+ * browser for those.
+ *
+ * A dead or erroring gateway contributes nothing rather than breaking the
+ * sidebar.
+ */
+export async function fetchRegistrySessionRows(
+ sources: RegistrySessionSource[],
+ searchParams: URLSearchParams,
+ getJson: GetJsonForDescriptor
+): Promise<unknown[]> {
+ const rows: unknown[] = []
+
+ const tag = (data: unknown, connectionId: string, profileLabel: null | string) => {
+ for (const row of rowsOf(data)) {
+ if (!row || typeof row !== 'object') {
+ continue
+ }
+
+ const session = row as Record<string, unknown>
+
+ if (profileLabel !== null) {
+ session.profile = profileLabel
+ } else if (typeof session.profile !== 'string' || !session.profile) {
+ session.profile = 'default'
+ }
+
+ session.is_default_profile = false
+ session.connection_id = connectionId
+ rows.push(session)
+ }
+ }
+
+ await Promise.all(
+ sources.map(async source => {
+ if (source.kind === 'ssh') {
+ // Each ssh-scoped backend serves its own state.db natively.
+ await Promise.all(
+ source.backends.map(async ({ descriptor, profileLabel }) => {
+ const params = new URLSearchParams(searchParams)
+ params.delete('profile')
+
+ const data = await getJson(descriptor, `/api/sessions?${params}`).catch(() => null)
+
+ if (data) {
+ tag(data, source.connectionId, profileLabel || 'default')
+ }
+ })
+ )
+
+ return
+ }
+
+ // Shared remote/cloud host: one cross-profile read returns every
+ // profile's rows, each tagged with its owning remote profile.
+ const shared = source.backends[0]
+
+ if (!shared) {
+ return
+ }
+
+ const params = new URLSearchParams(searchParams)
+ params.set('profile', 'all')
+
+ let data = await getJson(shared.descriptor, `/api/profiles/sessions?${params}`).catch(() => null)
+
+ if (!data) {
+ // Older remote without the aggregator: its own default-profile list.
+ const flat = new URLSearchParams(searchParams)
+ flat.delete('profile')
+ data = await getJson(shared.descriptor, `/api/sessions?${flat}`).catch(() => null)
+ }
+
+ if (data) {
+ tag(data, source.connectionId, null)
+ }
+ })
+ )
+
+ return rows
+}
+
+/** 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
+ * recency sort, and extend the per-profile totals so truncation flags stay
+ * honest. Mutates and returns `merged`/`profileTotals` the way the v1 splice
+ * does. */
+export function spliceRegistrySessionRows(
+ merged: unknown[],
+ registryRows: unknown[],
+ profileTotals: Record<string, number>
+): { added: number } {
+ const seen = new Set(merged.map(sessionId).filter((id): id is string => id !== null))
+ let added = 0
+
+ for (const row of registryRows) {
+ const id = sessionId(row)
+
+ if (id && seen.has(id)) {
+ continue
+ }
+
+ if (id) {
+ seen.add(id)
+ }
+
+ merged.push(row)
+ added += 1
+
+ const profile =
+ row && typeof row === 'object' && 'profile' in row && typeof row.profile === 'string' && row.profile
+ ? row.profile
+ : 'default'
+
+ profileTotals[profile] = (profileTotals[profile] || 0) + 1
+ }
+
+ return { added }
+}
+
export async function fetchRemoteProfileSessions(
profile: string,
searchParams: URLSearchParams,
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 4679f4f1446..1ef6200e9b0 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -20,6 +20,7 @@ import {
$activeGatewayProfile,
$gatewaySwapTarget,
$newChatProfile,
+ ensureGatewayAgent,
ensureGatewayProfile,
normalizeProfileKey
} from '@/store/profile'
@@ -735,7 +736,14 @@ export function useSessionActions({
return
}
- await ensureGatewayProfile(sessionProfile)
+ // A row spliced from a CONNECTED registry gateway (#88880) carries its
+ // owning connection — activate THAT gateway, not a same-named local
+ // profile. Rows without the tag keep the legacy profile path.
+ if (storedForProfile?.connection_id) {
+ await ensureGatewayAgent(storedForProfile.connection_id, sessionProfile || 'default')
+ } else {
+ await ensureGatewayProfile(sessionProfile)
+ }
// Request-time routing guard for every session-scoped RPC below. The
// await above REQUESTS the swap, but by dispatch time the active gateway
diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
index 0feed4309b0..3c33363984f 100644
--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
@@ -308,4 +308,47 @@ describe('reconnect fail-stop on a removed connection', () => {
await ensureActiveGatewayOpen()
expect(getConnection.mock.calls.length).toBe(callsAfterFailStop)
})
+
+ it('waits out an in-flight secondary activation instead of failing instantly (#88880)', async () => {
+ // A remote secondary whose activation is ALREADY in flight from another
+ // path (wake sweep, agent activation) used to make ensureActiveGatewayOpen
+ // return null immediately: reconnectSecondary early-returns on
+ // `reconnecting`, the socket is still closed, and the caller surfaced
+ // "Hermes gateway is not connected" on the Sessions + action. The drive
+ // must ride out the in-flight activation and hand back the opened socket.
+ let releaseDial: (() => void) | undefined
+ const dialGate = new Promise<void>(resolve => {
+ releaseDial = resolve
+ })
+
+ const getConnectionFor = vi.fn(async () => descriptorFor('homelab', 'default'))
+
+ installDesktop({ getConnectionFor })
+
+ gatewayMocks.connect
+ .mockImplementationOnce(async () => undefined) // initial open
+ .mockImplementationOnce(async () => {
+ await dialGate // the sweep-driven reconnect dial hangs until released
+ })
+
+ await ensureGatewayForAgent('homelab', 'default')
+
+ const socket = gatewayMocks.instances[0] as unknown as { connectionState: string }
+ socket.connectionState = 'closed'
+
+ // Another path (the wake sweep) starts the reconnect first — the drive
+ // below meets an entry that is already `reconnecting`.
+ reconnectSecondaryGateways()
+ await Promise.resolve()
+
+ const driving = ensureActiveGatewayOpen()
+
+ await new Promise(resolve => setTimeout(resolve, 300))
+ releaseDial?.()
+
+ const result = await driving
+
+ expect(result).not.toBeNull()
+ expect((result as unknown as { connectionState: string }).connectionState).toBe('open')
+ })
})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index e8c8cc9e6d0..2966b93d6d7 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -782,9 +782,30 @@ export async function ensureActiveGatewayOpen(): Promise<HermesGateway | null> {
await reconnectSecondary(entry)
}
+ if (!isOpen(entry.gateway)) {
+ // A remote/registry secondary can still be ACTIVATING (backend waking,
+ // socket dialing). Failing instantly turned a routine cold start into
+ // "Hermes gateway is not connected" on the Sessions `+` action (#88880).
+ // Wait a bounded beat for the in-flight activation instead of erroring;
+ // a genuinely dead gateway still returns null when the window closes.
+ const deadline = Date.now() + ACTIVE_GATEWAY_OPEN_WAIT_MS
+
+ while (Date.now() < deadline && entry.wantOpen && g.secondaries.get(g.activeKey) === entry) {
+ if (isOpen(entry.gateway)) {
+ break
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 250))
+ }
+ }
+
return isOpen(entry.gateway) ? entry.gateway : null
}
+// How long ensureActiveGatewayOpen waits out an in-flight secondary
+// activation before reporting the gateway as unavailable.
+const ACTIVE_GATEWAY_OPEN_WAIT_MS = 8_000
+
// Wake signal (sleep/network/visibility): nudge every live secondary back open.
export function reconnectSecondaryGateways(): void {
for (const entry of g.secondaries.values()) {
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index ce407ddc493..dc5e3d24a4d 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -534,6 +534,11 @@ export interface SessionInfo {
profile?: string
/** True when {@link profile} is the default profile. */
is_default_profile?: boolean
+ /** Registry connection that owns this row when it came from a CONNECTED
+ * non-primary gateway (Electron's unified-list splice, #88880). Absent for
+ * rows served by the primary/local backend. Opens must route through the
+ * connection-scoped gateway (`ensureGatewayAgent`) when present. */
+ connection_id?: string
}
export type TimelineDisplayMetadata =