The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep background roster auth from opening login (#125972)
Gille83597d9b7127
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 07cc3f25e0e..61f8093aca9 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -369,9 +369,11 @@ import { isExpectedOauthNavigationAbort } from './oauth-navigation'import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'import {+ canShowInteractiveOauthLogin,mintGatewayWsTicket as mintOauthGatewayWsTicket,requestWithOauthFallback,- shouldReplayAfterCookie401+ retryCookie401WithLogin,+ withoutInteractiveOauthLogin} from './oauth-rest-request'import { wireOauthSessionResponse } from './oauth-session-response'import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'@@ -7629,6 +7631,10 @@ function openOauthLoginWindow({ silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}) {return new Promise((resolve, reject) => {+ // Background roster work may silently renew a Cloud session, but must+ // never turn an expired saved gateway into a visible login window.+ const hiddenRecovery = background || !canShowInteractiveOauthLogin()+if (!app.isReady()) {reject(new Error('Desktop is not ready to start an OAuth login.'))@@ -7711,7 +7717,7 @@ function openOauthLoginWindow(// only reveal it as a fallback if the cascade DOESN'T complete quickly// (e.g. the portal session lapsed and the gate fell through to the// interactive chooser) — see the reveal timer below.- show: !silent && !background,+ show: !silent && !hiddenRecovery,webPreferences: {contextIsolation: true,nodeIntegration: false,@@ -7743,7 +7749,7 @@ function openOauthLoginWindow(// loop-guard tripped, etc.) and the window is now showing an interactive// page. Reveal it so the user can complete sign-in manually rather than// staring at nothing. Cleared on finish().- if (silent && win && !background) {+ if (silent && win && !hiddenRecovery) {revealTimer = setTimeout(() => {try {if (!settled && win && !win.isDestroyed() && !win.isVisible()) {@@ -7755,7 +7761,7 @@ function openOauthLoginWindow(}, 2500)}- if (background) {+ if (hiddenRecovery) {deadlineTimer = setTimeout(() => finish(new Error('Cloud session recovery requires sign-in.')), 12_000)}@@ -7780,7 +7786,7 @@ function openOauthLoginWindow(win.loadURL(loginUrl, oauthLoginLoadUrlOptions(loginHeaders)).catch(error => {// Callback navigation can abort the original load after setting cookies.// Keep the bounded hidden recovery alive long enough to observe them.- if (background && isExpectedOauthNavigationAbort(error)) {+ if (hiddenRecovery && isExpectedOauthNavigationAbort(error)) {void checkCookie()return@@ -7908,23 +7914,20 @@ function fetchJsonViaOauthSession(url, options: any = {}) {})return attempt().catch(async error => {- if (!shouldReplayAfterCookie401(error, options)) {- throw error- }-- // Stale mirror + dead jar: force one silent re-login, then retry once.- remoteSessionCookies.clear(partition, url)-- try {- await openOauthLoginWindow(new URL(url).origin, { silent: true })- } catch (reloginError) {- rememberLog(- `Remote session re-login after 401 failed for ${new URL(url).host}: ${reloginError?.message || reloginError}`- )- throw error- }-- return attempt()+ return retryCookie401WithLogin(error, options, {+ clearCookies: () => remoteSessionCookies.clear(partition, url),+ login: async () => {+ try {+ await openOauthLoginWindow(new URL(url).origin, { silent: true })+ } catch (reloginError) {+ rememberLog(+ `Remote session re-login after 401 failed for ${new URL(url).host}: ${reloginError?.message || reloginError}`+ )+ throw reloginError+ }+ },+ retry: attempt+ })})}@@ -16136,7 +16139,7 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe}}- return Promise.all(+ return withoutInteractiveOauthLogin(() => Promise.all(registry.connections.map(async connection => {let sourceFailureDetail = ''@@ -16262,7 +16265,8 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsReconnection,profiles: null,error: redactSecrets(String(error?.message || error)),- needsSignIn: isReauthRequiredError(error)+ needsSignIn: isReauthRequiredError(error) ||+ (connection.authMode === 'oauth' && isGatewayAuthRejection(error))}}@@ -16293,7 +16297,7 @@ async function enumerateRegistryAgentSources(registry = readDesktopConnectionsRe...(raw.profileMetadata ? { profileMetadata: raw.profileMetadata } : {})}})- )+ ))}ipcMain.handle('hermes:agents:roster', async () => {diff --git a/apps/desktop/electron/oauth-rest-request.test.ts b/apps/desktop/electron/oauth-rest-request.test.tsindex df423a904d0..a1905fa5535 100644--- a/apps/desktop/electron/oauth-rest-request.test.ts+++ b/apps/desktop/electron/oauth-rest-request.test.ts@@ -3,7 +3,14 @@ import { expect, test } from 'vitest'import { httpStatusError } from './api-transport'import { isGatewayAuthRejection } from './connection-config'import { NativeAuthChangedError } from './native-access-token'-import { mintGatewayWsTicket, requestWithOauthFallback, shouldReplayAfterCookie401 } from './oauth-rest-request'+import {+ canShowInteractiveOauthLogin,+ mintGatewayWsTicket,+ requestWithOauthFallback,+ retryCookie401WithLogin,+ shouldReplayAfterCookie401,+ withoutInteractiveOauthLogin+} from './oauth-rest-request'const GATE_401 = () =>httpStatusError(@@ -45,6 +52,117 @@ test('a cookie 401 is replayed only for a gate refusal on an idempotent or vouchexpect(shouldReplayAfterCookie401(new Error('socket reset'), {})).toBe(false)})+test('background roster auth leaves a gate 401 for the source row without clearing cookies or opening login', async () => {+ const refusal = GATE_401()+ const actions: string[] = []++ const recover = () =>+ retryCookie401WithLogin(+ refusal,+ { method: 'GET' },+ {+ clearCookies: () => {+ actions.push('clear')+ },+ login: async () => {+ actions.push('login')+ },+ retry: async () => {+ actions.push('retry')++ return 'ok'+ }+ }+ )++ await expect(+ withoutInteractiveOauthLogin(async () => {+ await Promise.resolve()++ return recover()+ })+ ).rejects.toBe(refusal)+ expect(actions).toEqual([])++ // A separate foreground request retains the existing one-login, one-retry path.+ expect(await recover()).toBe('ok')+ expect(actions).toEqual(['clear', 'login', 'retry'])+})++test('background auth intent stays isolated from a concurrent foreground request', async () => {+ const refusal = GATE_401()++ let releaseBackground: () => void = () => {}++ const backgroundReady = new Promise<void>(resolve => {+ releaseBackground = resolve+ })++ let foregroundLogins = 0++ const background = withoutInteractiveOauthLogin(async () => {+ await backgroundReady+ expect(canShowInteractiveOauthLogin()).toBe(false)++ return retryCookie401WithLogin(+ refusal,+ {},+ {+ clearCookies: () => {+ throw new Error('background cookies cleared')+ },+ login: async () => {+ throw new Error('background login opened')+ },+ retry: async () => 'unexpected'+ }+ )+ })++ const foreground = retryCookie401WithLogin(+ refusal,+ {},+ {+ clearCookies: () => {},+ login: async () => {+ foregroundLogins += 1+ },+ retry: async () => 'foreground recovered'+ }+ )++ releaseBackground()++ await expect(background).rejects.toBe(refusal)+ expect(canShowInteractiveOauthLogin()).toBe(true)+ expect(await foreground).toBe('foreground recovered')+ expect(foregroundLogins).toBe(1)+})++test('failed foreground re-login returns the original gate refusal without retrying', async () => {+ const refusal = GATE_401()+ let retries = 0++ await expect(+ retryCookie401WithLogin(+ refusal,+ {},+ {+ clearCookies: () => {},+ login: async () => {+ throw new Error('login window closed')+ },+ retry: async () => {+ retries += 1++ return 'unexpected'+ }+ }+ )+ ).rejects.toBe(refusal)+ expect(retries).toBe(0)+})+test('ws-ticket minting vouches for replay on a cookie 401', async () => {let seen: anydiff --git a/apps/desktop/electron/oauth-rest-request.ts b/apps/desktop/electron/oauth-rest-request.tsindex 158d77742a8..60cba284832 100644--- a/apps/desktop/electron/oauth-rest-request.ts+++ b/apps/desktop/electron/oauth-rest-request.ts@@ -1,3 +1,5 @@+import { AsyncLocalStorage } from 'node:async_hooks'+import { readJsonErrorBody, readStatusCode } from './api-transport'import { isGatewayAuthRejection } from './connection-config'import { type NativeAccessTokenOptions, NativeAuthChangedError } from './native-access-token'@@ -57,6 +59,38 @@ export interface MintGatewayWsTicketDeps {fetchJsonViaOauthSession: (url: string, options: any) => Promise<any>}+// Roster polling reads saved gateways in the background. Its auth failures+// belong on the source row, not in a login window over the active workspace.+const interactiveLoginAllowed = new AsyncLocalStorage<boolean>()++export function withoutInteractiveOauthLogin<T>(work: () => Promise<T>): Promise<T> {+ return interactiveLoginAllowed.run(false, work)+}++export function canShowInteractiveOauthLogin(): boolean {+ return interactiveLoginAllowed.getStore() !== false+}++export async function retryCookie401WithLogin<T>(+ error: unknown,+ options: { method?: unknown; replayOn401?: unknown },+ actions: { clearCookies: () => void; login: () => Promise<unknown>; retry: () => Promise<T> }+): Promise<T> {+ if (!canShowInteractiveOauthLogin() || !shouldReplayAfterCookie401(error, options)) {+ throw error+ }++ actions.clearCookies()++ try {+ await actions.login()+ } catch {+ throw error+ }++ return actions.retry()+}+/*** Whether a cookie-mode 401 may be answered by ONE silent re-login and a* single resubmission of the same request (#61457). The no-replay rule above