Skip to content

The agent that grows with you

fix(desktop): re-auth a lapsed saved Cloud gateway from Settings

Carl Taylor0def3f162f18
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsx
index 97945e5e4fb..948c6344817 100644
--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx
@@ -1,3 +1,4 @@
+import { GatewayReauthRequiredError } from '@hermes/shared'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -256,4 +257,93 @@ describe('GatewaySettings', () => {
expect(screen.queryByText('All profiles')).toBeNull()
expect(screen.queryByText('Use default gateway')).toBeNull()
})
+
+ // A saved cloud connection on a local-primary device has exactly one
+ // recovery when its gateway session lapses: the silent portal cascade. The
+ // dial's error copy sends the user to Settings → Gateways, so the "Use
+ // gateway" action there must run that cascade and retry the switch — a
+ // plain reauth failure toast would point at a page that cannot help.
+ describe('saved cloud gateway re-auth', () => {
+ const reauthError = new GatewayReauthRequiredError(
+ 'Reached the gateway over HTTP, but the OAuth session was rejected while minting a WebSocket ticket.'
+ )
+
+ const saved = {
+ id: 'saved-a',
+ kind: 'cloud',
+ label: 'Research',
+ url: 'https://a.example',
+ authMode: 'oauth'
+ }
+
+ const mountCloudPanelWith = (cloud: Record<string, unknown>) => {
+ getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: saved.url })
+ registry.value = { connections: [saved] }
+ Object.assign(window.hermesDesktop, { cloud })
+ }
+
+ it('re-signs a lapsed saved gateway session via the portal cascade and retries the switch', async () => {
+ mountCloudPanelWith({
+ status: vi.fn().mockResolvedValue({ signedIn: true }),
+ login: vi.fn(),
+ agentSignIn: vi.fn().mockResolvedValue({ connected: true })
+ })
+ const oauthLogoutConnectionConfig = vi.fn().mockResolvedValue({ ok: true })
+ Object.assign(window.hermesDesktop, { oauthLogoutConnectionConfig })
+ selectConnection.mockRejectedValueOnce(reauthError).mockResolvedValueOnce(undefined)
+
+ render(<GatewaySettings embedded />)
+ const row = (await screen.findByText('Research')).closest('[data-slot]') as HTMLElement
+ fireEvent.click(within(row).getByRole('button', { name: 'Use gateway' }))
+
+ await waitFor(() => expect(selectConnection).toHaveBeenCalledTimes(2))
+ expect(selectConnection).toHaveBeenNthCalledWith(1, saved.id)
+ expect(selectConnection).toHaveBeenNthCalledWith(2, saved.id)
+ expect(oauthLogoutConnectionConfig).toHaveBeenCalledWith(saved.url)
+ expect(window.hermesDesktop!.cloud!.agentSignIn).toHaveBeenCalledWith(saved.url)
+ // The portal session was already live: no interactive portal login.
+ expect(window.hermesDesktop!.cloud!.login).not.toHaveBeenCalled()
+ registry.value = null
+ })
+
+ it('does not cascade for a non-reauth switch failure', async () => {
+ mountCloudPanelWith({
+ status: vi.fn().mockResolvedValue({ signedIn: true }),
+ login: vi.fn(),
+ agentSignIn: vi.fn()
+ })
+ const oauthLogoutConnectionConfig = vi.fn()
+ Object.assign(window.hermesDesktop, { oauthLogoutConnectionConfig })
+ selectConnection.mockRejectedValueOnce(new Error('Timed out connecting to "Research".'))
+
+ render(<GatewaySettings embedded />)
+ const row = (await screen.findByText('Research')).closest('[data-slot]') as HTMLElement
+ fireEvent.click(within(row).getByRole('button', { name: 'Use gateway' }))
+
+ await waitFor(() => expect(selectConnection).toHaveBeenCalledTimes(1))
+ expect(oauthLogoutConnectionConfig).not.toHaveBeenCalled()
+ expect(window.hermesDesktop!.cloud!.agentSignIn).not.toHaveBeenCalled()
+ registry.value = null
+ })
+
+ it('signs into the portal first when that session has lapsed too', async () => {
+ mountCloudPanelWith({
+ status: vi.fn().mockResolvedValue({ signedIn: false }),
+ login: vi.fn().mockResolvedValue({ ok: true, signedIn: true }),
+ agentSignIn: vi.fn().mockResolvedValue({ connected: true })
+ })
+ const oauthLogoutConnectionConfig = vi.fn().mockResolvedValue({ ok: true })
+ Object.assign(window.hermesDesktop, { oauthLogoutConnectionConfig })
+ selectConnection.mockRejectedValueOnce(reauthError).mockResolvedValueOnce(undefined)
+
+ render(<GatewaySettings embedded />)
+ const row = (await screen.findByText('Research')).closest('[data-slot]') as HTMLElement
+ fireEvent.click(within(row).getByRole('button', { name: 'Use gateway' }))
+
+ await waitFor(() => expect(selectConnection).toHaveBeenCalledTimes(2))
+ expect(window.hermesDesktop!.cloud!.login).toHaveBeenCalledTimes(1)
+ expect(window.hermesDesktop!.cloud!.agentSignIn).toHaveBeenCalledWith(saved.url)
+ registry.value = null
+ })
+ })
})
diff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsx
index 432c570479b..c64acc3331f 100644
--- a/apps/desktop/src/app/settings/gateway-settings.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.tsx
@@ -1,3 +1,4 @@
+import { isGatewayReauthRequired } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useEffect, useMemo, useRef, useState } from 'react'
@@ -14,6 +15,7 @@ import type {
DesktopRegistryConnection
} from '@/global'
import { useI18n } from '@/i18n'
+import { reestablishCloudAgentSession } from '@/lib/cloud-agent-session'
import { ExternalLink } from '@/lib/external-link'
import {
AlertCircle,
@@ -417,11 +419,48 @@ function GatewayConnectionSettings({ embedded, standalone }: { embedded: boolean
const isConnectedAgent = (agent: DesktopCloudAgent) =>
savedAgent(agent)?.id === activeConnectionId && !cloudTeamChanged(savedAgent(agent), cloudOrg)
- const activateSavedCloud = async (id: string) => {
+ // A saved cloud connection's gateway session can lapse while the app sits
+ // on a local-primary device — the dial then rejects with a reauth-shaped
+ // error whose copy points here ("Open Settings → Gateway and sign in
+ // again"), yet nothing else in Settings re-authenticates a cloud row. Run
+ // the one recovery that exists for this state — drop the lapsed cookies,
+ // ensure the portal session, silent-cascade the agent — then retry the
+ // switch once. Everything else stays a plain failed switch.
+ const selectSavedCloudWithReauth = async (id: string, url: string) => {
+ try {
+ await selectConnection(id)
+ } catch (error) {
+ if (!isGatewayReauthRequired(error)) {
+ throw error
+ }
+
+ const desktop = window.hermesDesktop
+
+ if (!desktop?.cloud) {
+ throw error
+ }
+
+ const outcome = await reestablishCloudAgentSession(desktop, url)
+
+ if (outcome !== 'connected') {
+ notify({
+ kind: 'warning',
+ title: t.boot.failure.signInIncompleteTitle,
+ message: t.boot.failure.signInIncompleteMessage
+ })
+
+ throw error
+ }
+
+ await selectConnection(id)
+ }
+ }
+
+ const activateSavedCloud = async (id: string, url: string) => {
setCloudConnectingId(id)
try {
- await selectConnection(id)
+ await selectSavedCloudWithReauth(id, url)
} catch (err) {
notifyError(err, g.cloudConnectFailed)
} finally {
@@ -1039,7 +1078,7 @@ function GatewayConnectionSettings({ embedded, standalone }: { embedded: boolean
await refreshConnectionsRegistry()
}
- await selectConnection(saved.id)
+ await selectSavedCloudWithReauth(saved.id, agent.dashboardUrl)
return
}
@@ -1320,7 +1359,7 @@ function GatewayConnectionSettings({ embedded, standalone }: { embedded: boolean
) : (
<Button
disabled={cloudConnectingId !== null}
- onClick={() => void activateSavedCloud(connection.id)}
+ onClick={() => void activateSavedCloud(connection.id, connection.url || '')}
size="sm"
variant="outline"
>
diff --git a/apps/desktop/src/components/boot-failure-overlay.tsx b/apps/desktop/src/components/boot-failure-overlay.tsx
index 7f9fa3d4104..b3364586ad6 100644
--- a/apps/desktop/src/components/boot-failure-overlay.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.tsx
@@ -9,6 +9,7 @@ import { Loader } from '@/components/ui/loader'
import { LogView } from '@/components/ui/log-view'
import type { DesktopConnectionConfig } from '@/global'
import { useI18n } from '@/i18n'
+import { reestablishCloudAgentSession } from '@/lib/cloud-agent-session'
import { openExternalLink } from '@/lib/external-link'
import { ChevronLeft, ExternalLink, FileText, Loader2, LogIn, RefreshCw, SlidersHorizontal, Wrench } from '@/lib/icons'
import { $desktopBoot } from '@/store/boot'
@@ -194,6 +195,8 @@ export function BootFailureOverlay() {
// connection's owning login flow. Hermes Cloud must reuse its portal session
// and per-agent cascade; generic remote gateways use native/embedded OAuth.
// Reload after success so boot mints a fresh ticket against the new session.
+ // The cloud ladder is shared with Settings (reestablishCloudAgentSession) so
+ // the boot recovery and the in-Settings recovery cannot drift apart.
const signInRemote = async () => {
if (!remoteReauth) {
return
@@ -206,31 +209,27 @@ export function BootFailureOverlay() {
await desktop?.oauthLogoutConnectionConfig?.(remoteReauth.url)
- let result: { connected?: boolean } | undefined
+ let connected: boolean
if (connectionConfig?.mode === 'cloud' && desktop?.cloud) {
- const status = await desktop.cloud.status()
+ const outcome = await reestablishCloudAgentSession(desktop, remoteReauth.url)
- if (!status.signedIn) {
- const login = await desktop.cloud.login()
+ if (outcome === 'portal-incomplete') {
+ notify({
+ kind: 'warning',
+ title: t.boot.failure.signInIncompleteTitle,
+ message: t.boot.failure.signInIncompleteMessage
+ })
- if (!login.signedIn) {
- notify({
- kind: 'warning',
- title: t.boot.failure.signInIncompleteTitle,
- message: t.boot.failure.signInIncompleteMessage
- })
-
- return
- }
+ return
}
- result = await desktop.cloud.agentSignIn(remoteReauth.url)
+ connected = true
} else {
- result = await desktop?.oauthLoginConnectionConfig(remoteReauth.url)
+ connected = (await desktop?.oauthLoginConnectionConfig(remoteReauth.url))?.connected === true
}
- if (result?.connected) {
+ if (connected) {
if (connectionConfig?.mode === 'cloud') {
await desktop?.resetBootstrap().catch(() => undefined)
}
diff --git a/apps/desktop/src/lib/cloud-agent-session.ts b/apps/desktop/src/lib/cloud-agent-session.ts
new file mode 100644
index 00000000000..d4fa40b97e2
--- /dev/null
+++ b/apps/desktop/src/lib/cloud-agent-session.ts
@@ -0,0 +1,74 @@
+import type { DesktopCloudAgentSignInResult } from '@/global'
+
+/**
+ * Re-establish a Hermes Cloud agent's gateway session from the shared portal
+ * session: drop any lapsed gateway cookies, make sure the portal session is
+ * live (interactive login window when it has lapsed), then run the silent
+ * per-agent cascade so a fresh gateway session cookie lands for `url`.
+ *
+ * This is the recovery behind the "Open Settings → Gateway and sign in again"
+ * copy: a saved cloud connection on a local-primary device has no other
+ * sign-in surface when its gateway session lapses. The boot overlay used this
+ * sequence inline; Settings reuses the exact same ladder so there is ONE
+ * recovery path, not two that drift.
+ */
+
+export interface CloudAgentSessionBridge {
+ cloud?: {
+ status: () => Promise<{ signedIn: boolean }>
+ login: () => Promise<{ ok: boolean; signedIn: boolean }>
+ agentSignIn: (dashboardUrl: string) => Promise<DesktopCloudAgentSignInResult>
+ }
+ oauthLogoutConnectionConfig?: (url: string) => Promise<unknown>
+}
+
+/**
+ * One silent cascade attempt against `url`. Assumes the portal session is
+ * live (call `ensureCloudPortalSession` first); returns whether the gateway
+ * session cookie landed.
+ */
+async function cascadeCloudAgentSession(
+ desktop: CloudAgentSessionBridge,
+ url: string
+): Promise<boolean> {
+ const result = await desktop.cloud!.agentSignIn(url)
+
+ return result.connected === true
+}
+
+/** True when the portal session is live, signing in (a login window) when it is not. */
+async function ensureCloudPortalSession(desktop: CloudAgentSessionBridge): Promise<boolean> {
+ const status = await desktop.cloud!.status()
+
+ if (!status.signedIn) {
+ const login = await desktop.cloud!.login()
+
+ if (!login.signedIn) {
+ return false
+ }
+ }
+
+ return true
+}
+
+/**
+ * Full recovery ladder for one cloud agent's gateway session. Returns
+ * `'connected'` when the silent cascade landed a fresh gateway session,
+ * `'portal-incomplete'` when the interactive portal login never completed,
+ * or throws the underlying error (network, portal outage, cascade failure)
+ * for the caller to surface the way it already surfaces failures.
+ */
+export async function reestablishCloudAgentSession(
+ desktop: CloudAgentSessionBridge,
+ url: string
+): Promise<'connected' | 'portal-incomplete'> {
+ // Drop this gateway's lapsed cookies first — a dead AT/RT pair must not be
+ // mistaken for a live session by the cascade or any liveness probe.
+ await desktop.oauthLogoutConnectionConfig?.(url)
+
+ if (!(await ensureCloudPortalSession(desktop))) {
+ return 'portal-incomplete'
+ }
+
+ return (await cascadeCloudAgentSession(desktop, url)) ? 'connected' : 'portal-incomplete'
+}
\ No newline at end of file