Skip to content

The agent that grows with you

fix(desktop): keep a profile picked during boot over the primary adoption

Teknium9828007479c9
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot-profile-pick.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-profile-pick.test.tsx
new file mode 100644
index 00000000000..8a9a4da1f9d
--- /dev/null
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-profile-pick.test.tsx
@@ -0,0 +1,171 @@
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { $desktopBoot } from '@/store/boot'
+import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'
+import { $activeGatewayProfile, ensureGatewayProfile } from '@/store/profile'
+import { $connection, $gatewayState } from '@/store/session'
+
+import { deferred } from '../../../test/deferred'
+import { FakeWebSocket } from '../../../test/fake-gateway-socket'
+
+import { takeGatewaySurvivor } from './gateway-hmr-survivor'
+import { useGatewayBoot } from './use-gateway-boot'
+
+// The blocked update-hold screen's renderer leg (R8 D3/M6): a hold the main
+// process publishes on boot progress lands in $desktopBoot even after boot.
+// Shares the fake socket with use-gateway-boot.test.tsx; the desktop bridge
+// here carries only what the boot hook touches.
+
+vi.mock(import('@/store/notifications'), async importOriginal => ({
+ ...(await importOriginal()),
+ notifyError: vi.fn()
+}))
+
+vi.mock(import('@/store/terminal-backend-warning'), () => ({
+ warnIfTerminalBackendUnavailable: vi.fn(async () => false)
+}))
+
+const primaryConn = {
+ authMode: 'token' as const,
+ baseUrl: 'https://vps.example.com',
+ connectionId: 'primary-vps',
+ profile: 'default',
+ token: 't',
+ wsUrl: 'wss://vps.example.com/api/ws?token=t'
+}
+
+const coderConn = {
+ ...primaryConn,
+ baseUrl: 'https://coder.example.com',
+ connectionId: 'coder-remote',
+ profile: 'coder',
+ token: 'c',
+ wsUrl: 'wss://coder.example.com/api/ws?token=c'
+}
+
+function fakeDesktop() {
+ let bootProgressHandler: ((payload: Record<string, unknown>) => void) | null = null
+ const unsubscribe = () => () => undefined
+
+ return {
+ getConnection: vi.fn(async (_profile?: null | string): Promise<typeof primaryConn> => primaryConn),
+ getGatewayWsUrl: vi.fn(async (conn?: { wsUrl?: string }) => conn?.wsUrl ?? primaryConn.wsUrl),
+ getBootProgress: vi.fn(async () => ({
+ error: null,
+ fakeMode: false,
+ message: '',
+ phase: 'init',
+ progress: 0,
+ retryable: false,
+ running: true,
+ timestamp: Date.now()
+ })),
+ onBootProgress: vi.fn(callback => {
+ bootProgressHandler = callback
+
+ return () => {
+ bootProgressHandler = null
+ }
+ }),
+ emitBootProgress(payload: Record<string, unknown>) {
+ bootProgressHandler?.(payload)
+ },
+ onBackendExit: vi.fn(unsubscribe),
+ onConnectionApplied: vi.fn(unsubscribe),
+ onPowerResume: vi.fn(unsubscribe),
+ revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),
+ onWindowStateChanged: vi.fn(unsubscribe),
+ profile: { get: vi.fn(async () => ({ profile: 'default' })) }
+ }
+}
+
+function Harness({ refreshSessions }: { refreshSessions: () => Promise<void> }) {
+ useGatewayBoot({
+ beforeConnectionSwitch: () => undefined,
+ handleGatewayEvent: () => undefined,
+ handleServerRequest: () => false,
+ onConnectionReady: () => undefined,
+ onGatewayReady: () => undefined,
+ refreshHermesConfig: async () => undefined,
+ refreshSessions
+ })
+
+ return null
+}
+
+function closeSurvivor() {
+ try {
+ takeGatewaySurvivor()?.gateway.close()
+ } catch {
+ // ignore
+ }
+}
+
+const originalWebSocket = globalThis.WebSocket
+
+beforeEach(() => {
+ closeSurvivor()
+ closeSecondaryGateways()
+ $activeGatewayProfile.set('default')
+ $connection.set(null)
+ vi.useFakeTimers()
+ FakeWebSocket.mode = 'open'
+ FakeWebSocket.instances = []
+ FakeWebSocket.pingMode = 'pong'
+ ;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket
+ $gatewayState.set('idle')
+ $desktopBoot.set({
+ error: null,
+ fakeMode: false,
+ message: '',
+ phase: 'init',
+ progress: 0,
+ running: true,
+ timestamp: Date.now(),
+ visible: true
+ })
+})
+
+afterEach(() => {
+ cleanup()
+ closeSurvivor()
+ closeSecondaryGateways()
+ $connection.set(null)
+ vi.useRealTimers()
+ ;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket
+ delete (window as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+// T19 (#134889): the first secondary-profile click right after boot lands
+// while boot is still resolving the primary. Boot's late adoption must not
+// re-point the active route (and the session list it scopes) at default.
+it('a profile picked while boot is still connecting survives the primary adoption', async () => {
+ const desktop = fakeDesktop()
+ const primaryLookup = deferred<typeof primaryConn>()
+ desktop.getConnection.mockImplementation(async (profile?: null | string) =>
+ (profile ?? '').trim() === 'coder' ? coderConn : primaryLookup.promise
+ )
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ const scopes: string[] = []
+ render(<Harness refreshSessions={async () => void scopes.push($activeGatewayProfile.get())} />)
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ vi.useRealTimers()
+ await ensureGatewayProfile('coder')
+ expect(isActivePrimary()).toBe(false)
+
+ primaryLookup.resolve(primaryConn)
+ await new Promise(resolve => setTimeout(resolve, 50))
+ vi.useFakeTimers()
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ expect($desktopBoot.get().running).toBe(false)
+ expect($activeGatewayProfile.get()).toBe('coder')
+ expect(isActivePrimary()).toBe(false)
+ expect(scopes).toEqual(['coder'])
+})
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 4bf0dd8becf..902cb80bacb 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -68,6 +68,7 @@ import { watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
import { notify, notifyError, RECOVERY_ACTIONS } from '@/store/notifications'
import {
$activeGatewayProfile,
+ currentProfileSelectionRevision,
normalizeProfileKey,
refreshActiveProfile
} from '@/store/profile'
@@ -739,6 +740,7 @@ export function useGatewayBoot({
async function adoptPrimaryProfile(
connection: HermesConnection,
+ selectionRevision: number,
shouldPublish: () => boolean = () => true
): Promise<boolean> {
// The resolved descriptor reflects the explicit startup default. The
@@ -753,15 +755,29 @@ export function useGatewayBoot({
}
const key = normalizeProfileKey(profileKey)
- $activeGatewayProfile.set(key)
+ // A profile the user picked after this boot/apply started is newer
+ // intent than the primary adoption (T19, #134889): record the primary
+ // socket, but leave the active route and the profile atom — which
+ // scopes the session list refreshed next — on the user's pick.
+ const userPicked = currentProfileSelectionRevision() !== selectionRevision
+
+ if (!userPicked) {
+ $activeGatewayProfile.set(key)
+ }
+
setPrimaryGateway(gateway, key)
- void ensureGatewayForProfile(key)
+
+ if (!userPicked) {
+ void ensureGatewayForProfile(key)
+ }
} catch {
if (!shouldPublish()) {
return false
}
- $activeGatewayProfile.set(normalizeProfileKey(override))
+ if (currentProfileSelectionRevision() === selectionRevision) {
+ $activeGatewayProfile.set(normalizeProfileKey(override))
+ }
}
return true
@@ -865,7 +881,16 @@ 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(conn, ownsSwitch)) || !ownsSwitch()) {
+ if (
+ !(await adoptPrimaryProfile(
+ conn,
+ // A connection apply replaces the machine context wholesale, so it
+ // always adopts the new primary; only cold boot defers to a pick.
+ currentProfileSelectionRevision(),
+ ownsSwitch
+ )) ||
+ !ownsSwitch()
+ ) {
return
}
@@ -1431,6 +1456,7 @@ export function useGatewayBoot({
})
async function boot() {
+ const selectionRevision = currentProfileSelectionRevision()
// Where this boot attempt got to — a historical fact, not a late read of
// gateway.connectionState. A socket can close after a successful dial;
// later initialization errors must not be reclassified as boot dials.
@@ -1542,7 +1568,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(conn)
+ await adoptPrimaryProfile(conn, selectionRevision)
setDesktopBootStep({
phase: 'renderer.config',
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index e43adff9f37..d5c61bec0e7 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -543,6 +543,18 @@ export function prewarmProfileBackend(name: string, connectionId: null | string
let gatewaySwitch: Promise<void> | null = null
+// Bumped by every explicit profile selection (ensureGatewayProfile with a
+// target). Boot and connection applies snapshot it before their slow
+// descriptor/dial awaits; a selection made in between is newer intent than
+// the boot's primary adoption, which must then leave the active route alone
+// (T19, #134889: the first secondary click right after boot otherwise flipped
+// back to default and the sidebar loaded default's sessions).
+let profileSelectionRevision = 0
+
+export function currentProfileSelectionRevision(): number {
+ return profileSelectionRevision
+}
+
// Descriptor lookups are IPC round-trips into Electron main. A wedged main
// (the #93454 class: a ticket mint that never answers) must not latch the
// gatewaySwitch mutex — and, through it, every later profile/source switch
@@ -607,6 +619,7 @@ export async function ensureGatewayProfile(
}
const target = normalizeProfileKey(profile)
+ profileSelectionRevision += 1
// Fast path: only when the REGISTRY's active route — the authority that
// selects the socket in applyActive — already serves the target. The