Skip to content

The agent that grows with you

fix(desktop): recover Cloud connections after team changes

Robin Fernandes969a7cbaae26
diff --git a/apps/desktop/electron/api-transport.ts b/apps/desktop/electron/api-transport.ts
index dd1cfa61fa3..4b59e2841bf 100644
--- a/apps/desktop/electron/api-transport.ts
+++ b/apps/desktop/electron/api-transport.ts
@@ -194,6 +194,29 @@ function readStatusCode(error: unknown): number {
return Number(error && typeof error === 'object' ? (error as { statusCode?: unknown }).statusCode : NaN)
}
+/**
+ * The structured JSON body an httpStatusError carries after its "<status>: "
+ * prefix, or null when the body was not a JSON object. NAS answers
+ * `{ error: "<code>", ... }` on 4xx, and every reader of that code (the 409
+ * org picker, the stale-team fallback) must parse the prefix the same way.
+ */
+function readJsonErrorBody(error: unknown): null | Record<string, unknown> {
+ const message = error instanceof Error ? error.message : ''
+ const start = message.indexOf('{')
+
+ if (start < 0) {
+ return null
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(message.slice(start))
+
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null
+ } catch {
+ return null
+ }
+}
+
/**
* Error for a JSON endpoint that did not answer JSON. A 2xx HTML body is the
* SPA index.html for an unregistered /api path, and downstream capability
@@ -253,6 +276,7 @@ export {
isIdempotentMethod,
isTransientTransportError,
jsonAgentFor,
+ readJsonErrorBody,
readStatusCode,
shouldRetryRequest,
withRetry
diff --git a/apps/desktop/electron/cloud-discovery.test.ts b/apps/desktop/electron/cloud-discovery.test.ts
new file mode 100644
index 00000000000..7284f70824f
--- /dev/null
+++ b/apps/desktop/electron/cloud-discovery.test.ts
@@ -0,0 +1,71 @@
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+
+import { expect, test } from 'vitest'
+
+import { httpStatusError } from './api-transport'
+import { discoverWithTeamFallback } from './cloud-discovery'
+
+test('a stale team falls back once to current memberships; unrelated failures retain their meaning', async () => {
+ const requests: string[] = []
+ let status = 403
+ let error = 'org_access_denied'
+ let fallbackStatus = 409
+
+ const server = createServer((req, res) => {
+ requests.push(req.url!)
+ const scoped = req.url!.includes('?org=')
+ res.writeHead(scoped ? status : fallbackStatus, { 'Content-Type': 'application/json' })
+ const body =
+ fallbackStatus === 200
+ ? { agents: [], org: { id: 'new-team' } }
+ : { error: 'org_selection_required', orgs: [{ id: 'new-team' }] }
+ res.end(JSON.stringify(scoped ? { error } : body))
+ })
+
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/agents`
+
+ const fetchAgents = async (org?: string) => {
+ const response = await fetch(`${base}${org ? `?org=${encodeURIComponent(org)}` : ''}`)
+ const text = await response.text()
+
+ if (!response.ok) {
+ throw httpStatusError(response.status, text)
+ }
+
+ return JSON.parse(text)
+ }
+
+ try {
+ for (const pair of [
+ [403, 'org_access_denied'],
+ [404, 'org_not_found']
+ ] as const) {
+ ;[status, error] = pair
+ requests.length = 0
+ await expect(discoverWithTeamFallback(fetchAgents, 'old-team')).rejects.toMatchObject({ statusCode: 409 })
+ expect(requests).toEqual(['/api/agents?org=old-team', '/api/agents'])
+ }
+
+ fallbackStatus = 200
+ await expect(discoverWithTeamFallback(fetchAgents, 'old-team')).resolves.toMatchObject({
+ agents: [],
+ org: { id: 'new-team' }
+ })
+
+ for (const pair of [
+ [401, 'invalid_token'],
+ [403, 'forbidden'],
+ [503, 'org_access_denied']
+ ] as const) {
+ ;[status, error] = pair
+ requests.length = 0
+ await expect(discoverWithTeamFallback(fetchAgents, 'old-team')).rejects.toMatchObject({ statusCode: status })
+ expect(requests).toHaveLength(1)
+ }
+ } finally {
+ server.closeAllConnections()
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ }
+})
diff --git a/apps/desktop/electron/cloud-discovery.ts b/apps/desktop/electron/cloud-discovery.ts
new file mode 100644
index 00000000000..f4593606b09
--- /dev/null
+++ b/apps/desktop/electron/cloud-discovery.ts
@@ -0,0 +1,22 @@
+import { readJsonErrorBody, readStatusCode } from './api-transport'
+
+// The NAS (status, error code) pairs that mean the remembered team itself is
+// gone for this user, as opposed to the credential or the request being bad.
+const STALE_TEAM_RESPONSES: Record<number, string> = { 403: 'org_access_denied', 404: 'org_not_found' }
+
+// A remembered team is a discovery preference, not an authorization grant.
+// If NAS says it no longer exists or is inaccessible, let NAS resolve current
+// memberships (including its 409 team picker). Never retry generic denials.
+export async function discoverWithTeamFallback<T>(fetchAgents: (org?: string) => Promise<T>, org?: string): Promise<T> {
+ try {
+ return await fetchAgents(org)
+ } catch (error) {
+ const staleTeamCode = STALE_TEAM_RESPONSES[readStatusCode(error)]
+
+ if (org && staleTeamCode && readJsonErrorBody(error)?.error === staleTeamCode) {
+ return fetchAgents()
+ }
+
+ throw error
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 95b241b29d5..eb143ead166 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -36,6 +36,7 @@ import {
htmlResponseError,
httpStatusError,
jsonAgentFor,
+ readJsonErrorBody,
readStatusCode,
withRetry
} from './api-transport'
@@ -96,6 +97,7 @@ import {
import { detectBundleSkew } from './bundle-skew'
import { detectBundleSwap } from './bundle-swap'
import { registerChatOnboardingWindow } from './chat-onboarding-window'
+import { discoverWithTeamFallback } from './cloud-discovery'
import { installCommandScreenshot } from './command-screenshot'
import { writeComposerPaste } from './composer-paste'
import { applyConnectionChange, teardownSshState } from './connection-apply'
@@ -8453,14 +8455,17 @@ async function discoverCloudAgents(org?: string) {
await renewPortalAccessSilently()
}
- const orgQuery = org ? `?org=${encodeURIComponent(org)}` : ''
let body
const fetchAgents = () =>
- fetchJsonViaOauthSession(`${portalBaseUrl}/api/agents${orgQuery}`, {
- method: 'GET',
- timeoutMs: 15_000
- })
+ discoverWithTeamFallback(
+ selectedOrg =>
+ fetchJsonViaOauthSession(`${portalBaseUrl}/api/agents${selectedOrg ? `?org=${encodeURIComponent(selectedOrg)}` : ''}`, {
+ method: 'GET',
+ timeoutMs: 15_000
+ }),
+ org
+ )
try {
body = (await fetchAgents()) as any
@@ -8528,24 +8533,11 @@ function trimCloudOrg(org) {
}
}
-// Extract the org list from a 409 org_selection_required error body. The error
-// message is "409: <raw json>" (see fetchJsonViaOauthSession); parse defensively
-// and return null if it isn't the shape we expect (caller then rethrows).
+// Extract the org list from a 409 org_selection_required error body. Parse
+// defensively and return null if it isn't the shape we expect (caller then
+// rethrows).
function parseOrgSelectionError(error) {
- const msg = String(error?.message || '')
- const jsonStart = msg.indexOf('{')
-
- if (jsonStart < 0) {
- return null
- }
-
- let parsed
-
- try {
- parsed = JSON.parse(msg.slice(jsonStart))
- } catch {
- return null
- }
+ const parsed = readJsonErrorBody(error)
if (parsed?.error !== 'org_selection_required' || !Array.isArray(parsed.orgs)) {
return null
diff --git a/apps/desktop/src/app/settings/cloud-team-change.ts b/apps/desktop/src/app/settings/cloud-team-change.ts
new file mode 100644
index 00000000000..0d3cd3c38ae
--- /dev/null
+++ b/apps/desktop/src/app/settings/cloud-team-change.ts
@@ -0,0 +1,56 @@
+import type { DesktopRegistryConnection } from '@/global'
+
+// `org` values are the refs NAS echoes (`slug ?? id`) and are compared as
+// opaque strings. If a team gains or changes its slug, a connection saved under
+// the old ref reads as moved once: the reconnect below re-authenticates and
+// rewrites the ref, so the mismatch self-heals at the cost of one silent cascade.
+export function cloudTeamChanged(connection: DesktopRegistryConnection | undefined, org: string | null): boolean {
+ return Boolean(connection?.kind === 'cloud' && org && connection.org !== org)
+}
+
+// Only called after the user chooses an agent returned by NAS for this team.
+// Keep the connection id and user label; the normal registry save invalidates
+// its old pooled routes when org changes. Authenticate before committing it.
+// Resolves false when the silent cascade did not land a gateway session (the
+// caller warns the same way it does for a fresh connect); true once saved.
+export async function reconnectMovedCloudAgent(
+ desktop: NonNullable<Window['hermesDesktop']>,
+ connection: DesktopRegistryConnection & { url: string },
+ org: string,
+ isCurrent: () => boolean
+): Promise<boolean> {
+ const { url } = connection
+ await desktop.oauthLogoutConnectionConfig(url)
+
+ if (!isCurrent()) {
+ return false
+ }
+ const result = await desktop.cloud.agentSignIn(url)
+
+ if (!isCurrent() || !result.connected) {
+ return false
+ }
+
+ await desktop.connections.save({
+ id: connection.id,
+ kind: 'cloud',
+ label: connection.label,
+ url,
+ authMode: 'oauth',
+ org
+ })
+
+ // Legacy settings remember a team independently of the registry. Update it
+ // only for this same gateway; selecting a secondary must not change defaults.
+ const config = await desktop.getConnectionConfig()
+
+ if (!isCurrent()) {
+ return false
+ }
+
+ if (config.mode === 'cloud' && config.remoteUrl.replace(/\/+$/, '') === url.replace(/\/+$/, '')) {
+ await desktop.saveConnectionConfig({ mode: 'cloud', remoteUrl: config.remoteUrl, cloudOrg: org })
+ }
+
+ return isCurrent()
+}
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsx
index a42a6ed77f0..87811b30cc3 100644
--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx
@@ -57,6 +57,59 @@ afterEach(() => {
})
describe('GatewaySettings', () => {
+ it('reconnects a moved agent under its new team without replacing its saved identity or changing another default', async () => {
+ const saved = {
+ id: 'saved-b',
+ kind: 'cloud',
+ label: 'My agent',
+ url: 'https://moved.example',
+ authMode: 'oauth',
+ org: 'old-team'
+ }
+ registry.value = { connections: [saved] }
+ getConnectionConfig.mockResolvedValue({
+ ...localConnection,
+ mode: 'cloud',
+ cloudOrg: 'old-team',
+ remoteUrl: 'https://other.example'
+ })
+ const calls: string[] = []
+ const oauthLogoutConnectionConfig = vi.fn(async () => {
+ calls.push('logout')
+ })
+ const agentSignIn = vi.fn(async () => {
+ calls.push('login')
+ return { connected: true }
+ })
+ const save = vi.fn(async () => {
+ calls.push('save')
+ })
+ const discover = vi.fn().mockResolvedValue({
+ needsOrgSelection: true,
+ orgs: [{ id: 'new-team', name: 'New team', role: 'OWNER' }]
+ })
+ Object.assign(window.hermesDesktop, {
+ oauthLogoutConnectionConfig,
+ connections: { save },
+ cloud: { status: vi.fn().mockResolvedValue({ signedIn: true }), discover, agentSignIn }
+ })
+ render(<GatewaySettings embedded />)
+ await screen.findByText('New team')
+ discover.mockResolvedValue({
+ agents: [{ id: 'moved', name: 'Moved agent', dashboardUrl: saved.url }],
+ org: { id: 'new-team' }
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Select', exact: true }))
+ await screen.findByRole('button', { name: 'Use gateway' })
+ expect(save).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Use gateway' }))
+ await waitFor(() => expect(selectConnection).toHaveBeenCalledWith(saved.id))
+ expect(calls).toEqual(['logout', 'login', 'save'])
+ expect(agentSignIn).toHaveBeenCalledWith(saved.url)
+ expect(save).toHaveBeenCalledWith({ ...saved, org: 'new-team' })
+ expect(saveConnectionConfig).not.toHaveBeenCalled()
+ registry.value = null
+ })
it('keeps saved Cloud instances usable without discovery and marks the live source, not the default', async () => {
getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })
registry.value = {
diff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsx
index 874e5e0b4c8..90155bd6596 100644
--- a/apps/desktop/src/app/settings/gateway-settings.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.tsx
@@ -6,7 +6,13 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Tip } from '@/components/ui/tooltip'
-import type { DesktopAuthProvider, DesktopCloudAgent, DesktopCloudOrg, DesktopConnectionProbeResult } from '@/global'
+import type {
+ DesktopAuthProvider,
+ DesktopCloudAgent,
+ DesktopCloudOrg,
+ DesktopConnectionProbeResult,
+ DesktopRegistryConnection
+} from '@/global'
import { useI18n } from '@/i18n'
import { ExternalLink } from '@/lib/external-link'
import {
@@ -33,6 +39,7 @@ import {
} from '@/store/connections'
import { notify, notifyError, readableError } from '@/store/notifications'
+import { cloudTeamChanged, reconnectMovedCloudAgent } from './cloud-team-change'
import { ConnectionsRegistrySection } from './connections-registry'
import { CONTROL_TEXT } from './constants'
import { ManagedUpdatesSection } from './managed-updates-section'
@@ -306,17 +313,25 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
// prefers a fresh probe result over the saved value.
const trimmedUrl = coerceRemoteUrlScheme(state.remoteUrl)
- const savedAgent = (agent: DesktopCloudAgent) =>
- registry?.connections.find(
- connection =>
+ const savedAgent = (agent: DesktopCloudAgent) => {
+ const dashboardUrl = agent.dashboardUrl
+
+ if (!dashboardUrl) {
+ return undefined
+ }
+
+ const target = savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: dashboardUrl })
+
+ return registry?.connections.find(
+ (connection): connection is DesktopRegistryConnection & { url: string } =>
(connection.kind === 'cloud' || connection.kind === 'remote') &&
- connection.url &&
- agent.dashboardUrl &&
- savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: connection.url }) ===
- savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: agent.dashboardUrl })
+ typeof connection.url === 'string' &&
+ savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: connection.url }) === target
)
+ }
- const isConnectedAgent = (agent: DesktopCloudAgent) => savedAgent(agent)?.id === activeConnectionId
+ const isConnectedAgent = (agent: DesktopCloudAgent) =>
+ savedAgent(agent)?.id === activeConnectionId && !cloudTeamChanged(savedAgent(agent), cloudOrg)
const activateSavedCloud = async (id: string) => {
setCloudConnectingId(id)
@@ -714,6 +729,7 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
// Multi-org user with no org chosen yet: show the picker. Don't clear a
// previously-chosen org list on a refresh.
setCloudOrgs(result.orgs)
+ setCloudOrg(null)
setCloudAgents([])
setCloudDiscover('done')
@@ -908,12 +924,37 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
setCloudConnectingId(agent.id)
+ const warnSignInIncomplete = () =>
+ notify({
+ kind: 'warning',
+ title: t.boot.failure.signInIncompleteTitle,
+ message: t.boot.failure.signInIncompleteMessage
+ })
+
try {
// Saved sources keep their identity, credentials and default gateway.
// The activation path reuses healthy sockets and validates auth on a new dial.
const saved = savedAgent(agent)
if (saved) {
+ const org = cloudOrgRef.current
+
+ if (org && cloudTeamChanged(saved, org)) {
+ const reconnected = await reconnectMovedCloudAgent(desktop, saved, org, () => seq === contextSeq.current)
+
+ if (seq !== contextSeq.current) {
+ return
+ }
+
+ if (!reconnected) {
+ warnSignInIncomplete()
+
+ return
+ }
+
+ await refreshConnectionsRegistry()
+ }
+
await selectConnection(saved.id)
return
@@ -926,11 +967,7 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
}
if (!result.connected) {
- notify({
- kind: 'warning',
- title: t.boot.failure.signInIncompleteTitle,
- message: t.boot.failure.signInIncompleteMessage
- })
+ warnSignInIncomplete()
return
}