The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): isolate SSH routing by window
Mabolla7944ad2168a8
diff --git a/apps/desktop/electron/connection-apply.ts b/apps/desktop/electron/connection-apply.tsindex 579af1a79e9..04de2bdc7ae 100644--- a/apps/desktop/electron/connection-apply.ts+++ b/apps/desktop/electron/connection-apply.ts@@ -54,4 +54,17 @@ async function resolveTerminalConnection(getTarget, ensureBackend) {return target}-export { applyConnectionChange, commitConnectionFailure, resolveTerminalConnection }+async function resolveTerminalConnectionForSender(webContentsId, getTarget, ensureBackend) {+ return resolveTerminalConnection(+ () => getTarget(webContentsId),+ () => ensureBackend(webContentsId)+ )+}+++export {+ applyConnectionChange,+ commitConnectionFailure,+ resolveTerminalConnection,+ resolveTerminalConnectionForSender+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 949096457eb..8a3cb1bff49 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -312,6 +312,10 @@ import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'import { createStreamThrottle } from './stream-throttle'import { registerTerminalIpc } from './terminal-ipc'+import {+ registrySshScopeForWindowRoute,+ WindowConnectionRouteRegistry+} from './window-connection-route'import { nativeOverlayWidth as computeNativeOverlayWidth, macTitleBarOverlayHeight } from './titlebar-overlay-width'import {backgroundMaterialFor,@@ -9517,8 +9521,26 @@ async function teardownSshConnection(profile) {// any cached SSH state. A per-profile token/OAuth override wins over a global// SSH connection — so if the active profile resolves to a NON-SSH backend, the// terminal must NOT fall through to a global SSH host.-function activeSshTerminalTarget() {- const profile = primaryProfileKey()+function activeSshTerminalTarget(webContentsId?: number) {+ const windowRoute =+ typeof webContentsId === 'number' ? windowConnectionRoutes.get(webContentsId) : null++ if (windowRoute?.registryScoped && windowRoute.connectionId) {+ const scope = registrySshScopeForWindowRoute(+ windowRoute,+ readDesktopConnectionsRegistry()+ )++ if (!scope) {+ return null+ }++ const state = sshConnections.get(scope)++ return state && state.ssh ? { ssh: state.ssh, scope } : 'pending'+ }++ const profile = windowRoute?.profile ?? primaryProfileKey()const config = readDesktopConnectionConfig()const route = resolveDesktopRemoteRoute({config,@@ -9542,15 +9564,41 @@ function activeSshTerminalTarget() {return state && state.ssh ? { ssh: state.ssh, scope } : 'pending'}+async function ensureTerminalBackend(webContentsId: number) {+ const windowRoute = windowConnectionRoutes.get(webContentsId)++ if (windowRoute?.registryScoped && windowRoute.connectionId) {+ return ensureRegistryBackend(windowRoute.connectionId, windowRoute.profile)+ }++ return ensureBackend(windowRoute?.profile ?? primaryProfileKey())+}+// Loopback reach for the browser pane. Scoped to the SSH connection that// authorized it: a different host (or none) must never inherit live forwards// into somebody else's machine.-const previewReach = new PreviewReachRegistry()-let previewReachScope: null | string = null+const previewReachByWebContents = new Map<+ number,+ { registry: PreviewReachRegistry; scope: string }+>()++async function resetPreviewReach(webContentsId?: number) {+ if (typeof webContentsId === 'number') {+ const current = previewReachByWebContents.get(webContentsId)-async function resetPreviewReach() {- previewReachScope = null- await previewReach.closeAll()+ previewReachByWebContents.delete(webContentsId)++ if (current) {+ await current.registry.closeAll()+ }++ return+ }++ const open = [...previewReachByWebContents.values()]++ previewReachByWebContents.clear()+ await Promise.allSettled(open.map(entry => entry.registry.closeAll()))}/**@@ -9561,25 +9609,33 @@ async function resetPreviewReach() {* remote with no tunnel to borrow. Callers must not treat an unchanged URL as* failure; the pane explains an unreachable one on its own.*/-async function reachablePreviewUrl(rawUrl: string): Promise<string> {- const target = activeSshTerminalTarget()+async function reachablePreviewUrl(webContentsId: number, rawUrl: string): Promise<string> {+ let target = activeSshTerminalTarget(webContentsId)++ if (target === 'pending') {+ await ensureTerminalBackend(webContentsId).catch(() => undefined)+ target = activeSshTerminalTarget(webContentsId)+ }if (!target || target === 'pending') {- // No SSH transport behind this gateway; nothing to forward through.- await resetPreviewReach()+ // No SSH transport behind this renderer's gateway. Another window's+ // forward must never be reused for this preview.+ await resetPreviewReach(webContentsId)return rawUrl}const { scope, ssh } = target as { scope: string; ssh: any }+ let reach = previewReachByWebContents.get(webContentsId)- if (previewReachScope !== scope) {- await resetPreviewReach()- previewReachScope = scope+ if (!reach || reach.scope !== scope) {+ await resetPreviewReach(webContentsId)+ reach = { registry: new PreviewReachRegistry(), scope }+ previewReachByWebContents.set(webContentsId, reach)}try {- const rewritten = await previewReach.resolve(rawUrl, {+ const rewritten = await reach.registry.resolve(rawUrl, {cancel: (localPort, remotePort) => ssh.cancelForward(localPort, remotePort),forward: (localPort, remotePort, remoteHost) => ssh.forward(localPort, remotePort, remoteHost),isCurrent: () => sshConnections.get(scope)?.ssh === ssh,@@ -9589,8 +9645,6 @@ async function reachablePreviewUrl(rawUrl: string): Promise<string> {return rewritten || rawUrl} catch (error: any) {- // A failed forward is a preview problem, not a session problem: log it and- // let the original URL through so the pane shows its own explanation.sshRememberLog(`preview reach failed for ${rawUrl}: ${error?.message || error}`)return rawUrl@@ -12884,6 +12938,32 @@ ipcMain.handle('hermes:connection:for', async (_event, payload) => {return { ...connection, connectionId: id, registryScoped: true }})++const windowConnectionRoutes = new WindowConnectionRouteRegistry()+const windowConnectionRouteOwners = new Set<number>()++ipcMain.on('hermes:connection:active-route', (event, route) => {+ const id = event.sender.id+ const previous = windowConnectionRoutes.get(id)+ const next = windowConnectionRoutes.set(id, route)++ if (+ previous?.connectionId !== next?.connectionId ||+ previous?.profile !== next?.profile ||+ previous?.registryScoped !== next?.registryScoped+ ) {+ void resetPreviewReach(id)+ }++ if (!windowConnectionRouteOwners.has(id)) {+ windowConnectionRouteOwners.add(id)+ event.sender.once('destroyed', () => {+ windowConnectionRoutes.delete(id)+ windowConnectionRouteOwners.delete(id)+ void resetPreviewReach(id)+ })+ }+})// Reconnect-after-wake recovery. A REMOTE primary backend has no child process,// so the 'exit'/'error' handlers that would clear a dead connection promise never// fire — once the remote becomes unreachable across a sleep/wake the renderer@@ -15218,7 +15298,9 @@ ipcMain.handle('hermes:stop-find-in-page', event => {// The renderer can't know whether a loopback URL is reachable — only main// knows which transport backs this gateway. Ask before loading one.-ipcMain.handle('hermes:preview:reach', async (_event, url) => reachablePreviewUrl(String(url || '')))+ipcMain.handle('hermes:preview:reach', async (event, url) =>+ reachablePreviewUrl(event.sender.id, String(url || ''))+)ipcMain.handle('hermes:openPreviewInBrowser', async (_event, url) => {if (!(await openPreviewInBrowser(url))) {@@ -15320,7 +15402,7 @@ const terminalIpc = registerTerminalIpc({findOnPath,rememberLog,activeSshTerminalTarget,- ensureBackend: () => ensureBackend(primaryProfileKey()),+ ensureBackend: webContentsId => ensureTerminalBackend(webContentsId),getSshConnectionState: scope => sshConnections.get(scope)})diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex f406f67cdfc..402588bc137 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -267,6 +267,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {openExternal: url => ipcRenderer.invoke('hermes:openExternal', url),openPreviewInBrowser: url => ipcRenderer.invoke('hermes:openPreviewInBrowser', url),reachPreviewUrl: url => ipcRenderer.invoke('hermes:preview:reach', url),+ setActiveConnectionRoute: route => ipcRenderer.send('hermes:connection:active-route', route),fetchLinkTitle: url => ipcRenderer.invoke('hermes:fetchLinkTitle', url),resolveFavicon: url => ipcRenderer.invoke('hermes:resolveFavicon', url),sanitizeWorkspaceCwd: cwd => ipcRenderer.invoke('hermes:workspace:sanitize', cwd),diff --git a/apps/desktop/electron/terminal-ipc.test.ts b/apps/desktop/electron/terminal-ipc.test.tsindex 75fb7e5dd8f..6b80d9ae068 100644--- a/apps/desktop/electron/terminal-ipc.test.ts+++ b/apps/desktop/electron/terminal-ipc.test.ts@@ -2,7 +2,10 @@ import assert from 'node:assert/strict'import { test } from 'vitest'-import { resolveTerminalConnection } from './connection-apply'+import {+ resolveTerminalConnection,+ resolveTerminalConnectionForSender+} from './connection-apply'const ssh = {host: 'registry-box.test',@@ -58,3 +61,19 @@ test('terminal start re-reads the SSH target after backend startup', async () =>assert.equal(resolved, target)assert.equal(resolved?.scope, 'connection:registry-ssh')})++test('keeps terminal routing isolated by renderer sender id', async () => {+ const targets = new Map([+ [11, { ssh, scope: 'conn:source-b::worker' }],+ [22, null]+ ])++ const getTarget = (webContentsId: number) => targets.get(webContentsId) ?? null+ const ensureBackend = async (_webContentsId: number) => undefined++ const windowB = await resolveTerminalConnectionForSender(11, getTarget, ensureBackend)+ const windowC = await resolveTerminalConnectionForSender(22, getTarget, ensureBackend)++ assert.equal(windowB?.scope, 'conn:source-b::worker')+ assert.equal(windowC, null)+})diff --git a/apps/desktop/electron/terminal-ipc.ts b/apps/desktop/electron/terminal-ipc.tsindex 1b5953b859d..6cf91cfd089 100644--- a/apps/desktop/electron/terminal-ipc.ts+++ b/apps/desktop/electron/terminal-ipc.ts@@ -10,7 +10,7 @@ import path from 'node:path'import { app, ipcMain } from 'electron'import nodePty from 'node-pty'-import { resolveTerminalConnection } from './connection-apply'+import { resolveTerminalConnectionForSender } from './connection-apply'import { ensureSpawnHelperExecutable } from './spawn-helper-perms'import { buildInteractiveSshArgs } from './ssh-connection'import { buildWindowsInteractiveCommand } from './windows-remote-lifecycle'@@ -19,8 +19,8 @@ export interface TerminalIpcDeps {isWindows: booleanfindOnPath: (command: string) => null | stringrememberLog: (line: string) => void- activeSshTerminalTarget: () => unknown- ensureBackend: () => Promise<unknown>+ activeSshTerminalTarget: (webContentsId: number) => unknown+ ensureBackend: (webContentsId: number) => Promise<unknown>getSshConnectionState: (scope: string) => undefined | { remotePlatform?: string }}@@ -292,7 +292,11 @@ export function registerTerminalIpc({const cols = Math.max(2, Number.parseInt(String(payload?.cols || 80), 10) || 80)const rows = Math.max(2, Number.parseInt(String(payload?.rows || 24), 10) || 24)- const sshTarget = await resolveTerminalConnection(activeSshTerminalTarget, ensureBackend)+ const sshTarget = await resolveTerminalConnectionForSender(+ event.sender.id,+ activeSshTerminalTarget,+ ensureBackend+ )const remote = Boolean(sshTarget)const remoteState = remote ? getSshConnectionState(sshTarget.scope) : nulldiff --git a/apps/desktop/electron/window-connection-route.test.ts b/apps/desktop/electron/window-connection-route.test.tsnew file mode 100644index 00000000000..b0f9f7da70c--- /dev/null+++ b/apps/desktop/electron/window-connection-route.test.ts@@ -0,0 +1,126 @@+import assert from 'node:assert/strict'++import { test } from 'vitest'++import {+ normalizeWindowConnectionRoute,+ registrySshScopeForWindowRoute,+ WindowConnectionRouteRegistry+} from './window-connection-route'++test('normalizes an exact registry-scoped connection and profile', () => {+ assert.deepEqual(+ normalizeWindowConnectionRoute({+ connectionId: 'source-b',+ profile: 'research',+ registryScoped: true+ }),+ {+ connectionId: 'source-b',+ profile: 'research',+ registryScoped: true+ }+ )+})++test('keeps legacy/profile-only routes distinct from registry identities', () => {+ assert.deepEqual(normalizeWindowConnectionRoute({ profile: 'work' }), {+ connectionId: null,+ profile: 'work',+ registryScoped: false+ })+})++test('preserves a registry connection when no profile is selected', () => {+ assert.deepEqual(+ normalizeWindowConnectionRoute({+ connectionId: 'source-b',+ registryScoped: true+ }),+ {+ connectionId: 'source-b',+ profile: undefined,+ registryScoped: true+ }+ )+})++test('isolates active routes by webContents id', () => {+ const routes = new WindowConnectionRouteRegistry()++ routes.set(11, { connectionId: 'source-a', profile: 'default', registryScoped: true })+ routes.set(22, { connectionId: 'source-b', profile: 'worker', registryScoped: true })++ assert.equal(routes.get(11)?.connectionId, 'source-a')+ assert.equal(routes.get(22)?.connectionId, 'source-b')++ routes.delete(11)++ assert.equal(routes.get(11), null)+ assert.equal(routes.get(22)?.connectionId, 'source-b')+})++test('invalid publications clear only the sender route', () => {+ const routes = new WindowConnectionRouteRegistry()++ routes.set(11, { connectionId: 'source-a', profile: 'default', registryScoped: true })+ routes.set(22, { connectionId: 'source-b', profile: 'worker', registryScoped: true })++ routes.set(11, null)++ assert.equal(routes.get(11), null)+ assert.equal(routes.get(22)?.connectionId, 'source-b')+})++test('routes a non-primary SSH connection independently from another window', () => {+ const registry = {+ primary: 'source-a',+ connections: [+ { id: 'source-a', kind: 'ssh' },+ { id: 'source-b', kind: 'ssh' },+ { id: 'source-c', kind: 'remote' }+ ]+ } as never++ const routes = new WindowConnectionRouteRegistry()++ routes.set(11, {+ connectionId: 'source-b',+ profile: 'worker',+ registryScoped: true+ })+ routes.set(22, {+ connectionId: 'source-c',+ profile: 'default',+ registryScoped: true+ })++ assert.equal(+ registrySshScopeForWindowRoute(routes.get(11), registry),+ 'conn:source-b::worker'+ )+ assert.equal(registrySshScopeForWindowRoute(routes.get(22), registry), null)+})++test('uses the canonical default profile scope when a registry SSH route has no profile', () => {+ const registry = {+ primary: 'source-a',+ connections: [+ { id: 'source-a', kind: 'ssh' },+ { id: 'source-b', kind: 'ssh' }+ ]+ } as never++ assert.equal(+ registrySshScopeForWindowRoute(+ {+ connectionId: 'source-b',+ profile: undefined,+ registryScoped: true+ },+ registry+ ),+ 'conn:source-b::default'+ )+})+diff --git a/apps/desktop/electron/window-connection-route.ts b/apps/desktop/electron/window-connection-route.tsnew file mode 100644index 00000000000..9c55e5af1d2--- /dev/null+++ b/apps/desktop/electron/window-connection-route.ts@@ -0,0 +1,67 @@+import { backendScopeKey, type ConnectionRegistry } from './connection-registry'++export interface WindowConnectionRoute {+ connectionId: null | string+ profile: string | undefined+ registryScoped: boolean+}++export function normalizeWindowConnectionRoute(value: unknown): WindowConnectionRoute | null {+ if (!value || typeof value !== 'object') {+ return null+ }++ const input = value as Record<string, unknown>+ const connectionId = typeof input.connectionId === 'string' ? input.connectionId.trim() : ''+ const profile =+ typeof input.profile === 'string' && input.profile.trim()+ ? input.profile.trim()+ : undefined++ return {+ connectionId: connectionId || null,+ profile,+ registryScoped: input.registryScoped === true+ }+}++export function registrySshScopeForWindowRoute(+ route: WindowConnectionRoute | null | undefined,+ registry: ConnectionRegistry+): null | string {+ if (!route?.registryScoped || !route.connectionId) {+ return null+ }++ const source = registry.connections.find(connection => connection.id === route.connectionId)++ if (!source || source.kind !== 'ssh') {+ return null+ }++ return backendScopeKey(route.connectionId, route.profile)+}++export class WindowConnectionRouteRegistry {+ private readonly routes = new Map<number, WindowConnectionRoute>()++ set(webContentsId: number, value: unknown): WindowConnectionRoute | null {+ const route = normalizeWindowConnectionRoute(value)++ if (!route) {+ this.routes.delete(webContentsId)+ return null+ }++ this.routes.set(webContentsId, route)+ return route+ }++ get(webContentsId: number): WindowConnectionRoute | null {+ return this.routes.get(webContentsId) ?? null+ }++ delete(webContentsId: number): void {+ this.routes.delete(webContentsId)+ }+}diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 71fc3dc773a..eed4329893c 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -172,6 +172,15 @@ export function useGatewayBoot({const publish = (next: HermesConnection | null) => {callbacksRef.current.onConnectionReady(next)setConnection(next)+ desktop?.setActiveConnectionRoute?.(+ next+ ? {+ connectionId: next.connectionId ?? null,+ profile: next.profile,+ registryScoped: next.registryScoped === true+ }+ : null+ )}if (!desktop) {diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 5e8d1c8154a..62c1799c1b4 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -415,6 +415,11 @@ declare global {write: (id: string, data: string) => Promise<boolean>}reachPreviewUrl?: (url: string) => Promise<string>+ setActiveConnectionRoute?: (route: {+ connectionId?: null | string+ profile?: string+ registryScoped?: boolean+ } | null) => voidonClosePreviewRequested?: (callback: () => void) => () => voidonPreviewNav?: (callback: (command: 'back' | 'forward' | 'reload') => void) => () => voidonOpenFolderRequested?: (callback: () => void) => () => void