Merge pull request #357 from nwparker/cloud/ja02-signin-cancel

fix(cloud-auth): Cancel always ends a pending Orca sign-in; second click replaces it; calm timeout (JA-02)
This commit is contained in:
Neil
2026-11-10 22:54:08 -08:00
committed by GitHub
36 changed files with 720 additions and 125 deletions
@@ -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)
}
@@ -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<unknown>
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)
})
})
+16 -2
View File
@@ -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') {
@@ -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' })
})
})
@@ -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<void>((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'])
})
})
+28 -29
View File
@@ -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)
}
}
@@ -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)
})
})
@@ -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<ProgressListener>()
@@ -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()
}
+3 -1
View File
@@ -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<ConnectCurrentOrcaProfileResult>
signInProgress: () => Promise<OrcaCloudSignInProgress | null>
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<void>
refreshAuth: () => Promise<RefreshCurrentOrcaProfileAuthResult>
+7 -3
View File
@@ -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)
},
@@ -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<void> {
}
}
/**
* 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<React.ComponentProps<typeof Button>, '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 (
<Button
{...props}
type="button"
disabled={disabled || signingIn}
onClick={() => void connect()}
>
{signingIn ? (
<Button {...props} type="button" onClick={onClick}>
{link ? (
<>
<Loader2 className="animate-spin" />
{t('auto.components.OrcaSignInProgress.signingIn', 'Signing in…')}
{t('auto.components.OrcaSignInProgress.reopenBrowser', 'Reopen browser')}
<ExternalLink aria-hidden />
</>
) : (
children
@@ -45,16 +53,32 @@ export function OrcaSignInButton({
)
}
function cancelSignIn(): void {
void window.api.orcaProfiles.cancelSignIn().catch(() => {})
}
export function OrcaSignInWaitNotice({
className
}: {
className?: string
}): React.JSX.Element | null {
const t = useTranslate()
const link = useAppStore((state) => state.orcaProfileSignInProgress?.link)
if (!link) {
return null
const progress = useAppStore((state) => state.orcaProfileSignInProgress)
const timedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out')
const signedIn = useAppStore((state) => state.orcaProfileAuthStatus?.state === 'connected')
// While this is on screen a timeout is said here, not in a toast.
useEffect(() => registerSignInNotice(), [])
if (!progress) {
if (!timedOut || signedIn) {
return null
}
return (
<p role="status" className={cn('text-xs text-muted-foreground', className)}>
{t('auto.components.OrcaSignInProgress.didNotFinish', 'Sign-in didn’t finish. Try again.')}
</p>
)
}
const link = progress.link
return (
<div
role="status"
@@ -63,20 +87,22 @@ export function OrcaSignInWaitNotice({
className
)}
>
<Loader2 className="mr-1.5 size-3 motion-safe:animate-spin" aria-hidden />
<span className="pr-2">
{t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser')}
{link
? t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser')
: t('auto.components.OrcaSignInProgress.signingIn', 'Signing in…')}
</span>
{link ? (
<>
<span aria-hidden>·</span>
<Button type="button" variant="link" size="xs" onClick={() => void copySignInLink(link)}>
{t('auto.components.OrcaSignInProgress.copyLink', 'Copy sign-in link')}
</Button>
</>
) : null}
<span aria-hidden>·</span>
<Button type="button" variant="link" size="xs" onClick={() => void copySignInLink(link)}>
{t('auto.components.OrcaSignInProgress.copyLink', 'Copy sign-in link')}
</Button>
<span aria-hidden>·</span>
<Button
type="button"
variant="link"
size="xs"
onClick={() => void window.api.orcaProfiles.cancelSignIn().catch(() => {})}
>
<Button type="button" variant="link" size="xs" onClick={cancelSignIn}>
{t('auto.components.OrcaSignInProgress.cancel', 'Cancel')}
</Button>
</div>
@@ -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) {
@@ -130,6 +130,11 @@ function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element {
{t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')}
</span>
<span className="ms-auto flex items-center gap-2">
{flow.signingIn ? (
<Button type="button" variant="ghost" size="sm" onClick={flow.cancelSignIn}>
{t('cloudSetupPage.cancelSignIn', 'Cancel')}
</Button>
) : null}
{flow.copyLink ? (
<Button type="button" variant="ghost" size="sm" onClick={flow.copyLink}>
<Copy aria-hidden />
@@ -159,12 +164,22 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu
flow.action === 'choose-plan' ||
flow.action === 'fix-billing' ||
flow.action === 'github-install'
if (flow.inBrowser && inBrowserAction && !flow.error) {
if (flow.signingIn || (flow.inBrowser && inBrowserAction && !flow.error)) {
return <BrowserWaiting flow={flow} />
}
const continueLabel = t('cloudSetupPage.continueInBrowser', 'Continue in browser')
switch (flow.action) {
case 'sign-in':
return flow.signInDidNotFinish ? (
<div className="flex flex-col items-start gap-3">
<p role="status" className="text-sm text-muted-foreground">
{t('cloudSetupPage.signIn.didNotFinish', 'Sign-in didn’t finish. Try again.')}
</p>
{browser(continueLabel, flow.continueInBrowser)}
</div>
) : (
browser(continueLabel, flow.continueInBrowser)
)
case 'choose-plan':
return browser(continueLabel, flow.continueInBrowser)
case 'fix-billing':
@@ -269,9 +284,16 @@ export function CloudSetupPage({
setViewing(previous.id)
return
}
// Leaving setup cancels a sign-in this page started (it must not finish behind the user).
flow.abandon()
onBackToComposer()
}
const exit = (): void => {
flow.abandon()
onExit()
}
// Each new step moves focus to its heading so screen readers hear the change once.
const stepKey = `${viewing ?? shown.current?.id ?? 'done'}:${shown.action}`
React.useEffect(() => {
@@ -311,7 +333,7 @@ export function CloudSetupPage({
size="icon-sm"
aria-label={t('cloudSetupPage.exit', 'Exit setup')}
title={t('cloudSetupPage.exit', 'Exit setup')}
onClick={onExit}
onClick={exit}
>
<X aria-hidden />
</Button>
@@ -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<typeof parseCloudSetupError>
@@ -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,
@@ -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' })
@@ -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<typeof createTestStore>
@@ -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()
})
})
@@ -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
+1 -2
View File
@@ -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": {
+8 -4
View File
@@ -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",
+1 -2
View File
@@ -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": {
+1 -2
View File
@@ -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": {
+1 -2
View File
@@ -893,8 +893,7 @@
"76deec8f58": "組織の切り替えに失敗しました",
"7d4bc516ee": "プロファイルの切り替えに失敗しました",
"f518e89aa5": "プロジェクトはそのプロファイルに既に存在します",
"f03ae7f27b": "プロジェクトの転送に失敗しました",
"signInTimedOut": "サインインがタイムアウトしました"
"f03ae7f27b": "プロジェクトの転送に失敗しました"
}
},
"runtime": {
+1 -2
View File
@@ -893,8 +893,7 @@
"76deec8f58": "조직을 전환하지 못했습니다",
"7d4bc516ee": "프로필을 전환하지 못했습니다",
"f518e89aa5": "프로젝트가 해당 프로필에 이미 있습니다",
"f03ae7f27b": "프로젝트를 전송하지 못했습니다",
"signInTimedOut": "로그인 시간이 초과되었습니다"
"f03ae7f27b": "프로젝트를 전송하지 못했습니다"
}
},
"runtime": {
+1 -2
View File
@@ -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": {
+1 -2
View File
@@ -1413,8 +1413,7 @@
"76deec8f58": "Не удалось переключить организацию",
"7d4bc516ee": "Не удалось переключить профиль",
"f518e89aa5": "Проект уже есть в этом профиле",
"f03ae7f27b": "Не удалось перенести проект",
"signInTimedOut": "Время ожидания входа истекло"
"f03ae7f27b": "Не удалось перенести проект"
}
},
"runtime": {
+1 -2
View File
@@ -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": {
+1 -2
View File
@@ -1317,8 +1317,7 @@
"76deec8f58": "切換組織失敗",
"7d4bc516ee": "切換設定檔失敗",
"f518e89aa5": "該專案已存在於那個設定檔中",
"f03ae7f27b": "轉移專案失敗",
"signInTimedOut": "登入逾時"
"f03ae7f27b": "轉移專案失敗"
}
},
"runtime": {
+1 -2
View File
@@ -893,8 +893,7 @@
"76deec8f58": "切换组织失败",
"7d4bc516ee": "切换配置文件失败",
"f518e89aa5": "该项目已存在于那个配置文件中",
"f03ae7f27b": "转移项目失败",
"signInTimedOut": "登录超时"
"f03ae7f27b": "转移项目失败"
}
},
"runtime": {
@@ -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<string, { revision: number; value: CloudSetupSessionSnapshot | null }>()
/** Call after each poll so open composers re-read their session. */
export function notifyCloudSetupSessionChanged(): void {
@@ -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)
@@ -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<CloudSetupSessionStart> {
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
}
@@ -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
}
@@ -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<AppState, [], [], OrcaProfile
activeOrcaProfileId: null,
orcaProfileAuthStatus: null,
orcaProfileSignInProgress: null,
orcaProfileSignInEnd: null,
orcaProfilesMultiProfileUi: false,
orcaProfilesLoading: false,
orcaProfileSwitching: false,
@@ -0,0 +1,55 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
ConnectCurrentOrcaProfileResult,
OrcaProfileAuthStatus
} from '../../../../../shared/orca-profiles'
import { registerSignInNotice } from '@/lib/orca-cloud/sign-in-notice-visibility'
import { createTestStore } from '../../testing/app-store-test-fixture'
const { toastMock } = vi.hoisted(() => {
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()
}
})
})
@@ -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' &&
+3
View File
@@ -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'