feat(cloud): progressive billing (JA-21, Neil) — no plan/hours/payment warnings or blocks in the composer; Create goes on and the creating sheet shows a blocker card (Turn on overage / raise cap / Compare plans / Update payment, member: ask an owner or admin), continuing the create after an in-app fix

This commit is contained in:
Neil
2026-11-12 00:34:23 -08:00
parent 2691accd1d
commit ebecd11dc8
21 changed files with 876 additions and 638 deletions
@@ -87,6 +87,23 @@ describe('Orca Cloud built-in recipe steps', () => {
expect(result.failure?.errorCode).toBe('cloudPlanRequired')
})
it.each([
'no_subscription',
'included_hours_exhausted',
'overage_cap_reached',
'payment_past_due'
] as const)(
'JA-21: a %s refusal creates no sandbox, so a blocked create uses no hours',
async (reason) => {
const { plane, step } = setup()
plane.denyNextStart(reason)
const result = await step({ mode: 'create', repoPath, context })
expect(result.failure?.errorCode).toBe('cloudPlanRequired')
expect(result.stderr).toContain(`Orca Cloud: ${reason}`)
expect(plane.sandboxes.size).toBe(0)
}
)
it('tells the user to free a slot, not to buy a plan, when the member is at their cap', async () => {
const { plane, step } = setup()
plane.denyNextStart('member_concurrency_limit')
@@ -1,6 +1,5 @@
import { OrcaCloudNeedsRepoLine } from './run-on/OrcaCloudNeedsRepoLine'
import { ORCA_CLOUD_NEEDS_REPO_ID } from './run-on/cloud-start-view'
import { OrcaCloudWallLine } from './run-on/OrcaCloudWallLine'
import React from 'react'
import { FolderPlus, LoaderCircle, PlugZap } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -230,7 +229,6 @@ export function NewWorkspaceComposerProjectSection({
{ephemeralVmRecipeError}
</p>
) : null}
{cloudStart?.wall ? <OrcaCloudWallLine wall={cloudStart.wall} /> : null}
</div>
) : null}
</div>
@@ -64,7 +64,7 @@ function Preview({
recipes?: EphemeralVmRecipeOption[]
recipeValue?: string | null
access?: OrcaCloudRunTargetAccess
/** The composer's picker: setup comes after Start, JA-21's preflight applies when flagged. */
/** The composer's picker: setup and billing come after Create. */
composer?: boolean
}): React.JSX.Element {
return (
@@ -286,82 +286,30 @@ export const rowActions = defineFixture({
interact: pressKeys('ArrowDown', 'ArrowDown')
})
// JA-21 (flagged): the composer's picker for an owner at a billing wall, flag off then on.
const preflight = (on: boolean): void => {
if (on) {
localStorage.setItem('orca:dev:runOnPreflight', '1')
} else {
localStorage.removeItem('orca:dev:runOnPreflight')
}
// JA-21 (Neil): progressive billing. In the composer Orca Cloud is pickable whatever billing says,
// with no plan, hours or payment words; the creating sheet shows any blocker after Create.
function composerWith(access: OrcaCloudRunTargetAccess, width = 420) {
return defineFixture({
width,
render: () => <Preview composer recipes={withCloud} access={access} />,
interact: open
})
}
export const composerOutOfHoursPreflightOff = defineFixture({
width: 420,
render: () => {
preflight(false)
return (
<Preview
composer
recipes={withCloud}
access={{ state: 'out-of-hours', cause: 'hours', canManageBilling: true }}
/>
)
},
interact: open
export const composerOwnerOutOfHours = composerWith({
state: 'out-of-hours',
cause: 'hours',
canManageBilling: true
})
export const composerOutOfHoursPreflight = defineFixture({
width: 420,
render: () => {
preflight(true)
return (
<Preview
composer
recipes={withCloud}
access={{ state: 'out-of-hours', cause: 'hours', canManageBilling: true }}
/>
)
},
interact: open
export const composerMemberOutOfHours = composerWith({
state: 'out-of-hours',
cause: 'hours',
canManageBilling: false
})
export const composerPaymentIssuePreflight = defineFixture({
width: 420,
render: () => {
preflight(true)
return (
<Preview
composer
recipes={withCloud}
access={{ state: 'payment-issue', canManageBilling: true }}
/>
)
},
interact: open
})
export const composerLapsedPreflight = defineFixture({
width: 420,
render: () => {
preflight(true)
return (
<Preview
composer
recipes={withCloud}
access={{ state: 'no-plan', lapsed: true, canManageBilling: true }}
/>
)
},
interact: open
})
// The composer's Run on column is narrow (~300px): "Orca Cloud" stays whole, the reason wraps.
export const composerOutOfHoursPreflightNarrow = defineFixture({
width: 320,
render: () => {
preflight(true)
return (
<Preview
composer
recipes={withCloud}
access={{ state: 'out-of-hours', cause: 'hours', canManageBilling: true }}
/>
)
},
interact: open
export const composerMemberPaymentIssue = composerWith({
state: 'payment-issue',
canManageBilling: false
})
export const composerMemberPlanEnded = composerWith(
{ state: 'no-plan', lapsed: true, canManageBilling: false },
320
)
@@ -16,7 +16,9 @@ vi.mock('@/components/ui/popover', () => ({
PopoverAnchor: ({ children }: { children: React.ReactNode }) => <>{children}</>,
PopoverContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>
}))
vi.mock('@/components/billing/plans/plans-page-store', () => ({ openPlansPage: vi.fn() }))
vi.mock('@/components/billing/plans/plans-page-store', () => ({
openPlansPage: vi.fn()
}))
const hosts: ProjectHostSetupOption[] = [
{
@@ -90,11 +92,13 @@ function cloudRow(): HTMLElement | null {
)
}
const outOfHours: OrcaCloudRunTargetAccess = {
state: 'out-of-hours',
cause: 'hours',
canManageBilling: true
}
const blocked: [string, OrcaCloudRunTargetAccess][] = [
['owner out of hours', { state: 'out-of-hours', cause: 'hours', canManageBilling: true }],
['member out of hours', { state: 'out-of-hours', cause: 'hours', canManageBilling: false }],
['member at the spend cap', { state: 'out-of-hours', cause: 'cap', canManageBilling: false }],
['member, payment failed', { state: 'payment-issue', canManageBilling: false }],
['member, plan ended', { state: 'no-plan', lapsed: true, canManageBilling: false }]
]
beforeEach(() => {
resetOrcaCloudBillingCache()
@@ -110,42 +114,30 @@ afterEach(() => {
root.unmount()
})
container.remove()
localStorage.removeItem('orca:dev:runOnPreflight')
})
describe('Run on preflight (JA-21, flagged)', () => {
it('flag off: nothing changes, the composer picks Orca Cloud and setup comes after Start', () => {
const onSelectOrcaCloud = vi.fn()
renderComposer(outOfHours, onSelectOrcaCloud)
expect(cloudRow()?.getAttribute('aria-disabled')).toBeNull()
expect(container.textContent).not.toContain('Turn on overage')
press('ArrowDown')
press('Enter')
expect(onSelectOrcaCloud).toHaveBeenCalledOnce()
})
it('flag on: a billing wall disables the row with its reason and one fix, and Enter runs the fix', () => {
localStorage.setItem('orca:dev:runOnPreflight', '1')
const onSelectOrcaCloud = vi.fn()
renderComposer(outOfHours, onSelectOrcaCloud)
expect(cloudRow()?.getAttribute('aria-disabled')).toBe('true')
expect(cloudRow()?.textContent).toContain('Out of sandbox hours')
expect(cloudRow()?.textContent).toContain('Turn on overage')
press('ArrowDown')
press('Enter')
expect(onSelectOrcaCloud).not.toHaveBeenCalled()
expect(openSettingsTarget).toHaveBeenCalledWith(
expect.objectContaining({ pane: 'cloud-billing' })
)
})
it('flag on: a plan not started yet is setup, not a wall, so it stays pickable', () => {
localStorage.setItem('orca:dev:runOnPreflight', '1')
const onSelectOrcaCloud = vi.fn()
renderComposer({ state: 'no-plan', lapsed: false, canManageBilling: true }, onSelectOrcaCloud)
expect(cloudRow()?.getAttribute('aria-disabled')).toBeNull()
press('ArrowDown')
press('Enter')
expect(onSelectOrcaCloud).toHaveBeenCalledOnce()
})
describe('progressive billing in Run on (JA-21, Neil)', () => {
it.each(blocked)(
'%s: Orca Cloud stays pickable with no billing words, and Enter picks it',
(_name, access) => {
const onSelectOrcaCloud = vi.fn()
renderComposer(access, onSelectOrcaCloud)
expect(cloudRow()?.getAttribute('aria-disabled')).toBeNull()
const text = cloudRow()?.textContent ?? ''
for (const word of [
'sandbox hours',
'overage',
'spend cap',
'Payment',
'plan ended',
'Ask an owner'
]) {
expect(text).not.toContain(word)
}
press('ArrowDown')
press('Enter')
expect(onSelectOrcaCloud).toHaveBeenCalledOnce()
expect(openSettingsTarget).not.toHaveBeenCalled()
}
)
})
@@ -14,7 +14,6 @@ import {
type OrcaCloudRunTargetAccess
} from './orca-cloud-run-target-access'
import { ORCA_CLOUD_SANDBOX_SPEC } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire'
import { orcaCloudNeedsFixFirst, useRunOnPreflightEnabled } from '@/lib/orca-cloud/run-on-preflight'
/**
* Looks like a button but is plain option content: focus stays in the combobox input, Enter on the
@@ -94,7 +93,9 @@ export function useOrcaCloudHoursLeft(access: OrcaCloudRunTargetAccess): string
'Trial · {{hours}} sandbox hours left · No card needed',
{
count: offered,
hours: new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(offered),
hours: new Intl.NumberFormat(locale, {
maximumFractionDigits: 1
}).format(offered),
defaultValue_one: 'Trial · {{hours}} sandbox hour left · No card needed'
}
)
@@ -110,7 +111,9 @@ export function useOrcaCloudHoursLeft(access: OrcaCloudRunTargetAccess): string
'Trial · {{hours}} sandbox hours left',
{
count,
hours: new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(count),
hours: new Intl.NumberFormat(locale, {
maximumFractionDigits: 1
}).format(count),
defaultValue_one: 'Trial · {{hours}} sandbox hour left'
}
)
@@ -294,28 +297,6 @@ function OrcaCloudMeta({
}
}
/**
* In the composer, hours and plan details wait until after create (Neil): the row only keeps what
* explains why it can't be picked, "Ask an owner or admin".
*/
function showsMetaAfterStart(access: OrcaCloudRunTargetAccess, preflight: boolean): boolean {
// JA-21 (flagged): a billing wall is fixed here, before Start, not on the setup page after it.
if (preflight && orcaCloudNeedsFixFirst(access)) {
return true
}
switch (access.state) {
case 'no-plan':
case 'out-of-hours':
case 'payment-issue':
return !access.canManageBilling
case 'loading':
case 'entitled':
case 'signed-out':
case 'unknown':
return false
}
}
/** Orca Cloud as a first-class Run-on target, with the fix for what blocks it (and hours, behind RUN_ON_SHOWS_HOURS_LEFT). */
export function RunTargetOrcaCloudRow({
recipe,
@@ -343,41 +324,44 @@ export function RunTargetOrcaCloudRow({
setupAfterStart?: boolean
}): React.JSX.Element {
const t = useTranslate()
const preflight = useRunOnPreflightEnabled() && setupAfterStart
// A billing wall keeps "Orca Cloud" whole and wraps its reason under it (design-squad).
const wallShown = preflight && orcaCloudNeedsFixFirst(access)
// JA-21 (Neil): the composer says nothing about plan, hours or payment; Create checks and the
// creating sheet shows any blocker. Outside the composer the row still names the fix.
const shown: OrcaCloudRunTargetAccess =
setupAfterStart &&
(access.state === 'no-plan' ||
access.state === 'out-of-hours' ||
access.state === 'payment-issue')
? { state: 'unknown' }
: access
return (
<RunTargetRow
icon={<Cloud className="size-3.5 shrink-0 text-muted-foreground" />}
label={recipe?.name ?? ORCA_CLOUD_LABEL}
labelBadge={
access.state === 'no-plan' && !access.lapsed ? (
shown.state === 'no-plan' && !shown.lapsed ? (
<Badge variant="tag">
{t('auto.components.new.workspace.RunTargetCombobox.orcaCloudTeamBadge', 'Team')}
</Badge>
) : undefined
}
detail=""
detailNode={<OrcaCloudDetail access={access} />}
detailNode={<OrcaCloudDetail access={shown} />}
armed={armed}
current={current}
disabled={
((access.state === 'no-plan' ||
access.state === 'out-of-hours' ||
access.state === 'payment-issue') &&
!access.canManageBilling) ||
wallShown
(shown.state === 'no-plan' ||
shown.state === 'out-of-hours' ||
shown.state === 'payment-issue') &&
!shown.canManageBilling
}
optionId={optionId}
wrapDetail={wallShown}
busy={pending}
onArm={onArm}
onCommit={onSelect}
description={orcaCloudRowHint(access, t)}
description={orcaCloudRowHint(shown, t)}
trailing={
setupAfterStart && !showsMetaAfterStart(access, preflight) ? undefined : (
<OrcaCloudMeta access={access} onAction={onBlockedAction} alignTop={wallShown} />
)
// The composer walks sign-in on its setup page after Start: no inline meta here.
setupAfterStart ? undefined : <OrcaCloudMeta access={shown} onAction={onBlockedAction} />
}
/>
)
@@ -15,7 +15,6 @@ import {
toOrcaCloudRunTargetAccess,
type OrcaCloudRunTargetAccess
} from './orca-cloud-run-target-access'
import { devBillingFaultAccess } from '@/lib/orca-cloud/run-on-preflight'
/**
* The Run-on picker's and selection hint's view of the shared billing store. The composer prefetches
@@ -46,11 +45,6 @@ export function invalidateOrcaCloudBilling({ refetchNow = true } = {}): void {
}
function accessFrom(snapshot: BillingStoreState): OrcaCloudRunTargetAccess {
// Dev/QA: a simulated billing wall for real-app shots (never in production builds).
const fault = devBillingFaultAccess()
if (fault) {
return fault
}
if (!snapshot.result && snapshot.loading) {
return { state: 'loading' }
}
@@ -1,42 +0,0 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import { OrcaCloudWallLine } from './OrcaCloudWallLine'
// The Run on column is half the composer: about 230px. The reason wraps, never truncates.
function Column({ children }: { children: React.ReactNode }): React.JSX.Element {
return <div className="w-[230px] p-2">{children}</div>
}
export const ownerOutOfHours = defineFixture({
width: 260,
render: () => (
<Column>
<OrcaCloudWallLine
wall={{
reason: 'Out of sandbox hours',
action: { label: 'Turn on overage', run: () => {} }
}}
/>
</Column>
)
})
export const ownerPaymentFailed = defineFixture({
width: 260,
render: () => (
<Column>
<OrcaCloudWallLine
wall={{
reason: 'Payment failed',
action: { label: 'Update payment method', run: () => {} }
}}
/>
</Column>
)
})
export const memberPlanEnded = defineFixture({
width: 260,
render: () => (
<Column>
<OrcaCloudWallLine wall={{ reason: 'Your Team plan ended', action: null }} />
</Column>
)
})
@@ -1,34 +0,0 @@
import React from 'react'
import { Button } from '@/components/ui/button'
import { useTranslate } from '@/i18n/use-translate'
import type { OrcaCloudWallNotice } from '@/lib/orca-cloud/run-on-preflight'
/**
* JA-21b (flagged): under Run on when Orca Cloud is the selected target and a billing wall applies.
* The reason, then the one fix (or who can fix it) on its own line, flush with the reason: one
* layout in the narrow column, never a dangling separator (design-squad). Create waits until fixed.
*/
export function OrcaCloudWallLine({ wall }: { wall: OrcaCloudWallNotice }): React.JSX.Element {
const t = useTranslate()
return (
<div role="status" className="flex flex-col items-start text-[11px]" data-orca-cloud-wall>
{/* Wraps rather than truncating: the glossary reason is never cut. */}
<p className="text-muted-foreground">{wall.reason}</p>
{wall.action ? (
// statusAction pads its label by px-1; the wrapper's -mx-1 puts the text flush-left.
<div className="-mx-1">
<Button type="button" variant="link" size="statusAction" onClick={wall.action.run}>
<span className="underline underline-offset-4">{wall.action.label}</span>
</Button>
</div>
) : (
<p className="text-muted-foreground">
{t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskOwnerOrAdmin',
'Ask an owner or admin'
)}
</p>
)}
</div>
)
}
@@ -58,41 +58,48 @@ describe('setup rows and the setup page', () => {
expect(page(steps)).toBe('sign-in')
})
it('owner without a plan chooses one in the browser; lapsed renews there', () => {
const noPlan = deriveCloudSetupSteps({
availability: 'needs-capability',
access: { state: 'no-plan', lapsed: false, canManageBilling: true }
})
expect(page(noPlan)).toBe('choose-plan')
const lapsed = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'no-plan', lapsed: true, canManageBilling: true }
})
expect(page(lapsed)).toBe('choose-plan')
expect(lapsed.find((s) => s.id === 'plan')?.need).toBe('renew-plan')
})
it('a member who cannot fix billing is told to ask an owner, with no agent row', () => {
const steps = deriveCloudSetupSteps({
availability: 'needs-capability',
access: { state: 'no-plan', lapsed: false, canManageBilling: false }
})
expect(steps.some((s) => s.id === 'agent')).toBe(false)
expect(page(steps)).toBe('ask-owner')
const outOfHours = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'out-of-hours', cause: 'hours', canManageBilling: false }
})
expect(page(outOfHours)).toBe('ask-owner')
})
it('an owner out of hours fixes it in billing', () => {
const steps = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'out-of-hours', cause: 'hours', canManageBilling: true }
})
expect(page(steps)).toBe('fix-billing')
})
it.each([
[
'owner, no plan',
'needs-capability',
{ state: 'no-plan', lapsed: false, canManageBilling: true }
],
['owner, plan ended', 'offered', { state: 'no-plan', lapsed: true, canManageBilling: true }],
[
'member, no plan',
'needs-capability',
{ state: 'no-plan', lapsed: false, canManageBilling: false }
],
[
'owner, trial used up',
'offered',
{ state: 'no-plan', lapsed: false, canManageBilling: true, trialUsedUp: true }
],
[
'member, trial used up',
'offered',
{ state: 'no-plan', lapsed: false, canManageBilling: false, trialUsedUp: true }
],
[
'owner out of hours',
'offered',
{ state: 'out-of-hours', cause: 'hours', canManageBilling: true }
],
[
'member out of hours',
'offered',
{ state: 'out-of-hours', cause: 'hours', canManageBilling: false }
],
['member, payment failed', 'offered', { state: 'payment-issue', canManageBilling: false }]
] as const)(
'JA-21 progressive billing: %s is not a setup step; Create goes on and the sheet shows any blocker',
(_name, availability, access) => {
const steps = deriveCloudSetupSteps({ availability, access })
expect(steps.find((s) => s.id === 'plan')?.state).toBe('done')
expect(steps.some((s) => s.id === 'agent')).toBe(true)
expect(cloudSetupRequired(steps)).toBe(false)
}
)
it('a missing GitHub grant alone is the GitHub step', () => {
expect(
@@ -108,29 +115,24 @@ describe('setup rows and the setup page', () => {
it('a team that can still get its trial claims it in the app (B1)', () => {
const steps = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialOfferSeconds: 7200 }
access: {
state: 'no-plan',
lapsed: false,
canManageBilling: false,
trialOfferSeconds: 7200
}
})
const plan = steps.find((s) => s.id === 'plan')
expect(plan).toMatchObject({ need: 'trial', trialSeconds: 7200, canFix: true })
expect(plan).toMatchObject({
need: 'trial',
trialSeconds: 7200,
canFix: true
})
// Members aren't blocked from the trial: the agent row stays.
expect(steps.some((s) => s.id === 'agent')).toBe(true)
expect(page(steps)).toBe('start-trial')
})
it('trial used up: owner chooses a plan; member asks an owner (T2, C1)', () => {
const owner = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'no-plan', lapsed: false, canManageBilling: true, trialUsedUp: true }
})
expect(owner.find((s) => s.id === 'plan')?.need).toBe('trial-used-up')
expect(page(owner)).toBe('choose-plan')
const member = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialUsedUp: true }
})
expect(page(member)).toBe('ask-owner')
})
it('signed out: the trial row is included and GitHub is checked up front (A1)', () => {
const steps = deriveCloudSetupSteps({
availability: 'needs-sign-in',
@@ -147,7 +149,12 @@ describe('setup rows and the setup page', () => {
const steps = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'entitled', remainingSeconds: 3600 },
github: { id: 'github', state: 'pending', need: 'github', blocksStart: true }
github: {
id: 'github',
state: 'pending',
need: 'github',
blocksStart: true
}
})
expect(cloudSetupRequired(steps)).toBe(true)
expect(page(steps)).toBe('github-waiting')
@@ -157,7 +164,12 @@ describe('setup rows and the setup page', () => {
const steps = deriveCloudSetupSteps({
availability: 'needs-sign-in',
access: { state: 'signed-out' },
github: { id: 'github', state: 'failed', need: 'github', blocksStart: true }
github: {
id: 'github',
state: 'failed',
need: 'github',
blocksStart: true
}
})
expect(steps.map((s) => s.id)).toEqual(['github'])
expect(page(steps)).toBe('needs-repository')
@@ -170,7 +182,10 @@ describe('setup rows and the setup page', () => {
github: { id: 'github', state: 'loading' }
})
expect(page(github)).toBe('checking')
const billing = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'loading' } })
const billing = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'loading' }
})
expect(page(billing)).toBe('checking')
})
@@ -133,21 +133,12 @@ function derivePlanStep(
trialSeconds: access.trialOfferSeconds
}
}
return {
id: 'plan',
state: 'needed',
need: access.trialUsedUp ? 'trial-used-up' : access.lapsed ? 'renew-plan' : 'plan',
canFix: access.canManageBilling
}
// JA-21 (Neil): billing is progressive. A plan, hours, cap or payment problem isn't a setup
// step; Create goes ahead and the creating sheet shows the blocker with its fix.
return { id: 'plan', state: 'done' }
case 'out-of-hours':
return {
id: 'plan',
state: 'needed',
need: access.cause === 'cap' ? 'spend-cap' : 'hours',
canFix: access.canManageBilling
}
case 'payment-issue':
return { id: 'plan', state: 'needed', need: 'payment', canFix: access.canManageBilling }
return { id: 'plan', state: 'done' }
}
}
@@ -1,7 +1,6 @@
// What the composer card needs for Orca Cloud, shared by the hook and the card. Picking Orca Cloud
// changes nothing else in the dialog (composer-redo): setup lives on its own page after Start.
import type { CloudOnlyRepo } from './use-cloud-only-repo'
import type { OrcaCloudWallNotice } from '@/lib/orca-cloud/run-on-preflight'
export type CloudStartView = {
/** Picks Orca Cloud even while the account still needs setup; Start walks it on a page. */
@@ -11,8 +10,6 @@ export type CloudStartView = {
cloudOnly?: CloudOnlyRepo
/** The project is a plain folder: Orca Cloud needs a GitHub repository instead (D3/D4). */
folderProject?: boolean
/** JA-21b (flagged): Orca Cloud is selected and a billing wall applies; Create waits for the fix. */
wall?: OrcaCloudWallNotice | null
/**
* RR-c1: Orca Cloud is selected but the project is a plain folder. Both selections stay and Create
* stays enabled; Create (button or ⌘↵) then stops before submitting and this error shows under
@@ -31,7 +31,6 @@ import {
orcaCloudNeedsGitHubRepo,
type CloudStartView
} from './cloud-start-view'
import { orcaCloudWallNotice, useRunOnPreflightEnabled } from '@/lib/orca-cloud/run-on-preflight'
export type { CloudStartView } from './cloud-start-view'
@@ -86,12 +85,7 @@ export function useCloudStartComposer({
const cloudSelected = selectedRecipeId === ORCA_CLOUD_RECIPE_ID
const fetched = useOrcaCloudRunTargetAccess(segment === 'enabled' && !accessOverride)
const access = accessOverride ?? fetched
const preflight = useRunOnPreflightEnabled()
const githubProjectCount = useAppStore((s) => s.repos.filter(isGitHubBackedProject).length)
const wall = useMemo(
() => (cloudSelected && preflight ? orcaCloudWallNotice(access) : null),
[access, cloudSelected, preflight]
)
const cloudOnly = useCloudOnlyRepo({
repoId,
cloudSelected,
@@ -108,7 +102,9 @@ export function useCloudStartComposer({
githubOverride: cloudOnly.githubStep
})
const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected)
const setupNeeded = cloudSetupRequired(steps, { teamSwitch: switchTeam !== null })
const setupNeeded = cloudSetupRequired(steps, {
teamSwitch: switchTeam !== null
})
// An agent with no Orca Cloud account is still created with the workspace: its launch holds on
// the pane's "Set up once" strip and never reaches the agent's own /login (PC-3b, #385). In the
// workspace the strip asks; away, the sidebar row's mark does (N-03: no toast follows the user).
@@ -207,7 +203,6 @@ export function useCloudStartComposer({
onUserPick: markTouched,
cloudOnly,
folderProject: cloudOnly.folderProject,
wall,
needsGitHubRepo: orcaCloudNeedsGitHubRepo({
cloudSelected,
folderProject: cloudOnly.folderProject,
@@ -216,7 +211,7 @@ export function useCloudStartComposer({
githubProjectCount
})
},
[cloudOnly, cloudSelected, githubProjectCount, markTouched, onSelectOrcaCloud, segment, wall]
[cloudOnly, cloudSelected, githubProjectCount, markTouched, onSelectOrcaCloud, segment]
)
if (!view || !cloudSelected) {
return { view, onPrimary: null, recordCreated }
@@ -46,7 +46,11 @@ export function useComposerCloudStart({
// see that edit.
const runCreate = useCallback(() => void handleCreate(), [handleCreate])
const composerSnapshot = useCallback(
() => buildComposerSnapshot(modalData, cardProps, { ...quickAgentPick, agent: quickAgent }),
() =>
buildComposerSnapshot(modalData, cardProps, {
...quickAgentPick,
agent: quickAgent
}),
[cardProps, modalData, quickAgent, quickAgentPick]
)
const cloudStart = useCloudStartComposer({
@@ -79,8 +83,7 @@ export function useComposerCloudStart({
return {
cloudStart: { ...cloudStart, view },
// Local and Orca Cloud share one button: same label, same rules for when it's enabled.
// JA-21b: a billing wall on the selected Orca Cloud holds Create until it's fixed.
primaryCreateDisabled: createDisabled || Boolean(cloudStart.view?.wall),
primaryCreateDisabled: createDisabled,
onPrimary: guard.onPrimary
}
}
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { orcaCloudNeedsFixFirst, useRunOnPreflightEnabled } from '@/lib/orca-cloud/run-on-preflight'
import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types'
import { isOrcaCloudRecipe, type EphemeralVmRecipeOption } from './run-target-options'
import { getOrcaCloudPick, type OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access'
@@ -71,8 +70,6 @@ export function useRunTargetOrcaCloud({
runBlockedAction: () => void
select: (recipe: EphemeralVmRecipeOption | null) => void
} {
// JA-21 (flagged): in the composer a billing wall routes to its fix instead of picking Orca Cloud.
const preflight = useRunOnPreflightEnabled() && Boolean(onSelectOrcaCloud)
const fetched = useOrcaCloudRunTargetAccess(
!override && (recipes.some(isOrcaCloudRecipe) || offer?.state === 'no-plan')
)
@@ -102,16 +99,14 @@ export function useRunTargetOrcaCloud({
)
const pickFor = useCallback(
(resolved: OrcaCloudRunTargetAccess, recipe: EphemeralVmRecipeOption | null): void => {
const pick = getOrcaCloudPick(resolved)
if (
onSelectOrcaCloud &&
pick.kind !== 'blocked' &&
!(preflight && orcaCloudNeedsFixFirst(resolved))
) {
// JA-21 (Neil): in the composer Orca Cloud is always pickable; billing is checked after
// Create, on the creating sheet, so owners and members alike can start a draft.
if (onSelectOrcaCloud) {
close()
onSelectOrcaCloud()
return
}
const pick = getOrcaCloudPick(resolved)
if (pick.kind === 'act') {
close()
// The fix finishes elsewhere (plans, portal, settings): reread billing on return.
@@ -121,7 +116,7 @@ export function useRunTargetOrcaCloud({
selectRecipe(recipe.id)
}
},
[close, onSelectOrcaCloud, preflight, selectRecipe]
[close, onSelectOrcaCloud, selectRecipe]
)
const runBlockedAction = useCallback((): void => pickFor(access, null), [access, pickFor])
const select = useCallback(
@@ -0,0 +1,157 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type {
OrcaBillingOverageResult,
OrcaBillingStatusResult
} from '../../../../shared/orca-billing'
import { sampleTeam } from '../billing/plan-billing-fixtures'
import { VmBuildBillingBlocker, type BillingBlockKind } from './VmBuildBillingBlocker'
const setOverage =
vi.fn<(args: { enabled: boolean; spendCapCents?: number }) => Promise<OrcaBillingOverageResult>>()
const billingStatus = vi.fn<() => Promise<OrcaBillingStatusResult>>()
const openPortal = vi.fn(() => Promise.resolve({ status: 'opened' as const }))
beforeEach(() => {
setOverage.mockReset()
billingStatus.mockReset()
openPortal.mockClear()
Object.assign(window, {
api: {
orcaProfiles: {
billingSetOverage: setOverage,
billingStatus,
billingOpenPortal: openPortal
}
}
})
})
afterEach(() => {
cleanup()
})
function renderBlocker(
kind: BillingBlockKind,
{ canManageBilling = true, capCents = 2500 } = {}
): {
onContinue: ReturnType<typeof vi.fn>
onBackToDraft: ReturnType<typeof vi.fn>
onComparePlans: ReturnType<typeof vi.fn>
} {
const onContinue = vi.fn()
const onBackToDraft = vi.fn()
const onComparePlans = vi.fn()
render(
<VmBuildBillingBlocker
kind={kind}
canManageBilling={canManageBilling}
entitlement={{
...sampleTeam,
overage: { ...sampleTeam.overage, spendCapCents: capCents }
}}
onContinue={onContinue}
onComparePlans={onComparePlans}
onBackToDraft={onBackToDraft}
/>
)
return { onContinue, onBackToDraft, onComparePlans }
}
describe('billing blocker on the creating sheet (JA-21)', () => {
it('out of hours: Turn on with a $25 cap saves overage and continues the create', async () => {
setOverage.mockResolvedValue({ status: 'ok', entitlement: sampleTeam })
const { onContinue } = renderBlocker('hoursUsed')
expect(screen.getByRole('heading', { name: 'Out of sandbox hours' })).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Turn on with a $25 cap' }))
await waitFor(() => expect(onContinue).toHaveBeenCalledOnce())
expect(setOverage).toHaveBeenCalledWith({
enabled: true,
spendCapCents: 2500
})
})
it('a failed save shows inline and does not continue', async () => {
setOverage.mockResolvedValue({ status: 'failed', error: 'boom' })
const { onContinue } = renderBlocker('hoursUsed')
fireEvent.click(screen.getByRole('button', { name: 'Turn on with a $25 cap' }))
await waitFor(() => expect(screen.getByRole('status').textContent).not.toBe(''))
expect(onContinue).not.toHaveBeenCalled()
})
it('spend cap reached: the field starts at the cap plus $25 and saving continues', async () => {
setOverage.mockResolvedValue({ status: 'ok', entitlement: sampleTeam })
const { onContinue } = renderBlocker('spendCap', { capCents: 4000 })
const field = screen.getByLabelText('Monthly spend cap')
expect(field).toHaveProperty('value', '65')
fireEvent.change(field, { target: { value: '100' } })
fireEvent.click(screen.getByRole('button', { name: 'Raise spend cap and continue' }))
await waitFor(() => expect(onContinue).toHaveBeenCalledOnce())
expect(setOverage).toHaveBeenCalledWith({
enabled: true,
spendCapCents: 10_000
})
})
it('payment failed: Update payment method opens billing, and returning re-checks once', async () => {
billingStatus.mockResolvedValue({
status: 'ok',
entitlement: { ...sampleTeam, canStartSandbox: true }
})
const { onContinue } = renderBlocker('payment')
fireEvent.click(screen.getByRole('button', { name: 'Update payment method' }))
expect(openPortal).toHaveBeenCalledOnce()
expect(screen.getByText('Finish in your browser.')).toBeTruthy()
act(() => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(onContinue).toHaveBeenCalledOnce())
expect(billingStatus).toHaveBeenCalledOnce()
})
it('still blocked after the browser: stays on the card with Check again', async () => {
billingStatus.mockResolvedValue({
status: 'ok',
entitlement: { ...sampleTeam, canStartSandbox: false }
})
const { onContinue } = renderBlocker('payment')
fireEvent.click(screen.getByRole('button', { name: 'Update payment method' }))
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
await waitFor(() =>
expect(
screen.getByText('Not updated yet. Finish in your browser, then check again.')
).toBeTruthy()
)
expect(onContinue).not.toHaveBeenCalled()
})
it('no plan: Compare plans is the way forward', () => {
const { onComparePlans } = renderBlocker('plan')
expect(screen.getByRole('heading', { name: 'Choose a plan' })).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Compare plans' }))
expect(onComparePlans).toHaveBeenCalledOnce()
})
it.each([
['hoursUsed', 'Ask an owner or admin to add hours.'],
['spendCap', 'Ask an owner or admin to raise the spend cap.'],
['payment', 'Ask an owner or admin to update the payment method.'],
['plan', 'Ask an owner or admin to choose a plan.']
] as const)('member, %s: says who can fix it and offers only Back to draft', (kind, ask) => {
renderBlocker(kind, { canManageBilling: false })
expect(screen.getByText(ask)).toBeTruthy()
expect(screen.getAllByRole('button').map((button) => button.textContent)).toEqual([
'Back to draft'
])
})
it('Back to draft hands the draft back without saving anything', () => {
const { onBackToDraft, onContinue } = renderBlocker('hoursUsed')
fireEvent.click(screen.getByRole('button', { name: 'Back to draft' }))
expect(onBackToDraft).toHaveBeenCalledOnce()
expect(setOverage).not.toHaveBeenCalled()
expect(onContinue).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,347 @@
import React from 'react'
import { AlertTriangle, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate'
import type {
OrcaBillingEntitlement,
OrcaBillingOverageResult
} from '../../../../shared/orca-billing'
import { overageFailureCopy } from '../billing/plan-billing-copy'
import { formatCents } from '../billing/plans/plans-pricing'
/** The four ways billing can refuse a create (JA-21 progressive billing). */
export type BillingBlockKind = 'plan' | 'hoursUsed' | 'spendCap' | 'payment'
/** Overage turned on from the blocker: the same $25 cap as Plan & billing's off state. */
export const BLOCKER_OVERAGE_CAP_CENTS = 2500
/** Raising a reached cap suggests this much more. */
export const BLOCKER_CAP_STEP_CENTS = 2500
export type BillingBlockerPhase =
| { kind: 'idle' }
| { kind: 'saving' }
| { kind: 'error'; message: string }
/** A fix in the browser (portal): re-check on return, or with Check again. */
| { kind: 'browser'; checking: boolean; stillBlocked: boolean }
function blockerCopy(
kind: BillingBlockKind,
t: Translate
): { title: string; body: string; ask: string } {
switch (kind) {
case 'plan':
return {
title: t('worktreeCreation.billingBlock.plan.title', 'Choose a plan'),
body: t(
'worktreeCreation.billingBlock.plan.body',
'Your team needs a plan to start cloud workspaces.'
),
ask: t('worktreeCreation.billingBlock.plan.ask', 'Ask an owner or admin to choose a plan.')
}
case 'hoursUsed':
return {
title: t('worktreeCreation.billingBlock.hours.title', 'Out of sandbox hours'),
body: t(
'worktreeCreation.billingBlock.hours.body',
'Your team has used all of this month’s sandbox hours.'
),
ask: t('worktreeCreation.billingBlock.hours.ask', 'Ask an owner or admin to add hours.')
}
case 'spendCap':
return {
title: t('worktreeCreation.billingBlock.cap.title', 'Spend cap reached'),
body: t(
'worktreeCreation.billingBlock.cap.body',
'Overage is on, and this month’s spend cap is used.'
),
ask: t(
'worktreeCreation.billingBlock.cap.ask',
'Ask an owner or admin to raise the spend cap.'
)
}
case 'payment':
return {
title: t('worktreeCreation.billingBlock.payment.title', 'Payment failed'),
body: t('worktreeCreation.billingBlock.payment.body', 'New sandboxes can’t start.'),
ask: t(
'worktreeCreation.billingBlock.payment.ask',
'Ask an owner or admin to update the payment method.'
)
}
}
}
export type VmBuildBillingBlockerViewProps = {
kind: BillingBlockKind
canManageBilling: boolean
phase: BillingBlockerPhase
/** Spend cap reached: the field's starting value, in whole dollars. */
suggestedCapDollars: number
onTurnOnOverage: () => void
onRaiseCap: (dollars: number) => void
onComparePlans: () => void
onUpdatePayment: () => void
onCheckAgain: () => void
onBackToDraft: () => void
}
/**
* The creating sheet's billing blocker: replaces the steps when billing refuses a create. Nothing
* was created and no hours were used; the draft is kept, and an in-app fix continues the create.
*/
export function VmBuildBillingBlockerView({
kind,
canManageBilling,
phase,
suggestedCapDollars,
onTurnOnOverage,
onRaiseCap,
onComparePlans,
onUpdatePayment,
onCheckAgain,
onBackToDraft
}: VmBuildBillingBlockerViewProps): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const copy = blockerCopy(kind, t)
const capId = React.useId()
const [cap, setCap] = React.useState(String(suggestedCapDollars))
const headingRef = React.useRef<HTMLHeadingElement>(null)
React.useLayoutEffect(() => {
headingRef.current?.focus({ preventScroll: true })
}, [kind])
const saving = phase.kind === 'saving'
const capDollars = Number(cap)
const capValid = /^\d+$/.test(cap.trim()) && capDollars > 0
const inBrowser = phase.kind === 'browser'
return (
<div className="flex flex-col gap-3">
<div
role="alert"
className="flex gap-3 rounded-lg border border-border bg-card px-4 py-4 text-sm"
>
<AlertTriangle aria-hidden className="mt-0.5 size-4 shrink-0 text-status-warning-text" />
<div className="min-w-0 flex-1 space-y-3">
<div className="space-y-1">
<h3 ref={headingRef} tabIndex={-1} className="font-semibold outline-none">
{copy.title}
</h3>
<p className="text-muted-foreground">{copy.body}</p>
</div>
{canManageBilling ? (
inBrowser ? (
<div className="space-y-2">
<p className="text-muted-foreground">
{phase.stillBlocked
? t(
'worktreeCreation.billingBlock.browserStill',
'Not updated yet. Finish in your browser, then check again.'
)
: t('worktreeCreation.billingBlock.browser', 'Finish in your browser.')}
</p>
<Button
type="button"
variant="outline"
size="sm"
aria-busy={phase.checking || undefined}
aria-disabled={phase.checking || undefined}
onClick={phase.checking ? undefined : onCheckAgain}
>
{phase.checking ? <Loader2 className="animate-spin" /> : null}
{t('worktreeCreation.billingBlock.checkAgain', 'Check again')}
</Button>
</div>
) : kind === 'spendCap' ? (
<form
className="flex flex-wrap items-end gap-2"
onSubmit={(event) => {
event.preventDefault()
if (!saving && capValid) {
onRaiseCap(capDollars)
}
}}
>
<div className="space-y-1">
<label htmlFor={capId} className="block text-xs font-medium">
{t('auto.components.billing.capLabel2', 'Monthly spend cap')}
</label>
<div className="flex items-center gap-1">
<span className="text-muted-foreground">$</span>
<Input
id={capId}
inputMode="numeric"
className="w-24"
value={cap}
aria-invalid={!capValid || undefined}
onChange={(event) => setCap(event.target.value)}
/>
</div>
</div>
<Button
type="submit"
size="sm"
aria-busy={saving || undefined}
aria-disabled={saving || !capValid || undefined}
>
{saving ? <Loader2 className="animate-spin" /> : null}
{t(
'worktreeCreation.billingBlock.raiseCapAndContinue',
'Raise spend cap and continue'
)}
</Button>
</form>
) : (
<div className="flex flex-wrap gap-2">
{kind === 'hoursUsed' ? (
<Button
type="button"
size="sm"
aria-busy={saving || undefined}
aria-disabled={saving || undefined}
onClick={saving ? undefined : onTurnOnOverage}
>
{saving ? <Loader2 className="animate-spin" /> : null}
{t('auto.components.billing.overage.turnOn', 'Turn on with a {{cap}} cap', {
cap: formatCents(BLOCKER_OVERAGE_CAP_CENTS, locale)
})}
</Button>
) : null}
{kind === 'payment' ? (
<Button type="button" size="sm" onClick={onUpdatePayment}>
{t(
'auto.components.worktree.creation.VmBuildFailureCard.updatePayment',
'Update payment method'
)}
</Button>
) : (
<Button
type="button"
size="sm"
variant={kind === 'hoursUsed' ? 'outline' : 'default'}
onClick={onComparePlans}
>
{t('auto.components.billing.comparePlans', 'Compare plans')}
</Button>
)}
</div>
)
) : (
<p className="text-muted-foreground">{copy.ask}</p>
)}
{phase.kind === 'error' ? (
<p role="status" className="text-destructive-text">
{phase.message}
</p>
) : null}
</div>
</div>
<Button
type="button"
variant="ghost"
size="sm"
className="self-start"
onClick={onBackToDraft}
>
{t('worktreeCreation.billingBlock.backToDraft', 'Back to draft')}
</Button>
</div>
)
}
/**
* The live blocker: in-app fixes (overage, a higher cap) save and continue the create at once; a
* browser fix (payment) re-checks once when Orca regains focus, or on Check again.
*/
export function VmBuildBillingBlocker({
kind,
canManageBilling,
entitlement,
onContinue,
onComparePlans,
onBackToDraft
}: {
kind: BillingBlockKind
canManageBilling: boolean
entitlement: OrcaBillingEntitlement | null
/** Starts the create again from "Checking your plan…". */
onContinue: () => void
onComparePlans: () => void
onBackToDraft: () => void
}): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const [phase, setPhase] = React.useState<BillingBlockerPhase>({
kind: 'idle'
})
const currentCap = entitlement?.overage.spendCapCents ?? 0
const suggestedCapDollars = Math.round((currentCap + BLOCKER_CAP_STEP_CENTS) / 100)
const maxCap = entitlement?.offers?.team.maxSpendCapCents ?? null
const saveOverage = async (spendCapCents: number): Promise<void> => {
setPhase({ kind: 'saving' })
const outcome = await window.api.orcaProfiles
.billingSetOverage({ enabled: true, spendCapCents })
.catch((error: unknown): OrcaBillingOverageResult => ({
status: 'failed',
error: String(error)
}))
if (outcome.status === 'ok') {
onContinue()
return
}
setPhase({
kind: 'error',
message:
overageFailureCopy(outcome, t, maxCap, locale) ??
t(
'worktreeCreation.billingBlock.saveFailed',
'Couldn’t save that. Try again, or change it in Plan & billing.'
)
})
}
const checkBilling = React.useCallback(async (): Promise<void> => {
setPhase({ kind: 'browser', checking: true, stillBlocked: false })
const status = await window.api.orcaProfiles.billingStatus().catch(() => null)
// The service's own verdict: a fixed payment makes new sandboxes startable again.
if (status?.status === 'ok' && status.entitlement.canStartSandbox) {
onContinue()
return
}
setPhase({ kind: 'browser', checking: false, stillBlocked: true })
}, [onContinue])
// Back from the browser: check once; if billing is fine the create continues on its own.
const waitingOnBrowser = phase.kind === 'browser'
React.useEffect(() => {
if (!waitingOnBrowser) {
return
}
const onFocus = (): void => {
window.removeEventListener('focus', onFocus)
void checkBilling()
}
window.addEventListener('focus', onFocus)
return () => window.removeEventListener('focus', onFocus)
}, [waitingOnBrowser, checkBilling])
return (
<VmBuildBillingBlockerView
kind={kind}
canManageBilling={canManageBilling}
phase={phase}
suggestedCapDollars={suggestedCapDollars}
onTurnOnOverage={() => void saveOverage(BLOCKER_OVERAGE_CAP_CENTS)}
onRaiseCap={(dollars) => void saveOverage(dollars * 100)}
onComparePlans={onComparePlans}
onUpdatePayment={() => {
setPhase({ kind: 'browser', checking: false, stillBlocked: false })
void window.api.orcaProfiles.billingOpenPortal().catch(() => {})
}}
onCheckAgain={() => void checkBilling()}
onBackToDraft={onBackToDraft}
/>
)
}
@@ -20,6 +20,7 @@ import { formatEnvironmentDoctorChecks } from '../../../../shared/environment-do
import { VmBuildStepRow } from './VmBuildStepRow'
import { firstBuildLogErrorLine, VmBuildLog } from './VmBuildLog'
import { VmBuildFailureCard } from './VmBuildFailureCard'
import { VmBuildBillingBlocker } from './VmBuildBillingBlocker'
import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow'
import { VmBuildSecretsRow } from '../cloud-secrets-ask/VmBuildSecretsRow'
import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt'
@@ -154,6 +155,9 @@ export function VmBuildSheet({
const failure = classifyVmBuildFailure({ entry, error, cloud })
const gated = isAccountGate(failure)
const billing = useOrcaBillingStatus(isBillingFailure(failure))
// JA-21: on Orca Cloud a billing refusal is a blocker card in place of the steps, under the
// sheet's own title; nothing was created and the draft is kept.
const billingBlock = cloud && failure && isBillingFailure(failure) ? failure.kind : null
// Unknown roles get the owner's copy; only a known member is told to ask someone else.
const canManageBilling =
billing.result?.status !== 'ok' || billing.result.entitlement.canManageBilling
@@ -210,7 +214,7 @@ export function VmBuildSheet({
<div data-vm-build-sheet className="flex min-h-full justify-center pt-12">
<div className="flex w-full max-w-2xl flex-col gap-4">
{/* JA-24: on Orca Cloud a failure card carries the one title; no page title above it. */}
{cloud && failure ? null : (
{cloud && failure && !billingBlock ? null : (
<div className="flex min-h-7 items-center justify-between gap-3">
<div className="flex items-center gap-2">
<span className="grid size-4 shrink-0 place-items-center">
@@ -240,7 +244,9 @@ export function VmBuildSheet({
aria-live={failure ? 'off' : 'polite'}
className="text-sm font-medium text-foreground outline-none"
>
{headerTitle(state, cloud, t, failure?.kind === 'create')}
{billingBlock
? headerTitle('building', cloud, t)
: headerTitle(state, cloud, t, failure?.kind === 'create')}
</h2>
{/* Orca Cloud: each step carries its own timer, so the header has none. */}
{gated || cloud ? null : (
@@ -258,117 +264,137 @@ export function VmBuildSheet({
</div>
)}
<div>
{/* An account refusal happens before anything starts, so there are no steps to show. */}
{gated ? null : (
<ol className="flex flex-col rounded-lg border border-border bg-card px-4 py-2 text-sm">
{steps.map((step) => (
<VmBuildStepRow
key={step.id}
step={step}
cloud={cloud}
detail={
cloud && step.id === 'provision' && step.state === 'running'
? provisionStageLabel(entry, step.elapsedMs, t)
: step.id === 'clone' && step.state === 'running'
? cloneStageLabel(step.stage, t, step.cloneMode)
: null
}
timing={timings[step.id] ?? null}
stopped={failure !== null}
t={t}
waitedMs={steps.find((candidate) => candidate.id === 'provision')?.elapsedMs ?? 0}
/>
))}
{/* Orca Cloud: agent setup happens after create (the setup page and the workspace's
sign-in strip), so the build card has no agent row. Other VMs keep the host's own. */}
{agentSignInRow ??
(!cloud && entry.vmEnvironmentId ? (
<VmBuildAgentSignInRow
creationId={creationId}
environmentId={entry.vmEnvironmentId}
/>
) : null)}
{secretsRow !== undefined ? (
secretsRow
) : cloud ? (
<VmBuildSecretsRow entry={entry} />
) : null}
</ol>
)}
<VmBuildFailureCard
failure={failure}
cloud={cloud}
vmKept={
failure?.kind === 'checks'
? failure.sandbox !== 'deleted'
: Boolean(entry.request.ephemeralVmRuntimeId)
}
firstErrorLine={firstErrorLine}
canFixWithAgent={Boolean(recipe)}
{billingBlock === 'plan' ||
billingBlock === 'hoursUsed' ||
billingBlock === 'spendCap' ||
billingBlock === 'payment' ? (
<VmBuildBillingBlocker
kind={billingBlock}
canManageBilling={canManageBilling}
signingIn={signingIn}
connectingGitHub={connectingGitHub}
repoName={repoName}
actions={{
onFixWithAgent: () => {
if (recipe) {
startFixWithAgent({
repoId: recipe.sourceRepoId,
recipeId: recipe.recipeId,
failure: fixContext(failure, derived, entry, error, cloud, t)
})
}
},
onRetry:
failure?.kind === 'checks'
? () => resolveVmEnvironmentCheckDecision(creationId, 'retry')
: onRetry,
onEditRecipe,
onOpenAnyway: () => resolveVmEnvironmentCheckDecision(creationId, 'open-anyway'),
// A paused create deletes this sandbox and starts over; one already gone just retries.
onStartAgain: () =>
isAwaitingVmEnvironmentCheckDecision(creationId)
? resolveVmEnvironmentCheckDecision(creationId, 'restart')
: onRetry(),
// Nothing was created, so leaving a billing refusal hands the typed prompt back.
onDismiss:
isBillingFailure(failure) && typedComposerPrompt(entry).trim()
? () => onReturnToComposer({ local: false })
: onDismiss,
onSeePlans: () => {
// Once paid, the plans dialog closes and retries this create.
requestOrcaCloudAfterCheckout({ kind: 'retry', creationId })
openPlansPage('sandbox')
},
onCreateLocally: () => onReturnToComposer({ local: true }),
onOpenBilling: () => {
const store = useAppStore.getState()
store.openSettingsTarget({
pane: 'cloud-billing',
repoId: null,
// "Turn on overage" / "Raise spend cap" land on the overage card itself; the
// payment notice is at the top of the section already.
...(failure?.kind === 'payment'
? {}
: { sectionId: ORCA_BILLING_OVERAGE_SECTION_ID })
})
store.openSettingsPage()
},
onSignIn: signIn,
// Your workspaces on Home, where you can put one to sleep or delete it.
onShowWorkspaces: () => openCloudWorkspacesHome({ running: true }),
onContactSupport: () => openAppHttpLink(SUPPORT_URL),
onConnectGitHub: connectGitHub,
onPushToGitHub: () => openAppHttpLink(PUSH_TO_GITHUB_URL)
entitlement={billing.result?.status === 'ok' ? billing.result.entitlement : null}
onContinue={onRetry}
onComparePlans={() => {
// Once paid, the plans page closes and continues this create.
requestOrcaCloudAfterCheckout({ kind: 'retry', creationId })
openPlansPage('sandbox')
}}
onBackToDraft={() => onReturnToComposer({ local: false })}
/>
</div>
) : (
<div>
{/* An account refusal happens before anything starts, so there are no steps to show. */}
{gated ? null : (
<ol className="flex flex-col rounded-lg border border-border bg-card px-4 py-2 text-sm">
{steps.map((step) => (
<VmBuildStepRow
key={step.id}
step={step}
cloud={cloud}
detail={
cloud && step.id === 'provision' && step.state === 'running'
? provisionStageLabel(entry, step.elapsedMs, t)
: step.id === 'clone' && step.state === 'running'
? cloneStageLabel(step.stage, t, step.cloneMode)
: null
}
timing={timings[step.id] ?? null}
stopped={failure !== null}
t={t}
waitedMs={
steps.find((candidate) => candidate.id === 'provision')?.elapsedMs ?? 0
}
/>
))}
{/* Orca Cloud: agent setup happens after create (the setup page and the workspace's
sign-in strip), so the build card has no agent row. Other VMs keep the host's own. */}
{agentSignInRow ??
(!cloud && entry.vmEnvironmentId ? (
<VmBuildAgentSignInRow
creationId={creationId}
environmentId={entry.vmEnvironmentId}
/>
) : null)}
{secretsRow !== undefined ? (
secretsRow
) : cloud ? (
<VmBuildSecretsRow entry={entry} />
) : null}
</ol>
)}
<VmBuildFailureCard
failure={failure}
cloud={cloud}
vmKept={
failure?.kind === 'checks'
? failure.sandbox !== 'deleted'
: Boolean(entry.request.ephemeralVmRuntimeId)
}
firstErrorLine={firstErrorLine}
canFixWithAgent={Boolean(recipe)}
canManageBilling={canManageBilling}
signingIn={signingIn}
connectingGitHub={connectingGitHub}
repoName={repoName}
actions={{
onFixWithAgent: () => {
if (recipe) {
startFixWithAgent({
repoId: recipe.sourceRepoId,
recipeId: recipe.recipeId,
failure: fixContext(failure, derived, entry, error, cloud, t)
})
}
},
onRetry:
failure?.kind === 'checks'
? () => resolveVmEnvironmentCheckDecision(creationId, 'retry')
: onRetry,
onEditRecipe,
onOpenAnyway: () => resolveVmEnvironmentCheckDecision(creationId, 'open-anyway'),
// A paused create deletes this sandbox and starts over; one already gone just retries.
onStartAgain: () =>
isAwaitingVmEnvironmentCheckDecision(creationId)
? resolveVmEnvironmentCheckDecision(creationId, 'restart')
: onRetry(),
// Nothing was created, so leaving a billing refusal hands the typed prompt back.
onDismiss:
isBillingFailure(failure) && typedComposerPrompt(entry).trim()
? () => onReturnToComposer({ local: false })
: onDismiss,
onSeePlans: () => {
// Once paid, the plans dialog closes and retries this create.
requestOrcaCloudAfterCheckout({ kind: 'retry', creationId })
openPlansPage('sandbox')
},
onCreateLocally: () => onReturnToComposer({ local: true }),
onOpenBilling: () => {
const store = useAppStore.getState()
store.openSettingsTarget({
pane: 'cloud-billing',
repoId: null,
// "Turn on overage" / "Raise spend cap" land on the overage card itself; the
// payment notice is at the top of the section already.
...(failure?.kind === 'payment'
? {}
: { sectionId: ORCA_BILLING_OVERAGE_SECTION_ID })
})
store.openSettingsPage()
},
onSignIn: signIn,
// Your workspaces on Home, where you can put one to sleep or delete it.
onShowWorkspaces: () => openCloudWorkspacesHome({ running: true }),
onContactSupport: () => openAppHttpLink(SUPPORT_URL),
onConnectGitHub: connectGitHub,
onPushToGitHub: () => openAppHttpLink(PUSH_TO_GITHUB_URL)
}}
/>
</div>
)}
{building ? <OrcaCloudQueuedPrompt creationId={creationId} /> : null}
{cloud && !gated ? (
{cloud && !gated && !billingBlock ? (
<Button
type="button"
variant="ghost"
@@ -1,5 +1,6 @@
import { defineFixture } from '../../component-fixtures/component-fixture'
import { recordBillingStatus } from '../billing/billing-summary-store'
import { sampleTeam } from '../billing/plan-billing-fixtures'
import {
CLOUD_FAILED_LOG,
CLOUD_LOG,
@@ -15,8 +16,17 @@ import {
// Orca Cloud refusals and failures, one card each.
function stubBillingRole(canManageBilling: boolean, plan: Record<string, unknown> = {}): void {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the card reads only the role and the running caps.
const result = { status: 'ok', entitlement: { canManageBilling, offers: null, ...plan } } as never
// A team with overage on at a $25 cap (so the spend-cap blocker suggests $50); no plan numbers
// unless the fixture gives them (ENTITLEMENTS-C).
const entitlement = {
...sampleTeam,
canManageBilling,
offers: null,
overage: { ...sampleTeam.overage, optedIn: true, spendCapCents: 2500 },
...plan
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture plans override only entitlement fields the sheet reads.
const result = { status: 'ok', entitlement } as never
window.api.orcaProfiles.billingStatus = () => Promise.resolve(result)
// The caps come from the last billing read the app made.
recordBillingStatus(result)
@@ -209,14 +219,17 @@ export const cloudPaymentDue = cloudFailure(
export const cloudNetwork = cloudFailure(undefined, 'fetch failed', CLOUD_LOG)
// An owner without a plan gets See plans and Try again; More holds "Create on this computer
// instead", which every billing card offers.
export const cloudPlanRequiredMore = defineFixture({
...cloudPlanRequired,
// JA-21: an owner fixing payment in the browser; the card waits with Check again.
export const cloudPaymentFinishInBrowser = defineFixture({
...cloudPaymentDue,
setup: () => {
cloudPaymentDue.setup?.()
window.api.orcaProfiles.billingOpenPortal = () => Promise.resolve({ status: 'opened' })
},
interact: async (frameElement) => {
Array.from(frameElement.querySelectorAll('button'))
.find((button) => button.textContent?.trim() === 'More')
?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }))
await new Promise((resolve) => setTimeout(resolve, 300))
.find((button) => button.textContent?.trim() === 'Update payment method')
?.click()
await new Promise((resolve) => setTimeout(resolve, 200))
}
})
+30
View File
@@ -28589,5 +28589,35 @@
"overLimit": "The mirror is limited to {{size}}. Larger files and anything past the limit aren’t copied.",
"tooLarge": "Files over {{size}} aren’t copied.",
"removal": "The copy on this computer is removed too."
},
"worktreeCreation": {
"billingBlock": {
"plan": {
"title": "Choose a plan",
"body": "Your team needs a plan to start cloud workspaces.",
"ask": "Ask an owner or admin to choose a plan."
},
"hours": {
"title": "Out of sandbox hours",
"body": "Your team has used all of this month’s sandbox hours.",
"ask": "Ask an owner or admin to add hours."
},
"cap": {
"title": "Spend cap reached",
"body": "Overage is on, and this month’s spend cap is used.",
"ask": "Ask an owner or admin to raise the spend cap."
},
"payment": {
"title": "Payment failed",
"body": "New sandboxes can’t start.",
"ask": "Ask an owner or admin to update the payment method."
},
"browserStill": "Not updated yet. Finish in your browser, then check again.",
"browser": "Finish in your browser.",
"checkAgain": "Check again",
"raiseCapAndContinue": "Raise spend cap and continue",
"backToDraft": "Back to draft",
"saveFailed": "Couldn’t save that. Try again, or change it in Plan & billing."
}
}
}
@@ -1,68 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/components/billing/plans/plans-page-store', () => ({ openPlansPage: vi.fn() }))
import {
devBillingFaultAccess,
orcaCloudNeedsFixFirst,
orcaCloudWallNotice
} from './run-on-preflight'
afterEach(() => {
localStorage.removeItem('orca:dev:billingFault')
})
describe('orcaCloudWallNotice (JA-21b: Orca Cloud already selected at a billing wall)', () => {
it('gives an owner the reason and the one fix', () => {
const notice = orcaCloudWallNotice({
state: 'out-of-hours',
cause: 'hours',
canManageBilling: true
})
expect(notice?.reason).toBe('Out of sandbox hours')
expect(notice?.action?.label).toBe('Turn on overage')
expect(orcaCloudWallNotice({ state: 'payment-issue', canManageBilling: true })).toMatchObject({
reason: 'Payment failed',
action: { label: 'Update payment method' }
})
expect(
orcaCloudWallNotice({ state: 'no-plan', lapsed: true, canManageBilling: true })
).toMatchObject({ reason: 'Your Team plan ended', action: { label: 'Renew' } })
})
it('gives a member the reason and no action (they ask an owner or admin)', () => {
const notice = orcaCloudWallNotice({ state: 'payment-issue', canManageBilling: false })
expect(notice).toEqual({ reason: 'Payment failed', action: null })
})
it('has no wall for a usable account or a trial not started yet', () => {
expect(orcaCloudWallNotice({ state: 'entitled', remainingSeconds: 3600 })).toBeNull()
expect(orcaCloudWallNotice({ state: 'loading' })).toBeNull()
expect(
orcaCloudWallNotice({ state: 'no-plan', lapsed: false, canManageBilling: true })
).toBeNull()
})
})
describe('orcaCloudNeedsFixFirst', () => {
it('only an owner or admin at a wall must fix first; a trial offer is setup', () => {
expect(orcaCloudNeedsFixFirst({ state: 'payment-issue', canManageBilling: true })).toBe(true)
expect(orcaCloudNeedsFixFirst({ state: 'payment-issue', canManageBilling: false })).toBe(false)
expect(
orcaCloudNeedsFixFirst({ state: 'no-plan', lapsed: false, canManageBilling: true })
).toBe(false)
})
})
describe('devBillingFaultAccess (dev/QA shots)', () => {
it('simulates each wall from localStorage, and nothing when unset', () => {
expect(devBillingFaultAccess()).toBeNull()
localStorage.setItem('orca:dev:billingFault', 'out-of-hours')
expect(devBillingFaultAccess()).toMatchObject({ state: 'out-of-hours', canManageBilling: true })
localStorage.setItem('orca:dev:billingFault', 'lapsed')
expect(devBillingFaultAccess()).toMatchObject({ state: 'no-plan', lapsed: true })
localStorage.setItem('orca:dev:billingFault', 'nonsense')
expect(devBillingFaultAccess()).toBeNull()
})
})
@@ -1,120 +0,0 @@
// JA-21, behind a flag Neil can veto (off unless the account's capabilities turn it on): the
// composer's Run on preflight. An owner or admin whose team can't start a sandbox right now (out of
// hours, payment failed, plan ended) sees Orca Cloud disabled in place, with the reason and the one
// fix, instead of picking it and hitting the wall after Start. Members already get "Ask an owner or
// admin". A plan not started yet (trial offer) is setup, not a wall, so it stays pickable.
import { useAppStore } from '@/store'
import { translate } from '@/i18n/i18n'
import {
getOrcaCloudPick,
type OrcaCloudRunTargetAccess
} from '@/components/new-workspace/orca-cloud-run-target-access'
export const RUN_ON_PREFLIGHT_CAPABILITY = 'runOnPreflight'
/** Dev/QA override for the harnesses: localStorage['orca:dev:runOnPreflight'] = '1'. */
const DEV_OVERRIDE_KEY = 'orca:dev:runOnPreflight'
function devOverride(): boolean {
try {
return globalThis.localStorage?.getItem(DEV_OVERRIDE_KEY) === '1'
} catch {
return false
}
}
export function useRunOnPreflightEnabled(): boolean {
const capability = useAppStore((state) => {
const status = state.orcaProfileAuthStatus
return status?.state === 'connected'
? status.capabilities?.flags[RUN_ON_PREFLIGHT_CAPABILITY] === true
: false
})
return capability || devOverride()
}
/** An owner or admin must fix billing before a sandbox can start: the row offers that fix. */
export function orcaCloudNeedsFixFirst(access: OrcaCloudRunTargetAccess): boolean {
switch (access.state) {
case 'out-of-hours':
case 'payment-issue':
return access.canManageBilling
case 'no-plan':
return access.canManageBilling && access.lapsed
case 'loading':
case 'unknown':
case 'entitled':
case 'signed-out':
return false
}
}
export type OrcaCloudWallNotice = {
/** "Out of sandbox hours", "Payment failed", "Your Team plan ended", … */
reason: string
/** The one fix, for owners and admins; members are told who can fix it instead. */
action: { label: string; run: () => void } | null
}
const ROW_COPY = 'auto.components.new.workspace.RunTargetCombobox'
/**
* JA-21b: Orca Cloud is already the selected target (a remembered default) and a billing wall
* applies. The composer keeps the selection, says why under Run on, and holds Create until fixed.
*/
export function orcaCloudWallNotice(access: OrcaCloudRunTargetAccess): OrcaCloudWallNotice | null {
let reason: string
let actionLabel: string
switch (access.state) {
case 'out-of-hours':
reason =
access.cause === 'cap'
? translate(`${ROW_COPY}.orcaCloudCapReached`, 'Spend cap reached')
: translate(`${ROW_COPY}.orcaCloudOutOfHours`, 'Out of sandbox hours')
actionLabel =
access.cause === 'cap'
? translate(`${ROW_COPY}.orcaCloudRaiseSpendCap`, 'Raise spend cap')
: translate(`${ROW_COPY}.orcaCloudTurnOnOverage`, 'Turn on overage')
break
case 'payment-issue':
reason = translate(`${ROW_COPY}.orcaCloudPaymentFailed`, 'Payment failed')
actionLabel = translate(`${ROW_COPY}.orcaCloudUpdatePaymentMethod`, 'Update payment method')
break
case 'no-plan':
if (!access.lapsed) {
return null
}
reason = translate(`${ROW_COPY}.orcaCloudPlanEnded`, 'Your Team plan ended')
actionLabel = translate(`${ROW_COPY}.orcaCloudRenew`, 'Renew')
break
case 'loading':
case 'unknown':
case 'entitled':
case 'signed-out':
return null
}
const pick = getOrcaCloudPick(access)
return {
reason,
action: pick.kind === 'act' ? { label: actionLabel, run: pick.run } : null
}
}
/** Dev/QA only: localStorage['orca:dev:billingFault'] = 'out-of-hours' | 'payment-issue' | 'lapsed'. */
export function devBillingFaultAccess(): OrcaCloudRunTargetAccess | null {
if (!import.meta.env.DEV) {
return null
}
let fault: string | null = null
try {
fault = globalThis.localStorage?.getItem('orca:dev:billingFault') ?? null
} catch {
return null
}
return (fault && DEV_BILLING_FAULTS.get(fault)) || null
}
const DEV_BILLING_FAULTS = new Map<string, OrcaCloudRunTargetAccess>([
['out-of-hours', { state: 'out-of-hours', cause: 'hours', canManageBilling: true }],
['payment-issue', { state: 'payment-issue', canManageBilling: true }],
['lapsed', { state: 'no-plan', lapsed: true, canManageBilling: true }]
])