fix(cloud-setup): the composer follows its setup session; billing reaches the control plane for GitHub

- The composer read the setup session with a bare readCloudSetupSession() call in render. The React
  Compiler memoizes that on the session id, so the panel kept its first (empty) read: rows never
  moved past 'In browser', the finished session never auto-started the workspace, and the GitHub
  row stayed 'Needed' after the browser said 'You're all set'. Read it through
  useCloudSetupSession (useSyncExternalStore with a per-poll cached snapshot) instead.
- Billing asked the control plane for the GitHub install URL with a plain fetch to its workers.dev
  origin. Same-account Workers can't do that (Cloudflare error 1042), so every setup GitHub step
  showed 'Orca Cloud setup is unavailable'. Bind the control plane as a service (SANDBOX_CONTROL)
  in the dev config and send the request through it when bound.

Found by the NP-4 end-to-end run (np4-e2e) on m4air against staging.
This commit is contained in:
Neil
2026-11-10 14:32:37 -08:00
parent 3a9ab1de36
commit ff64af20b0
7 changed files with 149 additions and 21 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": {
@@ -1,15 +1,11 @@
// 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'
@@ -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(
@@ -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)
}