Skip to content

The agent that grows with you

fix(desktop): enforce gateway switch publication ownership

Zeus-Deusee3dc554f5d4
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 d5c533be7a8..f5bae0e6693 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
@@ -570,6 +570,90 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect(setLastUsed).toHaveBeenCalledWith('coder-remote')
})
+ it('a Settings switch superseded while reading its descriptor cannot publish over a newer Sessions switch', async () => {
+ const registryConnections: DesktopConnectionsRegistry = {
+ connections: [
+ { id: 'primary-vps', kind: 'remote', label: 'VPS', tokenPreview: '...t', tokenSet: true },
+ { id: 'coder-remote', kind: 'remote', label: 'Coder', tokenPreview: '...c', tokenSet: true }
+ ],
+ primary: 'primary-vps',
+ secureTokenStorage: true,
+ version: 2
+ }
+
+ const desktop = fakeDesktop() as ReturnType<typeof fakeDesktop> & Record<string, unknown>
+
+ const settingsConn = {
+ ...primaryConn,
+ connectionId: 'settings-a',
+ profile: 'settings-profile',
+ wsUrl: 'wss://settings-a.example.com/api/ws?token=a'
+ }
+
+ let releaseSettings: (connection: typeof settingsConn) => void = () => undefined
+
+ desktop.api = vi.fn(async ({ path }: { path: string }) =>
+ path === '/api/profiles/active' ? { active: 'coder', current: 'coder' } : { profiles: [] }
+ )
+ desktop.getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({
+ ...coderConn,
+ connectionId,
+ profile,
+ registryScoped: true
+ }))
+ desktop.getGatewayWsUrlFor = vi.fn(async () => coderConn.wsUrl)
+ desktop.connections = {
+ list: vi.fn(async () => registryConnections),
+ setLastUsed: vi.fn(async (id: string) => ({ ok: true, registry: { ...registryConnections, lastUsed: id } }))
+ }
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+
+ render(<Harness />)
+ await flushAsync()
+ expect($gatewayState.get()).toBe('open')
+
+ setConnectionsRegistry(registryConnections)
+ desktop.getConnection.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ releaseSettings = resolve
+ })
+ )
+
+ act(() => connectionApplied?.())
+ await vi.waitFor(() => expect(desktop.getConnection).toHaveBeenCalledTimes(2))
+
+ const sessionsSwitch = selectConnection('coder-remote')
+ await flushAsync()
+ await flushAsync()
+ await flushAsync()
+ await sessionsSwitch
+
+ expect(isActivePrimary()).toBe(false)
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.connectionId).toBe('coder-remote')
+
+ const wsUrlReads = desktop.getGatewayWsUrl.mock.calls.length
+ const profileReads = desktop.profile.get.mock.calls.length
+ const profileRefreshes = vi.mocked(desktop.api as ReturnType<typeof vi.fn>).mock.calls.length
+ const socketCount = FakeWebSocket.instances.length
+
+ await act(async () => {
+ releaseSettings(settingsConn)
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ // Switch-token ownership governs every later publication, not just loading
+ // teardown: stale Settings work cannot publish/connect/refresh after B won.
+ expect(isActivePrimary()).toBe(false)
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.connectionId).toBe('coder-remote')
+ expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(wsUrlReads)
+ expect(desktop.profile.get).toHaveBeenCalledTimes(profileReads)
+ expect(desktop.api).toHaveBeenCalledTimes(profileRefreshes)
+ expect(FakeWebSocket.instances).toHaveLength(socketCount)
+ })
+
it('re-fetches the profile rail from the NEW backend after a connection apply (#85731)', async () => {
// The reported repro: connected to backend A, the rail shows A's named
// profiles; the user applies a different remote/Cloud connection (soft
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 e62ff6cb5ca..a0677228c03 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -443,27 +443,43 @@ 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() {
+ async function adoptPrimaryProfile(shouldPublish: () => boolean = () => true): Promise<boolean> {
const override = windowProfileOverride()
try {
const profileKey = override ?? (await desktop.profile?.get?.())?.profile ?? ''
+
+ if (!shouldPublish()) {
+ return false
+ }
+
const key = normalizeProfileKey(profileKey)
$activeGatewayProfile.set(key)
setPrimaryGateway(gateway, key)
void ensureGatewayForProfile(key)
} catch {
+ if (!shouldPublish()) {
+ return false
+ }
+
$activeGatewayProfile.set(normalizeProfileKey(override))
}
+
+ return true
}
// Seed the working dir from the backend default on a fresh view (nothing
// open yet). Shared by boot + soft switch.
- async function seedDefaultCwd() {
+ async function seedDefaultCwd(shouldPublish: () => boolean = () => true) {
await ensureDefaultWorkspaceCwd()
+
+ if (!shouldPublish()) {
+ return
+ }
+
const remoteDefault = await desktopDefaultCwd().catch(() => null)
- if (remoteDefault?.cwd && !$activeSessionId.get() && !$currentCwd.get()) {
+ if (shouldPublish() && remoteDefault?.cwd && !$activeSessionId.get() && !$currentCwd.get()) {
setCurrentCwd(remoteDefault.cwd)
setCurrentBranch(remoteDefault.branch || '')
}
@@ -484,6 +500,7 @@ export function useGatewayBoot({
// inside the error boundary: lifecycle/wipe setup can throw before a
// token is returned and must follow the normal boot-failure path.
switchToken = beginGatewaySwitch()
+ const ownsSwitch = () => !cancelled && switchToken !== null && isCurrentGatewaySwitch(switchToken)
clearReconnectTimer()
clearBootRetryTimer()
bootRetryAttempt = 0
@@ -499,7 +516,7 @@ export function useGatewayBoot({
// on its pinned profile's backend across a soft switch.
const conn = await desktop.getConnection(windowProfileOverride() ?? undefined)
- if (cancelled) {
+ if (!ownsSwitch()) {
return
}
@@ -513,9 +530,13 @@ export function useGatewayBoot({
'Timed out re-minting the gateway WebSocket URL'
)
+ if (!ownsSwitch()) {
+ return
+ }
+
await gateway.connect(wsUrl)
- if (cancelled) {
+ if (!ownsSwitch()) {
return
}
@@ -527,13 +548,21 @@ export function useGatewayBoot({
// rail stale or (if a stale in-flight response landed) collapsed
// (#85731). Best-effort like the rest: a failure keeps the cached
// list rather than blanking the rail.
- await adoptPrimaryProfile()
+ if (!(await adoptPrimaryProfile(ownsSwitch)) || !ownsSwitch()) {
+ return
+ }
+
await Promise.all([
- seedDefaultCwd(),
+ seedDefaultCwd(ownsSwitch),
refreshActiveProfile().catch(() => undefined),
callbacksRef.current.refreshHermesConfig().catch(() => undefined),
callbacksRef.current.refreshSessions().catch(() => undefined)
])
+
+ if (!ownsSwitch()) {
+ return
+ }
+
completeDesktopBoot()
bootCompleted = true
} catch (err) {
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index b0fc2849804..9af6bd0ebfe 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -557,6 +557,89 @@ describe('selectConnection', () => {
}
})
+ it('a timed-out activation that already published cannot republish after a newer source wins', async () => {
+ vi.useFakeTimers()
+
+ try {
+ let releaseDescriptor: () => void = () => undefined
+
+ setConnectionsRegistry(registry)
+ // Seed A's remembered profile through the real source/profile observer,
+ // then restore the currently active local source.
+ $activeGatewayProfile.set('research')
+ $connection.set({ connectionId: 'homelab', mode: 'remote', profile: 'research', registryScoped: true })
+ $activeGatewayProfile.set('default')
+ $connection.set({ connectionId: 'local', mode: 'local', profile: 'default', registryScoped: true })
+
+ ensureGatewayAgent
+ .mockImplementationOnce((connectionId, profile, options) => {
+ options?.beforeActivate?.()
+
+ // Low-level activation publishes synchronously. The trailing descriptor
+ // promise remains alive beyond selectConnection's commit timeout.
+ $activeGatewayProfile.set(profile)
+ $connection.set({
+ connectionId: connectionId ?? undefined,
+ mode: 'remote',
+ profile,
+ registryScoped: true
+ })
+
+ return new Promise<void>(resolve => {
+ releaseDescriptor = () => {
+ // Mirrors ensureGatewayAgent's publication seam: a revoked owner
+ // observes its signal and must not publish its late descriptor.
+ if (!options?.signal?.aborted) {
+ $activeGatewayProfile.set(profile)
+ $connection.set({
+ connectionId: connectionId ?? undefined,
+ mode: 'remote',
+ profile,
+ registryScoped: true
+ })
+ }
+
+ resolve()
+ }
+ })
+ })
+ .mockImplementationOnce(async (connectionId, profile, options) => {
+ if (options?.beforeActivate && !options.beforeActivate()) {
+ return
+ }
+
+ $activeGatewayProfile.set(profile)
+ $connection.set({
+ connectionId: connectionId ?? undefined,
+ mode: 'remote',
+ profile,
+ registryScoped: true
+ })
+ })
+
+ const timedOutOwner = selectConnection('homelab')
+ await vi.advanceTimersByTimeAsync(20_000)
+ await timedOutOwner
+
+ // Fail open: A really did become active before its trailing descriptor
+ // work timed out, so the commit remains successful.
+ expect($activeGatewayProfile.get()).toBe('research')
+ expect($connection.get()?.connectionId).toBe('homelab')
+
+ await selectConnection('work-vps')
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.connectionId).toBe('work-vps')
+
+ releaseDescriptor()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.connectionId).toBe('work-vps')
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('an activation that stalls AFTER the wipe times out: barrier down, still-active source repainted', async () => {
vi.useFakeTimers()
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index f9ca7de5b2f..aa6d220dc15 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -310,14 +310,12 @@ export async function selectConnection(connectionId: string): Promise<void> {
SWITCH_COMMIT_TIMEOUT_MS,
`Timed out activating "${targetConnection.label}".`,
error => {
- // withTimeout does not cancel its input. Revoke this activation's
- // ownership before publishing the timeout so a queued/stalled
- // ensure cannot wake later and commit without a caller. If the
- // gateway already published the target, the commit landed and its
- // trailing descriptor resync remains a harmless fail-open straggler.
- if (!targetIsActive()) {
- activationController.abort(error)
- }
+ // withTimeout does not cancel its input. Every timed-out owner
+ // loses future activation/publication rights, even when low-level
+ // activation already published the target and the commit remains
+ // fail-open. The shared activation signal suppresses any trailing
+ // descriptor/profile publication when stale work later settles.
+ activationController.abort(error)
}
)
)
@@ -327,9 +325,9 @@ export async function selectConnection(connectionId: string): Promise<void> {
await Promise.race([activation, timedActivation])
} catch (error) {
// The socket is activated and its descriptor published synchronously;
- // only the best-effort descriptor resync trails it. A commit that timed
- // out AFTER the new source became active has landed — the straggler is
- // fail-open and cannot undo it.
+ // only best-effort descriptor resync trails it. A commit that timed out
+ // AFTER the new source became active has landed, so keep it fail-open;
+ // the timeout signal still revokes all trailing publication rights.
if (!isTimeoutError(error) || !targetIsActive()) {
throw error
}