wip(team): W10 round-1 fixes, return page, docs

This commit is contained in:
Neil
2026-11-09 06:55:55 -08:00
parent 90adbc6601
commit dde40cbdeb
46 changed files with 1724 additions and 810 deletions
+3 -7
View File
@@ -31,6 +31,7 @@ import { OverageRequestSchema, updateOverage } from './overage'
import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe'
import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage'
import { handleStripeWebhook } from './webhook'
import { renderReturnPage, returnOutcome } from './return-page'
const MAX_JSON_BYTES = 16 * 1024
@@ -68,13 +69,8 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
try {
switch (route) {
case 'GET /return':
// Where Checkout and the Portal send the browser back. Static; reveals nothing.
return new Response(
'<!doctype html><meta charset="utf-8"><title>Orca</title>' +
'<body style="font:15px system-ui;margin:4rem auto;max-width:28rem;text-align:center">' +
'<p>You can close this tab and return to Orca.</p></body>',
{ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } }
)
// Where Checkout and the Portal send the browser back; hands off to the desktop app.
return renderReturnPage(returnOutcome(url))
case 'POST /v1/stripe/webhook':
return await handleStripeWebhook(env, stripe, request, now)
+87
View File
@@ -0,0 +1,87 @@
// Where Stripe Checkout and the Customer Portal send the browser back. It hands the user back to
// the desktop app through an orca:// link (opened at once, plus a button if the browser asks first).
// Static per outcome: query values only pick one of three fixed pages, nothing is reflected.
type Outcome = 'checkout-success' | 'checkout-cancel' | 'portal'
const COPY: Record<Outcome, { title: string; body: string; link: string }> = {
'checkout-success': {
title: 'Payment complete',
body: 'Your team is on Orca Cloud. Head back to Orca to invite people and start a cloud workspace.',
link: 'orca://billing/return?checkout=success'
},
'checkout-cancel': {
title: 'Checkout canceled',
body: 'Nothing was charged. You can pick a plan again from Orca any time.',
link: 'orca://billing/return?checkout=cancel'
},
portal: {
title: 'Billing updated',
body: 'Your changes are saved. Orca picks them up when you switch back.',
link: 'orca://billing/return?portal=return'
}
}
export function returnOutcome(url: URL): Outcome {
if (url.searchParams.get('checkout') === 'success') {
return 'checkout-success'
}
if (url.searchParams.get('checkout') === 'cancel') {
return 'checkout-cancel'
}
return 'portal'
}
const CHECK =
'<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>'
export function renderReturnPage(outcome: Outcome): Response {
const copy = COPY[outcome]
const success = outcome === 'checkout-success'
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<meta http-equiv="refresh" content="0;url=${copy.link}">
<title>${copy.title} · Orca</title>
<style>
:root { --bg:#fafafa; --card:#fff; --fg:#0a0a0a; --muted:#6b6b6b; --border:#e5e5e5; --ok:#15803d; --okbg:#ecfdf3; }
@media (prefers-color-scheme: dark) { :root { --bg:#0b0b0b; --card:#161616; --fg:#f5f5f5; --muted:#a3a3a3; --border:#2a2a2a; --ok:#4ade80; --okbg:#0f2a1a; } }
* { box-sizing: border-box; }
body { margin:0; min-height:100vh; display:grid; place-items:center; background:var(--bg); color:var(--fg);
font: 15px/1.5 ui-sans-serif, -apple-system, "Segoe UI", system-ui, sans-serif; -webkit-font-smoothing: antialiased; }
main { width:min(26rem, calc(100vw - 2rem)); background:var(--card); border:1px solid var(--border); border-radius:16px;
padding:2rem; text-align:center; box-shadow: 0 20px 60px rgba(0,0,0,.08); }
.mark { width:44px; height:44px; margin:0 auto 1rem; border-radius:999px; display:grid; place-items:center;
background:${success ? 'var(--okbg)' : 'transparent'}; color:var(--ok); border:1px solid ${success ? 'transparent' : 'var(--border)'}; }
h1 { font-size:1.25rem; letter-spacing:-.01em; margin:0 0 .5rem; }
p { margin:0 0 1.5rem; color:var(--muted); }
a.button { display:inline-block; padding:.6rem 1.1rem; border-radius:8px; background:var(--fg); color:var(--bg);
text-decoration:none; font-weight:500; }
a.button:focus-visible { outline:3px solid color-mix(in oklab, var(--fg) 40%, transparent); outline-offset:2px; }
small { display:block; margin-top:1rem; color:var(--muted); font-size:.8rem; }
</style>
</head>
<body>
<main>
<div class="mark">${success ? CHECK : ''}</div>
<h1>${copy.title}</h1>
<p>${copy.body}</p>
<a class="button" href="${copy.link}">Open Orca</a>
<small>You can close this tab.</small>
</main>
</body>
</html>`
return new Response(html, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-store',
// No scripts, no external loads; only inline styles.
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
'referrer-policy': 'no-referrer',
'x-content-type-options': 'nosniff'
}
})
}
+11 -1
View File
@@ -41,6 +41,16 @@ describe('dev operator keys', () => {
passThroughOnException() {}
} as unknown as ExecutionContext)
expect(response.status).toBe(200)
expect(await response.text()).toContain('return to Orca')
const html = await response.text()
expect(html).toContain('Payment complete')
expect(html).toContain('orca://billing/return?checkout=success')
expect(response.headers.get('content-security-policy')).toContain("default-src 'none'")
const cancel = await handleRequest(new Request('https://billing.test/return?checkout=cancel&x=<script>'), h.env, {
waitUntil() {},
passThroughOnException() {}
} as unknown as ExecutionContext)
const cancelHtml = await cancel.text()
expect(cancelHtml).toContain('Nothing was charged')
expect(cancelHtml).not.toContain('<script>')
})
})
+42
View File
@@ -79,6 +79,41 @@ everyone not suspended at renewal and prorates later additions.
(pull-only in production for now, stablyai/orca-cloud#691). Missing or malformed counts are
rejected, and seats are never below 1.
## Desktop: Team page, upgrade moments, checkout (decision)
**Checkout = Stripe hosted Checkout in the system browser, followed in-app.** Options weighed:
- *Embedded Checkout in an Electron window*: looks in-app, but there is no URL bar to verify (it trains users to type
cards into chrome-less windows), Apple Pay does not work in Electron/Chromium, password-manager and browser card
autofill are missing, and it needs Stripe.js under a relaxed CSP plus a hosted page anyway.
- *Stripe Elements*: same Electron limits, plus we own the PaymentIntent/subscription confirmation and 3DS edge cases.
- *Hosted Checkout in the browser* (chosen): PCI SAQ A (no card data near Orca), Apple Pay/Link/autofill, 3-D Secure
handled by Stripe, a verifiable `checkout.stripe.com` URL, no CSP change in the app.
The in-app half: "Continue to checkout" turns the plans dialog into a checkout panel (order summary, "Finish payment in
your browser", Reopen/Cancel). It polls the entitlement every 2 s for 3 min (then "Keep waiting"), and the Worker's
`/return` page opens `orca://billing/return?checkout=success|cancel` (also `?portal=return`) so Orca comes to the front
and reacts at once. Paid → a short check → the Team page with a one-time "You're on Team" card (Create a cloud
workspace / Invite teammates). Canceled → "Nothing was charged". `incomplete`/`past_due` first invoice → "Your payment
needs one more step". The return page is static per outcome, no scripts, strict CSP.
**Team page** (account menu → Team; Settings → Orca account links to it): team mark and name, plan + seats card (seats
paid / in use, interval, next invoice estimate = renewal seats × price, before tax), or "Upgrade to use Orca Cloud" when
there is no plan; multi-email invite (paste lists, `Name <email>` lines; invalid entries stay as red chips) with seat
impact copy computed client-side from the peak-seat rules ("When alex accepts, they add a seat: $23.96 prorated that
day, then $50/month", or "Covered: uses a seat you already paid for"); members and invites in one list with status
(Active / Pending sign-in / Invited), inline role select, row menu (Make owner…, Remove…, Resend/Revoke invite, Leave
team…). Changes are optimistic per row with rollback + the reason on the row, and toasts with Undo (role, revoke).
Members see a read-only view. Personal accounts get "Create a team" and a list of teams to switch to.
Ownership transfer is auth's two-step model: an owner makes someone an owner, then that person changes the old
owner's role (auth refuses self role changes and the last owner leaving).
**Auth routes the desktop calls that auth does not have yet** (desktop maps a route 404 to "not available yet"):
`POST /v1/desktop/orgs {name}` → `{orgId, name}` (creator becomes owner) and `POST /v1/desktop/orgs/:orgId/members/leave`
(400 `last_owner` for the last owner). Resend invite = revoke + invite.
**Upgrade entry points:** account menu "Upgrade to Orca Cloud" (only once billing reports no plan, never while
loading), the Run-on picker's Orca Cloud row ("Upgrade" pill → plans page; members are told to ask an admin), and the
Team page card. All open the plans page.
## Payment failure
- On `invoice.payment_failed` (status `past_due`, later `unpaid` when retries are exhausted) billing records
@@ -167,6 +202,13 @@ never followed with the key; JWT max age 15 min.
when `BILLING_ENV=prod`).
- Same e2e run against dev: 18/18 passed (grace expiry is exercised locally; dev keeps the 96 h grace).
**Shared dev signing key.** `BILLING_DEV_JWKS` on orca-billing-dev holds two public keys: `e2e` (the original e2e
key) and `dev1` (`/tmp/vdrv/secrets/dev-jwk.json`, the key the dev sandbox control plane also trusts). Tokens use
issuer `orca-billing-dev-test`, `aud=orca-billing`, `purpose=billing`; sandbox tokens use the same key with issuer
`orca-sandbox-dev-test`, `aud=orca-sandbox`. Unpackaged desktop builds with `ORCA_BILLING_DEV_KEY_FILE=<dev-jwk.json>`
self-sign billing tokens (sub = profile user, org/orgRole from the active org's live roster); packaged builds never
read the file.
## What the user sets
| Where | Name | Value |
+4 -1
View File
@@ -38,7 +38,10 @@ type Ready =
/** Dev builds with ORCA_BILLING_DEV_KEY_FILE self-sign instead of asking auth (see billing-dev-token). */
function prepareDev(userDataPath: string, keyFile: string): Ready {
const billingApiUrl = cleanCloudServiceUrl(process.env.ORCA_BILLING_API_URL, true)
const billingApiUrl = cleanCloudServiceUrl(
withCloudBuildDefaults(process.env).ORCA_BILLING_API_URL,
true
)
if (!billingApiUrl) {
return { ok: false, status: 'unconfigured' }
}
+2
View File
@@ -6,6 +6,7 @@ import { ConfirmationDialogProvider } from './components/confirmation-dialog'
import { BrowserWebAuthnAccountDialog } from './components/browser-webauthn-account-dialog'
import { BrowserExtensionInstallDialog } from './components/browser-extension-install-dialog'
import { PlansDialogHost } from './components/billing/plans/PlansDialogHost'
import { TeamDialogHost } from './components/billing/team/TeamDialogHost'
import { BrowserPagePrompts } from './components/browser-pane/browser-page-prompts'
import { LinkRoutingPreferenceDialogProvider } from './components/link-routing-preference-dialog'
import { SkillFreshnessNudge } from './components/skills/SkillFreshnessNudge'
@@ -119,6 +120,7 @@ function App(): React.JSX.Element {
<BrowserWebAuthnAccountDialog />
<BrowserExtensionInstallDialog />
<PlansDialogHost />
<TeamDialogHost />
</LinkRoutingPreferenceDialogProvider>
</ConfirmationDialogProvider>
{createPortal(
@@ -40,7 +40,10 @@ export function PaymentIssueNotice({
<div className="min-w-0 flex-1 space-y-2">
<p className="text-sm font-medium">
{payment.suspendRunning
? t('auto.components.billing.paymentSuspended', 'Sandboxes suspended: payment overdue')
? t(
'auto.components.billing.paymentFailedSuspended',
'Payment failed · sandboxes suspended'
)
: t('auto.components.billing.paymentFailed', 'Payment failed')}
</p>
<p className="text-xs text-muted-foreground">
@@ -59,14 +62,21 @@ export function PaymentIssueNotice({
<Button
type="button"
size="sm"
variant="outline"
disabled={busy}
onClick={onUpdatePayment}
data-plans-primary=""
>
{t('auto.components.billing.updatePayment', 'Update payment method')}
<ExternalLink />
</Button>
) : null}
) : (
<p className="text-xs font-medium">
{t(
'auto.components.billing.paymentAskAdmin',
'Ask an owner or admin to update the payment method.'
)}
</p>
)}
</div>
</div>
)
@@ -1,6 +1,5 @@
import { useState } from 'react'
import { CreditCard, ExternalLink, RefreshCw, Sparkles } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { CreditCard, ExternalLink, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { formatCents } from './plans/plans-pricing'
@@ -14,13 +13,8 @@ import type {
import { openPlansPage } from './plans/plans-page-store'
import { PaymentIssueNotice } from './PaymentIssueNotice'
import { OverageControls, UsageSummary } from './PlanBillingUsage'
import {
denyReasonCopy,
openFailureCopy,
overageFailureCopy,
statusLabel
} from './plan-billing-copy'
import { planBillingTone } from './plan-billing-format'
import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy'
import { PlanStatusBadge } from './PlanStatusBadge'
import { useOrcaBillingStatus } from './use-orca-billing-status'
export function PlanBillingSection(): React.JSX.Element | null {
@@ -137,10 +131,9 @@ export function PlanBillingView({
}
const entitlement = result.entitlement
const tone = planBillingTone(entitlement)
const hasPlan = entitlement.plan !== null && entitlement.status !== 'canceled'
const annualCents = entitlement.offers?.team.annualPriceCentsPerSeat ?? null
const teamFrom = annualCents === null ? null : formatCents(Math.round(annualCents / 12), locale)
const monthlyCents = entitlement.offers?.team.monthlyPriceCentsPerSeat ?? null
const teamPrice = monthlyCents === null ? null : formatCents(monthlyCents, locale)
return (
<div className="space-y-4 border-t border-border/60 pt-5">
@@ -159,48 +152,40 @@ export function PlanBillingView({
: t('auto.components.billing.monthly', 'Monthly')
})}
</span>
<Badge
variant={
tone === 'blocked' ? 'destructive' : tone === 'warning' ? 'secondary' : 'outline'
}
>
{statusLabel(entitlement.status, t)}
</Badge>
<PlanStatusBadge entitlement={entitlement} />
</div>
<UsageSummary entitlement={entitlement} />
<OverageControls
// Re-seed the cap field when the saved cap changes.
key={entitlement.overage.spendCapCents}
entitlement={entitlement}
busy={busy}
onSetOverage={onSetOverage}
/>
<OverageControls entitlement={entitlement} busy={busy} onSetOverage={onSetOverage} />
</div>
) : null}
<PaymentIssueNotice entitlement={entitlement} busy={busy} onUpdatePayment={onPortal} />
{entitlement.reason && entitlement.payment.pastDueSince === null ? (
<p className="text-xs text-muted-foreground">{denyReasonCopy(entitlement.reason, t)}</p>
<p className="text-xs text-muted-foreground">
{denyReasonCopy(entitlement.reason, t, entitlement.canManageBilling)}
</p>
) : null}
{!hasPlan && teamFrom ? (
<p className="text-xs text-muted-foreground">
{t(
'auto.components.billing.teamFrom',
'Team starts at {{value0}} per seat per month, billed annually.',
{
value0: teamFrom
}
)}
{!hasPlan ? (
<p className="text-sm text-pretty">
{teamPrice
? t(
'auto.components.billing.upsellLine',
'Orca Cloud runs agents in hosted sandboxes. Team is {{value0}} per seat / month.',
{ value0: teamPrice }
)
: t(
'auto.components.billing.upsellLineNoPrice',
'Orca Cloud runs agents in hosted sandboxes for your whole team.'
)}
</p>
) : null}
<div className="flex flex-wrap gap-2">
{hasPlan ? null : (
<Button type="button" size="sm" onClick={onSeePlans}>
<Sparkles />
{t('auto.components.billing.choosePlan', 'Choose a plan')}
{t('auto.components.billing.upgrade.cta', 'See plans')}
</Button>
)}
{hasPlan && entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? (
@@ -1,4 +1,5 @@
import { useState } from 'react'
import { useId, useState } from 'react'
import { Check } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Progress } from '@/components/ui/progress'
@@ -8,7 +9,8 @@ import type {
OrcaBillingEntitlement,
OrcaBillingOverageArgs
} from '../../../../shared/orca-billing'
import { formatDollars, formatHours, includedUsagePercent } from './plan-billing-format'
import { formatHours, includedUsagePercent } from './plan-billing-format'
import { formatCents } from './plans/plans-pricing'
export function UsageSummary({
entitlement
@@ -27,7 +29,7 @@ export function UsageSummary({
'auto.components.billing.hoursUsedMonth',
'{{value0}} of {{value1}} hours used this month',
{
value0: formatHours(entitlement.usedSeconds),
value0: formatHours(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)),
value1: formatHours(entitlement.includedSeconds)
}
)}
@@ -42,6 +44,19 @@ export function UsageSummary({
value={includedUsagePercent(entitlement)}
aria-label={t('auto.components.billing.usageLabel', 'Included hours used')}
/>
{entitlement.overageSeconds > 0 ? (
<p className="text-xs text-muted-foreground tabular-nums">
{t(
'auto.components.billing.overageHours',
'{{value0}} overage hours · {{value1}} of {{value2}} cap',
{
value0: formatHours(entitlement.overageSeconds),
value1: formatCents(entitlement.overage.spentCents, locale),
value2: formatCents(entitlement.overage.spendCapCents, locale)
}
)}
</p>
) : null}
{entitlement.usageWarningPercent !== null ? (
<p className="text-xs font-medium">
{entitlement.usageWarningPercent >= 100
@@ -87,11 +102,25 @@ export function OverageControls({
onSetOverage: (args: OrcaBillingOverageArgs) => void
}): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const capId = useId()
const { overage } = entitlement
const [capDollars, setCapDollars] = useState(String(Math.round(overage.spendCapCents / 100)))
const savedDollars = String(Math.round(overage.spendCapCents / 100))
const [capDollars, setCapDollars] = useState(savedDollars)
// Shows "Saved" after a successful cap change until the field is edited again (review M13).
const [savedFlash, setSavedFlash] = useState(false)
// Re-seed the field when the saved cap changes (render-time adjustment, no effect).
const [seededFrom, setSeededFrom] = useState(savedDollars)
if (seededFrom !== savedDollars) {
setSeededFrom(savedDollars)
setCapDollars(savedDollars)
}
const parsedCap = Number(capDollars)
const capValid = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0
const rate = formatDollars(overage.centsPerHour)
const changed = capValid && capDollars.trim() !== savedDollars
const largeWeight = entitlement.offers?.team.largeMachineWeight ?? 2
const suspended = entitlement.payment.suspendRunning || entitlement.payment.pastDueSince !== null
const canEdit = entitlement.canManageBilling && !suspended
return (
<div className="space-y-3 rounded-md border border-border/60 p-3">
<div className="flex items-start justify-between gap-3">
@@ -103,53 +132,78 @@ export function OverageControls({
{t(
'auto.components.billing.overageDescription',
'Keep starting sandboxes after included hours at {{value0}}/hr Standard ({{value1}}/hr Large).',
{ value0: rate, value1: formatDollars(overage.centsPerHour * 2) }
{
value0: formatCents(overage.centsPerHour, locale),
value1: formatCents(Math.round(overage.centsPerHour * largeWeight), locale)
}
)}
</p>
</div>
<Switch
checked={overage.optedIn}
disabled={busy || !entitlement.canManageBilling}
disabled={busy || !canEdit}
onCheckedChange={(enabled) => onSetOverage({ enabled })}
aria-label={t('auto.components.billing.overageToggle', 'Allow overage')}
/>
</div>
{overage.optedIn ? (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
<p className="text-xs text-muted-foreground tabular-nums">
{t(
'auto.components.billing.overageSpent',
'{{value0}} of {{value1}} monthly cap spent',
{
value0: formatDollars(overage.spentCents),
value1: formatDollars(overage.spendCapCents)
value0: formatCents(overage.spentCents, locale),
value1: formatCents(overage.spendCapCents, locale)
}
)}
</p>
{entitlement.canManageBilling ? (
{canEdit ? (
<form
className="flex items-center gap-2"
className="flex flex-wrap items-center gap-2"
onSubmit={(event) => {
event.preventDefault()
if (capValid) {
if (changed) {
onSetOverage({ enabled: true, spendCapCents: parsedCap * 100 })
setSavedFlash(true)
}
}}
>
<span className="text-xs text-muted-foreground">
{t('auto.components.billing.capLabel', 'Monthly cap ($)')}
</span>
<div className="w-24">
<label htmlFor={capId} className="text-xs font-medium">
{t('auto.components.billing.capLabel2', 'Monthly spend cap')}
</label>
<div className="relative w-28">
<span
aria-hidden
className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-sm text-muted-foreground"
>
$
</span>
<Input
id={capId}
inputMode="numeric"
className="pl-6 tabular-nums"
value={capDollars}
onChange={(event) => setCapDollars(event.target.value)}
aria-label={t('auto.components.billing.capLabel', 'Monthly cap ($)')}
aria-invalid={!capValid || undefined}
onChange={(event) => {
setCapDollars(event.target.value)
setSavedFlash(false)
}}
/>
</div>
<Button type="submit" size="sm" variant="outline" disabled={busy || !capValid}>
{t('auto.components.billing.saveCap', 'Save')}
</Button>
{changed ? (
<Button type="submit" size="sm" variant="outline" disabled={busy}>
{t('auto.components.billing.saveCap', 'Save')}
</Button>
) : savedFlash && !busy ? (
<span
role="status"
className="flex items-center gap-1 text-xs text-muted-foreground"
>
<Check className="size-3.5" />
{t('auto.components.billing.capSaved', 'Saved')}
</span>
) : null}
</form>
) : null}
</div>
@@ -12,13 +12,16 @@ export function planHealth(entitlement: OrcaBillingEntitlement, t: Translate): P
return { label: t('auto.components.billing.health.suspended', 'Suspended'), dot: 'destructive' }
}
if (entitlement.payment.pastDueSince !== null || entitlement.status === 'past_due') {
return { label: t('auto.components.billing.statusPastDue', 'Payment due'), dot: 'destructive' }
return {
label: t('auto.components.billing.paymentFailed', 'Payment failed'),
dot: 'destructive'
}
}
if (entitlement.reason === 'overage_cap_reached') {
return { label: t('auto.components.billing.health.capReached', 'Cap reached'), dot: 'warning' }
}
if (entitlement.reason === 'included_hours_exhausted') {
return { label: t('auto.components.billing.health.hoursUsed', 'Hours used up'), dot: 'warning' }
return { label: t('auto.components.billing.health.outOfHours', 'Out of hours'), dot: 'warning' }
}
if (entitlement.cancelAtPeriodEnd) {
return { label: t('auto.components.billing.health.ending', 'Ending'), dot: 'warning' }
@@ -37,13 +40,13 @@ export function PlanStatusBadge({
const t = useTranslate()
const health = planHealth(entitlement, t)
return (
<Badge variant="outline" className={cn('gap-1.5', className)}>
<Badge variant="outline" className={className}>
{health.dot ? (
<span
aria-hidden
className={cn(
'size-1.5 rounded-full',
health.dot === 'destructive' ? 'bg-destructive' : 'bg-amber-500'
health.dot === 'destructive' ? 'bg-destructive' : 'bg-status-warning'
)}
/>
) : null}
@@ -0,0 +1,67 @@
// What the always-visible upgrade entry points need to know: does this account have a plan?
// Read when the account (or org) changes and refreshed by any billing view that loads status.
import { useSyncExternalStore } from 'react'
import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing'
import { isActivePlan } from './team/team-seat-math'
export type BillingSummary = {
/** null until the first read answers (or when billing is off for this build/account). */
subscribed: boolean | null
canManageBilling: boolean
}
let summary: BillingSummary = { subscribed: null, canManageBilling: false }
const listeners = new Set<() => void>()
let lastReadAt = 0
let inFlight: Promise<void> | null = null
const MIN_REFRESH_MS = 60_000
export function recordBillingStatus(result: OrcaBillingStatusResult): void {
const next: BillingSummary =
result.status === 'ok'
? {
subscribed: isActivePlan(result.entitlement),
canManageBilling: result.entitlement.canManageBilling
}
: result.status === 'failed'
? summary
: { subscribed: null, canManageBilling: false }
if (
next.subscribed !== summary.subscribed ||
next.canManageBilling !== summary.canManageBilling
) {
summary = next
for (const listener of listeners) {
listener()
}
}
}
/** Re-reads billing status at most once a minute unless `force` (account or org switched). */
export function refreshBillingSummary(force = false): Promise<void> {
if (inFlight || (!force && Date.now() - lastReadAt < MIN_REFRESH_MS)) {
return inFlight ?? Promise.resolve()
}
lastReadAt = Date.now()
inFlight = window.api.orcaProfiles
.billingStatus()
.then(recordBillingStatus)
.catch(() => undefined)
.finally(() => {
inFlight = null
})
return inFlight
}
export function getBillingSummary(): BillingSummary {
return summary
}
export function subscribeBillingSummary(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
export function useBillingSummary(): BillingSummary {
return useSyncExternalStore(subscribeBillingSummary, getBillingSummary)
}
@@ -0,0 +1,73 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import { Dialog } from '@/components/ui/dialog'
import { sampleOffers, sampleTeam } from '../plan-billing-fixtures'
import { PlansDialogContent } from '../plans/PlansDialogContent'
import { CheckoutPanel, type CheckoutPanelProps } from './CheckoutPanel'
const NOW = Date.UTC(2026, 10, 18, 15)
const order = { interval: 'month' as const, seats: 3 }
const width = 1280
function Page({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JSX.Element {
return (
<Dialog open modal={false}>
<PlansDialogContent
result={{ status: 'ok', entitlement: sampleTeam }}
busy={false}
notice={null}
seats={3}
onCheckout={() => {}}
onManage={() => {}}
onContactSales={() => {}}
onRetry={() => {}}
checkout={
<CheckoutPanel
phase={phase}
team={sampleOffers.team}
now={NOW}
onReopen={() => {}}
onKeepWaiting={() => {}}
onBack={() => {}}
/>
}
/>
</Dialog>
)
}
export const opening = defineFixture({
width,
render: () => <Page phase={{ kind: 'opening', order }} />
})
export const awaitingPayment = defineFixture({
width,
render: () => <Page phase={{ kind: 'awaiting-payment', order, since: NOW }} />
})
export const paid = defineFixture({
width,
render: () => <Page phase={{ kind: 'paid', order, seats: 3 }} />
})
export const canceled = defineFixture({
width,
render: () => <Page phase={{ kind: 'canceled', order }} />
})
export const needsAttention = defineFixture({
width,
render: () => <Page phase={{ kind: 'needs-attention', order }} />
})
export const timedOut = defineFixture({
width,
render: () => <Page phase={{ kind: 'timed-out', order }} />
})
export const openFailed = defineFixture({
width,
render: () => (
<Page phase={{ kind: 'open-failed', order, result: { status: 'failed', error: 'timeout' } }} />
)
})
export const annual = defineFixture({
width,
render: () => (
<Page phase={{ kind: 'awaiting-payment', order: { interval: 'year', seats: 5 }, since: NOW }} />
)
})
@@ -82,7 +82,7 @@ function StatusIcon({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JS
return (
<span
aria-hidden
className="flex size-11 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-600 animate-in zoom-in-50 fade-in-0 duration-300 motion-reduce:animate-none dark:text-emerald-400"
className="flex size-11 items-center justify-center rounded-full border border-status-success-border bg-status-success-background text-status-success animate-in zoom-in-50 fade-in-0 duration-300 motion-reduce:animate-none"
>
<Check className="size-6" strokeWidth={2.5} />
</span>
@@ -102,7 +102,7 @@ function StatusIcon({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JS
return (
<span
aria-hidden
className="flex size-11 items-center justify-center rounded-full bg-amber-500/15 text-amber-600 dark:text-amber-400"
className="flex size-11 items-center justify-center rounded-full border border-status-warning-border bg-status-warning-background text-status-warning-text"
>
<AlertCircle className="size-5" />
</span>
@@ -6,7 +6,11 @@ import type {
OrcaBillingOverageResult
} from '../../../../shared/orca-billing'
export function denyReasonCopy(reason: OrcaBillingDenyReason, t: Translate): string {
export function denyReasonCopy(
reason: OrcaBillingDenyReason,
t: Translate,
canManage = true
): string {
switch (reason) {
case 'no_subscription':
return t('auto.components.billing.reasonNoPlan', 'Hosted sandboxes need a paid plan.')
@@ -31,10 +35,15 @@ export function denyReasonCopy(reason: OrcaBillingDenyReason, t: Translate): str
'You have used all included hours this month. Turn on overage to keep starting sandboxes.'
)
case 'overage_cap_reached':
return t(
'auto.components.billing.reasonCapRaise',
'You reached this month’s overage spend cap. An admin can raise it.'
)
return canManage
? t(
'auto.components.billing.reasonCapAdmin',
'This month’s overage cap is spent. Raise the cap to keep starting sandboxes.'
)
: t(
'auto.components.billing.reasonCapMember',
'This month’s overage cap is spent. Ask an owner or admin to raise it.'
)
}
}
@@ -45,7 +54,7 @@ export function statusLabel(status: string, t: Translate): string {
case 'trialing':
return t('auto.components.billing.statusTrial', 'Trial')
case 'past_due':
return t('auto.components.billing.statusPastDue', 'Payment due')
return t('auto.components.billing.paymentFailed', 'Payment failed')
case 'canceled':
return t('auto.components.billing.statusCanceled', 'Canceled')
default:
@@ -1,20 +1,29 @@
import type { ReactNode } from 'react'
import { DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useTranslate } from '@/i18n/use-translate'
import { PlansView, isSubscribed, type PlansViewProps } from './PlansView'
/** The plans page surface: heading plus plans. Rendered inside a <Dialog>. */
export function PlansDialogContent(props: PlansViewProps): React.JSX.Element {
/**
* The plans page surface: heading plus plans, or the checkout panel while Checkout runs.
* Top-anchored so loading, plans and checkout never make the dialog jump (review M4).
*/
export function PlansDialogContent(
props: PlansViewProps & { checkout?: ReactNode }
): React.JSX.Element {
const t = useTranslate()
const subscribed = isSubscribed(props.result)
const { checkout, ...viewProps } = props
return (
<DialogContent
scrollable
className="sm:max-w-4xl"
// Focus the dialog itself so no button looks pre-selected; Tab reaches the actions.
className="top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-4xl [@media(max-height:800px)]:top-4 [@media(max-height:800px)]:max-h-[calc(100vh-2rem)] [@media(max-height:800px)]:gap-3 [@media(max-height:800px)]:p-5"
onOpenAutoFocus={(event) => {
// Land on the primary action for this state when it is already rendered (review P1-13);
// otherwise on the dialog itself so nothing looks pre-selected.
event.preventDefault()
if (event.currentTarget instanceof HTMLElement) {
event.currentTarget.focus()
const primary = event.currentTarget.querySelector<HTMLElement>('[data-plans-primary]')
;(primary ?? event.currentTarget).focus()
}
}}
>
@@ -23,23 +32,30 @@ export function PlansDialogContent(props: PlansViewProps): React.JSX.Element {
{t('auto.components.billing.plans.eyebrow', 'Orca Cloud')}
</p>
<DialogTitle size="display">
{subscribed
? t('auto.components.billing.plans.titleSubscribed', 'Your Orca Cloud plan')
: t('auto.components.billing.plans.title', 'Cloud sandboxes for your whole team')}
{checkout
? t('auto.components.billing.checkout.title', 'Checkout')
: subscribed
? t('auto.components.billing.plans.titleSubscribed', 'Your Orca Cloud plan')
: t('auto.components.billing.plans.title', 'Cloud sandboxes for your whole team')}
</DialogTitle>
<DialogDescription className="max-w-xl">
{subscribed
<DialogDescription className={subscribed && !checkout ? 'sr-only' : 'max-w-xl'}>
{checkout
? t(
'auto.components.billing.plans.subtitleSubscribed',
'Usage this month, your plan, and what Enterprise adds.'
'auto.components.billing.checkout.subtitle',
'Pay on Stripe’s secure page in your browser. Orca picks it up the moment it goes through.'
)
: t(
'auto.components.billing.plans.subtitle2',
'Run Orca agents in hosted sandboxes that keep going when you step away.'
)}
: subscribed
? t(
'auto.components.billing.plans.subtitleSubscribed',
'Usage this month, your plan, and what Enterprise adds.'
)
: t(
'auto.components.billing.plans.subtitle2',
'Run Orca agents in hosted sandboxes that keep going when you step away.'
)}
</DialogDescription>
</DialogHeader>
<PlansView {...props} />
{checkout ?? <PlansView {...viewProps} />}
</DialogContent>
)
}
@@ -1,17 +1,22 @@
import { useState } from 'react'
import { useCallback, useState } from 'react'
import { Dialog } from '@/components/ui/dialog'
import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store/index'
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
import { CheckoutPanel } from '../checkout/CheckoutPanel'
import { useCheckoutFlow } from '../checkout/use-checkout-flow'
import { openFailureCopy } from '../plan-billing-copy'
import { openTeamPage } from '../team/team-page-store'
import { useOrcaBillingStatus } from '../use-orca-billing-status'
import { PlansDialogContent } from './PlansDialogContent'
import { closePlansPage, usePlansPageState } from './plans-page-store'
import { useOrgSeatCount } from './use-org-seat-count'
import { useAppStore } from '@/store/index'
/**
* The plans page. A dialog because choosing a plan is a decision step in front of Checkout;
* it reads the billing service's offers, so prices and limits are never hardcoded here.
* Checkout itself runs on Stripe's hosted page in the browser; this dialog follows it and,
* once paid, hands over to the Team page.
*/
export function PlansDialogHost(): React.JSX.Element {
const t = useTranslate()
@@ -21,14 +26,23 @@ export function PlansDialogHost(): React.JSX.Element {
const seats = useOrgSeatCount(open ? orgId : null)
const [busy, setBusy] = useState(false)
const [notice, setNotice] = useState<string | null>(null)
const [orderedAt, setOrderedAt] = useState(0)
const run = async (action: () => Promise<OrcaBillingOpenResult>): Promise<void> => {
const onPaid = useCallback((paidSeats: number) => {
closePlansPage()
openTeamPage({ kind: 'checkout-success', seats: paidSeats })
}, [])
const checkout = useCheckoutFlow({ active: open, onPaid })
const openPortal = async (): Promise<void> => {
setBusy(true)
setNotice(null)
const outcome = await action().catch((error: unknown): OrcaBillingOpenResult => ({
status: 'failed',
error: String(error)
}))
const outcome = await window.api.orcaProfiles
.billingOpenPortal()
.catch((error: unknown): OrcaBillingOpenResult => ({
status: 'failed',
error: String(error)
}))
setBusy(false)
setNotice(
outcome.status === 'opened'
@@ -40,6 +54,8 @@ export function PlansDialogHost(): React.JSX.Element {
)
}
const team = billing.result?.status === 'ok' ? billing.result.entitlement.offers?.team : null
return (
<Dialog
open={open}
@@ -52,20 +68,32 @@ export function PlansDialogHost(): React.JSX.Element {
>
{open ? (
<PlansDialogContent
// Remount once the status arrives so the interval starts fresh.
key={billing.result ? 'ready' : 'loading'}
result={billing.result}
busy={busy}
notice={notice}
seats={seats}
onCheckout={({ interval, seats: count }) =>
void run(() =>
window.api.orcaProfiles.billingOpenCheckout({ plan: 'team', interval, seats: count })
)
}
onManage={() => void run(() => window.api.orcaProfiles.billingOpenPortal())}
onCheckout={({ interval, seats: count }) => {
setOrderedAt(Date.now())
checkout.start({ interval, seats: count })
}}
onManage={() => void openPortal()}
onContactSales={(url) => void window.api.shell.openUrl(url)}
onRetry={billing.refresh}
checkout={
checkout.phase.kind !== 'idle' && team ? (
<CheckoutPanel
phase={checkout.phase}
team={team}
now={orderedAt}
onReopen={checkout.reopen}
onKeepWaiting={checkout.keepWaiting}
onBack={() => {
checkout.reset()
billing.refresh()
}}
/>
) : undefined
}
/>
) : null}
</Dialog>
@@ -23,7 +23,7 @@ export function PlansIntervalToggle({
hint:
savingsPercent === null
? null
: t('auto.components.billing.plans.saveShort', '−{{value0}}%', {
: t('auto.components.billing.plans.savePercent', 'Save {{value0}}%', {
value0: String(savingsPercent)
})
}
@@ -96,17 +96,6 @@ export const paymentFailed = defineFixture({
)
})
export const checkoutOpened = defineFixture({
width,
render: () => (
<Page
busy
notice="Continue in your browser. This updates when you come back."
result={{ status: 'ok', entitlement: noPlan }}
/>
)
})
export const loading = defineFixture({
width,
render: () => <Page result={null} />
@@ -1,9 +1,7 @@
import { useState } from 'react'
import { KeyRound, LaptopMinimal, RefreshCw, Zap } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Cloud, KeyRound, RefreshCw, Zap } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import {
ORCA_BILLING_MAX_SEATS,
@@ -12,7 +10,8 @@ import {
type OrcaBillingStatusResult
} from '../../../../../shared/orca-billing'
import { PaymentIssueNotice } from '../PaymentIssueNotice'
import { statusLabel } from '../plan-billing-copy'
import { PlanStatusBadge } from '../PlanStatusBadge'
import { seatCountLabel } from '../team/team-copy'
import { formatHours, includedUsagePercent } from '../plan-billing-format'
import { EnterprisePlanCard } from './EnterprisePlanCard'
import { PlansIntervalToggle } from './PlansIntervalToggle'
@@ -44,7 +43,7 @@ function ValueProps(): React.JSX.Element {
// Same promises as the marketing site's /cloud page.
const items = [
{
icon: LaptopMinimal,
icon: Cloud,
title: t('auto.components.billing.plans.vpRunningTitle', 'Agents keep running'),
body: t(
'auto.components.billing.plans.vpRunningBody2',
@@ -92,7 +91,6 @@ function CurrentPlanStrip({
}): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const paymentIssue = entitlement.payment.pastDueSince !== null
const resets = entitlement.usageWindow
? new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(entitlement.usageWindow.end)
: null
@@ -101,18 +99,15 @@ function CurrentPlanStrip({
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{entitlement.planLabel}</span>
<span className="text-muted-foreground">
{t('auto.components.billing.plans.seatsAndPeriod', 'Seats: {{value0}} · {{value1}}', {
value0: String(entitlement.seats),
{t('auto.components.billing.plans.seatsPeriod', '{{value0}} · {{value1}}', {
value0: seatCountLabel(entitlement.seats, t),
value1:
entitlement.interval === 'year'
? t('auto.components.billing.annual', 'Annual')
: t('auto.components.billing.monthly', 'Monthly')
})}
</span>
{/* The payment banner carries the alarm; the badge stays quiet. */}
<Badge variant={paymentIssue ? 'outline' : 'secondary'}>
{statusLabel(entitlement.status, t)}
</Badge>
<PlanStatusBadge entitlement={entitlement} />
</div>
<Progress
value={includedUsagePercent(entitlement)}
@@ -146,41 +141,74 @@ function CurrentPlanStrip({
)
}
function PlaceholderCards({
failed,
onRetry
}: {
failed: boolean
onRetry: () => void
}): React.JSX.Element {
function SkeletonLine({ className }: { className: string }): React.JSX.Element {
return <span className={`block rounded bg-muted motion-safe:animate-pulse ${className}`} />
}
function SkeletonCard({ lines }: { lines: number }): React.JSX.Element {
return (
<div className="flex h-full flex-col gap-5 rounded-xl border border-border bg-card p-5 shadow-xs">
<SkeletonLine className="h-4 w-24" />
<div className="space-y-2">
<SkeletonLine className="h-8 w-32" />
<SkeletonLine className="h-3 w-28" />
</div>
<div className="flex-1 space-y-3">
{Array.from({ length: lines }, (_, index) => (
<SkeletonLine key={index} className={index % 2 ? 'h-3 w-4/5' : 'h-3 w-11/12'} />
))}
</div>
<div className="min-h-[6rem] space-y-2 border-t border-border/60 pt-4">
<SkeletonLine className="h-9 w-full" />
<SkeletonLine className="mx-auto h-3 w-3/5" />
</div>
</div>
)
}
/** Same geometry as the loaded page (value props, toggle, two cards) so nothing jumps (review M4). */
function PlansSkeleton(): React.JSX.Element {
const t = useTranslate()
return (
<div
className="space-y-6"
role="status"
aria-label={t('auto.components.billing.plans.loading', 'Loading plans…')}
>
<ValueProps />
<div className="flex justify-center">
<SkeletonLine className="h-8 w-56 rounded-full" />
</div>
<div className="grid items-stretch gap-4 md:grid-cols-2">
<SkeletonCard lines={5} />
<SkeletonCard lines={4} />
</div>
</div>
)
}
function PlansLoadError({ onRetry }: { onRetry: () => void }): React.JSX.Element {
const t = useTranslate()
return (
<div className="space-y-6">
<ValueProps />
<div className="relative grid gap-4 md:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div aria-hidden className="h-[26rem] rounded-xl border border-border bg-muted/40" />
<div aria-hidden className="h-[26rem] rounded-xl border border-border bg-muted/40" />
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 text-sm text-muted-foreground">
{failed ? (
<>
<p>
{t(
'auto.components.billing.plans.loadFailed',
'Could not load plans. Try again in a moment.'
)}
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
<RefreshCw />
{t('auto.components.billing.plans.retry', 'Try again')}
</Button>
</>
) : (
<>
<LoadingSpinner />
<p>{t('auto.components.billing.plans.loading', 'Loading plans…')}</p>
</>
<div
role="alert"
className="mx-auto flex max-w-md flex-col items-center gap-3 rounded-xl border border-border p-8 text-center"
>
<p className="text-sm font-medium">
{t('auto.components.billing.plans.loadFailedTitle', 'Plans didn’t load')}
</p>
<p className="text-sm text-muted-foreground">
{t(
'auto.components.billing.plans.loadFailed',
'Could not load plans. Try again in a moment.'
)}
</div>
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
<RefreshCw />
{t('auto.components.billing.plans.retry', 'Try again')}
</Button>
</div>
</div>
)
@@ -202,7 +230,7 @@ export function PlansView(props: PlansViewProps): React.JSX.Element {
)
}
if (!result || result.status !== 'ok' || !result.entitlement.offers) {
return <PlaceholderCards failed={result !== null} onRetry={props.onRetry} />
return result === null ? <PlansSkeleton /> : <PlansLoadError onRetry={props.onRetry} />
}
const entitlement = result.entitlement
@@ -237,7 +265,7 @@ export function PlansView(props: PlansViewProps): React.JSX.Element {
onChange={setInterval}
/>
) : null}
<div className="grid items-stretch gap-4 md:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div className="grid items-stretch gap-4 md:grid-cols-2">
<TeamPlanCard
team={offers.team}
interval={subscribed && entitlement.interval ? entitlement.interval : interval}
@@ -257,14 +285,14 @@ export function PlansView(props: PlansViewProps): React.JSX.Element {
<div className="space-y-1 text-center text-xs text-muted-foreground text-pretty">
<p>
{t(
'auto.components.billing.plans.footHours',
'Hours reset every month, including on annual plans. When they run out, new sandboxes wait until the next month unless overage is on.'
'auto.components.billing.plans.footHours2',
'Hours reset monthly, including on annual plans.'
)}
</p>
<p>
{t(
'auto.components.billing.plans.footTerms',
'Prices in USD, before tax. Overage stays off until an owner or admin turns it on and sets a spend cap. Cancel anytime; your plan runs to the end of the period.'
'auto.components.billing.plans.footTerms2',
'Prices in USD, before tax. Overage is off until an owner or admin turns it on. Cancel anytime; your plan runs to the end of the billing period.'
)}
</p>
</div>
@@ -76,9 +76,10 @@ export function TeamPlanCard({
className="flex items-baseline gap-1.5 animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none"
>
{discounted && fullMonthly !== null ? (
<span className="text-lg text-muted-foreground line-through tabular-nums">
<del className="text-lg text-muted-foreground tabular-nums">
<span className="sr-only">{t('auto.components.billing.plans.was', 'Was')} </span>
{formatCents(fullMonthly, locale)}
</span>
</del>
) : null}
<span className="text-3xl font-semibold tracking-tight tabular-nums">
{monthly === null
@@ -134,7 +135,13 @@ export function TeamPlanCard({
if (mode === 'choose') {
footer = (
<>
<Button type="button" className="w-full" disabled={busy} onClick={onCheckout}>
<Button
type="button"
className="w-full"
disabled={busy}
onClick={onCheckout}
data-plans-primary=""
>
{busy ? <LoadingSpinner /> : null}
{busy
? t('auto.components.billing.plans.waiting', 'Waiting for checkout…')
@@ -166,6 +173,7 @@ export function TeamPlanCard({
className="w-full"
disabled={busy}
onClick={onManage}
data-plans-primary=""
>
{t('auto.components.billing.manageBilling', 'Manage billing')}
<ExternalLink />
@@ -2,7 +2,7 @@
// sandbox" upsell) calls openPlansPage(); PlansDialogHost renders it.
import { useSyncExternalStore } from 'react'
export type PlansPageSource = 'account-menu' | 'settings' | 'sandbox' | 'other'
export type PlansPageSource = 'account-menu' | 'settings' | 'sandbox' | 'team' | 'run-on' | 'other'
type PlansPageState = { open: boolean; source: PlansPageSource | null }
@@ -1,32 +1,13 @@
import { useEffect, useState } from 'react'
import { useOrgRoster } from '../team/use-org-roster'
/**
* Seats Team bills at Checkout: the active org's members (pending invites excluded), or 1 for a
* personal account. Billing re-reads the count from auth; this is only for showing the total.
*/
export function useOrgSeatCount(orgId: string | null): number {
const [members, setMembers] = useState<{ orgId: string; count: number } | null>(null)
useEffect(() => {
if (!orgId) {
return
}
let disposed = false
void window.api.orcaProfiles
.orgMembersList({ orgId })
.then((result) => {
if (!disposed && result.status === 'ok') {
setMembers({ orgId, count: result.roster.members.length })
}
})
.catch(() => undefined)
return () => {
disposed = true
}
}, [orgId])
if (!orgId) {
const roster = useOrgRoster(orgId)
if (!orgId || roster.result?.status !== 'ok') {
return 1
}
return members?.orgId === orgId ? Math.max(1, members.count) : 1
return Math.max(1, roster.result.roster.members.length)
}
@@ -1,44 +1,75 @@
import { describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
const openSettingsTarget = vi.fn()
const openSettingsPage = vi.fn()
vi.mock('@/store/index', () => ({
useAppStore: { getState: () => ({ openSettingsTarget, openSettingsPage }) }
useAppStore: { getState: () => ({ orcaProfileAuthStatus: null }), subscribe: () => () => {} }
}))
import {
getRegisteredAccountMenuItems,
selectVisibleAccountMenuItems
} from '../sidebar/account-menu/account-menu-items'
import { recordBillingStatus } from './billing-summary-store'
import { sampleTeam } from './plan-billing-fixtures'
import { BILLING_CAPABILITY, registerPlanBillingMenuItem } from './register-plan-billing-menu-item'
import { getPlansPageState } from './plans/plans-page-store'
import { closeTeamPage, getTeamPageState } from './team/team-page-store'
describe('Plan & billing and Team account menu items', () => {
it('register behind the billing capability and open Orca account settings', () => {
const visible = (): string[] =>
selectVisibleAccountMenuItems(getRegisteredAccountMenuItems(), {
activeProfileId: 'p1',
configured: true,
state: 'connected',
persistence: 'encrypted',
capabilities: { flags: { [BILLING_CAPABILITY]: true }, refreshedAt: 0 }
}).map((entry) => entry.id)
afterEach(() => {
recordBillingStatus({ status: 'signed-out' })
closeTeamPage()
})
describe('account menu billing items', () => {
it('registers Team and Plan & billing behind the billing capability', () => {
const dispose = registerPlanBillingMenuItem()
const items = getRegisteredAccountMenuItems()
expect(items.map((item) => [item.id, item.label(), item.requiredCapability])).toEqual([
['orca.plan-billing', 'Plan & billing', BILLING_CAPABILITY],
['orca.team', 'Team', BILLING_CAPABILITY]
])
items[0]?.onSelect()
expect(getPlansPageState()).toEqual({ open: true, source: 'account-menu' })
items[1]?.onSelect()
expect(openSettingsTarget).toHaveBeenCalledWith({ pane: 'orca-account', repoId: null })
expect(openSettingsPage).toHaveBeenCalled()
const visible = (flags: Record<string, boolean>): string[] =>
expect(
selectVisibleAccountMenuItems(getRegisteredAccountMenuItems(), {
activeProfileId: 'p1',
configured: true,
state: 'connected',
persistence: 'encrypted',
capabilities: { flags, refreshedAt: 0 }
}).map((entry) => entry.id)
expect(visible({})).toEqual([])
expect(visible({ [BILLING_CAPABILITY]: true })).toEqual(['orca.plan-billing', 'orca.team'])
capabilities: { flags: {}, refreshedAt: 0 }
})
).toEqual([])
expect(visible()).toEqual(['orca.team', 'orca.plan-billing'])
const plans = getRegisteredAccountMenuItems().find((item) => item.id === 'orca.plan-billing')
plans?.onSelect()
expect(getPlansPageState()).toEqual({ open: true, source: 'account-menu' })
dispose()
expect(getRegisteredAccountMenuItems()).toHaveLength(0)
})
it('adds an accent upgrade item only once billing says there is no plan', () => {
const dispose = registerPlanBillingMenuItem()
expect(visible()).not.toContain('orca.upgrade')
recordBillingStatus({
status: 'ok',
entitlement: { ...sampleTeam, plan: null, planLabel: null, status: 'none' }
})
expect(visible()).toEqual(['orca.upgrade', 'orca.team', 'orca.plan-billing'])
expect(getRegisteredAccountMenuItems().find((item) => item.id === 'orca.upgrade')?.tone).toBe(
'accent'
)
recordBillingStatus({ status: 'ok', entitlement: sampleTeam })
expect(visible()).not.toContain('orca.upgrade')
dispose()
})
it('opens the Team page from the Team item', () => {
const dispose = registerPlanBillingMenuItem()
getRegisteredAccountMenuItems()
.find((item) => item.id === 'orca.team')
?.onSelect()
expect(getTeamPageState()).toEqual({ open: true, arrival: null })
dispose()
})
})
@@ -1,25 +1,30 @@
import { CreditCard, Users } from 'lucide-react'
import { CreditCard, Sparkles, Users } from 'lucide-react'
import { translate } from '@/i18n/i18n'
import { useAppStore } from '@/store/index'
import { registerAccountMenuItem } from '../sidebar/account-menu/account-menu-items'
import {
getBillingSummary,
refreshBillingSummary,
subscribeBillingSummary
} from './billing-summary-store'
import { openPlansPage } from './plans/plans-page-store'
import { openTeamPage } from './team/team-page-store'
/** Cloud capability flag that turns billing on per account (server-controlled rollout). */
export const BILLING_CAPABILITY = 'billing'
function openAccountSettings(): void {
const state = useAppStore.getState()
state.openSettingsTarget({ pane: 'orca-account', repoId: null })
state.openSettingsPage()
}
const UPGRADE_ITEM_ID = 'orca.upgrade'
/** Account menu: "Plan & billing" opens the plans page; "Team" opens the Orca account settings. */
/**
* Account menu: "Team" opens the Team page; "Plan & billing" opens the plans page. Accounts
* without a plan also get "Upgrade to Orca Cloud" at the top of the group.
*/
export function registerPlanBillingMenuItem(): () => void {
const disposeBilling = registerAccountMenuItem({
id: 'orca.plan-billing',
label: () => translate('auto.components.billing.menuItem', 'Plan & billing'),
icon: CreditCard,
order: 10,
order: 11,
requiredCapability: BILLING_CAPABILITY,
onSelect: () => openPlansPage('account-menu')
})
@@ -27,12 +32,54 @@ export function registerPlanBillingMenuItem(): () => void {
id: 'orca.team',
label: () => translate('auto.components.billing.team.menuItem', 'Team'),
icon: Users,
order: 11,
order: 10,
requiredCapability: BILLING_CAPABILITY,
onSelect: openAccountSettings
onSelect: () => openTeamPage()
})
let disposeUpgrade: (() => void) | null = null
const syncUpgrade = (): void => {
// Only a known "no plan" shows it: never flash an upsell at a paying team while loading.
const show = getBillingSummary().subscribed === false
if (show && !disposeUpgrade) {
disposeUpgrade = registerAccountMenuItem({
id: UPGRADE_ITEM_ID,
label: () => translate('auto.components.billing.upgrade.menuItem', 'Upgrade to Orca Cloud'),
icon: Sparkles,
order: 9,
tone: 'accent',
requiredCapability: BILLING_CAPABILITY,
onSelect: () => openPlansPage('account-menu')
})
} else if (!show && disposeUpgrade) {
disposeUpgrade()
disposeUpgrade = null
}
}
const unsubscribeSummary = subscribeBillingSummary(syncUpgrade)
// Re-read when the signed-in account or its org changes; billing-flagged accounts only.
let lastKey: string | null = null
const onAuth = (): void => {
const auth = useAppStore.getState().orcaProfileAuthStatus
const enabled =
auth?.state === 'connected' && auth.capabilities?.flags[BILLING_CAPABILITY] === true
const key = enabled ? `${auth?.cloud?.userId}:${auth?.cloud?.activeOrgId ?? ''}` : null
if (key !== lastKey) {
lastKey = key
if (key) {
void refreshBillingSummary(true)
}
}
}
const unsubscribeAuth = useAppStore.subscribe(onAuth)
onAuth()
return () => {
disposeBilling()
disposeTeam()
disposeUpgrade?.()
unsubscribeSummary()
unsubscribeAuth()
}
}
@@ -29,10 +29,10 @@ export function PersonAvatar({
<span
aria-hidden
className={cn(
'flex size-8 shrink-0 items-center justify-center rounded-full text-[11px] font-medium select-none',
'flex size-6 shrink-0 items-center justify-center rounded-full text-[10px] font-medium select-none',
pending
? 'border border-dashed border-muted-foreground/50 text-muted-foreground'
: 'bg-foreground/85 text-background',
: 'border border-border bg-secondary text-secondary-foreground',
className
)}
>
@@ -0,0 +1,235 @@
import { useCallback, useState } from 'react'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store/index'
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
import type { OrcaProfileOrgCreateResult } from '../../../../../shared/orca-org-management'
import { openFailureCopy } from '../plan-billing-copy'
import { openPlansPage } from '../plans/plans-page-store'
import { useOrcaBillingStatus } from '../use-orca-billing-status'
import { TeamPageView } from './TeamPageView'
import { createTeamFailureCopy, mutationFailureCopy } from './team-copy'
import { clearTeamPageArrival, closeTeamPage, useTeamPageState } from './team-page-store'
import { useOrgRoster } from './use-org-roster'
import { useTeamActions } from './use-team-actions'
function TeamPageBody({ arrival }: { arrival: ReturnType<typeof useTeamPageState>['arrival'] }) {
const t = useTranslate()
const confirm = useConfirmationDialog()
const authStatus = useAppStore((state) => state.orcaProfileAuthStatus)
const selectOrg = useAppStore((state) => state.selectOrcaProfileOrg)
const refreshAuth = useAppStore((state) => state.refreshCurrentOrcaProfileAuth)
const openModal = useAppStore((state) => state.openModal)
const cloud = authStatus?.cloud
const orgId = cloud?.activeOrgId ?? null
const roster = useOrgRoster(orgId)
const billing = useOrcaBillingStatus(true)
const [userRefreshing, setUserRefreshing] = useState(false)
const [billingBusy, setBillingBusy] = useState(false)
const [creating, setCreating] = useState(false)
const [createError, setCreateError] = useState<string | null>(null)
const [switchingOrgId, setSwitchingOrgId] = useState<string | null>(null)
const [now] = useState(() => Date.now())
const quietRefresh = useCallback(() => {
roster.refresh()
billing.refresh()
}, [roster, billing])
const actions = useTeamActions({ orgId: orgId ?? '', onChanged: quietRefresh })
const rosterResult =
roster.result?.status === 'ok'
? { ...roster.result, roster: actions.applyOverlays(roster.result.roster) }
: roster.result
const openPortal = (): void => {
setBillingBusy(true)
void window.api.orcaProfiles
.billingOpenPortal()
.catch((error: unknown): OrcaBillingOpenResult => ({
status: 'failed',
error: String(error)
}))
.then((outcome) => {
setBillingBusy(false)
const failure = openFailureCopy(outcome, t)
if (failure) {
toast.error(failure)
}
})
}
const createTeam = (name: string): void => {
setCreating(true)
setCreateError(null)
void window.api.orcaProfiles
.orgCreate({ name })
.catch((error: unknown): OrcaProfileOrgCreateResult => ({
status: 'failed',
error: String(error)
}))
.then(async (outcome) => {
if (outcome.status === 'created') {
await selectOrg(outcome.orgId)
toast.success(
t('auto.components.billing.team.createdToast', '{{value0}} created', {
value0: outcome.name
})
)
} else {
setCreateError(createTeamFailureCopy(outcome, t))
}
setCreating(false)
})
}
const switchOrg = (target: string): void => {
setSwitchingOrgId(target)
void selectOrg(target).finally(() => setSwitchingOrgId(null))
}
const leave = (): void => {
if (!orgId) {
return
}
const name = cloud?.activeOrgName ?? t('auto.components.billing.team.thisTeam', 'this team')
void confirm({
title: t('auto.components.billing.team.leaveConfirmTitle', 'Leave {{value0}}?', {
value0: name
}),
description: t(
'auto.components.billing.team.leaveConfirmBody',
'You lose access to the team’s cloud workspaces and secrets right away. An owner or admin can invite you back.'
),
confirmLabel: t('auto.components.billing.team.leaveCta', 'Leave team'),
confirmVariant: 'destructive'
}).then((accepted) => {
if (!accepted) {
return
}
void window.api.orcaProfiles
.orgLeave({ orgId })
.catch((error: unknown) => ({ status: 'failed' as const, error: String(error) }))
.then(async (outcome) => {
if (outcome.status === 'ok') {
await refreshAuth()
closeTeamPage()
toast.success(
t('auto.components.billing.team.leftToast', 'You left {{value0}}', { value0: name })
)
} else {
toast.error(mutationFailureCopy(outcome, t) ?? '')
}
})
})
}
const org = orgId ? { orgId, name: cloud?.activeOrgName ?? orgId } : null
return (
<TeamPageView
org={org}
viewerUserId={cloud?.userId ?? null}
roster={rosterResult}
billing={billing.result}
arrival={arrival}
rowStates={actions.rowStates}
refreshing={userRefreshing && (roster.loading || billing.loading)}
billingBusy={billingBusy}
now={now}
create={{
organizations: (authStatus?.organizations ?? []).filter(
(candidate) => candidate.orgId !== orgId
),
creating,
error: createError,
switchingOrgId
}}
onCreateTeam={createTeam}
onSwitchOrg={switchOrg}
onRefresh={() => {
setUserRefreshing(true)
quietRefresh()
window.setTimeout(() => setUserRefreshing(false), 600)
}}
onInvite={actions.invite}
onChangeRole={(member, role) => actions.changeRole(member, role)}
onMakeOwner={actions.makeOwner}
onRemove={actions.remove}
onResend={actions.resend}
onRevoke={(email) => {
const role =
rosterResult?.status === 'ok'
? (rosterResult.roster.pendingInvites.find((invite) => invite.email === email)?.role ??
'member')
: 'member'
actions.revoke(email, role)
}}
onLeave={leave}
onSeePlans={() => {
closeTeamPage()
openPlansPage('team')
}}
onManageBilling={openPortal}
onCreateWorkspace={() => {
closeTeamPage()
openModal('new-workspace-composer', { telemetrySource: 'unknown' })
}}
onDismissArrival={clearTeamPageArrival}
/>
)
}
/** The Team page's dialog surface: top-anchored so loading and checkout arrivals never jump. */
export function TeamDialogContent({ children }: { children: React.ReactNode }): React.JSX.Element {
const t = useTranslate()
return (
<DialogContent
scrollable
className="top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-2xl"
onOpenAutoFocus={(event) => {
event.preventDefault()
if (event.currentTarget instanceof HTMLElement) {
event.currentTarget.focus()
}
}}
>
<DialogTitle className="sr-only">
{t('auto.components.billing.team.title', 'Team')}
</DialogTitle>
<DialogDescription className="sr-only">
{t(
'auto.components.billing.team.description',
'Members, invites, roles, seats and your Orca Cloud plan.'
)}
</DialogDescription>
{children}
</DialogContent>
)
}
/**
* The Team page: members, invites, roles, seats and the plan, in one place. A dialog like the
* plans page so it opens over whatever the user was doing; Checkout lands here when it succeeds.
*/
export function TeamDialogHost(): React.JSX.Element {
const { open, arrival } = useTeamPageState()
return (
<Dialog
open={open}
onOpenChange={(next) => {
if (!next) {
closeTeamPage()
}
}}
>
{open ? (
<TeamDialogContent>
<TeamPageBody arrival={arrival} />
</TeamDialogContent>
) : null}
</Dialog>
)
}
@@ -9,6 +9,7 @@ import {
SelectValue
} from '@/components/ui/select'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip'
import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
@@ -171,7 +172,7 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<div
className={cn(
'flex min-h-9 min-w-0 flex-1 cursor-text flex-wrap items-center gap-1 rounded-md border border-input bg-transparent px-2 py-1 shadow-xs transition-[color,box-shadow] dark:bg-input/30',
'flex min-h-8 min-w-0 flex-1 cursor-text flex-wrap items-center gap-1 rounded-md border border-input bg-transparent px-2 py-0.5 shadow-xs transition-[color,box-shadow] dark:bg-input/30',
'focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50'
)}
onClick={() => localInput.current?.focus()}
@@ -237,7 +238,7 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El
)
: undefined
}
className="h-7 min-w-[10rem] flex-1 bg-transparent px-1 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
className="h-6 min-w-[10rem] flex-1 bg-transparent px-1 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
value={draft}
onChange={(event) => {
const value = event.target.value
@@ -279,6 +280,7 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El
}}
>
<SelectTrigger
size="sm"
className="w-28"
aria-label={t('auto.components.billing.team.inviteRole', 'Role for the invite')}
>
@@ -286,36 +288,44 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El
</SelectTrigger>
<SelectContent align="end">
{roles.map((option) => (
<SelectItem key={option} value={option} textValue={roleLabel(option, t)}>
<span className="flex flex-col items-start">
<span>{roleLabel(option, t)}</span>
<span className="text-xs text-muted-foreground">
{roleDescription(option, t)}
</span>
</span>
<SelectItem key={option} value={option} title={roleDescription(option, t)}>
{roleLabel(option, t)}
</SelectItem>
))}
</SelectContent>
</Select>
<Button type="submit" disabled={sending || valid.length === 0} className="min-w-[7.5rem]">
{sending ? <LoadingSpinner className="size-3.5" /> : <Send />}
{valid.length > 1
? t('auto.components.billing.team.sendN', 'Send {{value0}} invites', {
value0: String(valid.length)
})
: t('auto.components.billing.team.send', 'Send invite')}
</Button>
<SettingsDisabledControlTooltip
reason={
!sending && valid.length === 0
? t('auto.components.billing.team.enterEmail', 'Enter a teammate’s email')
: undefined
}
>
<Button type="submit" size="sm" disabled={sending || valid.length === 0}>
{sending ? <LoadingSpinner className="size-3.5" /> : <Send />}
{valid.length > 1
? t('auto.components.billing.team.sendN', 'Send {{value0}} invites', {
value0: String(valid.length)
})
: t('auto.components.billing.team.send', 'Send invite')}
</Button>
</SettingsDisabledControlTooltip>
</div>
</div>
<p id={hintId} aria-live="polite" className="text-xs text-muted-foreground text-pretty">
{impactCopy(impact, valid, locale, t)}
{invalidCount > 0
{invalidCount === 1
? ` ${t(
'auto.components.billing.team.invalidCount',
'{{value0}} entries aren’t email addresses and won’t be sent.',
{ value0: String(invalidCount) }
'auto.components.billing.team.invalidOne',
'One entry isn’t an email address and won’t be sent.'
)}`
: null}
: invalidCount > 1
? ` ${t(
'auto.components.billing.team.invalidCount',
'{{value0}} entries aren’t email addresses and won’t be sent.',
{ value0: String(invalidCount) }
)}`
: null}
</p>
{describedErrors.length > 0 ? (
<ul role="alert" className="space-y-0.5 text-xs text-destructive">
@@ -68,7 +68,7 @@ function RoleControl({
const member = row.member
if (!row.manageable) {
return (
<span className="w-24 shrink-0 text-right text-xs text-muted-foreground">
<span className="w-28 shrink-0 text-right text-xs text-muted-foreground">
{roleLabel(member.role, t)}
</span>
)
@@ -87,7 +87,7 @@ function RoleControl({
>
<SelectTrigger
size="sm"
className="w-24 shrink-0"
className="w-28 shrink-0"
aria-label={t('auto.components.billing.team.roleFor', 'Role for {{value0}}', {
value0: member.displayName ?? member.email
})}
@@ -96,11 +96,8 @@ function RoleControl({
</SelectTrigger>
<SelectContent align="end">
{roles.map((role) => (
<SelectItem key={role} value={role} textValue={roleLabel(role, t)}>
<span className="flex flex-col items-start">
<span>{roleLabel(role, t)}</span>
<span className="text-xs text-muted-foreground">{roleDescription(role, t)}</span>
</span>
<SelectItem key={role} value={role} title={roleDescription(role, t)}>
{roleLabel(role, t)}
</SelectItem>
))}
</SelectContent>
@@ -184,7 +181,7 @@ function RowMenu({
type="button"
variant="ghost"
size="icon-sm"
className="size-7 shrink-0 text-muted-foreground"
className="size-7 shrink-0"
aria-label={t('auto.components.billing.team.actionsFor', 'Actions for {{value0}}', {
value0: name
})}
@@ -226,7 +223,7 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
data-team-row={row.key}
aria-busy={state.busy || undefined}
className={cn(
'group/row bg-card px-3 py-2.5 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none',
'group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none',
state.busy && 'opacity-70'
)}
>
@@ -245,7 +242,7 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
className={cn(
'shrink-0 rounded-full border px-1.5 py-px text-[10px] font-medium leading-4',
row.status === 'invited'
? 'border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300'
? 'border-callout-note/40 bg-callout-note/10 text-callout-note'
: 'border-border text-muted-foreground'
)}
>
@@ -266,14 +263,14 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
onChange={(role) => props.onChangeRole(row.member, role)}
/>
) : (
<span className="w-24 shrink-0 text-right text-xs text-muted-foreground">
<span className="w-28 shrink-0 text-right text-xs text-muted-foreground">
{roleLabel(row.invite.role, t)}
</span>
)}
<RowMenu row={row} props={props} />
</div>
{state.error ? (
<p role="alert" className="mt-1.5 pl-11 text-xs text-destructive">
<p role="alert" className="mt-1 pl-9 text-xs text-destructive">
{state.error}
</p>
) : null}
@@ -1,114 +0,0 @@
import { useState } from 'react'
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
import { useTranslate } from '@/i18n/use-translate'
import type { OrcaProfileOrgMemberMutationResult } from '../../../../../shared/orca-profiles'
import { useOrcaBillingStatus } from '../use-orca-billing-status'
import { TeamMembersView } from './TeamMembersView'
import { mutationFailureCopy } from './team-roles'
import { useOrgRoster } from './use-org-roster'
/**
* Team members for the active org: list, invite by email (accepted at Orca's sign-in provider),
* change roles, remove. Membership lives in Orca Cloud auth; Team seats follow it automatically
* (auth pushes removals, billing re-reads the count), so nothing here touches Stripe.
*/
export function TeamMembersSection({
orgId,
viewerUserId
}: {
orgId: string
viewerUserId: string | null
}): React.JSX.Element {
const t = useTranslate()
const confirm = useConfirmationDialog()
const roster = useOrgRoster(orgId)
const billing = useOrcaBillingStatus(true)
const [busy, setBusy] = useState(false)
const [notice, setNotice] = useState<string | null>(null)
const run = async (
action: () => Promise<OrcaProfileOrgMemberMutationResult>,
success: string
): Promise<void> => {
setBusy(true)
setNotice(null)
const outcome = await action().catch((error: unknown): OrcaProfileOrgMemberMutationResult => ({
status: 'failed',
error: String(error)
}))
setBusy(false)
setNotice(outcome.status === 'ok' ? success : mutationFailureCopy(outcome, t))
if (outcome.status === 'ok') {
roster.refresh()
billing.refresh()
}
}
const entitlement = billing.result?.status === 'ok' ? billing.result.entitlement : null
const billedSeats = entitlement && entitlement.plan !== null ? entitlement.seats : null
return (
<TeamMembersView
result={roster.result}
loading={roster.loading}
busy={busy}
notice={notice}
billedSeats={billedSeats}
seatChange={entitlement?.seatChange ?? null}
viewerUserId={viewerUserId}
onRefresh={() => {
roster.refresh()
billing.refresh()
}}
onInvite={(email, role) =>
void run(
() => window.api.orcaProfiles.orgMemberInvite({ orgId, email, role }),
t(
'auto.components.billing.team.invited',
'Invite sent to {{value0}}. They join (and become a billed seat) when they accept.',
{ value0: email }
)
)
}
onRevoke={(email) =>
void run(
() => window.api.orcaProfiles.orgInviteRevoke({ orgId, email }),
t('auto.components.billing.team.revoked', 'Invite revoked.')
)
}
onChangeRole={(member, role) => {
if (member.userId) {
const userId = member.userId
void run(
() => window.api.orcaProfiles.orgMemberChangeRole({ orgId, userId, role }),
t('auto.components.billing.team.roleChanged', 'Role updated.')
)
}
}}
onRemove={(member) => {
const userId = member.userId
if (!userId) {
return
}
void confirm({
title: t('auto.components.billing.team.removeTitle', 'Remove {{value0}}?', {
value0: member.displayName ?? member.email
}),
description: t(
'auto.components.billing.team.removeDescription2',
'They lose access to the org right away. Their seat stays paid until your plan renews, then drops off.'
),
confirmLabel: t('auto.components.billing.team.removeConfirm', 'Remove member'),
confirmVariant: 'destructive'
}).then((accepted) => {
if (accepted) {
void run(
() => window.api.orcaProfiles.orgMemberRemove({ orgId, userId }),
t('auto.components.billing.team.removed', 'Member removed.')
)
}
})
}}
/>
)
}
@@ -1,58 +0,0 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles'
import { TeamMembersView } from './TeamMembersView'
const roster: OrcaOrgMembersRoster = {
members: [
{ userId: 'u1', email: 'ada@acme.dev', displayName: 'Ada Lovelace', role: 'owner' },
{ userId: 'u2', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'admin' },
{ userId: 'u3', email: 'linus@acme.dev', role: 'member' },
{ userId: null, email: 'sso-only@acme.dev', role: 'member' }
],
pendingInvites: [
{ email: 'margaret@acme.dev', role: 'member', createdAt: Date.UTC(2026, 10, 7) }
],
viewerRole: 'owner',
canManageMembers: true
}
const handlers = {
loading: false,
busy: false,
onRefresh: () => {},
onInvite: () => {},
onRevoke: () => {},
onChangeRole: () => {},
onRemove: () => {}
}
export const ownerView = defineFixture({
width: 600,
render: () => (
<TeamMembersView
{...handlers}
notice={null}
billedSeats={5}
seatChange={{ seatsAtRenewal: 4, effectiveAt: Date.UTC(2026, 11, 3) }}
viewerUserId="u1"
result={{ status: 'ok', roster }}
/>
)
})
export const memberView = defineFixture({
width: 600,
render: () => (
<TeamMembersView
{...handlers}
notice={null}
billedSeats={null}
seatChange={null}
viewerUserId="u3"
result={{
status: 'ok',
roster: { ...roster, pendingInvites: [], viewerRole: 'member', canManageMembers: false }
}}
/>
)
})
@@ -1,280 +0,0 @@
import { useState } from 'react'
import { Mail, RefreshCw, UserMinus, UserPlus } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import type {
OrcaOrgMember,
OrcaOrgRole,
OrcaProfileOrgMembersListResult
} from '../../../../../shared/orca-profiles'
import { assignableRoles, canActOnRole, roleLabel } from './team-roles'
export type TeamMembersViewProps = {
result: OrcaProfileOrgMembersListResult | null
loading: boolean
busy: boolean
notice: string | null
/** Seats Team bills (from billing), or null when there is no plan or billing is off. */
billedSeats: number | null
/** Seats paid this period stay until renewal, then drop to the member count. */
seatChange: { seatsAtRenewal: number; effectiveAt: number } | null
viewerUserId: string | null
onRefresh: () => void
onInvite: (email: string, role: OrcaOrgRole) => void
onRevoke: (email: string) => void
onChangeRole: (member: OrcaOrgMember, role: OrcaOrgRole) => void
onRemove: (member: OrcaOrgMember) => void
}
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function RoleSelect({
value,
roles,
disabled,
onChange,
label
}: {
value: OrcaOrgRole
roles: OrcaOrgRole[]
disabled: boolean
onChange: (role: OrcaOrgRole) => void
label: string
}): React.JSX.Element {
const t = useTranslate()
return (
<Select
value={value}
disabled={disabled}
onValueChange={(next) => {
const role = roles.find((candidate) => candidate === next)
if (role) {
onChange(role)
}
}}
>
<SelectTrigger size="sm" aria-label={label}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{roles.map((role) => (
<SelectItem key={role} value={role}>
{roleLabel(role, t)}
</SelectItem>
))}
</SelectContent>
</Select>
)
}
export function TeamMembersView(props: TeamMembersViewProps): React.JSX.Element {
const t = useTranslate()
const { result, loading, busy, notice, billedSeats } = props
const locale = useIntlLocale()
const [email, setEmail] = useState('')
const [inviteRole, setInviteRole] = useState<OrcaOrgRole>('member')
const header = (
<div className="flex items-center justify-between gap-3">
<p className="text-[11px] font-semibold uppercase tracking-[0.05em] text-muted-foreground">
{t('auto.components.billing.team.title', 'Team')}
</p>
<Button
type="button"
variant="ghost"
size="icon-xs"
disabled={loading}
onClick={props.onRefresh}
aria-label={t('auto.components.billing.team.refresh', 'Refresh team')}
>
<RefreshCw className={cn(loading && 'animate-spin')} />
</Button>
</div>
)
if (!result || result.status !== 'ok') {
return (
<div className="space-y-3 border-t border-border/60 pt-5">
{header}
<p className="text-xs text-muted-foreground">
{result === null
? t('auto.components.billing.team.loading', 'Loading your team…')
: t('auto.components.billing.team.loadFailed', 'Could not load your team. Try again.')}
</p>
</div>
)
}
const roster = result.roster
const manager = roster.canManageMembers
const roles = assignableRoles(roster.viewerRole)
const emailValid = EMAIL.test(email.trim())
return (
<div className="space-y-4 border-t border-border/60 pt-5">
{header}
<p className="text-xs text-muted-foreground">
{billedSeats === null
? t('auto.components.billing.team.memberCount', '{{value0}} members', {
value0: String(roster.members.length)
})
: t(
'auto.components.billing.team.memberSeats',
'{{value0}} members · {{value1}} seats billed. Seats follow membership; pending invites are free until accepted.',
{ value0: String(roster.members.length), value1: String(billedSeats) }
)}
{props.seatChange
? ` ${t(
'auto.components.billing.team.seatsDrop',
'Seats paid this period stay until {{value0}}, then drop to {{value1}}.',
{
value0: new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(
props.seatChange.effectiveAt
),
value1: String(props.seatChange.seatsAtRenewal)
}
)}`
: null}
</p>
<ul className="divide-y divide-border/60 rounded-md border border-border/60">
{roster.members.map((member) => {
const self = member.userId !== null && member.userId === props.viewerUserId
const actionable =
manager &&
!self &&
member.userId !== null &&
canActOnRole(roster.viewerRole, member.role)
return (
<li key={member.email} className="flex items-center gap-3 px-3 py-2">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{member.displayName ?? member.email}
{self ? (
<span className="ml-2 text-xs font-normal text-muted-foreground">
{t('auto.components.billing.team.you', '(you)')}
</span>
) : null}
</p>
{member.displayName ? (
<p className="truncate text-xs text-muted-foreground">{member.email}</p>
) : null}
</div>
{actionable ? (
<RoleSelect
value={member.role}
roles={roles}
disabled={busy}
onChange={(role) => props.onChangeRole(member, role)}
label={t('auto.components.billing.team.roleFor', 'Role for {{value0}}', {
value0: member.email
})}
/>
) : (
<Badge variant="outline">{roleLabel(member.role, t)}</Badge>
)}
{actionable ? (
<Button
type="button"
variant="ghost"
size="icon-xs"
disabled={busy}
onClick={() => props.onRemove(member)}
aria-label={t('auto.components.billing.team.remove', 'Remove {{value0}}', {
value0: member.email
})}
>
<UserMinus />
</Button>
) : null}
</li>
)
})}
</ul>
{manager && roster.pendingInvites.length > 0 ? (
<div className="space-y-2">
<p className="text-xs font-medium">
{t('auto.components.billing.team.pending', 'Pending invites')}
</p>
<ul className="divide-y divide-border/60 rounded-md border border-dashed border-border/60">
{roster.pendingInvites.map((invite) => (
<li key={invite.email} className="flex items-center gap-3 px-3 py-2">
<Mail className="size-4 text-muted-foreground" />
<p className="min-w-0 flex-1 truncate text-sm">{invite.email}</p>
<Badge variant="outline">{roleLabel(invite.role, t)}</Badge>
{canActOnRole(roster.viewerRole, invite.role) ? (
<Button
type="button"
variant="ghost"
size="sm"
disabled={busy}
onClick={() => props.onRevoke(invite.email)}
>
{t('auto.components.billing.team.revoke', 'Revoke')}
</Button>
) : null}
</li>
))}
</ul>
</div>
) : null}
{manager ? (
<form
className="flex flex-wrap items-center gap-2"
onSubmit={(event) => {
event.preventDefault()
if (emailValid) {
props.onInvite(email.trim(), inviteRole)
setEmail('')
}
}}
>
<div className="min-w-48 flex-1">
<Input
type="email"
placeholder={t(
'auto.components.billing.team.invitePlaceholder',
'teammate@company.com'
)}
value={email}
onChange={(event) => setEmail(event.target.value)}
aria-label={t('auto.components.billing.team.inviteEmail', 'Email to invite')}
/>
</div>
<RoleSelect
value={inviteRole}
roles={roles}
disabled={busy}
onChange={setInviteRole}
label={t('auto.components.billing.team.inviteRole', 'Role for the invite')}
/>
<Button type="submit" size="sm" disabled={busy || !emailValid}>
<UserPlus />
{t('auto.components.billing.team.invite', 'Invite')}
</Button>
</form>
) : (
<p className="text-xs text-muted-foreground">
{t(
'auto.components.billing.team.askAdmin',
'Only owners and admins can invite or remove members.'
)}
</p>
)}
{notice ? <p className="text-xs text-muted-foreground">{notice}</p> : null}
</div>
)
}
@@ -0,0 +1,220 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import { Dialog } from '@/components/ui/dialog'
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles'
import { sampleTeam } from '../plan-billing-fixtures'
import { TeamDialogContent } from './TeamDialogHost'
import { TeamPageView, type TeamPageViewProps } from './TeamPageView'
const NOW = Date.UTC(2026, 10, 18, 15)
const DAY = 86_400_000
const width = 1100
const roster: OrcaOrgMembersRoster = {
viewerRole: 'owner',
canManageMembers: true,
members: [
{ userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' },
{ userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', role: 'admin' },
{ userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' },
{ userId: null, email: 'linus@acme.dev', role: 'member' }
],
pendingInvites: [
{ email: 'alex@acme.dev', role: 'member', createdAt: NOW - 2 * DAY },
{ email: 'sam@acme.dev', role: 'admin', createdAt: NOW - 3 * 3600_000 }
]
}
const team: OrcaBillingEntitlement = {
...sampleTeam,
seats: 4,
period: { start: Date.UTC(2026, 10, 3), end: Date.UTC(2026, 11, 3) }
}
const noPlan: OrcaBillingEntitlement = {
...sampleTeam,
plan: null,
planLabel: null,
status: 'none',
interval: null,
seats: 0,
period: null,
canStartSandbox: false,
reason: 'no_subscription'
}
const noop = (): void => {}
const base: TeamPageViewProps = {
org: { orgId: 'org-acme', name: 'Acme Engineering' },
viewerUserId: 'u-neil',
roster: { status: 'ok', roster },
billing: { status: 'ok', entitlement: team },
arrival: null,
rowStates: {},
refreshing: false,
billingBusy: false,
now: NOW,
create: { organizations: [], creating: false, error: null, switchingOrgId: null },
onCreateTeam: noop,
onSwitchOrg: noop,
onRefresh: noop,
onInvite: async () => ({ failed: [] }),
onChangeRole: noop,
onMakeOwner: noop,
onRemove: noop,
onResend: noop,
onRevoke: noop,
onLeave: noop,
onSeePlans: noop,
onManageBilling: noop,
onCreateWorkspace: noop,
onDismissArrival: noop
}
function Page(props: Partial<TeamPageViewProps>): React.JSX.Element {
return (
<Dialog open modal={false}>
<TeamDialogContent>
<TeamPageView {...base} {...props} />
</TeamDialogContent>
</Dialog>
)
}
export const ownerOnTeam = defineFixture({ width, render: () => <Page /> })
export const justUpgraded = defineFixture({
width,
render: () => <Page arrival={{ kind: 'checkout-success', seats: 4 }} />
})
export const noPlanUpgrade = defineFixture({
width,
render: () => <Page billing={{ status: 'ok', entitlement: noPlan }} />
})
export const memberReadOnly = defineFixture({
width,
render: () => (
<Page
viewerUserId="u-grace"
roster={{
status: 'ok',
roster: { ...roster, viewerRole: 'member', canManageMembers: false, pendingInvites: [] }
}}
billing={{ status: 'ok', entitlement: { ...noPlan, canManageBilling: false } }}
/>
)
})
export const rowBusyAndError = defineFixture({
width,
render: () => (
<Page
rowStates={{
'member:u-grace': { busy: true },
'invite:alex@acme.dev': {
error: 'Too many team changes at once. Wait a minute and try again.'
}
}}
/>
)
})
export const seatsDropAtRenewal = defineFixture({
width,
render: () => (
<Page
billing={{
status: 'ok',
entitlement: {
...team,
seats: 5,
seatChange: { seatsAtRenewal: 4, effectiveAt: Date.UTC(2026, 11, 3) }
}
}}
/>
)
})
export const paymentFailed = defineFixture({
width,
render: () => (
<Page
billing={{
status: 'ok',
entitlement: {
...team,
status: 'past_due',
payment: { pastDueSince: NOW - DAY, graceEndsAt: NOW + 3 * DAY, suspendRunning: false },
canStartSandbox: false,
reason: 'payment_past_due'
}
}}
/>
)
})
export const loading = defineFixture({ width, render: () => <Page roster={null} billing={null} /> })
export const loadFailed = defineFixture({
width,
render: () => (
<Page
roster={{ status: 'failed', error: 'timeout' }}
billing={{ status: 'failed', error: 'x' }}
/>
)
})
export const personalCreateTeam = defineFixture({
width,
render: () => (
<Page
org={null}
create={{
organizations: [
{ orgId: 'org-acme', name: 'Acme Engineering', role: 'Admin' },
{ orgId: 'org-oss', name: 'Open Source Club', role: 'Member' }
],
creating: false,
error: null,
switchingOrgId: null
}}
/>
)
})
export const createTeamUnsupported = defineFixture({
width,
render: () => (
<Page
org={null}
create={{
organizations: [],
creating: false,
error:
'Creating teams from Orca isn’t available on your account service yet. Ask a teammate to invite you to theirs.',
switchingOrgId: null
}}
/>
)
})
/** Pasted list mid-composition: valid chips, one invalid, and the seat impact line. */
export const invitePasted = defineFixture({
width,
render: () => <Page billing={{ status: 'ok', entitlement: { ...team, seats: 4 } }} />,
interact: async () => {
// The dialog portals to <body>, outside the fixture frame.
const input = document.querySelector<HTMLInputElement>('input[inputmode="email"]')
if (!input) {
return
}
input.focus()
// React listens for native input events; the trailing separator commits the chips.
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set
setValue?.call(input, 'jordan@acme.dev, kim@acme.dev, not-an-email ')
input.dispatchEvent(new Event('input', { bubbles: true }))
await new Promise((resolve) => setTimeout(resolve, 100))
}
})
@@ -1,6 +1,7 @@
import { useRef } from 'react'
import { LogOut, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import type { OrcaBillingStatusResult } from '../../../../../shared/orca-billing'
@@ -55,8 +56,8 @@ function SkeletonRows(): React.JSX.Element {
className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border"
>
{[0, 1, 2].map((index) => (
<div key={index} className="flex items-center gap-3 bg-card px-3 py-2.5">
<span className="size-8 rounded-full bg-muted motion-safe:animate-pulse" />
<div key={index} className="flex min-h-12 items-center gap-3 bg-card px-3 py-2">
<span className="size-6 rounded-full bg-muted motion-safe:animate-pulse" />
<span className="flex-1 space-y-1.5">
<span className="block h-3 w-32 rounded bg-muted motion-safe:animate-pulse" />
<span className="block h-2.5 w-44 rounded bg-muted/70 motion-safe:animate-pulse" />
@@ -179,7 +180,10 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
rowStates={props.rowStates}
canLeave={canLeave}
now={props.now}
onChangeRole={props.onChangeRole}
// Promoting to owner hands over billing control, so it always confirms first.
onChangeRole={(member, role) =>
role === 'owner' ? props.onMakeOwner(member) : props.onChangeRole(member, role)
}
onMakeOwner={props.onMakeOwner}
onRemove={props.onRemove}
onResend={props.onResend}
@@ -240,17 +244,27 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
)}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="text-destructive hover:text-destructive"
disabled={!canLeave}
onClick={props.onLeave}
<SettingsDisabledControlTooltip
reason={
canLeave
? undefined
: t(
'auto.components.billing.team.leaveNeedsOwner',
'Make someone else an owner first'
)
}
>
<LogOut />
{t('auto.components.billing.team.leaveCta', 'Leave team')}
</Button>
<Button
type="button"
variant="destructive"
size="sm"
disabled={!canLeave}
onClick={props.onLeave}
>
<LogOut />
{t('auto.components.billing.team.leaveCta', 'Leave team')}
</Button>
</SettingsDisabledControlTooltip>
</section>
) : null}
</div>
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'react'
import { ArrowRight, Check, Cloud, ExternalLink, Sparkles, UserPlus, X } from 'lucide-react'
import { ArrowRight, Check, Cloud, ExternalLink, UserPlus, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
@@ -31,17 +31,17 @@ export function TeamCheckoutCelebration({
return (
<section
aria-labelledby="team-celebration-title"
className="relative overflow-hidden rounded-xl border border-emerald-500/30 bg-emerald-500/[0.07] p-4 animate-in fade-in-0 slide-in-from-top-2 duration-300 motion-reduce:animate-none"
className="relative overflow-hidden rounded-xl border border-status-success-border bg-status-success-background p-4 animate-in fade-in-0 slide-in-from-top-2 duration-300 motion-reduce:animate-none"
>
{/* Soft glow; static, so reduced motion loses nothing. */}
<div
aria-hidden
className="pointer-events-none absolute -top-16 -right-10 size-48 rounded-full bg-emerald-400/20 blur-3xl"
className="pointer-events-none absolute -top-16 -right-10 size-48 rounded-full bg-status-success/20 blur-3xl"
/>
<div className="relative flex items-start gap-3">
<span
aria-hidden
className="flex size-9 shrink-0 items-center justify-center rounded-full bg-emerald-500 text-white shadow-sm animate-in zoom-in-50 duration-300 motion-reduce:animate-none"
className="flex size-9 shrink-0 items-center justify-center rounded-full bg-status-success text-background shadow-sm animate-in zoom-in-50 duration-300 motion-reduce:animate-none"
>
<Check className="size-5" strokeWidth={2.5} />
</span>
@@ -78,7 +78,6 @@ export function TeamCheckoutCelebration({
type="button"
variant="ghost"
size="icon-xs"
className="text-muted-foreground"
onClick={onDismiss}
aria-label={t('auto.components.billing.team.dismiss', 'Dismiss')}
>
@@ -231,7 +230,7 @@ export function TeamUpgradeCard({
/>
<div className="relative flex flex-wrap items-center gap-4">
<span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-foreground text-background">
<Sparkles className="size-4" />
<Cloud className="size-4" />
</span>
<div className="min-w-[14rem] flex-1 space-y-0.5">
<h3 id="team-upgrade-title" className="text-sm font-semibold">
@@ -0,0 +1,49 @@
import { ChevronRight } from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { TeamMark } from './TeamAvatar'
import { memberCountLabel } from './team-copy'
import { openTeamPage } from './team-page-store'
import { useOrgRoster } from './use-org-roster'
/** Settings → Orca account: one row that opens the Team page (members, invites, seats). */
export function TeamSettingsLink({
orgId,
orgName
}: {
orgId: string | null
orgName: string | null
}): React.JSX.Element {
const t = useTranslate()
const roster = useOrgRoster(orgId)
const members = roster.result?.status === 'ok' ? roster.result.roster.members.length : null
return (
<div className="space-y-3 border-t border-border/60 pt-5">
<p className="text-[11px] font-semibold uppercase tracking-[0.05em] text-muted-foreground">
{t('auto.components.billing.team.title', 'Team')}
</p>
<button
type="button"
onClick={() => openTeamPage()}
className="flex w-full items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-xs transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none"
>
{orgName ? <TeamMark name={orgName} className="size-8 text-xs" /> : null}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">
{orgName ?? t('auto.components.billing.team.createTitle', 'Create a team')}
</span>
<span className="block truncate text-xs text-muted-foreground">
{orgName
? members === null
? t('auto.components.billing.team.manage', 'Members, invites and seats')
: `${memberCountLabel(members, t)} · ${t('auto.components.billing.team.manage', 'Members, invites and seats')}`
: t(
'auto.components.billing.team.createHint',
'Share one Orca Cloud plan with your teammates.'
)}
</span>
</span>
<ChevronRight className="size-4 text-muted-foreground" />
</button>
</div>
)
}
@@ -36,10 +36,10 @@ function subscribe(listener: () => void): () => void {
return () => listeners.delete(listener)
}
function getState(): TeamPageState {
export function getTeamPageState(): TeamPageState {
return state
}
export function useTeamPageState(): TeamPageState {
return useSyncExternalStore(subscribe, getState)
return useSyncExternalStore(subscribe, getTeamPageState)
}
@@ -1,10 +1,7 @@
// Mirrors Orca Cloud auth's role rules (apps/auth/src/accounts/org-roles.ts) so the UI only offers
// actions the server will accept: owner > admin > member; only owners act on owners.
import type { Translate } from '@/i18n/use-translate'
import type {
OrcaOrgRole,
OrcaProfileOrgMemberMutationResult
} from '../../../../../shared/orca-profiles'
import type { OrcaOrgRole } from '../../../../../shared/orca-profiles'
export const ORG_ROLES: readonly OrcaOrgRole[] = ['owner', 'admin', 'member']
@@ -34,34 +31,3 @@ export function roleLabel(role: OrcaOrgRole, t: Translate): string {
return t('auto.components.billing.team.roleMember', 'Member')
}
}
export function mutationFailureCopy(
result: OrcaProfileOrgMemberMutationResult,
t: Translate
): string | null {
switch (result.status) {
case 'ok':
return null
case 'conflict':
return result.reason === 'already_member'
? t('auto.components.billing.team.alreadyMember', 'That person is already a member.')
: t('auto.components.billing.team.alreadyInvited', 'That person already has an invite.')
case 'invalid':
return result.reason === 'cannot_remove_self'
? t('auto.components.billing.team.cannotRemoveSelf', 'You cannot remove yourself.')
: t('auto.components.billing.team.cannotChangeOwnRole', 'You cannot change your own role.')
case 'forbidden':
return t(
'auto.components.billing.team.forbidden',
'Only owners and admins can manage members, and only owners can manage owners.'
)
case 'not-found':
return t('auto.components.billing.team.notFound', 'That member or invite no longer exists.')
case 'reconnect-required':
return t('auto.components.billing.openSignedOut', 'Sign in to Orca again to manage billing.')
case 'unconfigured':
return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')
case 'failed':
return t('auto.components.billing.team.failed', 'Could not update the team. Try again.')
}
}
@@ -1,7 +1,23 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useSyncExternalStore } from 'react'
import type { OrcaProfileOrgMembersListResult } from '../../../../../shared/orca-profiles'
type RosterState = { loading: boolean; result: OrcaProfileOrgMembersListResult | null }
// One shared read per org: the Team page, seat counts and workspace owner chips all use the
// same roster, so several mounted readers cost one IPC call (and one auth roster read).
type Entry = {
result: OrcaProfileOrgMembersListResult | null
loading: boolean
inFlight: Promise<void> | null
}
const entries = new Map<string, Entry>()
const listeners = new Set<() => void>()
const MAX_CACHED_ORGS = 16
function emit(): void {
for (const listener of listeners) {
listener()
}
}
function readRoster(orgId: string): Promise<OrcaProfileOrgMembersListResult> {
return window.api.orcaProfiles
@@ -12,24 +28,57 @@ function readRoster(orgId: string): Promise<OrcaProfileOrgMembersListResult> {
}))
}
/** The org's live roster (members, pending invites, viewer role), re-read on `refresh()`. */
export function useOrgRoster(orgId: string): RosterState & { refresh: () => void } {
const [state, setState] = useState<RosterState>({ loading: true, result: null })
const [reloadKey, setReloadKey] = useState(0)
const refresh = useCallback(() => setReloadKey((key) => key + 1), [])
useEffect(() => {
let disposed = false
setState((previous) => ({ ...previous, loading: true }))
void readRoster(orgId).then((result) => {
if (!disposed) {
setState({ loading: false, result })
}
})
return () => {
disposed = true
/** Starts a read unless one is already running for this org. */
export function loadOrgRoster(orgId: string): Promise<void> {
const existing = entries.get(orgId)
if (existing?.inFlight) {
return existing.inFlight
}
const entry: Entry = existing ?? { result: null, loading: true, inFlight: null }
const inFlight = readRoster(orgId).then((result) => {
// Keep the last good roster through a transient failure so the list doesn't vanish.
const keep = result.status !== 'ok' && entry.result?.status === 'ok'
entries.set(orgId, { result: keep ? entry.result : result, loading: false, inFlight: null })
emit()
})
entries.delete(orgId)
entries.set(orgId, { ...entry, loading: true, inFlight })
while (entries.size > MAX_CACHED_ORGS) {
const oldest = entries.keys().next()
if (oldest.done) {
break
}
}, [orgId, reloadKey])
entries.delete(oldest.value)
}
emit()
return inFlight
}
return { ...state, refresh }
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
const EMPTY: Entry = { result: null, loading: false, inFlight: null }
/** The org's live roster (members, pending invites, viewer role). `refresh()` re-reads it. */
export function useOrgRoster(orgId: string | null): {
loading: boolean
result: OrcaProfileOrgMembersListResult | null
refresh: () => void
} {
const entry = useSyncExternalStore(subscribe, () =>
orgId ? (entries.get(orgId) ?? EMPTY) : EMPTY
)
useEffect(() => {
if (orgId) {
void loadOrgRoster(orgId)
}
}, [orgId])
const refresh = useCallback(() => {
if (orgId) {
void loadOrgRoster(orgId)
}
}, [orgId])
return { loading: entry.loading, result: entry.result, refresh }
}
@@ -0,0 +1,257 @@
// Team mutations with optimistic rows: the change shows at once, the row shows a spinner while
// auth confirms, and a failure rolls back with the reason on that row (design review M11/M12).
import { useCallback, useState } from 'react'
import { toast } from 'sonner'
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
import { useTranslate } from '@/i18n/use-translate'
import type {
OrcaOrgMember,
OrcaOrgMembersRoster,
OrcaOrgRole,
OrcaProfileOrgMemberMutationResult
} from '../../../../../shared/orca-profiles'
import type { InviteBatchOutcome } from './TeamInviteComposer'
import type { TeamRowState } from './TeamMemberList'
import { mutationFailureCopy } from './team-copy'
import { roleLabel } from './team-roles'
type Overlay = (roster: OrcaOrgMembersRoster) => OrcaOrgMembersRoster
const memberKey = (member: OrcaOrgMember): string =>
`member:${member.userId ?? member.email.toLowerCase()}`
const inviteKey = (email: string): string => `invite:${email.toLowerCase()}`
async function settle(
call: () => Promise<OrcaProfileOrgMemberMutationResult>
): Promise<OrcaProfileOrgMemberMutationResult> {
return call().catch((error: unknown) => ({ status: 'failed' as const, error: String(error) }))
}
export function useTeamActions({
orgId,
onChanged
}: {
orgId: string
/** Re-read roster and billing quietly after a confirmed change. */
onChanged: () => void
}) {
const t = useTranslate()
const confirm = useConfirmationDialog()
const api = window.api.orcaProfiles
const [overlays, setOverlays] = useState<{ id: number; apply: Overlay }[]>([])
const [rowStates, setRowStates] = useState<Record<string, TeamRowState>>({})
const setRow = useCallback((key: string, state: TeamRowState | null) => {
setRowStates(({ [key]: _old, ...rest }) => (state ? { ...rest, [key]: state } : rest))
}, [])
/** Applies `overlay` now, runs `call`, and keeps or rolls back the overlay by the outcome. */
const optimistic = useCallback(
async (
key: string,
overlay: Overlay | null,
call: () => Promise<OrcaProfileOrgMemberMutationResult>
): Promise<OrcaProfileOrgMemberMutationResult> => {
const id = Math.random()
if (overlay) {
setOverlays((list) => [...list, { id, apply: overlay }])
}
setRow(key, { busy: true })
const outcome = await settle(call)
if (outcome.status === 'ok') {
setRow(key, null)
onChanged()
// The refreshed roster carries the change; drop the overlay once it has had time to land.
window.setTimeout(
() => setOverlays((list) => list.filter((entry) => entry.id !== id)),
4_000
)
} else {
setOverlays((list) => list.filter((entry) => entry.id !== id))
setRow(key, { error: mutationFailureCopy(outcome, t) ?? undefined })
}
return outcome
},
[onChanged, setRow, t]
)
const applyOverlays = useCallback(
(roster: OrcaOrgMembersRoster): OrcaOrgMembersRoster =>
overlays.reduce((current, overlay) => overlay.apply(current), roster),
[overlays]
)
const changeRole = (member: OrcaOrgMember, role: OrcaOrgRole, undoable = true): void => {
const userId = member.userId
if (!userId) {
return
}
const previous = member.role
void optimistic(
memberKey(member),
(roster) => ({
...roster,
members: roster.members.map((m) => (m.userId === userId ? { ...m, role } : m))
}),
() => api.orgMemberChangeRole({ orgId, userId, role })
).then((outcome) => {
if (outcome.status === 'ok' && undoable) {
toast.success(
t('auto.components.billing.team.roleToast', '{{value0}} is now {{value1}}', {
value0: member.displayName ?? member.email,
value1: roleLabel(role, t).toLowerCase()
}),
{
action: {
label: t('auto.components.billing.team.undo', 'Undo'),
onClick: () => changeRole({ ...member, role }, previous, false)
}
}
)
}
})
}
const invite = async (emails: string[], role: OrcaOrgRole): Promise<InviteBatchOutcome> => {
const now = Date.now()
const failed: InviteBatchOutcome['failed'] = []
// Sequential: auth rate-limits member changes per actor, and order keeps errors readable.
for (const email of emails) {
const outcome = await optimistic(
inviteKey(email),
(roster) =>
roster.pendingInvites.some((i) => i.email.toLowerCase() === email.toLowerCase())
? roster
: {
...roster,
pendingInvites: [...roster.pendingInvites, { email, role, createdAt: now }]
},
() => api.orgMemberInvite({ orgId, email, role })
)
if (outcome.status !== 'ok') {
setRow(inviteKey(email), null)
failed.push({ email, message: mutationFailureCopy(outcome, t) ?? '' })
if (outcome.status === 'rate-limited') {
for (const rest of emails.slice(emails.indexOf(email) + 1)) {
failed.push({ email: rest, message: mutationFailureCopy(outcome, t) ?? '' })
}
break
}
}
}
const sent = emails.length - failed.length
if (sent > 0) {
toast.success(
sent === 1
? t('auto.components.billing.team.inviteSentOne', 'Invite sent to {{value0}}', {
value0: emails.find((email) => !failed.some((f) => f.email === email)) ?? ''
})
: t('auto.components.billing.team.inviteSentMany', '{{value0}} invites sent', {
value0: String(sent)
}),
{
description: t(
'auto.components.billing.team.inviteSentBody',
'They join, and take a seat, when they accept.'
)
}
)
}
return { failed }
}
const revoke = (email: string, role: OrcaOrgRole): void => {
void optimistic(
inviteKey(email),
(roster) => ({
...roster,
pendingInvites: roster.pendingInvites.filter(
(i) => i.email.toLowerCase() !== email.toLowerCase()
)
}),
() => api.orgInviteRevoke({ orgId, email })
).then((outcome) => {
if (outcome.status === 'ok') {
toast.success(
t('auto.components.billing.team.revokedToast', 'Invite to {{value0}} revoked', {
value0: email
}),
{
action: {
label: t('auto.components.billing.team.undo', 'Undo'),
onClick: () => void invite([email], role)
}
}
)
}
})
}
const resend = (email: string, role: OrcaOrgRole): void => {
void optimistic(inviteKey(email), null, () => api.orgInviteResend({ orgId, email, role })).then(
(outcome) => {
if (outcome.status === 'ok') {
toast.success(
t('auto.components.billing.team.resentToast', 'New invite sent to {{value0}}', {
value0: email
})
)
}
}
)
}
const remove = (member: OrcaOrgMember): void => {
const userId = member.userId
if (!userId) {
return
}
const name = member.displayName ?? member.email
void confirm({
title: t('auto.components.billing.team.removeTitle', 'Remove {{value0}}?', { value0: name }),
description: t(
'auto.components.billing.team.removeDescription3',
'{{value0}} loses access to the team’s cloud workspaces and secrets right away. Their seat stays paid until your plan renews, and inviting them back before then is free.',
{ value0: name }
),
confirmLabel: t('auto.components.billing.team.removeConfirm', 'Remove member'),
confirmVariant: 'destructive'
}).then((accepted) => {
if (!accepted) {
return
}
void optimistic(
memberKey(member),
(roster) => ({ ...roster, members: roster.members.filter((m) => m.userId !== userId) }),
() => api.orgMemberRemove({ orgId, userId })
).then((outcome) => {
if (outcome.status === 'ok') {
toast.success(
t('auto.components.billing.team.removedToast', '{{value0}} removed', { value0: name })
)
}
})
})
}
const makeOwner = (member: OrcaOrgMember): void => {
const name = member.displayName ?? member.email
void confirm({
title: t('auto.components.billing.team.makeOwnerTitle', 'Make {{value0}} an owner?', {
value0: name
}),
description: t(
'auto.components.billing.team.makeOwnerBody',
'Owners control billing and can manage other owners. To hand the team over, make {{value0}} an owner, then ask them to change your role.',
{ value0: name }
),
confirmLabel: t('auto.components.billing.team.makeOwnerConfirm', 'Make owner')
}).then((accepted) => {
if (accepted) {
changeRole(member, 'owner')
}
})
}
return { rowStates, applyOverlays, changeRole, invite, revoke, resend, remove, makeOwner }
}
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing'
import { recordBillingStatus } from './billing-summary-store'
type BillingStatusState = {
loading: boolean
@@ -37,6 +38,7 @@ export function useOrcaBillingStatus(
setState((previous) => ({ ...previous, loading: true }))
void readBillingStatus().then((result) => {
// A newer request, or unmounting, supersedes this one.
recordBillingStatus(result)
if (!disposed && request === latest) {
setState({ loading: false, result })
}
@@ -1,5 +1,7 @@
import React from 'react'
import { Box, Boxes, ChevronDown, Network, Plus, Server } from 'lucide-react'
import { Box, Boxes, ChevronDown, Network, Plus, Server, Sparkles } from 'lucide-react'
import { useBillingSummary } from '@/components/billing/billing-summary-store'
import { openPlansPage } from '@/components/billing/plans/plans-page-store'
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { useTranslate } from '@/i18n/use-translate'
@@ -53,6 +55,7 @@ export function RecipesSubmenuRow({
onSelectRecipe: (recipeId: string) => void
}): React.JSX.Element {
const t = useTranslate()
const billing = useBillingSummary()
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverAnchor asChild>
@@ -84,17 +87,46 @@ export function RecipesSubmenuRow({
<div id={submenuArm.listId} role="listbox" aria-label={getEphemeralVmLabel(t)}>
{recipes.map((recipe) => {
const key = getRecipeSubmenuItemKey(recipe.id)
// Orca Cloud without a plan: the row explains and leads to plans instead of failing later.
const needsPlan = recipe.provider === 'orca-cloud' && billing.subscribed === false
return (
<RunTargetRow
key={recipe.id}
icon={<Box className="size-3.5 shrink-0 text-muted-foreground" />}
label={recipe.name}
detail={getRecipeDetail(recipe, t)}
detail={
needsPlan
? billing.canManageBilling
? t(
'auto.components.NewWorkspaceComposerCard.orcaCloudUpgrade',
'Upgrade to run agents in the cloud'
)
: t(
'auto.components.NewWorkspaceComposerCard.orcaCloudAskAdmin',
'Needs a plan. Ask an owner or admin to upgrade.'
)
: getRecipeDetail(recipe, t)
}
armed={submenuArm.armedItemKey === key}
current={recipe.id === selectedRecipeId}
optionId={itemId(submenuArm, key)}
onArm={() => submenuArm.onArmItem(key)}
onCommit={() => onSelectRecipe(recipe.id)}
onCommit={() => {
if (needsPlan) {
onOpenChange(false)
openPlansPage('run-on')
} else {
onSelectRecipe(recipe.id)
}
}}
trailing={
needsPlan ? (
<span className="ml-auto inline-flex shrink-0 items-center gap-1 self-center rounded-full border border-border bg-background px-1.5 py-px text-[10px] font-medium text-foreground">
<Sparkles className="size-2.5" />
{t('auto.components.NewWorkspaceComposerCard.upgradePill', 'Upgrade')}
</span>
) : undefined
}
/>
)
})}
@@ -10,7 +10,7 @@ import { useAppStore } from '@/store/index'
import { OrcaProfileSignOutConfirmDialog } from '../../../orca-profiles/OrcaProfileSignOutConfirmDialog'
import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress'
import { PlanBillingSection } from '../../../billing/PlanBillingSection'
import { TeamMembersSection } from '../../../billing/team/TeamMembersSection'
import { TeamSettingsLink } from '../../../billing/team/TeamSettingsLink'
function accountStatusCopy(
state: 'local' | 'unconfigured' | 'connected' | 'reconnect-required' | undefined,
@@ -131,10 +131,10 @@ export function OrcaAccountSettingsPane(): React.JSX.Element {
</div>
{connected ? <PlanBillingSection /> : null}
{connected && authStatus?.cloud?.activeOrgId ? (
<TeamMembersSection
orgId={authStatus.cloud.activeOrgId}
viewerUserId={authStatus.cloud.userId}
{connected && authStatus?.capabilities?.flags?.billing ? (
<TeamSettingsLink
orgId={authStatus.cloud?.activeOrgId ?? null}
orgName={authStatus.cloud?.activeOrgName ?? null}
/>
) : null}
@@ -1,6 +1,9 @@
import { defineFixture } from '../../component-fixtures/component-fixture'
import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles'
import SidebarToolbar from './SidebarToolbar'
import { registerPlanBillingMenuItem } from '../billing/register-plan-billing-menu-item'
import { recordBillingStatus } from '../billing/billing-summary-store'
import { sampleTeam } from '../billing/plan-billing-fixtures'
const settle = (ms = 300): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
@@ -35,6 +38,26 @@ const signedIn: OrcaProfileAuthStatus = {
}
}
const signedInWithBilling: OrcaProfileAuthStatus = {
...signedIn,
cloud: { ...signedIn.cloud!, activeOrgId: 'org-acme', activeOrgName: 'Acme' },
capabilities: { flags: { billing: true }, refreshedAt: 0 }
}
/** Registers the billing items as main.tsx does, with a known plan state. */
const withBilling = (subscribed: boolean) => (): void => {
const result = {
status: 'ok' as const,
entitlement: subscribed
? sampleTeam
: { ...sampleTeam, plan: null, planLabel: null, status: 'none' }
}
// The registration re-reads billing when the account changes; answer like the service would.
window.api.orcaProfiles.billingStatus = async () => result
registerPlanBillingMenuItem()
recordBillingStatus(result)
}
const signedOut: OrcaProfileAuthStatus = {
activeProfileId: 'local-default',
configured: true,
@@ -46,17 +69,20 @@ const footer = ({
width = 303,
height = 96,
authStatus = signedOut,
interact
interact,
setup
}: {
width?: number
height?: number
authStatus?: OrcaProfileAuthStatus
interact?: (frame: HTMLElement) => Promise<void>
setup?: () => void
}) =>
defineFixture({
width,
store: { persistedUIReady: true, orcaProfileAuthStatus: authStatus },
interact,
setup,
render: () => (
<div
style={{ height }}
@@ -78,3 +104,15 @@ export const helpSubmenu = footer({
authStatus: signedIn,
interact: openHelpSubmenu
})
export const signedInMenuNoPlan = footer({
height: 340,
authStatus: signedInWithBilling,
setup: withBilling(false),
interact: openAccountMenu
})
export const signedInMenuOnTeam = footer({
height: 320,
authStatus: signedInWithBilling,
setup: withBilling(true),
interact: openAccountMenu
})
@@ -186,9 +186,15 @@ export function SidebarAccountMenu(): React.JSX.Element {
<DropdownMenuItem
key={item.id}
data-account-menu-item={item.id}
data-tone={item.tone}
onSelect={item.onSelect}
className={cn(item.tone === 'accent' && 'font-medium text-foreground')}
>
{Icon ? <Icon className="size-3.5" /> : null}
{Icon ? (
<Icon
className={cn('size-3.5', item.tone === 'accent' && 'text-foreground')}
/>
) : null}
{item.label()}
</DropdownMenuItem>
)
@@ -12,6 +12,8 @@ export type AccountMenuItem = {
order?: number
/** Hide the item unless the signed-in account reports this capability flag as true. */
requiredCapability?: string
/** 'accent' marks a call to action (e.g. upgrade); default rows stay neutral. */
tone?: 'accent'
onSelect: () => void
}
+21
View File
@@ -209,6 +209,27 @@
"tokensAndCost_other": "{{tokens}} tokens · {{cost}}"
}
},
"billing": {
"team": {
"askAdmin": "Only owners and admins can invite or remove members.",
"cannotChangeOwnRole": "You cannot change your own role.",
"cannotRemoveSelf": "You cannot remove yourself.",
"invite": "Invite",
"inviteEmail": "Email to invite",
"invitePlaceholder": "teammate@company.com",
"invited": "Invite sent to {{value0}}. They join (and become a billed seat) when they accept.",
"memberCount": "{{value0}} members",
"memberSeats": "{{value0}} members · {{value1}} seats billed. Seats follow membership; pending invites are free until accepted.",
"pending": "Pending invites",
"remove": "Remove {{value0}}",
"removeDescription2": "They lose access to the org right away. Their seat stays paid until your plan renews, then drops off.",
"removed": "Member removed.",
"revoke": "Revoke",
"revoked": "Invite revoked.",
"roleChanged": "Role updated.",
"seatsDrop": "Seats paid this period stay until {{value0}}, then drop to {{value1}}."
}
},
"browser-pane": {
"markup": {
"errorAttach": "Could not attach the markup screenshot.",