The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): SSH/reconnect owner continuity, attachment routing, transport-error recovery
tachi317ae240fb2d
diff --git a/apps/desktop/src/app/chat/session-tile-actions.test.ts b/apps/desktop/src/app/chat/session-tile-actions.test.tsindex 0d0139905da..b3002f79002 100644--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts@@ -6,9 +6,9 @@ import { MAIN_COMPOSER_SCOPE } from './composer/scope'const requestGatewayMock = vi.hoisted(() => vi.fn())-const { $activeSessionId } = await import('@/store/session')+const { $activeSessionId, $sessions, setSessions } = await import('@/store/session')const { $sessionTiles, setSessionTileDelegate } = await import('@/store/session-states')-const { useSessionTileActions } = await import('./session-tile-actions')+const { listTileSessionRow, useSessionTileActions } = await import('./session-tile-actions')const RUNTIME_SESSION_ID = 'rt-tile-current'const STORED_SESSION_ID = 'stored-tile-db'@@ -25,6 +25,36 @@ function renderTileActions() {)}+describe('session tile optimistic owner metadata', () => {+ afterEach(() => {+ $sessions.set([])+ $sessionTiles.set([])+ })++ it('keeps the tile source on its first optimistic sidebar row', () => {+ const storedSessionId = 'stored-tile-owner-metadata'+ const ownerRoute = { connectionId: 'source-a', profile: 'default' }+ $sessionTiles.set([{ ownerRoute, storedSessionId }])++ expect(+ listTileSessionRow({+ cwd: '/remote/worktree',+ model: 'model-a',+ preview: 'hello from the tile',+ runtimeId: 'rt-tile-owner-metadata',+ sessions: [],+ storedSessionId+ })+ ).toBe(true)++ expect($sessions.get()[0]).toMatchObject({+ connection_id: 'source-a',+ id: storedSessionId,+ profile: 'default'+ })+ })+})+// A tile's cancelRun/steerPrompt/reloadFromMessage each build their own// requestGateway call directly instead of going through the shared// submitPromptText pipeline (which already wraps its call in@@ -34,6 +64,7 @@ function renderTileActions() {describe('useSessionTileActions sleep/wake session recovery', () => {beforeEach(() => {$activeSessionId.set('foreground-runtime')+ setSessions([])$sessionTiles.set([{ runtimeId: RUNTIME_SESSION_ID, storedSessionId: STORED_SESSION_ID }])setSessionTileDelegate({archiveSession: vi.fn(async () => undefined),@@ -59,6 +90,7 @@ describe('useSessionTileActions sleep/wake session recovery', () => {afterEach(() => {$activeSessionId.set(null)+ setSessions([])$sessionTiles.set([])requestGatewayMock.mockReset()vi.restoreAllMocks()diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 4397e932f18..056bb99b598 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -22,8 +22,19 @@ import { resetSessionBackground } from '@/store/composer-status'import { notifyError } from '@/store/notifications'import { clearPreviewArtifacts } from '@/store/preview-status'import { clearAllPrompts } from '@/store/prompts'-import { $sessions, sessionMatchesStoredId } from '@/store/session'-import { $sessionStates, isSessionRemote, patchSessionTile, sessionTileDelegate } from '@/store/session-states'+import { $connection, $sessions, knownSessionOwner, sessionMatchesStoredId } from '@/store/session'+import {+ requestForSessionProfile,+ type SessionOwnerScope,+ type SessionProfileRoute+} from '@/store/session-request-router'+import {+ $sessionStates,+ isSessionRemote,+ patchSessionTile,+ sessionTileDelegate,+ sessionTileOwnerRoute+} from '@/store/session-states'import { broadcastSessionsChanged } from '@/store/session-sync'import { clearSessionSubagents } from '@/store/subagents'import { clearSessionTodos } from '@/store/todos'@@ -85,11 +96,19 @@ export function listTileSessionRow(deps: {return false}+ const knownOwner =+ sessionTileOwnerRoute(deps.storedSessionId) ?? knownSessionOwner(deps.sessions, deps.storedSessionId)+ const ownerRoute: SessionProfileRoute | undefined =+ knownOwner && typeof knownOwner === 'object' ? knownOwner : undefined+upsertOptimisticSession({ info: { cwd: deps.cwd, model: deps.model }, session_id: deps.runtimeId, stored_session_id: deps.storedSessionId },deps.storedSessionId,null,- preview+ preview,+ null,+ undefined,+ ownerRoute)broadcastSessionsChanged()@@ -153,6 +172,22 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedconst readState = useCallback(() => $sessionStates.get()[runtimeIdRef.current], [])const readMessages = useCallback(() => readState()?.messages ?? [], [readState])+ // Tile session RPCs must follow the tile's composite owner even when the+ // active gateway has moved to a same-named profile on another source.+ const requestSessionGateway = useCallback(+ <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal) => {+ const knownOwner: SessionOwnerScope =+ sessionTileOwnerRoute(storedIdRef.current) ?? knownSessionOwner($sessions.get(), storedIdRef.current)+ // A bare profile is the legacy/unknown tile shape. Preserve its ambient+ // behavior; only a composite route is strong enough to retarget a tile+ // across same-named sources.+ const owner: SessionOwnerScope = knownOwner && typeof knownOwner === 'object' ? knownOwner : undefined++ return requestForSessionProfile<T>(owner, requestGateway, method, params ?? {}, timeoutMs, signal)+ },+ [requestGateway]+ )+// A ⌘T tab's session is unlisted until its first turn persists — seed the// row from the user's first message so the tab and sidebar name it right// away (see listTileSessionRow).@@ -200,7 +235,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedconst next = await uploadComposerAttachment(attachment, {backendCwd: readState()?.cwd,remote,- requestGateway,+ requestGateway: requestSessionGateway,sessionId: liveSessionId,storedSessionId: storedIdRef.current,onSessionRecovered@@ -233,7 +268,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedreturn { attachments: synced, sessionId: liveSessionId }},- [bindRecoveredRuntime, readState, requestGateway, scope.attachments]+ [bindRecoveredRuntime, readState, requestSessionGateway, scope.attachments])// The REAL submit pipeline with tile seams: session always exists, and the@@ -249,7 +284,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored// token is a stable constant (the guard never trips for a tile).getRouteToken: () => runtimeId,onRuntimeRecovered: bindRecoveredRuntime,- requestGateway,+ requestGateway: requestSessionGateway,runtimeIdByStoredSessionIdRef,// Tile ids are always bound before this hook mounts, so routed recovery is// unreachable here; keep the shared submit contract explicit.@@ -315,16 +350,16 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedawait withSessionNotFoundResume(sessionId,storedIdRef.current,- liveId => requestGateway('session.interrupt', { session_id: liveId }),+ liveId => requestSessionGateway('session.interrupt', { session_id: liveId }),{- requestGateway,+ requestGateway: requestSessionGateway,onRecovered: bindRecoveredRuntime})} catch (err) {notifyError(err, copy.stopFailed)}- }, [bindRecoveredRuntime, copy.stopFailed, requestGateway, update])+ }, [bindRecoveredRuntime, copy.stopFailed, requestSessionGateway, update])const steerPrompt = useCallback(async (rawText: string): Promise<boolean> => {@@ -374,9 +409,9 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedconst { result } = await withSessionNotFoundResume(sessionId,storedIdRef.current,- liveId => requestGateway<{ status?: string }>('session.redirect', { session_id: liveId, text }),+ liveId => requestSessionGateway<{ status?: string }>('session.redirect', { session_id: liveId, text }),{- requestGateway,+ requestGateway: requestSessionGateway,onRecovered: bindRecoveredRuntime})@@ -404,7 +439,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedreturn false},- [bindRecoveredRuntime, requestGateway]+ [bindRecoveredRuntime, requestSessionGateway])// Rewind primitive (interrupt-first for live turns, busy-retry) — shared with@@ -420,7 +455,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedrebindRowIds?: readonly number[]) =>runRewindSubmit(- requestGateway,+ requestSessionGateway,runtimeIdRef.current,text,truncateOrdinal,@@ -434,7 +469,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedsourceText,rebindRowIds),- [bindRecoveredRuntime, requestGateway]+ [bindRecoveredRuntime, requestSessionGateway])// After a durable rewind the surviving bubbles' cached rowIds are stale (thediff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex 4a381a19bfe..661fe8d966c 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@ -132,6 +132,25 @@ describe('useSessionTileDelegate resumeTile', () => {expect(requestGateway).not.toHaveBeenCalled()})+ it('carries a session row connection owner into a same-named tile resume', async () => {+ setSessions([row({ connection_id: 'source-b', id: 'stored-shared', profile: 'default' })])++ const ambientRequest = vi.fn(async () => ({}) as never)+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({ session_id: 'runtime-shared' } as never)++ renderTile(ambientRequest)+ const runtimeId = await sessionTileDelegate()!.resumeTile('stored-shared')++ expect(runtimeId).toBe('runtime-shared')+ expect(requestGatewayForAgent).toHaveBeenCalledWith('source-b', 'default', 'session.resume', {+ session_id: 'stored-shared',+ cols: 96,+ omit_messages: true,+ profile: 'default'+ })+ expect(ambientRequest).not.toHaveBeenCalled()+ })+it('routes a Bot tile prefetch and resume through its exact connection owner', async () => {const route = {connectionId: 'barry',diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 841ea84d8e0..ba60e4f6353 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -2,7 +2,7 @@ import { useEffect } from 'react'import { getLatestSessionMessages, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'import { toChatMessages } from '@/lib/chat-messages'-import { getSessionOwnerHint } from '@/store/session'+import { $sessions, knownSessionOwner } from '@/store/session'import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'import { publishSessionState, sessionTileOwnerRoute, setSessionTileDelegate } from '@/store/session-states'import type { SessionResumeResponse } from '@/types/hermes'@@ -76,8 +76,8 @@ export function useSessionTileDelegate({const ownerForStoredSession = async (storedSessionId: string): Promise<SessionOwnerScope> => {const owner =- getSessionOwnerHint(storedSessionId) ??sessionTileOwnerRoute(storedSessionId) ??+ knownSessionOwner($sessions.get(), storedSessionId) ??(await resolveSessionProfile(storedSessionId))return ownerdiff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 119eec86c3a..6b2b43113dc 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -320,7 +320,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {// profile's own local gateway — never to whatever is "active" (active is// presentation only). Resolve the owner from, in order: the tile's persisted// route (bot chats carry an exact connectionId+profile), the known session- // profile (row or open-time hint), then a cross-profile REST probe that+ // owner (row or open-time hint), then a cross-profile REST probe that// stamps ownership for a hidden/unlisted session. Only a request with NO// session at all (a fresh draft, global chrome) falls to the ambient socket.// The probe result is cached as an owner hint so the next call is sync.diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.tsindex 72ad6a2a268..20e54f34bd9 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts@@ -1,24 +1,230 @@+import type { GatewayWsUrlResult } from '@hermes/shared'import { act, renderHook } from '@testing-library/react'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+const gatewayMocks = vi.hoisted(() => ({+ instances: [] as Array<{+ connect: ReturnType<typeof vi.fn>+ connectionState: string+ request: ReturnType<typeof vi.fn>+ wsUrl: string+ }>+}))++vi.mock('@/hermes', async importOriginal => {+ const actual = await importOriginal<typeof HermesModule>()++ class FakeHermesGateway {+ connectionState = 'closed'+ wsUrl = ''+ request = vi.fn()+ connect = vi.fn(async (wsUrl: string) => {+ this.wsUrl = wsUrl+ this.connectionState = 'open'++ for (const handler of this.stateHandlers) {+ handler('open')+ }+ })+ close = vi.fn(() => {+ this.connectionState = 'closed'++ for (const handler of this.stateHandlers) {+ handler('closed')+ }+ })+ onEvent = vi.fn(() => () => undefined)+ onState = vi.fn((handler: (state: string) => void) => {+ this.stateHandlers.add(handler)+ handler(this.connectionState)++ return () => this.stateHandlers.delete(handler)+ })+ private stateHandlers = new Set<(state: string) => void>()++ constructor() {+ gatewayMocks.instances.push(this)+ }+ }++ return { ...actual, HermesGateway: FakeHermesGateway }+})++import type * as HermesModule from '@/hermes'import type { HermesGateway } from '@/hermes'-import { $gateway } from '@/store/gateway'+import {+ $gateway,+ closeSecondaryGateways,+ configureGatewayRegistry,+ ensureGatewayForAgent,+ setPrimaryGateway+} from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'+import { $connection, $gatewayState } from '@/store/session'import { useGatewayRequest } from './use-gateway-request'+interface TestGateway {+ connect: ReturnType<typeof vi.fn>+ connectionState: string+ request: ReturnType<typeof vi.fn>+ wsUrl?: string+}+const fakeGateway = { connectionState: 'open' } as unknown as HermesGateway+const remoteConnection = {+ authMode: 'oauth' as const,+ baseUrl: 'https://ssh.example.test',+ connectionId: 'ssh-source',+ mode: 'remote' as const,+ profile: 'research',+ remoteIdentity: 'ssh.example.test',+ remoteKind: 'ssh' as const,+ token: 'remote-token',+ wsUrl: 'wss://ssh.example.test/api/ws?ticket=stale'+}++function installRemoteDesktop() {+ let mintCount = 0+ const getConnection = vi.fn(async (profile?: null | string) => ({+ authMode: 'token' as const,+ baseUrl: 'http://127.0.0.1:5151',+ mode: 'local' as const,+ profile: profile ?? 'default',+ token: 'local-token',+ wsUrl: 'ws://127.0.0.1:5151/api/ws?token=local'+ }))+ const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({+ ...remoteConnection,+ connectionId,+ profile+ }))+ const getGatewayWsUrl = vi.fn(async () => ({+ ok: true as const,+ wsUrl: 'ws://127.0.0.1:5151/api/ws?token=fresh-local'+ }))+ const getGatewayWsUrlFor = vi.fn(+ async ({ connectionId, profile }: { connectionId: string; profile: string }): Promise<GatewayWsUrlResult> => {+ mintCount += 1++ return {+ ok: true as const,+ wsUrl: `wss://${connectionId}.example.test/api/ws?profile=${profile}&ticket=fresh-${mintCount}`+ }+ }+ )++ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { getConnection, getConnectionFor, getGatewayWsUrl, getGatewayWsUrlFor }+ })++ return { getConnection, getConnectionFor, getGatewayWsUrl, getGatewayWsUrlFor }+}++function installPrimaryDesktop(authMode: 'oauth' | 'token') {+ const getConnection = vi.fn(async (profile?: null | string) => ({+ authMode,+ baseUrl: authMode === 'oauth' ? 'https://gateway.example.test' : 'http://127.0.0.1:5151',+ mode: authMode === 'oauth' ? ('remote' as const) : ('local' as const),+ profile: profile ?? 'default',+ token: 'primary-token',+ wsUrl: authMode === 'oauth' ? 'wss://gateway.example.test/api/ws?ticket=stale' : 'ws://127.0.0.1:5151/api/ws'+ }))+ const getGatewayWsUrl = vi.fn(async (profile?: null | string) => ({+ ok: true as const,+ wsUrl:+ authMode === 'oauth'+ ? `wss://gateway.example.test/api/ws?profile=${profile ?? 'default'}&ticket=fresh`+ : 'ws://127.0.0.1:5151/api/ws?token=fresh'+ }))+ const getConnectionFor = vi.fn()+ const getGatewayWsUrlFor = vi.fn()++ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { getConnection, getConnectionFor, getGatewayWsUrl, getGatewayWsUrlFor }+ })++ return { getConnection, getConnectionFor, getGatewayWsUrl, getGatewayWsUrlFor }+}++function makePrimaryGateway(): TestGateway {+ return {+ connect: vi.fn(async () => undefined),+ connectionState: 'open',+ request: vi.fn()+ }+}++async function activateRemoteGateway() {+ const desktop = installRemoteDesktop()+ const primary = makePrimaryGateway()++ setPrimaryGateway(primary as unknown as HermesGateway, 'default')+ $gateway.set(primary as unknown as HermesGateway)+ await ensureGatewayForAgent('ssh-source', 'research')++ const gateway = $gateway.get() as unknown as TestGateway++ expect(gateway).not.toBe(primary)+ expect($activeGatewayProfile.get()).toBe('research')++ return { desktop, gateway }+}++async function expectSecondaryRecoveryFailure(+ gateway: TestGateway,+ request: ReturnType<typeof useGatewayRequest>['requestGateway']+) {+ const transportError = new Error('connection closed')+ gateway.request.mockRejectedValueOnce(transportError)+ gateway.connectionState = 'closed'++ vi.useFakeTimers()+ const retry = request('session.resume').then(+ () => undefined,+ error => error+ )++ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ await vi.advanceTimersByTimeAsync(8_000)+ })++ await expect(retry).resolves.toBe(transportError)+ expect(gateway.request).toHaveBeenCalledTimes(1)+ expect(gateway.connect).toHaveBeenCalledTimes(1)+}++beforeEach(() => {+ gatewayMocks.instances.length = 0+ closeSecondaryGateways()+ setPrimaryGateway(null)+ $gateway.set(null)+ $connection.set(null)+ $gatewayState.set('idle')+ $activeGatewayProfile.set('default')+ configureGatewayRegistry({+ onActiveRouteChanged: profile => $activeGatewayProfile.set(profile),+ onEvent: vi.fn()+ })+})+afterEach(() => {+ vi.useRealTimers()+ closeSecondaryGateways()+ setPrimaryGateway(null)$gateway.set(null)+ $connection.set(null)+ $gatewayState.set('idle')+ $activeGatewayProfile.set('default')+ Reflect.deleteProperty(window, 'hermesDesktop')})describe('useGatewayRequest', () => {- // The composer's `/` completions only exist when ChatBar receives a non-null- // gateway PROP. `gatewayRef` is populated by a subscription effect, so it is- // still null on the first render — a surface that read the ref while- // rendering (session tiles / ⌘T tabs) shipped `gateway={null}` and silently- // lost slash completions. The returned `gateway` value must be live- // immediately so that never happens again.it('exposes the live gateway on the first render, before effects run', () => {$gateway.set(fakeGateway)@@ -36,4 +242,113 @@ describe('useGatewayRequest', () => {expect(result.current.gateway).toBe(fakeGateway)})++ it.each([+ { error: new Error('connection closed'), label: 'closed message' },+ { error: new Error('ECONNRESET'), label: 'reset message' },+ { error: Object.assign(new Error('socket failed'), { code: 'ECONNRESET' }), label: 'error code' },+ { error: Object.assign(new Error('socket failed'), { cause: { code: 'ECONNRESET' } }), label: 'cause code' }+ ])('recovers the registered remote source after a $label failure', async ({ error }) => {+ const { desktop, gateway } = await activateRemoteGateway()+ gateway.request.mockResolvedValueOnce({ turn: 1 }).mockRejectedValueOnce(error).mockResolvedValueOnce({ turn: 2 })++ const { result } = renderHook(() => useGatewayRequest())++ await act(async () => {+ await expect(result.current.requestGateway('prompt.submit', { text: 'first' })).resolves.toEqual({ turn: 1 })+ })+ gateway.connectionState = 'closed'+ await act(async () => {+ await expect(result.current.requestGateway('prompt.submit', { text: 'second' })).resolves.toEqual({ turn: 2 })+ })++ expect(desktop.getConnectionFor).toHaveBeenCalledTimes(2)+ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'ssh-source', profile: 'research' })+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledTimes(2)+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledWith({ connectionId: 'ssh-source', profile: 'research' })+ expect(desktop.getConnection).not.toHaveBeenCalled()+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()+ expect(gateway.connect).toHaveBeenLastCalledWith(expect.stringContaining('ticket=fresh-2'))+ })++ it('does not reconnect for a non-transport request failure', async () => {+ const { desktop, gateway } = await activateRemoteGateway()+ const failure = Object.assign(new Error('request rejected'), { code: 'EVALIDATION' })+ gateway.request.mockRejectedValueOnce(failure)++ const { result } = renderHook(() => useGatewayRequest())++ await expect(result.current.requestGateway('session.resume')).rejects.toBe(failure)+ expect(desktop.getConnectionFor).toHaveBeenCalledTimes(1)+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledTimes(1)+ expect(gateway.connect).toHaveBeenCalledTimes(1)+ })++ it('surfaces a real secondary OAuth reauth rejection as the original transport failure', async () => {+ const { desktop, gateway } = await activateRemoteGateway()+ desktop.getGatewayWsUrlFor.mockImplementation(async () => ({+ error: '401 cookie expired',+ needsOauthLogin: true,+ ok: false as const+ }))++ const { result } = renderHook(() => useGatewayRequest())++ await expectSecondaryRecoveryFailure(gateway, result.current.requestGateway)++ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'ssh-source', profile: 'research' })+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalled()+ expect(desktop.getConnection).not.toHaveBeenCalled()+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()+ })++ it('surfaces a failed secondary OAuth ticket mint without using the stale ticket or local bridges', async () => {+ const { desktop, gateway } = await activateRemoteGateway()+ desktop.getGatewayWsUrlFor.mockRejectedValue(new Error('ticket mint failed'))++ const { result } = renderHook(() => useGatewayRequest())++ await expectSecondaryRecoveryFailure(gateway, result.current.requestGateway)++ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'ssh-source', profile: 'research' })+ expect(desktop.getConnection).not.toHaveBeenCalled()+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()+ })++ it('surfaces a missing optional scoped mint bridge without falling back to a stale ticket or local lookup', async () => {+ const { desktop, gateway } = await activateRemoteGateway()+ Reflect.deleteProperty(window.hermesDesktop, 'getGatewayWsUrlFor')++ const { result } = renderHook(() => useGatewayRequest())++ await expectSecondaryRecoveryFailure(gateway, result.current.requestGateway)++ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'ssh-source', profile: 'research' })+ expect(desktop.getConnection).not.toHaveBeenCalled()+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()+ })++ it.each([+ { authMode: 'oauth' as const, label: 'primary OAuth' },+ { authMode: 'token' as const, label: 'local primary' }+ ])('preserves $label recovery', async ({ authMode }) => {+ const desktop = installPrimaryDesktop(authMode)+ const primary = makePrimaryGateway()+ primary.request.mockRejectedValueOnce(new Error('connection closed')).mockResolvedValueOnce({ recovered: true })++ setPrimaryGateway(primary as unknown as HermesGateway, 'default')+ $gateway.set(primary as unknown as HermesGateway)+ $gatewayState.set('closed')++ const { result } = renderHook(() => useGatewayRequest())++ await act(async () => {+ await expect(result.current.requestGateway('session.resume')).resolves.toEqual({ recovered: true })+ })++ expect(desktop.getConnection).toHaveBeenCalledWith('default')+ expect(desktop.getGatewayWsUrl).toHaveBeenCalledWith('default')+ expect(desktop.getConnectionFor).not.toHaveBeenCalled()+ expect(desktop.getGatewayWsUrlFor).not.toHaveBeenCalled()+ })})diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.tsindex 04f53f785b4..dd659e76ed0 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts@@ -114,15 +114,14 @@ export function useGatewayRequest() {try {return await gateway.request<T>(method, params, timeoutMs, signal)} catch (error) {- const message = error instanceof Error ? error.message : String(error)-- if (!/not connected|connection closed/i.test(message)) {+ if (!isGatewayTransportError(error)) {throw error}// Primary keeps the OAuth-aware reconnect (remote gateways re-mint a- // single-use ticket); background profiles are always local pool- // backends, so the registry handles their reconnect with no reauth.+ // single-use ticket). Background profiles stay on the registry's+ // connection-owned reconnect path, including composite remote/SSH+ // sources.const recovered = isActivePrimary() ? await ensureGatewayOpen() : await ensureActiveGatewayOpen()if (!recovered) {@@ -146,3 +145,42 @@ export function useGatewayRequest() {return { connectionRef, gateway, gatewayRef, requestGateway }}++const GATEWAY_TRANSPORT_ERROR_CODES = new Set([+ 'ECONNABORTED',+ 'ECONNREFUSED',+ 'ECONNRESET',+ 'EHOSTUNREACH',+ 'ENETUNREACH',+ 'ENOTFOUND',+ 'EPIPE',+ 'ETIMEDOUT',+ 'ERR_NETWORK',+ 'ERR_SOCKET_CLOSED'+])++function errorCode(value: unknown): string | null {+ if (typeof value !== 'object' || value === null) {+ return null+ }++ const code = (value as { code?: unknown }).code++ return typeof code === 'string' ? code.toUpperCase() : null+}++function isGatewayTransportError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error)++ if (/not connected|connection closed|connection reset|ECONNRESET/i.test(message)) {+ return true+ }++ const cause = typeof error === 'object' && error !== null ? (error as { cause?: unknown }).cause : undefined++ return [error, cause].some(value => {+ const code = errorCode(value)++ return code !== null && GATEWAY_TRANSPORT_ERROR_CODES.has(code)+ })+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 7b054f860d1..ab342ddb812 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -27,6 +27,7 @@ import {setCurrentServiceTier,setCurrentUsage,setMessagingSessions,+ setSessionOwnerHint,setSessions,setWorkspaceCwdOwner,setYoloActive@@ -1246,13 +1247,16 @@ export function upsertOptimisticSession(title: string | null = null,preview: string | null = null,parentSessionId: string | null = null,- lastActive?: number+ lastActive?: number,+ ownerRoute?: SessionProfileRoute) {const now = lastActive ?? Date.now() / 1000- // Stamp the profile the session was just created on (= the live gateway's- // profile) so the scoped sidebar shows the new row immediately instead of- // filtering it out as "default" until the aggregator re-fetches.- const profileKey = normalizeProfileKey($activeGatewayProfile.get())+ // Stamp the profile/source the session was just created on so the scoped+ // sidebar shows the new row immediately instead of filtering it out as+ // "default" until the aggregator re-fetches. The active gateway is only a+ // presentation detail: a concurrent source switch can move it before this+ // optimistic row is inserted.+ const profileKey = normalizeProfileKey(ownerRoute?.profile ?? $activeGatewayProfile.get())const session: SessionInfo = {// Seed cwd so the grouped sidebar can place the new row in its repo/worktree@@ -1274,7 +1278,12 @@ export function upsertOptimisticSession(source: 'tui',started_at: now,title,- tool_call_count: 0+ tool_call_count: 0,+ ...(ownerRoute?.connectionId.trim() ? { connection_id: ownerRoute.connectionId.trim() } : {})+ }++ if (ownerRoute) {+ setSessionOwnerHint(id, ownerRoute)}setSessions(prev => [session, ...prev.filter(s => s.id !== id)])diff --git a/apps/desktop/src/store/session-request-router.test.ts b/apps/desktop/src/store/session-request-router.test.tsindex aef4597f55d..913d1930ab1 100644--- a/apps/desktop/src/store/session-request-router.test.ts+++ b/apps/desktop/src/store/session-request-router.test.ts@@ -487,4 +487,18 @@ describe('requestForSessionProfile', () => {expect(ambient).toHaveBeenCalledOnce()})++ it('preserves ambient request arity as optional controls are supplied', async () => {+ const ambient = vi.fn(async () => ({ ambient: true }))+ const params = { session_id: 'rt-3' }+ const controller = new AbortController()++ await requestForSessionProfile(null, ambient as never, 'session.usage', params)+ await requestForSessionProfile(null, ambient as never, 'session.usage', params, 1_800_000)+ await requestForSessionProfile(null, ambient as never, 'session.usage', params, undefined, controller.signal)++ expect(ambient.mock.calls.map(args => args.length)).toEqual([2, 3, 4])+ expect(ambient).toHaveBeenNthCalledWith(2, 'session.usage', params, 1_800_000)+ expect(ambient).toHaveBeenNthCalledWith(3, 'session.usage', params, undefined, controller.signal)+ })})diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.tsindex 4775975fe7f..68b1652841e 100644--- a/apps/desktop/src/store/session-request-router.ts+++ b/apps/desktop/src/store/session-request-router.ts@@ -154,9 +154,15 @@ export function requestForSessionProfile<T>(// changes the observed call shape for the many callers that never asked// for a deadline (the plugin host bridge in contrib/wiring is the only one// that does).- return timeoutMs === undefined && signal === undefined- ? ambientRequest<T>(method, params)- : ambientRequest<T>(method, params, timeoutMs, signal)+ if (signal !== undefined) {+ return ambientRequest<T>(method, params, timeoutMs, signal)+ }++ if (timeoutMs !== undefined) {+ return ambientRequest<T>(method, params, timeoutMs)+ }++ return ambientRequest<T>(method, params)}const profile = normKey(ownerProfile)diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.tsindex f21e701e755..653e895e7e6 100644--- a/apps/desktop/src/store/session-states.test.ts+++ b/apps/desktop/src/store/session-states.test.ts@@ -671,6 +671,12 @@ describe('knownOwnerForSession / requestForOwnedSession (#91684 client half)', (expect(knownOwnerForSession('stored-2')).toBe('loki')})+ it('keeps a session row connection owner when profiles share the same name', () => {+ setSessions([{ connection_id: 'source-b', id: 'stored-shared', profile: 'default' } as never])++ expect(knownOwnerForSession('stored-shared')).toEqual({ connectionId: 'source-b', profile: 'default' })+ })+it('returns undefined (ambient) when no owner is known, and for null ids', () => {expect(knownOwnerForSession('unknown-session')).toBeUndefined()expect(knownOwnerForSession(null)).toBeUndefined()diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex e112ecc5998..792f3d502e1 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -43,7 +43,7 @@ import {$selectedStoredSessionId,$sessions,clearReadBaseline,- knownSessionProfile,+ knownSessionOwner,lineageAliases,markSessionRead,sessionMatchesStoredId,@@ -844,7 +844,7 @@ export function openTileGatewayScopes(): Set<string> {/*** Sync owner resolution for a session id that may be a RUNTIME or a STORED id.* Tile route first (exact connectionId+profile, survives relaunch), then the- * known session profile (row or open-time hint). Returns undefined when no+ * known session owner (row or open-time hint). Returns undefined when no* owner is known — the caller falls back to ambient, never to "active".*/export function knownOwnerForSession(sessionId: null | string | undefined): SessionOwnerScope {@@ -854,7 +854,7 @@ export function knownOwnerForSession(sessionId: null | string | undefined): Sessconst storedSessionId = storedSessionIdForRuntimeId(sessionId) ?? sessionId- return sessionTileOwnerRoute(storedSessionId) ?? knownSessionProfile($sessions.get(), storedSessionId)+ return sessionTileOwnerRoute(storedSessionId) ?? knownSessionOwner($sessions.get(), storedSessionId)}/**diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex 71913e31ecf..8b7c489128d 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -1049,3 +1049,21 @@ describe('knownSessionProfile', () => {expect(knownSessionProfile([], null)).toBeUndefined()})})++describe('knownSessionOwner', () => {+ it('preserves a registry connection on a same-named session row', () => {+ expect(+ knownSessionOwner(+ [session({ connection_id: 'source-b', id: 'shared-session', profile: 'default' })],+ 'shared-session'+ )+ ).toEqual({ connectionId: 'source-b', profile: 'default' })+ })++ it('preserves a composite owner hint when the row is not listed', () => {+ const owner = { connectionId: 'source-a', profile: 'default', targetProfile: 'backend-default' }+ setSessionOwnerHint('hidden-session', owner)++ expect(knownSessionOwner([], 'hidden-session')).toEqual(owner)+ })+})diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 69d6710df31..3bfc4b00df4 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -126,19 +126,46 @@ export function sessionBelongsToProfile(* often the only sync source.*/export function knownSessionProfile(sessions: readonly SessionInfo[], sessionId: null | string): string | undefined {+ const owner = knownSessionOwner(sessions, sessionId)++ return typeof owner === 'string' ? owner : (owner?.targetProfile ?? owner?.profile)?.trim() || undefined+}++/**+ * The complete known owner of a session, including its registry connection+ * when the row or an open-time hint carries one. Session-scoped RPC callers+ * must use this instead of `knownSessionProfile`: two sources can expose the+ * same profile name, so returning only that name silently collapses the route+ * back to the local/profile-only path.+ */+export function knownSessionOwner(+ sessions: readonly SessionInfo[],+ sessionId: null | string+): SessionProfileRoute | string | undefined {if (!sessionId) {return undefined}- const owner = sessions.find(session => sessionMatchesStoredId(session, sessionId))?.profile?.trim()+ const session = sessions.find(candidate => sessionMatchesStoredId(candidate, sessionId))+ const profile = session?.profile?.trim()+ const connectionId = session?.connection_id?.trim()+ const hint = getSessionOwnerHint(sessionId)- if (owner) {- return owner+ if (connectionId) {+ return { connectionId, profile: profile || 'default' }}- const hint = getSessionOwnerHint(sessionId)+ const hintProfiles = new Set([hint?.profile.trim() || 'default', hint?.targetProfile?.trim() || 'default'])++ if (hint && (!profile || hintProfiles.has(profile || 'default'))) {+ return hint+ }++ if (profile) {+ return profile+ }- return (hint?.targetProfile ?? hint?.profile)?.trim() || undefined+ return hint}/**@@ -177,7 +204,7 @@ export function knownSessionOwner(** Do NOT use this to ROUTE a session-scoped RPC: the active-profile fallback is* exactly what sends a hidden/unlisted session's RPC to a backend that never- * owned it. Routing must use `knownSessionProfile` + a cross-profile probe and+ * owned it. Routing must use `knownSessionOwner` + a cross-profile probe and* surface an error instead of falling back. This remains for the navigation* keying it was written for.*/