Skip to content

The agent that grows with you

fix(desktop): unattended sign-in never shows a window

Austin Pickett5907cb1a8d8f
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 4c3473eb596..d59ff7c1197 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -402,7 +402,8 @@ import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
import { execGit, killTimedGitChildren, setNoConsoleGitRoots } from './no-console-git'
import { registerNativeNotifications } from './notification-ipc'
-import { type LoginAttempt, loginFlightKey, OauthLoginFlights } from './oauth-login-flights'
+import { loginFlightKey, OauthLoginFlights } from './oauth-login-flights'
+import { startOauthLoginWindow } from './oauth-login-window'
import { isExpectedOauthNavigationAbort } from './oauth-navigation'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
@@ -6183,7 +6184,9 @@ async function waitForRemoteHermes(remote) {
rememberLog('[cloud] boot: agent session rejected but portal session is live, running silent sign-in')
try {
- await cloudAgentSilentSignIn(remote.baseUrl)
+ // Boot re-runs on wake and renderer retries, not only on a click: keep
+ // the cascade hidden and let the overlay's Sign in button own any prompt.
+ await cloudAgentSilentSignIn(remote.baseUrl, { background: true })
} catch (cascadeError) {
rememberLog(`[cloud] boot: silent sign-in did not complete: ${cascadeError?.message || cascadeError}`)
@@ -7300,243 +7303,68 @@ async function clearOauthSession(baseUrl) {
}
}
-// Open a gateway login window in the OAuth session partition, resolving once
-// the access-token cookie appears (login done) or rejecting if the window is
-// closed first. The window navigates through the IDP and back to
-// /auth/callback, which sets the session cookies on the partition; we poll the
-// cookie jar rather than try to read the HttpOnly value.
-//
-// `silent` selects the URL the window loads:
-// - silent=false (default): ``/login``, the public provider chooser the
-// settings UI drives.
-// - silent=true: the PROTECTED root ``/``. With no session cookie the gate
-// runs ``_auto_sso_response``: single provider + a live portal session in
-// this partition → silent 302 through ``/auth/login`` → portal
-// ``/oauth/authorize`` → ``/auth/callback``, no prompt (decisions.md Q5).
-//
-// `background` (or a withoutInteractiveOauthLogin scope) means nobody asked
-// for this sign-in: the window stays hidden and gives up after 12s. Only a
-// user-driven caller may show a window. oauth-login-flights.ts keeps one flow
-// per cookie jar, so a burst of callers shares one window.
+// Open a gateway login window in the OAuth session partition; window mechanics
+// and the silent/background contract live in oauth-login-window.ts. A refused
+// background request is never a user gesture, so `background` (or a
+// withoutInteractiveOauthLogin scope) keeps the window hidden; only a
+// user-driven caller may show one. oauth-login-flights.ts keeps one flow per
+// cookie jar, so a burst of callers shares one window.
const oauthLoginFlights = new OauthLoginFlights()
-function openOauthLoginWindow(baseUrl, options: OauthLoginWindowOptions = {}) {
- const { connectionId = '', pendingAuthMode = '', pendingKind = '' } = options
- const background = Boolean(options.background) || !canShowInteractiveOauthLogin()
- const partition = resolveOauthPartitionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind })
- const key = loginFlightKey(partition, baseUrl)
-
- return oauthLoginFlights.run(key, background ? 'background' : 'foreground', () =>
- startOauthLoginWindow(baseUrl, { ...options, background })
- )
-}
-
-interface OauthLoginWindowOptions {
- silent?: boolean
- background?: boolean
- connectionId?: string
- pendingAuthMode?: string
- pendingKind?: string
-}
-
-type OauthLoginOutcome = { baseUrl: string; ok: boolean }
-
-function startOauthLoginWindow(baseUrl, options: OauthLoginWindowOptions = {}): LoginAttempt<OauthLoginOutcome> {
- const { silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = options
-
- let reveal = (): void => {}
-
- const result = new Promise<OauthLoginOutcome>((resolve, reject) => {
- // Unattended recovery may silently renew a session, but must never turn
- // an expired gateway into a visible login window (a user click promotes
- // it through reveal() below).
- let hiddenRecovery = background
-
- if (!app.isReady()) {
- reject(new Error('Desktop is not ready to start an OAuth login.'))
-
- return
- }
+function openOauthLoginWindow(
+ baseUrl,
+ { silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}
+) {
+ const identity = { connectionId, pendingAuthMode, pendingKind }
+ const unattended = background || !canShowInteractiveOauthLogin()
+ const partition = resolveOauthPartitionForUrl(baseUrl, identity)
- const sess = getOauthSessionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind })
+ return oauthLoginFlights.run(loginFlightKey(partition, baseUrl), unattended ? 'background' : 'foreground', () => {
+ const sess = app.isReady() ? getOauthSessionForUrl(baseUrl, identity) : null
if (!sess) {
- reject(new Error('OAuth session partition is unavailable.'))
-
- return
- }
-
- let settled = false
- let win = null
- let pollTimer = null
- let revealTimer = null
- let deadlineTimer = null
-
- const finish = err => {
- if (settled) {
- return
- }
-
- settled = true
-
- if (pollTimer) {
- clearInterval(pollTimer)
- }
-
- if (revealTimer) {
- clearTimeout(revealTimer)
- }
-
- if (deadlineTimer) {
- clearTimeout(deadlineTimer)
- }
-
- try {
- if (win && !win.isDestroyed()) {
- win.destroy()
- }
- } catch {
- // window already torn down
- }
-
- if (err) {
- reject(err)
- } else {
- // #61457: the jar just got the fresh session cookies — mirror them
- // into memory immediately, before the jar can drop them again.
- void captureRemoteSessionCookiesIntoMirror(
- sess,
- resolveOauthPartitionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind }),
- baseUrl
- )
- resolve({ baseUrl, ok: true })
- }
- }
-
- const checkCookie = async () => {
- if (settled) {
- return
- }
-
- if (await hasOauthSessionCookie(baseUrl, { connectionId, pendingAuthMode, pendingKind })) {
- finish(null)
- }
- }
-
- try {
- win = new BrowserWindow({
- width: 520,
- height: 720,
- title: silent ? 'Connecting to Hermes Cloud agent…' : 'Sign in to Hermes gateway',
- autoHideMenuBar: true,
- // Silent cascade: start HIDDEN. The auto-SSO 302 chain completes in
- // well under a second, so the window normally never needs to show. We
- // 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 && !hiddenRecovery,
- webPreferences: {
- contextIsolation: true,
- nodeIntegration: false,
- sandbox: true,
- session: sess,
- webSecurity: true
- }
- })
- } catch (error) {
- finish(error instanceof Error ? error : new Error(String(error)))
-
- return
- }
-
- // Re-check the cookie jar on every successful navigation (the callback
- // redirect is the moment cookies get set) plus a low-frequency poll as a
- // belt-and-braces fallback for IDPs that finish via in-page JS.
- win.webContents.on('did-navigate', () => void checkCookie())
- win.webContents.on('did-redirect-navigation', () => void checkCookie())
- win.webContents.on('did-frame-navigate', () => void checkCookie())
- // Log-only lifecycle diagnostics: a crashed sign-in renderer is invisible
- // to the window's promise path (it never settles), so without this the
- // failure leaves no trace in desktop.log (#81290 follow-up).
- installWindowRendererLifecycle(win, { kind: 'oauth', callbacks: { log: rememberLog } })
- pollTimer = setInterval(() => void checkCookie(), 750)
-
- // Silent-mode reveal fallback: if the cascade hasn't settled shortly, the
- // auto-SSO didn't go through silently (no portal session, multi-provider,
- // 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 && !hiddenRecovery) {
- revealTimer = setTimeout(() => {
- try {
- if (!settled && win && !win.isDestroyed() && !win.isVisible()) {
- win.show()
- }
- } catch {
- // window torn down
- }
- }, 2500)
- }
-
- if (hiddenRecovery) {
- deadlineTimer = setTimeout(() => finish(new Error('Silent sign-in did not complete; sign-in required.')), 12_000)
+ throw new Error(
+ app.isReady() ? 'OAuth session partition is unavailable.' : 'Desktop is not ready to start an OAuth login.'
+ )
}
- // A user's click joined this flow: show the window it already has (a
- // second window would replace the gateway's PKCE state cookie) and drop
- // the unattended deadline so they have time to finish.
- reveal = () => {
- if (settled || !win || win.isDestroyed()) {
- return
- }
-
- hiddenRecovery = false
-
- if (deadlineTimer) {
- clearTimeout(deadlineTimer)
- deadlineTimer = null
- }
-
- try {
- win.show()
- win.focus()
- } catch {
- // window torn down
- }
- }
+ return startOauthLoginWindow(
+ { baseUrl: normalizeRemoteBaseUrl(baseUrl), session: sess, silent, background: unattended },
+ {
+ createWindow: ({ session: windowSession, show, title }) =>
+ new BrowserWindow({
+ width: 520,
+ height: 720,
+ title,
+ autoHideMenuBar: true,
+ show,
+ webPreferences: {
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ session: windowSession,
+ webSecurity: true
+ }
+ }),
+ hasSessionCookie: () => hasOauthSessionCookie(baseUrl, identity),
+ isExpectedNavigationAbort: isExpectedOauthNavigationAbort,
+ loadOptionsFor: loginUrl => {
+ const loginHeaders = headersForRemoteRequest(loginUrl)
+ rememberLog(
+ `OAuth login: attaching ${Object.keys(loginHeaders).length} extra gateway header(s) to ${new URL(loginUrl).host}`
+ )
- win.on('closed', () => {
- if (!settled) {
- finish(new Error('Login window closed before authentication completed.'))
+ return oauthLoginLoadUrlOptions(loginHeaders)
+ },
+ log: rememberLog,
+ // #61457: mirror the fresh cookies before the jar can drop them again.
+ onLanded: () => void captureRemoteSessionCookiesIntoMirror(sess, partition, baseUrl),
+ // A crashed sign-in renderer never settles the promise; log it (#81290).
+ onWindowCreated: win =>
+ installWindowRendererLifecycle(win as BrowserWindow, { kind: 'oauth', callbacks: { log: rememberLog } })
}
- })
-
- // ``next`` is intentionally omitted: the gateway lands on ``/`` after
- // login, which is a valid authenticated page that sets the cookies. We
- // only care that the cookie jar is populated.
- //
- // silent=true loads the protected root so the gate auto-SSOs (no chooser);
- // silent=false loads the public ``/login`` chooser for interactive sign-in.
- const normalizedBase = normalizeRemoteBaseUrl(baseUrl)
- const loginUrl = silent ? `${normalizedBase}/` : `${normalizedBase}/login`
- const loginHeaders = headersForRemoteRequest(loginUrl)
- rememberLog(
- `OAuth login: attaching ${Object.keys(loginHeaders).length} extra gateway header(s) to ${new URL(normalizedBase).host}`
)
- 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 (hiddenRecovery && isExpectedOauthNavigationAbort(error)) {
- void checkCookie()
-
- return
- }
-
- finish(error instanceof Error ? error : new Error(String(error)))
- })
})
-
- return { result, reveal: () => reveal() }
}
// JSON request routed through the OAuth session partition so the HttpOnly
@@ -7668,7 +7496,10 @@ function fetchJsonViaOauthSession(url, options: any = {}) {
},
login: async () => {
try {
- await openOauthLoginWindow(origin, { silent: true })
+ // A refused request is never a user gesture: try the hidden
+ // auto-SSO, and on failure leave the 401 to the app's own "Sign in"
+ // surface instead of opening a window nobody asked for.
+ await openOauthLoginWindow(origin, { silent: true, background: true })
} catch (reloginError) {
rememberLog(
`Remote session re-login after 401 failed for ${new URL(url).host}: ${reloginError?.message || reloginError}`
@@ -8157,7 +7988,7 @@ function trimCloudAgents(body) {
// if the portal session were absent it would fall through to an interactive
// login, which the discovery gate already prevents). Returns once the agent's
// gateway session cookie is present.
-async function cloudAgentSilentSignIn(dashboardUrl) {
+async function cloudAgentSilentSignIn(dashboardUrl, { background = false } = {}) {
const baseUrl = normalizeRemoteBaseUrl(dashboardUrl)
// Pre-req: a live portal session must exist, or this would surface an
@@ -8177,7 +8008,7 @@ async function cloudAgentSilentSignIn(dashboardUrl) {
await renewPortalAccessSilently()
}
- await openOauthLoginWindow(baseUrl, { silent: true })
+ await openOauthLoginWindow(baseUrl, { silent: true, background })
return { baseUrl, connected: await hasOauthSessionCookie(baseUrl) }
}
diff --git a/apps/desktop/electron/oauth-login-flights.test.ts b/apps/desktop/electron/oauth-login-flights.test.ts
index 4d15ba4b875..653686dfb82 100644
--- a/apps/desktop/electron/oauth-login-flights.test.ts
+++ b/apps/desktop/electron/oauth-login-flights.test.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from 'node:fs'
+
import { afterEach, expect, test, vi } from 'vitest'
import {
@@ -184,3 +186,16 @@ test('the flight key is the jar plus the gateway origin', () => {
expect(loginFlightKey(JAR, 'https://other.example.test')).not.toBe(KEY)
expect(loginFlightKey(`${JAR}-conn-x`, GATEWAY)).not.toBe(KEY)
})
+
+// main.ts is not importable under vitest; pin which callers count as unattended.
+test('refused requests and the boot cascade sign in hidden; only user actions may show a window', () => {
+ const source = readFileSync(new URL('./main.ts', import.meta.url), 'utf8')
+ const fetchStart = source.indexOf('function fetchJsonViaOauthSession(')
+ const fetchBody = source.slice(fetchStart, source.indexOf('\n}\n', fetchStart))
+ const bootStart = source.indexOf('async function waitForRemoteHermes(')
+ const bootBody = source.slice(bootStart, source.indexOf('\n}\n', bootStart))
+
+ expect(fetchBody).toContain('openOauthLoginWindow(origin, { silent: true, background: true })')
+ expect(bootBody).toContain('cloudAgentSilentSignIn(remote.baseUrl, { background: true })')
+ expect(source).toContain("unattended ? 'background' : 'foreground'")
+})
diff --git a/apps/desktop/electron/oauth-login-window.test.ts b/apps/desktop/electron/oauth-login-window.test.ts
new file mode 100644
index 00000000000..b8bfe8138e8
--- /dev/null
+++ b/apps/desktop/electron/oauth-login-window.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+
+import { OauthLoginFlights } from './oauth-login-flights'
+import { type OauthLoginWindowLike, startOauthLoginWindow } from './oauth-login-window'
+
+const GATEWAY = 'https://fedora.example.ts.net'
+
+/** A login window double that records visibility and lets a test fire events. */
+function fakeWindow() {
+ const closed: Array<() => void> = []
+ const navigations: Array<(event: unknown, url: string) => void> = []
+
+ const state = { destroyed: false, focused: 0, loaded: '', shown: false, visible: false }
+
+ const win: OauthLoginWindowLike = {
+ destroy: () => {
+ state.destroyed = true
+ },
+ focus: () => {
+ state.focused += 1
+ },
+ isDestroyed: () => state.destroyed,
+ isVisible: () => state.visible,
+ loadURL: async url => {
+ state.loaded = url
+ },
+ on: (_event, listener) => closed.push(listener),
+ show: () => {
+ state.shown = true
+ state.visible = true
+ },
+ webContents: {
+ on: (event, listener) => {
+ if (event === 'did-navigate') {
+ navigations.push(listener)
+ }
+ }
+ }
+ }
+
+ return {
+ close: () => closed.forEach(listener => listener()),
+ navigate: (url = `${GATEWAY}/`) => navigations.forEach(listener => listener({}, url)),
+ state,
+ win
+ }
+}
+
+function harness(cookie = { present: false }) {
+ const windows: Array<ReturnType<typeof fakeWindow>> = []
+ const created: Array<{ show: boolean; title: string }> = []
+
+ const deps = {
+ createWindow: (options: { session: string; show: boolean; title: string }) => {
+ const handle = fakeWindow()
+ handle.state.visible = options.show
+ windows.push(handle)
+ created.push({ show: options.show, title: options.title })
+
+ return handle.win
+ },
+ hasSessionCookie: async () => cookie.present,
+ isExpectedNavigationAbort: () => false,
+ loadOptionsFor: () => ({}),
+ log: () => {},
+ onLanded: vi.fn()
+ }
+
+ const start = (request: { silent: boolean; background: boolean }) =>
+ startOauthLoginWindow({ baseUrl: GATEWAY, session: 'jar', ...request }, deps)
+
+ return { cookie, created, deps, start, windows }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+test('an unattended sign-in never shows its window and gives up after the deadline', async () => {
+ const h = harness()
+ const attempt = h.start({ silent: true, background: true })
+ const outcome = attempt.result.catch(error => error)
+
+ expect(h.created).toEqual([{ show: false, title: 'Connecting to Hermes Cloud agent…' }])
+ expect(h.windows[0].state.loaded).toBe(`${GATEWAY}/`)
+
+ // Past the 2.5s reveal point a foreground silent window would have shown.
+ await vi.advanceTimersByTimeAsync(11_999)
+ expect(h.windows[0].state.shown).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(1)
+ expect(await outcome).toBeInstanceOf(Error)
+ expect(h.windows[0].state).toMatchObject({ destroyed: true, shown: false })
+})
+
+test('an unattended attempt that lands on the gateway chooser stops at once', async () => {
+ const h = harness()
+ const attempt = h.start({ silent: true, background: true })
+
+ h.windows[0].navigate(`${GATEWAY}/login?next=%2F`)
+ await expect(attempt.result).rejects.toThrow(/sign-in required/)
+ expect(h.windows[0].state).toMatchObject({ destroyed: true, shown: false })
+})
+
+test('a revealed attempt stays open on the chooser for the user', async () => {
+ const h = harness()
+ const attempt = h.start({ silent: true, background: true })
+ let settled = false
+
+ void attempt.result.then(
+ () => (settled = true),
+ () => (settled = true)
+ )
+ attempt.reveal()
+ h.windows[0].navigate(`${GATEWAY}/login`)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(settled).toBe(false)
+})
+
+test('a foreground silent sign-in reveals itself when auto-SSO does not finish', async () => {
+ const h = harness()
+
+ h.start({ silent: true, background: false })
+ expect(h.created[0].show).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(2_500)
+ expect(h.windows[0].state.shown).toBe(true)
+})
+
+test('an interactive sign-in opens visible on the provider chooser', () => {
+ const h = harness()
+
+ h.start({ silent: false, background: false })
+ expect(h.created).toEqual([{ show: true, title: 'Sign in to Hermes gateway' }])
+ expect(h.windows[0].state.loaded).toBe(`${GATEWAY}/login`)
+})
+
+test('reveal promotes a hidden attempt and lifts its unattended deadline', async () => {
+ const h = harness()
+ const attempt = h.start({ silent: true, background: true })
+ let settled = false
+
+ void attempt.result.then(
+ () => (settled = true),
+ () => (settled = true)
+ )
+
+ attempt.reveal()
+ expect(h.windows[0].state).toMatchObject({ focused: 1, shown: true })
+
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(settled).toBe(false)
+
+ h.cookie.present = true
+ h.windows[0].navigate()
+ await expect(attempt.result).resolves.toEqual({ baseUrl: GATEWAY, ok: true })
+ expect(h.deps.onLanded).toHaveBeenCalledTimes(1)
+})
+
+test('closing the window rejects the attempt', async () => {
+ const h = harness()
+ const attempt = h.start({ silent: false, background: false })
+
+ h.windows[0].close()
+ await expect(attempt.result).rejects.toThrow(/closed before authentication/)
+})
+
+test('overnight burst: ten refused requests open one hidden window and none is ever shown', async () => {
+ const h = harness()
+ const flights = new OauthLoginFlights({ joinTimeoutMs: 15_000 })
+ const key = `jar ${GATEWAY}`
+
+ const burst = Array.from({ length: 10 }, () =>
+ flights.run(key, 'background', () => h.start({ silent: true, background: true })).catch(error => error)
+ )
+
+ await vi.advanceTimersByTimeAsync(12_000)
+ const outcomes = await Promise.all(burst)
+
+ expect(outcomes.every(outcome => outcome instanceof Error)).toBe(true)
+ expect(h.windows).toHaveLength(1)
+ expect(h.windows[0].state.shown).toBe(false)
+
+ // The next poll right after is held by the backoff instead of opening another.
+ await expect(flights.run(key, 'background', () => h.start({ silent: true, background: true }))).rejects.toThrow(
+ /held/
+ )
+ expect(h.windows).toHaveLength(1)
+
+ // The user then clicks Sign in: one visible window, never held.
+ void flights.run(key, 'foreground', () => h.start({ silent: false, background: false }))
+ expect(h.windows).toHaveLength(2)
+ expect(h.windows[1].state.visible).toBe(true)
+})
diff --git a/apps/desktop/electron/oauth-login-window.ts b/apps/desktop/electron/oauth-login-window.ts
new file mode 100644
index 00000000000..36bc9215eca
--- /dev/null
+++ b/apps/desktop/electron/oauth-login-window.ts
@@ -0,0 +1,216 @@
+/**
+ * The embedded gateway sign-in window (cookie-mode OAuth).
+ *
+ * The window loads the gateway in the connection's cookie partition, follows
+ * the IdP round trip back to `/auth/callback`, and settles as soon as the
+ * session cookie lands. We poll the jar because the cookie is HttpOnly.
+ *
+ * `silent` selects the URL:
+ * - false: `/login`, the public provider chooser the settings UI drives.
+ * - true: the protected root `/`. With no session cookie the gate runs
+ * `_auto_sso_response`: single provider + a live portal session in this
+ * partition → 302 through `/auth/login` → portal `/oauth/authorize` →
+ * `/auth/callback`, with no prompt (decisions.md Q5).
+ *
+ * `background` means nobody asked for this sign-in. The window stays hidden
+ * and gives up after `deadlineMs`; it never reveals itself. Otherwise a silent
+ * window reveals itself after `revealAfterMs` when auto-SSO did not finish.
+ * `reveal()` promotes a hidden attempt when the user's own click joins it.
+ */
+
+import type { LoginAttempt } from './oauth-login-flights'
+
+export interface OauthLoginWindowLike {
+ destroy: () => void
+ focus: () => void
+ isDestroyed: () => boolean
+ isVisible: () => boolean
+ loadURL: (url: string, options?: unknown) => Promise<unknown>
+ on: (event: 'closed', listener: () => void) => unknown
+ show: () => void
+ webContents: { on: (event: string, listener: (...args: any[]) => void) => unknown }
+}
+
+export interface OauthLoginWindowDeps<S> {
+ createWindow: (options: { session: S; show: boolean; title: string }) => OauthLoginWindowLike
+ hasSessionCookie: () => Promise<boolean>
+ isExpectedNavigationAbort: (error: unknown) => boolean
+ loadOptionsFor: (loginUrl: string) => unknown
+ log: (message: string) => void
+ onLanded: () => void
+ onWindowCreated?: (win: OauthLoginWindowLike) => void
+ pollMs?: number
+ revealAfterMs?: number
+ deadlineMs?: number
+}
+
+export interface OauthLoginWindowRequest<S> {
+ baseUrl: string
+ session: S
+ silent: boolean
+ background: boolean
+}
+
+export type OauthLoginOutcome = { baseUrl: string; ok: boolean }
+
+const SIGN_IN_REQUIRED = 'Silent sign-in did not complete; sign-in required.'
+
+export function startOauthLoginWindow<S>(
+ { baseUrl, session, silent, background }: OauthLoginWindowRequest<S>,
+ deps: OauthLoginWindowDeps<S>
+): LoginAttempt<OauthLoginOutcome> {
+ const { pollMs = 750, revealAfterMs = 2_500, deadlineMs = 12_000 } = deps
+
+ let reveal = (): void => {}
+
+ const result = new Promise<OauthLoginOutcome>((resolve, reject) => {
+ let hiddenRecovery = background
+ let settled = false
+ let win: OauthLoginWindowLike | null = null
+ let pollTimer: ReturnType<typeof setInterval> | null = null
+ let revealTimer: ReturnType<typeof setTimeout> | null = null
+ let deadlineTimer: ReturnType<typeof setTimeout> | null = null
+
+ const finish = (err: Error | null) => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+
+ if (pollTimer) {
+ clearInterval(pollTimer)
+ }
+
+ if (revealTimer) {
+ clearTimeout(revealTimer)
+ }
+
+ if (deadlineTimer) {
+ clearTimeout(deadlineTimer)
+ }
+
+ try {
+ if (win && !win.isDestroyed()) {
+ win.destroy()
+ }
+ } catch {
+ // window already torn down
+ }
+
+ if (err) {
+ reject(err)
+ } else {
+ deps.onLanded()
+ resolve({ baseUrl, ok: true })
+ }
+ }
+
+ const checkCookie = async () => {
+ if (!settled && (await deps.hasSessionCookie())) {
+ finish(null)
+ }
+ }
+
+ try {
+ win = deps.createWindow({
+ session,
+ title: silent ? 'Connecting to Hermes Cloud agent…' : 'Sign in to Hermes gateway',
+ // Silent windows start hidden: the auto-SSO chain normally finishes
+ // in well under a second and never needs to be seen.
+ show: !silent && !hiddenRecovery
+ })
+ } catch (error) {
+ finish(error instanceof Error ? error : new Error(String(error)))
+
+ return
+ }
+
+ const live = win
+
+ // Auto-SSO that cannot complete ends on the gateway's own chooser. A
+ // hidden attempt stops there instead of waiting out its deadline, so the
+ // app's Sign in prompt appears promptly.
+ const chooserUrl = `${baseUrl.replace(/\/+$/, '')}/login`
+
+ // Re-check on every navigation (the callback redirect sets the cookies)
+ // plus a slow poll for IdPs that finish via in-page JS.
+ live.webContents.on('did-navigate', (_event: unknown, url?: string) => {
+ if (hiddenRecovery && typeof url === 'string' && url.split(/[?#]/)[0] === chooserUrl) {
+ void deps.hasSessionCookie().then(present => finish(present ? null : new Error(SIGN_IN_REQUIRED)))
+
+ return
+ }
+
+ void checkCookie()
+ })
+ live.webContents.on('did-redirect-navigation', () => void checkCookie())
+ live.webContents.on('did-frame-navigate', () => void checkCookie())
+ deps.onWindowCreated?.(live)
+ pollTimer = setInterval(() => void checkCookie(), pollMs)
+
+ // Auto-SSO did not finish (no portal session, several providers, loop
+ // guard): the window now shows an interactive page the user asked for.
+ if (silent && !hiddenRecovery) {
+ revealTimer = setTimeout(() => {
+ try {
+ if (!settled && !live.isDestroyed() && !live.isVisible()) {
+ live.show()
+ }
+ } catch {
+ // window torn down
+ }
+ }, revealAfterMs)
+ }
+
+ if (hiddenRecovery) {
+ deadlineTimer = setTimeout(
+ () => finish(new Error('Silent sign-in did not complete; sign-in required.')),
+ deadlineMs
+ )
+ }
+
+ // The user's click joined this flow: show this window (a second one would
+ // replace the gateway's PKCE state cookie) and drop the unattended
+ // deadline so they have time to finish.
+ reveal = () => {
+ if (settled || live.isDestroyed()) {
+ return
+ }
+
+ hiddenRecovery = false
+
+ if (deadlineTimer) {
+ clearTimeout(deadlineTimer)
+ deadlineTimer = null
+ }
+
+ try {
+ live.show()
+ live.focus()
+ } catch {
+ // window torn down
+ }
+ }
+
+ live.on('closed', () => finish(new Error('Login window closed before authentication completed.')))
+
+ // `next` is omitted on purpose: the gateway lands on `/` after login,
+ // which sets the cookies; only the jar matters.
+ const loginUrl = silent ? `${baseUrl.replace(/\/+$/, '')}/` : chooserUrl
+
+ live.loadURL(loginUrl, deps.loadOptionsFor(loginUrl)).catch(error => {
+ // Callback navigation can abort the original load after setting cookies.
+ // Keep the bounded hidden recovery alive long enough to observe them.
+ if (hiddenRecovery && deps.isExpectedNavigationAbort(error)) {
+ void checkCookie()
+
+ return
+ }
+
+ finish(error instanceof Error ? error : new Error(String(error)))
+ })
+ })
+
+ return { result, reveal: () => reveal() }
+}