The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): share one silent OAuth re-login per gateway
xxxigm70b970af228c
diff --git a/apps/desktop/electron/oauth-login-coalescer.test.ts b/apps/desktop/electron/oauth-login-coalescer.test.tsnew file mode 100644index 00000000000..cdceafbe047--- /dev/null+++ b/apps/desktop/electron/oauth-login-coalescer.test.ts@@ -0,0 +1,177 @@+import { expect, test } from 'vitest'++import { loginKeyFor, SilentLoginCoalescer, SilentLoginSuppressedError } from './oauth-login-coalescer'++function fakeClock(start = 1_000_000) {+ let now = start++ return {+ now: () => now,+ advance: (ms: number) => {+ now += ms+ }+ }+}++function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (error: unknown) => void++ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })++ return { promise, resolve, reject }+}++const GATEWAY = 'https://gateway.example.test'+const KEY = loginKeyFor(GATEWAY)++test('concurrent silent logins for one gateway share a single attempt', async () => {+ const coalescer = new SilentLoginCoalescer()+ const first = deferred<string>()+ let calls = 0++ const login = () => {+ calls += 1++ return first.promise+ }++ const silent = { silent: true }+ const a = coalescer.run(KEY, login)+ const b = coalescer.run(KEY, login)+ const c = coalescer.runFor(`${GATEWAY}/api/status`, silent, () => login())++ expect(calls).toBe(1)++ first.resolve('ok')++ await expect(Promise.all([a, b, c])).resolves.toEqual(['ok', 'ok', 'ok'])+ expect(calls).toBe(1)+})++test('a silent login forwards the gateway url and options to a single opener', async () => {+ const coalescer = new SilentLoginCoalescer()+ const seen: Array<{ url: string; options: { silent?: boolean; background?: boolean } }> = []++ const open = (url: string, options: { silent?: boolean; background?: boolean }) => {+ seen.push({ url, options })++ return Promise.resolve('ok')+ }++ const options = { silent: true as const, background: true }++ await Promise.all([+ coalescer.runFor(`${GATEWAY}/api/status`, options, open),+ coalescer.runFor(GATEWAY, options, open)+ ])++ expect(seen).toEqual([{ url: `${GATEWAY}/api/status`, options }])+})++test('a failed silent login is not retried until its cooldown expires', async () => {+ const clock = fakeClock()+ const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })+ let calls = 0++ const login = () => {+ calls += 1++ return Promise.reject(new Error('Login window closed before authentication completed.'))+ }++ await expect(coalescer.run(KEY, login)).rejects.toThrow(/Login window closed/)+ expect(calls).toBe(1)++ const suppressed = await coalescer.run(KEY, login).then(+ () => null,+ error => error+ )++ expect(suppressed).toBeInstanceOf(SilentLoginSuppressedError)+ expect((suppressed as SilentLoginSuppressedError).retryAfterMs).toBe(5_000)+ expect(calls).toBe(1)++ clock.advance(5_000)+ await expect(coalescer.run(KEY, login)).rejects.toThrow(/Login window closed/)+ expect(calls).toBe(2)+})++test('the backoff doubles per consecutive failure and stops at the ceiling', async () => {+ const clock = fakeClock()+ const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 20_000 })+ const delays: number[] = []++ const fail = () => Promise.reject(new Error('nope'))++ for (let attempt = 0; attempt < 5; attempt += 1) {+ await expect(coalescer.run(KEY, fail)).rejects.toThrow(/nope/)+ delays.push(coalescer.cooldownRemainingMs(KEY))+ clock.advance(coalescer.cooldownRemainingMs(KEY))+ }++ expect(delays).toEqual([5_000, 10_000, 20_000, 20_000, 20_000])+})++test('a successful login clears the backoff', async () => {+ const clock = fakeClock()+ const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })++ await expect(coalescer.run(KEY, () => Promise.reject(new Error('nope')))).rejects.toThrow(/nope/)+ clock.advance(5_000)+ await expect(coalescer.run(KEY, () => Promise.resolve('ok'))).resolves.toBe('ok')+ expect(coalescer.cooldownRemainingMs(KEY)).toBe(0)++ await expect(coalescer.run(KEY, () => Promise.reject(new Error('nope')))).rejects.toThrow(/nope/)+ expect(coalescer.cooldownRemainingMs(KEY)).toBe(5_000)+})++test('separate gateways are coalesced independently', async () => {+ const coalescer = new SilentLoginCoalescer()+ let calls = 0++ const login = () => {+ calls += 1++ return Promise.resolve('ok')+ }++ await Promise.all([coalescer.run(KEY, login), coalescer.run(loginKeyFor('https://other.example.test'), login)])+ expect(calls).toBe(2)+})++test('an interactive sign-in is never coalesced and still receives the url', async () => {+ const clock = fakeClock()+ const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })+ const seen: string[] = []++ const open = (url: string) => {+ seen.push(url)++ return Promise.resolve('ok')+ }++ const silentAttempt = deferred<string>()+ const silent = coalescer.runFor(GATEWAY, { silent: true }, () => silentAttempt.promise)++ await Promise.all([+ coalescer.runFor(GATEWAY, { silent: false }, open),+ coalescer.runFor(GATEWAY, { silent: false }, open)+ ])+ expect(seen).toEqual([GATEWAY, GATEWAY])++ silentAttempt.reject(new Error('nope'))+ await expect(silent).rejects.toThrow(/nope/)+ await expect(coalescer.runFor(GATEWAY, { silent: false }, open)).resolves.toBe('ok')+ expect(seen).toEqual([GATEWAY, GATEWAY, GATEWAY])+})++test('the coalescing key is the gateway origin', () => {+ expect(loginKeyFor('https://gateway.example.test')).toBe('https://gateway.example.test')+ expect(loginKeyFor('https://gateway.example.test/some/path')).toBe('https://gateway.example.test')+ expect(loginKeyFor('http://127.0.0.1:9119')).toBe('http://127.0.0.1:9119')+ expect(loginKeyFor('https://gateway.example.test')).not.toBe(loginKeyFor('https://other.example.test'))+})diff --git a/apps/desktop/electron/oauth-login-coalescer.ts b/apps/desktop/electron/oauth-login-coalescer.tsnew file mode 100644index 00000000000..ab21df33f56--- /dev/null+++ b/apps/desktop/electron/oauth-login-coalescer.ts@@ -0,0 +1,143 @@+/**+ * One silent OAuth login window per gateway origin.+ *+ * A gated remote gateway answers every cookie-less request with+ * `401 {reason: "no_cookie"}`, and each refused request answers that with one+ * silent re-login (`retryCookie401WithLogin` → `openOauthLoginWindow`). A burst+ * — boot, sidebar polls, a wake while the network is still down — therefore+ * opened one BrowserWindow per request.+ *+ * Silent callers share one attempt: the jar either gains a session cookie or it+ * does not. After a failure the next silent attempt waits, so a closed or+ * unreachable window is not replaced once per incoming request. An interactive+ * sign-in is the user's own click and always opens immediately.+ *+ * `silent` also selects the URL the window loads:+ * - silent=false: `/login`, the provider chooser.+ * - silent=true: the protected root `/`, so the gate can auto-SSO through+ * portal `/oauth/authorize` back to `/auth/callback` without a chooser.+ */++export interface SilentLoginCoalescerOptions {+ now?: () => number+ baseDelayMs?: number+ maxDelayMs?: number+}++export class SilentLoginSuppressedError extends Error {+ readonly retryAfterMs: number++ constructor(retryAfterMs: number) {+ super(+ `A silent sign-in for this gateway failed recently; the next attempt is held for ${Math.ceil(retryAfterMs / 1000)}s.`+ )+ this.name = 'SilentLoginSuppressedError'+ this.retryAfterMs = retryAfterMs+ }+}++/** Session cookies belong to the origin, which is the scope one silent login serves. */+export function loginKeyFor(baseUrl: string): string {+ try {+ return new URL(baseUrl).origin+ } catch {+ return baseUrl+ }+}++export class SilentLoginCoalescer {+ private readonly now: () => number+ private readonly baseDelayMs: number+ private readonly maxDelayMs: number+ private readonly inFlight = new Map<string, Promise<unknown>>()+ private readonly failures = new Map<string, { consecutive: number; blockedUntil: number }>()++ constructor(options: SilentLoginCoalescerOptions = {}) {+ this.now = options.now ?? Date.now+ this.baseDelayMs = options.baseDelayMs ?? 5_000+ this.maxDelayMs = options.maxDelayMs ?? 60_000+ }++ /**+ * Open one login for `baseUrl`. The opener is always called as+ * `open(baseUrl, options)` — a zero-arg callback drops the gateway URL and+ * no window can load.+ */+ runFor<T, O extends { silent?: boolean }>(+ baseUrl: string,+ options: O,+ open: (baseUrl: string, options: O) => Promise<T>+ ): Promise<T> {+ if (options?.silent !== true) {+ return open(baseUrl, options)+ }++ return this.run(loginKeyFor(baseUrl), () => open(baseUrl, options))+ }++ cooldownRemainingMs(key: string): number {+ const failure = this.failures.get(key)++ if (!failure) {+ return 0+ }++ return Math.max(0, failure.blockedUntil - this.now())+ }++ run<T>(key: string, login: () => Promise<T>): Promise<T> {+ const running = this.inFlight.get(key)++ if (running) {+ return running as Promise<T>+ }++ const remaining = this.cooldownRemainingMs(key)++ if (remaining > 0) {+ return Promise.reject(new SilentLoginSuppressedError(remaining))+ }++ let started: Promise<T>++ try {+ started = login()+ } catch (error) {+ this.recordFailure(key)++ return Promise.reject(error)+ }++ const attempt: Promise<T> = started.then(+ value => {+ this.failures.delete(key)++ return value+ },+ error => {+ this.recordFailure(key)++ throw error+ }+ )++ this.inFlight.set(key, attempt)++ const release = (): void => {+ if (this.inFlight.get(key) === attempt) {+ this.inFlight.delete(key)+ }+ }++ void attempt.then(release, release)++ return attempt+ }++ private recordFailure(key: string): void {+ const consecutive = (this.failures.get(key)?.consecutive ?? 0) + 1+ const delay = Math.min(this.baseDelayMs * 2 ** (consecutive - 1), this.maxDelayMs)++ this.failures.set(key, { consecutive, blockedUntil: this.now() + delay })+ }+}diff --git a/apps/desktop/electron/oauth-rest-request.test.ts b/apps/desktop/electron/oauth-rest-request.test.tsindex a1905fa5535..9fbfb5906e4 100644--- a/apps/desktop/electron/oauth-rest-request.test.ts+++ b/apps/desktop/electron/oauth-rest-request.test.ts@@ -139,6 +139,98 @@ test('background auth intent stays isolated from a concurrent foreground requestexpect(foregroundLogins).toBe(1)})+test('concurrent gate 401s for one gateway clear cookies and open login once', async () => {+ const refusal = GATE_401()+ let clears = 0+ let logins = 0++ let releaseLogin: () => void = () => {}++ const loginGate = new Promise<void>(resolve => {+ releaseLogin = resolve+ })++ const attempt = () =>+ retryCookie401WithLogin(+ refusal,+ { method: 'GET', loginKey: 'https://gw.test' },+ {+ clearCookies: () => {+ clears += 1+ },+ login: async () => {+ logins += 1+ await loginGate+ },+ retry: async () => 'ok'+ }+ )++ const first = attempt()+ const second = attempt()++ expect(clears).toBe(1)+ expect(logins).toBe(1)++ releaseLogin()++ await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok'])+ expect(clears).toBe(1)+ expect(logins).toBe(1)+})++test('a joiner does not clear cookies when the shared re-login fails', async () => {+ const refusal = GATE_401()+ let joinerClears = 0++ const first = retryCookie401WithLogin(+ refusal,+ { loginKey: 'https://gw.test' },+ {+ clearCookies: () => {},+ login: async () => {+ throw new Error('Login window closed before authentication completed.')+ },+ retry: async () => 'unexpected'+ }+ )++ const second = retryCookie401WithLogin(+ refusal,+ { loginKey: 'https://gw.test' },+ {+ clearCookies: () => {+ joinerClears += 1+ },+ login: async () => {+ throw new Error('joiner opened a window')+ },+ retry: async () => 'unexpected'+ }+ )++ await expect(first).rejects.toBe(refusal)+ await expect(second).rejects.toBe(refusal)+ expect(joinerClears).toBe(0)++ let laterLogins = 0++ await expect(+ retryCookie401WithLogin(+ refusal,+ { loginKey: 'https://gw.test' },+ {+ clearCookies: () => {},+ login: async () => {+ laterLogins += 1+ },+ retry: async () => 'recovered'+ }+ )+ ).resolves.toBe('recovered')+ expect(laterLogins).toBe(1)+})+test('failed foreground re-login returns the original gate refusal without retrying', async () => {const refusal = GATE_401()let retries = 0diff --git a/apps/desktop/electron/oauth-rest-request.ts b/apps/desktop/electron/oauth-rest-request.tsindex 60cba284832..b928ebaf033 100644--- a/apps/desktop/electron/oauth-rest-request.ts+++ b/apps/desktop/electron/oauth-rest-request.ts@@ -71,15 +71,57 @@ export function canShowInteractiveOauthLogin(): boolean {return interactiveLoginAllowed.getStore() !== false}+const cookieReloginFlights = new Map<string, Promise<void>>()++async function shareCookieRelogin(+ key: string,+ actions: { clearCookies: () => void; login: () => Promise<unknown> }+): Promise<void> {+ const running = cookieReloginFlights.get(key)++ if (running) {+ await running++ return+ }++ // One burst shares one cookie clear. A joiner that clears mid-flight wipes+ // the mirror the in-flight window is about to fill.+ actions.clearCookies()++ const flight = actions.login().then(() => undefined)++ const tracked = flight.finally(() => {+ if (cookieReloginFlights.get(key) === tracked) {+ cookieReloginFlights.delete(key)+ }+ })++ cookieReloginFlights.set(key, tracked)+ await tracked+}+export async function retryCookie401WithLogin<T>(error: unknown,- options: { method?: unknown; replayOn401?: unknown },+ options: { method?: unknown; replayOn401?: unknown; loginKey?: unknown },actions: { clearCookies: () => void; login: () => Promise<unknown>; retry: () => Promise<T> }): Promise<T> {if (!canShowInteractiveOauthLogin() || !shouldReplayAfterCookie401(error, options)) {throw error}+ const loginKey = typeof options.loginKey === 'string' ? options.loginKey : ''++ if (loginKey) {+ try {+ await shareCookieRelogin(loginKey, actions)+ } catch {+ throw error+ }++ return actions.retry()+ }+actions.clearCookies()try {