Skip to content

The agent that grows with you

feat(desktop): apply profile defaults to startup and new chats

brooklyn!63d129bf1774
diff --git a/apps/desktop/src/app/gateway/hooks/use-default-profile-preference.ts b/apps/desktop/src/app/gateway/hooks/use-default-profile-preference.ts
new file mode 100644
index 00000000000..cd796119921
--- /dev/null
+++ b/apps/desktop/src/app/gateway/hooks/use-default-profile-preference.ts
@@ -0,0 +1,14 @@
+import { useEffect } from 'react'
+
+import { refreshDefaultProfile, subscribeDefaultProfile } from '@/store/default-profile'
+
+export function useDefaultProfilePreference(): void {
+ useEffect(() => {
+ const unsubscribe = subscribeDefaultProfile()
+ // A failed read leaves the last known preference intact. It must never
+ // prevent gateway boot, and the next boot/menu refresh can retry it.
+ void refreshDefaultProfile().catch(() => undefined)
+
+ return unsubscribe
+ }, [])
+}
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 2bef0496753..1a9c6b284c3 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
@@ -377,6 +377,45 @@ async function advanceBackoff() {
})
}
+describe('default-route profile adoption', () => {
+ it.each([null, 'coder-remote'])(
+ 'dials the saved startup route before an ambient sender can replace it (%s)',
+ async connectionId => {
+ const base = fakeDesktop()
+ const route = { connectionId, profile: 'coder' }
+ const desktop = {
+ ...base,
+ getConnectionFor: vi.fn(async () => ({ ...coderConn, registryScoped: true })),
+ profile: { ...base.profile, getDefault: vi.fn(async () => route) }
+ }
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ render(<Harness />)
+ await flushAsync()
+
+ if (connectionId) {
+ expect(desktop.getConnectionFor).toHaveBeenCalledWith(route)
+ } else {
+ expect(desktop.getConnection).toHaveBeenCalledWith('coder')
+ expect(desktop.getConnectionFor).not.toHaveBeenCalled()
+ }
+ expect($connection.get()?.profile).toBe('coder')
+ expect($desktopBoot.get().running).toBe(false)
+ }
+ )
+
+ it('adopts the resolved backend profile rather than the old last-used preference', async () => {
+ const desktop = fakeDesktop()
+ desktop.getConnection.mockResolvedValue({ ...primaryConn, profile: 'research' })
+ desktop.profile.get.mockResolvedValue({ profile: 'old-last-used' })
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ render(<Harness />)
+ await flushAsync()
+ expect($connection.get()?.profile).toBe('research')
+ expect($activeGatewayProfile.get()).toBe('research')
+ expect($desktopBoot.get().running).toBe(false)
+ })
+})
+
describe('primary failure foreground isolation', () => {
it('ignores a boot snapshot superseded by a successful connection', async () => {
const snapshot = deferred<Awaited<ReturnType<ReturnType<typeof fakeDesktop>['getBootProgress']>>>()
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 94afeec1957..b510158fe52 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -93,9 +93,10 @@ import {
resetTileRuntimeBindings
} from '@/store/session-states'
import { warnIfTerminalBackendUnavailable } from '@/store/terminal-backend-warning'
-import { windowProfileOverride } from '@/store/windows'
+import { isPeerInstanceWindow, windowProfileOverride } from '@/store/windows'
import { stashGatewaySurvivor, survivorIsStale, takeGatewaySurvivor } from './gateway-hmr-survivor'
+import { useDefaultProfilePreference } from './use-default-profile-preference'
// After the reconnect loop has been failing for this long, raise a NON-blocking
// warning toast. Full-screen BootFailureOverlay used to lock the user out of
@@ -172,6 +173,8 @@ export function useGatewayBoot({
refreshHermesConfig,
refreshSessions
}: GatewayBootOptions) {
+ useDefaultProfilePreference()
+
const callbacksRef = useRef({
beforeConnectionSwitch,
handleGatewayEvent,
@@ -583,8 +586,31 @@ export function useGatewayBoot({
// session id against the wrong backend — the HUD then falls back to the
// default profile's last session (#82285). The override wins over the
// stored preference; absent, behavior is unchanged.
- async function adoptPrimaryProfile(shouldPublish: () => boolean = () => true): Promise<boolean> {
- const override = windowProfileOverride()
+ async function getWindowBackend(startup = false): Promise<HermesConnection> {
+ const profile = windowProfileOverride()
+ const peer = isPeerInstanceWindow()
+ const route = profile
+ ? { profile, connectionId: peer ? new URLSearchParams(window.location.search).get('connectionId') : null }
+ : startup && !peer
+ ? await desktop.profile?.getDefault?.()
+ : null
+
+ // Initial registry publication can precede boot. Resolve captured launch
+ // intent explicitly rather than through that still-initializing mirror.
+ if (route?.connectionId && desktop.getConnectionFor) {
+ return desktop.getConnectionFor(route)
+ }
+
+ return desktop.getConnection(route?.profile ?? undefined)
+ }
+
+ async function adoptPrimaryProfile(
+ connection: HermesConnection,
+ shouldPublish: () => boolean = () => true
+ ): Promise<boolean> {
+ // The resolved descriptor reflects the explicit startup default. The
+ // legacy profile.get preference only remembers the last workspace used.
+ const override = windowProfileOverride() ?? connection.profile
try {
const profileKey = override ?? (await desktop.profile?.get?.())?.profile ?? ''
@@ -667,7 +693,7 @@ export function useGatewayBoot({
// shared backend-boot budget rather than the reconnect budget because
// ensureBackend may cold-spawn a pooled helper backend here.
const conn = await withTimeout(
- desktop.getConnection(windowProfileOverride() ?? undefined),
+ getWindowBackend(),
BACKEND_BOOT_WAIT_TIMEOUT_MS,
'Timed out reconnecting to Hermes backend'
)
@@ -707,7 +733,7 @@ export function useGatewayBoot({
// list rather than blanking the rail. NOT awaited: refreshProfiles
// now carries a bounded retry chain (#70679), and switch completion
// must not wait out backoff timers against an unhealthy backend.
- if (!(await adoptPrimaryProfile(ownsSwitch)) || !ownsSwitch()) {
+ if (!(await adoptPrimaryProfile(conn, ownsSwitch)) || !ownsSwitch()) {
return
}
@@ -1128,13 +1154,13 @@ export function useGatewayBoot({
try {
// A profile-pinned helper window (the HUD) dials its target profile's
// backend directly — ensureBackend spawns/reuses it from the pool.
- // Everything else keeps dialing the primary.
+ // Full peers use the source/profile Electron pinned before loading.
// Bounded like the reconnect path (#93454): a wedged main-process
// round-trip must not hang "Starting Hermes…" forever. Initial boot
// rides out a full backend cold spawn, so it gets the shared 45s
// backend-boot budget, not the 20s reconnect budget.
const conn = await withTimeout(
- desktop.getConnection(windowProfileOverride() ?? undefined),
+ getWindowBackend(true),
BACKEND_BOOT_WAIT_TIMEOUT_MS,
'Timed out connecting to Hermes backend'
)
@@ -1197,7 +1223,7 @@ export function useGatewayBoot({
// (cwd seed, config, sessions) are independent REST calls — running
// them serially added their sum to time-to-populated-sidebar when only
// the max is needed.
- await adoptPrimaryProfile()
+ await adoptPrimaryProfile(conn)
setDesktopBootStep({
phase: 'renderer.config',
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
new file mode 100644
index 00000000000..afaaa162b17
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/default-new-session.test.tsx
@@ -0,0 +1,251 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { DesktopProfileRoute } from '@/global'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { $defaultProfileRoute, setDefaultProfile } from '@/store/default-profile'
+import { requestGatewayForAgent } from '@/store/gateway'
+import {
+ $activeGatewayProfile,
+ $newChatConnectionId,
+ $newChatProfile,
+ $newChatRoute,
+ captureNewChatSource,
+ ensureGatewayAgent,
+ ensureGatewayProfile,
+ resolveNewChatOwnerRoute
+} from '@/store/profile'
+import { $projectScope, ALL_PROJECTS } from '@/store/projects'
+import {
+ $activeSessionId,
+ $sessions,
+ _resetSessionOwnerHintsForTests,
+ applyConfiguredDefaultProjectDir,
+ getSessionOwnerHint,
+ setActiveSessionId,
+ setConnection,
+ setSessions
+} from '@/store/session'
+
+import { useSlashCommand } from './use-prompt-actions/slash'
+import { useSessionActions } from './use-session-actions'
+
+vi.mock('@/store/profile', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ ensureGatewayAgent: vi.fn(async () => undefined),
+ ensureGatewayProfile: vi.fn(async () => undefined)
+}))
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ activeGatewayConnectionId: vi.fn(() => 'previous'),
+ requestGatewayForAgent: vi.fn(),
+ retainGatewayForAgent: vi.fn(async () => () => undefined)
+}))
+
+function mountActions() {
+ const ref = <T,>(current: T) => ({ current })
+ const requestGateway = vi.fn(async () => ({ session_id: 'ambient', stored_session_id: 'ambient-stored' }) as never)
+ const navigate = vi.fn()
+ const state = createClientSessionState()
+ const result = renderHook(() =>
+ useSessionActions({
+ activeSessionId: 'existing-runtime',
+ activeSessionIdRef: ref<string | null>('existing-runtime'),
+ busyRef: ref(false),
+ creatingSessionRef: ref(false),
+ ensureSessionState: () => state,
+ getRouteToken: () => 'route',
+ getRoutedStoredSessionId: () => null,
+ navigate,
+ requestGateway,
+ resetViewSync: vi.fn(),
+ runtimeIdByStoredSessionIdRef: ref(new Map()),
+ selectedStoredSessionId: null,
+ selectedStoredSessionIdRef: ref<string | null>(null),
+ sessionStateByRuntimeIdRef: ref(new Map()),
+ syncSessionStateToView: vi.fn(),
+ updateSessionState: () => state
+ })
+ )
+ return { ...result, navigate, requestGateway }
+}
+
+beforeEach(() => {
+ _resetSessionOwnerHintsForTests()
+ $defaultProfileRoute.set(null)
+ $newChatRoute.set({ connectionId: 'previous', profile: 'other' })
+ $newChatProfile.set('other')
+ $newChatConnectionId.set('previous')
+ $activeGatewayProfile.set('other')
+ $projectScope.set(ALL_PROJECTS)
+ setSessions([])
+ setActiveSessionId('existing-runtime')
+ setConnection({
+ baseUrl: 'http://localhost:7070',
+ connectionId: 'previous',
+ isFullscreen: false,
+ logs: [],
+ mode: 'remote',
+ nativeOverlayWidth: 0,
+ token: '',
+ windowButtonPosition: null,
+ wsUrl: 'ws://localhost:7070'
+ })
+ window.hermesDesktop = { profile: { setDefault: async (route: DesktopProfileRoute) => route } } as never
+ vi.mocked(requestGatewayForAgent).mockReset()
+ vi.mocked(requestGatewayForAgent).mockResolvedValue({
+ session_id: 'created',
+ stored_session_id: 'created-stored',
+ info: {}
+ })
+})
+
+afterEach(() => {
+ cleanup()
+ applyConfiguredDefaultProjectDir('')
+ window.history.replaceState(null, '', '/')
+ $defaultProfileRoute.set(null)
+ $newChatRoute.set(null)
+ $newChatProfile.set(null)
+ $newChatConnectionId.set(null)
+ captureNewChatSource(null)
+ setActiveSessionId(null)
+ setConnection(null)
+ setSessions([])
+ vi.clearAllMocks()
+})
+
+describe('generic new session default routing', () => {
+ 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' }))
+
+ if (action === 'draft') {
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ expect(resolveNewChatOwnerRoute()).toBeNull()
+ await act(() => result.current.createBackendSessionForSend())
+ } else {
+ await act(() => result.current.openNewSessionTile('right'))
+ }
+
+ expect(ensureGatewayProfile).toHaveBeenCalledWith('personal', { forceLegacyRoute: true })
+ expect(ensureGatewayAgent).not.toHaveBeenCalledWith('local', 'personal')
+ expect(ensureGatewayAgent).not.toHaveBeenCalledWith('previous', 'personal')
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ expect(requestGateway).toHaveBeenCalledWith('session.create', expect.objectContaining({ profile: 'personal' }))
+ })
+
+ 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')
+ const { result, requestGateway } = mountActions()
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ expect(resolveNewChatOwnerRoute()).toBeNull()
+ await act(() => result.current.createBackendSessionForSend())
+ expect(ensureGatewayProfile).toHaveBeenCalledWith('peer-agent', { forceLegacyRoute: true })
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ expect(requestGateway).toHaveBeenCalledWith('session.create', expect.objectContaining({ profile: 'peer-agent' }))
+ })
+
+ it('keeps an explicit legacy-profile tile request ahead of both defaults', async () => {
+ const { result, requestGateway } = mountActions()
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ await act(() => result.current.openNewSessionTile('right', { profile: 'chosen', route: null }))
+ expect(requestGateway).toHaveBeenCalledWith('session.create', expect.objectContaining({ profile: 'chosen' }))
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ })
+
+ it('does not mistake the configured default folder for explicit project routing', async () => {
+ applyConfiguredDefaultProjectDir('/configured-default')
+ const { result } = mountActions()
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ expect($newChatRoute.get()).toEqual({ connectionId: 'lab', profile: 'research' })
+ 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('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')
+ const { result } = mountActions()
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ await act(() => result.current.createBackendSessionForSend())
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'peer-host',
+ 'peer-agent',
+ 'session.create',
+ expect.objectContaining({ profile: 'peer-agent' })
+ )
+ })
+
+ it.each([
+ { options: undefined, connectionId: 'lab', profile: 'research' },
+ { options: { profile: 'chosen' }, connectionId: 'previous', profile: 'chosen' },
+ {
+ options: { route: { connectionId: 'chosen-host', profile: 'chosen' } },
+ connectionId: 'chosen-host',
+ profile: 'chosen'
+ },
+ { options: { cwd: '/clicked-project' }, connectionId: 'previous', profile: 'other' }
+ ])(
+ 'routes tiles by explicit intent before the saved default: $profile',
+ async ({ options, connectionId, profile }) => {
+ const { result } = mountActions()
+ await act(() => setDefaultProfile({ connectionId: 'lab', profile: 'research' }))
+ await act(() => result.current.openNewSessionTile('right', options))
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ connectionId,
+ profile,
+ 'session.create',
+ expect.objectContaining({ profile })
+ )
+ expect(getSessionOwnerHint('created-stored')).toEqual({ connectionId, profile })
+ }
+ )
+
+ it.each([
+ { connectionId: 'lab', profile: 'research' },
+ { connectionId: 'local', profile: 'personal' }
+ ])('uses the saved exact owner only for a new draft: $connectionId/$profile', async saved => {
+ const { result, requestGateway } = mountActions()
+ await act(() => setDefaultProfile(saved))
+ expect($activeSessionId.get()).toBe('existing-runtime')
+ expect($newChatProfile.get()).toBe('other')
+
+ act(() => result.current.selectSidebarItem({ action: 'new-session' } as never))
+ await act(() => result.current.createBackendSessionForSend('hello'))
+
+ const expected = saved
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ expected.connectionId,
+ expected.profile,
+ 'session.create',
+ expect.objectContaining({ profile: expected.profile })
+ )
+ expect(getSessionOwnerHint('created-stored')).toEqual(expected)
+ expect($sessions.get().find(row => row.id === 'created-stored')).toMatchObject({
+ connection_id: expected.connectionId,
+ profile: expected.profile
+ })
+ expect(requestGateway).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
index c65106dff46..f83cf41bc44 100644
--- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
+++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
@@ -5,7 +5,9 @@ import { useEffect, useMemo, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
import { createSessionRpcDispatcher } from '@/app/contrib/session-rpc-dispatcher'
+import { prepareDefaultNewSession } from '@/app/session/new-session-route'
import { getSession } from '@/hermes'
+import { $defaultProfileRoute } from '@/store/default-profile'
import {
activeGateway,
activeGatewayConnectionId,
@@ -19,8 +21,11 @@ import {
$newChatConnectionId,
$newChatProfile,
$newChatRoute,
+ captureNewChatSource,
ensureGatewayAgent,
newSessionInProfile,
+ pinLegacyNewChatProfile,
+ resolveNewChatOwnerRoute,
selectProfile
} from '@/store/profile'
import {
@@ -41,6 +46,7 @@ import {
setSessions
} from '@/store/session'
import { foregroundSessionScopes } from '@/store/session-states'
+import { deferred } from '@/test/deferred'
import type { SessionInfo } from '@/types/hermes'
import type { ClientSessionState } from '../../types'
@@ -257,6 +263,7 @@ function makePrimary(): MockGateway {
interface HarnessHandle {
busyRef: { current: boolean }
bindings: () => { runtimeForStored: null | string; storedForRuntime: null | string }
+ createSession: () => Promise<string | null>
submitText: (text: string, options?: SubmitTextOptions) => Promise<boolean>
updateSessionState: (
sessionId: string,
@@ -353,6 +360,7 @@ function Harness({
runtimeForStored: cache.runtimeIdByStoredSessionIdRef.current.get(mintedStoredId) ?? null,
storedForRuntime: cache.sessionStateByRuntimeIdRef.current.get(mintedRuntimeId)?.storedSessionId ?? null
}),
+ createSession: () => act(async () => sessionActions.createBackendSessionForSend()) as Promise<string | null>,
submitText: (...args) => act(async () => submitText(...args)) as Promise<boolean>,
updateSessionState: cache.updateSessionState as HarnessHandle['updateSessionState']
})
@@ -361,6 +369,7 @@ function Harness({
cache.sessionStateByRuntimeIdRef,
cache.updateSessionState,
onReady,
+ sessionActions.createBackendSessionForSend,
submitText
])
@@ -395,7 +404,8 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across
setAwaitingResponse(false)
$newChatProfile.set(null)
$newChatRoute.set(null)
- $newChatConnectionId.set(null)
+ captureNewChatSource(null)
+ $defaultProfileRoute.set(null)
_resetSessionOwnerHintsForTests({ storage: true })
})
@@ -408,7 +418,8 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across
setConnection(null)
$newChatProfile.set(null)
$newChatRoute.set(null)
- $newChatConnectionId.set(null)
+ captureNewChatSource(null)
+ $defaultProfileRoute.set(null)
$activeGatewayProfile.set('default')
vi.clearAllMocks()
delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
@@ -483,6 +494,90 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across
const calls = (socket: MockGateway) => socket.request.mock.calls.map(call => call[0] as string)
+ it('an ordinary profile pick supersedes the legacy default pin on the active registry source', async () => {
+ setPrimaryGateway(makePrimary() as never, 'default')
+ await ensureGatewayAgent(SOURCE_ID, 'default')
+ pinLegacyNewChatProfile('omar')
+ expect(resolveNewChatOwnerRoute()).toBeNull()
+
+ selectProfile('omar')
+ expect(resolveNewChatOwnerRoute()).toEqual({ connectionId: SOURCE_ID, profile: 'omar' })
+ await waitFor(() => expect(activeGatewayProfileKey()).toBe('omar'))
+ expect(activeGatewayConnectionId()).toBe(SOURCE_ID)
+ expect(window.hermesDesktop.getConnection).not.toHaveBeenCalledWith('omar')
+ })
+
+ it.each([
+ { connectionId: null, activeProfile: 'default' },
+ { connectionId: 'local', activeProfile: 'default' },
+ { connectionId: null, activeProfile: 'omar' }
+ ])('captures the saved $connectionId default before activation from remote $activeProfile', async ({ connectionId, activeProfile }) => {
+ const primary = makePrimary()
+ setPrimaryGateway(primary as never, 'default')
+ await ensureGatewayAgent(SOURCE_ID, activeProfile)
+ ownerPort = connectionId === null ? V1_PORT : OMAR_PORT
+ const activation = deferred<void>()
+ const desktop = window.hermesDesktop!
+ vi.mocked(desktop.getConnectionFor!).mockClear()
+ const getConnection = vi.mocked(desktop.getConnection).getMockImplementation()!
+ const getConnectionFor = vi.mocked(desktop.getConnectionFor!).getMockImplementation()!
+
+ vi.mocked(desktop.getConnection).mockImplementation(async profile => {
+ await activation.promise
+ return { ...(await getConnection(profile)), mode: 'remote' }
+ })
+ vi.mocked(desktop.getConnectionFor!).mockImplementation(async route => {
+ await activation.promise
+ return getConnectionFor(route)
+ })
+
+ const ambientRequest = vi.fn(async (method: string, params?: Record<string, unknown>) =>
+ (activeGateway() as unknown as MockGateway).request(method, params)
+ )
+ let handle: HarnessHandle | null = null
+ render(<Harness ambientRequest={ambientRequest} onReady={h => (handle = h)} />)
+ await waitFor(() => expect(handle).not.toBeNull())
+ $defaultProfileRoute.set({ connectionId, profile: 'omar' })
+ let creating!: Promise<string | null>
+
+ try {
+ act(() => prepareDefaultNewSession())
+ expect(activeGatewayConnectionId()).toBe(SOURCE_ID)
+ expect(resolveNewChatOwnerRoute()).toEqual(connectionId === null ? null : { connectionId, profile: 'omar' })
+ creating = handle!.createSession()
+ expect(runtimeOwner).toBeNull()
+ } finally {
+ activation.resolve()
+ }
+
+ await expect(creating).resolves.toBe(mintedRuntimeId)
+ await expect(handle!.submitText('first prompt')).resolves.toBe(true)
+ await settleTurn(handle!)
+ await expect(handle!.submitText('second prompt')).resolves.toBe(true)
+ const owner = sockets.find(socket => socket.connectUrl?.includes(`:${ownerPort}`))!
+ expect(runtimeOwner).toBe(owner)
+ expect(calls(owner).filter(method => method === 'session.create')).toHaveLength(1)
+ expect(calls(owner).filter(method => method === 'prompt.submit')).toHaveLength(2)
+ expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: SOURCE_ID, profile: 'omar' })
+
+ if (connectionId === null) {
+ expect(desktop.getConnection).toHaveBeenCalledWith('omar')
+ expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })
+ expect($connection.get()?.mode).toBe('remote')
+ expect(getSessionOwnerHint(mintedStoredId)).toBeUndefined()
+ } else {
+ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })
+ expect(desktop.getConnection).not.toHaveBeenCalledWith('omar')
+ expect(getSessionOwnerHint(mintedStoredId)).toEqual({ connectionId, profile: 'omar' })
+ }
+
+ for (const socket of [primary, ...sockets]) {
+ if (socket !== owner) {
+ expect(socket.request.mock.calls.filter(call => sessionScoped(call[1]) || call[0] === 'session.create')).toEqual([])
+ }
+ }
+ })
+
it('dials homelab::omar when boot published homelab on the active primary gateway', async () => {
const primary = makePrimary()
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index 44dc819ffdc..db873644551 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@ -2,6 +2,7 @@ import { skillInvocationText } from '@hermes/shared'
import { parseCommandDispatch, parseSlashCommand } from '@hermes/shared'
import { type MutableRefObject, useCallback, useRef } from 'react'
+import { prepareDefaultNewSession } from '@/app/session/new-session-route'
import { getProfiles } from '@/hermes'
import type { Translations } from '@/i18n'
import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
@@ -495,6 +496,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {
// new branch in a dispatch ladder.
const actionHandlers: Record<DesktopActionId, (ctx: SlashActionCtx) => Promise<void>> = {
new: async () => {
+ prepareDefaultNewSession()
startFreshSessionDraft()
},
branch: async () => {
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 76779987317..635e836d42f 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -4,6 +4,7 @@ import type { NavigateFunction } from 'react-router'
import { NO_PROJECT_ID } from '@/app/chat/sidebar/projects/workspace-groups'
import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'
+import { defaultNewSessionTarget, prepareDefaultNewSession } from '@/app/session/new-session-route'
import { revealTreePane } from '@/components/pane-shell/tree/store'
import { setWorkspaceScope } from '@/components/pane-shell/workspace-scope'
import {
@@ -48,6 +49,7 @@ import {
type AgentProfileRoute,
ensureGatewayAgent,
ensureGatewayProfile,
+ isLegacyNewChatProfile,
normalizeProfileKey,
resolveNewChatOwnerRoute
} from '@/store/profile'
@@ -292,7 +294,9 @@ function reconcileAuthoritativeMessages(
// value is a mirror of Settings → Model and must not pin the new chat.
async function desktopSessionCreateParams(
cwd: string,
- capturedRoute = resolveNewChatOwnerRoute()
+ capturedRoute = resolveNewChatOwnerRoute(),
+ requestedProfile?: string,
+ legacyProfileIntent = false
): Promise<Record<string, unknown>> {
// Treat Send as the linearization point for the visible selector state. The
// profile handshake below can yield long enough for background config/model
@@ -311,10 +315,13 @@ async function desktopSessionCreateParams(
provider: isManualSelection ? $currentProvider.get().trim() : ''
}
- const profile = capturedRoute?.profile || $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())
+ const profile =
+ capturedRoute?.profile || requestedProfile || $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())
if (capturedRoute) {
await ensureGatewayAgent(capturedRoute.connectionId, profile)
+ } else if (legacyProfileIntent) {
+ await ensureGatewayProfile(profile, { forceLegacyRoute: true })
} else {
await ensureGatewayProfile(profile)
}
@@ -588,9 +595,11 @@ export function useSessionActions({
// reduce the owner to a bare profile name that later RPCs dial on a
// different socket than the one that minted the runtime.
const capturedRoute = resolveNewChatOwnerRoute()
+ const capturedProfile = $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())
+ const legacyProfileIntent = isLegacyNewChatProfile(capturedProfile)
const params = {
- ...(await desktopSessionCreateParams(cwd, capturedRoute)),
+ ...(await desktopSessionCreateParams(cwd, capturedRoute, capturedProfile, legacyProfileIntent)),
...sessionCreateOverrideParams(createOverrides, seedMessages)
}
@@ -737,6 +746,7 @@ export function useSessionActions({
const selectSidebarItem = useCallback(
(item: SidebarNavItem) => {
if (item.action === 'new-session') {
+ prepareDefaultNewSession()
setWorkspaceScope('sessions')
startFreshSessionDraft()
@@ -782,7 +792,16 @@ export function useSessionActions({
// `options?.cwd || resolve…` is wrong for Home: null is falsy and used
// to fall through into the last project folder while main chat was
// occupied (openTab path for "New session in Home").
- const capturedRoute = options?.route !== undefined ? options.route : resolveNewChatOwnerRoute(options?.profile)
+ const explicitTarget =
+ options?.profile !== undefined || options?.cwd !== undefined || options?.workspaceScope?.ownerRoute !== undefined
+
+ const defaultTarget = options?.route === undefined && !explicitTarget ? defaultNewSessionTarget() : null
+
+ const capturedRoute =
+ options?.route !== undefined
+ ? options.route
+ : options?.workspaceScope?.ownerRoute ??
+ (defaultTarget ? defaultTarget.route : resolveNewChatOwnerRoute(options?.profile))
// A named local profile uses the legacy profile-only transport (no
// connectionId). Tab-strip "+" omits `options.profile`; the draft or
@@ -791,7 +810,7 @@ export function useSessionActions({
const requestedProfile = normalizeProfileKey(
typeof options?.profile === 'string' && options.profile
? options.profile
- : $newChatProfile.get() || $activeGatewayProfile.get()
+ : defaultTarget?.profile || $newChatProfile.get() || $activeGatewayProfile.get()
)
const legacyOwnerProfile =
@@ -813,7 +832,12 @@ export function useSessionActions({
options?.cwd === null ? '' : typeof options?.cwd === 'string' ? options.cwd.trim() : resolveNewSessionCwd()
const params = {
- ...(await desktopSessionCreateParams(cwd, capturedRoute)),
+ ...(await desktopSessionCreateParams(
+ cwd,
+ capturedRoute,
+ requestedProfile,
+ options?.route === null || defaultTarget?.route === null
+ )),
...(workspaceScope.workspaceMode === 'bots' ? { hidden: true } : {})
}
diff --git a/apps/desktop/src/app/session/new-session-route.ts b/apps/desktop/src/app/session/new-session-route.ts
new file mode 100644
index 00000000000..009f2103c40
--- /dev/null
+++ b/apps/desktop/src/app/session/new-session-route.ts
@@ -0,0 +1,64 @@
+import { NO_PROJECT_ID } from '@/app/chat/sidebar/projects/workspace-groups'
+import { $defaultProfileRoute } from '@/store/default-profile'
+import { notifyError } from '@/store/notifications'
+import {
+ $newChatProfile,
+ $newChatRoute,
+ type AgentProfileRoute,
+ captureNewChatSource,
+ ensureGatewayAgent,
+ ensureGatewayProfile,
+ pinLegacyNewChatProfile
+} from '@/store/profile'
+import { $projectScope, ALL_PROJECTS } from '@/store/projects'
+import { windowProfileOverride } from '@/store/windows'
+
+/** Only generic New Session actions consult this preference. Explicit profile,
+ * agent, project and existing-session actions keep their captured owner. */
+export function defaultNewSessionTarget(): { profile: string; route: AgentProfileRoute | null } | null {
+ const project = $projectScope.get()
+
+ if (project !== ALL_PROJECTS && project !== NO_PROJECT_ID) {
+ return null
+ }
+
+ const profile = windowProfileOverride()
+ const saved = profile
+ ? { connectionId: new URLSearchParams(window.location.search).get('connectionId') || null, profile }
+ : $defaultProfileRoute.get()
+
+ if (!saved) {
+ return null
+ }
+
+ // A captured target can explicitly choose the legacy profile door (null
+ // route), distinct from no default and from the override-bypassing `local`.
+ return {
+ profile: saved.profile,
+ route: saved.connectionId === null ? null : { connectionId: saved.connectionId, profile: saved.profile }
+ }
+}
+
+export function prepareDefaultNewSession(): void {
+ const target = defaultNewSessionTarget()
+
+ if (!target) {
+ return
+ }
+
+ if (target.route) {
+ $newChatProfile.set(target.profile)
+ $newChatRoute.set(target.route)
+ captureNewChatSource(target.route.connectionId)
+ } else {
+ pinLegacyNewChatProfile(target.profile)
+ }
+
+ const activation = target.route
+ ? ensureGatewayAgent(target.route.connectionId, target.profile)
+ : ensureGatewayProfile(target.profile, { forceLegacyRoute: true })
+
+ void activation.catch(error => {
+ notifyError(error, `Failed to open profile "${target.profile}"`)
+ })
+}
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 3238debb641..62410210b7b 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -8,6 +8,7 @@ import { deferred } from '../test/deferred'
const $activeGatewayProfile = atom('default')
const $newChatProfile = atom<null | string>(null)
+const $freshSessionRequest = atom(0)
const $showAllProfiles = atom(false)
const $connection = atom<null | {
@@ -59,7 +60,7 @@ const endGatewaySwitch = vi.fn((token?: number) => {
const recoverActiveSourceAfterFailedGatewaySwitch = vi.fn()
-vi.mock('@/store/session', () => ({ $connection }))
+vi.mock('@/store/session', () => ({ $connection, $activeSessionId, $selectedStoredSessionId: atom(null) }))
vi.mock('@/store/gateway-switch', () => ({
$gatewaySwitching,
beginGatewaySwitch,
@@ -69,6 +70,7 @@ vi.mock('@/store/gateway-switch', () => ({
}))
vi.mock('@/store/profile', () => ({
$activeGatewayProfile,
+ $freshSessionRequest,
$newChatProfile,
$showAllProfiles,
captureNewChatSource: vi.fn(),
@@ -148,7 +150,7 @@ beforeEach(() => {
api.mockResolvedValue({ profiles: [] })
setApiRequestConnection(null)
setApiRequestProfile(null)
- vi.stubGlobal('window', { hermesDesktop: { api, connections: { list, setLastUsed } }, localStorage })
+ vi.stubGlobal('window', { hermesDesktop: { api, connections: { list, setLastUsed } }, localStorage, location: window.location })
})
afterEach(() => vi.unstubAllGlobals())
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index cdd83e6e234..0aab5ecb537 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -5,6 +5,7 @@ import type { DesktopConnectionsRegistry } from '@/global'
import { persistStringRecord, storedStringRecord } from '@/lib/storage'
import { BACKEND_BOOT_WAIT_TIMEOUT_MS, isTimeoutError, withTimeout } from '@/lib/with-timeout'
import { $connectionsRegistry } from '@/store/connection-registry-state'
+import { $defaultProfileRoute, refreshDefaultProfile } from '@/store/default-profile'
import {
beginGatewaySwitch,
endGatewaySwitch,
@@ -13,6 +14,7 @@ import {
} from '@/store/gateway-switch'
import {
$activeGatewayProfile,
+ $freshSessionRequest,
$newChatProfile,
$showAllProfiles,
captureNewChatSource,
@@ -22,7 +24,8 @@ import {
refreshActiveProfile,
requestFreshSession
} from '@/store/profile'
-import { $connection } from '@/store/session'
+import { $activeSessionId, $connection, $selectedStoredSessionId } from '@/store/session'
+import { isPeerInstanceWindow, windowProfileOverride } from '@/store/windows'
const LAST_PROFILE_STORAGE_KEY = 'hermes.desktop.lastProfileByConnection'
@@ -185,14 +188,24 @@ function waitForInitialConnection(): Promise<void> {
}
/**
- * Load the registry once for Sessions and restore the last successfully used
- * source. Later registry refreshes stay side-effect free, so editing Settings
- * in another window never changes the active workspace.
+ * Load the registry once for Sessions and restore the explicit default route,
+ * otherwise the last successfully used source. Later registry refreshes stay
+ * side-effect free, so editing Settings in another window never changes the
+ * active workspace.
*/
export async function initializeConnectionsRegistry(): Promise<DesktopConnectionsRegistry | null> {
- const registry = await refreshConnectionsRegistry()
+ const freshSessionRequest = $freshSessionRequest.get()
+ const [registry, defaultLoaded] = await Promise.all([
+ refreshConnectionsRegistry(),
+ refreshDefaultProfile().then(
+ () => true,
+ () => false
+ )
+ ])
- if (!registry || restoreAttempted) {
+ // Main may already have opened the explicit default. A failed preference
+ // read is not evidence of an absent preference; keep that live route.
+ if (!registry || !defaultLoaded || restoreAttempted || isPeerInstanceWindow() || windowProfileOverride()) {
return registry
}
@@ -203,10 +216,34 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection
// (statusbar switcher, fleet profile rail) is not drift to "restore" over.
// The launch preference only decides where a window lands when nobody has
// said otherwise yet.
- if (switchRevision > 0 || pendingTarget !== null) {
+ if (switchRevision > 0 || pendingTarget !== null || $freshSessionRequest.get() !== freshSessionRequest) {
return registry
}
+ // An explicit default is stronger than the registry's last-used preference,
+ // including the last profile remembered on the SAME source. A legacy null
+ // route is already resolved by main's ensureBackend(profile), including any
+ // per-profile remote override; the registry must not reinterpret it as local.
+ const defaultRoute = $defaultProfileRoute.get()
+
+ if (defaultRoute) {
+ if ($activeSessionId.get() || $selectedStoredSessionId.get()) {
+ return registry
+ }
+
+ const connectionId = defaultRoute.connectionId
+
+ if (connectionId === null) {
+ return registry
+ }
+
+ if (registry.connections.some(connection => connection.id === connectionId)) {
+ await selectConnection(connectionId, { profile: defaultRoute.profile })
+ }
+
+ return $connectionsRegistry.get() ?? registry
+ }
+
// Residual drift: a window can be live on a source the registry cannot name
// (a v1-configured remote that reconciliation has not repaired yet, e.g. a
// read-only userData that rejected the healed write). $activeConnectionId is
diff --git a/apps/desktop/src/store/default-profile-startup.test.ts b/apps/desktop/src/store/default-profile-startup.test.ts
new file mode 100644
index 00000000000..da05a386ad7
--- /dev/null
+++ b/apps/desktop/src/store/default-profile-startup.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { DesktopConnectionsRegistry, DesktopProfileRoute, HermesConnection } from '@/global'
+import { deferred } from '@/test/deferred'
+
+import { _resetConnectionsForTests, initializeConnectionsRegistry } from './connections'
+import { $defaultProfileRoute } from './default-profile'
+import { ensureGatewayForAgent, openGatewayForAgent } from './gateway'
+import { $activeGatewayProfile, pinNewChatProfile, requestFreshSession } from './profile'
+import { $connection, setActiveSessionId, setConnection } from './session'
+
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ ensureGatewayForAgent: vi.fn(async () => ({})),
+ openGatewayForAgent: vi.fn(async () => ({}))
+}))
+
+const registry: DesktopConnectionsRegistry = {
+ connections: [
+ { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false },
+ { id: 'lab', kind: 'remote', label: 'Lab', tokenPreview: null, tokenSet: false }
+ ],
+ primary: 'lab',
+ lastUsed: 'lab',
+ launchMode: 'last-used',
+ secureTokenStorage: true,
+ version: 2
+}
+
+function descriptor(connectionId: string, profile: string): HermesConnection {
+ return {
+ baseUrl: 'http://localhost:7070',
+ connectionId,
+ isFullscreen: false,
+ logs: [],
+ mode: connectionId === 'local' ? 'local' : 'remote',
+ nativeOverlayWidth: 0,
+ profile,
+ registryScoped: true,
+ token: '',
+ windowButtonPosition: null,
+ wsUrl: 'ws://localhost:7070'
+ }
+}
+
+beforeEach(() => {
+ _resetConnectionsForTests()
+ $defaultProfileRoute.set(null)
+ window.history.replaceState(null, '', '/')
+ $activeGatewayProfile.set('personal')
+ setConnection(descriptor('local', 'personal'))
+ window.hermesDesktop = {
+ connections: {
+ list: async () => registry,
+ setLastUsed: async (id: string) => ({ ok: true, registry: { ...registry, lastUsed: id } })
+ },
+ getConnectionFor: async ({ connectionId, profile }: DesktopProfileRoute) =>
+ descriptor(connectionId ?? 'local', profile),
+ profile: { getDefault: async () => null },
+ api: async ({ path }: { path: string }) =>
+ path.includes('active')
+ ? { active: $activeGatewayProfile.get(), current: $activeGatewayProfile.get() }
+ : { profiles: [] }
+ } as never
+})
+
+afterEach(() => {
+ window.history.replaceState(null, '', '/')
+ setConnection(null)
+ setActiveSessionId(null)
+ $defaultProfileRoute.set(null)
+ vi.clearAllMocks()
+})
+
+describe('startup default route', () => {
+ it('does not replace the main-process route after a transient preference read failure', async () => {
+ window.hermesDesktop.profile.getDefault = async () => {
+ throw new Error('IPC interrupted')
+ }
+ await initializeConnectionsRegistry()
+ expect($connection.get()).toMatchObject({ connectionId: 'local', profile: 'personal' })
+ expect(openGatewayForAgent).not.toHaveBeenCalled()
+ })
+
+ it('does not override a profile picked while the preference read was pending', async () => {
+ const reading = deferred<DesktopProfileRoute>()
+ window.hermesDesktop.profile.getDefault = () => reading.promise
+ const initializing = initializeConnectionsRegistry()
+ pinNewChatProfile('chosen')
+ requestFreshSession()
+ reading.resolve({ connectionId: 'lab', profile: 'research' })
+ await initializing
+ expect(openGatewayForAgent).not.toHaveBeenCalled()
+ expect($connection.get()).toMatchObject({ connectionId: 'local', profile: 'personal' })
+ })
+
+ it('does not re-home an already selected session when the preference loads', async () => {
+ setActiveSessionId('session-already-open')
+ window.hermesDesktop.profile.getDefault = async () => ({ connectionId: 'lab', profile: 'research' })
+ await initializeConnectionsRegistry()
+ expect(openGatewayForAgent).not.toHaveBeenCalled()
+ })
+
+ it('keeps the native legacy default and its per-profile remote override out of registry restoration', async () => {
+ setConnection({ ...descriptor('lab', 'personal'), registryScoped: false })
+ window.hermesDesktop.profile.getDefault = async () => ({ connectionId: null, profile: 'personal' })
+ await initializeConnectionsRegistry()
+ expect($connection.get()).toMatchObject({ connectionId: 'lab', profile: 'personal', registryScoped: false })
+ expect(openGatewayForAgent).not.toHaveBeenCalled()
+ expect(ensureGatewayForAgent).not.toHaveBeenCalled()
+ })
+
+ it('restores the saved profile, not last-used source/profile, across local → remote → local', async () => {
+ for (const route of [
+ { connectionId: 'local', profile: 'personal' },
+ { connectionId: 'lab', profile: 'research' },
+ { connectionId: 'local', profile: 'personal' }
+ ]) {
+ _resetConnectionsForTests()
+ window.hermesDesktop.profile.getDefault = async () => route
+ await initializeConnectionsRegistry()
+ expect($connection.get()).toMatchObject({ connectionId: route.connectionId ?? 'local', profile: route.profile })
+ expect($activeGatewayProfile.get()).toBe(route.profile)
+ }
+ expect(ensureGatewayForAgent).toHaveBeenCalledWith('lab', 'research', expect.anything())
+ expect(ensureGatewayForAgent).toHaveBeenCalledWith('local', 'personal', expect.anything())
+ })
+
+ it('leaves profile peer windows on their requested source rather than restoring the application default', async () => {
+ window.history.replaceState(null, '', '/?peer=1&profile=personal&connectionId=local')
+ window.hermesDesktop.profile.getDefault = async () => ({ connectionId: 'lab', profile: 'research' })
+ await initializeConnectionsRegistry()
+ expect($connection.get()).toMatchObject({ connectionId: 'local', profile: 'personal' })
+ expect(openGatewayForAgent).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/store/default-profile.test.ts b/apps/desktop/src/store/default-profile.test.ts
new file mode 100644
index 00000000000..f3193bac8a7
--- /dev/null
+++ b/apps/desktop/src/store/default-profile.test.ts
@@ -0,0 +1,63 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { useDefaultProfilePreference } from '@/app/gateway/hooks/use-default-profile-preference'
+import type { DesktopProfileRoute } from '@/global'
+import { deferred } from '@/test/deferred'
+
+import * as preference from './default-profile'
+
+// The native bridge is the persistence boundary; the renderer owns only a mirror.
+afterEach(() => {
+ cleanup()
+ vi.unstubAllGlobals()
+})
+
+describe('default profile preference', () => {
+ it('subscribes before loading, mirrors cross-window changes, and tears down', async () => {
+ const oldRoute = { connectionId: null, profile: 'personal' }
+ const nextRoute = { connectionId: 'lab', profile: 'research' }
+ const read = deferred<typeof oldRoute>()
+ let listener!: (route: DesktopProfileRoute | null) => void
+ const off = vi.fn()
+ const onDefaultChanged = vi.fn(callback => {
+ listener = callback
+ return off
+ })
+ const getDefault = vi.fn(() => {
+ expect(onDefaultChanged).toHaveBeenCalledTimes(1)
+ return read.promise
+ })
+ vi.stubGlobal('window', { hermesDesktop: { profile: { getDefault, onDefaultChanged } } })
+ const { unmount } = renderHook(useDefaultProfilePreference)
+
+ await act(async () => {
+ listener(nextRoute)
+ read.resolve(oldRoute)
+ await read.promise
+ })
+ expect(preference.$defaultProfileRoute.get()).toEqual(nextRoute)
+ unmount()
+ expect(off).toHaveBeenCalledTimes(1)
+ })
+
+ it('publishes only successful native writes and rejects stale refreshes', async () => {
+ const first = { connectionId: null, profile: 'personal' }
+ const second = { connectionId: 'lab', profile: 'research' }
+ const read = deferred<typeof first>()
+ const getDefault = vi.fn(() => read.promise)
+ const setDefault = vi.fn(async () => second)
+ vi.stubGlobal('window', { hermesDesktop: { profile: { getDefault, setDefault } } })
+
+ const refreshing = preference.refreshDefaultProfile()
+ await preference.setDefaultProfile(second)
+ read.resolve(first)
+ await refreshing
+ expect(preference.$defaultProfileRoute.get()).toEqual(second)
+
+ setDefault.mockRejectedValueOnce(new Error('read-only preferences'))
+ await expect(preference.setDefaultProfile(first)).rejects.toThrow('read-only preferences')
+ expect(preference.$defaultProfileRoute.get()).toEqual(second)
+ expect(setDefault).toHaveBeenLastCalledWith(first)
+ })
+})
diff --git a/apps/desktop/src/store/default-profile.ts b/apps/desktop/src/store/default-profile.ts
new file mode 100644
index 00000000000..686fbbf1107
--- /dev/null
+++ b/apps/desktop/src/store/default-profile.ts
@@ -0,0 +1,58 @@
+import { atom } from 'nanostores'
+
+import type { DesktopProfileRoute } from '@/global'
+import { withTimeout } from '@/lib/with-timeout'
+
+// Electron owns persistence and cross-window changes. This atom is only a
+// mirror: changing the preference must not re-home an existing conversation.
+export const $defaultProfileRoute = atom<DesktopProfileRoute | null>(null)
+let revision = 0
+
+function publish(route: DesktopProfileRoute | null): void {
+ const current = $defaultProfileRoute.get()
+
+ if (current?.connectionId !== route?.connectionId || current?.profile !== route?.profile) {
+ $defaultProfileRoute.set(route)
+ }
+}
+
+export async function refreshDefaultProfile(): Promise<DesktopProfileRoute | null> {
+ const getDefault = window.hermesDesktop?.profile?.getDefault
+
+ if (!getDefault) {
+ return $defaultProfileRoute.get()
+ }
+
+ const requestRevision = ++revision
+ const route = await withTimeout(getDefault(), 5_000, 'Timed out loading the default profile')
+
+ if (requestRevision === revision) {
+ publish(route)
+ }
+
+ return $defaultProfileRoute.get()
+}
+
+export async function setDefaultProfile(route: DesktopProfileRoute): Promise<DesktopProfileRoute> {
+ const setDefault = window.hermesDesktop?.profile?.setDefault
+
+ if (!setDefault) {
+ throw new Error('This Desktop version cannot save a default profile.')
+ }
+
+ const requestRevision = ++revision
+ const saved = await withTimeout(setDefault(route), 5_000, 'Timed out saving the default profile')
+
+ if (requestRevision === revision) {
+ publish(saved)
+ }
+
+ return saved
+}
+
+export function subscribeDefaultProfile(): (() => void) | undefined {
+ return window.hermesDesktop?.profile?.onDefaultChanged?.(route => {
+ revision += 1
+ publish(route)
+ })
+}
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index b258528fcba..c1805f5e5f5 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -320,13 +320,36 @@ export const $newChatRoute = atom<AgentProfileRoute | null>(null)
// profile pick on the explicit `local` source — see profilePickConnectionId).
export const $newChatConnectionId = atom<null | string>(null)
+// A saved null default explicitly chooses the legacy profile door even while
+// a remote source is still active. Ordinary profile picks retain their existing
+// source policy; only this pinned intent suppresses the ambient fallback.
+let legacyNewChatProfile: null | string = null
+
/** Capture the registry source a new-chat profile intent lands on — by
* default the active one; callers that dial a different door (a profile
* pick, see profilePickConnectionId) pass the source that door uses. */
export function captureNewChatSource(connectionId: null | string = activeGatewayConnectionId()): void {
+ legacyNewChatProfile = null
$newChatConnectionId.set(connectionId)
}
+export function pinLegacyNewChatProfile(profile: string): void {
+ const target = normalizeProfileKey(profile)
+ $newChatProfile.set(target)
+ $newChatRoute.set(null)
+ captureNewChatSource(null)
+ legacyNewChatProfile = target
+}
+
+export function isLegacyNewChatProfile(profile: string): boolean {
+ return (
+ legacyNewChatProfile === normalizeProfileKey(profile) &&
+ $newChatProfile.get() === legacyNewChatProfile &&
+ $newChatRoute.get() === null &&
+ $newChatConnectionId.get() === null
+ )
+}
+
/**
* The registry source a PROFILE PICK dials, mirroring activateOnCurrentSource:
* a live remote registry source keeps its connection id. Named picks on the
@@ -374,6 +397,10 @@ export function resolveNewChatOwnerRoute(forProfile?: string): AgentProfileRoute
const intentProfile = forProfile ? normalizeProfileKey(forProfile) : $newChatProfile.get()
+ if (intentProfile && isLegacyNewChatProfile(intentProfile)) {
+ return null
+ }
+
const connectionId = (
(intentProfile
? ($newChatConnectionId.get() ?? profilePickConnectionId(intentProfile))
@@ -546,7 +573,10 @@ async function resolveConnectionForProfile(profile: string): Promise<HermesConne
// their sockets — so their sessions keep streaming concurrently. A null/empty
// target means "no explicit profile" → keep the current gateway (a plain new
// chat stays put; single-profile users never leave the primary).
-export async function ensureGatewayProfile(profile: string | null | undefined): Promise<void> {
+export async function ensureGatewayProfile(
+ profile: string | null | undefined,
+ { forceLegacyRoute = false }: { forceLegacyRoute?: boolean } = {}
+): Promise<void> {
if (profile == null || !String(profile).trim()) {
// "No explicit profile" = use the current gateway. But if an explicit swap
// (e.g. the user just picked a profile in the switcher) is still in flight,
@@ -575,6 +605,12 @@ export async function ensureGatewayProfile(profile: string | null | undefined):
// scope — recognized via the active descriptor so global-remote keeps its
// fast path instead of re-running the swap on every create.
const routeAgrees = (): boolean => {
+ // A saved legacy default names a door, not just a profile. A registry
+ // source can serve the SAME name without being that legacy backend.
+ if (forceLegacyRoute && activeGatewayConnectionId() !== null) {
+ return false
+ }
+
if (normalizeProfileKey($activeGatewayProfile.get()) !== target || $gateway.get()?.connectionState !== 'open') {
return false
}
@@ -1028,7 +1064,7 @@ export function newSessionInAgent(route: AgentProfileRoute): void {
$newChatProfile.set(captured.profile)
$newChatRoute.set(captured)
- $newChatConnectionId.set(captured.connectionId)
+ captureNewChatSource(captured.connectionId)
requestFreshSession()
// #81094: surface the failed dial instead of failing silently.
void ensureGatewayAgent(captured.connectionId, captured.profile).catch((error: unknown) => {