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.ts index ba60e4f635..f3aecf106f 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 @@ -10,7 +10,7 @@ import type { SessionResumeResponse } from '@/types/hermes' import type { usePromptActions } from '../../session/hooks/use-prompt-actions' import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume' import { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils' -import { resolveSessionProfile } from '../../session/hooks/use-session-actions/utils' +import { resolveSessionOwner } from '../../session/hooks/use-session-actions/utils' import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache' import type { GatewayRequester } from '../types' @@ -74,11 +74,14 @@ export function useSessionTileDelegate({ } } + // Same ladder as the window's session-RPC dispatcher: tile route → the + // row's owner (exact when connection-tagged, else the hint / profile) → + // the async cross-profile probe (exact when the resolved row is tagged). const ownerForStoredSession = async (storedSessionId: string): Promise => { const owner = sessionTileOwnerRoute(storedSessionId) ?? knownSessionOwner($sessions.get(), storedSessionId) ?? - (await resolveSessionProfile(storedSessionId)) + (await resolveSessionOwner(storedSessionId)) return owner } diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts new file mode 100644 index 0000000000..5f3d67d0d5 --- /dev/null +++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts @@ -0,0 +1,150 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// Fail-closed owner resolution for the window's ONE session-scoped RPC +// dispatcher. A request that names a session whose owner NO rung can name +// (tile route → exact hint → connection-tagged / profiled row → REST probe) +// must not ride the ambient presentation socket: "active" has no routing +// authority, and the fallback turned missing ownership metadata into a +// misleading backend "session not found". The single exception is the legacy +// single-backend Desktop (no registry source, ≤1 profile), where the ambient +// gateway IS the owner by construction. + +const gatewayMocks = vi.hoisted(() => ({ + activeConnectionId: null as null | string, + requestGatewayForAgent: vi.fn(async () => ({ routed: true })), + requestGatewayForProfile: vi.fn(async () => ({ profiled: true })) +})) + +vi.mock('@/store/gateway', async importActual => ({ + ...(await importActual>()), + activeGatewayConnectionId: () => gatewayMocks.activeConnectionId, + requestGatewayForAgent: gatewayMocks.requestGatewayForAgent, + requestGatewayForProfile: gatewayMocks.requestGatewayForProfile +})) + +const probe = vi.hoisted(() => ({ resolveSessionOwner: vi.fn(async () => undefined as unknown) })) + +vi.mock('@/app/session/hooks/use-session-actions/utils', async importActual => ({ + ...(await importActual>()), + resolveSessionOwner: probe.resolveSessionOwner +})) + +const { createSessionRpcDispatcher } = await import('./session-rpc-dispatcher') +const { $profiles } = await import('@/store/profile') +const { _resetSessionOwnerHintsForTests, setSessionOwnerHint, setSessions } = await import('@/store/session') +const { isSessionOwnerResolutionError } = await import('@/store/session-owner-resolution') +const { $sessionTiles } = await import('@/store/session-states') +const { makeSessionInfo } = await import('@/test/session-info') + +function dispatcher(ambientRequest = vi.fn(async () => ({ ambient: true }))) { + return { + ambientRequest, + request: createSessionRpcDispatcher({ + ambientRequest: ambientRequest as never, + runtimeIdByStoredSessionIdRef: { current: new Map([['stored-omar', 'rt-omar']]) }, + selectedStoredSessionIdRef: { current: null }, + sessionStateByRuntimeIdRef: { current: new Map() } + }) + } +} + +beforeEach(() => { + gatewayMocks.activeConnectionId = 'local' + $profiles.set([{ name: 'default' }, { name: 'omar' }] as never) + probe.resolveSessionOwner.mockResolvedValue(undefined) +}) + +afterEach(() => { + setSessions([]) + $sessionTiles.set([]) + $profiles.set([]) + _resetSessionOwnerHintsForTests({ storage: true }) + vi.clearAllMocks() +}) + +describe('createSessionRpcDispatcher: fail closed', () => { + it('rejects with an explicit owner-resolution error instead of riding the ambient socket', async () => { + const { ambientRequest, request } = dispatcher() + + await expect(request('prompt.submit', { session_id: 'rt-orphan', text: 'hi' })).rejects.toSatisfy( + isSessionOwnerResolutionError + ) + await expect(request('prompt.submit', { session_id: 'rt-orphan', text: 'hi' })).rejects.toThrow( + /owner could not be resolved for "rt-orphan" \(prompt.submit\)/ + ) + + expect(probe.resolveSessionOwner).toHaveBeenCalledWith('rt-orphan') + expect(ambientRequest).not.toHaveBeenCalled() + expect(gatewayMocks.requestGatewayForAgent).not.toHaveBeenCalled() + expect(gatewayMocks.requestGatewayForProfile).not.toHaveBeenCalled() + }) + + it('still lets a request with NO session (ambient chrome) reach the ambient socket', async () => { + const { ambientRequest, request } = dispatcher() + + await expect(request('config.get', {})).resolves.toEqual({ ambient: true }) + expect(ambientRequest).toHaveBeenCalledWith('config.get', {}) + }) + + it('keeps the legacy single-backend Desktop on the ambient socket: no registry source, one profile', async () => { + gatewayMocks.activeConnectionId = null + $profiles.set([{ name: 'default' }] as never) + const { ambientRequest, request } = dispatcher() + + await expect(request('session.resume', { session_id: 'stored-legacy' })).resolves.toEqual({ ambient: true }) + expect(ambientRequest).toHaveBeenCalledWith('session.resume', { session_id: 'stored-legacy' }) + }) + + it('fails closed as soon as there is somewhere to misroute to: a second profile, or a live registry source', async () => { + gatewayMocks.activeConnectionId = null + $profiles.set([{ name: 'default' }, { name: 'omar' }] as never) + await expect(dispatcher().request('session.resume', { session_id: 'stored-x' })).rejects.toSatisfy( + isSessionOwnerResolutionError + ) + + gatewayMocks.activeConnectionId = 'local' + $profiles.set([{ name: 'default' }] as never) + await expect(dispatcher().request('session.resume', { session_id: 'stored-x' })).rejects.toSatisfy( + isSessionOwnerResolutionError + ) + }) +}) + +describe('createSessionRpcDispatcher: exact owner rungs', () => { + it('routes by the connection-tagged row when the hint is gone (runtime id translated to the stored id)', async () => { + setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })]) + const { ambientRequest, request } = dispatcher() + + await expect(request('prompt.submit', { session_id: 'rt-omar', text: 'again' })).resolves.toEqual({ routed: true }) + + expect(gatewayMocks.requestGatewayForAgent).toHaveBeenCalledWith('local', 'omar', 'prompt.submit', { + session_id: 'rt-omar', + text: 'again' + }) + expect(ambientRequest).not.toHaveBeenCalled() + expect(probe.resolveSessionOwner).not.toHaveBeenCalled() + }) + + it('prefers the exact hint over an untagged row profile, and the probe result over nothing', async () => { + setSessions([makeSessionInfo({ id: 'stored-omar', profile: 'default' })]) + setSessionOwnerHint('stored-omar', { connectionId: 'local', profile: 'omar' }) + + await expect(dispatcher().request('session.interrupt', { session_id: 'rt-omar' })).resolves.toEqual({ + routed: true + }) + expect(gatewayMocks.requestGatewayForAgent).toHaveBeenLastCalledWith('local', 'omar', 'session.interrupt', { + session_id: 'rt-omar' + }) + + _resetSessionOwnerHintsForTests() + setSessions([]) + probe.resolveSessionOwner.mockResolvedValue({ connectionId: 'homelab', profile: 'worker' }) + + await expect(dispatcher().request('session.activate', { session_id: 'stored-hidden' })).resolves.toEqual({ + routed: true + }) + expect(gatewayMocks.requestGatewayForAgent).toHaveBeenLastCalledWith('homelab', 'worker', 'session.activate', { + session_id: 'stored-hidden' + }) + }) +}) diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts index 958fa32d4b..ea0d03b1ab 100644 --- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts +++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts @@ -23,15 +23,20 @@ * * Session-scoped RPCs route to the backend that OWNS the session — never to * whatever is "active" (active is presentation only). The owner ladder is - * resolveSessionRpcOwner (tile route → exact unique owner hint → row profile), - * then a cross-profile REST probe for a hidden/unlisted session. Only a - * request with NO session at all falls to the ambient socket. + * resolveSessionRpcOwner (tile route → exact unique owner hint → the row's + * owner: exact when connection-tagged, else its profile), then a + * cross-profile REST probe for a hidden/unlisted session. A request with a + * session whose owner STILL cannot be named fails closed with an explicit + * SessionOwnerResolutionError rather than riding the ambient socket (the one + * exception: the legacy single-backend Desktop, where ambient IS the owner). + * Only a request with NO session at all falls to the ambient socket. */ import type { MutableRefObject } from 'react' -import { resolveSessionProfile } from '@/app/session/hooks/use-session-actions/utils' +import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils' import type { ClientSessionState } from '@/app/types' import { $sessions, getSessionOwnerHint, knownSessionOwner } from '@/store/session' +import { assertSessionOwnerResolved } from '@/store/session-owner-resolution' import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router' import { $focusedStoredSessionId, sessionTileOwnerRoute, storedSessionIdForRuntimeId } from '@/store/session-states' @@ -78,16 +83,20 @@ export function createSessionRpcDispatcher(deps: SessionRpcDispatcherDeps): Ambi if (!owner && routingSessionId) { // Unknown owner for a REAL session: probe across profiles (REST, not the // gateway socket, so no recursion) rather than defaulting to active. A - // hit stamps ownership + caches a hint; a miss leaves owner undefined - // and the request falls to ambient, exactly as an unroutable session did - // before — but only after we tried, never as a silent active fallback. - const probed = await resolveSessionProfile(routingSessionId) + // hit stamps ownership on the row (exact when the row came back + // connection-tagged); a miss leaves owner undefined. + const probed = await resolveSessionOwner(routingSessionId) if (probed) { owner = probed } } + // A request that names a session but whose owner nobody can name must not + // ride the ambient socket: that turns missing metadata into a misleading + // backend "session not found" on a backend that never held the runtime. + assertSessionOwnerResolved(owner, { method, sessionId: paramSessionId ? routingSessionId : null }) + return requestForSessionProfile(owner, ambientRequest, method, params ?? {}, timeoutMs, signal) } } diff --git a/apps/desktop/src/app/contrib/wiring-routing.test.ts b/apps/desktop/src/app/contrib/wiring-routing.test.ts index 77694efe19..cb981d40d0 100644 --- a/apps/desktop/src/app/contrib/wiring-routing.test.ts +++ b/apps/desktop/src/app/contrib/wiring-routing.test.ts @@ -118,6 +118,31 @@ describe('resolveSessionRpcOwner', () => { expect(owner).toEqual(omar) }) + it('reconstructs the EXACT owner from a connection-tagged row when the hint is gone (evicted / relaunch)', () => { + // The bounded hint map is transient. A row tagged with its owning + // connection (optimistic create row, unified-list splice, or a tag + // mergeSessionPage carried across a refresh) names the same registry + // entry, so the second turn still dials the socket that holds the runtime. + expect( + resolveSessionRpcOwner({ + routingSessionId: 'stored-omar', + sessionOwnerHint: none, + sessionRowOwner: () => ({ connectionId: 'local', profile: 'omar' }), + tileOwnerRoute: none + }) + ).toEqual({ connectionId: 'local', profile: 'omar' }) + + // The hint still outranks the row when both exist. + expect( + resolveSessionRpcOwner({ + routingSessionId: 'stored-omar', + sessionOwnerHint: () => omar, + sessionRowOwner: () => ({ connectionId: 'homelab', profile: 'omar' }), + tileOwnerRoute: none + }) + ).toEqual(omar) + }) + it('falls back to the session row profile, then to undefined for the probe', () => { expect( resolveSessionRpcOwner({ @@ -136,5 +161,14 @@ describe('resolveSessionRpcOwner', () => { tileOwnerRoute: none }) ).toBeUndefined() + + expect( + resolveSessionRpcOwner({ + routingSessionId: 'stored-1', + sessionOwnerHint: none, + sessionRowOwner: () => null, + tileOwnerRoute: none + }) + ).toBeUndefined() }) }) diff --git a/apps/desktop/src/app/contrib/wiring-routing.ts b/apps/desktop/src/app/contrib/wiring-routing.ts index 5cb1baa911..8ad82a5ef9 100644 --- a/apps/desktop/src/app/contrib/wiring-routing.ts +++ b/apps/desktop/src/app/contrib/wiring-routing.ts @@ -5,6 +5,8 @@ * React/Electron controller module. */ +import type { SessionOwnerRoute } from '@/store/session-request-router' + /** * Resolve a runtime session id back to its stored id by reverse-scanning the * stored->runtime binding map — the same ladder use-session-tile-delegate's @@ -51,14 +53,8 @@ export function resolveRoutingSessionId(args: { /** The owner shapes the ladder below can return: an exact route (connection + * profile), a bare profile name, or undefined (unknown — probe, never - * "active"). Structural twin of store/session-request-router's - * SessionOwnerScope, kept local so this module stays import-free. */ -export interface SessionRpcOwnerRoute { - connectionId: string - mode?: 'local' | 'remote' - profile: string - targetProfile?: string -} + * "active"). The type-only import keeps this module runtime-import-free. */ +export type SessionRpcOwnerRoute = SessionOwnerRoute /** * The SYNC owner a session-scoped RPC routes to, resolved in this order: @@ -66,21 +62,23 @@ export interface SessionRpcOwnerRoute { * 1. the persisted tile owner route (a bot chat / split tile records the * exact connectionId + profile it was opened with, survives relaunch); * 2. the exact, UNIQUE session owner hint (recorded the moment a routed - * session.create returns, or at plugin open time) — the only durable - * exact owner a fresh main-pane chat or a hidden session has; + * session.create returns, or at plugin open time; persisted, bounded); * 3. the session row's owner — an EXACT route when the row is - * connection-tagged (optimistic row from a routed create, or the - * unified list splice), else its bare profile (the cross-profile - * aggregator tags rows, but a bare profile loses the connection and - * can lag the create); - * 4. undefined → the caller runs the cross-profile probe. + * connection-tagged (optimistic row from a routed create, the unified + * list splice, or a tag carried across a refresh), else its bare + * profile (the cross-profile aggregator tags rows, but a bare profile + * loses the connection and can lag the create); + * 4. undefined → the caller runs the cross-profile probe, and fails closed + * if that misses too. * * The hint outranks the row because the row is presentation state that can * be stamped from the AMBIENT profile (an optimistic row minted while * All-profiles / Bot routing left `default` active), and because it carries * no connection: a fresh chat created on `local::omar` whose row read * `default` ran its first turn on omar and then 4001'd "session not found" - * on the second, when the row's `default` owner won the route. + * on the second, when the row's `default` owner won the route. The + * connection-tagged row rung is what keeps two-turn continuity from resting + * on the transient hint alone (bounded, evictable, gone after a relaunch). */ export function resolveSessionRpcOwner(args: { routingSessionId: null | string diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts index 3299f62df1..59b598de1c 100644 --- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts +++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts @@ -54,8 +54,10 @@ import { $activeSessionId, $connection, $currentCwd, + $selectedStoredSessionId, $sessions, ensureDefaultWorkspaceCwd, + forgetSessionOwnerHintsForConnection, setConnection, setCurrentBranch, setCurrentCwd, @@ -672,6 +674,11 @@ export function useGatewayBoot({ // (connectionId, profile) keep-set so two sources exposing the same // profile name (every source has a 'default') can't collide. configureGatewayRegistry({ + // Every dispose path in the registry (live-work pruner AND the + // refcount-0 request leases) spares a socket a mounted tile, the + // primary thread or a just-created session's owner hold is bound to + // (#93892). + foregroundScopes: foregroundSessionScopes, onActiveConnectionChanged: publish, // Keep $activeGatewayProfile in lockstep with the registry's OWN record // of which profile the active socket serves. The registry is the only @@ -770,6 +777,13 @@ export function useGatewayBoot({ } disposeSecondariesForConnection(payload.connectionId, { redial: payload.reason === 'updated' }) + + if (payload.reason !== 'updated') { + // Nothing can dial the removed source again: drop the persisted exact + // owner hints naming it so its sessions are not pinned (fail-closed) + // to a route that no longer exists. + forgetSessionOwnerHintsForConnection(payload.connectionId) + } }) const onOnline = () => void forceReconnectNow() @@ -821,6 +835,11 @@ export function useGatewayBoot({ keep.add(scope) } + // A just-created session's owner hold and every open pane's owner ride + // in through foregroundSessionScopes above; the registry ALSO reads that + // set itself (its `foregroundScopes` hook) so the refcount-0 lease + // releases agree with this pruner. This recompute only has to RUN when + // they change — see the tile / selected session / hold subscriptions. pruneSecondaryGateways(keep) } @@ -830,6 +849,7 @@ export function useGatewayBoot({ const offSessionTiles = $sessionTiles.subscribe(() => recomputeKeptGateways()) const offActiveProfile = $activeGatewayProfile.subscribe(() => recomputeKeptGateways()) const offTiles = $sessionTiles.subscribe(() => recomputeKeptGateways()) + const offSelectedSession = $selectedStoredSessionId.subscribe(() => recomputeKeptGateways()) const offWindowState = desktop.onWindowStateChanged?.(payload => { const current = $connection.get() @@ -1027,6 +1047,7 @@ export function useGatewayBoot({ offSessionTiles() offActiveProfile() offTiles() + offSelectedSession() window.removeEventListener('online', onOnline) document.removeEventListener('visibilitychange', onVisible) window.removeEventListener('focus', onFocus) diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx index d2a6e44791..09b48b5c82 100644 --- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx +++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx @@ -26,7 +26,9 @@ import { $activeSessionId, $selectedStoredSessionId, $sessions, + _resetSessionOwnerHintsForTests, getSessionOwnerHint, + mergeSessionPage, sessionMatchesStoredId, setActiveSessionId, setAwaitingResponse, @@ -35,6 +37,8 @@ import { setSelectedStoredSessionId, setSessions } from '@/store/session' +import { foregroundSessionScopes } from '@/store/session-states' +import type { SessionInfo } from '@/types/hermes' import type { ClientSessionState } from '../../types' @@ -64,7 +68,7 @@ import { useSessionStateCache } from './use-session-state-cache' // The explicit `local` source (This device) is different by design: a profile // pick made there takes the legacy profile-only door (ensureGatewayProfile, // so a per-profile remote override still resolves), and the draft's owner is -// that v1 profile socket — the second case pins that the same one-socket +// that v1 profile socket — the last case pins that the same one-socket // continuity holds there too. // // This suite drives the ACTUAL code path: the real registry store with mocked @@ -344,6 +348,7 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across $newChatProfile.set(null) $newChatRoute.set(null) $newChatConnectionId.set(null) + _resetSessionOwnerHintsForTests({ storage: true }) }) afterEach(() => { @@ -360,7 +365,10 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop }) - it('session.create and both prompt.submit calls ride the SAME conn:homelab::omar socket', async () => { + /** Boot the exact field state: remote primary on `default`, `homelab` as + * the active registry source, then selectProfile("omar") in the rail; mount + * the window's real hook stack over the production dispatcher. */ + async function bootProfileRailOmar() { // Primary / ambient source: a remote gateway on `default`. const primary = makePrimary() setPrimaryGateway(primary as never, 'default') @@ -396,8 +404,32 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across render( (handle = h)} />) await waitFor(() => expect(handle).not.toBeNull()) + return { handle: handle!, omarSocket: omarSocket!, primary } + } + + /** What the gateway's stream end does: the turn settles. */ + async function settleTurn(handle: HarnessHandle) { + await act(async () => { + handle.updateSessionState(RUNTIME_ID, state => ({ + ...state, + awaitingResponse: false, + busy: false, + streamId: null, + turnStartedAt: null + })) + handle.busyRef.current = false + setBusy(false) + setAwaitingResponse(false) + }) + } + + const calls = (socket: MockGateway) => socket.request.mock.calls.map(call => call[0] as string) + + it('session.create and both prompt.submit calls ride the SAME conn:homelab::omar socket', async () => { + const { handle, omarSocket, primary } = await bootProfileRailOmar() + // Turn one: no session yet → createBackendSessionForSend → prompt.submit. - await expect(handle!.submitText('first prompt')).resolves.toBe(true) + await expect(handle.submitText('first prompt')).resolves.toBe(true) await waitFor(() => expect($activeSessionId.get()).toBe(RUNTIME_ID)) // The stored↔runtime binding minted by the create must survive the first @@ -405,35 +437,28 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across // (null) stored id, which the state cache read as a detach — after which // no session-scoped RPC could translate the runtime id back to the stored // id, so tile route / owner hint / row were all bypassed. - expect(handle!.bindings()).toEqual({ runtimeForStored: RUNTIME_ID, storedForRuntime: STORED_ID }) + expect(handle.bindings()).toEqual({ runtimeForStored: RUNTIME_ID, storedForRuntime: STORED_ID }) - // Answer one arrives: the turn settles (what the gateway's stream end does). - await act(async () => { - handle!.updateSessionState(RUNTIME_ID, state => ({ - ...state, - awaitingResponse: false, - busy: false, - streamId: null, - turnStartedAt: null - })) - handle!.busyRef.current = false - setBusy(false) - setAwaitingResponse(false) - }) + // From the moment the create returned, the owner socket is foreground- + // pinned (owner hold → selected-thread rung) so no prune / lease release + // can close it before the first prompt.submit lands. + expect(foregroundSessionScopes()).toContain(omarScope) + + // Answer one arrives: the turn settles. + await settleTurn(handle) // Turn two on the now-existing session. - await expect(handle!.submitText('second prompt')).resolves.toBe(true) - expect(handle!.bindings()).toEqual({ runtimeForStored: RUNTIME_ID, storedForRuntime: STORED_ID }) + await expect(handle.submitText('second prompt')).resolves.toBe(true) + expect(handle.bindings()).toEqual({ runtimeForStored: RUNTIME_ID, storedForRuntime: STORED_ID }) // Every session-scoped RPC (create + both submits) hit ONE socket: the // registry entry conn:homelab::omar that minted the runtime. - const calls = (socket: MockGateway) => socket.request.mock.calls.map(call => call[0] as string) - const omarCalls = calls(omarSocket!) + const omarCalls = calls(omarSocket) expect(omarCalls).toContain('session.create') expect(omarCalls.filter(method => method === 'prompt.submit')).toHaveLength(2) expect( - omarSocket!.request.mock.calls + omarSocket.request.mock.calls .filter(call => call[0] === 'prompt.submit') .map(call => [(call[1] as { session_id: string }).session_id, (call[1] as { text: string }).text]) ).toEqual([ @@ -476,6 +501,66 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across expect($newChatConnectionId.get()).toBe(SOURCE_ID) }) + it('turn two still rides conn:homelab::omar after the transient hint is evicted AND a refresh returned the row untagged', async () => { + const { handle, omarSocket, primary } = await bootProfileRailOmar() + + await expect(handle.submitText('first prompt')).resolves.toBe(true) + await waitFor(() => expect($activeSessionId.get()).toBe(RUNTIME_ID)) + await settleTurn(handle) + + // The two things that used to leave only a bare "omar" behind: + // 1. the bounded owner-hint map evicts (or the app relaunched); + // 2. the sidebar refresh comes back with the row untagged (the primary + // aggregate serves a source's rows as plain profile rows whenever the + // unified-list splice did not tag them). + _resetSessionOwnerHintsForTests() + expect(getSessionOwnerHint(STORED_ID)).toBeUndefined() + + const untagged: SessionInfo = { + ...$sessions.get().find(session => sessionMatchesStoredId(session, STORED_ID))!, + profile: 'omar' + } + + delete untagged.connection_id + setSessions(prev => mergeSessionPage(prev, [untagged], [])) + + // The row still names the exact owner: the refresh carried the tag. + expect($sessions.get().find(session => sessionMatchesStoredId(session, STORED_ID))).toMatchObject({ + connection_id: SOURCE_ID, + profile: 'omar' + }) + + await expect(handle.submitText('second prompt')).resolves.toBe(true) + expect(handle.bindings()).toEqual({ runtimeForStored: RUNTIME_ID, storedForRuntime: STORED_ID }) + + expect( + omarSocket.request.mock.calls + .filter(call => call[0] === 'prompt.submit') + .map(call => (call[1] as { session_id: string; text: string }).text) + ).toEqual(['first prompt', 'second prompt']) + + // Nothing session-scoped reached the primary, a v1 "omar" socket, or any + // other socket; no REST probe, no session.close, no second create. + expect(calls(primary).filter(method => method === 'session.create' || method === 'prompt.submit')).toEqual([]) + expect(sockets.some(socket => socket.connectUrl?.includes(`:${V1_PORT}`))).toBe(false) + + for (const socket of sockets) { + if (socket !== omarSocket) { + expect( + socket.request.mock.calls.filter(call => sessionScoped(call[1]) || call[0] === 'session.create') + ).toEqual([]) + } + } + + expect(vi.mocked(getSession)).not.toHaveBeenCalled() + + for (const socket of [primary, ...sockets]) { + expect(calls(socket).filter(method => method === 'session.close')).toEqual([]) + } + + expect(calls(omarSocket).filter(method => method === 'session.create')).toHaveLength(1) + }) + it('a pick on the explicit `local` source is a legacy profile pick: create and both turns ride the ONE v1 omar socket', async () => { const primary = makePrimary() setPrimaryGateway(primary as never, 'default') @@ -540,8 +625,6 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across // The legacy owner is the bare profile: no registry route, no hint — the // row's profile names the same v1 pool entry that minted the runtime. - const calls = (socket: MockGateway) => socket.request.mock.calls.map(call => call[0] as string) - expect(calls(v1Socket!).filter(method => method === 'session.create')).toHaveLength(1) expect( v1Socket!.request.mock.calls diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx index 7e20f884b5..fca3f31346 100644 --- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx @@ -102,7 +102,8 @@ vi.mock('@/store/profile', async importOriginal => ({ vi.mock('@/store/gateway', async importOriginal => ({ ...(await importOriginal>()), requestGatewayForAgent: vi.fn(), - requestGatewayForProfile: vi.fn() + requestGatewayForProfile: vi.fn(), + retainGatewayForAgent: vi.fn(async () => () => undefined) })) vi.mock('@/components/pane-shell/tree/store', async importOriginal => ({ 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 b454cc8730..436326d1dd 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 @@ -22,7 +22,12 @@ import { setSessionYolo } from '@/lib/yolo-session' import { $clarifyRequests } from '@/store/clarify' import { migrateSessionDraft } from '@/store/composer' import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue' -import { openGatewayForAgent, openGatewayForProfile, requestGatewayForAgent } from '@/store/gateway' +import { + openGatewayForAgent, + openGatewayForProfile, + requestGatewayForAgent, + retainGatewayForAgent +} from '@/store/gateway' import { $gatewaySwitching } from '@/store/gateway-switch' import { $pinnedSessionIds } from '@/store/layout' import { clearNotifications, notify, notifyError } from '@/store/notifications' @@ -94,9 +99,11 @@ import { $sessionTiles, closeSessionTile, dropSessionState, + holdSessionOwnerUntilForeground, openSessionTile, patchSessionTile, publishSessionState, + releaseSessionOwnerHold, type SessionTileWorkspaceScope, type TileDock } from '@/store/session-states' @@ -484,28 +491,49 @@ export function useSessionActions({ const capturedRoute = resolveNewChatOwnerRoute() const params = await desktopSessionCreateParams(cwd, capturedRoute) - const created = capturedRoute - ? await requestGatewayForAgent( - capturedRoute.connectionId, - capturedRoute.profile, - 'session.create', - params - ) - : await requestGateway('session.create', params) + // Lease the owner socket for the whole create → owner-publication + // sequence (#93602 primitive). The per-request lease inside + // requestGatewayForAgent ends when session.create returns; the + // foreground hold below takes over from that point until the created + // chat is selected. Between the two, nothing may close the socket + // that just minted the runtime. + const releaseCreateLease = capturedRoute + ? await retainGatewayForAgent(capturedRoute.connectionId, capturedRoute.profile) + : () => undefined - const stored = created.stored_session_id ?? null + let created: SessionCreateResponse + let stored: null | string - // Record the EXACT owner the moment a routed create returns a stored - // id — before the drift check, the optimistic row, navigation, or any - // session-scoped RPC can resolve this session's owner. The route is - // the only authority: in All-profiles / Bot routing the ambient - // $activeGatewayProfile stays on `default` while the session lives on - // `capturedRoute` (e.g. local::omar). Without this hint the optimistic - // row (stamped from ambient) was the only owner record, so the first - // turn ran on omar and every later session-scoped RPC resolved the row - // as `default` and 4001'd "session not found". - if (stored && capturedRoute) { - setSessionOwnerHint(stored, capturedRoute) + try { + created = capturedRoute + ? await requestGatewayForAgent( + capturedRoute.connectionId, + capturedRoute.profile, + 'session.create', + params + ) + : await requestGateway('session.create', params) + + stored = created.stored_session_id ?? null + + // Record the EXACT owner the moment a routed create returns a stored + // id — before the drift check, the optimistic row, navigation, or any + // session-scoped RPC can resolve this session's owner. The route is + // the only authority: in All-profiles / Bot routing the ambient + // $activeGatewayProfile stays on `default` while the session lives on + // `capturedRoute` (e.g. local::omar). Without this hint the optimistic + // row (stamped from ambient) was the only owner record, so the first + // turn ran on omar and every later session-scoped RPC resolved the row + // as `default` and 4001'd "session not found". + if (stored && capturedRoute) { + setSessionOwnerHint(stored, capturedRoute) + // Pin the owner socket until the foreground publication (route → + // $selectedStoredSessionId) covers it, so a prune or lease release + // in that gap cannot close the runtime before the first prompt. + holdSessionOwnerUntilForeground(stored, capturedRoute) + } + } finally { + releaseCreateLease() } // Only a genuine move to a DIFFERENT chat mid-create should orphan the @@ -538,6 +566,10 @@ export function useSessionActions({ await closeCreated.catch(() => undefined) + if (stored) { + releaseSessionOwnerHold(stored) + } + return null } @@ -655,16 +687,38 @@ export function useSessionActions({ ...(workspaceScope.workspaceMode === 'bots' ? { hidden: true } : {}) } - const created = capturedRoute - ? await requestGatewayForAgent( - capturedRoute.connectionId, - capturedRoute.profile, - 'session.create', - params - ) - : await requestGateway('session.create', params) + // Same lease chain as createBackendSessionForSend: owner socket held + // across the create, then the foreground hold carries it until the + // tile is mounted ($sessionTiles names the owner from then on). + const releaseCreateLease = capturedRoute + ? await retainGatewayForAgent(capturedRoute.connectionId, capturedRoute.profile) + : () => undefined - const stored = created.stored_session_id + let created: SessionCreateResponse + let stored: string | undefined + + try { + created = capturedRoute + ? await requestGatewayForAgent( + capturedRoute.connectionId, + capturedRoute.profile, + 'session.create', + params + ) + : await requestGateway('session.create', params) + + stored = created.stored_session_id + + if (stored && capturedRoute) { + // Same ownership transition as createBackendSessionForSend: the + // route that minted the session is its exact owner from this + // moment on, and its socket stays pinned until the tile mounts. + setSessionOwnerHint(stored, capturedRoute) + holdSessionOwnerUntilForeground(stored, capturedRoute) + } + } finally { + releaseCreateLease() + } if (!stored) { const closeCreated = capturedRoute @@ -681,12 +735,6 @@ export function useSessionActions({ createdThisRun.add(stored) - // Same ownership transition as createBackendSessionForSend: the route - // that minted the session is its exact owner from this moment on. - if (capturedRoute) { - setSessionOwnerHint(stored, capturedRoute) - } - // Seed the per-runtime cache so the tile renders immediately without a // redundant resume. Only add the row to the SIDEBAR when `listed` — an // unlisted (draft) tab stays out of the session list until its first 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.ts index 6f35f38713..83e599b589 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 @@ -37,6 +37,7 @@ import type { SessionProfileRoute } from '@/store/session-request-router' // Re-exported for the many session-actions/tile call sites that already import // it from here; the canonical definition lives in @/store/session. export { sessionMatchesStoredId } +import { sessionOwnerRouteFromRow, type SessionOwnerScope } from '@/store/session-request-router' import { reportBackendContract, reportInstallMethodWarning } from '@/store/updates' import type { SessionCreateResponse, SessionInfo, SessionResumeResponse, SessionRuntimeInfo } from '@/types/hermes' @@ -1506,6 +1507,25 @@ export async function resolveSessionProfile(storedSessionId: null | string): Pro return profile || undefined } +/** + * The OWNER of a stored session through the same cache → active-backend → + * cross-profile ladder, preferring the EXACT route when the resolved row is + * connection-tagged (unified-list splice, optimistic create row, a carried + * tag) over its bare profile. Session-scoped RPC dispatch uses this as the + * async rung after the sync ladder (tile route → hint → row) misses, so a + * registry-owned session never degrades to a profile-only route that dials a + * different socket than the one holding its runtime. + */ +export async function resolveSessionOwner(storedSessionId: null | string): Promise { + if (!storedSessionId) { + return undefined + } + + const row = await resolveStoredSession(storedSessionId) + + return sessionOwnerRouteFromRow(row) ?? (row?.profile?.trim() || undefined) +} + type SessionRuntimeStatePatch = Partial< Pick< ClientSessionState, diff --git a/apps/desktop/src/store/gateway-foreground-retention.test.ts b/apps/desktop/src/store/gateway-foreground-retention.test.ts new file mode 100644 index 0000000000..baf801bdf2 --- /dev/null +++ b/apps/desktop/src/store/gateway-foreground-retention.test.ts @@ -0,0 +1,177 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// #93892 regression: the registry disposed the secondary socket an idle Bot +// Chat tile was bound to — the live-work pruner for a pre-dialed (retained) +// entry, and the refcount-0 request lease for one the tile's own resume +// created. openGatewayForAgent marks the entry `retained`, but `retained` is +// a one-way latch every hover pre-warm and profile switch also sets, so no +// dispose path can honor it without leaking every socket ever warmed. +// Instead the registry's `foregroundScopes` hook names the scopes FOREGROUND +// surfaces are bound to (foregroundSessionScopes): a mounted tile pins its +// owner socket for exactly as long as it is mounted, on every dispose path. + +const gatewayMocks = vi.hoisted(() => ({ + closed: [] as string[] +})) + +vi.mock('@/hermes', async importActual => ({ + ...(await importActual>()), + setApiRequestConnection: vi.fn(), + HermesGateway: class { + connectionState = 'closed' + wsUrl = '' + connect = async (wsUrl: string): Promise => { + this.wsUrl = wsUrl + this.connectionState = 'open' + } + close = (): void => { + gatewayMocks.closed.push(this.wsUrl) + this.connectionState = 'closed' + } + request = async (): Promise => ({}) + onEvent = vi.fn(() => () => {}) + onState = vi.fn(() => () => {}) + } +})) +vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() })) + +const { + closeSecondaryGateways, + configureGatewayRegistry, + openGatewayForAgent, + pruneSecondaryGateways, + requestGatewayForAgent, + setPrimaryGateway +} = await import('./gateway') + +const { $sessionTiles, foregroundSessionScopes, liveSessionScopes } = await import('./session-states') + +function installDesktop(): void { + ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { + getConnection: vi.fn(async () => ({ + authMode: 'token', + profile: 'default', + token: 't', + wsUrl: 'wss://local.invalid/api/ws?token=t' + })), + getConnectionFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({ + authMode: 'token', + connectionId, + profile, + token: 't', + wsUrl: `wss://${connectionId}.invalid/api/ws?profile=${profile}` + })), + getGatewayWsUrlFor: vi.fn( + async ({ connectionId, profile }: { connectionId: string; profile: string }) => + `wss://${connectionId}.invalid/api/ws?profile=${profile}` + ), + touchBackend: vi.fn(async () => undefined) + } +} + +// What use-gateway-boot's recomputeKeptGateways feeds the pruner for a +// window with NO busy / needs-input work anywhere — the idle bot chat case. +// Foreground pins are NOT in here: the registry reads them itself. +const idleKeepSet = () => liveSessionScopes() + +const BOT_TILE = { + ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'bot' }, + runtimeId: 'rt-bot', + storedSessionId: 'stored-bot' +} + +beforeEach(() => { + installDesktop() + // Wired exactly as use-gateway-boot wires it. + configureGatewayRegistry({ foregroundScopes: foregroundSessionScopes, onEvent: vi.fn() }) + setPrimaryGateway({ connectionState: 'open' } as never, 'default') + gatewayMocks.closed = [] + $sessionTiles.set([]) +}) + +afterEach(() => { + closeSecondaryGateways() + $sessionTiles.set([]) + vi.clearAllMocks() + delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop +}) + +describe('foreground tile retention vs. the live-work pruner (#93892)', () => { + it('keeps an idle Bot Chat tile’s owner socket across prune recomputes', async () => { + // The BOTS workspace dials the bot's own backend without activating it + // (keepAllProfilesScope) and opens the canonical chat as a tile on that + // route. The global active profile stays primary/default. + await openGatewayForAgent('local', 'bot') + $sessionTiles.set([BOT_TILE]) + + // Idle: no working / needs-input session anywhere. Before the fix this + // recompute closed the socket → backend reaped the runtime → reclaim → + // unbind → resume → … forever. + pruneSecondaryGateways(idleKeepSet()) + pruneSecondaryGateways(idleKeepSet()) + + expect(gatewayMocks.closed).toEqual([]) + }) + + it('keeps the socket while the tile is still resuming (no runtime bound yet)', async () => { + await openGatewayForAgent('local', 'bot') + $sessionTiles.set([{ ...BOT_TILE, runtimeId: undefined }]) + + pruneSecondaryGateways(idleKeepSet()) + + expect(gatewayMocks.closed).toEqual([]) + }) + + it('releases the socket once the tile is closed — the pin never latches', async () => { + await openGatewayForAgent('local', 'bot') + $sessionTiles.set([BOT_TILE]) + pruneSecondaryGateways(idleKeepSet()) + expect(gatewayMocks.closed).toEqual([]) + + $sessionTiles.set([]) + pruneSecondaryGateways(idleKeepSet()) + + expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=bot']) + }) + + it('keeps the socket a tile’s OWN resume dialed (no pre-dial, refcount-0 lease path)', async () => { + // Relaunch with a persisted Bot Chat tab: nothing pre-dials the bot, so + // the tile's session.resume goes out through requestGatewayForAgent's + // per-request lease on a fresh, NON-retained entry. Before the fix the + // lease's `finally` disposed that socket the instant the resume returned + // — the runtime it had just minted was orphaned on the spot. + $sessionTiles.set([{ ...BOT_TILE, runtimeId: undefined }]) + + await requestGatewayForAgent('local', 'bot', 'session.resume', { session_id: 'stored-bot' }) + + expect(gatewayMocks.closed).toEqual([]) + + // …and the pruner agrees with the lease. + pruneSecondaryGateways(idleKeepSet()) + expect(gatewayMocks.closed).toEqual([]) + + // Tile gone: the next lease release disposes as it always did. + $sessionTiles.set([]) + await requestGatewayForAgent('local', 'bot', 'session.usage', { session_id: 'stored-bot' }) + expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=bot']) + }) + + it('still prunes a merely pre-warmed (retained, no surface) socket — `retained` is not a pin', async () => { + // A roster hover warms the bot's socket through the same door and sets + // the same `retained` flag; with no tile bound to it, it is idle garbage. + await openGatewayForAgent('local', 'bot') + + pruneSecondaryGateways(idleKeepSet()) + + expect(gatewayMocks.closed).toEqual(['wss://local.invalid/api/ws?profile=bot']) + }) + + it('does not let a tile on one source pin another source’s same-named profile', async () => { + await openGatewayForAgent('homelab', 'bot') + $sessionTiles.set([BOT_TILE]) + + pruneSecondaryGateways(idleKeepSet()) + + expect(gatewayMocks.closed).toEqual(['wss://homelab.invalid/api/ws?profile=bot']) + }) +}) diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts index d646515b7b..b6d12e3ecd 100644 --- a/apps/desktop/src/store/gateway.ts +++ b/apps/desktop/src/store/gateway.ts @@ -36,6 +36,19 @@ interface RegistryConfig { * (#89206: the stale-profile split-brain that stranded bot wake-ups). */ onActiveRouteChanged?: (profile: string) => void + /** + * Scopes a FOREGROUND surface is bound to right now — every mounted + * session tile's owner and the primary thread's (foregroundSessionScopes in + * store/session-states; a config hook because that store imports this + * one). Consulted by EVERY dispose path — the live-work pruner and the + * dispose-at-refcount-0 request/relay leases alike (#93892): a tile's + * resume mints its runtime on its owner's socket, and any path that closes + * that socket makes the backend orphan-reap the runtime, whose + * `session.reclaimed` unbinds the tile and re-arms its resume — a spinner + * loop with no terminal state. Read at decision time, never cached: it + * follows the tile set, so closing the tile releases the socket. + */ + foregroundScopes?: () => ReadonlySet } // ── Secondary (pool) backends ────────────────────────────────────────────── @@ -56,7 +69,16 @@ interface Secondary { reconnectTimer: ReturnType | null reconnectAttempt: number reconnecting: boolean - /** True when a foreground/prewarmed consumer owns this entry beyond one RPC. */ + /** + * True when a foreground/prewarmed consumer owns this entry beyond one RPC. + * Guards ONLY the dispose-at-refcount-0 paths (request/relay leases), never + * the live-work pruner: it is a one-way latch that every hover pre-warm and + * profile switch sets and nothing ever clears, so honoring it in + * pruneSecondaryGateways would pin every socket ever warmed. A foreground + * surface that must keep its owner socket (a mounted session tile, the + * primary thread) is represented in the pruner's keep-set instead — see + * foregroundSessionScopes in store/session-states (#93892). + */ retained: boolean /** * Bot-relay retainers pinning this socket open across drain ticks (#93594). @@ -695,7 +717,13 @@ async function gatewayForProfile( released = true entry.activeRequests = Math.max(0, entry.activeRequests - 1) - if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) { + if ( + entry.activeRequests === 0 && + !entry.retained && + !relayRetained(entry) && + !foregroundPinned(entry) && + g.activeKey !== entry.scope + ) { disposeSecondary(entry) if (g.secondaries.get(entry.scope) === entry) { @@ -811,7 +839,13 @@ export async function requestGatewayForAgent( } finally { entry.activeRequests = Math.max(0, entry.activeRequests - 1) - if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) { + if ( + entry.activeRequests === 0 && + !entry.retained && + !relayRetained(entry) && + !foregroundPinned(entry) && + g.activeKey !== entry.scope + ) { disposeSecondary(entry) if (g.secondaries.get(entry.scope) === entry) { @@ -831,6 +865,22 @@ export async function requestGatewayForAgent( // scheduleReconnect/backoff machinery) alive across ticks; stopBotRelay (and // plugin dispose) releases it, restoring the dispose-at-refcount-0 behavior. +/** + * True when a foreground surface (mounted tile / primary thread) is bound to + * this entry's scope (#93892). Registry-scoped entries match on their + * composite key only; local/legacy entries also match on the bare profile — + * the same key language pruneSecondaryGateways' keep-set speaks. + */ +function foregroundPinned(entry: Secondary): boolean { + const scopes = g.config?.foregroundScopes?.() + + if (!scopes) { + return false + } + + return scopes.has(entry.scope) || (!entry.connectionId && scopes.has(entry.profile)) +} + /** True when the bot relay currently pins this entry open. Number guard: * dev-HMR entries predate the field. */ function relayRetained(entry: Secondary): boolean { @@ -879,6 +929,7 @@ export function retainGatewayForRelay(connectionId: null | string, profile: stri entry.relayRetainCount === 0 && entry.activeRequests === 0 && !entry.retained && + !foregroundPinned(entry) && g.activeKey !== entry.scope && g.secondaries.get(entry.scope) === entry ) { @@ -941,7 +992,13 @@ export async function retainGatewayForAgent(connectionId: null | string, profile released = true entry.activeRequests = Math.max(0, entry.activeRequests - 1) - if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) { + if ( + entry.activeRequests === 0 && + !entry.retained && + !relayRetained(entry) && + !foregroundPinned(entry) && + g.activeKey !== entry.scope + ) { disposeSecondary(entry) if (g.secondaries.get(entry.scope) === entry) { @@ -1400,6 +1457,16 @@ function restoreActiveToPrimaryIfEvicted(): void { // source exposes a 'default' profile, so matching a non-local entry on the // bare profile name kept gateway B's 'default' socket alive off gateway A's // 'default' activity (and vice versa) — cross-connection attribution. +// +// Live work is not the only thing worth a socket: an idle tile still holds a +// resumed runtime on its owner's socket, and closing that socket makes the +// backend detach and orphan-reap the runtime, whose `session.reclaimed` +// unbinds the tile and re-resumes it on a fresh socket that the next +// recompute closes again — a spinner loop with no terminal state (#93892). +// Foreground-bound scopes come from the registry's `foregroundScopes` hook +// (foregroundPinned), not from `keep`, so every dispose path sees the same +// pin. `entry.retained` is deliberately NOT consulted here (see the field's +// doc). export function pruneSecondaryGateways(keep: Set): void { const now = Date.now() @@ -1412,6 +1479,9 @@ export function pruneSecondaryGateways(keep: Set): void { // its whole active lifetime; the live-work pruner must not undo that // pin between drain ticks or the socket churn returns. relayRetained(entry) || + // A mounted tile / the primary thread is bound to a runtime on this + // socket (#93892) — pinned for as long as that surface is mounted. + foregroundPinned(entry) || // Mid-dial activation target: the profile being switched TO is not yet // active and has no live work, so without this lease any recompute // during its cold spawn disposed the entry and the click died silently diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts index 7a274b049f..e0e72cbc91 100644 --- a/apps/desktop/src/store/profile.ts +++ b/apps/desktop/src/store/profile.ts @@ -26,6 +26,7 @@ import { import { notifyError } from '@/store/notifications' import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override' import { setConnection } from '@/store/session' +import type { SessionOwnerRoute } from '@/store/session-request-router' import { resetStarmapGraph } from '@/store/starmap' import type { ProfileInfo } from '@/types/hermes' @@ -250,12 +251,9 @@ export const $activeGatewayProfile = atom('default') // Profile for the NEXT new chat (chosen via the new-chat picker). null = primary // / default, so single-profile users are unaffected. export const $newChatProfile = atom(null) -export interface AgentProfileRoute { - connectionId: string - mode?: 'local' | 'remote' - profile: string - targetProfile?: string -} +/** The draft's exact owner — the same shape every session-scoped surface + * routes by (store/session-request-router SessionOwnerRoute). */ +export type AgentProfileRoute = SessionOwnerRoute // A draft remembers the source it was created for. The active gateway may // change before the first Send; the draft's owner must not change with it. diff --git a/apps/desktop/src/store/session-owner-resolution.ts b/apps/desktop/src/store/session-owner-resolution.ts new file mode 100644 index 0000000000..ae280979ac --- /dev/null +++ b/apps/desktop/src/store/session-owner-resolution.ts @@ -0,0 +1,76 @@ +/** + * Fail-closed owner resolution for session-scoped RPCs. + * + * A request that carries a `session_id` only means anything on the backend + * that OWNS that session. When every rung of the owner ladder (tile route → + * exact owner hint → connection-tagged / profiled row → cross-profile REST + * probe) misses, the request must NOT quietly ride the ambient presentation + * gateway: "active" is presentation state with no routing authority, and an + * ambient fallback turns missing ownership metadata into a misleading backend + * "session not found" (or, worse, an answer from a backend that merely happens + * to know a same-named session). Surface an explicit owner-resolution error + * instead — the caller's error UX shows it, and the runtime that minted the + * session is left untouched for the next correctly-routed attempt. + * + * The ONE case where the ambient gateway is not a fallback but the owner by + * construction: no registry source is live (legacy v1 primary) AND at most + * one profile exists — a single backend serves every session, so there is + * nothing to misroute to. Older single-profile backends omit `profile` on + * their rows entirely; those users keep working unchanged. + */ +import { activeGatewayConnectionId } from './gateway' +import { $profiles } from './profile' +import { isSessionOwnerRoute, type SessionOwnerScope } from './session-request-router' + +export class SessionOwnerResolutionError extends Error { + constructor( + readonly sessionId: string, + readonly method: string + ) { + super( + `Session owner could not be resolved for "${sessionId}" (${method}): ` + + 'no owner route, hint, connection-tagged row or profile probe named the backend that holds this session, ' + + 'and routing it to the active gateway would be a guess.' + ) + this.name = 'SessionOwnerResolutionError' + } +} + +export function isSessionOwnerResolutionError(error: unknown): error is SessionOwnerResolutionError { + return ( + error instanceof SessionOwnerResolutionError || + (error as { name?: unknown })?.name === 'SessionOwnerResolutionError' + ) +} + +/** True when the ambient gateway is provably the only backend any session + * can live on (legacy single-backend Desktop): no registry source is active + * and there is at most one profile. Everything else has somewhere to misroute. */ +export function ambientGatewayOwnsEverySession(): boolean { + return activeGatewayConnectionId() === null && $profiles.get().length <= 1 +} + +/** True when `owner` names a backend (an exact route or a profile). */ +export function sessionOwnerIsKnown(owner: SessionOwnerScope): boolean { + if (isSessionOwnerRoute(owner)) { + return Boolean(owner.connectionId.trim()) + } + + return owner != null && Boolean(String(owner).trim()) +} + +/** + * Gate before a session-scoped RPC falls to the ambient dispatcher. Throws + * SessionOwnerResolutionError when the session's owner is unknown and the + * ambient gateway is not the sole backend; otherwise returns normally. + */ +export function assertSessionOwnerResolved( + owner: SessionOwnerScope, + context: { method: string; sessionId: null | string | undefined } +): void { + if (!context.sessionId || sessionOwnerIsKnown(owner) || ambientGatewayOwnsEverySession()) { + return + } + + throw new SessionOwnerResolutionError(context.sessionId, context.method) +} diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.ts index 68b1652841..65649fd034 100644 --- a/apps/desktop/src/store/session-request-router.ts +++ b/apps/desktop/src/store/session-request-router.ts @@ -1,13 +1,47 @@ import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForSessionTurn } from '@/store/gateway' -export interface SessionProfileRoute { +/** + * The ONE authoritative exact owner of a session: the registry connection whose + * socket minted (or resumed) the runtime, plus the Desktop profile that selects + * that route. `targetProfile` is the backend profile the route serves when it + * differs from the Desktop-side name (remote overrides); `mode` is informative. + * + * Captured ONCE at the new-chat intent / send linearization point + * (store/profile resolveNewChatOwnerRoute) and carried through session.create, + * the owner hint, the optimistic row, the runtime binding, the foreground hold + * and every later session-scoped RPC. Never re-derived from ambient state after + * an asynchronous activation: connection/profile EQUALITY is not enough — the + * runtime lives on one concrete WebSocket, and only this route names the + * registry entry that holds it. + */ +export interface SessionOwnerRoute { connectionId: string mode?: 'local' | 'remote' profile: string targetProfile?: string } -export type SessionOwnerScope = undefined | null | string | SessionProfileRoute +/** @deprecated Alias kept for existing imports; new code names SessionOwnerRoute. */ +export type SessionProfileRoute = SessionOwnerRoute + +export type SessionOwnerScope = undefined | null | string | SessionOwnerRoute + +/** Exact owner reconstructed from a CONNECTION-TAGGED session row (the + * Electron unified-list splice tags foreign registry rows; an optimistic row + * carries the create route's connection; mergeSessionPage carries the tag + * across refreshes). A row without a connection tag yields undefined — a bare + * profile is not an exact owner. */ +export function sessionOwnerRouteFromRow( + row: { connection_id?: null | string; profile?: null | string } | null | undefined +): SessionOwnerRoute | undefined { + const connectionId = String(row?.connection_id ?? '').trim() + + if (!connectionId) { + return undefined + } + + return { connectionId, profile: String(row?.profile ?? '').trim() || 'default' } +} // ── Session-scoped RPC routing (the #89206 class) ─────────────────────────── // A session-scoped RPC (session.resume / session.activate / session.usage / @@ -29,9 +63,11 @@ export type SessionOwnerScope = undefined | null | string | SessionProfileRoute const normKey = (profile: null | string | undefined): string => (profile ?? '').trim() || 'default' -const isRoute = (owner: SessionOwnerScope): owner is SessionProfileRoute => +export const isSessionOwnerRoute = (owner: SessionOwnerScope): owner is SessionOwnerRoute => Boolean(owner && typeof owner === 'object' && 'connectionId' in owner) +const isRoute = isSessionOwnerRoute + function routeParams(route: SessionProfileRoute, params: Record): Record { if (!route.targetProfile || !Object.prototype.hasOwnProperty.call(params, 'profile')) { return params diff --git a/apps/desktop/src/store/session-states-foreground-scopes.test.ts b/apps/desktop/src/store/session-states-foreground-scopes.test.ts new file mode 100644 index 0000000000..7325b6d51a --- /dev/null +++ b/apps/desktop/src/store/session-states-foreground-scopes.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + $selectedStoredSessionId, + _resetSessionOwnerHintsForTests, + setActiveSessionId, + setSessionOwnerHint +} from '@/store/session' + +import { + $sessionTiles, + _resetSessionOwnerHoldsForTests, + foregroundSessionScopes, + holdSessionOwnerUntilForeground, + recordSessionEventScope, + releaseSessionOwnerHold +} from './session-states' + +// A routed session.create returns a stored id on the owner's socket, but the +// surface that will pin that socket (the selected primary thread, or a tile) +// is published later and asynchronously. The hold names the owner in +// foregroundSessionScopes — the gateway keep-set — from the moment the create +// returns until the foreground publication takes over, the caller releases +// it, or a bounded TTL expires. Nothing latches. + +afterEach(() => { + $sessionTiles.set([]) + setActiveSessionId(null) + $selectedStoredSessionId.set(null) + _resetSessionOwnerHoldsForTests() + _resetSessionOwnerHintsForTests({ storage: true }) + vi.useRealTimers() +}) + +describe('foregroundSessionScopes: owner hold across the create → foreground gap', () => { + const omar = { connectionId: 'local', mode: 'local' as const, profile: 'omar' } + + it('names the owner from the moment a routed create returns, before anything is selected or tiled', () => { + holdSessionOwnerUntilForeground('stored-fresh', omar) + + expect(foregroundSessionScopes()).toEqual(new Set(['conn:local::omar'])) + }) + + it('retires once the foreground publication covers it (selected primary thread / mounted tile)', () => { + holdSessionOwnerUntilForeground('stored-fresh', omar) + setSessionOwnerHint('stored-fresh', omar) + + // Selected, but the runtime's event scope is not known yet: the hold is + // still the only thing naming the owner socket, so it stays. + $selectedStoredSessionId.set('stored-fresh') + expect(foregroundSessionScopes()).toEqual(new Set(['conn:local::omar'])) + + // The first event from the owner socket records the runtime's scope; the + // selected-thread rung now covers it and the hold retires for good. + recordSessionEventScope({ connectionId: 'local', profile: 'omar', session_id: 'rt-fresh' }) + setActiveSessionId('rt-fresh') + expect(foregroundSessionScopes()).toEqual(new Set(['conn:local::omar'])) + setActiveSessionId(null) + $selectedStoredSessionId.set(null) + _resetSessionOwnerHintsForTests() + expect(foregroundSessionScopes()).toEqual(new Set()) + + holdSessionOwnerUntilForeground('stored-tile', { connectionId: 'homelab', profile: 'bot' }) + $sessionTiles.set([{ ownerRoute: { connectionId: 'homelab', profile: 'bot' }, storedSessionId: 'stored-tile' }]) + // Covered by the tile's own route rung now; the hold retired. + expect(foregroundSessionScopes()).toEqual(new Set(['conn:homelab::bot'])) + $sessionTiles.set([]) + expect(foregroundSessionScopes()).toEqual(new Set()) + }) + + it('is released explicitly by the caller (failed create / drift close) and expires on its own', () => { + vi.useFakeTimers() + + const release = holdSessionOwnerUntilForeground('stored-a', omar) + holdSessionOwnerUntilForeground('stored-b', { connectionId: 'homelab', profile: 'worker' }) + + release() + expect(foregroundSessionScopes()).toEqual(new Set(['conn:homelab::worker'])) + + releaseSessionOwnerHold('stored-b') + expect(foregroundSessionScopes()).toEqual(new Set()) + + holdSessionOwnerUntilForeground('stored-c', omar) + vi.advanceTimersByTime(60_000 + 1) + expect(foregroundSessionScopes()).toEqual(new Set()) + }) + + it('ignores blank ids, null owners and profile-only owners map to the legacy pool key', () => { + holdSessionOwnerUntilForeground(' ', omar) + holdSessionOwnerUntilForeground('stored-null', null) + holdSessionOwnerUntilForeground('stored-legacy', 'research') + + expect(foregroundSessionScopes()).toEqual(new Set(['research'])) + }) +}) diff --git a/apps/desktop/src/store/session-states-runtime-map.test.ts b/apps/desktop/src/store/session-states-runtime-map.test.ts index c9e8d91788..1b12f91a9a 100644 --- a/apps/desktop/src/store/session-states-runtime-map.test.ts +++ b/apps/desktop/src/store/session-states-runtime-map.test.ts @@ -1,6 +1,18 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' -import { $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states' +import { createClientSessionState } from '@/lib/chat-runtime' +import { $profiles } from '@/store/profile' +import { _resetSessionOwnerHintsForTests, setSessionOwnerHint, setSessions } from '@/store/session' +import { isSessionOwnerResolutionError } from '@/store/session-owner-resolution' +import { + $sessionTiles, + clearAllSessionStates, + knownOwnerForSession, + publishSessionState, + requestForOwnedSession, + storedSessionIdForRuntimeId +} from '@/store/session-states' +import { makeSessionInfo } from '@/test/session-info' // #92687-adjacent Bot Mode misroute: a session RPC (prompt.submit et al.) // carries its target as a RUNTIME id, while tile owner routes key on the @@ -47,6 +59,20 @@ describe('storedSessionIdForRuntimeId', () => { expect(storedSessionIdForRuntimeId('undefined')).toBeNull() }) + it('maps a MAIN-PANE runtime id through the per-runtime state mirror (no tile involved)', () => { + // approval.respond from a native notification, a queued send: the caller + // holds the runtime id of the primary thread, which no tile knows. The + // state mirror carries the stored id the wiring cache bound. + publishSessionState('rt-main', createClientSessionState('stored-main')) + + expect(storedSessionIdForRuntimeId('rt-main')).toBe('stored-main') + // A detached runtime (null stored id) is still unknown. + publishSessionState('rt-detached', createClientSessionState(null)) + expect(storedSessionIdForRuntimeId('rt-detached')).toBeNull() + + clearAllSessionStates() + }) + it('prefers the stored-id identity when one tile is stored-matched and another is runtime-matched', () => { // Pathological but possible after a stale rebind: some other tile's dead // runtimeId equals a live tile's storedSessionId. The stored-id claim is @@ -59,3 +85,45 @@ describe('storedSessionIdForRuntimeId', () => { expect(storedSessionIdForRuntimeId('collision')).toBe('collision') }) }) + +describe('knownOwnerForSession / requestForOwnedSession', () => { + afterEach(() => { + $sessionTiles.set([]) + clearAllSessionStates() + setSessions([]) + $profiles.set([]) + _resetSessionOwnerHintsForTests({ storage: true }) + }) + + it('resolves a main-pane runtime id to its EXACT owner via the mirror + the hint, then the tagged row', () => { + publishSessionState('rt-main', createClientSessionState('stored-main')) + setSessionOwnerHint('stored-main', { connectionId: 'local', profile: 'omar' }) + + expect(knownOwnerForSession('rt-main')).toEqual({ connectionId: 'local', profile: 'omar' }) + + _resetSessionOwnerHintsForTests() + setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-main', profile: 'omar' })]) + expect(knownOwnerForSession('rt-main')).toEqual({ connectionId: 'local', profile: 'omar' }) + + setSessions([makeSessionInfo({ id: 'stored-main', profile: 'coder' })]) + expect(knownOwnerForSession('rt-main')).toBe('coder') + }) + + it('fails closed with an explicit owner-resolution error instead of the ambient socket', async () => { + // Somewhere to misroute to: two profiles exist. + $profiles.set([{ name: 'default' }, { name: 'omar' }] as never) + const ambient = vi.fn(async () => ({ ok: true })) + + await expect( + requestForOwnedSession('rt-orphan', ambient as never, 'approval.respond', { session_id: 'rt-orphan' }) + ).rejects.toSatisfy(isSessionOwnerResolutionError) + expect(ambient).not.toHaveBeenCalled() + + // Legacy single backend: the ambient gateway IS the owner. + $profiles.set([{ name: 'default' }] as never) + await expect( + requestForOwnedSession('rt-orphan', ambient as never, 'approval.respond', { session_id: 'rt-orphan' }) + ).resolves.toEqual({ ok: true }) + expect(ambient).toHaveBeenCalledWith('approval.respond', { session_id: 'rt-orphan' }) + }) +}) diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts index a936d0c301..70ee2f7b8d 100644 --- a/apps/desktop/src/store/session-states.ts +++ b/apps/desktop/src/store/session-states.ts @@ -53,7 +53,8 @@ import { setBusy, setSessions } from './session' -import { requestForSessionProfile, type SessionOwnerScope, type SessionProfileRoute } from './session-request-router' +import { assertSessionOwnerResolved } from './session-owner-resolution' +import { requestForSessionProfile, type SessionOwnerRoute, type SessionOwnerScope } from './session-request-router' import { ackStoredSessionId, markSessionUnreadFinished } from './session-unread' import { isBrowserWindow, isSecondaryWindow } from './windows' @@ -102,6 +103,43 @@ export function liveSessionScopes(): Set { return scopes } +// ── Owner hold across the create → foreground gap ─────────────────────────── +// A routed session.create returns a stored id on the owner's socket, but the +// surface that will PIN that socket (the selected primary thread, or a tile) +// is published later and asynchronously: navigate → route effect → +// $selectedStoredSessionId, or openSessionTile → $sessionTiles. In that gap +// the entry has no active request, is not yet foreground-bound and, if the +// user switched source meanwhile, is not the active key either — so the +// live-work pruner or a refcount-0 lease release could close the socket that +// holds the just-minted runtime before the first prompt.submit. The hold +// names the owner in foregroundSessionScopes from the moment the create +// returns until the foreground publication takes over (the stored id becomes +// selected or tiled), the caller releases it (failed create / drift close), +// or a bounded TTL expires — nothing latches. +const SESSION_OWNER_HOLD_TTL_MS = 60_000 +const sessionOwnerHolds = new Map() + +export function holdSessionOwnerUntilForeground(storedSessionId: string, owner: SessionOwnerScope): () => void { + const id = storedSessionId.trim() + + if (!id || !owner) { + return () => undefined + } + + sessionOwnerHolds.set(id, { owner, until: Date.now() + SESSION_OWNER_HOLD_TTL_MS }) + + return () => releaseSessionOwnerHold(id) +} + +export function releaseSessionOwnerHold(storedSessionId: string): void { + sessionOwnerHolds.delete(storedSessionId.trim()) +} + +/** @internal Tests. */ +export function _resetSessionOwnerHoldsForTests(): void { + sessionOwnerHolds.clear() +} + /** * Registry scopes owned by an open foreground surface, when known. * @@ -111,6 +149,11 @@ export function liveSessionScopes(): Set { * the same ownership contract: a non-focused idle tile is still user-visible * state and must not be evicted just because another pane has focus. Prefer the * live event scope, with the tile's persisted route as the pre-bind fallback. + * + * A just-created session's owner is named by its create → foreground hold + * (holdSessionOwnerUntilForeground) until the selected/tiled publication or + * a bounded TTL retires it, so nothing can close the socket that minted the + * runtime before the first prompt lands. */ export function foregroundSessionScopes(): Set { const scopes = new Set() @@ -123,7 +166,7 @@ export function foregroundSessionScopes(): Set { } } - const addRouteScope = (route: SessionProfileRoute | undefined) => { + const addRouteScope = (route: SessionOwnerRoute | undefined) => { const connectionId = route?.connectionId?.trim() const profile = route?.profile?.trim() @@ -139,6 +182,28 @@ export function foregroundSessionScopes(): Set { addRouteScope(tile.ownerRoute) } + // Create → foreground holds. A hold whose scope the rungs above already + // name (the runtime's event scope once selected, a mounted tile's route) is + // covered and retires; an expired one retires too. + const now = Date.now() + + for (const [storedSessionId, hold] of [...sessionOwnerHolds]) { + const scope = + typeof hold.owner === 'string' + ? normalizeProfileKey(hold.owner) + : hold.owner?.connectionId?.trim() + ? registryBackendScopeKey(hold.owner.connectionId.trim(), normalizeProfileKey(hold.owner.profile)) + : null + + if (!scope || hold.until <= now || scopes.has(scope)) { + sessionOwnerHolds.delete(storedSessionId) + + continue + } + + scopes.add(scope) + } + return scopes } @@ -609,13 +674,13 @@ export interface SessionTile { /** Exact opaque owner key for Bot Mode tabs. */ workspaceOwnerKey?: string /** Credential-free exact route used to resume this tab after relaunch. */ - ownerRoute?: SessionProfileRoute + ownerRoute?: SessionOwnerRoute /** Stable title for hidden relationship chats absent from the Sessions list. */ workspaceTabTitle?: string } export interface SessionTileWorkspaceScope { - ownerRoute?: SessionProfileRoute + ownerRoute?: SessionOwnerRoute workspaceMode: WorkspaceMode workspaceOwnerKey?: string workspaceTabTitle?: string @@ -803,7 +868,7 @@ export function patchSessionTile(storedSessionId: string, patch: Partial (t.storedSessionId === storedSessionId ? { ...t, ...patch } : t))) } -export function sessionTileOwnerRoute(storedSessionId: string): SessionProfileRoute | undefined { +export function sessionTileOwnerRoute(storedSessionId: string): SessionOwnerRoute | undefined { return $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.ownerRoute } @@ -846,11 +911,12 @@ export function openTileGatewayScopes(): Set { * 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 * exact unique owner hint (stamped when a routed create returns / at open - * time), then the known session owner (a connection-tagged row's exact route, - * else its profile / the hint). The hint outranks the row for the same reason - * as contrib/wiring's ladder: a row can be stamped from the ambient profile - * and carries no connection. Returns undefined when no owner is known — the - * caller falls back to ambient, never to "active". + * time; persisted), then the session row's owner (an exact route when the row + * is connection-tagged, else its bare profile, else the hint's profile). The + * hint outranks the row for the same reason as contrib/wiring's ladder: a + * row can be stamped from the ambient profile and carries no connection. + * Returns undefined when no owner is known — the caller fails closed + * (assertSessionOwnerResolved), never falls to "active". */ export function knownOwnerForSession(sessionId: null | string | undefined): SessionOwnerScope { if (!sessionId) { @@ -889,10 +955,12 @@ export function isSessionRemote(sessionId: null | string | undefined): boolean { /** * Dispatch a session-scoped RPC through the OWNER of `sessionId` (tile route → - * known profile), falling back to the ambient dispatcher only when no owner is - * known. This is the client half of #91684: approval.respond (and siblings) - * sent on the ambient socket land on whatever backend is active, which for a - * cross-profile session is a backend that never held the approval. + * hint → connection-tagged row / known profile). This is the client half of + * #91684: approval.respond (and siblings) sent on the ambient socket land on + * whatever backend is active, which for a cross-profile session is a backend + * that never held the approval. An UNKNOWN owner fails closed with an + * explicit SessionOwnerResolutionError unless the ambient gateway is provably + * the only backend (legacy single-profile, no registry source). */ export function requestForOwnedSession( sessionId: null | string | undefined, @@ -907,7 +975,15 @@ export function requestForOwnedSession( timeoutMs?: number, signal?: AbortSignal ): Promise { - return requestForSessionProfile(knownOwnerForSession(sessionId), ambientRequest, method, params, timeoutMs, signal) + const owner = knownOwnerForSession(sessionId) + + try { + assertSessionOwnerResolved(owner, { method, sessionId }) + } catch (error) { + return Promise.reject(error) + } + + return requestForSessionProfile(owner, ambientRequest, method, params, timeoutMs, signal) } /** Resolve a session id THAT MAY BE A RUNTIME ID to the stored id its tile @@ -935,7 +1011,14 @@ export function storedSessionIdForRuntimeId(sessionId: string): null | string { } } - return null + // The per-runtime state mirror carries the stored id the wiring cache bound + // (ensureSessionState / a resume). This is how a MAIN-PANE runtime id — an + // approval.respond from a native notification, a queued send — finds its + // durable identity, and through it the exact owner (hint / tagged row). + // Without this rung such ids fell straight to the ambient socket. + const mirrored = $sessionStates.get()[sessionId]?.storedSessionId?.trim() + + return mirrored || null } export function setSessionTileWorkspaceScope(storedSessionId: string, scope: SessionTileWorkspaceScope): boolean { diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.ts index 8b7c489128..aef88437aa 100644 --- a/apps/desktop/src/store/session.test.ts +++ b/apps/desktop/src/store/session.test.ts @@ -26,13 +26,16 @@ import { $sessions, $unreadFinishedSessionIds, _resetLegacyDiscardForTests, + _resetSessionOwnerHintsForTests, applyConfiguredDefaultProjectDir, commitWorkspaceCwdForSelectedSession, ensureDefaultWorkspaceCwd, + forgetSessionOwnerHintsForConnection, getConfiguredDefaultProjectDir, getRememberedRoute, getRememberedSessionId, getSessionOwnerHint, + hydrateSessionOwnerHints, knownSessionOwner, knownSessionProfile, mergeSessionPage, @@ -61,6 +64,10 @@ import { const session = (over: Partial): SessionInfo => makeSessionInfo({ id: 'live', ...over }) describe('session owner hints', () => { + afterEach(() => { + _resetSessionOwnerHintsForTests({ storage: true }) + }) + it('preserves the registry owner recorded on a discovered session row', () => { expect( knownSessionOwner( @@ -109,6 +116,93 @@ describe('session owner hints', () => { expect(getSessionOwnerHint('bounded-0', scope)).toBeUndefined() expect(getSessionOwnerHint('bounded-256', scope)).toMatchObject({ connectionId: 'bounded-source' }) }) + + it('survives a relaunch: hints are persisted and rehydrated in LRU order', () => { + const omar = { connectionId: 'local', mode: 'local' as const, profile: 'omar' } + const remote = { connectionId: 'homelab', mode: 'remote' as const, profile: 'worker', targetProfile: 'w' } + + setSessionOwnerHint('stored-omar', omar) + setSessionOwnerHint('stored-remote', remote) + + // "Relaunch": the in-memory map is gone, storage is not. + _resetSessionOwnerHintsForTests() + expect(getSessionOwnerHint('stored-omar')).toBeUndefined() + + hydrateSessionOwnerHints() + + expect(getSessionOwnerHint('stored-omar')).toEqual(omar) + expect(getSessionOwnerHint('stored-remote')).toEqual(remote) + + // LRU order survives: the oldest persisted entry is the first evicted. + for (let index = 0; index < 255; index += 1) { + setSessionOwnerHint(`filler-${index}`, { connectionId: 'filler', profile: 'p' }) + } + + expect(getSessionOwnerHint('stored-omar')).toBeUndefined() + expect(getSessionOwnerHint('stored-remote')).toEqual(remote) + }) + + it('ignores malformed persisted entries and never throws on hydrate', () => { + window.localStorage.setItem( + 'hermes.desktop.sessionOwnerHints.v1', + JSON.stringify([ + 'junk', + ['no-route', null], + ['bad-shape', { connectionId: 7, profile: 'x' }], + ['good', { connectionId: 'local', profile: 'omar', mode: 'sideways' }] + ]) + ) + + _resetSessionOwnerHintsForTests() + expect(() => hydrateSessionOwnerHints()).not.toThrow() + expect(getSessionOwnerHint('good')).toEqual({ connectionId: 'local', profile: 'omar' }) + expect(getSessionOwnerHint('no-route')).toBeUndefined() + expect(getSessionOwnerHint('bad-shape')).toBeUndefined() + }) + + it('forgets every hint naming a removed connection, in memory and on disk', () => { + setSessionOwnerHint('stored-a', { connectionId: 'gone', profile: 'omar' }) + setSessionOwnerHint('stored-b', { connectionId: 'gone', profile: 'default' }) + setSessionOwnerHint('stored-c', { connectionId: 'local', profile: 'omar' }) + + forgetSessionOwnerHintsForConnection('gone') + + expect(getSessionOwnerHint('stored-a')).toBeUndefined() + expect(getSessionOwnerHint('stored-b')).toBeUndefined() + expect(getSessionOwnerHint('stored-c')).toEqual({ connectionId: 'local', profile: 'omar' }) + + _resetSessionOwnerHintsForTests() + hydrateSessionOwnerHints() + expect(getSessionOwnerHint('stored-a')).toBeUndefined() + expect(getSessionOwnerHint('stored-c')).toEqual({ connectionId: 'local', profile: 'omar' }) + }) +}) + +describe('knownSessionOwner', () => { + afterEach(() => { + _resetSessionOwnerHintsForTests({ storage: true }) + }) + + it('returns the EXACT route for a connection-tagged row, the bare profile otherwise', () => { + const rows = [ + session({ connection_id: 'local', id: 'tagged', profile: 'omar' }), + session({ id: 'untagged', profile: 'coder' }), + session({ connection_id: ' ', id: 'blank-tag', profile: 'coder' }) + ] + + expect(knownSessionOwner(rows, 'tagged')).toEqual({ connectionId: 'local', profile: 'omar' }) + expect(knownSessionOwner(rows, 'untagged')).toBe('coder') + expect(knownSessionOwner(rows, 'blank-tag')).toBe('coder') + expect(knownSessionOwner(rows, null)).toBeUndefined() + }) + + it('falls through to the EXACT hint route for an unlisted session', () => { + const route = { connectionId: 'homelab', profile: 'worker', targetProfile: 'w' } + + setSessionOwnerHint('hidden', route) + + expect(knownSessionOwner([], 'hidden')).toEqual(route) + }) }) describe('computed $attentionSessionIds', () => { @@ -201,6 +295,39 @@ describe('shouldMigrateComposerScope', () => { }) describe('mergeSessionPage', () => { + it('carries the owning connection onto a row that comes back untagged (local registry source)', () => { + // A `local` registry source's rows are served by the primary aggregate as + // plain local rows: the unified-list splice tags only non-local sources. + // The refresh must not strip the exact owner the routed create stamped. + const previous = [session({ connection_id: 'local', id: 'omar-1', last_active: 5, profile: 'omar' })] + const incoming = [session({ id: 'omar-1', last_active: 5, profile: 'omar' })] + + expect(mergeSessionPage(previous, incoming, [])[0]).toMatchObject({ connection_id: 'local', profile: 'omar' }) + }) + + it('drops the carried tag when the refreshed row names a different profile, and never overrides an incoming tag', () => { + const previous = [ + session({ connection_id: 'local', id: 'moved', profile: 'omar' }), + session({ connection_id: 'local', id: 'foreign', profile: 'omar' }) + ] + + const incoming = [ + session({ id: 'moved', profile: 'default' }), + session({ connection_id: 'homelab', id: 'foreign', profile: 'omar' }) + ] + + const merged = mergeSessionPage(previous, incoming, []) + expect(merged.find(s => s.id === 'moved')?.connection_id).toBeUndefined() + expect(merged.find(s => s.id === 'foreign')?.connection_id).toBe('homelab') + }) + + it('keeps reference identity when the carried tag is already present', () => { + const previous = [session({ connection_id: 'local', id: 'same', last_active: 1, profile: 'omar' })] + const incoming = [session({ connection_id: 'local', id: 'same', last_active: 1, profile: 'omar' })] + + expect(mergeSessionPage(previous, incoming, [])[0]).toBe(incoming[0]) + }) + it('returns the server page untouched when there is nothing to keep', () => { const previous = [session({ id: 'a' }), session({ id: 'b' })] const incoming = [session({ id: 'a' })] diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts index 0b7b99fefa..3cea70ceaf 100644 --- a/apps/desktop/src/store/session.ts +++ b/apps/desktop/src/store/session.ts @@ -6,11 +6,11 @@ import type { ContextSuggestion } from '@/app/types' import type { HermesConnection } from '@/global' import type { ChatMessage } from '@/lib/chat-messages' import { activeConnectionScopeSuffix, rescopeConnectionScopedStores } from '@/lib/connection-scoped' -import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage' +import { persistBoolean, persistString, readJson, storedBoolean, storedString, writeJson } from '@/lib/storage' import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope' import type { SessionInfo, UsageStats } from '@/types/hermes' -import type { SessionProfileRoute } from './session-request-router' +import type { SessionOwnerRoute, SessionOwnerScope } from './session-request-router' import { clearUnreadOnOpen } from './session-unread-remote' type Updater = T | ((current: T) => T) @@ -132,16 +132,18 @@ export function knownSessionProfile(sessions: readonly SessionInfo[], sessionId: } /** - * 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. + * The complete known owner of a session: the EXACT route when the row is + * connection-tagged (an optimistic row from a routed create, a foreign + * registry row from the unified-list splice, or a tag mergeSessionPage carried + * across a refresh), else the open-time / create-time owner hint when it + * agrees with the row, else the bare profile. 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. The exact rungs are what let a session's + * owner be reconstructed after the bounded hint map has evicted it or the app + * relaunched. */ -export function knownSessionOwner( - sessions: readonly SessionInfo[], - sessionId: null | string -): SessionProfileRoute | string | undefined { +export function knownSessionOwner(sessions: readonly SessionInfo[], sessionId: null | string): SessionOwnerScope { if (!sessionId) { return undefined } @@ -457,6 +459,24 @@ export function resolveComposerSessionKey( * either its live `id` or its `_lineage_root_id`. Optimistic deletes/archives * drop the row from `previous` (and unpin it), so a removed session can't be * resurrected here. */ +const profileKeyOf = (profile: null | string | undefined): string => (profile ?? '').trim() || 'default' + +function carriedConnectionId(prev: SessionInfo | undefined, incoming: SessionInfo): string | undefined { + if (incoming.connection_id?.trim()) { + return incoming.connection_id + } + + const carried = prev?.connection_id?.trim() + + if (!carried) { + return undefined + } + + return !incoming.profile?.trim() || profileKeyOf(incoming.profile) === profileKeyOf(prev?.profile) + ? carried + : undefined +} + export function mergeSessionPage( previous: SessionInfo[], incoming: SessionInfo[], @@ -480,8 +500,19 @@ export function mergeSessionPage( // (last_active = MAX(messages.timestamp)). Keep the fresher of the two. const last_active = Math.max(prev?.last_active ?? 0, session.last_active ?? 0) const title = session.title?.trim() ? session.title : prev?.title?.trim() ? prev.title : session.title + // Carry the owning connection onto a row that arrives untagged. The + // primary aggregate serves a `local` registry source's rows as plain + // local rows (the unified-list splice tags only NON-local sources), so + // the first refresh after a routed create used to replace the optimistic + // row's exact owner (connection_id + profile) with a bare profile — after + // which only the transient owner hint knew which socket held the runtime. + // A refresh is new information layered over what we know, not a clobber; + // the tag is kept only while the row still names the same profile. + const connection_id = carriedConnectionId(prev, session) - return last_active === session.last_active && title === session.title ? session : { ...session, last_active, title } + return last_active === session.last_active && title === session.title && connection_id === session.connection_id + ? session + : { ...session, last_active, title, ...(connection_id ? { connection_id } : {}) } }) if (keep.size === 0) { @@ -657,31 +688,53 @@ export const $awaitingResponse = atom(false) // Null whenever the active route has a healthy (or in-flight) resume. export const $resumeFailedSessionId = atom(null) export interface SessionResumeRequest { - ownerRoute?: SessionProfileRoute + ownerRoute?: SessionOwnerRoute sequence: number sessionId: string } let sessionResumeRequestSequence = 0 export const $sessionResumeRequest = atom(null) +// ── Exact session owner hints ─────────────────────────────────────────────── +// The (connectionId, profile[, targetProfile, mode]) route a session was +// created / resumed / opened on, keyed by stored id. Bounded LRU and +// PERSISTED (best-effort, same origin storage as the tiles): the runtime a +// routed create minted lives on one concrete socket, and after the sidebar +// refresh replaced the optimistic row, or after a relaunch, this record is +// how the exact owner is reconstructed for that session's next RPC instead of +// degrading to a bare profile name that dials a different socket. Connection +// ids are stable registry identities (`local`, registry uuids), so a hint +// stays valid across restarts; forgetSessionOwnerHintsForConnection drops +// them when a connection is removed from the registry. const SESSION_OWNER_HINT_LIMIT = 256 -const sessionOwnerHints = new Map() +const SESSION_OWNER_HINTS_KEY = 'hermes.desktop.sessionOwnerHints.v1' +const sessionOwnerHints = new Map() -function sessionOwnerHintKey(sessionId: string, route: Pick): string { +function sessionOwnerHintKey(sessionId: string, route: Pick): string { return JSON.stringify([route.connectionId.trim(), route.profile.trim() || 'default', sessionId]) } -export function setSessionOwnerHint(sessionId: string, route: SessionProfileRoute): void { - const id = sessionId.trim() - - const normalized = { +function normalizeOwnerRoute(route: SessionOwnerRoute): SessionOwnerRoute { + return { ...route, connectionId: route.connectionId.trim(), profile: route.profile.trim() || 'default', ...(route.targetProfile ? { targetProfile: route.targetProfile.trim() || 'default' } : {}) } +} + +function persistSessionOwnerHints(): void { + writeJson( + SESSION_OWNER_HINTS_KEY, + sessionOwnerHints.size === 0 ? null : [...sessionOwnerHints.values()].map(entry => [entry.id, entry.route]) + ) +} + +function rememberSessionOwnerHint(sessionId: string, route: SessionOwnerRoute): boolean { + const id = sessionId.trim() + const normalized = normalizeOwnerRoute(route) if (!id || !normalized.connectionId) { - return + return false } const key = sessionOwnerHintKey(id, normalized) @@ -697,9 +750,89 @@ export function setSessionOwnerHint(sessionId: string, route: SessionProfileRout sessionOwnerHints.delete(oldest) } + + return true } -export function getSessionOwnerHints(sessionId: string): SessionProfileRoute[] { +/** Load persisted hints (oldest first, so LRU order survives). Malformed or + * foreign-shaped entries are skipped; nothing here can throw. */ +export function hydrateSessionOwnerHints(): void { + const raw = readJson(SESSION_OWNER_HINTS_KEY) + + if (!Array.isArray(raw)) { + return + } + + for (const entry of raw) { + if (!Array.isArray(entry) || entry.length !== 2) { + continue + } + + const [id, route] = entry as [unknown, unknown] + + if ( + typeof id !== 'string' || + !route || + typeof route !== 'object' || + typeof (route as SessionOwnerRoute).connectionId !== 'string' || + typeof (route as SessionOwnerRoute).profile !== 'string' + ) { + continue + } + + const candidate = route as SessionOwnerRoute + + rememberSessionOwnerHint(id, { + connectionId: candidate.connectionId, + profile: candidate.profile, + ...(typeof candidate.targetProfile === 'string' ? { targetProfile: candidate.targetProfile } : {}), + ...(candidate.mode === 'local' || candidate.mode === 'remote' ? { mode: candidate.mode } : {}) + }) + } +} + +hydrateSessionOwnerHints() + +export function setSessionOwnerHint(sessionId: string, route: SessionOwnerRoute): void { + if (rememberSessionOwnerHint(sessionId, route)) { + persistSessionOwnerHints() + } +} + +/** Drop every hint naming `connectionId` — the registry no longer has it, so + * nothing can dial that route again (fail-closed would otherwise pin those + * sessions to a dead source forever). */ +export function forgetSessionOwnerHintsForConnection(connectionId: string): void { + const id = connectionId.trim() + + if (!id) { + return + } + + let changed = false + + for (const [key, entry] of [...sessionOwnerHints]) { + if (entry.route.connectionId === id) { + sessionOwnerHints.delete(key) + changed = true + } + } + + if (changed) { + persistSessionOwnerHints() + } +} + +/** @internal Tests: forget every in-memory hint (storage untouched unless asked). */ +export function _resetSessionOwnerHintsForTests({ storage = false }: { storage?: boolean } = {}): void { + sessionOwnerHints.clear() + + if (storage) { + writeJson(SESSION_OWNER_HINTS_KEY, null) + } +} + +export function getSessionOwnerHints(sessionId: string): SessionOwnerRoute[] { const id = sessionId.trim() return [...sessionOwnerHints.values()].filter(entry => entry.id === id).map(entry => ({ ...entry.route })) @@ -707,8 +840,8 @@ export function getSessionOwnerHints(sessionId: string): SessionProfileRoute[] { export function getSessionOwnerHint( sessionId: string, - scope?: Pick -): SessionProfileRoute | undefined { + scope?: Pick +): SessionOwnerRoute | undefined { const id = sessionId.trim() if (scope) { @@ -896,7 +1029,7 @@ export const setMessages = (next: Updater) => updateAtom($message export const setFreshDraftReady = (next: Updater) => updateAtom($freshDraftReady, next) export const setResumeFailedSessionId = (next: Updater) => updateAtom($resumeFailedSessionId, next) -export const requestSessionResume = (sessionId: string, ownerRoute?: SessionProfileRoute) => { +export const requestSessionResume = (sessionId: string, ownerRoute?: SessionOwnerRoute) => { const id = sessionId.trim() if (!id) { diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.ts index 9c1bf44937..cea46b004f 100644 --- a/apps/desktop/src/store/updates.test.ts +++ b/apps/desktop/src/store/updates.test.ts @@ -15,6 +15,23 @@ vi.mock('@/lib/storage', () => ({ storage.set(key, value) } }, + // store/session persists its exact owner hints through the JSON helpers. + readJson: (key: string) => { + const value = storage.get(key) + + try { + return value === undefined ? null : JSON.parse(value) + } catch { + return null + } + }, + writeJson: (key: string, value: unknown) => { + if (value === null) { + storage.delete(key) + } else { + storage.set(key, JSON.stringify(value)) + } + }, storedBoolean: (key: string, fallback: boolean) => { const value = storage.get(key)