Skip to content

The agent that grows with you

fix(desktop): route session branches through the parent's owning connection

Zeus-Deusc4bddd9a4e61
diff --git a/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts b/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts
new file mode 100644
index 00000000000..d4a8f0fb8ad
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/branch-owner-routing.integration.test.ts
@@ -0,0 +1,127 @@
+/**
+ * End-to-end owner routing for BRANCH (the #97764-adjacent strand).
+ *
+ * The unit tests in use-session-actions.test.tsx mock `@/store/gateway`, so
+ * they prove the branch path ASKS for the right route. They cannot prove the
+ * routing layer HONOURS it. This file mocks nothing inside the router: the real
+ * `requestGatewayForAgent` runs against a fake Electron bridge + transport, so
+ * a regression that re-collapses a registry route onto the ambient socket fails
+ * here even if the call-site assertions still pass.
+ *
+ * Reproduces the reported shape: a session owned by a remote connection
+ * ("pandora") is branched while a different backend is active. Before the fix
+ * the create rode the ambient socket and the child was created on the wrong
+ * backend (or nowhere), stranding an optimistic sidebar row on an id no backend
+ * owned — "Couldn't load this session".
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// Every socket the registry dials, and every RPC that travelled over one.
+const dialed: { connectionId: string; profile: string }[] = []
+const sent: { method: string; params: Record<string, unknown>; url: string }[] = []
+
+class FakeHermesGateway {
+ connectionState = 'closed'
+ private url = ''
+
+ async connect(wsUrl: string) {
+ if (typeof wsUrl !== 'string' || !wsUrl.startsWith('ws')) {
+ throw new Error(`bad ws url: ${String(wsUrl)}`)
+ }
+
+ this.url = wsUrl
+ this.connectionState = 'open'
+ }
+
+ async request<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
+ sent.push({ method, params, url: this.url })
+
+ if (method === 'session.create' || method === 'session.branch') {
+ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as T
+ }
+
+ return {} as T
+ }
+
+ close() {
+ this.connectionState = 'closed'
+ }
+
+ onEvent(_listener: (event: unknown) => void) {
+ return () => undefined
+ }
+
+ onState(_listener: (state: unknown) => void) {
+ return () => undefined
+ }
+
+ onStateChange(_listener: (state: unknown) => void) {
+ return () => undefined
+ }
+
+ on() {}
+ off() {}
+ addEventListener() {}
+ removeEventListener() {}
+}
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ HermesGateway: FakeHermesGateway,
+ setApiRequestConnection: vi.fn()
+}))
+
+describe('branch owner routing (real router, faked transport)', () => {
+ beforeEach(() => {
+ dialed.length = 0
+ sent.length = 0
+ vi.resetModules()
+
+ // A registry with two backends exposing the SAME profile name — the exact
+ // ambiguity that makes profile-only routing wrong.
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: async () => ({ mode: 'local' }),
+ getConnectionFor: async ({ connectionId, profile }: { connectionId: string; profile: string }) => {
+ dialed.push({ connectionId, profile })
+
+ return { connectionId, mode: 'remote', profile }
+ },
+ getGatewayWsUrlFor: async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
+ `ws://${connectionId}/gateway?profile=${profile}`,
+ touchBackend: async () => undefined
+ }
+ })
+
+ it('dials the parent connection and sends the create over that socket', async () => {
+ const { requestGatewayForAgent } = await import('@/store/gateway')
+
+ await requestGatewayForAgent('pandora', 'default', 'session.create', {
+ parent_session_id: 'stored-parent',
+ source: 'desktop'
+ })
+
+ // The registry resolved a socket for the PARENT's connection...
+ expect(dialed).toContainEqual({ connectionId: 'pandora', profile: 'default' })
+
+ // ...and the create actually travelled over that socket.
+ const create = sent.find(entry => entry.method === 'session.create')
+ expect(create).toBeDefined()
+ expect(create!.url).toContain('pandora')
+ expect(create!.params).toMatchObject({ parent_session_id: 'stored-parent' })
+ })
+
+ it('keeps two same-named profiles on separate sockets', async () => {
+ const { requestGatewayForAgent } = await import('@/store/gateway')
+
+ await requestGatewayForAgent('pandora', 'default', 'session.create', { source: 'desktop' })
+ await requestGatewayForAgent('other-box', 'default', 'session.create', { source: 'desktop' })
+
+ const urls = sent.filter(entry => entry.method === 'session.create').map(entry => entry.url)
+
+ expect(urls).toHaveLength(2)
+ // Same profile name, different backends — they must NOT share a socket.
+ expect(new Set(urls).size).toBe(2)
+ expect(urls.some(url => url.includes('pandora'))).toBe(true)
+ expect(urls.some(url => url.includes('other-box'))).toBe(true)
+ })
+})
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 7aaef72699a..bdf9ae8ecae 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
@@ -1802,6 +1802,122 @@ describe('branchStoredSession desktop source tagging', () => {
})
})
+ // A branch belongs to the backend that OWNS its parent. Routing on profile
+ // alone silently sends session.create to whatever socket is active, so a
+ // remote-owned parent branched while another connection is active creates
+ // the child on the wrong backend — or nowhere — while the sidebar still
+ // paints an optimistic row that can never hydrate ("Couldn't load this
+ // session"). Same ownership contract removeSession already honours.
+ it('routes a connection-tagged parent branch through its owning connection', async () => {
+ const ambientRequest = vi.fn(async () => ({}) as never)
+
+ vi.mocked(requestGatewayForAgent).mockImplementation((async (
+ _connectionId: null | string,
+ _profile: string,
+ method: string
+ ) => {
+ if (method === 'session.create') {
+ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as never
+ }
+
+ return {} as never
+ }) as never)
+
+ setSessions([
+ storedSession({ connection_id: 'pandora', id: 'stored-parent', message_count: 1, profile: 'default' })
+ ])
+ vi.mocked(getAllSessionMessages).mockResolvedValue({
+ messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],
+ session_id: 'stored-parent'
+ } as never)
+
+ let branchStoredSession: ((storedSessionId: string) => Promise<boolean>) | null = null
+ render(<BranchHarness onReady={branch => (branchStoredSession = branch)} requestGateway={ambientRequest} />)
+ await waitFor(() => expect(branchStoredSession).not.toBeNull())
+
+ await expect(branchStoredSession!('stored-parent')).resolves.toBe(true)
+
+ // The create must ride the parent's own (connection, profile) socket...
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'pandora',
+ 'default',
+ 'session.create',
+ expect.objectContaining({ parent_session_id: 'stored-parent', source: 'desktop' })
+ )
+ // ...and never the ambient socket, which may serve a different machine.
+ expect(ambientRequest).not.toHaveBeenCalledWith('session.create', expect.anything())
+ })
+
+ // The parent transcript read must land on the owning backend too: reading it
+ // from the ambient socket returns nothing for a foreign-owned parent, which
+ // aborts the branch as "nothing to branch" before any create is attempted.
+ it('reads a connection-tagged parent transcript from its owning connection', async () => {
+ const ambientRequest = vi.fn(async () => ({}) as never)
+
+ vi.mocked(requestGatewayForAgent).mockImplementation((async (
+ _connectionId: null | string,
+ _profile: string,
+ method: string
+ ) => {
+ if (method === 'session.create') {
+ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as never
+ }
+
+ return {} as never
+ }) as never)
+
+ setSessions([
+ storedSession({ connection_id: 'pandora', id: 'stored-parent', message_count: 1, profile: 'default' })
+ ])
+ vi.mocked(getAllSessionMessages).mockResolvedValue({
+ messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],
+ session_id: 'stored-parent'
+ } as never)
+
+ let branchStoredSession: ((storedSessionId: string) => Promise<boolean>) | null = null
+ render(<BranchHarness onReady={branch => (branchStoredSession = branch)} requestGateway={ambientRequest} />)
+ await waitFor(() => expect(branchStoredSession).not.toBeNull())
+
+ await expect(branchStoredSession!('stored-parent')).resolves.toBe(true)
+
+ expect(getAllSessionMessages).toHaveBeenCalledWith('stored-parent', {
+ connectionId: 'pandora',
+ profile: 'default'
+ })
+ })
+
+ // An untagged row (single-backend users, the overwhelmingly common case)
+ // must keep the ambient path exactly as before — no behaviour change.
+ it('keeps an untagged parent branch on the ambient socket', async () => {
+ let createParams: Record<string, unknown> | undefined
+
+ const ambientRequest = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'session.create') {
+ createParams = params
+
+ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as never
+ }
+
+ return {} as never
+ })
+
+ vi.mocked(requestGatewayForAgent).mockClear()
+ setSessions([storedSession({ id: 'stored-parent', message_count: 1 })])
+ vi.mocked(getAllSessionMessages).mockResolvedValue({
+ messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],
+ session_id: 'stored-parent'
+ } as never)
+
+ let branchStoredSession: ((storedSessionId: string) => Promise<boolean>) | null = null
+ render(<BranchHarness onReady={branch => (branchStoredSession = branch)} requestGateway={ambientRequest} />)
+ await waitFor(() => expect(branchStoredSession).not.toBeNull())
+
+ await expect(branchStoredSession!('stored-parent')).resolves.toBe(true)
+
+ expect(createParams).toMatchObject({ parent_session_id: 'stored-parent', source: 'desktop' })
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ })
+
it('branches an open live chat via session.branch with a trimmed message count (bug #1/#3 fix)', async () => {
let branchParams: Record<string, unknown> | undefined
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 df31c30c759..f659d4c0d65 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
@@ -101,6 +101,8 @@ import {
import { isSessionOwnerResolutionError } from '@/store/session-owner-resolution'
import {
requestForSessionProfile,
+ type SessionOwnerRoute,
+ sessionOwnerRouteFromRow,
type SessionOwnerScope,
type SessionProfileRoute
} from '@/store/session-request-router'
@@ -1954,27 +1956,48 @@ export function useSessionActions({
parentStoredId: null | string,
cwd?: string,
profile?: null | string,
- branchCount?: number
+ branchCount?: number,
+ ownerRoute?: SessionOwnerRoute
): Promise<boolean> => {
creatingSessionRef.current = true
try {
- // A branch belongs to its parent's OWNING profile. Swapping the live
- // gateway first AND passing `profile` on the create mirrors
- // desktopSessionCreateParams/resumeSession: in app-global remote mode
- // one backend serves every profile, so an omitted profile silently
- // lands the branch on the launch (default) profile — the "session
- // jumps between profiles after branching" bug. The swap also makes
- // upsertOptimisticSession's $activeGatewayProfile stamp correct.
- await ensureGatewayProfile(profile)
+ // A branch belongs to its parent's OWNING backend. Two facets, and both
+ // matter once more than one connection is configured:
+ //
+ // 1. PROFILE — passing `profile` on the create mirrors
+ // desktopSessionCreateParams/resumeSession: in app-global remote mode
+ // one backend serves every profile, so an omitted profile silently
+ // lands the branch on the launch (default) profile — the "session
+ // jumps between profiles after branching" bug.
+ // 2. CONNECTION — a profile name alone does not identify a backend when
+ // several connections expose the same name. Routing on profile only
+ // sends session.create to whatever socket happens to be active, so
+ // branching a remote-owned parent from another connection creates the
+ // child on the wrong backend (or nowhere), while the optimistic
+ // sidebar row below still points at an id no backend owns — the
+ // "Couldn't load this session" strand. removeSession already routes
+ // by (connection, profile); this is the same ownership contract.
+ //
+ // An untagged parent keeps the historic profile-only path exactly.
+ if (ownerRoute) {
+ await ensureGatewayAgent(ownerRoute.connectionId, ownerRoute.profile)
+ } else {
+ await ensureGatewayProfile(profile)
+ }
+
+ const requestBranchGateway = <T,>(method: string, params: Record<string, unknown>): Promise<T> =>
+ ownerRoute
+ ? requestGatewayForAgent<T>(ownerRoute.connectionId, ownerRoute.profile, method, params)
+ : requestGateway<T>(method, params)
// No title: the backend auto-names the branch from its parent's lineage.
const branched = sourceSessionId
- ? await requestGateway<SessionCreateResponse>('session.branch', {
+ ? await requestBranchGateway<SessionCreateResponse>('session.branch', {
session_id: sourceSessionId,
...(branchCount !== undefined ? { count: branchCount } : {})
})
- : await requestGateway<SessionCreateResponse>('session.create', {
+ : await requestBranchGateway<SessionCreateResponse>('session.create', {
cols: 96,
source: 'desktop',
...(cwd && { cwd }),
@@ -2094,9 +2117,17 @@ export function useSessionActions({
let authoritativeMessages: ChatMessage[] | null = null
const profile = await resolveSessionProfile(storedSessionId)
+ // The open chat's exact owner, when its row carries a connection tag.
+ // Same contract as branchStoredSession: the transcript read and the
+ // branch RPC must both land on the backend that owns the parent, not on
+ // whichever socket is active.
+ const ownerRoute = storedSessionId
+ ? sessionOwnerRouteFromRow($sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId)))
+ : undefined
+
if (storedSessionId) {
try {
- const persisted = await getAllSessionMessages(storedSessionId, profile)
+ const persisted = await getAllSessionMessages(storedSessionId, ownerRoute ?? profile)
const hydrated = toChatMessages(persisted.messages)
if (hydrated.length) {
@@ -2144,7 +2175,8 @@ export function useSessionActions({
storedSessionId,
startingCwd,
profile,
- messageId ? branchMessages.length : undefined
+ messageId ? branchMessages.length : undefined,
+ ownerRoute
)
},
[activeSessionIdRef, busyRef, copy, forkBranch, getRouteToken, selectedStoredSessionIdRef]
@@ -2166,9 +2198,22 @@ export function useSessionActions({
const profile = sessionProfile ?? stored?.profile
+ // An exact owner from the parent row — connection AND profile. Undefined
+ // for an untagged row, which keeps the ambient/profile-only path.
+ const ownerRoute = sessionOwnerRouteFromRow(stored)
+
try {
- await ensureGatewayProfile(profile)
- const { messages } = await getAllSessionMessages(storedSessionId, profile)
+ if (ownerRoute) {
+ await ensureGatewayAgent(ownerRoute.connectionId, ownerRoute.profile)
+ } else {
+ await ensureGatewayProfile(profile)
+ }
+
+ // Read the parent transcript from the backend that OWNS it. A bare
+ // profile scope resolves against the active connection, which for a
+ // foreign-owned parent holds no such session: the read comes back empty
+ // and the branch aborts as "nothing to branch" before any create.
+ const { messages } = await getAllSessionMessages(storedSessionId, ownerRoute ?? profile)
const branchMessages = toBranchMessages(toChatMessages(messages))
if (!branchMessages.length) {
@@ -2177,7 +2222,15 @@ export function useSessionActions({
return false
}
- return await forkBranch(branchMessages, null, stored?.id ?? storedSessionId, stored?.cwd?.trim(), profile)
+ return await forkBranch(
+ branchMessages,
+ null,
+ stored?.id ?? storedSessionId,
+ stored?.cwd?.trim(),
+ profile,
+ undefined,
+ ownerRoute
+ )
} catch (err) {
notifyError(err, copy.branchFailed)