diff --git a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts index efee902a662..b88fc0aa0b6 100644 --- a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts +++ b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts @@ -2,6 +2,7 @@ import { BrowserWindow } from 'electron' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress } from '../../../shared/orca-profiles' @@ -23,7 +24,8 @@ export function broadcastOrcaProfileAuthStatusChanged(): void { } export function broadcastOrcaProfileSignInProgressChanged( - progress: OrcaCloudSignInProgress | null + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd ): void { - broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress) + broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress, end ?? null) } diff --git a/src/main/orca-profiles/profile-cloud-pkce.test.ts b/src/main/orca-profiles/profile-cloud-pkce.test.ts index ca13f97a480..747b3bb3843 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.test.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.test.ts @@ -6,7 +6,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' +import { + beginOrcaCloudPkceFlow, + ORCA_CLOUD_SIGN_IN_TIMEOUT_MS, + orcaCloudSignInTimeoutMs +} from './profile-cloud-pkce' const base = 'https://auth.test' const config: OrcaCloudAuthConfig = { @@ -27,6 +31,7 @@ const config: OrcaCloudAuthConfig = { afterEach(() => { delete process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE + delete process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS }) describe('PKCE loopback for cloud setup', () => { @@ -76,3 +81,55 @@ describe('PKCE loopback for cloud setup', () => { expect((await browser).status).toBe(200) }) }) + +describe('PKCE loopback cancel and timeout', () => { + async function start(signal?: AbortSignal): Promise<{ + flow: Promise + redirect: URL + }> { + process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE = join(mkdtempSync(join(tmpdir(), 'pkce-')), 'urls') + let authorize = '' + const flow = beginOrcaCloudPkceFlow(config, 'profile-1', { + onAuthorizeUrl: (url) => (authorize = url), + ...(signal ? { signal } : {}) + }) + flow.catch(() => undefined) + await vi.waitFor(() => expect(authorize).not.toBe('')) + return { flow, redirect: new URL(new URL(authorize).searchParams.get('redirect_uri')!) } + } + + it('Cancel rejects the wait and closes the loopback listener', async () => { + const abort = new AbortController() + const { flow, redirect } = await start(abort.signal) + abort.abort() + await expect(flow).rejects.toThrow('orca_cloud_auth_cancelled') + // A late browser callback finds nothing listening. + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('an already-cancelled attempt never opens a listener', async () => { + const abort = new AbortController() + abort.abort() + const onAuthorizeUrl = vi.fn() + await expect( + beginOrcaCloudPkceFlow(config, 'profile-1', { signal: abort.signal, onAuthorizeUrl }) + ).rejects.toThrow('orca_cloud_auth_cancelled') + expect(onAuthorizeUrl).not.toHaveBeenCalled() + }) + + it('times out a sign-in the browser never finishes', async () => { + process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = '1000' + const { flow, redirect } = await start() + await expect(flow).rejects.toThrow('orca_cloud_auth_timeout') + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('waits five minutes by default; only unpackaged dev runs may shorten it', () => { + expect(ORCA_CLOUD_SIGN_IN_TIMEOUT_MS).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({}, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, false)).toBe(60_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, true)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '10' }, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: 'x' }, false)).toBe(300_000) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts index be85d68036f..43127271205 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -24,7 +24,17 @@ export type OrcaCloudAuthorizationCode = { /** How long a held browser tab waits for the caller before it gets the "signed in" page. */ const HOLD_BROWSER_MS = 30_000 -const AUTH_TIMEOUT_MS = 5 * 60 * 1000 +/** A sign-in the browser never answers ends after this, with "Sign-in didn’t finish. Try again." */ +export const ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000 + +/** Dev automation only (unpackaged): ORCA_CLOUD_SIGN_IN_TIMEOUT_MS shortens the wait for a test run. */ +export function orcaCloudSignInTimeoutMs( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = app.isPackaged +): number { + const override = packaged ? Number.NaN : Number(env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS) + return Number.isFinite(override) && override >= 1_000 ? override : ORCA_CLOUD_SIGN_IN_TIMEOUT_MS +} function base64Url(buffer: Buffer): string { return buffer.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '') @@ -159,7 +169,7 @@ export function beginOrcaCloudPkceFlow( const timeout = setTimeout(() => { rejectFlow(new Error('orca_cloud_auth_timeout')) - }, AUTH_TIMEOUT_MS) + }, orcaCloudSignInTimeoutMs()) const cancel = (): void => rejectFlow(new Error('orca_cloud_auth_cancelled')) options.signal?.addEventListener('abort', cancel, { once: true }) server.once('close', () => { @@ -167,6 +177,10 @@ export function beginOrcaCloudPkceFlow( options.signal?.removeEventListener('abort', cancel) }) server.once('error', rejectFlow) + if (options.signal?.aborted) { + cancel() + return + } server.listen(0, '127.0.0.1', () => { const address = server.address() if (!address || typeof address === 'string') { diff --git a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts index 04dd63f7e67..4417aad27a3 100644 --- a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts +++ b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts @@ -184,7 +184,8 @@ describe('Orca cloud overlapping connect', () => { redirectUri: 'http://127.0.0.1:4100/auth/callback', state: 'earlier-state' }) - await expect(earlier).resolves.toMatchObject({ status: 'connected' }) + // The later sign-in replaced the earlier one, so the earlier callback can't link anything. + await expect(earlier).resolves.toMatchObject({ status: 'cancelled' }) await expect(signOutCurrentOrcaProfile(userDataPath)).resolves.toMatchObject({ status: 'signed-out' }) @@ -196,7 +197,7 @@ describe('Orca cloud overlapping connect', () => { state: 'later-state' }) await expect(later).resolves.toMatchObject({ status: 'cancelled' }) - expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalledTimes(1) + expect(exchangeOrcaCloudAuthCodeMock).not.toHaveBeenCalled() expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ state: 'local' }) }) }) diff --git a/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts new file mode 100644 index 00000000000..6b7dab91dd5 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts @@ -0,0 +1,171 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { OrcaCloudSignInEnd, OrcaProfileCloudSummary } from '../../shared/orca-profiles' + +const { beginOrcaCloudPkceFlowMock, exchangeOrcaCloudAuthCodeMock, safeStorageMock } = vi.hoisted( + () => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } + }) +) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { getPath: () => userDataPath }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + createOrcaCloudProfile: vi.fn(), + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSession: vi.fn(async () => undefined), + selectOrcaCloudOrg: vi.fn() +})) + +import { connectCurrentOrcaProfile, getCurrentOrcaProfileAuthStatus } from './profile-cloud-service' +import { + cancelOrcaCloudSignIn, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests +} from './profile-cloud-sign-in-progress' + +const cloud: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +// A fixed far-future expiry: no wall clock in tests. +const EXPIRES_AT = 4_102_444_800_000 + +const code = { + code: 'the-code', + codeVerifier: 'verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' +} + +/** Waits for the browser like the real loopback: rejects when the attempt is aborted. */ +function pendingBrowser(): { + answer: (value: typeof code) => void + fail: (error: Error) => void +} { + const handle = { + answer: (_value: typeof code): void => undefined, + fail: (_error: Error): void => undefined + } + beginOrcaCloudPkceFlowMock.mockImplementationOnce( + (_config: unknown, _profile: string, options: { signal?: AbortSignal }) => + new Promise((resolve, reject) => { + handle.answer = resolve + handle.fail = reject + options.signal?.addEventListener('abort', () => + reject(new Error('orca_cloud_auth_cancelled')) + ) + }) + ) + return handle +} + +describe('Orca Cloud sign-in cancel, supersede and timeout', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-sign-in-cancel-')) + beginOrcaCloudPkceFlowMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: EXPIRES_AT, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + }) + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') + }) + + afterEach(() => { + resetOrcaCloudSignInProgressForTests() + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('Cancel while the browser is open ends the sign-in and clears progress', async () => { + pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(getOrcaCloudSignInProgress()).not.toBeNull()) + cancelOrcaCloudSignIn() + expect(getOrcaCloudSignInProgress()).toBeNull() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('Cancel after the browser answered still wins: the session is not saved', async () => { + const browser = pendingBrowser() + let finishExchange!: () => void + exchangeOrcaCloudAuthCodeMock.mockImplementationOnce(async () => { + await new Promise((resolve) => (finishExchange = resolve)) + return { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: EXPIRES_AT, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + } + }) + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.answer(code) + await vi.waitFor(() => expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalled()) + cancelOrcaCloudSignIn() + finishExchange() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('a second sign-in replaces the first: the first closes, the second signs in', async () => { + pendingBrowser() + const second = pendingBrowser() + const first = connectCurrentOrcaProfile(userDataPath) + const later = connectCurrentOrcaProfile(userDataPath) + await expect(first).resolves.toMatchObject({ status: 'cancelled' }) + expect(getOrcaCloudSignInProgress()).not.toBeNull() + second.answer(code) + await expect(later).resolves.toMatchObject({ status: 'connected' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(getCurrentOrcaProfileAuthStatus(userDataPath).cloud?.email).toBe('nina@example.com') + }) + + it('a timed-out sign-in clears progress and says it did not finish', async () => { + const ends: (OrcaCloudSignInEnd | undefined)[] = [] + onOrcaCloudSignInProgressChanged((progress, end) => { + if (!progress) { + ends.push(end) + } + }) + const browser = pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.fail(new Error('orca_cloud_auth_timeout')) + await expect(connect).resolves.toMatchObject({ status: 'timed-out' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(ends).toEqual(['timed-out']) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index 4bd70e0412f..616151ba594 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -39,6 +39,7 @@ import { import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' import { selectCloudOrg } from './profile-cloud-org-selection' import { + cancelOrcaCloudSignIn, endOrcaCloudSignInProgress, setOrcaCloudSignInLink, startOrcaCloudSignInProgress @@ -53,7 +54,8 @@ let linkedCloudConnectAttempt = 0 function invalidateOutstandingCloudConnectAttempts(): void { nextCloudConnectAttempt += 1 linkedCloudConnectAttempt = nextCloudConnectAttempt - endOrcaCloudSignInProgress() + // Also closes the pending loopback listener, so a late browser callback has nowhere to land. + cancelOrcaCloudSignIn() } function activeAuth( @@ -100,23 +102,27 @@ export async function connectCurrentOrcaProfile( } const attempt = ++nextCloudConnectAttempt - const browserWait = new AbortController() - startOrcaCloudSignInProgress(attempt, () => browserWait.abort()) + // Cancel (or a newer attempt) aborts this one at any stage before the session is saved. + const attemptAbort = new AbortController() + const cancelled = (): ConnectCurrentOrcaProfileResult => ({ + status: 'cancelled', + auth: getCurrentOrcaProfileAuthStatus(userDataPath) + }) + const stale = (): boolean => attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted + let end: 'timed-out' | undefined + startOrcaCloudSignInProgress(attempt, () => attemptAbort.abort()) let finishBrowser: ((location: string | null) => void) | undefined try { const code = await beginOrcaCloudPkceFlow(configState.config, active.profile.id, { - signal: browserWait.signal, + signal: attemptAbort.signal, onAuthorizeUrl: (link) => setOrcaCloudSignInLink(attempt, link), ...(setup ? { authorizeParams: setup.authorizeParams, holdBrowser: true } : {}) }) finishBrowser = code.finishBrowser // The callback listener has closed, so its browser link is dead. setOrcaCloudSignInLink(attempt, null) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (stale()) { + return cancelled() } const exchange = await exchangeOrcaCloudAuthCode(configState.config, { code: code.code, @@ -126,11 +132,8 @@ export async function connectCurrentOrcaProfile( state: code.state, localProfileId: active.profile.id }) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (stale()) { + return cancelled() } signInCloudSession(active.profile.id, userDataPath, exchange) const list = linkOrcaProfileToCloud(active.profile.id, exchange.cloud, userDataPath) @@ -148,21 +151,17 @@ export async function connectCurrentOrcaProfile( } } catch (error) { const message = error instanceof Error ? error.message : String(error) - if (message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { - return { - status: 'timed-out', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (!stale() && message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { + end = 'timed-out' + return { status: 'timed-out', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } } - if ( - message === 'orca_cloud_auth_timeout' || - message === 'orca_cloud_auth_denied' || - message === 'orca_cloud_auth_cancelled' - ) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + const stopped = [ + 'orca_cloud_auth_timeout', + 'orca_cloud_auth_denied', + 'orca_cloud_auth_cancelled' + ] + if (attemptAbort.signal.aborted || stopped.includes(message)) { + return cancelled() } return { status: 'failed', @@ -171,7 +170,7 @@ export async function connectCurrentOrcaProfile( } } finally { finishBrowser?.(null) - endOrcaCloudSignInProgress(attempt) + endOrcaCloudSignInProgress(attempt, end) } } diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts new file mode 100644 index 00000000000..2e4135c9cb7 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import { + cancelOrcaCloudSignIn, + endOrcaCloudSignInProgress, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests, + setOrcaCloudSignInLink, + startOrcaCloudSignInProgress +} from './profile-cloud-sign-in-progress' + +afterEach(() => resetOrcaCloudSignInProgressForTests()) + +function record(): [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] { + const events: [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] = [] + onOrcaCloudSignInProgressChanged((progress, end) => events.push([progress, end])) + return events +} + +describe('Orca Cloud sign-in progress', () => { + it('Cancel aborts the pending attempt and clears progress at once', () => { + const events = record() + const abort = vi.fn() + startOrcaCloudSignInProgress(1, abort) + setOrcaCloudSignInLink(1, 'https://auth.test/authorize') + cancelOrcaCloudSignIn() + expect(abort).toHaveBeenCalledOnce() + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(events.at(-1)).toEqual([null, undefined]) + // The aborted attempt ending later changes nothing. + endOrcaCloudSignInProgress(1) + expect(events).toHaveLength(3) + }) + + it('clears progress even when aborting throws', () => { + startOrcaCloudSignInProgress(1, () => { + throw new Error('already closed') + }) + expect(() => cancelOrcaCloudSignIn()).not.toThrow() + expect(getOrcaCloudSignInProgress()).toBeNull() + }) + + it('a second sign-in replaces the first and cancels it', () => { + const first = vi.fn() + const second = vi.fn() + startOrcaCloudSignInProgress(1, first) + setOrcaCloudSignInLink(1, 'https://auth.test/one') + startOrcaCloudSignInProgress(2, second) + expect(first).toHaveBeenCalledOnce() + expect(second).not.toHaveBeenCalled() + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + // The replaced attempt can neither set its link nor end the newer one. + setOrcaCloudSignInLink(1, 'https://auth.test/stale') + endOrcaCloudSignInProgress(1) + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + setOrcaCloudSignInLink(2, 'https://auth.test/two') + expect(getOrcaCloudSignInProgress()).toEqual({ link: 'https://auth.test/two' }) + }) + + it('says when a sign-in timed out', () => { + const events = record() + startOrcaCloudSignInProgress(3, vi.fn()) + endOrcaCloudSignInProgress(3, 'timed-out') + expect(events.at(-1)).toEqual([null, 'timed-out']) + }) + + it('Cancel with nothing pending is a no-op', () => { + const events = record() + cancelOrcaCloudSignIn() + expect(events).toHaveLength(0) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts index 88cb98cc23d..5c33fb6873c 100644 --- a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts @@ -1,8 +1,9 @@ -import type { OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' -type ProgressListener = (progress: OrcaCloudSignInProgress | null) => void +type ProgressListener = (progress: OrcaCloudSignInProgress | null, end?: OrcaCloudSignInEnd) => void -// Only the newest attempt owns progress; late updates from older attempts are ignored. +// One sign-in at a time: a newer attempt cancels the older one (its loopback listener closes), and +// Cancel clears the pending state at once, so nothing can leave the app stuck on "Signing in…". let current: { attempt: number; link: string | null; cancel: () => void } | null = null const listeners = new Set() @@ -10,18 +11,26 @@ function snapshot(): OrcaCloudSignInProgress | null { return current ? { link: current.link } : null } -function update(next: typeof current): void { +function update(next: typeof current, end?: OrcaCloudSignInEnd): void { current = next const progress = snapshot() for (const listener of listeners) { try { - listener(progress) + listener(progress, end) } catch (error) { console.warn('[orca-profiles] Sign-in progress listener failed:', error) } } } +function cancelQuietly(cancel: () => void): void { + try { + cancel() + } catch (error) { + console.warn('[orca-profiles] Cancelling a sign-in failed:', error) + } +} + export function getOrcaCloudSignInProgress(): OrcaCloudSignInProgress | null { return snapshot() } @@ -33,8 +42,13 @@ export function onOrcaCloudSignInProgressChanged(listener: ProgressListener): () } } +/** Starts tracking `attempt`; an older pending attempt is cancelled (a second click supersedes it). */ export function startOrcaCloudSignInProgress(attempt: number, cancel: () => void): void { + const previous = current update({ attempt, link: null, cancel }) + if (previous && previous.attempt !== attempt) { + cancelQuietly(previous.cancel) + } } export function setOrcaCloudSignInLink(attempt: number, link: string | null): void { @@ -43,12 +57,24 @@ export function setOrcaCloudSignInLink(attempt: number, link: string | null): vo } } -export function endOrcaCloudSignInProgress(attempt?: number): void { +export function endOrcaCloudSignInProgress(attempt?: number, end?: OrcaCloudSignInEnd): void { if (current && (attempt === undefined || current.attempt === attempt)) { - update(null) + update(null, end) } } +/** Cancel: aborts the pending attempt (closing its loopback listener) and clears progress now. */ export function cancelOrcaCloudSignIn(): void { - current?.cancel() + const pending = current + if (!pending) { + return + } + update(null) + cancelQuietly(pending.cancel) +} + +/** Test-only. */ +export function resetOrcaCloudSignInProgressForTests(): void { + current = null + listeners.clear() } diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index c572bd04513..20dd9cb6684 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -10,6 +10,7 @@ import type { OrcaProfileOrgLeaveArgs } from '../../shared/orca-org-management' import type { + OrcaCloudSignInEnd, OrcaCloudSignInProgress, ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -68,7 +69,8 @@ export type OrcaProfileApi = { connectCurrent: () => Promise signInProgress: () => Promise onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + /** `end` says why a sign-in stopped when the UI should tell the user (it timed out). */ + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ) => () => void cancelSignIn: () => Promise refreshAuth: () => Promise diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index 15bc3fb5991..3f32e5a26f5 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -3,6 +3,7 @@ import type { PreloadApi } from '../api-types' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress, type OrcaProfileListResult, type SwitchOrcaProfileResult, @@ -29,10 +30,13 @@ export const orcaProfilesApi = { return () => ipcRenderer.removeListener(ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, listener) }, onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ): (() => void) => { - const listener = (_event: unknown, progress: OrcaCloudSignInProgress | null): void => - callback(progress) + const listener = ( + _event: unknown, + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ): void => callback(progress, end ?? null) ipcRenderer.on(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) return () => ipcRenderer.removeListener(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) }, diff --git a/src/renderer/src/components/OrcaSignInProgress.tsx b/src/renderer/src/components/OrcaSignInProgress.tsx index 10caa6e6dae..55fcbd11d2d 100644 --- a/src/renderer/src/components/OrcaSignInProgress.tsx +++ b/src/renderer/src/components/OrcaSignInProgress.tsx @@ -1,5 +1,7 @@ -import { Loader2 } from 'lucide-react' +import { useEffect } from 'react' +import { ExternalLink, Loader2 } from 'lucide-react' import { toast } from 'sonner' +import { registerSignInNotice } from '@/lib/orca-cloud/sign-in-notice-visibility' import { Button } from './ui/button' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' @@ -18,25 +20,31 @@ async function copySignInLink(link: string): Promise { } } +/** + * Never disabled by a pending sign-in, so a closed or lost tab can't strand the user. While the + * browser is out it reads "Reopen browser" and reopens the same sign-in link; otherwise a click + * starts a sign-in, replacing any pending one (main cancels it). + */ export function OrcaSignInButton({ children, - disabled, ...props }: Omit, 'onClick' | 'type'>): React.JSX.Element { const t = useTranslate() const connect = useAppStore((state) => state.connectCurrentOrcaProfile) - const signingIn = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) + const link = useAppStore((state) => state.orcaProfileSignInProgress?.link ?? null) + const onClick = (): void => { + if (!link) { + void connect() + return + } + void window.api.shell.openUrl(link).catch(() => void connect()) + } return ( - + + ) : null} · - - · - diff --git a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts index 753c6b2afff..b4b983241bf 100644 --- a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts +++ b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts @@ -66,7 +66,7 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void }) // O1: a plan always lands on a team. The browser makes or picks the team, then Checkout; // the setup session switches this profile to that team when it's there. const started = await startCloudSetupSession({ needs: ['team', 'plan'], chooseTeam: true }) - return started ? { status: 'opened' } : result + return started && 'sessionId' in started ? { status: 'opened' } : result }) .then((result) => { if (id === runId.current) { diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 6c0301cabbc..255e7e0e41b 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -130,6 +130,11 @@ function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { {t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')} + {flow.signingIn ? ( + + ) : null} {flow.copyLink ? ( diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 680274cf170..4c7bd0b3e05 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -3,6 +3,7 @@ // one-trip setup session (#255) with its deep-link return (#257), B2's team switch, and the // tracker's error parsing (#260). Only the UI moved: from a card in the dialog to this page. import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useAppStore } from '@/store' import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' import { invalidateOrcaCloudBilling, @@ -76,6 +77,13 @@ function useLiveAvailability( export type CloudSetupFlow = CloudSetupPageModel & { /** True from the click until the browser opens or the trial answers. */ busy: boolean + /** This page's browser sign-in is pending: the page offers Cancel and keeps Reopen browser live. */ + signingIn: boolean + /** The last sign-in stopped on its own (it timed out): "Sign-in didn’t finish. Try again." */ + signInDidNotFinish: boolean + cancelSignIn: () => void + /** Leaving setup (Back): cancels a sign-in this page started. */ + abandon: () => void /** The browser trip is open: the current step reads "Waiting for your browser". */ inBrowser: boolean error: ReturnType @@ -160,6 +168,12 @@ export function useCloudSetupFlow( [access, availability] ) + const runRef = useRef(0) + const [startedSignIn, setStartedSignIn] = useState(false) + const signInPending = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) + const signInTimedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out') + const signingIn = busy && startedSignIn && signInPending + // One browser trip for everything still open from here (sign-in, team, trial or Checkout, GitHub). const continueInBrowser = useCallback(() => { const needs = sessionNeedsFrom(stepsRef.current) @@ -174,9 +188,19 @@ export function useCloudSetupFlow( fallback() return } + // Each click is a new run. An older run that ends late (its sign-in was replaced or cancelled) + // must not touch the page or open anything. + const run = ++runRef.current + const isCurrent = (): boolean => run === runRef.current setBusy(true) + setBrowserStep(null) + setStartedSignIn(cloudSetupPageModel(stepsRef.current).current?.id === 'account') void start({ repoId: request.repoId, needs }) .then((opened) => { + if (!isCurrent() || (opened && 'cancelled' in opened)) { + // Cancelled, timed out or replaced: back to the step's own button; nothing reopens. + return + } markInBrowser() if (opened) { setSessionId(opened.sessionId) @@ -184,10 +208,31 @@ export function useCloudSetupFlow( fallback() } }) - .catch(() => fallback()) - .finally(() => setBusy(false)) + .catch(() => { + if (isCurrent()) { + fallback() + } + }) + .finally(() => { + if (isCurrent()) { + setBusy(false) + setStartedSignIn(false) + } + }) }, [fallback, markInBrowser, openInstall, request.repoId]) + const cancelSignIn = useCallback(() => { + void window.api.orcaProfiles.cancelSignIn().catch(() => {}) + }, []) + + const abandon = useCallback(() => { + if (busy && startedSignIn) { + // Back means "not now": the tab this page opened must not sign in behind the user's back. + runRef.current++ + cancelSignIn() + } + }, [busy, cancelSignIn, startedSignIn]) + const startTrial = useCallback(() => { setBusy(true) void claimOrcaCloudTrial() @@ -215,7 +260,11 @@ export function useCloudSetupFlow( return { ...model, - busy, + busy: busy && !signingIn, + signingIn, + signInDidNotFinish: !busy && signInTimedOut && model.action === 'sign-in', + cancelSignIn, + abandon, inBrowser: browserStep !== null && (sessionId !== null || model.current?.id === browserStep), error, canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx index 3c5a6bc38fe..623e53f1ad2 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx @@ -1,13 +1,27 @@ import { defineFixture } from '../../../../component-fixtures/component-fixture' -import type { OrcaProfileAuthStatus } from '../../../../../../shared/orca-profiles' +import type { + OrcaCloudSignInEnd, + OrcaCloudSignInProgress, + OrcaProfileAuthStatus +} from '../../../../../../shared/orca-profiles' import { OrcaAccountSettingsPane } from './OrcaAccountSettingsPane' const width = 760 -function pane(status: OrcaProfileAuthStatus) { +function pane( + status: OrcaProfileAuthStatus, + signIn: { + progress?: OrcaCloudSignInProgress | null + end?: OrcaCloudSignInEnd | null + } = {} +) { return defineFixture({ width, - store: { orcaProfileAuthStatus: status }, + store: { + orcaProfileAuthStatus: status, + orcaProfileSignInProgress: signIn.progress ?? null, + orcaProfileSignInEnd: signIn.end ?? null + }, // The pane re-reads auth status on mount; answer with the same state so the frame holds it. setup: () => { Object.assign(window.api.orcaProfiles, { authStatus: () => Promise.resolve(status) }) @@ -31,3 +45,18 @@ export const reconnectRequired = pane({ state: 'reconnect-required', persistence: 'encrypted' }) + +const signedOutStatus: OrcaProfileAuthStatus = { + activeProfileId: 'default', + configured: true, + state: 'local', + persistence: 'none' +} + +/** Waiting on the browser: the primary stays live as "Reopen browser"; the line offers Cancel. */ +export const signInPending = pane(signedOutStatus, { + progress: { link: 'https://auth.example/v1/desktop/auth/authorize?state=preview' } +}) + +/** The browser never came back: a calm inline note, and Sign in to Orca again. */ +export const signInTimedOut = pane(signedOutStatus, { end: 'timed-out' }) diff --git a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts index ee223e3dd19..bb214773b5c 100644 --- a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts +++ b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaCloudSignInProgress } from '../../../../shared/orca-profiles' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../../../shared/orca-profiles' import { createTestStore } from '../../store/testing/app-store-test-fixture' type TestStore = ReturnType @@ -11,8 +11,10 @@ const { storeHolder } = vi.hoisted((): { storeHolder: { current: TestStore | nul vi.mock('../../store', () => ({ useAppStore: { getState: () => storeHolder.current?.getState(), - setState: (partial: { orcaProfileSignInProgress: OrcaCloudSignInProgress | null }) => - storeHolder.current?.setState(partial) + setState: (partial: { + orcaProfileSignInProgress: OrcaCloudSignInProgress | null + orcaProfileSignInEnd?: OrcaCloudSignInEnd | null + }) => storeHolder.current?.setState(partial) } })) @@ -23,7 +25,10 @@ vi.mock('sonner', () => ({ import { registerOrcaProfileAuthIpcBridge } from './orca-profile-auth-ipc-bridge' describe('orca profile sign-in progress IPC bridge', () => { - let emitProgress: (progress: OrcaCloudSignInProgress | null) => void + let emitProgress: ( + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ) => void const snapshots: ((progress: OrcaCloudSignInProgress | null) => void)[] = [] const WAITING = { link: 'https://login.example/authorize?state=a' } @@ -34,7 +39,10 @@ describe('orca profile sign-in progress IPC bridge', () => { api: { orcaProfiles: { onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + callback: ( + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ) => void ) => { emitProgress = callback return () => {} @@ -59,4 +67,16 @@ describe('orca profile sign-in progress IPC bridge', () => { await new Promise((resolve) => setTimeout(resolve, 0)) expect(progress()).toBeNull() }) + + it('keeps the timed-out note until the next sign-in starts', () => { + registerOrcaProfileAuthIpcBridge([]) + const end = (): OrcaCloudSignInEnd | null => + storeHolder.current?.getState().orcaProfileSignInEnd ?? null + emitProgress(WAITING, null) + emitProgress(null, 'timed-out') + expect(progress()).toBeNull() + expect(end()).toBe('timed-out') + emitProgress({ link: null }, null) + expect(end()).toBeNull() + }) }) diff --git a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts index 7d7ba00f5a0..b77d59958ae 100644 --- a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts @@ -12,9 +12,13 @@ export function registerOrcaProfileAuthIpcBridge(unsubs: (() => void)[]): void { if (typeof api?.onSignInProgressChanged === 'function') { // Why: a sign-in can already be in flight when this window loads; a later event or teardown wins. let ignoreSnapshot = false - const unsubscribe = api.onSignInProgressChanged((progress) => { + const unsubscribe = api.onSignInProgressChanged((progress, end) => { ignoreSnapshot = true - useAppStore.setState({ orcaProfileSignInProgress: progress }) + // A new sign-in (or one that finished) clears the "didn't finish" note; a timeout sets it. + useAppStore.setState({ + orcaProfileSignInProgress: progress, + orcaProfileSignInEnd: end ?? null + }) }) unsubs.push(() => { ignoreSnapshot = true diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 2497b5a27e4..f07918eec8a 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -1369,8 +1369,7 @@ "76deec8f58": "Organisation konnte nicht gewechselt werden", "7d4bc516ee": "Profil konnte nicht gewechselt werden", "f518e89aa5": "Projekt existiert bereits in diesem Profil", - "f03ae7f27b": "Projekt konnte nicht übertragen werden", - "signInTimedOut": "Zeitüberschreitung bei der Anmeldung" + "f03ae7f27b": "Projekt konnte nicht übertragen werden" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 2ba1725f935..ff8b3267c05 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1778,7 +1778,7 @@ "7d4bc516ee": "Failed to switch profile", "f518e89aa5": "Project already exists in that profile", "f03ae7f27b": "Failed to transfer project", - "signInTimedOut": "Sign-in timed out" + "signInDidNotFinish": "Sign-in didn’t finish. Try again." } }, "runtime": { @@ -20415,7 +20415,9 @@ "copied": "Sign-in link copied", "copyFailed": "Could not copy the link.", "signingIn": "Signing in…", - "cancel": "Cancel" + "cancel": "Cancel", + "didNotFinish": "Sign-in didn’t finish. Try again.", + "reopenBrowser": "Reopen browser" }, "plainSshTerminal": { "open": "Open plain SSH terminal", @@ -28199,7 +28201,8 @@ "signIn": { "lead": "Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.", "note": "New teams get a trial with no card needed. This page picks up each step on its own.", - "title": "Sign in to Orca" + "title": "Sign in to Orca", + "didNotFinish": "Sign-in didn’t finish. Try again." }, "starting": "Starting…", "step": { @@ -28231,7 +28234,8 @@ "exited": "Orca Cloud setup closed. Your draft is kept.", "header": "Setting up Orca Cloud", "headerFor": "Setting up Orca Cloud for {{name}}", - "resumeDraft": "Open draft" + "resumeDraft": "Open draft", + "cancelSignIn": "Cancel" }, "orcaCloudSignInSheet": { "title": "Agents in Orca Cloud", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index d7b57a7a968..2d80780d87a 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -901,8 +901,7 @@ "76deec8f58": "Error al cambiar organización", "7d4bc516ee": "Error al cambiar perfil", "f518e89aa5": "El proyecto ya existe en ese perfil", - "f03ae7f27b": "Error al transferir proyecto", - "signInTimedOut": "Se agotó el tiempo de inicio de sesión" + "f03ae7f27b": "Error al transferir proyecto" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 19f4b0701d9..2c6bbfe8571 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -1140,8 +1140,7 @@ "76deec8f58": "Échec du changement d'organisation", "7d4bc516ee": "Échec du changement de profil", "f518e89aa5": "Le projet existe déjà dans ce profil", - "f03ae7f27b": "Échec du transfert du projet", - "signInTimedOut": "La connexion a expiré" + "f03ae7f27b": "Échec du transfert du projet" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 464d3ee878e..b0312a9a76f 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -893,8 +893,7 @@ "76deec8f58": "組織の切り替えに失敗しました", "7d4bc516ee": "プロファイルの切り替えに失敗しました", "f518e89aa5": "プロジェクトはそのプロファイルに既に存在します", - "f03ae7f27b": "プロジェクトの転送に失敗しました", - "signInTimedOut": "サインインがタイムアウトしました" + "f03ae7f27b": "プロジェクトの転送に失敗しました" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index d0b29054d0a..514167ef532 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -893,8 +893,7 @@ "76deec8f58": "조직을 전환하지 못했습니다", "7d4bc516ee": "프로필을 전환하지 못했습니다", "f518e89aa5": "프로젝트가 해당 프로필에 이미 있습니다", - "f03ae7f27b": "프로젝트를 전송하지 못했습니다", - "signInTimedOut": "로그인 시간이 초과되었습니다" + "f03ae7f27b": "프로젝트를 전송하지 못했습니다" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 70738a15daa..ad6d2052b29 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -2126,8 +2126,7 @@ "76deec8f58": "Falha ao alternar organização", "7d4bc516ee": "Falha ao alternar perfil", "f518e89aa5": "O projeto já existe nesse perfil", - "f03ae7f27b": "Falha ao transferir o projeto", - "signInTimedOut": "O tempo para entrar expirou" + "f03ae7f27b": "Falha ao transferir o projeto" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 80d7e72dfb5..f730e1c5d41 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -1413,8 +1413,7 @@ "76deec8f58": "Не удалось переключить организацию", "7d4bc516ee": "Не удалось переключить профиль", "f518e89aa5": "Проект уже есть в этом профиле", - "f03ae7f27b": "Не удалось перенести проект", - "signInTimedOut": "Время ожидания входа истекло" + "f03ae7f27b": "Не удалось перенести проект" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 5588afb0dae..72a5a13ca00 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -1345,8 +1345,7 @@ "76deec8f58": "Organizasyon değiştirilemedi", "7d4bc516ee": "Profil değiştirilemedi", "f518e89aa5": "Proje bu profilde zaten mevcut", - "f03ae7f27b": "Proje aktarılamadı", - "signInTimedOut": "Oturum açma zaman aşımına uğradı" + "f03ae7f27b": "Proje aktarılamadı" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 069c664a563..7f3e88e23f3 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -1317,8 +1317,7 @@ "76deec8f58": "切換組織失敗", "7d4bc516ee": "切換設定檔失敗", "f518e89aa5": "該專案已存在於那個設定檔中", - "f03ae7f27b": "轉移專案失敗", - "signInTimedOut": "登入逾時" + "f03ae7f27b": "轉移專案失敗" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index ecdb385b775..dd08c38154d 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -893,8 +893,7 @@ "76deec8f58": "切换组织失败", "7d4bc516ee": "切换配置文件失败", "f518e89aa5": "该项目已存在于那个配置文件中", - "f03ae7f27b": "转移项目失败", - "signInTimedOut": "登录超时" + "f03ae7f27b": "转移项目失败" } }, "runtime": { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts index e92b0addc43..d0ae500d0a3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts @@ -42,8 +42,13 @@ export type CloudSetupStartRequest = { /** The rows still open when the user clicked (account, team, plan, github). */ needs: CloudSetupStep['id'][] } -/** Null when the session couldn't open; the composer then falls back to today's actions. */ -type SessionStarter = (request: CloudSetupStartRequest) => Promise<{ sessionId: string } | null> +/** + * Null when the session couldn't open; the composer then falls back to today's actions. + * `cancelled` when the user cancelled the sign-in: no fallback, nothing else opens. + */ +type SessionStarter = ( + request: CloudSetupStartRequest +) => Promise<{ sessionId: string } | { cancelled: true } | null> let source: SessionSource | null = null let starter: SessionStarter | null = null @@ -71,10 +76,7 @@ export function readCloudSetupSession(sessionId: string | null): CloudSetupSessi // Bumped on every change, so a read is cached per (session, revision): useSyncExternalStore needs // the same object back until something changed. let revision = 0 -const cachedReads = new Map< - string, - { revision: number; value: CloudSetupSessionSnapshot | null } ->() +const cachedReads = new Map() /** Call after each poll so open composers re-read their session. */ export function notifyCloudSetupSessionChanged(): void { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts index 0a0c7c08411..4a9b5046fad 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts @@ -126,6 +126,10 @@ describe('cloud setup session (renderer)', () => { it('stops on an expired session and returns null when setup cannot open', async () => { cloudSetupStart.mockResolvedValueOnce({ status: 'signed-out' }) expect(await startCloudSetupSession({ needs: ['plan'] })).toBeNull() + // A cancelled (or timed-out, or replaced) sign-in is not a failure: callers must not fall back + // to another browser trip. + cloudSetupStart.mockResolvedValueOnce({ status: 'cancelled' }) + expect(await startCloudSetupSession({ needs: ['plan'] })).toEqual({ cancelled: true }) cloudSetupGet.mockResolvedValue({ status: 'not-found' }) await refreshCloudSetupSession(ID) diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts index d4bd4812bee..51199abb3fd 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts @@ -172,12 +172,18 @@ export function stopWatchingCloudSetupSession(sessionId: string): void { entries.delete(sessionId) } -/** "Set up and start": opens the one browser tab and starts polling. Null when it couldn't. */ +/** + * What "Set up and start" got back: the session it opened, `cancelled` when the user cancelled the + * sign-in (or it timed out, or a newer one replaced it), or null when setup couldn't open. + */ +export type CloudSetupSessionStart = { sessionId: string } | { cancelled: true } | null + +/** "Set up and start": opens the one browser tab and starts polling. */ export async function startCloudSetupSession(request: { repo?: string needs: CloudSetupNeed[] chooseTeam?: boolean -}): Promise<{ sessionId: string } | null> { +}): Promise { let result: CloudSetupStartResult try { result = await window.api.orcaProfiles.cloudSetupStart({ @@ -188,6 +194,10 @@ export async function startCloudSetupSession(request: { } catch { return null } + if (result.status === 'cancelled') { + // The user stopped the sign-in: nothing else may open a browser on their behalf. + return { cancelled: true } + } if (result.status !== 'opened') { return null } diff --git a/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts b/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts new file mode 100644 index 00000000000..921f75a1d71 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts @@ -0,0 +1,19 @@ +// Whether an inline Orca sign-in notice is on screen. A sign-in that didn't finish is said inline +// where one is shown; the toast is only for sign-ins started from a surface without one. +let mounted = 0 + +/** Call from an inline notice's mount effect; the returned function unregisters it. */ +export function registerSignInNotice(): () => void { + mounted += 1 + let registered = true + return () => { + if (registered) { + registered = false + mounted -= 1 + } + } +} + +export function isSignInNoticeVisible(): boolean { + return mounted > 0 +} diff --git a/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts b/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts index 8bf623831b0..c87919d7bb4 100644 --- a/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts +++ b/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts @@ -2,6 +2,7 @@ import type { StateCreator } from 'zustand' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { + OrcaCloudSignInEnd, OrcaCloudSignInProgress, OrcaProfileAuthStatus, OrcaProfileSummary, @@ -20,6 +21,8 @@ export type OrcaProfilesSlice = OrcaProfilesAuthActions & { activeOrcaProfileId: string | null orcaProfileAuthStatus: OrcaProfileAuthStatus | null orcaProfileSignInProgress: OrcaCloudSignInProgress | null + /** Set when the last sign-in stopped without finishing (it timed out); cleared by the next one. */ + orcaProfileSignInEnd: OrcaCloudSignInEnd | null orcaProfilesMultiProfileUi: boolean orcaProfilesLoading: boolean orcaProfileSwitching: boolean @@ -41,6 +44,7 @@ export const createOrcaProfilesSlice: StateCreator { + const toastMock = Object.assign(vi.fn(), { + error: vi.fn(), + info: vi.fn(), + success: vi.fn(), + warning: vi.fn() + }) + return { toastMock } +}) + +vi.mock('sonner', () => ({ toast: toastMock })) + +const signedOut: OrcaProfileAuthStatus = { + activeProfileId: 'local-default', + configured: true, + state: 'local', + persistence: 'none' +} +const timedOut: ConnectCurrentOrcaProfileResult = { status: 'timed-out', auth: signedOut } +const connectCurrent = vi.fn() + +describe('a sign-in that times out', () => { + beforeEach(() => { + vi.resetAllMocks() + vi.stubGlobal('window', { api: { orcaProfiles: { connectCurrent } } }) + connectCurrent.mockResolvedValue(timedOut) + }) + + it('says so calmly in a toast when no inline notice is on screen', async () => { + const store = createTestStore() + await store.getState().connectCurrentOrcaProfile() + expect(toastMock).toHaveBeenCalledWith('Sign-in didn’t finish. Try again.') + expect(toastMock.error).not.toHaveBeenCalled() + }) + + it('leaves it to the inline notice when one is on screen', async () => { + const unregister = registerSignInNotice() + try { + const store = createTestStore() + await store.getState().connectCurrentOrcaProfile() + expect(toastMock).not.toHaveBeenCalled() + expect(toastMock.error).not.toHaveBeenCalled() + } finally { + unregister() + } + }) +}) diff --git a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts index e3107fb6e8d..913fd4c684d 100644 --- a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts +++ b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts @@ -1,6 +1,7 @@ import type { StateCreator } from 'zustand' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' +import { isSignInNoticeVisible } from '@/lib/orca-cloud/sign-in-notice-visibility' import type { ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileResult, @@ -108,9 +109,13 @@ export const createOrcaProfilesAuthActions: StateCreator< description: result.auth.setupMessage } ) - } else if (result.status === 'timed-out' && !alreadyConnected) { - toast.error( - translate('auto.store.slices.orca.profiles.signInTimedOut', 'Sign-in timed out') + } else if (result.status === 'timed-out' && !alreadyConnected && !isSignInNoticeVisible()) { + // Calm, not an error. Said inline where a sign-in notice is on screen; toast otherwise. + toast( + translate( + 'auto.store.slices.orca.profiles.signInDidNotFinish', + 'Sign-in didn’t finish. Try again.' + ) ) } else if ( result.status === 'failed' && diff --git a/src/shared/orca-profiles.ts b/src/shared/orca-profiles.ts index 2e04da3796c..7704c8aee72 100644 --- a/src/shared/orca-profiles.ts +++ b/src/shared/orca-profiles.ts @@ -155,6 +155,9 @@ export type TransferOrcaProfileProjectResult = /** A sign-in in flight; `link` is set only while the browser has not answered yet. */ export type OrcaCloudSignInProgress = { link: string | null } +/** Why a sign-in stopped, when the UI should say so ("Sign-in didn’t finish. Try again."). */ +export type OrcaCloudSignInEnd = 'timed-out' + export type ConnectCurrentOrcaProfileResult = | { status: 'connected'