Merge pull request #305 from nwparker/np4-e2e/setup-session-fixes

fix(cloud-setup): composer follows its setup session; signed-out start asks for GitHub; billing reaches the control plane
This commit is contained in:
Neil
2026-11-10 14:51:11 -08:00
committed by GitHub
11 changed files with 220 additions and 30 deletions
+6 -1
View File
@@ -634,7 +634,12 @@ export async function setupGithubInstall(
url.searchParams.set('githubLogin', body.githubLogin)
}
const token = (env.CONTROL_PLANE_TOKEN ?? '').split(',')[0]?.trim() ?? ''
const response = await fetchImpl(url, {
// Over the service binding when there is one: a plain fetch between same-account workers.dev
// Workers fails with error 1042, which surfaced as "setup is unavailable" on the GitHub step.
const send: typeof fetch = env.SANDBOX_CONTROL
? (input, init) => env.SANDBOX_CONTROL!.fetch(input, init)
: fetchImpl
const response = await send(url, {
headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
signal: AbortSignal.timeout(8000)
})
+3
View File
@@ -67,4 +67,7 @@ export type Env = {
CLOUD_SETUP_PAGES_URL?: string
// Control plane origin billing asks for a repository's GitHub install URL (CONTROL_PLANE_TOKEN).
SANDBOX_CONTROL_URL?: string
// Service binding to that control plane. Same-account Workers can't fetch each other over
// workers.dev (Cloudflare error 1042), so when bound the request goes through it instead.
SANDBOX_CONTROL?: Fetcher
}
+32 -2
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { TrialPort, SetupTrial } from '../src/cloud-setup-trial'
import { normalizeRepo } from '../src/cloud-setup'
import type { Env } from '../src/env'
import { checkoutCompleted } from './stripe-fake'
import { CONTROL_TOKEN, createHarness } from './harness'
@@ -27,8 +28,13 @@ function fakeTrials(options: { refuse?: boolean } = {}) {
return { port, trials, grants }
}
async function setup(options: { refuseTrial?: boolean } = {}) {
const h = await createHarness({ MEMBERSHIP_SYNC_TOKEN: SYNC, CLOUD_SETUP_PAGES_URL: 'https://auth.test', SANDBOX_CONTROL_URL: 'https://cp.test' })
async function setup(options: { refuseTrial?: boolean; env?: Partial<Env> } = {}) {
const h = await createHarness({
MEMBERSHIP_SYNC_TOKEN: SYNC,
CLOUD_SETUP_PAGES_URL: 'https://auth.test',
SANDBOX_CONTROL_URL: 'https://cp.test',
...options.env
})
const trials = fakeTrials({ refuse: options.refuseTrial })
h.setTrial(trials.port)
const sync = { authorization: `Bearer ${SYNC}` }
@@ -57,6 +63,30 @@ describe('cloud setup sessions', () => {
expect(offers.body.team.monthlyPriceLabel).toMatch(/per seat per month/)
})
it('asks the control plane for the GitHub install URL over its service binding when bound', async () => {
// Same-account workers.dev Workers can't fetch each other (Cloudflare 1042): use the binding.
const viaBinding: string[] = []
const binding = {
fetch: async (input: RequestInfo | URL) => {
viaBinding.push(String(input))
return Response.json({ access: 'missing', url: 'https://github.com/apps/orca-cloud/installations/new?state=s' })
}
} as unknown as Fetcher
const { h, create, pages } = await setup({ env: { SANDBOX_CONTROL: binding } })
const viaFetch: string[] = []
h.setFetch(async (input) => {
viaFetch.push(String(input))
return new Response('error code: 1042', { status: 404 })
})
const { session, ticket } = ticketOf((await create()).body.url)
await pages.redeem(session, ticket)
await pages.post(session, 'team', { userId: 'u1', orgId: 'o_acme', name: 'acme', created: true })
const install = await pages.post(session, 'github', { userId: 'u1' })
expect(install.body).toEqual({ access: 'missing', url: 'https://github.com/apps/orca-cloud/installations/new?state=s' })
expect(viaBinding.map((url) => new URL(url).pathname)).toEqual(['/v1/internal/github/install-url'])
expect(viaFetch.filter((url) => url.includes('install-url'))).toEqual([])
})
it('normalizes GitHub repositories', () => {
expect(normalizeRepo('https://github.com/Acme/Web.git/')).toBe('https://github.com/acme/web')
expect(normalizeRepo('git@github.com:acme/web.git')).toBe('https://github.com/acme/web')
+3
View File
@@ -18,6 +18,9 @@
"migrations_dir": "migrations"
}
],
// Same-account Workers cannot call each other over workers.dev (error 1042): the GitHub install URL
// for the setup chain goes to the control plane through this binding (SANDBOX_CONTROL_URL names the origin).
"services": [{ "binding": "SANDBOX_CONTROL", "service": "orca-sandbox-control-dev" }],
// Retries Stripe meter reports that failed inline.
"triggers": { "crons": ["*/10 * * * *"] },
"vars": {
@@ -5,7 +5,8 @@ import {
getOrcaCloudSegmentState,
getRunOnSegment,
isCloudSetupPanelVisible,
resolveDefaultRunOn
resolveDefaultRunOn,
withReachableGitHub
} from './cloud-start-model'
describe('Run on segment', () => {
@@ -250,3 +251,25 @@ describe('remembered Run on default', () => {
).toEqual({ target: 'local', cloudFellBack: false })
})
})
describe('withReachableGitHub', () => {
const session = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'done', detail: 'subscription' },
{ id: 'github', state: 'active' }
] as const
it("marks the session's GitHub row done once this desktop reaches the repository", () => {
expect(withReachableGitHub([...session], true)).toEqual([
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'done', detail: 'subscription' },
{ id: 'github', state: 'done' }
])
expect(getCloudPrimaryAction([...withReachableGitHub([...session], true)])).toBe('start')
})
it('leaves the rows alone while the repository is still unreachable', () => {
const steps = [...session]
expect(withReachableGitHub(steps, false)).toBe(steps)
})
})
@@ -260,3 +260,20 @@ export function resolveDefaultRunOn({
}
return { target: wanted, cloudFellBack: false }
}
/**
* The session's rows, with its GitHub row done once this desktop's own check reaches the
* repository: the control plane's notice to the session is best effort, and the desktop's
* repo-access poll is the fallback that keeps a waiting start from hanging.
*/
export function withReachableGitHub(
steps: readonly CloudSetupStep[],
reachable: boolean
): readonly CloudSetupStep[] {
if (!reachable || !steps.some((step) => step.id === 'github' && step.state !== 'done')) {
return steps
}
return steps.map(
(step): CloudSetupStep => (step.id === 'github' ? { id: 'github', state: 'done' } : step)
)
}
@@ -1,18 +1,14 @@
// The setup panel's rows for the composer: billing access (account, trial or plan), the GitHub
// repository check (D1–D3) and the agent row, or the setup session's own rows once one is open.
import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'
import { useEffect, useMemo, useRef } from 'react'
import { translate } from '@/i18n/i18n'
import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open'
import { orcaCloudGitHubSetupRow } from '@/lib/orca-cloud/orca-cloud-github-setup-row'
import { useOrcaCloudRepoAccess } from '@/lib/orca-cloud/use-orca-cloud-repo-access'
import {
getCloudSetupSessionRevision,
readCloudSetupSession,
subscribeCloudSetupSessionRevision
} from '@/lib/orca-cloud/cloud-setup-session-seam'
import { useCloudSetupSession } from '@/lib/orca-cloud/cloud-setup-session-seam'
import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types'
import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access'
import { deriveCloudSetupSteps, type CloudSetupStep } from './cloud-start-model'
import { deriveCloudSetupSteps, withReachableGitHub, type CloudSetupStep } from './cloud-start-model'
import { cloudStartAgentStep } from './cloud-start-agent-step'
import {
orcaCloudAgentSetupRow,
@@ -92,9 +88,8 @@ export function useCloudStartSteps({
: null,
[cloudSelected, grant, loading, owner, repoName, state]
)
// Subscribing re-renders on each poll; the read itself is a cheap synchronous lookup.
useSyncExternalStore(subscribeCloudSetupSessionRevision, getCloudSetupSessionRevision)
const session = readCloudSetupSession(setupSessionId)
// Re-renders on each poll with that poll's snapshot.
const session = useCloudSetupSession(setupSessionId)
const signedOut = availability === 'needs-sign-in' || access.state === 'signed-out'
const accounts = useOrcaCloudAgentAccounts(cloudSelected && !signedOut)
const agentRow = useMemo(
@@ -114,11 +109,12 @@ export function useCloudStartSteps({
const steps = useMemo(
() =>
decorateCloudSetupSteps(
session?.steps ??
deriveCloudSetupSteps({ availability, access, github: githubOverride ?? github }),
session
? withReachableGitHub(session.steps, Boolean(githubOverride) || state === 'ok')
: deriveCloudSetupSteps({ availability, access, github: githubOverride ?? github }),
agentRow
),
[access, agentRow, availability, github, githubOverride, session?.steps]
[access, agentRow, availability, github, githubOverride, session, state]
)
return { steps, session, openInstall }
}
@@ -0,0 +1,68 @@
// @vitest-environment happy-dom
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it } from 'vitest'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
import {
getCloudSetupSessionSnapshot,
notifyCloudSetupSessionChanged,
setCloudSetupSessionSource,
useCloudSetupSession,
type CloudSetupSessionSnapshot
} from './cloud-setup-session-seam'
const planActive: CloudSetupStep[] = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'active' }
]
const planDone: CloudSetupStep[] = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'done' }
]
/** A poller stand-in: the source builds a new object on every read, like the real one. */
function installPoller(): { set: (next: CloudSetupSessionSnapshot | null) => void } {
let latest: CloudSetupSessionSnapshot | null = null
setCloudSetupSessionSource((sessionId) =>
sessionId === 'cs_test' && latest ? { ...latest, steps: [...latest.steps] } : null
)
return {
set: (next) => {
latest = next
notifyCloudSetupSessionChanged()
}
}
}
afterEach(() => {
cleanup()
setCloudSetupSessionSource(null)
})
describe('getCloudSetupSessionSnapshot', () => {
it('returns the same object until the next change, then the new snapshot', () => {
const poller = installPoller()
poller.set({ steps: planActive, finished: false })
const first = getCloudSetupSessionSnapshot('cs_test')
expect(getCloudSetupSessionSnapshot('cs_test')).toBe(first)
poller.set({ steps: planDone, finished: true })
expect(getCloudSetupSessionSnapshot('cs_test')).toEqual({ steps: planDone, finished: true })
})
it('is null without a session id or a source', () => {
expect(getCloudSetupSessionSnapshot(null)).toBeNull()
expect(getCloudSetupSessionSnapshot('cs_test')).toBeNull()
})
})
describe('useCloudSetupSession', () => {
it('re-renders with each poll, starting from no snapshot yet', () => {
const poller = installPoller()
const { result } = renderHook(() => useCloudSetupSession('cs_test'))
expect(result.current).toBeNull()
act(() => poller.set({ steps: planActive, finished: false }))
expect(result.current?.steps).toEqual(planActive)
act(() => poller.set({ steps: planDone, finished: true }))
expect(result.current).toEqual({ steps: planDone, finished: true })
})
})
@@ -4,6 +4,7 @@
// - a starter: "Set up and start" calls it and keeps the returned session id (also on the draft);
// - a source: a synchronous read of the latest polled snapshot for a session id;
// and calls notifyCloudSetupSessionChanged() after each poll so the panel re-renders.
import { useCallback, useSyncExternalStore } from 'react'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
/** "All set" holds this long before the composer submits itself (O4; 0 with reduced motion). */
@@ -67,8 +68,17 @@ export function readCloudSetupSession(sessionId: string | null): CloudSetupSessi
return sessionId && source ? source(sessionId) : null
}
// 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 }
>()
/** Call after each poll so open composers re-read their session. */
export function notifyCloudSetupSessionChanged(): void {
revision += 1
for (const listener of listeners) {
listener()
}
@@ -79,14 +89,28 @@ export function subscribeCloudSetupSession(listener: () => void): () => void {
return () => listeners.delete(listener)
}
let revision = 0
/** useSyncExternalStore pair: each poll bumps the revision so composers re-read their session. */
export function subscribeCloudSetupSessionRevision(listener: () => void): () => void {
return subscribeCloudSetupSession(() => {
revision += 1
listener()
})
/** The latest snapshot for a session: the same object until the next poll or source change. */
export function getCloudSetupSessionSnapshot(
sessionId: string | null
): CloudSetupSessionSnapshot | null {
if (!sessionId) {
return null
}
const cached = cachedReads.get(sessionId)
if (cached?.revision === revision) {
return cached.value
}
const value = readCloudSetupSession(sessionId)
cachedReads.set(sessionId, { revision, value })
return value
}
export function getCloudSetupSessionRevision(): number {
return revision
/**
* A setup session's snapshot that re-renders on every poll. Read it through this hook, never by
* calling readCloudSetupSession in a render: the React Compiler memoizes a bare call on its
* arguments, so the panel would keep the first (empty) read and never see the session move on.
*/
export function useCloudSetupSession(sessionId: string | null): CloudSetupSessionSnapshot | null {
const getSnapshot = useCallback(() => getCloudSetupSessionSnapshot(sessionId), [sessionId])
return useSyncExternalStore(subscribeCloudSetupSession, getSnapshot)
}
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ repos: [] }) } }))
import { githubRepoUrlFor, setupNeedsFrom } from './install-cloud-setup-session'
import { githubRepoUrlFor, sessionNeedsFor, setupNeedsFrom } from './install-cloud-setup-session'
describe('cloud setup seam wiring', () => {
it('maps a project remote to the setup session repository', () => {
@@ -19,4 +19,13 @@ describe('cloud setup seam wiring', () => {
'github'
])
})
it('asks a signed-out start for GitHub access, which it could not check yet', () => {
const repo = 'https://github.com/acme/web'
expect(sessionNeedsFor(['account', 'plan', 'agent'], repo)).toEqual(['plan', 'github'])
expect(sessionNeedsFor(['account', 'plan'], undefined)).toEqual(['plan'])
// Signed in, the composer's own GitHub check already decided.
expect(sessionNeedsFor(['plan'], repo)).toEqual(['plan'])
expect(sessionNeedsFor(['plan', 'github'], undefined)).toEqual(['plan'])
})
})
@@ -34,6 +34,20 @@ export function setupNeedsFrom(needs: readonly string[]): CloudSetupNeed[] {
)
}
/**
* What the session is asked to run. Signed out, Orca can't check GitHub access yet, so a GitHub
* project always asks for it: the chain marks it done on its own when access is already there.
* Without it the browser said "You're all set" while the composer still needed GitHub.
*/
export function sessionNeedsFor(needs: readonly string[], repoUrl: string | undefined): CloudSetupNeed[] {
const steps = setupNeedsFrom(needs)
if (!repoUrl) {
// Without a GitHub remote there's nothing to install; D3 covers that case in the composer.
return steps.filter((need) => need !== 'github')
}
return needs.includes('account') && !steps.includes('github') ? [...steps, 'github'] : steps
}
export function installCloudSetupSession(): () => void {
setCloudSetupSessionSource((sessionId) => {
const snapshot = getCloudSetupSnapshot(sessionId)
@@ -57,11 +71,9 @@ export function installCloudSetupSession(): () => void {
setCloudSetupStarter(async (request) => {
const repo = getIndexedRepoMap(useAppStore.getState().repos).get(request.repoId)
const repoUrl = githubRepoUrlFor(repo?.gitRemoteIdentity?.remoteUrl)
const needs = setupNeedsFrom(request.needs)
return startCloudSetupSession({
...(repoUrl ? { repo: repoUrl } : {}),
// Without a GitHub remote there's nothing to install; D3 covers that case in the composer.
needs: repoUrl ? needs : needs.filter((need) => need !== 'github')
needs: sessionNeedsFor(request.needs, repoUrl)
})
})
const unsubscribe = subscribeCloudSetupSessions(() => notifyCloudSetupSessionChanged())