Skip to content

The agent that grows with you

fix(desktop): clear the pinned new-chat route when a gateway switch commits

unsupportedpastelsbe3c9206a97a
diff --git a/apps/desktop/src/store/connections-new-chat-route.test.ts b/apps/desktop/src/store/connections-new-chat-route.test.ts
new file mode 100644
index 00000000000..a4ee7529daf
--- /dev/null
+++ b/apps/desktop/src/store/connections-new-chat-route.test.ts
@@ -0,0 +1,164 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import type { DesktopConnectionsRegistry, HermesConnection } from '@/global'
+import type * as Hermes from '@/hermes'
+
+import { deferred } from '../test/deferred'
+
+vi.mock('@/app/contrib/hooks/use-background-sync', () => ({ resetLiveRuntimeTracking: vi.fn() }))
+vi.mock('@/hermes', async importOriginal => {
+ const actual = await importOriginal<typeof Hermes>()
+
+ return {
+ ...actual,
+ getProfiles: vi.fn(async () => ({ profiles: [{ name: 'default' }] })),
+ hermesApi: vi.fn(async () => ({ current: 'default', profiles: [{ name: 'default' }] })),
+ HermesGateway: class {
+ connectionState = 'closed'
+ wsUrl = ''
+ connect = async (url: string) => {
+ this.wsUrl = url
+ this.connectionState = 'open'
+ }
+ close = () => {
+ this.connectionState = 'closed'
+ }
+ onEvent = () => () => undefined
+ onState = () => () => undefined
+ request = async () => ({})
+ }
+ }
+})
+
+import { $activeConnectionId, _resetConnectionsForTests, selectConnection, setConnectionsRegistry } from './connections'
+import {
+ activeGatewayConnectionId,
+ closeSecondaryGateways,
+ configureGatewayRegistry,
+ setPrimaryGateway,
+ setPrimaryGatewayConnection
+} from './gateway'
+import {
+ $activeGatewayProfile,
+ $newChatRoute,
+ $showAllProfiles,
+ ensureGatewayAgent,
+ newSessionInAgent,
+ resolveNewChatOwnerRoute
+} from './profile'
+import { setConnection } from './session'
+
+const registry: DesktopConnectionsRegistry = {
+ version: 2,
+ primary: 'homelab',
+ secureTokenStorage: true,
+ connections: [
+ { id: 'homelab', kind: 'remote', label: 'Home', tokenSet: true, tokenPreview: null },
+ { id: 'local', kind: 'local', label: 'This device', tokenSet: false, tokenPreview: null }
+ ]
+}
+
+function descriptor(connectionId: string, profile = 'default'): HermesConnection {
+ return {
+ connectionId,
+ profile,
+ registryScoped: true,
+ isFullscreen: false,
+ nativeOverlayWidth: 0,
+ logs: [],
+ windowButtonPosition: null,
+ mode: connectionId === 'local' ? 'local' : 'remote',
+ authMode: 'token',
+ token: 'test',
+ wsUrl: `ws://${connectionId}.invalid/ws`,
+ baseUrl: `http://${connectionId}.invalid`
+ }
+}
+
+const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) =>
+ descriptor(connectionId, profile)
+)
+
+beforeEach(async () => {
+ _resetConnectionsForTests()
+ getConnectionFor.mockReset()
+ getConnectionFor.mockImplementation(async ({ connectionId, profile }) => descriptor(connectionId, profile))
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: {
+ getConnectionFor,
+ getGatewayWsUrlFor: vi.fn(async ({ connectionId }) => ({ ok: true, wsUrl: `ws://${connectionId}.invalid/ws` })),
+ api: vi.fn(async () => ({ current: 'default', profiles: [{ name: 'default' }] }))
+ }
+ })
+ setConnectionsRegistry(registry)
+ setPrimaryGateway({ connectionState: 'open', request: vi.fn(async () => ({})) } as never, 'default')
+ setPrimaryGatewayConnection({ connectionId: 'homelab', mode: 'remote' })
+ setConnection(descriptor('homelab'))
+ configureGatewayRegistry({ onEvent: vi.fn(), onActiveRouteChanged: profile => $activeGatewayProfile.set(profile) })
+ $showAllProfiles.set(false)
+ newSessionInAgent({ connectionId: 'homelab', profile: 'default' })
+ // Drain the real activation mutex used by the fire-and-forget agent action.
+ await ensureGatewayAgent('homelab', 'default')
+})
+
+afterEach(() => {
+ closeSecondaryGateways()
+ $newChatRoute.set(null)
+})
+
+it('re-homes an explicit draft with the selected source, including the return trip', async () => {
+ for (const connectionId of ['local', 'homelab']) {
+ await selectConnection(connectionId)
+ expect($activeConnectionId.get()).toBe(connectionId)
+ expect(activeGatewayConnectionId()).toBe(connectionId)
+ expect(resolveNewChatOwnerRoute()).toEqual({ connectionId, profile: 'default' })
+ }
+})
+
+it('re-homes a fresh draft when leaving All profiles on the already active source', async () => {
+ $newChatRoute.set({ connectionId: 'local', profile: 'default' })
+ $showAllProfiles.set(true)
+ await selectConnection('homelab')
+ expect(resolveNewChatOwnerRoute()).toEqual({ connectionId: 'homelab', profile: 'default' })
+})
+
+it('preserves the explicit draft when the target dial fails', async () => {
+ const route = $newChatRoute.get()
+ getConnectionFor.mockRejectedValueOnce(new Error('offline'))
+ await expect(selectConnection('local')).rejects.toThrow('offline')
+ expect($newChatRoute.get()).toEqual(route)
+ expect(resolveNewChatOwnerRoute()).toEqual(route)
+})
+
+it('does not overwrite a newer draft when remembering a committed switch settles late', async () => {
+ const remembered = deferred<{ ok: boolean; registry: DesktopConnectionsRegistry }>()
+ Object.assign(window.hermesDesktop!, {
+ connections: {
+ setLastUsed: vi.fn().mockReturnValueOnce(remembered.promise).mockResolvedValue({ ok: true, registry })
+ }
+ })
+ const first = selectConnection('local')
+ await vi.waitFor(() => expect(window.hermesDesktop!.connections!.setLastUsed).toHaveBeenCalled())
+ await selectConnection('homelab')
+ const route = { connectionId: 'homelab', profile: 'default' }
+ $newChatRoute.set(route)
+ remembered.resolve({ ok: true, registry })
+ await first
+ expect($newChatRoute.get()).toEqual(route)
+ expect(resolveNewChatOwnerRoute()).toEqual(route)
+})
+
+it('does not let a superseded dial clear a newer explicit draft', async () => {
+ const dial = deferred<HermesConnection>()
+ getConnectionFor.mockImplementationOnce(() => dial.promise)
+ const first = selectConnection('local')
+ await vi.waitFor(() => expect(getConnectionFor).toHaveBeenCalled())
+ await selectConnection('homelab')
+ const route = { connectionId: 'homelab', profile: 'default' }
+ $newChatRoute.set(route)
+ dial.resolve(descriptor('local'))
+ await first
+ expect($newChatRoute.get()).toEqual(route)
+ expect(resolveNewChatOwnerRoute()).toEqual(route)
+})
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 496c9d0fa6b..bac0ab96fd4 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -73,6 +73,7 @@ vi.mock('@/store/profile', () => ({
$activeGatewayProfile,
$freshSessionRequest,
$newChatProfile,
+ $newChatRoute: atom(null),
$showAllProfiles,
captureNewChatSource: vi.fn(),
ensureGatewayAgent,
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index c0ebec017ed..16709796416 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -23,6 +23,7 @@ import {
$activeGatewayProfile,
$freshSessionRequest,
$newChatProfile,
+ $newChatRoute,
$showAllProfiles,
captureNewChatSource,
ensureGatewayAgent,
@@ -405,6 +406,8 @@ export async function selectConnection(connectionId: string, options: SelectConn
// A connection switch is a new-chat intent on THAT source: keep the
// registry identity with the profile so the next create names local::x /
// <source>::x exactly, never a bare profile string.
+ // An older explicit agent route must not override the selected source.
+ $newChatRoute.set(null)
captureNewChatSource()
requestFreshSession()
await rememberConnection(connectionId)
@@ -533,11 +536,18 @@ export async function selectConnection(connectionId: string, options: SelectConn
if (revision === switchRevision) {
await rememberConnection(connectionId)
+ // Remembering crosses IPC too; a newer click may now own the draft.
+ if (revision !== switchRevision) {
+ return
+ }
+
if (!restoreOnBoot) {
$showAllProfiles.set(false)
}
$newChatProfile.set(targetProfile)
+ // An older explicit agent route must not override the selected source.
+ $newChatRoute.set(null)
captureNewChatSource()
requestFreshSession()
await refreshActiveProfile()