Skip to content

The agent that grows with you

fix(desktop): keep selected device in ordinary peer windows

BearHuddlestonf1fdb5484bc7
diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.md
index effa71f30ca..ed32a81e886 100644
--- a/apps/desktop/DESIGN.md
+++ b/apps/desktop/DESIGN.md
@@ -69,6 +69,9 @@ full peer window without switching the source window. The desktop default
applies at startup and to generic new chats; explicit profile/project actions
and profile-specific windows keep their own destinations. Changing the default
does not move existing sessions or replace the active conversation.
+Ordinary **New Window** (`⌘⇧N` / `Ctrl+Shift+N`) inherits its opener's device and
+profile only at startup, not as a window-specific default. Later device/profile
+selections remain authoritative for new chats unless a desktop default is set.
Navigation must preserve context. A background session finishing, a tool result
arriving, or a project refresh may update badges and cached data; it must not
diff --git a/apps/desktop/e2e/peer-device-reset.spec.ts b/apps/desktop/e2e/peer-device-reset.spec.ts
new file mode 100644
index 00000000000..9855b837ff8
--- /dev/null
+++ b/apps/desktop/e2e/peer-device-reset.spec.ts
@@ -0,0 +1,262 @@
+/**
+ * A generic peer window inherits its initial owner, not a permanent New session
+ * target. Exercise two real gateways; only inference uses the shared mock.
+ * Requires the built desktop and a repo venv (or HERMES_DESKTOP_PYTHON).
+ */
+import { type ChildProcess, spawn } from 'node:child_process'
+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 {
+ buildAppEnv,
+ createSandbox,
+ launchDesktop,
+ type Sandbox,
+ writeEnvFile,
+ writeMockProviderConfig,
+} from './fixtures'
+import { collectErrorBanners, type ElectronApplication, expect, installErrorBannerGuard, type Page, test } from './test'
+
+const REPO_ROOT = path.resolve(import.meta.dirname, '../../..')
+const LOCAL_LABEL = 'This device'
+const REMOTE_LABEL = 'E2E remote'
+const REMOTE_ID = 'e2e-remote'
+const REMOTE_TOKEN = 'e2e-peer-disposable-token'
+
+function pythonBinary(): string {
+ if (process.env.HERMES_DESKTOP_PYTHON) {
+ return process.env.HERMES_DESKTOP_PYTHON
+ }
+
+ const suffix = process.platform === 'win32' ? ['Scripts', 'python.exe'] : ['bin', 'python']
+ const candidate = ['.venv', 'venv'].map(dir => path.join(REPO_ROOT, dir, ...suffix)).find(file => fs.existsSync(file))
+
+ if (!candidate) {
+ throw new Error('Create the repo Python venv or set HERMES_DESKTOP_PYTHON before running this spec')
+ }
+
+ return candidate
+}
+
+// Do not inherit profile selection, provider secrets, a dev-server URL, or
+// native account state. buildAppEnv supplies the suite's desktop launch flags.
+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']) {
+ if (defaults[key]) {
+ env[key] = defaults[key]
+ }
+ }
+
+ for (const key of ['XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR', 'APPDATA', 'LOCALAPPDATA']) {
+ env[key] = path.join(sandbox.root, key.toLowerCase())
+ fs.mkdirSync(env[key], { recursive: true, mode: 0o700 })
+ }
+
+ for (const key of ['HERMES_DESKTOP_USER_DATA_DIR', 'HERMES_DESKTOP_IGNORE_EXISTING', 'HERMES_DESKTOP_HERMES_ROOT', 'HERMES_DESKTOP_APP_NAME', 'HERMES_DESKTOP_SKIP_QUIT_CONFIRM']) {
+ env[key] = defaults[key]
+ }
+
+ return {
+ ...env,
+ HOME: sandbox.root,
+ USERPROFILE: sandbox.root,
+ HERMES_HOME: sandbox.hermesHome,
+ HERMES_DESKTOP_PYTHON: pythonBinary(),
+ PYTHONPATH: REPO_ROOT,
+ // On Linux CI, DISPLAY belongs to Xvfb rather than the host Wayland seat.
+ ...(process.platform === 'linux' ? { XDG_SESSION_TYPE: 'x11', ELECTRON_OZONE_PLATFORM_HINT: 'x11' } : {}),
+ }
+}
+
+async function freePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer()
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as net.AddressInfo
+ server.close(error => error ? reject(error) : resolve(port))
+ })
+ })
+}
+
+async function stopRemote(child: ChildProcess | undefined): Promise<void> {
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null) {
+ return
+ }
+
+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()))
+
+ const stop = (signal: NodeJS.Signals) => {
+ if (process.platform === 'win32') {
+ child.kill(signal)
+ } else {
+ process.kill(-child.pid!, signal)
+ }
+ }
+
+ stop('SIGTERM')
+ let timer: ReturnType<typeof setTimeout> | undefined
+ await Promise.race([exited, new Promise<void>(resolve => { timer = setTimeout(resolve, 5_000) })])
+ clearTimeout(timer)
+
+ if (child.exitCode === null && child.signalCode === null) {
+ stop('SIGKILL')
+ await exited
+ }
+}
+
+const gateway = (page: Page) => page.getByRole('button', { name: /^Registered gateways: / })
+const composer = (page: Page) => page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()
+
+async function expectReady(page: Page, label: string): Promise<void> {
+ await expect(gateway(page)).toHaveAttribute('aria-label', `Registered gateways: ${label}`, { timeout: 90_000 })
+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 90_000 })
+ await expect(composer(page)).toBeEditable()
+}
+
+async function switchTo(page: Page, label: string): Promise<void> {
+ await gateway(page).click()
+ await page.getByRole('menuitemradio', { name: new RegExp(label) }).click()
+ await expectReady(page, label)
+}
+
+async function newSession(page: Page, label: string): Promise<void> {
+ await page.locator('[data-tour="sidebar-nav-new-session"]').click()
+ await expectReady(page, label)
+ // Query the menu after the reset as well: the checked connection must agree
+ // with the ready statusbar, not merely retain its pre-click text for a frame.
+ await gateway(page).click()
+ await expect(page.getByRole('menuitemradio', { name: new RegExp(label) })).toHaveAttribute('aria-checked', 'true')
+ await page.keyboard.press('Escape')
+}
+
+const peerTest = test.extend<{ gateways: { app: ElectronApplication; source: Page } }>({
+ // Playwright requires object destructuring even for a fixture with no dependencies.
+ // eslint-disable-next-line no-empty-pattern
+ gateways: async ({}, runTest, info) => {
+ const local = createSandbox('peer-local')
+ const remote = createSandbox('peer-remote')
+ const mock = await startMockServer()
+ let child: ChildProcess | undefined
+ let app: ElectronApplication | undefined
+ let remoteLog = ''
+ let desktopLog = ''
+
+ try {
+ for (const sandbox of [local, remote]) {
+ writeMockProviderConfig(sandbox.hermesHome, mock.url)
+ writeEnvFile(sandbox.hermesHome)
+ }
+
+ const port = await freePort()
+ const remoteUrl = `http://127.0.0.1:${port}`
+ child = spawn(pythonBinary(), ['-m', 'hermes_cli.main', 'serve', '--host', '127.0.0.1', '--port', String(port), '--skip-build'], {
+ cwd: REPO_ROOT,
+ detached: process.platform !== 'win32',
+ env: { ...isolatedEnv(remote), HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ child.stdout?.on('data', chunk => { remoteLog += chunk.toString() })
+ child.stderr?.on('data', chunk => { remoteLog += chunk.toString() })
+ let spawnError: Error | undefined
+ child.on('error', error => { spawnError = error })
+ await expect.poll(async () => {
+ if (spawnError) { throw spawnError }
+
+ if (child!.exitCode !== null) { throw new Error(`Remote exited: ${remoteLog}`) }
+
+ try {
+ return (await fetch(`${remoteUrl}/api/status`, {
+ headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN },
+ signal: AbortSignal.timeout(2_000),
+ })).status
+ } catch { return 0 }
+ }, { timeout: 90_000 }).toBe(200)
+
+ fs.writeFileSync(path.join(local.userDataDir, 'connections.json'), JSON.stringify({
+ version: 2, primary: 'local', launchMode: 'primary', lastUsed: 'local',
+ connections: [
+ { id: 'local', kind: 'local', label: LOCAL_LABEL },
+ { id: REMOTE_ID, kind: 'remote', label: REMOTE_LABEL, url: remoteUrl,
+ authMode: 'token', token: { encoding: 'plain', value: REMOTE_TOKEN } },
+ ],
+ }), { encoding: 'utf8', mode: 0o600 })
+
+ const launched = await launchDesktop(isolatedEnv(local))
+ app = launched.app
+ app.process().stdout?.on('data', chunk => { desktopLog += chunk.toString() })
+ app.process().stderr?.on('data', chunk => { desktopLog += chunk.toString() })
+ await expectReady(launched.page, LOCAL_LABEL)
+ await runTest({ app, source: launched.page })
+ } finally {
+ const errors = new Set<string>()
+
+ if (app) {
+ for (const page of app.windows()) {
+ for (const error of await collectErrorBanners(page)) {
+ errors.add(error)
+ }
+
+ if (info.status !== info.expectedStatus) {
+ await page.screenshot({ path: info.outputPath(`window-${app.windows().indexOf(page)}.png`) }).catch(() => undefined)
+ }
+ }
+
+ await app.close().catch(() => undefined)
+ }
+
+ await stopRemote(child)
+ fs.writeFileSync(info.outputPath('remote.log'), remoteLog)
+ fs.writeFileSync(info.outputPath('desktop.log'), desktopLog)
+ await mock.close()
+ local.cleanup()
+ remote.cleanup()
+ // The shared afterEach checks only the last guarded page and runs before
+ // fixture teardown. Assert every window here, after releasing resources.
+ expect([...errors], 'Error banners in source or peer window').toEqual([])
+ }
+ },
+})
+
+peerTest.setTimeout(240_000)
+
+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)
+ 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, LOCAL_LABEL)
+
+ for (const label of [LOCAL_LABEL, REMOTE_LABEL, LOCAL_LABEL]) {
+ await test.step(`New session stays on ${label}`, async () => {
+ await switchTo(peer, label)
+ await newSession(peer, label)
+ await expectReady(source, LOCAL_LABEL)
+ await expect(composer(source)).toHaveText(sourceDraft)
+ })
+ }
+})
+
+peerTest('explicit profile window returns to its boot owner on New session', async ({ gateways: { app, source } }) => {
+ const remoteProfile = source.locator(`[data-slot="profile-rail-gateway"][data-connection-id="${REMOTE_ID}"]`)
+ .getByRole('button', { name: `default · ${REMOTE_LABEL}`, exact: true })
+
+ await expect(remoteProfile).toBeVisible({ timeout: 60_000 })
+ await remoteProfile.click({ button: 'right' })
+ const opened = app.waitForEvent('window')
+ await source.getByRole('menuitem', { name: 'Open in new window', exact: true }).click()
+ const pinned = await opened
+ installErrorBannerGuard(pinned)
+ await expectReady(pinned, REMOTE_LABEL)
+ await switchTo(pinned, LOCAL_LABEL)
+ await newSession(pinned, REMOTE_LABEL)
+ await expectReady(source, LOCAL_LABEL)
+})
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index eb143ead166..292f0323567 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -13633,6 +13633,7 @@ function createInstanceWindow(
win,
buildInstanceWindowUrl({
...route,
+ profileWindow: options !== undefined,
devServer: DEV_SERVER,
rendererIndexPath: DEV_SERVER ? undefined : resolveRendererIndex()
}),
diff --git a/apps/desktop/electron/session-windows.test.ts b/apps/desktop/electron/session-windows.test.ts
index 6d5a47082ec..9c21f9c1732 100644
--- a/apps/desktop/electron/session-windows.test.ts
+++ b/apps/desktop/electron/session-windows.test.ts
@@ -108,15 +108,18 @@ 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', () => {
+test('full peers carry their boot owner but only explicit profile windows pin future chats', () => {
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, '')
+ for (const profileWindow of [false, true]) {
+ const url = new URL(buildInstanceWindowUrl({ ...source, connectionId, profile: 'work', profileWindow }))
+ 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.get('profileWindow'), profileWindow ? '1' : null)
+ assert.equal(url.searchParams.has('win'), false)
+ assert.equal(url.hash, '')
+ }
}
}
})
diff --git a/apps/desktop/electron/session-windows.ts b/apps/desktop/electron/session-windows.ts
index c938e4bf618..669aa1efc82 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({ connectionId, devServer, profile, rendererIndexPath }: any = {}) {
- const query = `?peer=1${profile ? `&profile=${encodeURIComponent(profile)}&connectionId=${encodeURIComponent(connectionId ?? '')}` : ''}`
+function buildInstanceWindowUrl({ connectionId, devServer, profile, profileWindow, rendererIndexPath }: any = {}) {
+ const query = `?peer=1${profile ? `&profile=${encodeURIComponent(profile)}&connectionId=${encodeURIComponent(connectionId ?? '')}${profileWindow ? '&profileWindow=1' : ''}` : ''}`
if (devServer) {
const base = devServer.endsWith('/') ? devServer.slice(0, -1) : devServer
diff --git a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx b/apps/desktop/src/app/session/hooks/default-new-session.test.tsx
index 20c27993b41..479ecdb2bcd 100644
--- a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx
+++ b/apps/desktop/src/app/session/hooks/default-new-session.test.tsx
@@ -120,6 +120,56 @@ afterEach(() => {
})
describe('generic new session default routing', () => {
+ it.each(
+ [
+ { name: 'primary window control', query: '/' },
+ { name: 'peer inherited legacy route', query: '/?peer=1&profile=boot-profile&connectionId=' },
+ { name: 'peer inherited local', query: '/?peer=1&profile=other&connectionId=local' },
+ { name: 'peer inherited another remote', query: '/?peer=1&profile=other&connectionId=original-remote' }
+ ].flatMap(source => ['draft', 'slash', 'tile'].map(action => ({ ...source, action })))
+ )('preserves a later device selection for $action: $name', async ({ query, action }) => {
+ // beforeEach establishes the state after selecting `previous`/`other`.
+ // There is no saved app default; launch hints must not repin the draft.
+ window.history.replaceState(null, '', query)
+ const selected = { connectionId: 'previous', profile: 'other' }
+ const { result } = mountActions()
+ expect(resolveNewChatOwnerRoute()).toEqual(selected)
+
+ if (action === 'tile') {
+ await act(() => result.current.openNewSessionTile('right'))
+ } else {
+ if (action === 'slash') {
+ const slash = renderHook(() =>
+ useSlashCommand({
+ activeSessionIdRef: { current: 'existing-runtime' },
+ busyRef: { current: false },
+ selectedStoredSessionIdRef: { current: null },
+ startFreshSessionDraft: result.current.startFreshSessionDraft,
+ requestGateway: vi.fn(async () => ({})),
+ copy: {},
+ getRoutedStoredSessionId: () => null,
+ getRuntimeIdForStoredSession: () => null
+ } as never)
+ )
+
+ await act(() => slash.result.current('/new'))
+ } else {
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ }
+
+ await act(() => result.current.createBackendSessionForSend())
+ }
+
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ selected.connectionId,
+ selected.profile,
+ 'session.create',
+ expect.objectContaining({ profile: selected.profile }),
+ ...FOREGROUND_CREATE_DIAL
+ )
+ expect(getSessionOwnerHint('created-stored')).toEqual(selected)
+ })
+
it.each(['draft', 'tile'])('keeps a legacy default on the profile-only creation path for a %s', async action => {
const { result, requestGateway } = mountActions()
await act(() => setDefaultProfile({ connectionId: null, profile: 'personal' }))
@@ -140,7 +190,7 @@ describe('generic new session default routing', () => {
})
it('keeps a legacy profile peer separate from the app default and the active source', async () => {
- window.history.replaceState(null, '', '/?peer=1&profile=peer-agent')
+ window.history.replaceState(null, '', '/?peer=1&profile=peer-agent&profileWindow=1')
const { result, requestGateway } = mountActions()
await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
@@ -168,27 +218,33 @@ describe('generic new session default routing', () => {
applyConfiguredDefaultProjectDir('')
})
- it('routes /new to the saved default', async () => {
- const { result } = mountActions()
- const slash = renderHook(() =>
- useSlashCommand({
- activeSessionIdRef: { current: 'existing-runtime' },
- busyRef: { current: false },
- selectedStoredSessionIdRef: { current: null },
- startFreshSessionDraft: result.current.startFreshSessionDraft,
- requestGateway: vi.fn(async () => ({})),
- copy: {},
- getRoutedStoredSessionId: () => null,
- getRuntimeIdForStoredSession: () => null
- } as never)
- )
- await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
- await act(() => slash.result.current('/new'))
- expect($newChatRoute.get()).toEqual({ connectionId: 'lab', profile: 'research' })
- })
+ it.each(['/', '/?peer=1&profile=opener&connectionId=opener-host'])(
+ 'routes /new to the saved default in %s',
+ async query => {
+ window.history.replaceState(null, '', query)
+ const { result } = mountActions()
+
+ const slash = renderHook(() =>
+ useSlashCommand({
+ activeSessionIdRef: { current: 'existing-runtime' },
+ busyRef: { current: false },
+ selectedStoredSessionIdRef: { current: null },
+ startFreshSessionDraft: result.current.startFreshSessionDraft,
+ requestGateway: vi.fn(async () => ({})),
+ copy: {},
+ getRoutedStoredSessionId: () => null,
+ getRuntimeIdForStoredSession: () => null
+ } as never)
+ )
+
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ await act(() => slash.result.current('/new'))
+ expect($newChatRoute.get()).toEqual({ connectionId: 'lab', profile: 'research' })
+ }
+ )
it('prefers a profile peer window over the app default after switching away', async () => {
- window.history.replaceState(null, '', '/?peer=1&profile=peer-agent&connectionId=peer-host')
+ window.history.replaceState(null, '', '/?peer=1&profile=peer-agent&connectionId=peer-host&profileWindow=1')
const { result } = mountActions()
await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
diff --git a/apps/desktop/src/app/session/new-session-route.ts b/apps/desktop/src/app/session/new-session-route.ts
index 009f2103c40..b9a65e2fda8 100644
--- a/apps/desktop/src/app/session/new-session-route.ts
+++ b/apps/desktop/src/app/session/new-session-route.ts
@@ -11,7 +11,7 @@ import {
pinLegacyNewChatProfile
} from '@/store/profile'
import { $projectScope, ALL_PROJECTS } from '@/store/projects'
-import { windowProfileOverride } from '@/store/windows'
+import { isPeerInstanceWindow, windowProfileOverride } from '@/store/windows'
/** Only generic New Session actions consult this preference. Explicit profile,
* agent, project and existing-session actions keep their captured owner. */
@@ -22,10 +22,12 @@ export function defaultNewSessionTarget(): { profile: string; route: AgentProfil
return null
}
- const profile = windowProfileOverride()
- const saved = profile
- ? { connectionId: new URLSearchParams(window.location.search).get('connectionId') || null, profile }
- : $defaultProfileRoute.get()
+ const params = new URLSearchParams(window.location.search)
+ // An ordinary New Window inherits its opener only for boot. Reusing that
+ // seed here would undo a later device/profile selection. Only an explicit
+ // "Open profile in new window" makes the peer's launch route a default.
+ const profile = !isPeerInstanceWindow() || params.get('profileWindow') === '1' ? windowProfileOverride() : null
+ const saved = profile ? { connectionId: params.get('connectionId') || null, profile } : $defaultProfileRoute.get()
if (!saved) {
return null