Skip to content

The agent that grows with you

fix: preserve connectionId for secondary chat windows (Fixes #120213)

itsflownium25bc086d3f80
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index a1422c3b7d2..f5eb877b78b 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -13601,10 +13601,11 @@ function focusWindow(win) {
}
function spawnSecondaryWindow({
+ connectionId,
sessionId,
profile,
watch
-}: { sessionId?: string; profile?: null | string; watch?: boolean } = {}) {
+}: { connectionId?: null | string; sessionId?: string; profile?: null | string; watch?: boolean } = {}) {
const icon = getAppIconPath()
const win = new BrowserWindow({
@@ -13673,6 +13674,7 @@ function spawnSecondaryWindow({
loadWindowUrl(
win,
buildSessionWindowUrl(sessionId, {
+ connectionId,
devServer: DEV_SERVER,
profile,
rendererIndexPath: DEV_SERVER ? undefined : resolveRendererIndex(),
@@ -13685,8 +13687,9 @@ function spawnSecondaryWindow({
}
// Open (or focus) a standalone window for a single chat session.
-function createSessionWindow(sessionId, { profile = null, watch = false } = {}) {
- return sessionWindows.openOrFocus(sessionId, () => spawnSecondaryWindow({ sessionId, profile, watch }))
+function createSessionWindow(sessionId, { connectionId = null, profile = null, watch = false } = {}) {
+ const key = JSON.stringify([connectionId, profile, sessionId])
+ return sessionWindows.openOrFocus(key, () => spawnSecondaryWindow({ connectionId, sessionId, profile, watch }))
}
// Popped-out in-app Browser: same webview + address bar as a docked Browser
@@ -15469,6 +15472,7 @@ ipcMain.handle('hermes:window:openSession', async (_event, sessionId, opts) => {
}
createSessionWindow(sessionId.trim(), {
+ connectionId: typeof opts?.connectionId === 'string' ? opts.connectionId : null,
profile: typeof opts?.profile === 'string' ? opts.profile : null,
watch: opts?.watch === true
})
diff --git a/apps/desktop/electron/session-windows.test.ts b/apps/desktop/electron/session-windows.test.ts
index 9c673864986..cf890c44dbe 100644
--- a/apps/desktop/electron/session-windows.test.ts
+++ b/apps/desktop/electron/session-windows.test.ts
@@ -281,3 +281,23 @@ test('chatWindowWebPreferences allows autoplay so wake-started voice speaks its
assert.equal(prefs.autoplayPolicy, 'no-user-gesture-required')
})
+
+test('secondary URLs preserve exact local and remote routes in packaged and development windows', () => {
+ for (const connectionId of [null, 'remote/a']) {
+ for (const devServer of [undefined, 'http://localhost:5174']) {
+ const url = new URL(
+ buildSessionWindowUrl('child', {
+ connectionId,
+ profile: 'research',
+ watch: true,
+ devServer,
+ rendererIndexPath: '/tmp/hermes/index.html'
+ })
+ )
+ assert.equal(url.searchParams.get('connectionId'), connectionId ?? '')
+ assert.equal(url.searchParams.get('profile'), 'research')
+ assert.equal(url.searchParams.get('watch'), '1')
+ assert.equal(url.hash, '#/child')
+ }
+ }
+})
diff --git a/apps/desktop/electron/session-windows.ts b/apps/desktop/electron/session-windows.ts
index 877297f248d..36b6aabe250 100644
--- a/apps/desktop/electron/session-windows.ts
+++ b/apps/desktop/electron/session-windows.ts
@@ -71,9 +71,12 @@ function chatWindowWebPreferences(preloadPath: string) {
// HUD's buildHudWindowUrl): without it a pop-out/watch window adopts the
// PRIMARY profile and resolves the session id against the wrong backend
// (#82768, #61286). Absent → unchanged primary adoption.
-function buildSessionWindowUrl(sessionId: string, { devServer, profile, rendererIndexPath, watch }: any = {}) {
+function buildSessionWindowUrl(
+ sessionId: string,
+ { connectionId, devServer, profile, rendererIndexPath, watch }: any = {}
+) {
const profileKey = typeof profile === 'string' ? profile.trim() : ''
- const query = `?win=secondary${watch ? '&watch=1' : ''}${profileKey ? `&profile=${encodeURIComponent(profileKey)}` : ''}`
+ const query = `?win=secondary${watch ? '&watch=1' : ''}${profileKey ? `&profile=${encodeURIComponent(profileKey)}` : ''}${connectionId !== undefined ? `&connectionId=${encodeURIComponent(connectionId ?? '')}` : ''}`
const route = `#/${encodeURIComponent(sessionId)}`
if (devServer) {
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
index 05a8dfcb7cc..d994c687b62 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
@@ -200,7 +200,9 @@ export function ComposerStatusStack({ onSubmit, queue, sessionId }: ComposerStat
const openAgents = () => navigate(AGENTS_ROUTE)
const openSubagent = (item: ComposerStatusItem) =>
- item.sessionId ? void openSessionInNewWindow(item.sessionId, { watch: true }) : openAgents()
+ item.sessionId
+ ? void openSessionInNewWindow(item.sessionId, { watch: true, parentSessionId: storedSessionId ?? sessionId })
+ : openAgents()
const previewRows =
visiblePreviews.length > 0 && sessionId
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
index f1498665b6a..e26404ebeb7 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
@@ -456,37 +456,40 @@ async function advanceBackoff() {
}
describe('default-route profile adoption', () => {
- it('keeps a peer primary on its registered gateway across boot, reconnect and soft switch', async () => {
- const originalUrl = window.location.href
- window.history.replaceState(null, '', '/?peer=1&profile=coder&connectionId=coder-remote')
+ it.each(['peer=1', 'win=secondary&watch=1'])(
+ 'keeps %s on its registered gateway across boot, reconnect and soft switch',
+ async marker => {
+ const originalUrl = window.location.href
+ window.history.replaceState(null, '', `/?${marker}&profile=coder&connectionId=coder-remote`)
- const desktop = {
- ...fakeDesktop(),
- getConnection: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
- getConnectionFor: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
- getGatewayWsUrlFor: vi.fn(async () => coderConn.wsUrl)
- }
+ const desktop = {
+ ...fakeDesktop(),
+ getConnection: vi.fn(async profile => (profile ? primaryConn : { ...coderConn, registryScoped: true })),
+ getConnectionFor: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
+ getGatewayWsUrlFor: vi.fn(async () => coderConn.wsUrl)
+ }
- ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
- try {
- render(<Harness />)
- await flushAsync()
- expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
+ try {
+ render(<Harness />)
+ await flushAsync()
+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
- FakeWebSocket.instances.at(-1)!.drop()
- await advanceBackoff()
- expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
+ FakeWebSocket.instances.at(-1)!.drop()
+ await advanceBackoff()
+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
- act(() => connectionApplied?.())
- await flushAsync()
- expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
- expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledWith({ connectionId: 'coder-remote', profile: 'coder' })
- expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()
- } finally {
- window.history.replaceState(null, '', originalUrl)
+ act(() => connectionApplied?.())
+ await flushAsync()
+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(coderConn.wsUrl)
+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledWith({ connectionId: 'coder-remote', profile: 'coder' })
+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()
+ } finally {
+ window.history.replaceState(null, '', originalUrl)
+ }
}
- })
+ )
it.each([null, 'coder-remote'])(
'dials the saved startup route before an ambient sender can replace it (%s)',
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 9168fefee09..1bfa972fb1c 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -691,7 +691,7 @@ export function useGatewayBoot({
const peer = isPeerInstanceWindow()
const route = profile
- ? { profile, connectionId: peer ? new URLSearchParams(window.location.search).get('connectionId') : null }
+ ? { profile, connectionId: new URLSearchParams(window.location.search).get('connectionId') }
: startup && !peer
? await desktop.profile?.getDefault?.()
: null
diff --git a/apps/desktop/src/components/assistant-ui/tool/delegate.tsx b/apps/desktop/src/components/assistant-ui/tool/delegate.tsx
index 363127d126f..6d585c975ac 100644
--- a/apps/desktop/src/components/assistant-ui/tool/delegate.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/delegate.tsx
@@ -65,6 +65,7 @@ function statusGlyph(status: DelegateRowStatus, label: string): ReactNode {
* whatever they get up to.
*/
function DelegateRowView({ row }: { row: DelegateRow }) {
+ const parentSessionId = useStore(useSessionView().$storedId)
const { t } = useI18n()
const copy = t.assistant.tool
const { sessionId } = row
@@ -84,7 +85,7 @@ function DelegateRowView({ row }: { row: DelegateRow }) {
].filter(Boolean)
// Only a child that reported its own session id has somewhere to go.
- const open = sessionId ? () => void openSessionInNewWindow(sessionId, { watch: true }) : undefined
+ const open = sessionId ? () => void openSessionInNewWindow(sessionId, { watch: true, parentSessionId }) : undefined
// The scaffold mark goes on the goal row, NEVER on this wrapper: it fades to
// 0.67, and opacity opens a stacking context around the ticker's transformed
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 5f2b5d0d47e..661a1995a17 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -78,7 +78,7 @@ declare global {
// a running subagent's session.
openSessionWindow: (
sessionId: string,
- opts?: { profile?: null | string; watch?: boolean }
+ opts?: { connectionId?: null | string; profile?: null | string; watch?: boolean }
) => Promise<{ ok: boolean; error?: string }>
// Resume this session in the user's own terminal emulator (`hermes --tui
// --resume <id>`) — the external terminal, not the in-app pane.
diff --git a/apps/desktop/src/store/windows.test.ts b/apps/desktop/src/store/windows.test.ts
index add77a363b5..97844e5f90b 100644
--- a/apps/desktop/src/store/windows.test.ts
+++ b/apps/desktop/src/store/windows.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { $activeGatewayProfile } from './profile'
-import { $sessions } from './session'
+import { $sessions, setSessionOwnerHint } from './session'
import {
isPeerInstanceWindow,
isProfilePinnedWindow,
@@ -62,6 +62,23 @@ describe('isProfilePinnedWindow', () => {
})
describe('openSessionInNewWindow', () => {
+ it('carries an exact session or parent route through the window bridge independently of the foreground', async () => {
+ const open = vi.fn().mockResolvedValue({ ok: true })
+ installBridge(open)
+ $activeGatewayProfile.set('unrelated')
+ $sessions.set([{ id: 'remote-session', profile: 'writer', connection_id: 'remote-a' } as never])
+ setSessionOwnerHint('parent-session', { connectionId: 'remote-b', profile: 'research' })
+
+ await openSessionInNewWindow('remote-session')
+ await openSessionInNewWindow('unlisted-child', { watch: true, parentSessionId: 'parent-session' })
+ await openSessionInNewWindow('remote-session')
+
+ expect(open.mock.calls).toEqual([
+ ['remote-session', { connectionId: 'remote-a', profile: 'writer', watch: undefined }],
+ ['unlisted-child', { connectionId: 'remote-b', profile: 'research', watch: true }],
+ ['remote-session', { connectionId: 'remote-a', profile: 'writer', watch: undefined }]
+ ])
+ }, 60_000)
it('no-ops without a session id', async () => {
const open = vi.fn().mockResolvedValue({ ok: true })
installBridge(open)
@@ -87,10 +104,10 @@ describe('openSessionInNewWindow', () => {
$sessions.set([{ id: 's1', profile: 'research' } as never])
await openSessionInNewWindow('s1')
- await openSessionInNewWindow('child-not-listed-yet', { watch: true })
+ await openSessionInNewWindow('child-not-listed-yet', { watch: true, parentSessionId: 's1' })
- expect(open).toHaveBeenCalledWith('s1', { profile: 'research' })
- expect(open).toHaveBeenCalledWith('child-not-listed-yet', { profile: 'work', watch: true })
+ expect(open).toHaveBeenCalledWith('s1', { profile: 'research', connectionId: null })
+ expect(open).toHaveBeenCalledWith('child-not-listed-yet', { profile: 'research', connectionId: null, watch: true })
expect(notifyError).not.toHaveBeenCalled()
})
diff --git a/apps/desktop/src/store/windows.ts b/apps/desktop/src/store/windows.ts
index 271e28c93cb..322a2d70fda 100644
--- a/apps/desktop/src/store/windows.ts
+++ b/apps/desktop/src/store/windows.ts
@@ -212,29 +212,44 @@ async function runWindowOpen(call: () => Promise<WindowOpenResult>, failMessage:
// Open (or focus) a standalone OS window for a single chat session. No-ops
// gracefully outside Electron so callers can wire it unconditionally.
// `watch: true` opens a spectator window (lazy resume, live-mirror stream).
-// The window is a full renderer that adopts the PRIMARY profile unless told
-// otherwise, so the owning profile rides along (same ladder as openHud,
-// #82285): the session's stamped owner wins, and an unstamped/uncached id —
-// a brand-new subagent child — inherits the profile the user is looking at
-// (#82768, #61286).
-export async function openSessionInNewWindow(sessionId: string, opts?: { watch?: boolean }): Promise<void> {
+// Carry the exact owner route into the new renderer. Unlisted children use
+// their parent surface to resolve the same backend.
+export async function openSessionInNewWindow(
+ sessionId: string,
+ opts?: { watch?: boolean; parentSessionId?: null | string }
+): Promise<void> {
if (!sessionId || !canOpenSessionWindow()) {
return
}
// Lazy imports: `./profile` subscribes to the API client on load, so a
// static import here would drag it into every page that opens windows.
- const [{ $activeGatewayProfile, normalizeProfileKey }, { $sessions, rememberedSessionProfile }] = await Promise.all([
+ const [
+ { $activeGatewayProfile, normalizeProfileKey },
+ { resolveSessionOwner },
+ { assertSessionOwnerResolved },
+ { isSessionOwnerRoute }
+ ] = await Promise.all([
import('./profile'),
- import('./session')
+ import('@/app/session/hooks/use-session-actions/utils'),
+ import('./session-owner-resolution'),
+ import('./session-request-router')
])
- const profile = normalizeProfileKey(rememberedSessionProfile($sessions.get(), sessionId, $activeGatewayProfile.get()))
+ await runWindowOpen(async () => {
+ // Unlisted children live on the same backend as the parent surface.
+ const routingId = opts?.parentSessionId || sessionId
+ const owner = await resolveSessionOwner(routingId)
+ assertSessionOwnerResolved(owner, { method: 'openSessionWindow', sessionId: routingId })
- await runWindowOpen(
- () => window.hermesDesktop.openSessionWindow(sessionId, { ...opts, profile }),
- 'Could not open chat in a new window'
- )
+ const profile = normalizeProfileKey(
+ isSessionOwnerRoute(owner) ? owner.profile : (owner ?? $activeGatewayProfile.get())
+ )
+
+ const connectionId = isSessionOwnerRoute(owner) ? owner.connectionId : null
+
+ return window.hermesDesktop.openSessionWindow(sessionId, { watch: opts?.watch, profile, connectionId })
+ }, 'Could not open chat in a new window')
}
// Open a new full-chrome app window — a peer instance of the primary that