Skip to content

The agent that grows with you

fix(desktop): kanban (and every connection-scoped query) follows the gateway switch

Ben Barclay8027c370a107
diff --git a/apps/desktop/src/plugins/kanban/api.ts b/apps/desktop/src/plugins/kanban/api.ts
index d079693acea..78560261210 100644
--- a/apps/desktop/src/plugins/kanban/api.ts
+++ b/apps/desktop/src/plugins/kanban/api.ts
@@ -7,10 +7,17 @@
* (the app's standard, via the SDK). This module owns the query keys, the REST
* calls, and the selected-board atom — every call passes `?board=<slug>` so the
* desktop's selection never flips the server-wide current-board pointer.
+ *
+ * Every query key and the persisted board selection are scoped by the ACTIVE
+ * CONNECTION (`host.state.connectionId`): a board lives on ONE gateway, so a
+ * connection switch must be a clean cache miss (the hermes-bots roster
+ * pattern), and each gateway remembers its own selected board instead of
+ * pinning a slug the next gateway 404s on.
*/
import {
atom,
+ host,
type PluginOs,
type PluginRestOptions,
type PluginStorage,
@@ -60,6 +67,12 @@ const INTRO_KEY = 'introDismissed'
const LANES_KEY = 'lanesByProfile'
const COLLAPSED_KEY = 'collapsedLanes'
+/** Cache-scope id for the active connection — the segment every query key
+ * embeds. `'local'` (never '') for the local pool so the key is never empty. */
+export function kanbanConnectionScope(): string {
+ return String(host.state.connectionId?.get?.() || 'local')
+}
+
/** One live `task_events` frame → precise cache invalidation: the board, plus
* each touched task's detail. The polls (8s board / 4s drawer) stay as the
* fallback — the socket just makes the board feel instant. */
@@ -94,7 +107,14 @@ interface Persisted<T> {
/** Bind the plugin's doors at register time and return a disposer the host
* runs on unload/disable — so nothing (store sync, socket) survives a toggle
* or duplicates on re-enable. The events socket is pinned to a board at
- * handshake, so a board switch closes + reopens it. */
+ * handshake, so a board switch closes + reopens it.
+ *
+ * The events socket is ALSO re-opened when the active CONNECTION changes:
+ * `pluginSocket` resolves the backend only at connect time, so a socket left
+ * open across a switch keeps streaming the previous gateway's events against
+ * the new connection's request scope. The board slug re-hydrates from the
+ * per-connection storage key for the same reason — one gateway's slug pins a
+ * board the next gateway 404s on. */
export function bindApi(
r: Rest,
storage: PluginStorage,
@@ -112,7 +132,6 @@ export function bindApi(
unsubs.push(atom.listen(value => storage.set(key, value)))
}
- persist($boardSlug, BOARD_SLUG_KEY, '')
persist($introDismissed, INTRO_KEY, false)
persist($lanesByProfile, LANES_KEY, false)
persist($collapsedLanes, COLLAPSED_KEY, {})
@@ -124,6 +143,26 @@ export function bindApi(
close = socket(slug ? `/events?board=${encodeURIComponent(slug)}` : '/events', data => onEventsFrame(slug, data))
}
+ // Board selection is per-connection: hydrate under the connection's storage
+ // key, and re-hydrate + reopen the socket when the connection changes (the
+ // outgoing gateway's slug may 404 on the next one).
+ const slugStorageKey = () => `${BOARD_SLUG_KEY}.${kanbanConnectionScope()}`
+
+ const hydrateSlug = () => {
+ $boardSlug.set(storage.get(slugStorageKey(), ''))
+ }
+
+ hydrateSlug()
+ unsubs.push($boardSlug.listen(slug => storage.set(slugStorageKey(), slug)))
+ unsubs.push(
+ host.state.connectionId.listen(() => {
+ // Query keys embed the connection scope (kanbanConnectionScope), so the
+ // new connection is already a clean React Query cache miss — no
+ // invalidation needed here. Only the LIVE bindings (socket, slug) follow.
+ hydrateSlug()
+ open($boardSlug.get())
+ })
+ )
open($boardSlug.get())
unsubs.push($boardSlug.listen(open))
@@ -157,15 +196,20 @@ function withBoard(path: string, params: Record<string, string> = {}): string {
return qs ? `${path}?${qs}` : path
}
-// ── query keys (all board-scoped so switching boards is a clean cache miss) ──
+// ── query keys (connection- AND board-scoped so switching either is a clean
+// cache miss — one gateway's boards/tasks must never paint under another
+// connection's route) ─────────────────────────────────────────────────────────
+
+const scopeKey = (): readonly [string] => [kanbanConnectionScope()]
-export const boardKey = (slug: string, archived: boolean) => ['kanban', 'board', slug, archived] as const
-export const taskKey = (slug: string, id: string) => ['kanban', 'task', slug, id] as const
-export const logKey = (slug: string, id: string) => ['kanban', 'log', slug, id] as const
-export const BOARDS_KEY = ['kanban', 'boards'] as const
-export const PROFILES_KEY = ['kanban', 'profiles'] as const
-export const PROJECTS_KEY = ['kanban', 'projects'] as const
-export const ORCHESTRATION_KEY = ['kanban', 'orchestration'] as const
+export const boardKey = (slug: string, archived: boolean) =>
+ ['kanban', 'board', ...scopeKey(), slug, archived] as const
+export const taskKey = (slug: string, id: string) => ['kanban', 'task', ...scopeKey(), slug, id] as const
+export const logKey = (slug: string, id: string) => ['kanban', 'log', ...scopeKey(), slug, id] as const
+export const BOARDS_KEY = ['kanban', 'boards', ...scopeKey()] as const
+export const PROFILES_KEY = ['kanban', 'profiles', ...scopeKey()] as const
+export const PROJECTS_KEY = ['kanban', 'projects', ...scopeKey()] as const
+export const ORCHESTRATION_KEY = ['kanban', 'orchestration', ...scopeKey()] as const
// ── reads ─────────────────────────────────────────────────────────────────────
diff --git a/apps/desktop/src/plugins/kanban/board.tsx b/apps/desktop/src/plugins/kanban/board.tsx
index a7a8dcd14ad..89087ca59f1 100644
--- a/apps/desktop/src/plugins/kanban/board.tsx
+++ b/apps/desktop/src/plugins/kanban/board.tsx
@@ -76,7 +76,8 @@ import {
fetchBoards,
fetchProfiles,
patchTask,
- PROFILES_KEY
+ PROFILES_KEY,
+ taskKey
} from './api'
import { BoardSwitcher } from './board-switcher'
import { TaskDrawer } from './drawer'
@@ -1207,7 +1208,7 @@ export function KanbanBoardPage() {
},
onSettled: (_data, _err, vars) => {
void qc.invalidateQueries({ queryKey: ['kanban', 'board'] })
- void qc.invalidateQueries({ queryKey: ['kanban', 'task', slug, vars.id] })
+ void qc.invalidateQueries({ queryKey: taskKey(slug, vars.id) })
}
})
diff --git a/apps/desktop/src/plugins/kanban/drawer.tsx b/apps/desktop/src/plugins/kanban/drawer.tsx
index 525df44547c..bdca9b43ffe 100644
--- a/apps/desktop/src/plugins/kanban/drawer.tsx
+++ b/apps/desktop/src/plugins/kanban/drawer.tsx
@@ -586,7 +586,7 @@ export function TaskDrawer({
const invalidate = () => {
void qc.invalidateQueries({ queryKey: taskKey(slug, id!) })
- void qc.invalidateQueries({ queryKey: ['kanban', 'board', slug] })
+ void qc.invalidateQueries({ queryKey: ['kanban', 'board'] })
}
// Optimistic status change against the task cache; rolls back + toasts on a
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index 3801e139b45..1cda5c1d348 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -2,6 +2,7 @@ import { atom, computed } from 'nanostores'
import { getProfiles } from '@/api/profiles'
import type { DesktopConnectionsRegistry } from '@/global'
+import { invalidateProfileScopedQueries } from '@/lib/query-client'
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'
@@ -74,10 +75,39 @@ const $activeConnectionProfile = computed(
})
)
-// Remember one profile per source, so switching machines is a re-home rather
-// than a reset to `default`. The map is local UI preference only; Electron
-// remains the authority for the connection registry and all secrets.
+// The CONNECTION twin of profile.ts's $activeGatewayProfile subscription.
+// The switch commit point (beginGatewaySwitch → invalidateProfileScopedQueries)
+// runs inside beforeActivate — BEFORE the activation publishes the new request
+// scope (applyActive → setApiRequestConnection) — so that invalidation's
+// immediate refetches ride the OUTGOING backend and repaint its data under the
+// incoming connection's route. When the connection id later moves, no kanban
+// query key changes (the pane's keys are unscoped), so nothing re-invalidates:
+// the pane keeps painting the previous gateway's boards. Invalidate here, on
+// the actual (connectionId) change, so the refetch lands on the backend the
+// tags now name.
+//
+// The profile twin suppresses its FIRST fire via `_lastRoutedProfile !==
+// null`, which relies on the profile atom being non-null at startup. The
+// connection id is legitimately null on the primary local route, so null
+// cannot double as "uninitialized" here — an explicit sentinel does.
+let _lastRoutedConnectionId: null | string | undefined
+
+/** Remember one profile per source, so switching machines is a re-home rather
+ * than a reset to `default`. The map is local UI preference only; Electron
+ * remains the authority for the connection registry and all secrets.
+ */
$activeConnectionProfile.subscribe(({ connectionId, descriptorProfile, profile, registryScoped }) => {
+ // The connection twin (above) rides this existing subscription — the one
+ // listener already holding the computed open — instead of a second
+ // subscribe, so the store's task graph is unchanged.
+ const id = connectionId ?? null
+
+ if (_lastRoutedConnectionId !== undefined && _lastRoutedConnectionId !== id) {
+ invalidateProfileScopedQueries()
+ }
+
+ _lastRoutedConnectionId = id
+
// A migrated v1 per-profile remote may expose a client-side alias such as
// "work" while the registered source's actual profile is "default". Only
// remember a source/profile pair after Electron confirms that exact v2
diff --git a/apps/desktop/src/store/kanban-connection-scope.test.ts b/apps/desktop/src/store/kanban-connection-scope.test.ts
new file mode 100644
index 00000000000..aaaab9b5922
--- /dev/null
+++ b/apps/desktop/src/store/kanban-connection-scope.test.ts
@@ -0,0 +1,175 @@
+import { QueryObserver } from '@tanstack/react-query'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { HermesConnection } from '@/global'
+
+// A connection switch must leave every profile-scoped query refetched against
+// the NEW gateway. The switch commit point (beginGatewaySwitch →
+// wipeSessionListsForGatewaySwitch → invalidateProfileScopedQueries) runs
+// inside beforeActivate — BEFORE the activation publishes the new request
+// scope (applyActive → setApiRequestConnection) — so that invalidation's
+// refetches ride the OUTGOING backend. When the connection id later moves and
+// the profile atom is unchanged, nothing re-invalidates: a kanban pane (or
+// any connection-scoped query) keeps painting the previous gateway's data.
+// store/connections closes the hole with the CONNECTION twin of profile.ts's
+// $activeGatewayProfile subscription: invalidate on the actual connection-id
+// change, so the refetch lands on the backend the tags now name.
+//
+// Real store chain (store/gateway + store/profile + store/connections), only
+// the HermesGateway socket class stubbed — same harness as
+// plugin-socket-scope.test.ts.
+
+vi.mock('@/hermes', async importOriginal => {
+ const actual = await importOriginal<Record<string, unknown>>()
+
+ return {
+ ...actual,
+ // Stub only the socket class so gateway activations don't dial real WS.
+ HermesGateway: class {
+ connectionState = 'closed'
+ connect = async (_wsUrl: string): Promise<void> => {
+ this.connectionState = 'open'
+ }
+ close = (): void => {
+ this.connectionState = 'closed'
+ }
+ onEvent = vi.fn(() => () => {})
+ onState = vi.fn(() => () => {})
+ }
+ }
+})
+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+
+const { getApiRequestConnection, setApiRequestConnection, setApiRequestProfile } = await import('@/api/client')
+const { queryClient } = await import('@/lib/query-client')
+const { closeSecondaryGateways, configureGatewayRegistry, setPrimaryGateway } = await import('@/store/gateway')
+const { $activeGatewayProfile } = await import('@/store/profile')
+const { selectConnection, setConnectionsRegistry, _resetConnectionsForTests } = await import('@/store/connections')
+
+const conn = (over: Partial<HermesConnection> = {}): HermesConnection =>
+ ({
+ authMode: 'oauth',
+ baseUrl: 'https://pool.invalid',
+ mode: 'remote',
+ token: 'fake-test-token',
+ wsUrl: 'wss://pool.invalid/api/ws?token=fake-test-token',
+ ...over
+ }) as HermesConnection
+
+const registry = {
+ connections: [
+ { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false },
+ { id: 'spark', kind: 'remote', label: 'Spark', tokenPreview: '...abc', tokenSet: true }
+ ],
+ primary: 'local',
+ secureTokenStorage: true,
+ version: 2
+} as never
+
+describe('connection-switch query invalidation', () => {
+ let tagsAtFetch: Array<null | string>
+
+ let observer: QueryObserver<any, any, any, any, any> | undefined
+
+ beforeEach(() => {
+ vi.stubGlobal('window', {
+ hermesDesktop: {
+ api: vi.fn(async () => ({})),
+ connections: {
+ list: vi.fn(async () => registry),
+ setLastUsed: vi.fn(async () => ({ ok: true, registry }))
+ },
+ getConnection: vi.fn(async (profile?: null | string) =>
+ conn({ baseUrl: 'http://127.0.0.1:8117', profile: profile ?? 'default' })
+ ),
+ getConnectionFor: vi.fn(async ({ connectionId }: { connectionId?: null | string }) =>
+ conn({
+ baseUrl: connectionId === 'spark' ? 'https://spark.invalid' : 'http://127.0.0.1:8117',
+ connectionId: connectionId ?? undefined,
+ profile: 'default',
+ registryScoped: true
+ })
+ ),
+ getGatewayWsUrl: vi.fn(async () => 'wss://pool.invalid/api/ws?ticket=fake'),
+ getGatewayWsUrlFor: vi.fn(async () => 'wss://spark.invalid/api/ws?ticket=fake'),
+ touchBackend: vi.fn(async () => ({ ok: true }))
+ },
+ localStorage: new Map<string, string>() as unknown as Storage
+ })
+ configureGatewayRegistry({ onEvent: vi.fn() })
+ setPrimaryGateway({ connectionState: 'open' } as never, 'default')
+ setConnectionsRegistry(registry)
+ queryClient.clear()
+ tagsAtFetch = []
+ })
+
+ afterEach(() => {
+ observer?.destroy()
+ queryClient.clear()
+ closeSecondaryGateways()
+ $activeGatewayProfile.set('default')
+ setApiRequestProfile(null)
+ setApiRequestConnection(null)
+ _resetConnectionsForTests()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('refetches connection-scoped queries against the NEW gateway after a switch', async () => {
+ // One active profile-scoped query, exactly like the kanban pane's boards
+ // list: the connection tag is read at queryFn time, which is what
+ // pluginRest → hermesApi does.
+ observer = new QueryObserver(queryClient, {
+ queryKey: ['kanban', 'boards'],
+ queryFn: async () => {
+ tagsAtFetch.push(getApiRequestConnection())
+
+ return { boards: [] }
+ },
+ staleTime: 30_000
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+
+ // Let the initial fetch (old backend) settle.
+ await vi.waitFor(() => expect(tagsAtFetch).toEqual([null]))
+ tagsAtFetch.length = 0
+
+ await selectConnection('spark', { profile: 'default' })
+
+ // The switch's own pre-commit wipe refetches early on the OLD tag; the
+ // connection twin must invalidate again once the tag names spark, so at
+ // least one fetch rides the new backend and the FINAL fetch is
+ // spark-tagged.
+ await vi.waitFor(() => expect(tagsAtFetch.at(-1)).toBe('spark'), { timeout: 2_000 })
+
+ expect(getApiRequestConnection()).toBe('spark')
+ expect(tagsAtFetch).toContain('spark')
+
+ unsubscribe()
+ })
+
+ it('does not refetch when the connection id has not actually changed', async () => {
+ let fetches = 0
+ observer = new QueryObserver(queryClient, {
+ queryKey: ['kanban', 'boards'],
+ queryFn: async () => {
+ fetches += 1
+
+ return { boards: [] }
+ },
+ staleTime: 30_000
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+
+ await vi.waitFor(() => expect(fetches).toBe(1))
+
+ // Re-publishing the same registry must not re-invalidate (first-fire
+ // suppression + change guard, same contract as the profile twin).
+ setConnectionsRegistry(registry)
+
+ await new Promise(resolve => setTimeout(resolve, 200))
+ expect(fetches).toBe(1)
+
+ unsubscribe()
+ })
+})