The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): persist default profile and route peer windows
brooklyn!8eaf776c3b67
diff --git a/apps/desktop/electron/backend-dial-claim.test.ts b/apps/desktop/electron/backend-dial-claim.test.tsindex 03bbf4198b3..f280661563d 100644--- a/apps/desktop/electron/backend-dial-claim.test.ts+++ b/apps/desktop/electron/backend-dial-claim.test.ts@@ -5,7 +5,8 @@ import { fileURLToPath } from 'node:url'import { describe, expect, it, vi } from 'vitest'import { BackendDialClaims } from './backend-dial-claim'-import { parseBackendScopeKey } from './connection-registry'+import { backendScopeKey, parseBackendScopeKey } from './connection-registry'+import { resolveDesktopConnectionRequest } from './desktop-profile'const here = path.dirname(fileURLToPath(import.meta.url))const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')@@ -123,24 +124,28 @@ describe('parseBackendScopeKey (#90812/#93910)', () => {})describe('main.ts wiring for #90812', () => {- it('routes the profile-scoped dial IPC through the single-owner claim', () => {- const handlerStart = mainSource.indexOf("ipcMain.handle('hermes:connection', ")- expect(handlerStart).toBeGreaterThan(-1)- const body = mainSource.slice(handlerStart, handlerStart + 1200)-- expect(body).toContain('backendDialClaims.run(')- expect(body).toContain('ensureBackend(profile, { spawnPriority })')- })-- it('routes the registry-scoped dial IPC through the claim keyed by backendScopeKey(connectionId, profile)', () => {- const handlerStart = mainSource.indexOf("ipcMain.handle('hermes:connection:for', ")- expect(handlerStart).toBeGreaterThan(-1)- const body = mainSource.slice(handlerStart, handlerStart + 1_200)-- expect(body).toContain('const scopeKey = backendScopeKey(id, profile)')- expect(body).toContain('backendDialClaims.run(scopeKey, ')- expect(body).toContain("ensureRegistryBackend(id, profile, '', { spawnPriority })")- })+ it.each([null, 'office-ssh'])(+ 'coalesces resolved window routes without absorbing a same-named source (%s)',+ async connectionId => {+ const claims = new BackendDialClaims()+ const source = { connectionId, profile: 'work', registryScoped: connectionId !== null }+ const route = resolveDesktopConnectionRequest(undefined, source, 'default')+ const key = backendScopeKey(route.connectionId, route.profile)+ const dial = vi.fn(async () => ({ baseUrl: 'http://localhost:53150' }))+ const other = vi.fn(async () => ({ baseUrl: 'http://localhost:53151' }))++ const [first, second, separate] = await Promise.all([+ claims.run(key, dial),+ claims.run(key, dial),+ claims.run(backendScopeKey('another-source', route.profile), other)+ ])++ expect(first).toBe(second)+ expect(first).not.toBe(separate)+ expect(dial).toHaveBeenCalledTimes(1)+ expect(other).toHaveBeenCalledTimes(1)+ }+ )// The four IPC/probe surfaces below call ensureRegistryBackend()/ensureBackend()// directly, bypassing backendDialClaims entirely — so a renderer's guardeddiff --git a/apps/desktop/electron/desktop-profile-preload.test.ts b/apps/desktop/electron/desktop-profile-preload.test.tsnew file mode 100644index 00000000000..d8e07a0a79d--- /dev/null+++ b/apps/desktop/electron/desktop-profile-preload.test.ts@@ -0,0 +1,43 @@+import assert from 'node:assert/strict'++import { test, vi } from 'vitest'++const electron = vi.hoisted(() => ({+ contextBridge: { exposeInMainWorld: vi.fn() },+ ipcRenderer: {+ invoke: vi.fn(async () => ({ ok: true })),+ on: vi.fn(),+ removeListener: vi.fn(),+ sendSync: vi.fn(() => ({}))+ },+ webFrame: {},+ webUtils: {}+}))++vi.mock('electron', () => electron)++test('the native preload exposes routed peer opening and default preference events with unsubscribe', async () => {+ await import('./preload')+ const [name, bridge] = electron.contextBridge.exposeInMainWorld.mock.calls[0]+ assert.equal(name, 'hermesDesktop')+ const route = { connectionId: 'remote-work', profile: 'work' }++ await bridge.openWindow(route)+ assert.deepEqual(electron.ipcRenderer.invoke.mock.lastCall, ['hermes:window:openInstance', route])+ await bridge.openWindow()+ assert.deepEqual(electron.ipcRenderer.invoke.mock.lastCall, ['hermes:window:openInstance', undefined])+ await bridge.profile.setDefault(route)+ assert.deepEqual(electron.ipcRenderer.invoke.mock.lastCall, ['hermes:profile:default:set', route])+ await bridge.profile.getDefault()+ assert.deepEqual(electron.ipcRenderer.invoke.mock.lastCall, ['hermes:profile:default:get'])++ const changes: unknown[] = []+ const unsubscribe = bridge.profile.onDefaultChanged((value: unknown) => changes.push(value))+ const [channel, listener] = electron.ipcRenderer.on.mock.lastCall!+ assert.equal(channel, 'hermes:profile:default:changed')+ listener({}, route)+ listener({}, null)+ assert.deepEqual(changes, [route, null])+ unsubscribe()+ assert.deepEqual(electron.ipcRenderer.removeListener.mock.lastCall, [channel, listener])+})diff --git a/apps/desktop/electron/desktop-profile.test.ts b/apps/desktop/electron/desktop-profile.test.tsnew file mode 100644index 00000000000..61c790b9ad0--- /dev/null+++ b/apps/desktop/electron/desktop-profile.test.ts@@ -0,0 +1,148 @@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test } from 'vitest'++import {+ createDesktopProfilePreferences,+ resolveDesktopConnectionRequest,+ resolveDesktopWindowRoute+} from './desktop-profile'+import { WindowConnectionRouteRegistry } from './window-connection-route'++test('failed authoritative writes leave the previous default and listeners untouched', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-profile-write-'))+ const target = path.join(root, 'active-profile.json')+ const changes: unknown[] = []+ const preferences = createDesktopProfilePreferences(target, {+ onDefaultChanged: route => changes.push(route),+ validateRoute: route => {+ if (route.connectionId === 'missing') {+ throw new Error('Connection was removed')+ }+ }+ })++ try {+ const original = { connectionId: null, profile: 'work' }+ preferences.setDefault(original)+ for (const invalid of [+ null,+ {},+ { connectionId: 'missing', profile: 'work' },+ { connectionId: null, profile: ' work ' }+ ]) {+ assert.throws(() => preferences.setDefault(invalid))+ assert.deepEqual(preferences.getDefault(), original)+ }+ fs.mkdirSync(`${target}.tmp`)+ assert.throws(() => preferences.setDefault({ connectionId: 'remote', profile: 'personal' }))+ assert.deepEqual(preferences.getDefault(), original)+ assert.deepEqual(changes, [original])+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})++test('explicit routes are strict and never fall back to a different source window', () => {+ const routes = new WindowConnectionRouteRegistry()+ routes.set(1, { connectionId: 'remote-a', profile: 'work', registryScoped: true })+ routes.set(2, { connectionId: 'remote-b', profile: 'work', registryScoped: true })+ const fallback = { connectionId: null, profile: 'default' }+ const explicit = { connectionId: 'remote-c', profile: 'personal' }++ assert.deepEqual(resolveDesktopWindowRoute(undefined, routes.get(1), fallback), {+ connectionId: 'remote-a',+ profile: 'work'+ })+ assert.deepEqual(resolveDesktopWindowRoute(explicit, routes.get(1), fallback), explicit)+ assert.deepEqual(resolveDesktopWindowRoute(undefined, routes.get(2), fallback), {+ connectionId: 'remote-b',+ profile: 'work'+ })+ assert.deepEqual(resolveDesktopWindowRoute(undefined, routes.get(1), fallback), {+ connectionId: 'remote-a',+ profile: 'work'+ })+ assert.deepEqual(routes.get(1), { connectionId: 'remote-a', profile: 'work', registryScoped: true })+ assert.throws(() => resolveDesktopWindowRoute({ profile: 'work' }, routes.get(1), fallback))+ assert.throws(() => resolveDesktopWindowRoute({ connectionId: null, profile: '../work' }, routes.get(1), fallback))+ assert.throws(() => resolveDesktopWindowRoute({ connectionId: '', profile: 'work' }, routes.get(1), fallback))+})++test('boot and reconnect retain the window route rather than a later global default or another window', () => {+ const routeA = { connectionId: 'remote-a', profile: 'work', registryScoped: true }+ const routeB = { connectionId: null, profile: 'personal', registryScoped: false }++ for (const route of [routeA, routeB, routeA]) {+ assert.deepEqual(resolveDesktopConnectionRequest(undefined, route, 'last-used'), {+ connectionId: route.connectionId,+ profile: route.profile+ })+ assert.deepEqual(resolveDesktopConnectionRequest(route.profile, route, 'last-used'), {+ connectionId: null,+ profile: route.profile+ })+ }+ assert.deepEqual(resolveDesktopConnectionRequest('other', routeA, 'last-used'), {+ connectionId: null,+ profile: 'other'+ })+ assert.deepEqual(resolveDesktopConnectionRequest(undefined, null, 'last-used'), {+ connectionId: null,+ profile: 'last-used'+ })+})++test('an explicit default survives last-used profile writes and app restarts, isolated by desktop home', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-profile-'))++ try {+ const homeA = path.join(root, 'a', 'active-profile.json')+ const homeB = path.join(root, 'b', 'active-profile.json')+ const changes: unknown[] = []+ const a = createDesktopProfilePreferences(homeA, { onDefaultChanged: route => changes.push(route) })+ const b = createDesktopProfilePreferences(homeB)+ const route = { connectionId: 'remote-work', profile: 'work' }++ assert.equal(a.getDefault(), null)+ assert.equal(a.remember('personal'), 'personal')+ assert.deepEqual(a.setDefault(route), route)+ a.remember('other')+ b.setDefault({ connectionId: null, profile: 'personal' })++ assert.equal(a.readActive(), 'other')+ assert.deepEqual(createDesktopProfilePreferences(homeA).getDefault(), route)+ assert.deepEqual(b.getDefault(), { connectionId: null, profile: 'personal' })+ assert.deepEqual(a.getDefault(), route)+ assert.deepEqual(changes, [route])+ a.afterProfileRequest(+ 'remote-work',+ { method: 'PATCH', path: '/api/profiles/work', body: { new_name: 'ignored' } },+ { ok: false }+ )+ assert.deepEqual(a.getDefault(), route)+ a.afterProfileRequest(+ 'remote-work',+ { method: 'PATCH', path: '/api/profiles/work', body: { new_name: 'renamed' } },+ { ok: true }+ )+ assert.deepEqual(a.getDefault(), { ...route, profile: 'renamed' })+ a.afterProfileRequest('remote-work', { method: 'DELETE', path: '/api/profiles/renamed' }, { ok: true })+ assert.equal(a.getDefault(), null)+ a.setDefault(route)+ a.profileChanged('another-source', 'work', 'renamed')+ assert.deepEqual(a.getDefault(), route)+ a.profileChanged(route.connectionId, route.profile, 'renamed')+ assert.deepEqual(a.getDefault(), { ...route, profile: 'renamed' })+ a.profileChanged(route.connectionId, 'renamed', null)+ assert.equal(a.getDefault(), null)+ a.setDefault(route)+ a.connectionRemoved(route.connectionId)+ assert.equal(createDesktopProfilePreferences(homeA).getDefault(), null)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/desktop-profile.ts b/apps/desktop/electron/desktop-profile.tsnew file mode 100644index 00000000000..2dbcd96d6bd--- /dev/null+++ b/apps/desktop/electron/desktop-profile.ts@@ -0,0 +1,182 @@+import fs from 'node:fs'+import path from 'node:path'++import { profileNameFromDeleteRequest } from './profile-delete-routing'+import { profileRenameFromRequest, type ProfileRenameRequest } from './profile-rename-routing'+import type { WindowConnectionRoute } from './window-connection-route'++export interface DesktopProfileRoute {+ connectionId: null | string+ profile: string+}++export const DESKTOP_PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/++export function requireDesktopProfileRoute(value: unknown): DesktopProfileRoute {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error('A connection and profile route is required.')+ }++ const { connectionId, profile } = value as Record<string, unknown>++ if (typeof profile !== 'string' || !DESKTOP_PROFILE_NAME_RE.test(profile)) {+ throw new Error('Invalid profile name.')+ }++ if (+ connectionId !== null &&+ (typeof connectionId !== 'string' || !connectionId || connectionId.trim() !== connectionId)+ ) {+ throw new Error('Invalid connection id.')+ }++ return { connectionId: connectionId as null | string, profile }+}++// Explicit peer intent wins; a generic New Window inherits its IPC sender,+// never whichever other window happened to gain OS focus while IPC was queued.+export function resolveDesktopWindowRoute(+ explicit: unknown,+ source: WindowConnectionRoute | null,+ fallback: DesktopProfileRoute+): DesktopProfileRoute {+ if (explicit !== undefined) {+ return requireDesktopProfileRoute(explicit)+ }++ return source?.profile+ ? requireDesktopProfileRoute({+ connectionId: source.registryScoped ? source.connectionId : null,+ profile: source.profile+ })+ : { ...fallback }+}++// A profile-less boot/reconnect belongs to its sender. An explicit profile+// keeps the legacy route, even if the sender serves the same name remotely.+export function resolveDesktopConnectionRequest(+ profile: unknown,+ source: WindowConnectionRoute | null,+ primaryProfile: string+): DesktopProfileRoute {+ const requested = typeof profile === 'string' ? profile.trim() : ''++ if (source?.profile && !requested) {+ return resolveDesktopWindowRoute(undefined, source, { connectionId: null, profile: primaryProfile })+ }++ return { connectionId: null, profile: requested || primaryProfile }+}++// The legacy profile field records last use. defaultRoute is an explicit,+// app-wide preference, never changed by switching workspaces in any window.+export function createDesktopProfilePreferences(+ configPath: string,+ options: {+ onDefaultChanged?: (route: DesktopProfileRoute | null) => void+ validateRoute?: (route: DesktopProfileRoute) => void+ } = {}+) {+ function read(strict = false): Record<string, unknown> {+ try {+ const value = JSON.parse(fs.readFileSync(configPath, 'utf8'))++ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') {+ throw error+ }++ return {}+ }+ }++ function write(value: Record<string, unknown>) {+ fs.mkdirSync(path.dirname(configPath), { recursive: true })+ const temporaryPath = `${configPath}.tmp`+ fs.writeFileSync(temporaryPath, JSON.stringify(value, null, 2), 'utf8')+ fs.renameSync(temporaryPath, configPath)+ }++ function getDefault(): DesktopProfileRoute | null {+ try {+ return requireDesktopProfileRoute(read().defaultRoute)+ } catch {+ return null+ }+ }++ function readActive(): null | string {+ const value = read().profile+ const profile = typeof value === 'string' ? value.trim() : ''++ return DESKTOP_PROFILE_NAME_RE.test(profile) ? profile : null+ }++ function remember(name: unknown): null | string {+ const profile = typeof name === 'string' ? name.trim() : ''++ if (profile && !DESKTOP_PROFILE_NAME_RE.test(profile)) {+ throw new Error(`Invalid profile name: ${profile}`)+ }++ write({ ...read(true), profile: profile || null })++ return profile || null+ }++ function setDefault(value: unknown): DesktopProfileRoute {+ const route = requireDesktopProfileRoute(value)+ options.validateRoute?.(route)+ write({ ...read(true), defaultRoute: route })+ options.onDefaultChanged?.(route)++ return route+ }++ function clearDefault() {+ write({ ...read(true), defaultRoute: null })+ options.onDefaultChanged?.(null)+ }++ function profileChanged(connectionId: null | string, oldName: string, newName: null | string) {+ const route = getDefault()++ if (route?.connectionId !== connectionId || route?.profile !== oldName) {+ return+ }++ if (newName) {+ setDefault({ ...route, profile: newName })+ } else {+ clearDefault()+ }+ }++ function connectionRemoved(connectionId: string) {+ if (getDefault()?.connectionId === connectionId) {+ clearDefault()+ }+ }++ function afterProfileRequest(connectionId: null | string, request: ProfileRenameRequest, response: unknown) {+ if (response && typeof response === 'object') {+ const result = response as Record<string, unknown>++ if (result.ok === false || result.success === false || result.error) {+ return+ }+ }++ const renamed = profileRenameFromRequest(request)+ const deleted = profileNameFromDeleteRequest(request)++ if (renamed) {+ profileChanged(connectionId, renamed.oldName, renamed.newName)+ } else if (deleted) {+ profileChanged(connectionId, deleted, null)+ }+ }++ return { afterProfileRequest, connectionRemoved, getDefault, profileChanged, readActive, remember, setDefault }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 9c0c83fe977..62e0e48231c 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -163,6 +163,13 @@ import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'+import {+ createDesktopProfilePreferences,+ DESKTOP_PROFILE_NAME_RE,+ type DesktopProfileRoute,+ resolveDesktopConnectionRequest,+ resolveDesktopWindowRoute+} from './desktop-profile'import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'import {buildPosixCleanupScript,@@ -879,7 +886,7 @@ const DESKTOP_MANAGED_SSH_RECOVERY_PATH = path.join(app.getPath('userData'), 'maconst DESKTOP_PROFILE_CONFIG_PATH = path.join(app.getPath('userData'), 'active-profile.json')// Mirrors hermes_cli.profiles._PROFILE_ID_RE so we never hand the backend a// value its profile resolver would reject and exit on.-const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/+const PROFILE_NAME_RE = DESKTOP_PROFILE_NAME_RE// Branch we track for self-update. The GUI work has merged to main, so this// tracks main. User can also override at runtime via// hermesDesktop.updates.setBranch().@@ -9727,36 +9734,34 @@ async function saveRegistryConnection(input: any = {}) {return sanitizeRegistryConnection(entry)}-// Returns the desktop's chosen profile name, or null when unset. "default" is-// a valid stored value (pins the root HERMES_HOME explicitly); null means "no-// preference" and preserves the legacy launch (no --profile flag).-function readActiveDesktopProfile() {- try {- const raw = fs.readFileSync(DESKTOP_PROFILE_CONFIG_PATH, 'utf8')- const parsed = JSON.parse(raw)- const name = parsed && typeof parsed.profile === 'string' ? parsed.profile.trim() : ''-- if (name && (name === 'default' || PROFILE_NAME_RE.test(name))) {- return name+// Last-used profile and explicit app-wide default share the existing desktop+// preference file, but only the explicit action changes the default route.+const desktopProfilePreferences = createDesktopProfilePreferences(DESKTOP_PROFILE_CONFIG_PATH, {+ validateRoute: validateDesktopProfileRoute,+ onDefaultChanged: route => {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.webContents.isDestroyed()) {+ win.webContents.send('hermes:profile:default:changed', route)+ }}- } catch {- // Missing or malformed → no preference.}+})- return null-}--function writeActiveDesktopProfile(name) {- const value = typeof name === 'string' ? name.trim() : ''-- if (value && value !== 'default' && !PROFILE_NAME_RE.test(value)) {- throw new Error(`Invalid profile name: ${value}`)+function validateDesktopProfileRoute(route: DesktopProfileRoute) {+ if (+ route.connectionId &&+ !readDesktopConnectionsRegistry().connections.some((source: { id: string }) => source.id === route.connectionId)+ ) {+ throw new Error(`No connection with id "${route.connectionId}".`)}+}- fs.mkdirSync(path.dirname(DESKTOP_PROFILE_CONFIG_PATH), { recursive: true })- writeFileAtomic(DESKTOP_PROFILE_CONFIG_PATH, JSON.stringify({ profile: value || null }, null, 2))+function readActiveDesktopProfile() {+ return desktopProfilePreferences.readActive()+}- return value || null+function writeActiveDesktopProfile(name) {+ return desktopProfilePreferences.remember(name)}// True when the given pid belongs to a running process whose command line@@ -13705,8 +13710,7 @@ const instanceWindows = new Set<any>()// exactly on top of its source. Falls back to the persisted primary geometry// when there's no live source window (e.g. all windows closed on macOS). The// pure cascade math lives in session-windows.ts (instanceWindowBounds).-function nextInstanceBounds() {- const source = BrowserWindow.getFocusedWindow() || mainWindow+function nextInstanceBounds(source: BrowserWindow | null = BrowserWindow.getFocusedWindow() || mainWindow) {const fallback = computeWindowOptions(readWindowState(), screen.getAllDisplays())const base = source && !source.isDestroyed() ? source.getBounds() : null@@ -13716,14 +13720,22 @@ function nextInstanceBounds() {// Open a new full-chrome instance window. Mirrors createWindow()'s window// options (shared chatWindowWebPreferences + streamThrottle registration so a// streamed answer never stalls in the background) but is a peer, not the-// primary: it never overwrites the mainWindow global, doesn't start the backend-// (the renderer's getConnection() joins the already-running one), and loads the-// plain renderer URL so the full app renders.-function createInstanceWindow() {+// primary: it never overwrites mainWindow or re-homes the source. Its renderer+// joins the requested pooled backend through its own connection/profile route.+function createInstanceWindow(+ options?: DesktopProfileRoute,+ source: BrowserWindow | null = BrowserWindow.getFocusedWindow() || mainWindow+) {+ const route = resolveDesktopWindowRoute(+ options,+ source && !source.isDestroyed() ? windowConnectionRoutes.get(source.webContents.id) : null,+ { connectionId: null, profile: primaryProfileKey() }+ )+ validateDesktopProfileRoute(route)const icon = getAppIconPath()const win = new BrowserWindow({- ...nextInstanceBounds(),+ ...nextInstanceBounds(source),minWidth: WINDOW_MIN_WIDTH,minHeight: WINDOW_MIN_HEIGHT,title: 'Hermes',@@ -13737,6 +13749,7 @@ function createInstanceWindow() {})instanceWindows.add(win)+ recordWindowConnectionRoute(win.webContents, { ...route, registryScoped: route.connectionId !== null })// Chat-surface registration: see applyWindowTranslucency.translucencyBackedWindows.add(win)@@ -13779,6 +13792,7 @@ function createInstanceWindow() {loadWindowUrl(win,buildInstanceWindowUrl({+ ...route,devServer: DEV_SERVER,rendererIndexPath: DEV_SERVER ? undefined : resolveRendererIndex()}),@@ -14735,6 +14749,14 @@ function createWindow() {})const createdMainWindow = mainWindow+ const defaultRoute = desktopProfilePreferences.getDefault()++ if (defaultRoute) {+ recordWindowConnectionRoute(mainWindow.webContents, {+ ...defaultRoute,+ registryScoped: defaultRoute.connectionId !== null+ })+ }// Chat-surface registration: see applyWindowTranslucency.translucencyBackedWindows.add(mainWindow)@@ -14950,7 +14972,8 @@ function createWindow() {// shared (backendConnectionState), so the renderer's getConnection() joins// this in-flight boot instead of duplicating it; early boot-progress events// the renderer misses are recovered by its getBootProgress() pull on mount.- startHermes().catch(error => rememberLog(error.stack || error.message))+ const startup = defaultRoute ? connectDesktopProfileRoute(defaultRoute) : startHermes()+ startup.catch(error => rememberLog(error.stack || error.message))mainWindow.webContents.once('did-finish-load', () => {// Zoom restore is handled by wireCommonWindowHandlers (shared with session@@ -14960,31 +14983,48 @@ function createWindow() {})}-ipcMain.handle('hermes:connection', async (_event, profile, extra) => {+ipcMain.handle('hermes:connection', async (event, profile, extra) => {+ const route = resolveDesktopConnectionRequest(+ profile,+ windowConnectionRoutes.get(event.sender.id),+ primaryProfileKey()+ )++ return connectDesktopProfileRoute(route, spawnPriorityFrom(extra?.priority))+})++async function connectDesktopProfileRoute(+ route: DesktopProfileRoute,+ spawnPriority: LocalBackendSpawnPriority = 'foreground'+) {// Coalesce concurrent renderer dials for one profile scope (#90812): the// renderer-side reconnect lock is per-window, so two windows waking at once// both land here. The claim key mirrors ensureBackend()'s own profile// normalization so every spelling of the primary coalesces onto one dial.- const profileKey = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- // A user click may join an in-flight hydration claim; the foreground intent- // is applied to that claim so its slot wait can take the reserved slot.- const spawnPriority = spawnPriorityFrom(extra?.priority)-- const scopeKey = backendScopeKey(null, profileKey)+ const scopeKey = backendScopeKey(route.connectionId, route.profile)const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)let connectiontry {- connection = await backendDialClaims.run(scopeKey, () => ensureBackend(profile, { spawnPriority }))+ connection = await backendDialClaims.run(scopeKey, () =>+ route.connectionId+ ? ensureRegistryBackend(route.connectionId, route.profile, '', { spawnPriority })+ : ensureBackend(route.profile, { spawnPriority })+ )} finally {clearSpawnPriority()}+ if (route.connectionId) {+ return { ...connection, connectionId: route.connectionId, registryScoped: true }+ }+const connectionId = resolvedConnectionId(readDesktopConnectionsRegistry(), connection)return connectionId ? { ...connection, connectionId } : connection-})+}+// Registry-scoped variant: resolve a backend for (connectionId, profile).// connectionId '' / 'local' / the registry primary all behave sensibly; the// local kind delegates to ensureBackend when the v1 route is local, and@@ -14996,28 +15036,14 @@ ipcMain.handle('hermes:connection:for', async (_event, payload) => {const id = String(connectionId || '').trim() || registry.primaryconst spawnPriority = spawnPriorityFrom(priority)- // Same single-owner claim as 'hermes:connection', keyed by the composite- // (connectionId, profile) scope (#90812): concurrent registry dials for one- // scope share the first spawn instead of bootstrapping duplicate remotes.- const scopeKey = backendScopeKey(id, profile)- const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)-- let connection-- try {- connection = await backendDialClaims.run(scopeKey, () => ensureRegistryBackend(id, profile, '', { spawnPriority }))- } finally {- clearSpawnPriority()- }-- return { ...connection, connectionId: id, registryScoped: true }+ return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, spawnPriority)})const windowConnectionRoutes = new WindowConnectionRouteRegistry()const windowConnectionRouteOwners = new Set<number>()-ipcMain.on('hermes:connection:active-route', (event, route) => {- const id = event.sender.id+function recordWindowConnectionRoute(sender: Electron.WebContents, route: unknown) {+ const id = sender.idconst previous = windowConnectionRoutes.get(id)const next = windowConnectionRoutes.set(id, route)@@ -15031,13 +15057,15 @@ ipcMain.on('hermes:connection:active-route', (event, route) => {if (!windowConnectionRouteOwners.has(id)) {windowConnectionRouteOwners.add(id)- event.sender.once('destroyed', () => {+ sender.once('destroyed', () => {windowConnectionRoutes.delete(id)windowConnectionRouteOwners.delete(id)void resetPreviewReach(id)})}-})+}++ipcMain.on('hermes:connection:active-route', (event, route) => recordWindowConnectionRoute(event.sender, route))// 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@@ -15177,8 +15205,8 @@ ipcMain.handle('hermes:window:openSession', async (_event, sessionId, opts) => {return { ok: true }})-ipcMain.handle('hermes:window:openInstance', async () => {- createInstanceWindow()+ipcMain.handle('hermes:window:openInstance', async (event, options) => {+ createInstanceWindow(options, BrowserWindow.fromWebContents(event.sender))return { ok: true }})@@ -15551,6 +15579,7 @@ ipcMain.handle('hermes:connections:remove', async (_event, id) => {// removed connection keep their WebSocket open (remote/cloud have no local// process to kill) and stream ghost events until page reload.broadcastConnectionsChanged({ connectionId: key, reason: 'removed' })+ desktopProfilePreferences.connectionRemoved(key)return { ok: true, registry: sanitizeConnectionsRegistry(registry) }})@@ -16320,11 +16349,12 @@ ipcMain.handle('hermes:connection-config:apply', async (_event, payload) => {return sanitizeDesktopConnectionConfig(config, payload?.profile)})+ipcMain.handle('hermes:profile:default:get', async () => desktopProfilePreferences.getDefault())+ipcMain.handle('hermes:profile:default:set', async (_event, route) => desktopProfilePreferences.setDefault(route))ipcMain.handle('hermes:profile:get', async () => ({ profile: readActiveDesktopProfile() }))// Persistence-only sibling of hermes:profile:set: records the profile the-// Desktop should boot into next launch WITHOUT tearing down the backend or-// reloading the window — the rail's live workspace switch already re-homed-// the gateway (#79886).+// Desktop last used WITHOUT tearing down the backend or reloading the window.+// An explicit default route wins at launch and is never replaced here.ipcMain.handle('hermes:profile:remember', async (_event, name) => ({profile: writeActiveDesktopProfile(name)}))@@ -16770,7 +16800,10 @@ async function handleHermesApiRequest(request) {const registryConnectionId = apiRequestRegistryConnectionId(request)if (registryConnectionId) {- return dispatchRegistryApiRequest(request, registryConnectionId)+ const response = await dispatchRegistryApiRequest(request, registryConnectionId)+ desktopProfilePreferences.afterProfileRequest(registryConnectionId, request, response)++ return response}// Remote-profile session requests would otherwise hit the local primary off@@ -16832,7 +16865,11 @@ async function handleHermesApiRequest(request) {throw error}- await profileRename?.complete()+ try {+ desktopProfilePreferences.afterProfileRequest(null, request, response)+ } finally {+ await profileRename?.complete()+ }return response}@@ -16846,7 +16883,7 @@ ipcMain.handle('hermes:api', async (_event, request) => {const registryConnectionId = apiRequestRegistryConnectionId(request)if (deletingProfile && registryConnectionId) {- return dispatchConnectionScopedProfileDelete(request, {+ const response = await dispatchConnectionScopedProfileDelete(request, {acquire: profile => profileDeletionGate.acquire(profile),connectionKind: connectionId => registryConnectionKind(connectionId),dispatch: routeProfile =>@@ -16856,6 +16893,9 @@ ipcMain.handle('hermes:api', async (_event, request) => {prepareLocal: localRequest => prepareProfileDeleteRequest(localRequest).then(() => undefined),teardownConnection: (connectionId, profile) => teardownConnectionScopedProfileBackend(connectionId, profile)})+ desktopProfilePreferences.afterProfileRequest(registryConnectionId, request, response)++ return response}if (!mutatingProfile) {diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex eaaab24f316..5e53c06a544 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -1,5 +1,7 @@import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'+import type { DesktopProfileRoute } from './desktop-profile'+// Which translucency the OS can back. Asked synchronously because the renderer// needs it before its first paint, and answered by main because deciding it// needs `os.release()` — a sandboxed preload may only require electron, events,@@ -41,7 +43,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {getAgentRoster: () => ipcRenderer.invoke('hermes:agents:roster'),openSessionWindow: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openSession', sessionId, opts),openSessionInTerminal: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openInTerminal', sessionId, opts),- openWindow: () => ipcRenderer.invoke('hermes:window:openInstance'),+ openWindow: (options?: DesktopProfileRoute) => ipcRenderer.invoke('hermes:window:openInstance', options),openBrowserWindow: tabId => ipcRenderer.invoke('hermes:window:openBrowser', tabId),onBrowserPopoutClosed: callback => {const listener = (_event, tabId) => callback(tabId)@@ -254,6 +256,14 @@ contextBridge.exposeInMainWorld('hermesDesktop', {agentSignIn: dashboardUrl => ipcRenderer.invoke('hermes:cloud:agent-sign-in', dashboardUrl)},profile: {+ getDefault: () => ipcRenderer.invoke('hermes:profile:default:get'),+ setDefault: (route: DesktopProfileRoute) => ipcRenderer.invoke('hermes:profile:default:set', route),+ onDefaultChanged: (callback: (route: DesktopProfileRoute | null) => void) => {+ const listener = (_event: Electron.IpcRendererEvent, route: DesktopProfileRoute | null) => callback(route)+ ipcRenderer.on('hermes:profile:default:changed', listener)++ return () => ipcRenderer.removeListener('hermes:profile:default:changed', listener)+ },get: () => ipcRenderer.invoke('hermes:profile:get'),remember: name => ipcRenderer.invoke('hermes:profile:remember', name),set: name => ipcRenderer.invoke('hermes:profile:set', name)diff --git a/apps/desktop/electron/session-windows.test.ts b/apps/desktop/electron/session-windows.test.tsindex 64a9d6fb12d..6d5a47082ec 100644--- a/apps/desktop/electron/session-windows.test.ts+++ b/apps/desktop/electron/session-windows.test.ts@@ -108,6 +108,19 @@ test('buildInstanceWindowUrl marks a packaged full peer', () => {assert.match(url, /^file:\/\/.*index\.html\?peer=1$/)})+test('explicit full peers carry connection and profile in dev and packaged URLs without becoming session windows', () => {+ for (const source of [{ devServer: 'http://localhost:5173/' }, { rendererIndexPath: '/opt/app/index.html' }]) {+ for (const connectionId of [null, 'remote&work']) {+ const url = new URL(buildInstanceWindowUrl({ ...source, connectionId, profile: 'work' }))+ assert.equal(url.searchParams.get('peer'), '1')+ assert.equal(url.searchParams.get('profile'), 'work')+ assert.equal(url.searchParams.get('connectionId'), connectionId ?? '')+ assert.equal(url.searchParams.has('win'), false)+ assert.equal(url.hash, '')+ }+ }+})+test('instanceWindowBounds cascades a new window off its source bounds', () => {const bounds = instanceWindowBounds({ x: 100, y: 120, width: 1400, height: 900 }, { width: 1, height: 1 })diff --git a/apps/desktop/electron/session-windows.ts b/apps/desktop/electron/session-windows.tsindex 5fbd456a5b7..c938e4bf618 100644--- a/apps/desktop/electron/session-windows.ts+++ b/apps/desktop/electron/session-windows.ts@@ -87,8 +87,8 @@ function buildSessionWindowUrl(sessionId: string, { devServer, profile, renderer// separate marker lets the renderer distinguish a peer from the one primary// app window: app-launch source restoration belongs to the primary only, while// a peer keeps the already-running backend it joined during boot.-function buildInstanceWindowUrl({ devServer, rendererIndexPath }: any = {}) {- const query = '?peer=1'+function buildInstanceWindowUrl({ connectionId, devServer, profile, rendererIndexPath }: any = {}) {+ const query = `?peer=1${profile ? `&profile=${encodeURIComponent(profile)}&connectionId=${encodeURIComponent(connectionId ?? '')}` : ''}`if (devServer) {const base = devServer.endsWith('/') ? devServer.slice(0, -1) : devServerdiff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 6a2e0d04c30..ff31c93d143 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -78,9 +78,9 @@ declare global {opts?: { cwd?: string; profile?: string }) => Promise<{ ok: boolean; error?: string }>// Open a new full-chrome app window — a peer instance of the primary that- // renders the complete app against the shared backend, so the user can run- // multiple GUI windows at once.- openWindow: () => Promise<{ ok: boolean; error?: string }>+ // renders the complete app on an explicit connection/profile, or inherits+ // the calling window's route when no options are supplied.+ openWindow: (options?: DesktopProfileRoute) => Promise<{ ok: boolean; error?: string }>// Pop the in-app Browser (webview + address bar) into its own OS window.// `tabId` is the `$previewTabs` id; closing the window fires// `onBrowserPopoutClosed` so the caller can dock the tab again.@@ -252,9 +252,12 @@ declare global {agentSignIn: (dashboardUrl: string) => Promise<DesktopCloudAgentSignInResult>}profile: {+ getDefault: () => Promise<DesktopProfileRoute | null>+ setDefault: (route: DesktopProfileRoute) => Promise<DesktopProfileRoute>+ onDefaultChanged: (callback: (route: DesktopProfileRoute | null) => void) => () => voidget: () => Promise<DesktopActiveProfile>- // Persists the profile used on the next Desktop launch without- // interrupting the live gateway workspace switch.+ // Remembers last use without interrupting a live workspace switch or+ // replacing an explicit default route.remember: (name: string | null) => Promise<DesktopActiveProfile>// Persists the desktop's profile choice and relaunches the local// backend under the new HERMES_HOME (reloads the window). Pass null to@@ -863,6 +866,11 @@ export interface HermesWindowState {windowButtonPosition: { x: number; y: number } | null}+export interface DesktopProfileRoute {+ connectionId: null | string+ profile: string+}+export interface DesktopActiveProfile {// The desktop's stored profile preference, or null when unset (legacy launch// that defers to the sticky active_profile / default).