Skip to content

The agent that grows with you

fix(desktop): preserve remote profile routing in peer windows

BearHuddleston84f41249aab6
diff --git a/apps/desktop/e2e/peer-device-reset.spec.ts b/apps/desktop/e2e/peer-device-reset.spec.ts
index f068eeff95e..70963841485 100644
--- a/apps/desktop/e2e/peer-device-reset.spec.ts
+++ b/apps/desktop/e2e/peer-device-reset.spec.ts
@@ -8,7 +8,7 @@ import * as fs from 'node:fs'
import * as net from 'node:net'
import * as path from 'node:path'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
+import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
import {
buildAppEnv,
@@ -25,6 +25,7 @@ const LOCAL_LABEL = 'This device'
const REMOTE_LABEL = 'E2E remote'
const REMOTE_ID = 'e2e-remote'
const REMOTE_TOKEN = 'e2e-peer-disposable-token'
+const REMOTE_PROFILE = 'ai-dev'
function pythonBinary(): string {
if (process.env.HERMES_DESKTOP_PYTHON) {
@@ -47,7 +48,7 @@ function isolatedEnv(sandbox: Sandbox): Record<string, string> {
const defaults = buildAppEnv(sandbox)
const env: Record<string, string> = {}
- for (const key of ['PATH', 'DISPLAY', 'XAUTHORITY', 'LANG', 'LC_ALL', 'SystemRoot', 'COMSPEC', 'PATHEXT']) {
+ for (const key of ['PATH', 'DISPLAY', 'XAUTHORITY', 'LANG', 'LC_ALL', 'SystemRoot', 'COMSPEC', 'PATHEXT', 'TMPDIR', 'TEMP', 'TMP']) {
if (defaults[key]) {
env[key] = defaults[key]
}
@@ -158,9 +159,12 @@ const peerTest = test.extend<{ gateways: { app: ElectronApplication; source: Pag
let desktopLog = ''
try {
- for (const sandbox of [local, remote]) {
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
+ const remoteProfileHome = path.join(remote.hermesHome, 'profiles', REMOTE_PROFILE)
+ fs.mkdirSync(remoteProfileHome, { recursive: true })
+
+ for (const hermesHome of [local.hermesHome, remote.hermesHome, remoteProfileHome]) {
+ writeMockProviderConfig(hermesHome, mock.url)
+ writeEnvFile(hermesHome)
}
const port = await freePort()
@@ -244,6 +248,33 @@ const peerTest = test.extend<{ gateways: { app: ElectronApplication; source: Pag
peerTest.setTimeout(240_000)
+peerTest('Ctrl+Shift+N resumes a remote-only profile on its owning gateway', async ({ gateways: { app, source } }) => {
+ const remoteProfile = source.locator(`[data-slot="profile-rail-gateway"][data-connection-id="${REMOTE_ID}"]`)
+ .getByRole('button', { name: `${REMOTE_PROFILE} · ${REMOTE_LABEL}`, exact: true })
+
+ await expect(remoteProfile).toBeVisible({ timeout: 60_000 })
+ await remoteProfile.click()
+ await expectReady(source, REMOTE_LABEL)
+ await composer(source).fill('Remember this remote profile session for the peer-window regression.')
+ await composer(source).press('Enter')
+ await expect(source.locator('[data-slot="aui_assistant-message-content"]').getByText(MOCK_REPLY, { exact: true })).toBeVisible({ timeout: 60_000 })
+
+ const opened = app.waitForEvent('window')
+ await source.keyboard.press(process.platform === 'darwin' ? 'Meta+Shift+N' : 'Control+Shift+N')
+ const peer = await opened
+ installErrorBannerGuard(peer)
+ await expectReady(peer, REMOTE_LABEL)
+ await expect(peer.locator('[data-slot="aui_assistant-message-content"]').getByText(MOCK_REPLY, { exact: true })).toBeVisible({ timeout: 60_000 })
+ await expectReady(source, REMOTE_LABEL)
+ await peer.reload()
+ await expectReady(peer, REMOTE_LABEL)
+ await expect(peer.locator('[data-slot="aui_assistant-message-content"]').getByText(MOCK_REPLY, { exact: true })).toBeVisible({ timeout: 60_000 })
+ await composer(peer).fill('Continue this session after reopening the peer window.')
+ await composer(peer).press('Enter')
+ await expect(peer.locator('[data-slot="aui_assistant-message-content"]').getByText(MOCK_REPLY, { exact: true })).toHaveCount(2, { timeout: 60_000 })
+ await expectReady(source, REMOTE_LABEL)
+})
+
peerTest('Ctrl+Shift+N peer keeps local → remote → local choices on New session', async ({ gateways: { app, source } }) => {
const sourceDraft = 'Keep this source-window draft'
await composer(source).fill(sourceDraft)
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 ed584ddb8b2..11d2ea69bbd 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
@@ -384,6 +384,38 @@ 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')
+
+ const desktop = {
+ ...fakeDesktop(),
+ getConnection: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
+ getConnectionFor: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
+ getGatewayWsUrlFor: vi.fn(async () => coderConn.wsUrl)
+ }
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+
+ 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)
+
+ 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)',
async connectionId => {
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 f80e841c912..38b0dc44596 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -5,8 +5,7 @@ import {
isStableOpen,
JSON_RPC_METHOD_NOT_FOUND,
JsonRpcGatewayError,
- reconnectBackoffDelayMs,
- resolveGatewayWsUrl
+ reconnectBackoffDelayMs
} from '@hermes/shared'
import { useEffect, useRef } from 'react'
@@ -20,6 +19,7 @@ import {
LIVENESS_PROBE_TIMEOUT_MS,
LIVENESS_REPROBE_DELAY_MS
} from '@/lib/gateway-liveness-policy'
+import { resolveDesktopGatewayWsUrl } from '@/lib/gateway-ws-url'
import { BACKEND_BOOT_WAIT_TIMEOUT_MS, RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'
import {
$desktopBoot,
@@ -432,7 +432,7 @@ export function useGatewayBoot({
// this reconnect loop. For local/token gateways the URL carries a
// long-lived token and the re-mint is a cheap no-op.
const wsUrl = await withTimeout(
- resolveGatewayWsUrl(desktop, conn),
+ resolveDesktopGatewayWsUrl(desktop, conn),
RECONNECT_ATTEMPT_TIMEOUT_MS,
'Timed out re-minting the gateway WebSocket URL'
)
@@ -756,7 +756,7 @@ export function useGatewayBoot({
// Bounded for the same reason as attemptReconnect() (#93454): a wedged
// ticket mint would otherwise hang the gateway switch forever.
const wsUrl = await withTimeout(
- resolveGatewayWsUrl(desktop, conn),
+ resolveDesktopGatewayWsUrl(desktop, conn),
RECONNECT_ATTEMPT_TIMEOUT_MS,
'Timed out re-minting the gateway WebSocket URL'
)
@@ -1338,7 +1338,7 @@ export function useGatewayBoot({
// await is bounded like the reconnect path (#93454) so a wedged mint
// reaches the recovery affordance instead of hanging "Starting Hermes…".
const wsUrl = await withTimeout(
- resolveGatewayWsUrl(desktop, conn),
+ resolveDesktopGatewayWsUrl(desktop, conn),
RECONNECT_ATTEMPT_TIMEOUT_MS,
'Timed out minting the gateway WebSocket URL'
)
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
index 5173a500149..32486daf495 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
@@ -353,12 +353,52 @@ describe('useGatewayRequest', () => {
await expect(result.current.requestGateway('session.resume')).resolves.toEqual({ recovered: true })
})
- expect(desktop.getConnection).toHaveBeenCalledWith('default')
+ expect(desktop.getConnection).toHaveBeenCalledWith()
expect(desktop.getGatewayWsUrl).toHaveBeenCalledWith('default')
expect(desktop.getConnectionFor).not.toHaveBeenCalled()
expect(desktop.getGatewayWsUrlFor).not.toHaveBeenCalled()
})
+ it.each(['token', 'oauth'] as const)(
+ 'keeps a registered peer primary on its owner during %s request recovery',
+ async authMode => {
+ const connection = { ...remoteConnection, authMode, registryScoped: true }
+
+ const desktop = {
+ ...installRemoteDesktop(),
+ getConnection: vi.fn(async (profile?: string | null) => {
+ if (profile !== undefined) {
+ throw new Error(`Profile '${profile}' does not exist locally`)
+ }
+
+ return connection
+ })
+ }
+
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: desktop })
+
+ const primary = makePrimaryGateway()
+ primary.request.mockRejectedValueOnce(new Error('connection closed')).mockResolvedValueOnce({ recovered: true })
+ setPrimaryGateway(primary as unknown as HermesGateway, connection.profile)
+ $gateway.set(primary as unknown as HermesGateway)
+ $activeGatewayProfile.set(connection.profile)
+ $gatewayState.set('closed')
+
+ const { result } = renderHook(() => useGatewayRequest())
+ await act(async () => {
+ await expect(result.current.requestGateway('session.resume')).resolves.toEqual({ recovered: true })
+ })
+
+ expect(desktop.getConnection).toHaveBeenCalledWith()
+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledWith({
+ connectionId: connection.connectionId,
+ profile: connection.profile
+ })
+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()
+ expect(primary.connect).toHaveBeenCalledWith(expect.stringContaining('wss://ssh-source.example.test/'))
+ }
+ )
+
it('rejects instead of hanging forever when the reconnect getConnection() wedges (#93454)', async () => {
// Repro: a request lands on a dropped socket, the "not connected" catch
// kicks off a reconnect, and the IPC round-trip into main
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
index e2da17bc347..cea023681be 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
@@ -1,11 +1,11 @@
-import { isGatewayReauthRequired, resolveGatewayWsUrl } from '@hermes/shared'
+import { isGatewayReauthRequired } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useCallback, useEffect, useRef } from 'react'
import type { HermesGateway } from '@/hermes'
+import { resolveDesktopGatewayWsUrl } from '@/lib/gateway-ws-url'
import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'
import { $gateway, ensureActiveGatewayOpen, isActivePrimary } from '@/store/gateway'
-import { $activeGatewayProfile } from '@/store/profile'
import { $gatewayState, setConnection } from '@/store/session'
export function useGatewayRequest() {
@@ -71,16 +71,17 @@ export function useGatewayRequest() {
reauthErrorRef.current = null
try {
- // Reconnect to whichever profile the gateway is currently routed to (not
- // always the primary), so a sleep/wake reconnect keeps the user on the
- // profile they were chatting in. Both awaits below are IPC round-trips
+ // This recovery path serves the window primary; secondaries reconnect
+ // through the registry below. Omit the profile so main resolves the
+ // sender's full route, not a remote profile name in the local pool.
+ // Both awaits below are IPC round-trips
// into the main process with no timeout of their own (#93454) — a
// wedged main-process round-trip otherwise hangs this await forever,
// latching reconnectingRef.current so every later requestGateway() call
// returns the same never-settling promise. Bound the same way
// use-gateway-boot.ts bounds the primary boot/soft-switch equivalents.
const conn = await withTimeout(
- desktop.getConnection($activeGatewayProfile.get()),
+ desktop.getConnection(),
RECONNECT_ATTEMPT_TIMEOUT_MS,
'Timed out reconnecting to Hermes backend'
)
@@ -95,7 +96,7 @@ export function useGatewayRequest() {
// retryable. Stash only the former so requestGateway can show the
// actionable "sign in again" message.
const wsUrl = await withTimeout(
- resolveGatewayWsUrl(desktop, conn),
+ resolveDesktopGatewayWsUrl(desktop, conn),
RECONNECT_ATTEMPT_TIMEOUT_MS,
'Timed out re-minting the gateway WebSocket URL'
)
diff --git a/apps/desktop/src/lib/gateway-ws-url.test.ts b/apps/desktop/src/lib/gateway-ws-url.test.ts
index 48c7c7416d9..566573a0768 100644
--- a/apps/desktop/src/lib/gateway-ws-url.test.ts
+++ b/apps/desktop/src/lib/gateway-ws-url.test.ts
@@ -1,9 +1,54 @@
import { GatewayReauthRequiredError, isGatewayReauthRequired, resolveGatewayWsUrl } from '@hermes/shared'
import { describe, expect, it, vi } from 'vitest'
+import type { HermesConnection } from '@/global'
+
+import { resolveDesktopGatewayWsUrl } from './gateway-ws-url'
+
const oauthConn = { authMode: 'oauth' as const, wsUrl: 'ws://host/api/ws?ticket=stale' }
const tokenConn = { authMode: 'token' as const, wsUrl: 'ws://host/api/ws?token=abc' }
+describe('desktop connection scope', () => {
+ it.each(['token', 'oauth'] as const)(
+ 'preserves legacy aliases and never falls back to legacy minting for a registered %s route',
+ async authMode => {
+ const connection = {
+ authMode,
+ connectionId: 'remote-device',
+ profile: 'client-alias',
+ wsUrl: 'wss://remote.invalid/api/ws?token=cached'
+ } as HermesConnection
+
+ const desktop = {
+ getGatewayWsUrl: vi.fn(async () => 'wss://legacy.invalid/api/ws?token=fresh'),
+ getGatewayWsUrlFor: vi.fn(async () => 'wss://remote.invalid/api/ws?ticket=fresh')
+ } as unknown as Window['hermesDesktop']
+
+ await expect(resolveDesktopGatewayWsUrl(desktop, connection)).resolves.toContain('legacy.invalid')
+ expect(desktop.getGatewayWsUrl).toHaveBeenCalledWith('client-alias')
+ expect(desktop.getGatewayWsUrlFor).not.toHaveBeenCalled()
+ vi.mocked(desktop.getGatewayWsUrl!).mockClear()
+
+ const registered = { ...connection, profile: 'remote-profile', registryScoped: true }
+ await expect(resolveDesktopGatewayWsUrl(desktop, registered)).resolves.toContain('remote.invalid')
+ expect(desktop.getGatewayWsUrlFor).toHaveBeenCalledWith({
+ connectionId: 'remote-device',
+ profile: 'remote-profile'
+ })
+
+ delete desktop.getGatewayWsUrlFor
+
+ if (authMode === 'oauth') {
+ await expect(resolveDesktopGatewayWsUrl(desktop, registered)).rejects.toThrow('cannot refresh OAuth')
+ } else {
+ await expect(resolveDesktopGatewayWsUrl(desktop, registered)).resolves.toBe(registered.wsUrl)
+ }
+
+ expect(desktop.getGatewayWsUrl).not.toHaveBeenCalled()
+ }
+ )
+})
+
describe('resolveGatewayWsUrl', () => {
describe('oauth mode', () => {
it('uses the freshly minted URL', async () => {
diff --git a/apps/desktop/src/lib/gateway-ws-url.ts b/apps/desktop/src/lib/gateway-ws-url.ts
new file mode 100644
index 00000000000..bb21f0ea380
--- /dev/null
+++ b/apps/desktop/src/lib/gateway-ws-url.ts
@@ -0,0 +1,20 @@
+import { resolveGatewayWsUrl } from '@hermes/shared'
+
+import type { HermesConnection } from '@/global'
+
+export function resolveDesktopGatewayWsUrl(
+ desktop: Window['hermesDesktop'],
+ connection: HermesConnection
+): Promise<string> {
+ // An inferred connectionId can still carry a legacy profile alias. Only an
+ // explicitly registry-scoped descriptor is safe to send to the *For bridge.
+ const { connectionId, profile, registryScoped } = connection
+
+ if (!registryScoped || !connectionId) {
+ return resolveGatewayWsUrl(desktop, connection)
+ }
+
+ const mint = desktop.getGatewayWsUrlFor
+
+ return resolveGatewayWsUrl({ getGatewayWsUrl: mint ? () => mint({ connectionId, profile }) : undefined }, connection)
+}