Skip to content

The agent that grows with you

fix(desktop): pin session REST reads to the session's owner connection

Yuan Liaf9d7a6318bc
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index b4fdc848f7e..dc1870db322 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -225,3 +225,77 @@ export function profileScopeKey(scope?: ProfileScope): string {
export function getApiRequestConnection(): null | string {
return $apiRequestScope.get().connectionId
}
+
+// ── Session-owner reads: the connection a session-scoped REST read must ride ─
+//
+// A session-scoped read (detail / messages / timeline) only means anything on
+// the backend that OWNS the session's row (#125372). The renderer already
+// knows that owner (tile route → persisted hint → connection-tagged row,
+// resolved by store/session-states knownOwnerForSession), but read helpers
+// dispatched with the WINDOW's ambient connection scope — so with a registered
+// remote that exposes a same-named profile, the wrong backend answered
+// 404 "Session not found" in both directions. The store pushes its resolver
+// through setSessionOwnerResolver (same seam pattern as setApiRequestProfile:
+// no store import here, which would close a module cycle) and the session read
+// helpers pin the resolved connection.
+
+export interface SessionReadOwnerRoute {
+ connectionId?: null | string
+ mode?: string
+ profile?: null | string
+ targetProfile?: null | string
+}
+
+export type SessionReadOwner = string | SessionReadOwnerRoute
+
+export type SessionOwnerResolver = (sessionId: string) => SessionReadOwner | null | undefined
+
+let _sessionOwnerResolver: SessionOwnerResolver | null = null
+
+export function setSessionOwnerResolver(resolver: SessionOwnerResolver | null): void {
+ _sessionOwnerResolver = resolver
+}
+
+function sessionOwnerForRead(sessionId: string): SessionReadOwner | null | undefined {
+ return _sessionOwnerResolver?.(sessionId)
+}
+
+/** The connection pin a session-scoped READ must carry for `id`, or {} when
+ * the ambient scope is already right. An explicit (connection, profile)
+ * object scope short-circuits: the caller has already routed the request. An
+ * exact owner route pins its connection — 'local' INCLUDED, the sanctioned
+ * way back to this device when the window's primary is a remote registry
+ * source — plus, when the caller named no profile, the route's backend-facing
+ * profile: the answering host resolves ?profile= against ITS OWN profiles. */
+export function sessionReadOwnerPin(
+ id: string,
+ profile?: ProfileScope
+): { connectionId?: string; profile?: string } {
+ if (profile && typeof profile === 'object' && String(profile.connectionId ?? '').trim()) {
+ return {}
+ }
+
+ const owner = sessionOwnerForRead(id)
+
+ if (!owner || typeof owner === 'string' || !('connectionId' in owner)) {
+ return {}
+ }
+
+ const connectionId = String(owner.connectionId ?? '').trim()
+
+ // No exact connection in the route → no pin (ambient behavior, never guess).
+ if (!connectionId) {
+ return {}
+ }
+
+ const ownerProfile = String(owner.targetProfile || owner.profile || '').trim()
+
+ if (connectionId === (ambientOwnerConnectionId() ?? 'local')) {
+ return {}
+ }
+
+ return {
+ connectionId,
+ ...(profile == null && ownerProfile ? { profile: ownerProfile } : {})
+ }
+}
diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.ts
index 7290459d53d..19c65562030 100644
--- a/apps/desktop/src/api/sessions.test.ts
+++ b/apps/desktop/src/api/sessions.test.ts
@@ -5,11 +5,14 @@ import type { SidebarSessionsResponse } from './sessions'
vi.mock('@/lib/gateway-rpc', () => ({ isMissingRestEndpoint: () => false }))
vi.mock('@/store/transcript-tail', () => ({ pageHonorsLatestOrder: () => true, recordTranscriptTail: vi.fn() }))
vi.mock('./client', () => ({
+ ambientOwnerConnectionId: vi.fn(() => 'prometheus'),
capabilityScoped: vi.fn(),
+ connectionScoped: vi.fn(() => ({})),
getApiRequestConnection: vi.fn(() => 'prometheus'),
getApiRequestProfile: vi.fn(() => null),
hermesApi: vi.fn(),
- profileScoped: vi.fn(() => ({}))
+ profileScoped: vi.fn(() => ({})),
+ sessionReadOwnerPin: vi.fn(() => ({}))
}))
const client = await import('./client')
@@ -17,6 +20,8 @@ const client = await import('./client')
const {
deleteSession,
getSession,
+ getSessionMessages,
+ getLatestSessionMessages,
setSessionArchived,
setSessionPinnedRemote,
setSessionUnreadRemote,
@@ -247,3 +252,53 @@ describe('listSidebarSessions storage health', () => {
expect(result.storage).toEqual({ default: 'corrupt' })
})
})
+
+describe('session reads pin the owner connection (#125372)', () => {
+ beforeEach(() => {
+ // Ambient default: no explicit pin, no owner stamp.
+ vi.mocked(client.capabilityScoped).mockReturnValue({})
+ vi.mocked(client.sessionReadOwnerPin).mockReturnValue({})
+ })
+
+ it('pins getSession to the session owner when the ambient scope differs', async () => {
+ // Regression: a session-scoped read dispatched on the WINDOW's ambient
+ // connection scope. With a registered remote exposing a same-named
+ // profile, the wrong backend answered 404 "Session not found" in both
+ // directions. The read must carry the owner's connectionId (+ backend
+ // profile when the caller named none) so Electron routes to the owner.
+ vi.mocked(client.sessionReadOwnerPin).mockImplementation((id: string) =>
+ id === 'remote-owned' ? { connectionId: 'dale-home-lan-9119', profile: 'default' } : {}
+ )
+
+ await getSession('remote-owned')
+
+ expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ path: '/api/sessions/remote-owned?profile=default',
+ connectionId: 'dale-home-lan-9119'
+ })
+ })
+
+ it('leaves ambient reads untouched when no owner is known', async () => {
+ vi.mocked(client.sessionReadOwnerPin).mockReturnValue({})
+
+ await getSessionMessages('sess-x')
+
+ expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ path: '/api/sessions/sess-x/messages'
+ })
+ expect(hermesApi.mock.calls[0][0]).not.toHaveProperty('connectionId')
+ })
+
+ it('keeps an explicit (connection, profile) pin authoritative in getLatestSessionMessages', async () => {
+ // Explicit caller pin: the real capabilityScoped resolves it; the owner
+ // lookup must not override it.
+ vi.mocked(client.capabilityScoped).mockReturnValue({ profile: 'tommy', connectionId: 'other-conn' })
+
+ await getLatestSessionMessages('sess-y', { connectionId: 'other-conn', profile: 'tommy' })
+
+ expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ connectionId: 'other-conn',
+ profile: 'tommy'
+ })
+ })
+})
diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.ts
index 02a791205cd..d29f617e84d 100644
--- a/apps/desktop/src/api/sessions.ts
+++ b/apps/desktop/src/api/sessions.ts
@@ -18,7 +18,8 @@ import {
getApiRequestProfile,
hermesApi,
type ProfileScope,
- profileScoped
+ profileScoped,
+ sessionReadOwnerPin
} from './client'
const SESSION_LIST_REQUEST_TIMEOUT_MS = 60_000
@@ -435,10 +436,14 @@ export function searchSessions(query: string): Promise<SessionSearchResponse> {
// 404s when the id isn't on that profile — so a cheap by-id lookup replaces the
// cross-profile list scan when locating an unknown id's owner.
export function getSession(id: string, profile?: ProfileScope): Promise<SessionInfo> {
- const suffix = sessionScopeQuery(profile)
+ // Pin the read to the session's OWNER connection (#125372): the ambient dial
+ // 404s on the wrong backend whenever two connections expose a same-named
+ // profile.
+ const scope = { ...sessionScoped(profile), ...sessionReadOwnerPin(id, profile) }
+ const suffix = scope.profile ? `?profile=${encodeURIComponent(scope.profile)}` : ''
return hermesApi<SessionInfo>({
- ...sessionScoped(profile),
+ ...scope,
path: `/api/sessions/${encodeURIComponent(id)}${suffix}`
})
}
@@ -455,7 +460,8 @@ export function getSessionMessages(
): Promise<SessionMessagesResponse> {
const query = new URLSearchParams()
- const sessionScope = sessionScoped(profile)
+ // Owner connection pin (#125372) — see getSession.
+ const sessionScope = { ...sessionScoped(profile), ...sessionReadOwnerPin(id, profile) }
if (sessionScope.profile) {
query.set('profile', sessionScope.profile)
@@ -504,7 +510,7 @@ export function getLatestSessionMessages(
// (ambient, profile string, or explicit pin). Otherwise refreshes create
// duplicate tail entries and "Show earlier" cannot resolve the loaded tail.
// Capture before awaiting: the active gateway may change during the read.
- const route = { ...connectionScoped(), ...sessionScoped(profile) }
+ const route = { ...connectionScoped(), ...sessionScoped(profile), ...sessionReadOwnerPin(id, profile) }
// Only the lookup key is normalized — backfill replays `route` verbatim.
const ambientConnectionId = route.connectionId || ambientOwnerConnectionId()
const ambientProfile = getApiRequestProfile() || 'default'
diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
index d5750eb2b10..c3f54977823 100644
--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts
@@ -1,4 +1,4 @@
-import { capabilityScoped, hermesApi, type ProfileScope } from '@/api/client'
+import { capabilityScoped, hermesApi, type ProfileScope, sessionReadOwnerPin } from '@/api/client'
import type { TimelineEntry } from './timeline-data'
@@ -53,7 +53,10 @@ export function fetchTimelineIndex(id: string, scope: ProfileScope, beyondRowId?
const route = {
...capabilityScoped(scope),
- ...(typeof scope === 'object' && scope?.connectionId === 'local' ? { connectionId: 'local' } : {})
+ ...(typeof scope === 'object' && scope?.connectionId === 'local' ? { connectionId: 'local' } : {}),
+ // Owner connection pin (#125372) — a timeline jump for a session owned by
+ // another registry connection must read THAT host, not the ambient one.
+ ...sessionReadOwnerPin(id, scope)
}
const query = new URLSearchParams({ limit: '500' })
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index f3b44dc84fa..30c2ae9a955 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -19,6 +19,7 @@
import { type GatewayEvent, LOCAL_CONNECTION_ID, registryBackendScopeKey } from '@hermes/shared'
import { atom, computed } from 'nanostores'
+import { setSessionOwnerResolver } from '@/api/client'
import { routeSessionId } from '@/app/routes'
import type { ClientSessionState } from '@/app/types'
import { findGroupOfPane, type LayoutNode } from '@/components/pane-shell/tree/model'
@@ -1608,6 +1609,10 @@ export function knownOwnerForSession(sessionId: null | string | undefined): Sess
return sessionOwnerByRuntimeId.get(sessionId) ?? durable
}
+// Session-scoped REST reads (detail / messages / timeline) resolve their
+// connection pin through the SAME owner ladder as RPC dispatch (#125372).
+setSessionOwnerResolver(knownOwnerForSession)
+
/** The profile whose chat is on screen — the rail's scope.
*
* NOT `$activeGatewayProfile`: a focused tab does not swap the gateway socket,