Merge remote-tracking branch 'private/cloud/integration' into cloud/w2-ja15

# Conflicts:
#	src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts
This commit is contained in:
Neil
2026-11-10 22:25:47 -08:00
123 changed files with 5647 additions and 700 deletions
+15
View File
@@ -7,6 +7,7 @@
// POST /v1/billing/portal -> { url } Stripe Customer Portal
// POST /v1/billing/team-plans {orgIds} other teams' plan state ("Switch to <team>"), read-only
// POST /v1/billing/trial claim the team's one-time trial -> entitlement (trial.ts)
// GET /v1/billing/usage?utcOffset= 30 days of sandbox hours; top members/sandboxes for admins
// Stripe:
// POST /v1/stripe/webhook signed events
// Sandbox control plane (CONTROL_PLANE_TOKEN):
@@ -50,6 +51,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 { UsageHistoryQuerySchema, usageHistory } from './usage-history'
import { renderReturnPage, returnOutcome } from './return-page'
import {
BindTeamSchema,
@@ -316,6 +318,19 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
return json(await desktopEntitlement(env, caller, request, now))
}
case 'GET /v1/billing/usage': {
// Any member reads the team's daily hours and their own; the breakdown is owners/admins only.
const caller = await authenticateDesktop(env, request)
if (!caller) {
return json({ error: 'unauthorized' }, 401)
}
const query = UsageHistoryQuerySchema.safeParse(Object.fromEntries(url.searchParams))
if (!query.success) {
return json({ error: 'invalid_request' }, 400)
}
return json(await usageHistory(env.BILLING_DB, caller, now, query.data.utcOffset))
}
case 'POST /v1/billing/trial': {
// Any member may start the team's trial the first time they pick Orca Cloud (spec B1).
const caller = await authenticateDesktop(env, request)
+50 -4
View File
@@ -2,14 +2,23 @@
// Opting in puts exactly one metered overage item, at STRIPE_PRICE_OVERAGE, on the Stripe
// subscription: an item still on an older overage price is moved to the current one rather than a
// second added (two items on the same meter would bill the same seconds twice). Opting out stops
// metering immediately but leaves the item, so usage already reported is still invoiced.
// metering immediately. The item is removed once it has nothing left to invoice (no meter report
// this Stripe period): at once if none was sent, otherwise at a sync after the period rolls over,
// so usage already reported is still invoiced and no $0 overage line is left on later invoices.
import { z } from 'zod'
import type { BillingCaller } from './auth'
import { OPEN_STATUSES } from './checkout'
import type { Env } from './env'
import { planCatalog, planForPrice } from './plans'
import type { StripeClient, StripeSubscription } from './stripe'
import { accountSettings, currentSubscription, setOverageSettings, upsertSubscription, type SubscriptionRow } from './store'
import {
accountSettings,
currentSubscription,
meterReportsSince,
setOverageSettings,
upsertSubscription,
type SubscriptionRow
} from './store'
export const OverageRequestSchema = z
.object({
@@ -51,9 +60,35 @@ export async function updateOverage(
? (await accountSettings(env.BILLING_DB, caller.accountId)).spend_cap_cents
: request.spendCapCents
await setOverageSettings(env.BILLING_DB, caller.accountId, { optIn: request.enabled, spendCapCents }, now)
if (!request.enabled) {
// Best effort: the opt-out already stops metering; a failed removal is retried by the next sync.
await retireOverageItem(env, stripe, subscription, now).catch((error: unknown) => {
console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' }))
})
}
return { ok: true }
}
/**
* Removes an opted-out account's overage item once nothing on it is left to invoice: no meter
* report (sent or pending) since the Stripe period began. Returns whether it removed one.
*/
export async function retireOverageItem(env: Env, stripe: StripeClient, subscription: SubscriptionRow, now: number): Promise<boolean> {
if (!subscription.overage_item_id) {
return false
}
const settings = await accountSettings(env.BILLING_DB, subscription.account_id)
if (settings.overage_opt_in === 1) {
return false
}
if ((await meterReportsSince(env.BILLING_DB, subscription.account_id, subscription.current_period_start)) > 0) {
return false
}
await stripe.deleteSubscriptionItem(subscription.overage_item_id)
await upsertSubscription(env.BILLING_DB, { ...subscription, overage_enabled: 0, overage_item_id: null, updated_at: now })
return true
}
/** A metered item that is not a seat price and not the current overage price: an older overage price. */
function isStaleOverageItem(env: Env, item: StripeSubscription['items']['data'][number]): boolean {
return (
@@ -84,6 +119,17 @@ async function ensureOverageItem(env: Env, stripe: StripeClient, subscription: S
}
return replace.id
}
// Idempotent per subscription+price, so a retried opt-in cannot add a second item.
return (await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE })).id
// Idempotent per subscription+price, so a retried opt-in cannot add a second item. Opting out
// can remove the item, so a later opt-in may get the removed item's id replayed (Stripe keeps
// idempotent answers for 24 hours): then add again under a key that names the removed item.
let after: string | undefined
for (let attempt = 0; attempt < 3; attempt++) {
const added = await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE, after })
const fresh = await stripe.retrieveSubscription(subscription.stripe_subscription_id)
if (fresh.items.data.some((item) => item.id === added.id)) {
return added.id
}
after = added.id
}
throw new Error('overage_item_replayed')
}
+12
View File
@@ -220,6 +220,18 @@ export async function insertUsage(db: D1Database, usage: UsageInsert): Promise<b
return (result?.meta.changes ?? 0) > 0
}
/** Meter reports (any status) for usage that ended since `since`, plus any still pending. */
export async function meterReportsSince(db: D1Database, accountId: string, since: number): Promise<number> {
const row = await db
.prepare(
`SELECT COUNT(*) AS n FROM meter_reports m JOIN usage_events p ON p.usage_id = m.usage_id
WHERE p.account_id = ?1 AND (m.event_timestamp >= ?2 OR m.status = 'pending')`
)
.bind(accountId, since)
.first<{ n: number }>()
return row?.n ?? 0
}
/** Overage seconds already metered (billed) in an allowance window. */
export async function meteredSeconds(db: D1Database, accountId: string, windowStart: number): Promise<number> {
const row = await db
+3 -2
View File
@@ -143,13 +143,14 @@ export function createStripeClient(env: Env, fetchImpl: typeof fetch = fetch) {
idempotencyKey
)
},
addSubscriptionItem(args: { subscription: string; price: string }) {
/** `after`: the id a replayed add returned for an item since removed, so this add is a new one. */
addSubscriptionItem(args: { subscription: string; price: string; after?: string }) {
return request<{ id: string }>(
'POST',
'/v1/subscription_items',
// Metered: nothing to prorate; usage is billed in arrears.
{ subscription: args.subscription, price: args.price, proration_behavior: 'none' },
`overage-item:${args.subscription}:${args.price}`
`overage-item:${args.subscription}:${args.price}${args.after ? `:after:${args.after}` : ''}`
)
},
/** Moves an item to another price in place (an older overage price to the current one). */
+103
View File
@@ -0,0 +1,103 @@
// Usage history for Plan & billing: sandbox hours per day for the last 30 days, the caller's own
// share, and (for owners and admins only) the top members and sandboxes. Read-only over
// usage_events; hours are the same weighted seconds the included-hours meter counts. A segment
// counts on the day it ended, as it counts in the allowance window it ended in.
import { z } from 'zod'
import type { BillingCaller } from './auth'
export const USAGE_HISTORY_DAYS = 30
export const USAGE_HISTORY_TOP = 5
const DAY_MS = 24 * 3600 * 1000
/** `utcOffset`: the viewer's minutes east of UTC, so days start at their local midnight. */
export const UsageHistoryQuerySchema = z.object({
utcOffset: z.coerce.number().int().min(-840).max(840).default(0)
})
export type UsageHistoryTop<K extends string> = {
top: Array<{ [key in K]: string } & { seconds: number }>
/** Everyone (or everything) past the top entries, plus segments with no member recorded. */
otherCount: number
otherSeconds: number
}
export type UsageHistory = {
/** Oldest first, exactly USAGE_HISTORY_DAYS entries; `start` is the local midnight in epoch ms. */
days: Array<{ start: number; seconds: number }>
totalSeconds: number
/** The caller's own sandbox hours in the same days. */
yourSeconds: number
/** Owners and admins only; null for members. */
members: UsageHistoryTop<'userId'> | null
sandboxes: UsageHistoryTop<'sandboxId'> | null
}
/** Epoch ms of the local midnight that starts the oldest day shown. */
export function usageHistoryStart(now: number, utcOffsetMinutes: number): number {
const offset = utcOffsetMinutes * 60_000
const today = Math.floor((now + offset) / DAY_MS) * DAY_MS - offset
return today - (USAGE_HISTORY_DAYS - 1) * DAY_MS
}
function topOf<K extends string>(
key: K,
rows: Array<{ id: string | null; seconds: number }>
): UsageHistoryTop<K> {
const named = rows.filter((row) => row.id !== null).sort((a, b) => b.seconds - a.seconds)
const top = named.slice(0, USAGE_HISTORY_TOP)
const rest = [...named.slice(USAGE_HISTORY_TOP), ...rows.filter((row) => row.id === null)]
return {
top: top.map((row) => ({ [key]: row.id, seconds: row.seconds }) as { [k in K]: string } & { seconds: number }),
otherCount: rest.filter((row) => row.id !== null).length,
otherSeconds: rest.reduce((sum, row) => sum + row.seconds, 0)
}
}
export async function usageHistory(
db: D1Database,
caller: BillingCaller,
now: number,
utcOffsetMinutes: number
): Promise<UsageHistory> {
const start = usageHistoryStart(now, utcOffsetMinutes)
const range = 'account_id = ?1 AND ended_at >= ?2 AND ended_at <= ?3'
const [byDay, mine, byMember, bySandbox] = await Promise.all([
db
.prepare(
`SELECT CAST((ended_at - ?2) / ${DAY_MS} AS INTEGER) AS day, SUM(weighted_seconds) AS seconds
FROM usage_events WHERE ${range} GROUP BY day`
)
.bind(caller.accountId, start, now)
.all<{ day: number; seconds: number }>(),
db
.prepare(`SELECT COALESCE(SUM(weighted_seconds), 0) AS seconds FROM usage_events WHERE ${range} AND user_id = ?4`)
.bind(caller.accountId, start, now, caller.userId)
.first<{ seconds: number }>(),
caller.canManage
? db
.prepare(`SELECT user_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY user_id`)
.bind(caller.accountId, start, now)
.all<{ id: string | null; seconds: number }>()
: null,
caller.canManage
? db
.prepare(`SELECT sandbox_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY sandbox_id`)
.bind(caller.accountId, start, now)
.all<{ id: string; seconds: number }>()
: null
])
const days = Array.from({ length: USAGE_HISTORY_DAYS }, (_, index) => ({ start: start + index * DAY_MS, seconds: 0 }))
for (const row of byDay.results) {
const day = days[row.day]
if (day) {
day.seconds += row.seconds
}
}
return {
days,
totalSeconds: days.reduce((sum, day) => sum + day.seconds, 0),
yourSeconds: mine?.seconds ?? 0,
members: byMember ? topOf('userId', byMember.results) : null,
sandboxes: bySandbox ? topOf('sandboxId', bySandbox.results) : null
}
}
+11 -1
View File
@@ -3,7 +3,8 @@
import type { Env } from './env'
import { planForPrice } from './plans'
import { allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe'
import { accountForCustomer, claimEvent, customerFor, finishEvent, upsertSubscription } from './store'
import { accountForCustomer, claimEvent, currentSubscription, customerFor, finishEvent, upsertSubscription } from './store'
import { retireOverageItem } from './overage'
import { splitSecrets, verifyStripeSignature } from './webhook-signature'
const MAX_BODY_BYTES = 512 * 1024
@@ -112,6 +113,15 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript
// Membership comes from auth, not Stripe: keep the stored count.
member_count: null
})
if (overageItemId) {
// An opted-out account's overage item goes once the period it was used in has been invoiced.
const stored = await currentSubscription(db, accountId)
if (stored?.stripe_subscription_id === subscription.id) {
await retireOverageItem(env, stripe, stored, now).catch((error: unknown) => {
console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' }))
})
}
}
}
export async function handleStripeWebhook(env: Env, stripe: StripeClient, request: Request, now: number): Promise<Response> {
@@ -0,0 +1,97 @@
// Opting out of overage: nothing more is metered or billed, and the metered item comes off the
// subscription once nothing on it is left to invoice (no $0 overage line on later invoices).
import { describe, expect, it } from 'vitest'
import { checkoutCompleted, stripeEvent } from './stripe-fake'
import { createHarness } from './harness'
const HOUR = 3600
const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR
const PERIOD_END = PERIOD_START + 30 * 24 * HOUR
async function optedInTeam() {
const h = await createHarness()
const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' })
const auth = { authorization: `Bearer ${token}` }
await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth })
const customer = [...h.stripe.customers.keys()][0]!
const subscription = h.stripe.putSubscription({
customer,
accountId: 'org:o1',
basePrice: 'price_team_month',
quantity: 2,
periodStart: PERIOD_START,
periodEnd: PERIOD_END
})
await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' }))
const overage = (body: unknown) => h.call('POST', '/v1/billing/overage', { body, headers: auth })
expect((await overage({ enabled: true })).status).toBe(200)
const prices = () => subscription.items.data.map((item) => item.price.id)
expect(prices()).toEqual(['price_team_month', 'price_overage'])
let n = 0
const use = (hours: number) => {
const endedAt = Date.now() - 60_000
return h.controlPlane('/v1/internal/usage', {
usageId: `u-${n++}`,
accountId: 'org:o1',
sandboxId: 'sbx_1',
machineSize: 'standard',
startedAt: endedAt - hours * HOUR * 1000,
endedAt
})
}
const stored = () =>
h.raw.prepare('SELECT overage_enabled, overage_item_id IS NOT NULL AS has_item FROM subscriptions').get()
return { h, auth, subscription, overage, prices, use, stored }
}
describe('overage opt-out', () => {
it('removes the unused metered item at once, and opting back in adds it again', async () => {
const { h, overage, prices, use, stored } = await optedInTeam()
expect((await overage({ enabled: false })).status).toBe(200)
expect(prices()).toEqual(['price_team_month'])
expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 })
// Past the included hours with overage off: nothing is metered.
for (let i = 0; i < 6; i++) {
await use(24)
}
expect(h.stripe.meterEvents).toHaveLength(0)
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 })
expect((await overage({ enabled: true })).status).toBe(200)
expect(prices()).toEqual(['price_team_month', 'price_overage'])
})
it('a $0 cap never meters, even with overage on', async () => {
const { h, overage, use } = await optedInTeam()
expect((await overage({ enabled: true, spendCapCents: 0 })).status).toBe(200)
for (let i = 0; i < 6; i++) {
await use(24)
}
expect(h.stripe.meterEvents).toHaveLength(0)
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 })
})
it('keeps an item with usage to invoice until the period rolls over, then removes it', async () => {
const { h, overage, prices, use, stored, subscription } = await optedInTeam()
for (let i = 0; i < 5; i++) {
await use(24)
}
await use(2)
expect(h.stripe.meterEvents).toHaveLength(1)
expect((await overage({ enabled: false })).status).toBe(200)
// The 2 overage hours still have to be invoiced on this item.
expect(prices()).toEqual(['price_team_month', 'price_overage'])
await use(3)
expect(h.stripe.meterEvents).toHaveLength(1)
// A sync inside the same period keeps it.
await h.webhook(stripeEvent('customer.subscription.updated', subscription))
expect(prices()).toEqual(['price_team_month', 'price_overage'])
// Renewal: the next period has nothing metered, so the sync takes the item off.
for (const item of subscription.items.data) {
item.current_period_start = PERIOD_END
item.current_period_end = PERIOD_END + 30 * 24 * HOUR
}
await h.webhook(stripeEvent('customer.subscription.updated', subscription))
expect(prices()).toEqual(['price_team_month'])
expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 })
})
})
@@ -0,0 +1,98 @@
import { describe, expect, it } from 'vitest'
import { createHarness } from './harness'
import { USAGE_HISTORY_DAYS, usageHistoryStart } from '../src/usage-history'
const HOUR = 3600
const DAY_MS = 24 * 3600 * 1000
// Tokens are checked against the real clock, so the fixture's "now" is real too.
const NOW = Date.now()
const utcMidnight = Math.floor(NOW / DAY_MS) * DAY_MS
// Today's segment, kept inside today even just after midnight.
const END = Math.max(utcMidnight, NOW - 60_000)
async function seeded() {
const h = await createHarness()
h.setNow(NOW)
const insert = h.raw.prepare(
`INSERT INTO usage_events (usage_id, account_id, sandbox_id, machine_size, started_at, ended_at, weighted_seconds,
period_start, overage_seconds, created_at, user_id) VALUES (?, ?, ?, 'standard', ?, ?, ?, NULL, 0, ?, ?)`
)
let n = 0
const add = (endedAt: number, hours: number, sandboxId: string, userId: string | null, account = 'org:o1') => {
insert.run(`u${n++}`, account, sandboxId, endedAt - 60_000, endedAt, hours * HOUR, endedAt, userId)
}
add(END, 2, 'sbx_a', 'alice')
add(END - DAY_MS, 1, 'sbx_b', 'bob')
add(END - 3 * DAY_MS, 3, 'sbx_a', 'alice')
// Six more members, half an hour each: three make the top five, three don't.
for (const user of ['c', 'd', 'e', 'f', 'g', 'h']) {
add(END - 5 * DAY_MS, 0.5, `sbx_${user}`, user)
}
// A segment from before members were recorded.
add(END - 6 * DAY_MS, 0.25, 'sbx_old', null)
// Outside the 30 days, and another team's: never counted.
add(NOW - 31 * DAY_MS, 9, 'sbx_a', 'alice')
add(NOW - DAY_MS, 9, 'sbx_z', 'zed', 'org:o2')
return h
}
async function read(h: Awaited<ReturnType<typeof seeded>>, role: string, sub = 'alice', query = '') {
const token = await h.desktopToken({ sub, org: 'o1', orgRole: role })
return h.call('GET', `/v1/billing/usage${query}`, { headers: { authorization: `Bearer ${token}` } })
}
describe('GET /v1/billing/usage', () => {
it('returns 30 local days of team hours and the owner/admin breakdown', async () => {
const h = await seeded()
const { status, body } = await read(h, 'owner')
expect(status).toBe(200)
expect(body.days).toHaveLength(USAGE_HISTORY_DAYS)
expect(body.days.at(-1)).toEqual({ start: utcMidnight, seconds: 2 * HOUR })
expect(body.days.at(-2).seconds).toBe(1 * HOUR)
expect(body.days.at(-4).seconds).toBe(3 * HOUR)
expect(body.totalSeconds).toBe(9.25 * HOUR)
expect(body.yourSeconds).toBe(5 * HOUR)
expect(body.members.top.map((m: { userId: string }) => m.userId).slice(0, 2)).toEqual(['alice', 'bob'])
expect(body.members.top).toHaveLength(5)
expect(body.members.otherCount).toBe(3)
// Three members past the top five (1.5 hours) plus the unattributed quarter hour.
expect(body.members.otherSeconds).toBe(1.75 * HOUR)
expect(body.sandboxes.top[0]).toEqual({ sandboxId: 'sbx_a', seconds: 5 * HOUR })
})
it('gives members the team chart and their own hours, never the breakdown', async () => {
const h = await seeded()
const { body } = await read(h, 'member', 'bob')
expect(body.totalSeconds).toBe(9.25 * HOUR)
expect(body.yourSeconds).toBe(1 * HOUR)
expect(body.members).toBeNull()
expect(body.sandboxes).toBeNull()
})
it('starts days at the viewer’s local midnight', async () => {
const h = await seeded()
const { body } = await read(h, 'admin', 'alice', '?utcOffset=-480')
// In UTC-8 a day starts at 08:00 UTC.
const today = body.days.at(-1).start
expect(new Date(today).getUTCHours()).toBe(8)
expect(today).toBeLessThanOrEqual(NOW)
expect(NOW - today).toBeLessThan(DAY_MS)
expect(body.days[0].start).toBe(usageHistoryStart(NOW, -480))
})
it('rejects a bad offset and an unsigned caller', async () => {
const h = await seeded()
expect((await read(h, 'owner', 'alice', '?utcOffset=9999')).status).toBe(400)
expect((await h.call('GET', '/v1/billing/usage')).status).toBe(401)
})
it('returns zeroed days for a team with no usage', async () => {
const h = await createHarness()
h.setNow(NOW)
const token = await h.desktopToken({ sub: 'u1', org: 'o9', orgRole: 'owner' })
const { body } = await h.call('GET', '/v1/billing/usage', { headers: { authorization: `Bearer ${token}` } })
expect(body.totalSeconds).toBe(0)
expect(body.days.every((day: { seconds: number }) => day.seconds === 0)).toBe(true)
expect(body.members).toEqual({ top: [], otherCount: 0, otherSeconds: 0 })
})
})
@@ -0,0 +1,40 @@
-- G14: every cloud workspace gets a short number in its account (W-123), allocated from a per-account
-- counter so a number is never reused, even after the row is destroyed. Orgs get a URL slug for links
-- (orca://cloud/<slug>/W-123). G13: each member's sidebar prefs for cloud workspaces (pins, their
-- order, and the order of sections) live on the account so every device shows the same sidebar.
ALTER TABLE sandboxes ADD COLUMN number INTEGER;
-- Backfill: existing rows numbered by creation order within their account.
UPDATE sandboxes SET number = (
SELECT COUNT(*) FROM sandboxes AS earlier
WHERE earlier.account_id = sandboxes.account_id
AND (earlier.created_at < sandboxes.created_at OR (earlier.created_at = sandboxes.created_at AND earlier.id <= sandboxes.id))
);
CREATE UNIQUE INDEX sandboxes_account_number ON sandboxes (account_id, number) WHERE number IS NOT NULL;
CREATE TABLE org_workspace_counters (
account_id TEXT PRIMARY KEY,
last_number INTEGER NOT NULL
);
INSERT INTO org_workspace_counters (account_id, last_number)
SELECT account_id, MAX(number) FROM sandboxes GROUP BY account_id;
CREATE TABLE org_slugs (
account_id TEXT PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
created_by TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE workspace_prefs (
account_id TEXT NOT NULL,
user_id TEXT NOT NULL,
document TEXT NOT NULL,
revision INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
updated_by_device TEXT,
PRIMARY KEY (account_id, user_id)
);
+6
View File
@@ -132,6 +132,12 @@ export type Env = {
/** Operator routes (/v1/internal/*): kill switch, drain, bindings. Secret, >= 32 chars; unset = no routes. */
OPERATOR_TOKEN?: string
/**
* Auth's bearer for POST /v1/internal/org-members/removed only (PropelAuth offboarding and
* Orca-side removals). Secret, >= 32 chars; lets auth push removals without holding the
* operator token. The operator token is still accepted on that route.
*/
MEMBER_REMOVED_TOKEN?: string
/** `true` refuses every create/resume/rollover (static kill switch; the D1 flag is the runtime one). */
SANDBOX_CREATES_DISABLED?: string
/** Warm pool size (pool.ts); unset or 0 = off. */
+39 -3
View File
@@ -25,7 +25,8 @@
// POST /v1/device-sessions | GET | DELETE /:id per-phone access (see device-sessions.ts)
// Phones sign their own EdDSA tokens (device-sessions.ts) and act as their user, except that they
// cannot enroll devices, manage secrets or connect GitHub.
// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts
// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts,
// /v1/team/prefs (src/workspace-prefs.ts), /v1/team/org (src/org-slugs.ts)
// team workspace registry, presence, per-device grants (src/workspaces.ts, src/grants.ts)
// POST /v1/team/workspaces/:id/wake?wait=30s: any member who can open it wakes it (single-flight,
// billed to the account, counted on the owner's seat like every wake) -> {state, endpoint: null, …}
@@ -191,7 +192,10 @@ import {
userAuthorizeUrl
} from './github-user-tokens'
import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git'
import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs'
import { getOrgSlug, putOrgSlug } from './org-slugs'
import {
LinkOtherOrgError,
PatchSchema,
PresenceSchema,
WORKSPACE_ERROR_STATUS,
@@ -1146,7 +1150,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
return await internalInstallUrl(env, deps, url)
}
if (url.pathname.startsWith('/v1/internal/')) {
if (!(await isOperator(request, env.OPERATOR_TOKEN))) {
// Auth's member-removed push holds a token good for that one route, not the operator token.
const memberRemovedOnly =
url.pathname === '/v1/internal/org-members/removed' &&
request.method === 'POST' &&
(await isOperator(request, env.MEMBER_REMOVED_TOKEN))
if (!memberRemovedOnly && !(await isOperator(request, env.OPERATOR_TOKEN))) {
return fail('not_found', 404)
}
const life = await lifecycleDeps(env, deps)
@@ -1487,6 +1496,8 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
url.pathname.startsWith('/v1/team/workspaces/') ||
url.pathname === '/v1/team/links/resolve' ||
url.pathname === '/v1/team/prompts' ||
url.pathname === '/v1/team/prefs' ||
url.pathname === '/v1/team/org' ||
url.pathname.startsWith('/v1/team/members/') ||
url.pathname === '/v1/team/pokes' ||
url.pathname.startsWith('/v1/team/pokes/')
@@ -1866,7 +1877,32 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
// Labels for teammates' lists; a failure here must never fail the request itself.
await rememberCallerName(db, caller, now).catch((error: unknown) => console.warn('member_name_write_failed', String(error)))
if (url.pathname === '/v1/team/links/resolve' && request.method === 'GET') {
return json(await resolveLink(db, caller, url, now))
try {
return json(await resolveLink(db, caller, url, now))
} catch (error) {
if (error instanceof LinkOtherOrgError) {
return json({ error: 'not_found', reason: 'other_org', orgId: error.orgId }, 404)
}
throw error
}
}
if (url.pathname === '/v1/team/prefs') {
if (request.method === 'GET') {
return json(await getWorkspacePrefs(db, caller))
}
if (request.method === 'PUT') {
return json(await putWorkspacePrefs(db, caller, await readJson(request), now))
}
return fail('not_found', 404)
}
if (url.pathname === '/v1/team/org') {
if (request.method === 'GET') {
return json(await getOrgSlug(db, caller, url, now))
}
if (request.method === 'PUT') {
return json(await putOrgSlug(db, caller, await readJson(request), now))
}
return fail('not_found', 404)
}
if (url.pathname === '/v1/team/prompts') {
if (request.method === 'GET') {
+123
View File
@@ -0,0 +1,123 @@
// Org URL slugs for workspace links (orca://cloud/<slug>/W-123).
// GET /v1/team/org?name=<org display name> -> {slug, orgId}; the first call names it from `name`
// PUT /v1/team/org {slug} org owner/admin renames it (409 when another org has it)
// Auth owns orgs and knows their names; this Worker only sees ids. So the first member to ask
// proposes a slug from the name their client shows, and the Worker makes it unique. Personal
// accounts have no slug: their links keep the sandbox id form (orca://cloud/w/<sbx>).
import { z } from 'zod'
import type { SandboxCaller } from './auth'
import { WorkspaceError, isOrgAdmin } from './workspaces'
/** Path words a slug can't take: they'd read as a different link form. */
const RESERVED = new Set(['w', 'c', 'me', 'api', 'app', 'new', 'org', 'team', 'settings', 'cloud', 'orca', 'admin', 'help', 'setup'])
export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
export function isValidSlug(value: string): boolean {
return SLUG.test(value) && !value.includes('--') && !RESERVED.has(value)
}
/** "Acme Labs, Inc." → "acme-labs-inc"; falls back to "team" when nothing usable is left. */
export function slugify(name: string): string {
const base = name
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 32)
.replace(/-+$/g, '')
return base.length >= 2 && !RESERVED.has(base) ? base : base ? `${base}-team` : 'team'
}
type Row = { account_id: string; slug: string }
/** `org:abc` / `dev:org:abc` → `abc` (the id the desktop's org list uses). */
export function orgIdOf(accountId: string): string | null {
const match = /^(?:dev:)?org:(.+)$/.exec(accountId)
return match ? match[1]! : null
}
export async function slugForAccount(db: D1Database, accountId: string): Promise<string | null> {
const row = await db.prepare('SELECT slug FROM org_slugs WHERE account_id = ?').bind(accountId).first<{ slug: string }>()
return row?.slug ?? null
}
export async function accountForSlug(db: D1Database, slug: string): Promise<string | null> {
if (!isValidSlug(slug)) {
return null
}
const row = await db.prepare('SELECT account_id FROM org_slugs WHERE slug = ?').bind(slug).first<Row>()
return row?.account_id ?? null
}
const NameQuery = z.string().trim().min(1).max(120)
export async function getOrgSlug(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
const orgId = caller.orgId ? orgIdOf(caller.accountId) : null
if (!orgId) {
return { slug: null, orgId: null }
}
const existing = await slugForAccount(db, caller.accountId)
if (existing) {
return { slug: existing, orgId }
}
const name = NameQuery.safeParse(url.searchParams.get('name') ?? '')
if (!name.success) {
// Nothing to name it from yet; the next client that knows the org's name will.
return { slug: null, orgId }
}
const base = slugify(name.data)
for (let attempt = 0; attempt < 20; attempt += 1) {
const candidate = attempt === 0 ? base : `${base.slice(0, 32)}-${attempt + 1}`
const result = await db
.prepare('INSERT OR IGNORE INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)')
.bind(caller.accountId, candidate, now, caller.userId, now)
.run()
if (result.meta.changes === 1) {
return { slug: candidate, orgId }
}
// Either another org holds this slug, or a teammate just named ours (then use theirs).
const raced = await slugForAccount(db, caller.accountId)
if (raced) {
return { slug: raced, orgId }
}
}
throw new WorkspaceError('conflict', 'slug_exhausted')
}
const PutSchema = z.object({ slug: z.string().min(1).max(40) }).strict()
export async function putOrgSlug(db: D1Database, caller: SandboxCaller, body: unknown, now: number) {
const orgId = caller.orgId ? orgIdOf(caller.accountId) : null
if (!orgId) {
throw new WorkspaceError('invalid_request', 'personal_account')
}
if (!isOrgAdmin(caller)) {
throw new WorkspaceError('forbidden', 'admin_only')
}
const parsed = PutSchema.safeParse(body)
if (!parsed.success || !isValidSlug(parsed.data.slug)) {
throw new WorkspaceError('invalid_request', 'invalid_slug')
}
const slug = parsed.data.slug
const holder = await accountForSlug(db, slug)
if (holder && holder !== caller.accountId) {
throw new WorkspaceError('conflict', 'slug_taken')
}
await db
.prepare(
`INSERT INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (account_id) DO UPDATE SET slug = excluded.slug, updated_at = excluded.updated_at`
)
.bind(caller.accountId, slug, now, caller.userId, now)
.run()
.catch((error: unknown) => {
// The UNIQUE index lost a race with another org claiming the same slug.
if (String(error).includes('UNIQUE')) {
throw new WorkspaceError('conflict', 'slug_taken')
}
throw error
})
return { slug, orgId }
}
+24 -12
View File
@@ -71,6 +71,8 @@ export type SandboxRow = {
last_activity_at: number | null
last_activity_by: string | null
token_usd_micros: number | null
/** 0051: this workspace's number in its account (shown as W-123); null only on rows from before it. */
number?: number | null
}
export type WorkspaceVisibility = 'private' | 'team'
@@ -118,18 +120,28 @@ export async function insertSandbox(
Partial<Pick<SandboxRow, 'environment_id' | 'environment_build_id' | 'source_snapshot_id' | 'name' | 'repo_branch' | 'visibility' | 'section'>>,
now: number
): Promise<SandboxRow> {
await db
.prepare(
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status,
machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id,
source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by)
VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
)
.bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name,
row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null,
row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null,
row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id)
.run()
// One transaction: bump the account's counter, then take its value as this row's number (W-123).
// A failed insert rolls the bump back; a destroyed row keeps its number, so none is ever reused.
await db.batch([
db
.prepare(
`INSERT INTO org_workspace_counters (account_id, last_number) VALUES (?, 1)
ON CONFLICT (account_id) DO UPDATE SET last_number = last_number + 1`
)
.bind(row.account_id),
db
.prepare(
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status,
machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id,
source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by, number)
VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT last_number FROM org_workspace_counters WHERE account_id = ?))`
)
.bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name,
row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null,
row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null,
row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id, row.account_id)
])
const inserted = await getSandbox(db, row.id)
if (!inserted) {
throw new Error('sandbox insert lost')
@@ -0,0 +1,86 @@
// A member's own sidebar arrangement of cloud workspaces, stored on the account so every device
// (desktops and the phone) shows the same pins, order and sections.
// GET /v1/team/prefs -> {document, revision, updatedAt}
// PUT /v1/team/prefs {document, revision} `revision` is the one the client edited (compare-and-set:
// a stale write gets 409 and the client re-applies its edit)
// Per member, per account: switching teams switches arrangements. Ids that no longer exist are
// harmless (clients skip them) and are dropped the next time that client writes.
import { z } from 'zod'
import type { SandboxCaller } from './auth'
import { WorkspaceError } from './workspaces'
const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/)
const SectionName = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/)
const unique = (list: readonly string[]) => new Set(list).size === list.length
export const WorkspacePrefsDocumentSchema = z
.object({
/** Pinned workspaces, top to bottom. */
pinned: z.array(SandboxId).max(200).refine(unique, 'duplicate id'),
/** Manual order of the rest (drag to reorder); workspaces not listed follow, newest first. */
order: z.array(SandboxId).max(500).refine(unique, 'duplicate id'),
/** Section order, including sections that are empty right now. */
sections: z.array(SectionName).max(50).refine(unique, 'duplicate section'),
/** Sections this member keeps collapsed. */
collapsed: z.array(SectionName).max(50).refine(unique, 'duplicate section')
})
.strict()
.refine((doc) => !doc.pinned.some((id) => doc.order.includes(id)), 'pinned ids stay out of order')
export type WorkspacePrefsDocument = z.infer<typeof WorkspacePrefsDocumentSchema>
const PutSchema = z
.object({
document: WorkspacePrefsDocumentSchema,
revision: z.number().int().min(0),
/** Which device wrote it (a label for debugging sync, never trusted for access). */
deviceId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
})
.strict()
export const EMPTY_PREFS: WorkspacePrefsDocument = { pinned: [], order: [], sections: [], collapsed: [] }
type Row = { document: string; revision: number; updated_at: number }
export async function getWorkspacePrefs(db: D1Database, caller: SandboxCaller) {
const row = await db
.prepare('SELECT document, revision, updated_at FROM workspace_prefs WHERE account_id = ? AND user_id = ?')
.bind(caller.accountId, caller.userId)
.first<Row>()
if (!row) {
return { document: EMPTY_PREFS, revision: 0, updatedAt: null }
}
// A document from a newer schema parses leniently: unknown keys are ignored, bad ones reset.
const parsed = WorkspacePrefsDocumentSchema.safeParse(JSON.parse(row.document))
return { document: parsed.success ? parsed.data : EMPTY_PREFS, revision: row.revision, updatedAt: row.updated_at }
}
export async function putWorkspacePrefs(db: D1Database, caller: SandboxCaller, body: unknown, now: number) {
const parsed = PutSchema.safeParse(body)
if (!parsed.success) {
throw new WorkspaceError('invalid_request')
}
const { document, revision, deviceId } = parsed.data
const text = JSON.stringify(document)
const result =
revision === 0
? await db
.prepare(
`INSERT OR IGNORE INTO workspace_prefs (account_id, user_id, document, revision, updated_at, updated_by_device)
VALUES (?, ?, ?, 1, ?, ?)`
)
.bind(caller.accountId, caller.userId, text, now, deviceId ?? null)
.run()
: await db
.prepare(
`UPDATE workspace_prefs SET document = ?, revision = revision + 1, updated_at = ?, updated_by_device = ?
WHERE account_id = ? AND user_id = ? AND revision = ?`
)
.bind(text, now, deviceId ?? null, caller.accountId, caller.userId, revision)
.run()
if (result.meta.changes !== 1) {
throw new WorkspaceError('conflict', 'stale_revision')
}
return getWorkspacePrefs(db, caller)
}
+47 -12
View File
@@ -4,7 +4,7 @@
// GET /v1/team/workspaces/:id
// PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?}
// POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?}
// GET /v1/team/links/resolve?w=<sandboxId>&c=<chatId>
// GET /v1/team/links/resolve?w=<sandboxId>&c=<chatId> or ?org=<slug>&n=<number>&c=<chatId>
// Access rule: a workspace is visible to its owner, and to every member of the owning org when
// visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a
// departed member's workspaces can be reassigned or archived — metadata only, never access.
@@ -16,6 +16,7 @@ import { memberNamesFor } from './member-names'
import { recordTokenSpend } from './member-usage'
import { readSnapshotTimes } from './read-snapshots'
import { sandboxView } from './wire'
import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs'
import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
export const PRESENCE_TTL_MS = 45_000
@@ -171,11 +172,12 @@ function repoView(row: SandboxRow) {
export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) {
const ids = rows.map((r) => r.id)
const [presence, compute, granted, readAt] = await Promise.all([
const [presence, compute, granted, readAt, slug] = await Promise.all([
presenceFor(db, ids, now),
computeMsFor(db, ids),
activeGrantUsers(db, ids, caller.userId),
readSnapshotTimes(db, ids)
readSnapshotTimes(db, ids),
rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null)
])
const referenced = (row: SandboxRow, live: readonly PresenceRow[]) =>
[row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter(
@@ -197,6 +199,10 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
return {
...sandboxView(row),
title: row.name,
// W-123 in its account; null only for a row that predates numbering and was never backfilled.
number: row.number ?? null,
// The link to copy: org slug + number when both exist, else the sandbox id form.
link: workspaceLink(row, slug),
repo: repoView(row),
visibility: row.visibility,
section: row.section,
@@ -425,27 +431,56 @@ export async function reportPresence(
return { presence: view!.presence }
}
const LinkQuery = z.object({
w: z.string().regex(/^sbx_[0-9a-f]{24}$/),
c: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
})
const ChatParam = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional()
const LinkQuery = z.union([
z.object({ w: z.string().regex(/^sbx_[0-9a-f]{24}$/), c: ChatParam }),
z.object({ org: z.string().min(1).max(40), n: z.coerce.number().int().min(1).max(1e9), c: ChatParam })
])
/** orca://cloud/w/<id>[/c/<chat>] → the workspace if the caller can see it; otherwise not_found. */
/** A slug link that names a different org than the caller's current one. */
export class LinkOtherOrgError extends WorkspaceError {
constructor(readonly orgId: string | null) {
super('not_found', 'other_org')
}
}
/**
* orca://cloud/w/<id>[/c/<chat>] or orca://cloud/<slug>/W-<n>[/c/<chat>] → the workspace if the caller
* can see it; otherwise not_found. A slug link for another org answers not_found with reason
* `other_org` and that org's id, so a client that belongs to it can offer to switch teams.
*/
export async function resolveLink(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
const query = LinkQuery.safeParse(Object.fromEntries(url.searchParams))
if (!query.success) {
throw new WorkspaceError('invalid_request')
}
const row = await getSandbox(db, query.data.w)
const q = query.data
let row: SandboxRow | null
if ('w' in q) {
row = await getSandbox(db, q.w)
} else {
const accountId = await accountForSlug(db, q.org)
if (!accountId) {
throw new WorkspaceError('not_found')
}
if (accountId !== caller.accountId) {
throw new LinkOtherOrgError(orgIdOf(accountId))
}
row = await db
.prepare('SELECT * FROM sandboxes WHERE account_id = ? AND number = ?')
.bind(accountId, q.n)
.first<SandboxRow>()
}
if (!row || !canSee(caller, row)) {
// Private, other org, or gone: the link reveals nothing about which.
throw new WorkspaceError('not_found')
}
const [view] = await workspaceViews(db, caller, [row], now)
return { workspace: view, chatId: query.data.c ?? null }
return { workspace: view, chatId: q.c ?? null }
}
/** Canonical deep link for a workspace (and optionally a chat in it). */
export function workspaceLink(id: string, chatId?: string): string {
return `orca://cloud/w/${id}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}`
export function workspaceLink(row: Pick<SandboxRow, 'id' | 'number'>, slug: string | null, chatId?: string): string {
const chat = chatId ? `/c/${encodeURIComponent(chatId)}` : ''
return slug && row.number ? `orca://cloud/${slug}/W-${row.number}${chat}` : `orca://cloud/w/${row.id}${chat}`
}
@@ -180,3 +180,18 @@ describe('pokes', () => {
expect((await t.req(solo, 'GET', '/v1/team/pokes')).body).toEqual({ enabled: false, pokes: [] })
})
})
describe('member-removed token', () => {
it('authorizes only POST /v1/internal/org-members/removed, never other operator routes', async () => {
const MR = 'm'.repeat(40)
const body = { accountId: 'org:acme', userId: 'bob' }
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: MR })
expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: MR, body })).status).toBe(200)
expect((await h.call('GET', '/v1/internal/status', { bearer: MR })).status).toBe(404)
expect((await h.call('POST', '/v1/internal/members/removed', { bearer: MR, body })).status).toBe(404)
// The operator token still works on the route; a short token is never accepted.
expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body })).status).toBe(200)
const weak = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: 'short' })
expect((await weak.call('POST', '/v1/internal/org-members/removed', { bearer: 'short', body })).status).toBe(404)
})
})
@@ -0,0 +1,175 @@
import { readFileSync, readdirSync } from 'node:fs'
import { DatabaseSync } from 'node:sqlite'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { isValidSlug, slugify } from '../src/org-slugs'
import { createHarness } from './harness'
type Role = 'owner' | 'admin' | 'member'
type Who = { sub: string; org?: string; role: Role }
async function setup() {
const h = await createHarness()
const req = async (who: Who, method: string, path: string, body?: unknown) =>
h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', who.org ? { org_role: who.role } : {}), body })
let n = 0
const create = async (who: Who, extra: Record<string, unknown> = {}) => {
n += 1
const res = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${n}`, machineSize: 'standard', ...extra })
expect(res.status).toBe(200)
return res.body.sandbox.id as string
}
const alice: Who = { sub: 'alice', org: 'acme', role: 'member' }
const bob: Who = { sub: 'bob', org: 'acme', role: 'member' }
const admin: Who = { sub: 'carol', org: 'acme', role: 'admin' }
const eve: Who = { sub: 'eve', org: 'other', role: 'owner' }
const solo: Who = { sub: 'sam', role: 'member' }
return { h, req, create, alice, bob, admin, eve, solo }
}
describe('workspace numbers (W-123)', () => {
it('numbers workspaces per account and never reuses a number', async () => {
const t = await setup()
const a1 = await t.create(t.alice)
const a2 = await t.create(t.bob, { visibility: 'team' })
const e1 = await t.create(t.eve)
const view = async (who: Who, id: string) => (await t.req(who, 'GET', `/v1/team/workspaces/${id}`)).body.workspace
expect((await view(t.alice, a1)).number).toBe(1)
expect((await view(t.bob, a2)).number).toBe(2)
expect((await view(t.eve, e1)).number).toBe(1)
expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${a1}`)).status).toBe(200)
const a3 = await t.create(t.alice)
expect((await view(t.alice, a3)).number).toBe(3)
})
it('backfills existing rows by creation order and seeds the counter', () => {
const raw = new DatabaseSync(':memory:')
const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href)
const files = readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()
const at = files.indexOf('0051_workspace_numbers_prefs.sql')
for (const file of files.slice(0, at)) {
raw.exec(readFileSync(`${dir}${file}`, 'utf8'))
}
const insert = raw.prepare(
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region,
generation, created_at, updated_at) VALUES (?, ?, 'u', ?, 'vercel', ?, 'destroyed', 'standard', 'iad1', 0, ?, ?)`
)
insert.run('sbx_b', 'org:a', 'w2', 'p2', 20, 20)
insert.run('sbx_a', 'org:a', 'w1', 'p1', 10, 10)
insert.run('sbx_c', 'org:a', 'w3', 'p3', 20, 20)
insert.run('sbx_z', 'org:b', 'w1', 'pz', 5, 5)
for (const file of files.slice(at)) {
raw.exec(readFileSync(`${dir}${file}`, 'utf8'))
}
expect(raw.prepare('SELECT id, number FROM sandboxes ORDER BY id').all()).toEqual([
{ id: 'sbx_a', number: 1 },
{ id: 'sbx_b', number: 2 },
{ id: 'sbx_c', number: 3 },
{ id: 'sbx_z', number: 1 }
])
expect(raw.prepare('SELECT * FROM org_workspace_counters ORDER BY account_id').all()).toEqual([
{ account_id: 'org:a', last_number: 3 },
{ account_id: 'org:b', last_number: 1 }
])
})
})
describe('org slugs', () => {
it('slugifies names and refuses reserved or malformed slugs', () => {
expect(slugify('Acme Labs, Inc.')).toBe('acme-labs-inc')
expect(slugify('Ünïcode Crew')).toBe('unicode-crew')
expect(slugify('!!!')).toBe('team')
expect(slugify('w')).toBe('w-team')
expect(isValidSlug('acme')).toBe(true)
expect(isValidSlug('w')).toBe(false)
expect(isValidSlug('-acme')).toBe(false)
expect(isValidSlug('a--b')).toBe(false)
expect(isValidSlug('Acme')).toBe(false)
})
it('names an org once from the first name it hears, uniquely across orgs', async () => {
const t = await setup()
expect((await t.req(t.alice, 'GET', '/v1/team/org')).body).toEqual({ slug: null, orgId: 'acme' })
expect((await t.req(t.alice, 'GET', '/v1/team/org?name=Acme%20Labs')).body).toEqual({ slug: 'acme-labs', orgId: 'acme' })
// A teammate whose client shows another name still gets the org's slug.
expect((await t.req(t.bob, 'GET', '/v1/team/org?name=Whatever')).body.slug).toBe('acme-labs')
expect((await t.req(t.eve, 'GET', '/v1/team/org?name=Acme%20Labs')).body.slug).toBe('acme-labs-2')
expect((await t.req(t.solo, 'GET', '/v1/team/org?name=Sam')).body).toEqual({ slug: null, orgId: null })
})
it('lets only admins rename, and not onto another org', async () => {
const t = await setup()
await t.req(t.alice, 'GET', '/v1/team/org?name=Acme')
await t.req(t.eve, 'GET', '/v1/team/org?name=Other')
expect((await t.req(t.alice, 'PUT', '/v1/team/org', { slug: 'acme-co' })).status).toBe(403)
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'other' })).status).toBe(409)
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'w' })).status).toBe(400)
expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'acme-co' })).body).toEqual({ slug: 'acme-co', orgId: 'acme' })
expect((await t.req(t.bob, 'GET', '/v1/team/org')).body.slug).toBe('acme-co')
})
})
describe('slug links', () => {
it('copies org slug links and resolves them only for those who can see the workspace', async () => {
const t = await setup()
const id = await t.create(t.alice)
const before = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace
// No slug yet: the id form still works.
expect(before.link).toBe(`orca://cloud/w/${id}`)
await t.req(t.alice, 'GET', '/v1/team/org?name=Acme')
const after = (await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0]
expect(after.link).toBe('orca://cloud/acme/W-1')
const resolved = await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=1&c=s:abc')
expect(resolved.status).toBe(200)
expect(resolved.body).toMatchObject({ workspace: { id, number: 1 }, chatId: 's:abc' })
// Private to Alice: Bob sees nothing until she shares it.
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).status).toBe(404)
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' })
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).body.workspace.id).toBe(id)
expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=2')).status).toBe(404)
// Another org: not found, but says which org so a member of both can switch.
const other = await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=acme&n=1')
expect(other.status).toBe(404)
expect(other.body).toEqual({ error: 'not_found', reason: 'other_org', orgId: 'acme' })
expect((await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=nope&n=1')).body).toEqual({ error: 'not_found' })
expect((await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=0')).status).toBe(400)
})
})
describe('workspace prefs (synced pins and order)', () => {
const A = `sbx_${'a'.repeat(24)}`
const B = `sbx_${'b'.repeat(24)}`
it('stores one document per member and account with compare-and-set', async () => {
const t = await setup()
expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body).toEqual({
document: { pinned: [], order: [], sections: [], collapsed: [] },
revision: 0,
updatedAt: null
})
const doc = { pinned: [A], order: [B], sections: ['Auth', 'Billing'], collapsed: ['Billing'] }
const first = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: doc, revision: 0, deviceId: 'desk-1' })
expect(first.status).toBe(200)
expect(first.body).toMatchObject({ document: doc, revision: 1 })
// A second device that still holds revision 0 must re-read before writing.
const stale = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [] }, revision: 0 })
expect(stale.status).toBe(409)
const second = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [B, A], order: [] }, revision: 1 })
expect(second.body.revision).toBe(2)
expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body.document.pinned).toEqual([B, A])
// Teammates and other accounts have their own.
expect((await t.req(t.bob, 'GET', '/v1/team/prefs')).body.revision).toBe(0)
expect((await t.req({ ...t.alice, org: 'other' }, 'GET', '/v1/team/prefs')).body.revision).toBe(0)
expect((await t.req(t.solo, 'PUT', '/v1/team/prefs', { document: doc, revision: 0 })).status).toBe(200)
})
it('rejects malformed documents', async () => {
const t = await setup()
const put = (document: unknown) => t.req(t.alice, 'PUT', '/v1/team/prefs', { document, revision: 0 })
expect((await put({ pinned: [A], order: [A], sections: [], collapsed: [] })).status).toBe(400)
expect((await put({ pinned: [A, A], order: [], sections: [], collapsed: [] })).status).toBe(400)
expect((await put({ pinned: ['nope'], order: [], sections: [], collapsed: [] })).status).toBe(400)
expect((await put({ pinned: [], order: [], sections: ['x'], collapsed: [], extra: 1 })).status).toBe(400)
})
})
@@ -443,7 +443,7 @@ describe('desktop wire contract', () => {
).body
)
wire.CloudWorkspaceGrantListSchema.parse((await t.req(t.bob, 'GET', `/v1/team/workspaces/${t.id}/grants`)).body)
expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ workspaceId: t.id, chatId: 'chat 1' })
expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ target: { kind: 'id', workspaceId: t.id }, chatId: 'chat 1' })
expect(issued.grant.status).toBe('active')
})
@@ -188,6 +188,13 @@
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts",
"kind": "object-property:accessibilityLabel",
"text": "Cloud workspace number",
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx",
"kind": "jsx-attribute:title",
+1
View File
@@ -230,6 +230,7 @@ export default function RootLayout() {
<Stack.Screen name="cloud/new" options={{ headerShown: false }} />
<Stack.Screen name="cloud/access" options={{ headerShown: false }} />
<Stack.Screen name="cloud/w/[sandboxId]" options={{ headerShown: false }} />
<Stack.Screen name="cloud/[org]/[number]" options={{ headerShown: false }} />
<Stack.Screen
name="new-workspace"
options={{
+57
View File
@@ -0,0 +1,57 @@
import { useLocalSearchParams, useRouter } from 'expo-router'
import { Cloud } from 'lucide-react-native'
import { useEffect, useState } from 'react'
import { SafeAreaView } from 'react-native-safe-area-context'
import { MobileStateView } from '../../../src/components/MobileStateView'
import { CloudWorkspaceScreen } from '../../../src/cloud/CloudWorkspaceScreen'
import { resolveCloudWorkspaceLink } from '../../../src/cloud/cloud-workspace-prefs'
import { loadCloudControlPlane } from '../../../src/cloud/cloud-session'
import { useMobileTranslation } from '../../../src/i18n/use-mobile-translation'
import { colors } from '../../../src/theme/mobile-theme'
import { parseCloudWorkspaceLink } from '../../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
type Resolved = { kind: 'loading' } | { kind: 'found'; sandboxId: string } | { kind: 'missing' }
/** Team links with a number (orca://cloud/<org>/W-123, the desktop's "Copy link") open here. */
export default function CloudWorkspaceNumberLinkRoute() {
const t = useMobileTranslation()
const router = useRouter()
const params = useLocalSearchParams<{ org?: string; number?: string }>()
const link = `orca://cloud/${params.org ?? ''}/${params.number ?? ''}`
const [resolved, setResolved] = useState<Resolved>({ kind: 'loading' })
useEffect(() => {
let live = true
const parsed = parseCloudWorkspaceLink(link)
void (async () => {
const plane = parsed ? await loadCloudControlPlane() : null
const sandboxId =
plane && parsed ? await resolveCloudWorkspaceLink(plane, parsed.target) : null
if (live) {
setResolved(sandboxId ? { kind: 'found', sandboxId } : { kind: 'missing' })
}
})().catch(() => live && setResolved({ kind: 'missing' }))
return () => {
live = false
}
}, [link])
if (resolved.kind === 'found') {
return <CloudWorkspaceScreen key={resolved.sandboxId} sandboxId={resolved.sandboxId} />
}
return (
<SafeAreaView style={{ flex: 1, backgroundColor: colors.bgBase }}>
{resolved.kind === 'loading' ? (
<MobileStateView loading title={t('cloud.link.opening', 'Opening workspace…')} />
) : (
<MobileStateView
icon={Cloud}
title={t('cloud.link.missingTitle', 'Can’t open this workspace')}
message={t(
'cloud.link.missing',
'It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.'
)}
action={{ label: t('cloud.link.home', 'Go to Home'), onPress: () => router.replace('/') }}
/>
)}
</SafeAreaView>
)
}
+37 -1
View File
@@ -1,4 +1,4 @@
import { Archive, Moon } from 'lucide-react-native'
import { Archive, Moon, Pin, PinOff } from 'lucide-react-native'
import { useState } from 'react'
import { View } from 'react-native'
import { ConfirmModal } from '../components/ConfirmModal'
@@ -8,6 +8,41 @@ import { colors } from '../theme/mobile-theme'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import type { CloudWorkspace } from './cloud-control-plane-client'
import { cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles'
import { useCloudWorkspacePrefs } from './cloud-workspace-prefs'
import { useCloudEnrollment } from './use-cloud-workspaces'
import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
/** Pin to the top of the Cloud list on every device of yours (your own pins, not the team's). */
function CloudWorkspacePinRow(props: { workspace: CloudWorkspace }) {
const t = useMobileTranslation()
const enrollment = useCloudEnrollment()
const prefs = useCloudWorkspacePrefs(enrollment?.deviceSessionId ?? null)
const [busy, setBusy] = useState(false)
if (!enrollment || props.workspace.status === 'archived') {
return null
}
const pinned = prefs.document.pinned.includes(props.workspace.id)
const Icon = pinned ? PinOff : Pin
return (
<View style={styles.section}>
<View style={styles.card}>
<ListRow
key="pin"
leading={<Icon size={18} color={colors.textSecondary} />}
title={pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top')}
subtitle={t('cloud.actions.pinCaption', 'On all your devices. Only you see your pins.')}
busy={busy}
onPress={() => {
setBusy(true)
void prefs
.edit((doc) => setPinned(doc, props.workspace.id, !pinned))
.finally(() => setBusy(false))
}}
/>
</View>
</View>
)
}
/** Sleep (no sandbox hours, files kept) and Archive, each behind a confirm because both stop agents. */
export function CloudWorkspaceActions(props: {
@@ -29,6 +64,7 @@ export function CloudWorkspaceActions(props: {
const running = props.workspace.status === 'running'
return (
<>
<CloudWorkspacePinRow workspace={props.workspace} />
{running ? (
<View style={styles.section}>
<View style={styles.card}>
@@ -47,6 +47,9 @@ export type CloudWorkspace = {
createdByUserId: string | null
/** When the last sleeping read snapshot was stored (ms); null when none or unknown. */
readSnapshotAt: number | null
/** Its number in the account (W-123); absent on older control planes and the owner-only list. */
number?: number | null
section?: string | null
}
const SANDBOX_STATUS: Record<string, CloudWorkspaceStatus> = {
creating: 'creating',
@@ -99,7 +102,9 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace {
lastActivityAt: row.lastActivityAt,
sandboxMs: row.cost.computeMs,
createdByUserId: row.createdBy,
readSnapshotAt: row.readSnapshotAt ?? null
readSnapshotAt: row.readSnapshotAt ?? null,
number: row.number ?? null,
section: row.section
}
}
@@ -0,0 +1,83 @@
import { describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
vi.mock('./cloud-session', () => ({ loadCloudControlPlane: vi.fn() }))
import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
import { editCloudWorkspacePrefsOn, resolveCloudWorkspaceLink } from './cloud-workspace-prefs'
import type { CloudControlPlane } from './cloud-control-plane-request'
const PutBody = z.object({
document: z.object({
pinned: z.array(z.string()),
order: z.array(z.string()),
sections: z.array(z.string()),
collapsed: z.array(z.string())
}),
revision: z.number()
})
const A = `sbx_${'a'.repeat(24)}`
const B = `sbx_${'b'.repeat(24)}`
function plane(handler: (method: string, url: URL, body: unknown) => [number, unknown]) {
const calls: string[] = []
const fetchFn: typeof fetch = async (input, init = {}) => {
const url = new URL(String(input))
calls.push(`${init.method} ${url.pathname}${url.search}`)
const [status, body] = handler(
init.method ?? 'GET',
url,
init.body ? JSON.parse(String(init.body)) : undefined
)
return new Response(JSON.stringify(body), { status })
}
const p: CloudControlPlane = { baseUrl: 'https://cp.example', token: () => 't', fetch: fetchFn }
return { plane: p, calls }
}
describe('phone prefs sync', () => {
it('re-applies a pin on top of a desktop that wrote first', async () => {
let server: z.infer<typeof PutBody> = {
document: { pinned: [B], order: [], sections: [], collapsed: [] },
revision: 3
}
let firstPut = true
const { plane: p, calls } = plane((method, _url, body) => {
if (method === 'GET') {
return [200, { ...server, updatedAt: 1 }]
}
const put = PutBody.parse(body)
if (firstPut) {
// A desktop wrote between our read and our write.
firstPut = false
server = { ...server, revision: 4 }
return [409, { error: 'conflict', reason: 'stale_revision' }]
}
expect(put.revision).toBe(4)
server = { document: put.document, revision: 5 }
return [200, { ...server, updatedAt: 2 }]
})
const saved = await editCloudWorkspacePrefsOn(p, (doc) => setPinned(doc, A, true))
expect(saved.document.pinned).toEqual([B, A])
expect(calls).toEqual([
'GET /v1/team/prefs',
'PUT /v1/team/prefs',
'GET /v1/team/prefs',
'PUT /v1/team/prefs'
])
})
it('resolves number links and treats not found as null', async () => {
const { plane: p, calls } = plane((_method, url) =>
url.searchParams.get('n') === '7'
? [200, { workspace: { id: A }, chatId: null }]
: [404, { error: 'not_found' }]
)
await expect(
resolveCloudWorkspaceLink(p, { kind: 'number', org: 'acme', number: 8 })
).resolves.toBeNull()
expect(calls).toEqual(['GET /v1/team/links/resolve?org=acme&n=8'])
await expect(resolveCloudWorkspaceLink(p, { kind: 'id', workspaceId: B })).resolves.toBe(B)
})
})
+125
View File
@@ -0,0 +1,125 @@
// The phone's side of synced cloud workspace prefs (/v1/team/prefs): the same pins and order as
// the member's desktops, read and written with the phone's own device-signed token, and W-number
// links (orca://cloud/<org>/W-123) resolved to a workspace.
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import {
CloudWorkspaceLinkResponseSchema,
CloudWorkspacePrefsSchema,
EMPTY_CLOUD_WORKSPACE_PREFS,
type CloudWorkspaceLinkTarget,
type CloudWorkspacePrefs,
type CloudWorkspacePrefsDocument
} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
import {
CloudRequestError,
cloudRequest as request,
type CloudControlPlane
} from './cloud-control-plane-request'
import { loadCloudControlPlane } from './cloud-session'
const MAX_ATTEMPTS = 4
export function getCloudWorkspacePrefs(
plane: CloudControlPlane,
signal?: AbortSignal
): Promise<CloudWorkspacePrefs> {
return request(plane, 'GET', '/v1/team/prefs', CloudWorkspacePrefsSchema, { signal })
}
/**
* Applies `edit` to the newest server copy and writes it with compare-and-set; when a desktop wrote
* first it re-reads and applies the same edit again.
*/
export async function editCloudWorkspacePrefsOn(
plane: CloudControlPlane,
edit: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument
): Promise<CloudWorkspacePrefs> {
let current = await getCloudWorkspacePrefs(plane)
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
const next = edit(current.document)
if (next === current.document) {
return current
}
try {
return await request(plane, 'PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, {
body: { document: next, revision: current.revision }
})
} catch (error) {
if (!(error instanceof CloudRequestError) || error.code !== 'conflict') {
throw error
}
current = await getCloudWorkspacePrefs(plane)
}
}
throw new CloudRequestError('conflict', 409, 'stale_revision')
}
/** Either link form → the workspace's sandbox id (null when this account can't see it). */
export async function resolveCloudWorkspaceLink(
plane: CloudControlPlane,
target: CloudWorkspaceLinkTarget
): Promise<string | null> {
if (target.kind === 'id') {
return target.workspaceId
}
const params = new URLSearchParams({ org: target.org, n: String(target.number) })
try {
const body = await request(
plane,
'GET',
`/v1/team/links/resolve?${params}`,
CloudWorkspaceLinkResponseSchema
)
return body.workspace.id
} catch (error) {
if (error instanceof CloudRequestError && error.status === 404) {
return null
}
throw error
}
}
export const cloudWorkspacePrefsQueryKey = (sessionId: string | null) =>
['orca-cloud', 'prefs', sessionId] as const
/** This member's synced prefs and an edit that saves them (shown at once, rolled back on failure). */
export function useCloudWorkspacePrefs(sessionId: string | null) {
const client = useQueryClient()
const query = useQuery({
queryKey: cloudWorkspacePrefsQueryKey(sessionId),
enabled: sessionId !== null,
queryFn: async ({ signal }) => {
const plane = await loadCloudControlPlane()
return plane
? (await getCloudWorkspacePrefs(plane, signal)).document
: EMPTY_CLOUD_WORKSPACE_PREFS
},
// Desktops edit it too; pick their edits up whenever Home is in front.
refetchInterval: 15_000,
staleTime: 5_000
})
const edit = useCallback(
async (change: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument) => {
const key = cloudWorkspacePrefsQueryKey(sessionId)
const previous = client.getQueryData<CloudWorkspacePrefsDocument>(key)
client.setQueryData<CloudWorkspacePrefsDocument>(key, (doc) =>
change(doc ?? EMPTY_CLOUD_WORKSPACE_PREFS)
)
try {
const plane = await loadCloudControlPlane()
if (!plane) {
throw new CloudRequestError('not_enrolled', 0)
}
const saved = await editCloudWorkspacePrefsOn(plane, change)
client.setQueryData(key, saved.document)
return true
} catch {
client.setQueryData(key, previous)
return false
}
},
[client, sessionId]
)
return { document: query.data ?? EMPTY_CLOUD_WORKSPACE_PREFS, edit }
}
+62 -8
View File
@@ -1,7 +1,7 @@
import { useRouter } from 'expo-router'
import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native'
import { Fragment, useState } from 'react'
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
import { ChevronRight, Cloud, Pin, Plus, RotateCw } from 'lucide-react-native'
import { Fragment, useMemo, useState } from 'react'
import { ActivityIndicator, Alert, Pressable, Text, View } from 'react-native'
import { CloudStatusDot } from '../cloud/CloudStatusDot'
import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection'
import type { CloudWorkspace } from '../cloud/cloud-control-plane-client'
@@ -10,6 +10,12 @@ import { takeCloudReturnTo } from '../cloud/cloud-return-to'
import type { CloudEnrollment } from '../cloud/cloud-device-identity'
import { cloudRepoLine, cloudStatusLabel } from '../cloud/cloud-workspace-display'
import { useCloudWorkspaces } from '../cloud/use-cloud-workspaces'
import { useCloudWorkspacePrefs } from '../cloud/cloud-workspace-prefs'
import {
arrangeCloudWorkspaces,
setPinned
} from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement'
import { formatWorkspaceNumber } from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
import { formatTimeAgo } from '../worktree/agent-row-display'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { colors } from '../theme/mobile-theme'
@@ -35,13 +41,43 @@ export function MobileHomeCloudSection(props: {
const t = useMobileTranslation()
useMobileColorScheme()
const query = useCloudWorkspaces(props.enrollment)
// Pins and order are the member's own and sync with their desktops.
const prefs = useCloudWorkspacePrefs(props.enrollment?.deviceSessionId ?? null)
const workspaces = useMemo(
() =>
arrangeCloudWorkspaces(
(query.data ?? []).filter((workspace) => workspace.status !== 'archived'),
prefs.document
).flatMap((group) =>
group.rows.map((workspace) => ({ workspace, pinned: group.kind === 'pinned' }))
),
[query.data, prefs.document]
)
if (props.enrollment === undefined) {
return null
}
if (props.enrollment === null) {
return <CloudConnectRow desktop={props.enrollDesktop} deviceLabel={props.deviceLabel} />
}
const workspaces = (query.data ?? []).filter((workspace) => workspace.status !== 'archived')
const togglePin = (workspace: CloudWorkspace, pinned: boolean) => {
Alert.alert(workspace.title, undefined, [
{
text: pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top'),
onPress: () =>
void prefs
.edit((doc) => setPinned(doc, workspace.id, !pinned))
.then((saved) => {
if (!saved) {
Alert.alert(
t('cloud.home.pinFailed', 'Couldn’t save that change'),
t('cloud.home.pinFailedDetail', 'Check your connection and try again.')
)
}
})
},
{ text: t('common.cancel', 'Cancel'), style: 'cancel' }
])
}
const now = query.dataUpdatedAt || 0
return (
<>
@@ -94,12 +130,14 @@ export function MobileHomeCloudSection(props: {
</View>
</View>
) : (
workspaces.map((workspace) => (
workspaces.map(({ workspace, pinned }) => (
<Fragment key={workspace.id}>
<CloudWorkspaceRow
workspace={workspace}
pinned={pinned}
now={now}
onPress={() => props.onOpenWorkspace(workspace)}
onLongPress={() => togglePin(workspace, pinned)}
/>
<View style={[styles.separator, styles.tileSeparator]} />
</Fragment>
@@ -135,12 +173,16 @@ function SkeletonRow() {
function CloudWorkspaceRow({
workspace,
pinned,
now,
onPress
onPress,
onLongPress
}: {
workspace: CloudWorkspace
pinned: boolean
now: number
onPress: () => void
onLongPress: () => void
}) {
const t = useMobileTranslation()
const status = cloudStatusLabel(workspace.status, t)
@@ -175,7 +217,9 @@ function CloudWorkspaceRow({
: createdLine && lastActive - workspace.createdAt < 60_000
? null
: formatTimeAgo(lastActive, reference)
const line = [status, detail, when].filter(Boolean).join(' · ')
const number = workspace.number ? formatWorkspaceNumber(workspace.number) : null
const line = [status, number, detail, when].filter(Boolean).join(' · ')
const optionsLabel = pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top')
return (
<Pressable
accessibilityRole="button"
@@ -187,8 +231,17 @@ function CloudWorkspaceRow({
detail: line
}
)}
accessibilityHint={pinned ? t('cloud.home.pinnedHint', 'Pinned') : undefined}
accessibilityActions={[{ name: 'longpress', label: optionsLabel }]}
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === 'longpress') {
onLongPress()
}
}}
style={({ pressed }) => [styles.row, pressed && styles.rowPressed]}
onPress={onPress}
onLongPress={onLongPress}
delayLongPress={400}
>
<View style={styles.tile}>
<Cloud size={17} strokeWidth={1.8} color={colors.textPrimary} />
@@ -204,13 +257,14 @@ function CloudWorkspaceRow({
<Text style={workspace.status === 'failed' ? { color: colors.statusRed } : undefined}>
{status}
</Text>
{[detail, when]
{[number, detail, when]
.filter(Boolean)
.map((part) => ` · ${part}`)
.join('')}
</Text>
</View>
<View style={styles.trailing}>
{pinned ? <Pin size={14} color={colors.textMuted} /> : null}
<ChevronRight size={18} color={colors.textMuted} />
</View>
</Pressable>
+14 -2
View File
@@ -5020,7 +5020,8 @@
"actions": {
"sleep": "Sleep",
"sleepCaption": "Sandbox hours stop. Files are kept; agents restart when it wakes.",
"archive": "Archive"
"archive": "Archive",
"pinCaption": "On all your devices. Only you see your pins."
},
"sleep": {
"title": "Sleep {{title}}?",
@@ -5122,7 +5123,12 @@
"new": "New cloud workspace",
"createdAgo": "Created {{ago}} ago",
"createdJustNow": "Created just now",
"workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}"
"workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}",
"unpin": "Unpin",
"pin": "Pin to top",
"pinFailed": "Couldn’t save that change",
"pinFailedDetail": "Check your connection and try again.",
"pinnedHint": "Pinned"
},
"connect": {
"signedOut": "Sign in to Orca on {{desktop}}, then try again.",
@@ -5231,6 +5237,12 @@
"idle": {
"sleeps_one": "Sleeps after {{count}} minute idle.",
"sleeps_other": "Sleeps after {{count}} minutes idle."
},
"link": {
"opening": "Opening workspace…",
"missingTitle": "Can’t open this workspace",
"missing": "It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.",
"home": "Go to Home"
}
}
}
+11 -2
View File
@@ -141,7 +141,10 @@ const EntitlementSchema = z.object({
interval: z.enum(ORCA_BILLING_INTERVALS).nullable().catch(null),
seats: seconds,
seatChange: z
.object({ seatsAtRenewal: z.number().int().min(1), effectiveAt: z.number() })
.object({
seatsAtRenewal: z.number().int().min(1),
effectiveAt: z.number()
})
.nullable()
.catch(null),
period: window,
@@ -172,7 +175,13 @@ const EntitlementSchema = z.object({
spentCents: seconds,
centsPerHour: seconds
})
.catch({ optedIn: false, active: false, spendCapCents: 0, spentCents: 0, centsPerHour: 0 }),
.catch({
optedIn: false,
active: false,
spendCapCents: 0,
spentCents: 0,
centsPerHour: 0
}),
payment: z
.object({
pastDueSince: z.number().nullable().catch(null),
+26 -2
View File
@@ -11,7 +11,8 @@ import type {
OrcaBillingOverageResult,
OrcaBillingStatusResult,
OrcaBillingTeamPlansResult,
OrcaBillingTrialClaimResult
OrcaBillingTrialClaimResult,
OrcaBillingUsageHistoryResult
} from '../../shared/orca-billing'
import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config'
import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh'
@@ -28,6 +29,7 @@ import {
type BillingEndpoints
} from './billing-client'
import { getBillingEndpoints } from './billing-config'
import { fetchUsageHistory } from './billing-usage-client'
import { getBillingDevKeyFile, mintDevBillingToken } from './billing-dev-token'
import { cleanCloudServiceUrl } from '../../shared/cloud-service-url'
import { listOrcaProfileOrgMembers } from '../orca-profiles/profile-cloud-org-members-service'
@@ -55,7 +57,10 @@ function prepareDev(userDataPath: string, keyFile: string): Ready {
if (!cloud) {
return { ok: false, status: 'signed-out' }
}
const endpoints: BillingEndpoints = { billingApiUrl, billingTokenEndpoint: billingApiUrl }
const endpoints: BillingEndpoints = {
billingApiUrl,
billingTokenEndpoint: billingApiUrl
}
return {
ok: true,
run: async (call) => {
@@ -139,6 +144,25 @@ export async function getOrcaBillingStatus(userDataPath: string): Promise<OrcaBi
}
}
/** The last 30 days of sandbox hours, with days starting at the viewer's local midnight. */
export async function getOrcaBillingUsageHistory(
userDataPath: string,
utcOffsetMinutes: number
): Promise<OrcaBillingUsageHistoryResult> {
const ready = prepare(userDataPath)
if (!ready.ok) {
return { status: ready.status }
}
try {
const history = await ready.run((token, endpoints) =>
fetchUsageHistory(endpoints, token, utcOffsetMinutes)
)
return history === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', history }
} catch (error) {
return { status: 'failed', error: message(error) }
}
}
/** Plan state for other teams the signed-in user is on (cloud start B2); never switches teams. */
export async function getOrcaBillingTeamPlans(
userDataPath: string,
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { fetchUsageHistory } from './billing-usage-client'
const endpoints = {
billingApiUrl: 'https://billing.example.test',
billingTokenEndpoint: 'https://login.example.test/v1/desktop/auth/billing-token'
}
type Seen = { url: string; init: RequestInit | undefined }
function fakeFetch(responses: Record<string, Response>, seen: Seen[] = []): typeof fetch {
return async (input, init) => {
const url = String(input)
seen.push({ url, init })
const response = responses[url]
if (!response) {
throw new Error(`unexpected ${url}`)
}
return response
}
}
describe('fetchUsageHistory', () => {
const url = 'https://billing.example.test/v1/billing/usage?utcOffset=-480'
const body = {
days: [{ start: 1, seconds: 3600 }],
totalSeconds: 3600,
yourSeconds: 1800,
members: { top: [{ userId: 'u1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 },
sandboxes: { top: [{ sandboxId: 'sbx_1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 }
}
it('sends the local offset and maps both breakdowns to one row shape', async () => {
const seen: Seen[] = []
const history = await fetchUsageHistory(
endpoints,
'bt',
-480,
fakeFetch({ [url]: Response.json(body) }, seen)
)
expect(seen[0]!.init?.method).toBe('GET')
expect(history.members).toEqual({
top: [{ id: 'u1', seconds: 3600 }],
otherCount: 0,
otherSeconds: 0
})
expect(history.sandboxes?.top).toEqual([{ id: 'sbx_1', seconds: 3600 }])
})
it('accepts a member’s view and rejects malformed rows', async () => {
const member = await fetchUsageHistory(
endpoints,
'bt',
-480,
fakeFetch({ [url]: Response.json({ ...body, members: null, sandboxes: null }) })
)
expect(member.members).toBeNull()
await expect(
fetchUsageHistory(
endpoints,
'bt',
-480,
fakeFetch({
[url]: Response.json({
...body,
members: { top: [{ userId: '<script>', seconds: 1 }], otherCount: 0, otherSeconds: 0 }
})
})
)
).rejects.toThrow('invalid_billing_response')
})
})
+67
View File
@@ -0,0 +1,67 @@
// GET /v1/billing/usage behind Plan & billing's "Last 30 days". Pure (fetch injected).
import { z } from 'zod'
import type { OrcaBillingUsageHistory } from '../../shared/orca-billing'
import { billingRequest, type BillingEndpoints } from './billing-client'
const UsageId = z
.string()
.min(1)
.max(128)
.regex(/^[A-Za-z0-9_.:-]+$/)
const UsageSeconds = z.number().finite().nonnegative()
const usageTop = <K extends 'userId' | 'sandboxId'>(key: K) =>
z
.object({
top: z.array(z.record(z.string(), z.unknown())).max(20),
otherCount: z.number().int().nonnegative(),
otherSeconds: UsageSeconds
})
.transform((value, ctx) => {
const top = value.top.map((row) => ({
id: UsageId.safeParse(row[key]),
seconds: UsageSeconds.safeParse(row.seconds)
}))
if (top.some((row) => !row.id.success || !row.seconds.success)) {
ctx.addIssue({ code: 'custom', message: 'invalid_usage_row' })
return z.NEVER
}
return {
top: top.map((row) => ({
id: row.id.data!,
seconds: row.seconds.data!
})),
otherCount: value.otherCount,
otherSeconds: value.otherSeconds
}
})
.nullable()
const UsageHistoryBody = z.object({
days: z.array(z.object({ start: z.number().int(), seconds: UsageSeconds })).max(31),
totalSeconds: UsageSeconds,
yourSeconds: UsageSeconds,
members: usageTop('userId'),
sandboxes: usageTop('sandboxId')
})
/** GET /v1/billing/usage: 30 days of sandbox hours, days starting at the local midnight. */
export async function fetchUsageHistory(
endpoints: BillingEndpoints,
token: string,
utcOffsetMinutes: number,
fetchImpl: typeof fetch = fetch
): Promise<OrcaBillingUsageHistory> {
const body = UsageHistoryBody.safeParse(
await billingRequest(
endpoints,
token,
'GET',
`v1/billing/usage?utcOffset=${Math.round(utcOffsetMinutes)}`,
undefined,
fetchImpl
)
)
if (!body.success) {
throw new Error('invalid_billing_response')
}
return body.data
}
@@ -2,6 +2,7 @@
// hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential.
import { z } from 'zod'
import { errorMessage } from '../../shared/error-message'
import { cloudWorkspacePrefsMethods } from './cloud-workspaces-prefs-client'
import { HOSTED_SANDBOX_STATUSES } from '../../shared/hosted-sandbox/hosted-sandbox-wire'
import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
import {
@@ -14,6 +15,7 @@ import {
CloudWorkspacePresenceResponseSchema,
CloudWorkspaceResponseSchema,
OrgPromptsSchema,
type CloudWorkspaceLinkTarget,
type CloudWorkspaceListQuery,
type CloudWorkspacePatch,
type OrgPrompts
@@ -35,7 +37,9 @@ export class CloudWorkspacesError extends Error {
constructor(
readonly status: number,
readonly code: string,
readonly reason?: string
readonly reason?: string,
/** A slug link for another org (`reason: other_org`) names that org, so a member can switch. */
readonly orgId?: string
) {
super(reason ? `${code}:${reason}` : code)
this.name = 'CloudWorkspacesError'
@@ -118,7 +122,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
throw new CloudWorkspacesError(
response.status,
typeof err.error === 'string' ? err.error : 'error',
typeof err.reason === 'string' ? err.reason : undefined
typeof err.reason === 'string' ? err.reason : undefined,
typeof err.orgId === 'string' ? err.orgId.slice(0, 128) : undefined
)
}
const parsed = schema.safeParse(payload)
@@ -131,6 +136,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
const ws = (id: string) => `/v1/team/workspaces/${encodeURIComponent(id)}`
return {
...cloudWorkspacePrefsMethods(call),
async list(query: CloudWorkspaceListQuery = {}) {
const params = new URLSearchParams()
for (const [key, value] of Object.entries(query)) {
@@ -208,8 +214,12 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
CloudWorkspaceGrantListSchema.partial().passthrough()
)
},
async resolveLink(workspaceId: string, chatId?: string | null) {
const params = new URLSearchParams({ w: workspaceId })
async resolveLink(target: CloudWorkspaceLinkTarget, chatId?: string | null) {
const params = new URLSearchParams(
target.kind === 'id'
? { w: target.workspaceId }
: { org: target.org, n: String(target.number) }
)
if (chatId) {
params.set('c', chatId)
}
@@ -0,0 +1,44 @@
// Synced cloud workspace prefs (pins, order, sections) and the org's link slug, on the same
// authenticated call as the rest of the team registry client.
import type { z } from 'zod'
import {
CloudOrgSlugSchema,
CloudWorkspacePrefsSchema,
type CloudOrgSlug,
type CloudWorkspacePrefs,
type CloudWorkspacePrefsDocument
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
type Call = <T>(
method: 'GET' | 'PUT',
path: string,
schema: z.ZodType<T>,
body?: unknown
) => Promise<T>
export function cloudWorkspacePrefsMethods(call: Call) {
return {
/** This member's synced arrangement for the current account. */
getPrefs(): Promise<CloudWorkspacePrefs> {
return call('GET', '/v1/team/prefs', CloudWorkspacePrefsSchema)
},
/** Compare-and-set: a stale `revision` answers 409 `conflict`; re-read and re-apply. */
putPrefs(
document: CloudWorkspacePrefsDocument,
revision: number,
deviceId?: string
): Promise<CloudWorkspacePrefs> {
// JSON drops an undefined deviceId.
return call('PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, {
document,
revision,
deviceId
})
},
/** The org's link slug; `name` (the org name this client shows) names it the first time. */
getOrgSlug(name?: string | null): Promise<CloudOrgSlug> {
const qs = name ? `?${new URLSearchParams({ name: name.slice(0, 120) })}` : ''
return call('GET', `/v1/team/org${qs}`, CloudOrgSlugSchema)
}
}
}
@@ -5,9 +5,11 @@ import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store
import { openSealedGrant } from '../../shared/cloud-workspaces/sealed-grant'
import { errorMessage } from '../../shared/error-message'
import type {
CloudWorkspaceLinkTarget,
CloudWorkspace,
CloudWorkspaceListQuery,
CloudWorkspacePatch,
CloudWorkspacePrefsDocument,
CloudWorkspaceRoutineRuns,
OrgPrompts
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
@@ -30,7 +32,7 @@ const TYPING_HOLD_MS = 6_000
export type CloudWorkspacesResult<T> =
| { ok: true; value: T }
| { ok: false; error: string; reason?: string; status?: number }
| { ok: false; error: string; reason?: string; status?: number; orgId?: string }
/** A list read, plus what Home's Routine runs switch hides (absent from older control planes). */
export type CloudWorkspaceListResult =
@@ -49,7 +51,13 @@ async function wrap<T>(run: () => Promise<T>): Promise<CloudWorkspacesResult<T>>
return { ok: true, value: await run() }
} catch (error) {
if (error instanceof CloudWorkspacesError) {
return { ok: false, error: error.code, reason: error.reason, status: error.status }
return {
ok: false,
error: error.code,
reason: error.reason,
status: error.status,
...(error.orgId ? { orgId: error.orgId } : {})
}
}
return { ok: false, error: 'internal_error', reason: errorMessage(error).slice(0, 200) }
}
@@ -165,8 +173,12 @@ export function createCloudWorkspacesService(deps: {
get: (id: string) => wrap(() => client.get(id)),
patch: (id: string, patch: CloudWorkspacePatch) =>
wrap(async () => (await client.patch(id, patch)).workspace),
resolveLink: (workspaceId: string, chatId?: string | null) =>
wrap(() => client.resolveLink(workspaceId, chatId)),
resolveLink: (target: CloudWorkspaceLinkTarget, chatId?: string | null) =>
wrap(() => client.resolveLink(target, chatId)),
getPrefs: () => wrap(() => client.getPrefs()),
putPrefs: (document: CloudWorkspacePrefsDocument, revision: number) =>
wrap(() => client.putPrefs(document, revision, deps.clientId)),
getOrgSlug: (name?: string | null) => wrap(() => client.getOrgSlug(name)),
listGrants: (id: string) => wrap(() => client.listGrants(id)),
revokeGrant: (id: string, grantId: string) =>
wrap(async () => void (await client.revokeGrant(id, grantId))),
+31
View File
@@ -0,0 +1,31 @@
// IPC for synced cloud workspace prefs (pins, order, sections) and the org's link slug.
// Registered with the other cloud workspace handlers; same `not_configured` contract.
import { z } from 'zod'
import { CloudWorkspacePrefsDocumentSchema } from '../../shared/cloud-workspaces/cloud-workspaces-wire'
import type { CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service'
const NOT_CONFIGURED = { ok: false as const, error: 'not_configured' }
const INVALID = { ok: false as const, error: 'invalid_request' }
export function registerCloudWorkspacePrefsHandlers(
handle: (channel: string, fn: (args: unknown) => unknown) => void,
getService: () => Promise<CloudWorkspacesService | null>
): void {
handle('cloudWorkspaces:getPrefs', async () => (await getService())?.getPrefs() ?? NOT_CONFIGURED)
handle('cloudWorkspaces:putPrefs', async (args) => {
const parsed = z
.object({ document: CloudWorkspacePrefsDocumentSchema, revision: z.number().int().min(0) })
.safeParse(args)
const s = await getService()
return !s
? NOT_CONFIGURED
: parsed.success
? s.putPrefs(parsed.data.document, parsed.data.revision)
: INVALID
})
handle('cloudWorkspaces:getOrgSlug', async (args) => {
const parsed = z.object({ orgName: z.string().max(200).nullable().optional() }).safeParse(args)
const s = await getService()
return !s ? NOT_CONFIGURED : s.getOrgSlug(parsed.success ? parsed.data.orgName : null)
})
}
+12 -2
View File
@@ -18,11 +18,20 @@ import {
import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader'
import { registerTeamPresenceHandlers } from './cloud-workspaces-team-presence'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import { registerCloudWorkspacePrefsHandlers } from './cloud-workspaces-prefs'
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/)
const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/)
const ChatId = z.string().min(1).max(256)
const LinkTarget = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('id'), workspaceId: Id }),
z.object({
kind: z.literal('number'),
org: z.string().regex(/^[a-z0-9-]{1,40}$/),
number: z.number().int().min(1).max(999_999_999)
})
])
const ListQuery = z
.object({
scope: z.enum(['mine', 'team', 'all']).optional(),
@@ -217,13 +226,13 @@ export function registerCloudWorkspacesHandlers(): void {
})
handle('cloudWorkspaces:resolveLink', async (args) => {
const parsed = z
.object({ workspaceId: Id, chatId: ChatId.nullable().optional() })
.object({ target: LinkTarget, chatId: ChatId.nullable().optional() })
.safeParse(args)
const s = await getService()
return !s
? NOT_CONFIGURED
: parsed.success
? s.resolveLink(parsed.data.workspaceId, parsed.data.chatId)
? s.resolveLink(parsed.data.target, parsed.data.chatId)
: INVALID
})
handle('cloudWorkspaces:openGrant', async (args) => {
@@ -307,6 +316,7 @@ export function registerCloudWorkspacesHandlers(): void {
? s.putOrgPrompts(parsed.data.document, parsed.data.revision)
: INVALID
})
registerCloudWorkspacePrefsHandlers(handle, getService)
registerTeamPresenceHandlers(handle, getService)
// Handlers are re-registered per main window; the quit hook must only be added once.
if (!quitHookInstalled) {
@@ -7,7 +7,8 @@ import type {
OrcaBillingOverageResult,
OrcaBillingStatusResult,
OrcaBillingTeamPlansResult,
OrcaBillingTrialClaimResult
OrcaBillingTrialClaimResult,
OrcaBillingUsageHistoryResult
} from '../../../shared/orca-billing'
import {
ORCA_BILLING_INTERVALS,
@@ -19,6 +20,7 @@ import {
claimOrcaBillingTrial,
getOrcaBillingStatus,
getOrcaBillingTeamPlans,
getOrcaBillingUsageHistory,
openOrcaBillingCheckout,
openOrcaBillingPortal,
setOrcaBillingOverage
@@ -59,6 +61,21 @@ const OverageArgs = z
})
.strict()
// Minutes east of UTC (the renderer's -getTimezoneOffset()), so chart days are local days.
const UsageHistoryArgs = z
.object({ utcOffsetMinutes: z.number().int().min(-840).max(840) })
.strict()
export function billingUsageHistoryArgsFromUnknown(args: unknown): {
utcOffsetMinutes: number
} {
const parsed = UsageHistoryArgs.safeParse(args)
if (!parsed.success) {
throw new Error('invalid_orca_billing_usage_history')
}
return parsed.data
}
const TeamPlansArgs = z
.object({
orgIds: z
@@ -73,7 +90,9 @@ const TeamPlansArgs = z
})
.strict()
export function billingTeamPlansArgsFromUnknown(args: unknown): { orgIds: string[] } {
export function billingTeamPlansArgsFromUnknown(args: unknown): {
orgIds: string[]
} {
const parsed = TeamPlansArgs.safeParse(args)
if (!parsed.success) {
throw new Error('invalid_orca_billing_team_plans')
@@ -148,6 +167,14 @@ export function registerOrcaProfileBillingHandlers(store: Store): void {
async (_event, rawArgs: unknown): Promise<OrcaBillingOverageResult> =>
setOrcaBillingOverage(getProfileUserDataPath(), billingOverageArgsFromUnknown(rawArgs))
)
ipcMain.handle(
'orcaProfiles:billingUsageHistory',
async (_event, rawArgs: unknown): Promise<OrcaBillingUsageHistoryResult> =>
getOrcaBillingUsageHistory(
getProfileUserDataPath(),
billingUsageHistoryArgsFromUnknown(rawArgs).utcOffsetMinutes
)
)
ipcMain.handle(
'orcaProfiles:billingTeamPlans',
async (_event, rawArgs: unknown): Promise<OrcaBillingTeamPlansResult> =>
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { normalizeRoster } from './profile-cloud-org-members-client'
describe('normalizeRoster', () => {
it('keeps https profile pictures and drops anything else', () => {
const roster = normalizeRoster({
viewerRole: 'member',
canManageMembers: false,
pendingInvites: [],
members: [
{
userId: 'a',
email: 'a@x.dev',
role: 'member',
pictureUrl: 'https://img.propelauth.com/a.png'
},
{ userId: 'b', email: 'b@x.dev', role: 'member', pictureUrl: 'http://x.dev/b.png' },
{ userId: 'c', email: 'c@x.dev', role: 'member', pictureUrl: 'javascript:alert(1)' },
{ userId: 'd', email: 'd@x.dev', role: 'member', pictureUrl: 'file:///etc/passwd' },
{ userId: 'e', email: 'e@x.dev', role: 'member' }
]
})
expect(roster.members.map((m) => m.pictureUrl)).toEqual([
'https://img.propelauth.com/a.png',
undefined,
undefined,
undefined,
undefined
])
expect('pictureUrl' in roster.members[4]!).toBe(false)
})
})
@@ -40,6 +40,19 @@ function normalizeTimestamp(value: unknown): number {
return Date.now()
}
// The renderer loads this image, so only a plain https URL from auth is kept.
function optionalPictureUrl(value: unknown): string | undefined {
if (typeof value !== 'string' || value.length > 2048) {
return undefined
}
try {
const url = new URL(value)
return url.protocol === 'https:' && !url.username && !url.password ? url.toString() : undefined
} catch {
return undefined
}
}
function normalizeMember(value: unknown): OrcaOrgMember | null {
if (!value || typeof value !== 'object') {
return null
@@ -54,6 +67,9 @@ function normalizeMember(value: unknown): OrcaOrgMember | null {
userId: userId ?? null,
email,
displayName: optionalString(record.displayName),
...(optionalPictureUrl(record.pictureUrl)
? { pictureUrl: optionalPictureUrl(record.pictureUrl) }
: {}),
role: normalizeRole(record.role, 'member')
}
}
@@ -74,7 +90,7 @@ function normalizePendingInvite(value: unknown): OrcaOrgPendingInvite | null {
}
}
function normalizeRoster(value: unknown): OrcaOrgMembersRoster {
export function normalizeRoster(value: unknown): OrcaOrgMembersRoster {
if (!value || typeof value !== 'object') {
throw new Error('invalid_orca_org_members_roster')
}
+16 -2
View File
@@ -1,8 +1,12 @@
import type {
CloudWorkspace,
CloudWorkspaceGrant,
CloudOrgSlug,
CloudWorkspaceLinkTarget,
CloudWorkspaceListQuery,
CloudWorkspacePatch,
CloudWorkspacePrefs,
CloudWorkspacePrefsDocument,
CloudWorkspaceRoutineRuns,
OrgPrompts
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
@@ -11,7 +15,7 @@ import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-
export type CloudWorkspacesResult<T> =
| { ok: true; value: T }
| { ok: false; error: string; reason?: string; status?: number }
| { ok: false; error: string; reason?: string; status?: number; orgId?: string }
/** A list read, plus what Home's Routine runs switch hides (absent from older control planes). */
export type CloudWorkspaceListResult =
@@ -33,8 +37,9 @@ export type CloudWorkspacesApi = {
list: (query: CloudWorkspaceListQuery) => Promise<CloudWorkspaceListResult>
get: (id: string) => Promise<CloudWorkspacesResult<CloudWorkspace>>
patch: (id: string, patch: CloudWorkspacePatch) => Promise<CloudWorkspacesResult<CloudWorkspace>>
/** Resolves either link form; a slug link for another org fails with reason `other_org` and its `orgId`. */
resolveLink: (
workspaceId: string,
target: CloudWorkspaceLinkTarget,
chatId?: string | null
) => Promise<CloudWorkspacesResult<{ workspace: CloudWorkspace; chatId: string | null }>>
/** A fresh per-device pairing link for a teammate's workspace (E2EE grant, opened in main). */
@@ -69,6 +74,15 @@ export type CloudWorkspacesApi = {
document: OrgPrompts['document'],
revision: number
) => Promise<CloudWorkspacesResult<OrgPrompts>>
/** This member's synced sidebar arrangement of cloud workspaces (pins, order, sections). */
getPrefs: () => Promise<CloudWorkspacesResult<CloudWorkspacePrefs>>
/** Compare-and-set on `revision`; a stale write fails with `conflict`. */
putPrefs: (
document: CloudWorkspacePrefsDocument,
revision: number
) => Promise<CloudWorkspacesResult<CloudWorkspacePrefs>>
/** The org's link slug; `orgName` names it the first time anyone asks. */
getOrgSlug: (orgName?: string | null) => Promise<CloudWorkspacesResult<CloudOrgSlug>>
/** A teammate's profile: usage heatmap (levels only unless it is you) and workspaces you can see. */
teammateProfile: (
userId: string,
+6 -2
View File
@@ -6,8 +6,8 @@ export const cloudWorkspacesApi = {
list: (query) => ipcRenderer.invoke('cloudWorkspaces:list', query),
get: (id) => ipcRenderer.invoke('cloudWorkspaces:get', { id }),
patch: (id, patch) => ipcRenderer.invoke('cloudWorkspaces:patch', { id, patch }),
resolveLink: (workspaceId, chatId) =>
ipcRenderer.invoke('cloudWorkspaces:resolveLink', { workspaceId, chatId }),
resolveLink: (target, chatId) =>
ipcRenderer.invoke('cloudWorkspaces:resolveLink', { target, chatId }),
openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }),
readSnapshot: (id) => ipcRenderer.invoke('cloudWorkspaces:readSnapshot', { id }),
listGrants: (id) => ipcRenderer.invoke('cloudWorkspaces:listGrants', { id }),
@@ -27,6 +27,10 @@ export const cloudWorkspacesApi = {
getOrgPrompts: () => ipcRenderer.invoke('cloudWorkspaces:getOrgPrompts'),
putOrgPrompts: (document, revision) =>
ipcRenderer.invoke('cloudWorkspaces:putOrgPrompts', { document, revision }),
getPrefs: () => ipcRenderer.invoke('cloudWorkspaces:getPrefs'),
putPrefs: (document, revision) =>
ipcRenderer.invoke('cloudWorkspaces:putPrefs', { document, revision }),
getOrgSlug: (orgName) => ipcRenderer.invoke('cloudWorkspaces:getOrgSlug', { orgName }),
teammateProfile: (userId, utcOffsetMin) =>
ipcRenderer.invoke('cloudWorkspaces:teammateProfile', { userId, utcOffsetMin }),
poke: (userId) => ipcRenderer.invoke('cloudWorkspaces:poke', { userId }),
+6 -1
View File
@@ -44,7 +44,8 @@ import type {
OrcaBillingTrialClaimResult,
OrcaBillingReturn,
OrcaBillingStatusResult,
OrcaBillingTeamPlansResult
OrcaBillingTeamPlansResult,
OrcaBillingUsageHistoryResult
} from '../../shared/orca-billing'
import type { OrcaCloudSetupReturn } from '../../shared/orca-cloud-setup-link'
@@ -112,6 +113,10 @@ export type OrcaProfileApi = {
cloudSetupLink: (args: { sessionId: string }) => Promise<CloudSetupLinkResult>
/** Opens the Stripe Customer Portal in the browser. */
billingOpenPortal: () => Promise<OrcaBillingOpenResult>
/** The last 30 days of sandbox hours (breakdowns for owners and admins only). */
billingUsageHistory: (args: {
utcOffsetMinutes: number
}) => Promise<OrcaBillingUsageHistoryResult>
/** Plan state for other teams the user is on ("Switch to <team>"); never switches teams. */
billingTeamPlans: (args: { orgIds: string[] }) => Promise<OrcaBillingTeamPlansResult>
/** Opt in/out of sandbox overage and set the monthly spend cap (org admins). */
+1
View File
@@ -96,6 +96,7 @@ export const orcaProfilesApi = {
billingOpenCheckout: (args) => ipcRenderer.invoke('orcaProfiles:billingOpenCheckout', args),
billingOpenPortal: () => ipcRenderer.invoke('orcaProfiles:billingOpenPortal'),
billingTeamPlans: (args) => ipcRenderer.invoke('orcaProfiles:billingTeamPlans', args),
billingUsageHistory: (args) => ipcRenderer.invoke('orcaProfiles:billingUsageHistory', args),
cloudSetupStart: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupStart', args),
cloudSetupGet: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupGet', args),
cloudSetupLink: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupLink', args),
@@ -10,6 +10,7 @@ import { selectActiveTerminalChromeState } from './active-terminal-chrome-select
import { hasCustomTitleBar } from './app-window-chrome'
import type { AppChromeLayout } from './use-app-chrome-layout'
import { RunActionButton } from '../components/run-actions/RunActionButton'
import { CloudWorkspaceNumberChip } from '../components/cloud-workspaces/CloudWorkspaceNumberChip'
export function RightSidebarToggle(): React.JSX.Element {
const t = useTranslate()
@@ -68,6 +69,9 @@ export function TitlebarMainStrip({ layout }: { layout: AppChromeLayout }): Reac
className={`flex flex-1 min-w-0 self-stretch${!layout.workspaceChromeActive ? ' invisible pointer-events-none' : ''}`}
/>
)}
{layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? (
<CloudWorkspaceNumberChip worktreeId={activeWorktreeId} />
) : null}
{layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? (
<RunActionButton worktreeId={activeWorktreeId} />
) : null}
@@ -1,6 +1,12 @@
import { defineFixture } from '../../component-fixtures/component-fixture'
import { PlanBillingView } from './PlanBillingSection'
import { sampleTeam, sampleTrial, sampleTrialUsedUp } from './plan-billing-fixtures'
import {
sampleTeam,
sampleTrial,
sampleTrialUsedUp,
sampleUsageHistory,
sampleUsageNames
} from './plan-billing-fixtures'
const HOUR = 3600
@@ -14,9 +20,19 @@ const handlers = {
onSeePlans: () => {}
}
const usage = { status: 'ok', history: sampleUsageHistory, names: sampleUsageNames } as const
// JA-18: "<Team> · Team plan", the last 30 days with top workspaces and members, one cap field.
export const activeTeam = defineFixture({
width: 600,
render: () => <PlanBillingView {...handlers} result={{ status: 'ok', entitlement: sampleTeam }} />
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={usage}
result={{ status: 'ok', entitlement: sampleTeam }}
/>
)
})
export const noPlan = defineFixture({
@@ -1,11 +1,10 @@
import { useState } from 'react'
import { CreditCard, ExternalLink, RefreshCw } from 'lucide-react'
import { ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { Skeleton } from '@/components/ui/skeleton'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { formatCents } from './plans/plans-pricing'
import { cn } from '@/lib/utils'
import {
isOrcaCloudTrial,
type OrcaBillingOpenResult,
@@ -23,6 +22,12 @@ import { useOrcaBillingStatus } from './use-orca-billing-status'
import { useAppStore } from '@/store/index'
import { usageAlertLevel } from '../../../../shared/orca-billing-usage-alerts'
import { BILLING_CAPABILITY } from './register-plan-billing-menu-item'
import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup'
import { PlanBillingUsageHistory } from './PlanBillingUsageHistory'
import {
usePlanBillingUsageHistory,
type PlanBillingUsageState
} from './use-plan-billing-usage-history'
export function PlanBillingSection(): React.JSX.Element | null {
const t = useTranslate()
@@ -34,8 +39,20 @@ export function PlanBillingSection(): React.JSX.Element | null {
)
const [busy, setBusy] = useState(false)
const [notice, setNotice] = useState<PlanBillingNotice | null>(null)
const [userRefreshing, setUserRefreshing] = useState(false)
const [overageFailures, setOverageFailures] = useState(0)
const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud)
const entitlement = result?.status === 'ok' ? result.entitlement : null
const hasPlan =
entitlement !== null && entitlement.plan !== null && entitlement.status !== 'canceled'
// Re-read the history with every billing read (it re-reads on window focus).
const usage = usePlanBillingUsageHistory(
hasPlan && cloud
? `${cloud.userId}:${cloud.activeOrgId ?? ''}|${entitlement.usedSeconds}`
: null,
cloud?.activeOrgId ?? null,
cloud?.userId ?? null,
entitlement?.canManageBilling === true
)
const run = async (open: () => Promise<OrcaBillingOpenResult>): Promise<void> => {
setBusy(true)
@@ -85,15 +102,12 @@ export function PlanBillingSection(): React.JSX.Element | null {
<PlanBillingView
result={result}
loading={loading && (result !== null || billingFlagged)}
refreshing={userRefreshing}
busy={busy}
notice={notice}
onRefresh={() => {
// Spin only for a refresh the user asked for, and long enough to be seen (review M16).
setUserRefreshing(true)
refresh()
window.setTimeout(() => setUserRefreshing(false), 400)
}}
teamName={cloud?.activeOrgName ?? null}
usage={usage.state}
onRetryUsage={usage.retry}
onRefresh={refresh}
onPortal={() => void run(() => window.api.orcaProfiles.billingOpenPortal())}
overageFailures={overageFailures}
onSetOverage={(args) => void setOverage(args)}
@@ -102,15 +116,21 @@ export function PlanBillingSection(): React.JSX.Element | null {
)
}
const noop = (): void => {}
export type PlanBillingNotice = { kind: 'error' | 'info'; text: string }
export type PlanBillingViewProps = {
result: OrcaBillingStatusResult | null
loading: boolean
/** A user-requested refresh is running; background re-reads (window focus) never spin. */
refreshing?: boolean
busy: boolean
notice: PlanBillingNotice | null
/** The active team's name, for the "<Team> · Team plan" title. */
teamName?: string | null
/** The last 30 days; absent (fixtures without history) renders nothing. */
usage?: PlanBillingUsageState
onRetryUsage?: () => void
/** Re-reads the plan after a failed load (the page otherwise re-reads on window focus). */
onRefresh: () => void
onPortal: () => void
onSetOverage: (args: OrcaBillingOverageArgs) => void
@@ -122,9 +142,11 @@ export type PlanBillingViewProps = {
export function PlanBillingView({
result,
loading,
refreshing = false,
busy,
notice,
teamName = null,
usage,
onRetryUsage = noop,
onRefresh,
onPortal,
onSetOverage,
@@ -151,20 +173,6 @@ export function PlanBillingView({
return null
}
// Settings › Orca Cloud › Plan & billing owns the title; the refresh sits with the plan it reloads.
const refreshButton = (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-disabled={refreshing || undefined}
onClick={refreshing ? undefined : onRefresh}
aria-label={t('auto.components.billing.refresh', 'Refresh plan')}
>
<RefreshCw className={cn(refreshing && 'motion-safe:animate-spin')} />
</Button>
)
if (result.status === 'failed') {
return (
<div className="space-y-3">
@@ -190,25 +198,36 @@ export function PlanBillingView({
<div className="space-y-4">
<PaymentIssueNotice entitlement={entitlement} busy={busy} onUpdatePayment={onPortal} />
{hasPlan ? (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<CreditCard className="size-4 text-muted-foreground" />
<p className="text-sm font-medium">{entitlement.planLabel}</p>
<span className="text-xs text-muted-foreground">
{entitlement.interval === 'year'
? t('auto.components.billing.seatsAnnual', '{{count}} seats · Annual', {
count: entitlement.seats,
defaultValue_one: '{{count}} seat · Annual'
})
: t('auto.components.billing.seatsMonthly', '{{count}} seats · Monthly', {
count: entitlement.seats,
defaultValue_one: '{{count}} seat · Monthly'
})}
</span>
<PlanStatusBadge entitlement={entitlement} />
<span className="ml-auto">{refreshButton}</span>
<div className="space-y-6">
<div className="space-y-4">
<SettingsGroupHeader
className="px-0"
title={
teamName
? t('auto.components.billing.teamPlanTitle', '{{team}} · {{plan}} plan', {
team: teamName,
plan: entitlement.planLabel
})
: t('auto.components.billing.planTitle', '{{plan}} plan', {
plan: entitlement.planLabel
})
}
description={
entitlement.interval === 'year'
? t('auto.components.billing.seatsAnnual', '{{count}} seats · Annual', {
count: entitlement.seats,
defaultValue_one: '{{count}} seat · Annual'
})
: t('auto.components.billing.seatsMonthly', '{{count}} seats · Monthly', {
count: entitlement.seats,
defaultValue_one: '{{count}} seat · Monthly'
})
}
action={<PlanStatusBadge entitlement={entitlement} />}
/>
<UsageSummary entitlement={entitlement} />
</div>
<UsageSummary entitlement={entitlement} />
{usage ? <PlanBillingUsageHistory state={usage} onRetry={onRetryUsage} /> : null}
{/* Overage is moot while sandboxes are suspended for a failed payment. */}
{entitlement.payment.suspendRunning ? null : (
<OverageControls
@@ -273,12 +292,16 @@ export function PlanBillingView({
</Button>
) : null}
{hasPlan ? (
<Button type="button" variant="ghost" size="sm" onClick={onSeePlans}>
// Members have no other action here, so it gets the button's chrome (and its alignment).
<Button
type="button"
variant={entitlement.canManageBilling ? 'ghost' : 'outline'}
size="sm"
onClick={onSeePlans}
>
{t('auto.components.billing.comparePlans', 'Compare plans')}
</Button>
) : (
<span className="ml-auto">{refreshButton}</span>
)}
) : null}
</div>
{/* The payment alert already says who to ask; don't ask twice. */}
@@ -0,0 +1,174 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing'
import { OverageControls } from './PlanBillingUsage'
import { PlanBillingUsageHistory } from './PlanBillingUsageHistory'
import { PlanBillingView } from './PlanBillingSection'
import { sampleTeam, sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
import { UsageHistoryChart } from './UsageHistoryChart'
afterEach(cleanup)
const overageOn: OrcaBillingEntitlement = {
...sampleTeam,
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
}
function capField(): HTMLInputElement {
const field = screen.getByLabelText('Monthly spend cap')
if (!(field instanceof HTMLInputElement)) {
throw new Error('the spend cap is not an input')
}
return field
}
describe('spend cap field', () => {
it('shows $0 while overage is off and turns it on at the default cap in one click', () => {
const onSetOverage = vi.fn()
render(<OverageControls entitlement={sampleTeam} busy={false} onSetOverage={onSetOverage} />)
expect(capField().value).toBe('0')
expect(screen.queryByRole('switch')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Turn on with a $25 cap' }))
expect(onSetOverage).toHaveBeenCalledWith({ enabled: true, spendCapCents: 2500 })
expect(capField().value).toBe('25')
})
it('saves a new cap, and $0 turns overage off', () => {
const onSetOverage = vi.fn()
render(<OverageControls entitlement={overageOn} busy={false} onSetOverage={onSetOverage} />)
expect(capField().value).toBe('40')
fireEvent.change(capField(), { target: { value: '60' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
expect(onSetOverage).toHaveBeenLastCalledWith({ enabled: true, spendCapCents: 6000 })
cleanup()
render(<OverageControls entitlement={overageOn} busy={false} onSetOverage={onSetOverage} />)
fireEvent.change(capField(), { target: { value: '0' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
expect(onSetOverage).toHaveBeenLastCalledWith({ enabled: false })
})
it('puts the rate in one hint and keeps the alert sentence', () => {
render(<OverageControls entitlement={sampleTeam} busy={false} onSetOverage={() => {}} />)
expect(capField().getAttribute('aria-describedby')).toBeTruthy()
expect(
screen.getByText(
'$1.00 per sandbox hour after your included hours, billed by the minute. $0 keeps overage off.'
)
).toBeTruthy()
expect(screen.getByText(/alerted in Orca at 75%, 90% and 100%/)).toBeTruthy()
})
it('shows members the setting as text', () => {
render(
<OverageControls
entitlement={{ ...overageOn, canManageBilling: false }}
busy={false}
onSetOverage={() => {}}
/>
)
expect(screen.queryByLabelText('Monthly spend cap')).toBeNull()
expect(screen.getByText('On, up to $40 a month.')).toBeTruthy()
expect(screen.queryByText(/alerted in Orca/)).toBeNull()
})
})
describe('last 30 days', () => {
it('reads each day with the arrow keys and lists every day in a table', () => {
render(<UsageHistoryChart days={sampleUsageHistory.days} />)
const chart = screen.getByRole('group')
fireEvent.focus(chart)
expect(screen.getByRole('status').textContent).toMatch(/· 0\.6 sandbox hours$/)
fireEvent.keyDown(chart, { key: 'ArrowLeft' })
expect(screen.getByRole('status').textContent).toMatch(/· 1\.5 sandbox hours$/)
fireEvent.keyDown(chart, { key: 'Home' })
expect(screen.getByRole('status').textContent).toMatch(/· 0\.5 sandbox hours$/)
expect(screen.getAllByRole('row')).toHaveLength(30)
})
it('shows owners the top workspaces and members, and members only their share', () => {
render(
<PlanBillingUsageHistory
state={{ status: 'ok', history: sampleUsageHistory, names: sampleUsageNames }}
onRetry={() => {}}
/>
)
expect(screen.getByText('Top workspaces')).toBeTruthy()
expect(screen.getByText('Checkout retries')).toBeTruthy()
expect(screen.getByText('48 sandbox hours in 30 days')).toBeTruthy()
cleanup()
render(
<PlanBillingUsageHistory
state={{
status: 'ok',
history: { ...sampleUsageHistory, members: null, sandboxes: null },
names: sampleUsageNames
}}
onRetry={() => {}}
/>
)
expect(screen.queryByText('Top workspaces')).toBeNull()
expect(screen.getByText('You used 18.4 of your team’s 48 sandbox hours.')).toBeTruthy()
})
it('has empty, loading and error states', () => {
const onRetry = vi.fn()
render(<PlanBillingUsageHistory state={{ status: 'failed' }} onRetry={onRetry} />)
fireEvent.click(screen.getByRole('button', { name: 'Try again' }))
expect(onRetry).toHaveBeenCalled()
cleanup()
render(<PlanBillingUsageHistory state={{ status: 'loading' }} onRetry={onRetry} />)
expect(screen.getByRole('status', { name: 'Loading your usage history…' })).toBeTruthy()
cleanup()
const empty = {
...sampleUsageHistory,
days: sampleUsageHistory.days.map((day) => ({ ...day, seconds: 0 })),
totalSeconds: 0
}
render(
<PlanBillingUsageHistory
state={{ status: 'ok', history: empty, names: sampleUsageNames }}
onRetry={onRetry}
/>
)
expect(screen.getByText(/No sandbox hours yet/)).toBeTruthy()
expect(screen.queryByRole('group')).toBeNull()
})
})
describe('plan header', () => {
it('titles the page "<Team> · Team plan" with no refresh button', () => {
render(
<PlanBillingView
result={{ status: 'ok', entitlement: sampleTeam }}
loading={false}
busy={false}
notice={null}
teamName="Orca Staging Eval Team"
onRefresh={() => {}}
onPortal={() => {}}
onSetOverage={() => {}}
onSeePlans={() => {}}
/>
)
expect(screen.getByRole('heading', { name: 'Orca Staging Eval Team · Team plan' })).toBeTruthy()
expect(screen.queryByRole('button', { name: 'Refresh plan' })).toBeNull()
})
})
it('gives members an outlined Compare plans and the off line', () => {
render(
<PlanBillingView
result={{ status: 'ok', entitlement: { ...sampleTeam, canManageBilling: false } }}
loading={false}
busy={false}
notice={null}
onRefresh={() => {}}
onPortal={() => {}}
onSetOverage={() => {}}
onSeePlans={() => {}}
/>
)
expect(screen.getByText('Off. Ask an owner or admin to turn it on.')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Compare plans' }).className).toMatch(/border/)
})
@@ -4,7 +4,6 @@ import { Button } from '@/components/ui/button'
import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip'
import { Input } from '@/components/ui/input'
import { Progress } from '@/components/ui/progress'
import { Switch } from '@/components/ui/switch'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import type {
OrcaBillingEntitlement,
@@ -35,7 +34,9 @@ function resetLine(
value0: resets,
value1: ends
})
: t('auto.components.billing.endsOn', 'Plan ends {{value0}}', { value0: ends })
: t('auto.components.billing.endsOn', 'Plan ends {{value0}}', {
value0: ends
})
}
if (resets && ends) {
return resets === ends
@@ -48,9 +49,15 @@ function resetLine(
})
}
if (resets) {
return t('auto.components.billing.resets', 'Hours reset {{value0}}', { value0: resets })
return t('auto.components.billing.resets', 'Hours reset {{value0}}', {
value0: resets
})
}
return ends ? t('auto.components.billing.renewsOn', 'Renews {{value0}}', { value0: ends }) : null
return ends
? t('auto.components.billing.renewsOn', 'Renews {{value0}}', {
value0: ends
})
: null
}
export function UsageSummary({
@@ -106,30 +113,28 @@ export function OverageControls({
const t = useTranslate()
const locale = useIntlLocale()
const capId = useId()
const descriptionId = useId()
const hintId = useId()
const capErrorId = useId()
const savedRef = useRef<HTMLSpanElement>(null)
const { overage } = entitlement
const savedDollars = String(Math.round(overage.spendCapCents / 100))
// One field: the cap while overage is on, $0 while it's off.
const savedDollars = overage.optedIn ? String(Math.round(overage.spendCapCents / 100)) : '0'
const defaultCapCents = entitlement.offers?.team.defaultSpendCapCents ?? 2500
const [capDollars, setCapDollars] = useState(savedDollars)
// Shows "Saved" after a successful cap change until the field is edited again (review M13).
// Shows "Saved" after a successful change until the field is edited again (review M13).
const [savedFlash, setSavedFlash] = useState(false)
// The switch flips at once; the saved value takes over when billing answers.
const [optimisticOn, setOptimisticOn] = useState<boolean | null>(null)
// Re-seed from the server whenever the saved values change (render-time adjustment, no effect).
const [seededFrom, setSeededFrom] = useState(`${savedDollars}:${overage.optedIn}`)
if (seededFrom !== `${savedDollars}:${overage.optedIn}`) {
setSeededFrom(`${savedDollars}:${overage.optedIn}`)
const [seededFrom, setSeededFrom] = useState(savedDollars)
if (seededFrom !== savedDollars) {
setSeededFrom(savedDollars)
setCapDollars(savedDollars)
setOptimisticOn(null)
}
const [seenFailures, setSeenFailures] = useState(failures)
if (seenFailures !== failures) {
setSeenFailures(failures)
setOptimisticOn(null)
setCapDollars(savedDollars)
setSavedFlash(false)
}
const optedIn = optimisticOn ?? overage.optedIn
const parsedCap = Number(capDollars)
const maxCapCents = entitlement.offers?.team.maxSpendCapCents ?? null
const capWhole = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0
@@ -137,18 +142,11 @@ export function OverageControls({
const capValid = capWhole && !capTooHigh
const changed = capValid && capDollars.trim() !== savedDollars
const paymentFailed = entitlement.payment.pastDueSince !== null
const description = t(
'auto.components.billing.overageDescription7',
'Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set ({{cap}} by default).',
{
rate: formatRateCents(overage.centsPerHour, locale),
cap: formatCents(entitlement.offers?.team.defaultSpendCapCents ?? 2500, locale)
}
)
const descriptionOn = t(
'auto.components.billing.overageDescriptionOn4',
'Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set.',
{ rate: formatRateCents(overage.centsPerHour, locale) }
const rate = formatRateCents(overage.centsPerHour, locale)
const hint = t(
'auto.components.billing.overage.capHint',
'{{rate}} per sandbox hour after your included hours, billed by the minute. $0 keeps overage off.',
{ rate }
)
const capPercent =
overage.spendCapCents > 0
@@ -169,155 +167,147 @@ export function OverageControls({
</p>
</div>
)
const title = (
<p className="text-sm font-medium">{t('auto.components.billing.overageTitle', 'Overage')}</p>
)
// Members see the setting as plain text: a switch they can't use only invites clicks.
// Members see the setting as plain text: a field they can't use only invites clicks.
if (!entitlement.canManageBilling) {
return (
<div className="space-y-2 rounded-md border border-border/60 p-3">
<p className="text-sm">
<span className="font-medium">
{t('auto.components.billing.overageTitle', 'Overage')}
</span>
<span className="text-muted-foreground">
{' · '}
{overage.optedIn
? t('auto.components.billing.overageOnRead', 'On')
: t('auto.components.billing.overageOffRead', 'Off')}
</span>
{title}
<p className="text-xs text-muted-foreground tabular-nums">
{overage.optedIn
? t('auto.components.billing.overage.memberOn', 'On, up to {{cap}} a month.', {
cap: formatCents(overage.spendCapCents, locale)
})
: t(
'auto.components.billing.overage.memberOff2',
'Off. Ask an owner or admin to turn it on.'
)}
</p>
{overage.optedIn ? spent : null}
<p className="text-xs text-muted-foreground">
{t('auto.components.billing.overageMemberHint', 'Owners and admins can change overage.')}
</p>
</div>
)
}
const toggleBlocked = busy || paymentFailed
const save = (enabled: boolean, cents: number): void => {
onSetOverage(enabled ? { enabled: true, spendCapCents: cents } : { enabled: false })
setSavedFlash(true)
// The action turns into "Saving…" in place; move focus onto it.
window.requestAnimationFrame(() => savedRef.current?.focus())
}
const blockedReason = paymentFailed
? t(
'auto.components.billing.overagePaymentFailed',
'Update the payment method before changing overage.'
)
: undefined
return (
// Deep-link target: the Run-on picker's "Turn on overage" / "Raise cap" lands here.
<div
id={ORCA_BILLING_OVERAGE_SECTION_ID}
className="space-y-3 rounded-md border border-border/60 p-3"
>
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
<p className="text-sm font-medium">
{t('auto.components.billing.overageTitle', 'Overage')}
</p>
<p id={descriptionId} className="text-xs text-muted-foreground">
{optedIn ? descriptionOn : description}
</p>
<p className="text-xs text-muted-foreground">
{t(
'auto.components.billing.usageAlertsNote',
'Owners and admins are alerted in Orca at 75%, 90% and 100% of your team’s sandbox hours.'
)}
</p>
</div>
<SettingsDisabledControlTooltip
reason={
paymentFailed
? t(
'auto.components.billing.overagePaymentFailed',
'Update the payment method before changing overage.'
)
: undefined
{title}
<form
className="flex flex-wrap items-start gap-2"
onSubmit={(event) => {
event.preventDefault()
if (changed && !busy && !paymentFailed) {
save(parsedCap > 0, parsedCap * 100)
}
>
<Switch
checked={optedIn}
// aria-disabled keeps focus on the switch while a change saves.
aria-disabled={toggleBlocked || undefined}
aria-describedby={descriptionId}
onCheckedChange={(enabled) => {
if (toggleBlocked) {
return
}
setOptimisticOn(enabled)
onSetOverage({ enabled })
}}
aria-label={t('auto.components.billing.overageToggle', 'Allow overage')}
/>
</SettingsDisabledControlTooltip>
</div>
{optedIn ? (
<div className="space-y-3">
{spent}
{paymentFailed ? null : (
<form
className="flex flex-wrap items-start gap-2"
onSubmit={(event) => {
event.preventDefault()
if (changed && !busy) {
onSetOverage({ enabled: true, spendCapCents: parsedCap * 100 })
setSavedFlash(true)
// Save turns into "Saving…" in place; move focus onto it.
window.requestAnimationFrame(() => savedRef.current?.focus())
}
}}
>
<label htmlFor={capId} className="flex h-9 items-center text-xs font-medium">
{t('auto.components.billing.capLabel2', 'Monthly spend cap')}
</label>
<div className="space-y-1">
<div className="relative w-32">
<span
aria-hidden
className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm text-muted-foreground"
>
$
</span>
<Input
id={capId}
inputMode="numeric"
adornment="leading"
value={capDollars}
aria-invalid={!capValid || undefined}
aria-describedby={capValid ? undefined : capErrorId}
onChange={(event) => {
setCapDollars(event.target.value)
setSavedFlash(false)
}}
/>
</div>
{capValid ? null : (
<p id={capErrorId} className="text-xs text-destructive">
{capTooHigh && maxCapCents !== null
? capTooHighCopy(maxCapCents, locale, t)
: t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')}
</p>
)}
</div>
{savedFlash ? (
<span
ref={savedRef}
tabIndex={-1}
role="status"
className="flex h-9 items-center gap-1 text-xs text-muted-foreground outline-none"
>
<Check className="size-3.5" />
{busy || changed
? t('auto.components.billing.capSaving', 'Saving…')
: t('auto.components.billing.capSaved', 'Saved')}
</span>
) : changed ? (
<Button type="submit" variant="outline" aria-disabled={busy || undefined}>
{t('auto.components.billing.saveCap', 'Save')}
</Button>
) : null}
{capValid && entitlement.reason === 'overage_cap_reached' ? (
<p className="basis-full text-xs text-muted-foreground">
{t(
'auto.components.billing.capReachedHint2',
'Raise the cap to start sandboxes again. Your sandboxes are asleep, and your files are safe.'
)}
</p>
) : null}
</form>
}}
>
<label htmlFor={capId} className="flex h-9 items-center text-xs font-medium">
{t('auto.components.billing.capLabel2', 'Monthly spend cap')}
</label>
<div className="space-y-1">
<SettingsDisabledControlTooltip reason={blockedReason}>
<div className="relative w-32">
<span
aria-hidden
className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm text-muted-foreground"
>
$
</span>
<Input
id={capId}
inputMode="numeric"
adornment="leading"
value={capDollars}
readOnly={paymentFailed}
aria-disabled={paymentFailed || undefined}
aria-invalid={!capValid || undefined}
aria-describedby={capValid ? hintId : `${capErrorId} ${hintId}`}
onChange={(event) => {
setCapDollars(event.target.value)
setSavedFlash(false)
}}
/>
</div>
</SettingsDisabledControlTooltip>
{capValid ? null : (
<p id={capErrorId} className="text-xs text-destructive">
{capTooHigh && maxCapCents !== null
? capTooHighCopy(maxCapCents, locale, t)
: t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')}
</p>
)}
</div>
) : null}
{savedFlash ? (
<span
ref={savedRef}
tabIndex={-1}
role="status"
className="flex h-9 items-center gap-1 text-xs text-muted-foreground outline-none"
>
<Check className="size-3.5" />
{busy || changed
? t('auto.components.billing.capSaving', 'Saving…')
: t('auto.components.billing.capSaved', 'Saved')}
</span>
) : changed ? (
<Button type="submit" variant="outline" aria-disabled={busy || undefined}>
{t('auto.components.billing.saveCap', 'Save')}
</Button>
) : !overage.optedIn && !paymentFailed ? (
<Button
type="button"
variant="outline"
aria-disabled={busy || undefined}
onClick={() => {
if (busy) {
return
}
setCapDollars(String(Math.round(defaultCapCents / 100)))
save(true, defaultCapCents)
}}
>
{t('auto.components.billing.overage.turnOn', 'Turn on with a {{cap}} cap', {
cap: formatCents(defaultCapCents, locale)
})}
</Button>
) : null}
<p id={hintId} className="basis-full text-xs text-muted-foreground">
{hint}
</p>
{capValid && entitlement.reason === 'overage_cap_reached' ? (
<p className="basis-full text-xs text-muted-foreground">
{t(
'auto.components.billing.capReachedHint2',
'Raise the cap to start sandboxes again. Your sandboxes are asleep, and your files are safe.'
)}
</p>
) : null}
</form>
{overage.optedIn ? spent : null}
<p className="text-xs text-muted-foreground">
{t(
'auto.components.billing.usageAlertsNote',
'Owners and admins are alerted in Orca at 75%, 90% and 100% of your team’s sandbox hours.'
)}
</p>
</div>
)
}
@@ -0,0 +1,101 @@
import { defineFixture } from '../../component-fixtures/component-fixture'
import { PlanBillingView } from './PlanBillingSection'
import { sampleTeam, sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
// JA-18 states of Plan & billing's "Last 30 days" and spend cap (activeTeam lives with the page).
const HOUR = 3600
const handlers = {
loading: false,
busy: false,
notice: null,
onRefresh: () => {},
onPortal: () => {},
onSetOverage: () => {},
onSeePlans: () => {}
}
const usage = { status: 'ok', history: sampleUsageHistory, names: sampleUsageNames } as const
export const activeTeamOverageOn = defineFixture({
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={usage}
result={{
status: 'ok',
entitlement: {
...sampleTeam,
overage: { ...sampleTeam.overage, optedIn: true, active: true, spentCents: 320 }
}
}}
/>
)
})
// Members see the team's chart and their own hours, not who used what.
export const activeTeamMember = defineFixture({
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={{
...usage,
history: { ...sampleUsageHistory, members: null, sandboxes: null }
}}
result={{ status: 'ok', entitlement: { ...sampleTeam, canManageBilling: false } }}
/>
)
})
export const usageLoading = defineFixture({
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={{ status: 'loading' }}
result={{ status: 'ok', entitlement: sampleTeam }}
/>
)
})
export const usageEmpty = defineFixture({
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={{
...usage,
history: {
...sampleUsageHistory,
days: sampleUsageHistory.days.map((day) => ({ ...day, seconds: 0 })),
totalSeconds: 0,
yourSeconds: 0,
members: { top: [], otherCount: 0, otherSeconds: 0 },
sandboxes: { top: [], otherCount: 0, otherSeconds: 0 }
}
}}
result={{
status: 'ok',
entitlement: { ...sampleTeam, usedSeconds: 0, remainingIncludedSeconds: 120 * HOUR }
}}
/>
)
})
export const usageFailed = defineFixture({
width: 680,
render: () => (
<PlanBillingView
{...handlers}
teamName="Orca Staging Eval Team"
usage={{ status: 'failed' }}
result={{ status: 'ok', entitlement: sampleTeam }}
/>
)
})
@@ -0,0 +1,137 @@
import { InlineError } from '@/components/ui/inline-error'
import { Skeleton } from '@/components/ui/skeleton'
import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup'
import { useTranslate } from '@/i18n/use-translate'
import { formatHours } from './plan-billing-format'
import {
topMemberRows,
topWorkspaceRows,
usageWindowTotalLine,
yourUsageLine,
type UsageBreakdownRow
} from './plan-billing-usage-history'
import { UsageHistoryChart } from './UsageHistoryChart'
import type { PlanBillingUsageState } from './use-plan-billing-usage-history'
/** "Last 30 days": the team's daily hours; owners and admins also see the top workspaces and members. */
export function PlanBillingUsageHistory({
state,
onRetry
}: {
state: PlanBillingUsageState
onRetry: () => void
}): React.JSX.Element {
const t = useTranslate()
const title = t('auto.components.billing.usage.title', 'Last 30 days')
if (state.status === 'failed') {
return (
<section className="space-y-3">
<SettingsGroupHeader title={title} className="px-0" />
<InlineError
title={t('auto.components.billing.usage.loadFailed', 'Couldn’t load your usage history')}
retryLabel={t('auto.components.billing.plans.retry', 'Try again')}
onRetry={onRetry}
/>
</section>
)
}
if (state.status === 'loading') {
return (
<section
className="space-y-3"
role="status"
aria-busy
aria-label={t('auto.components.billing.usage.loading', 'Loading your usage history…')}
>
<SettingsGroupHeader title={title} className="px-0" />
<Skeleton shape="card" className="h-[136px] w-full" />
</section>
)
}
const { history, names } = state
const workspaces = topWorkspaceRows(history, names, t)
const members = topMemberRows(history, names, t)
const empty = history.totalSeconds <= 0
return (
<section className="space-y-3">
<SettingsGroupHeader
title={title}
className="px-0"
action={
empty ? null : (
<span className="text-xs text-muted-foreground tabular-nums">
{usageWindowTotalLine(history.totalSeconds, t)}
</span>
)
}
/>
{empty ? (
<p className="rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-muted-foreground">
{t(
'auto.components.billing.usage.empty',
'No sandbox hours yet. Usage shows here once your team runs cloud workspaces.'
)}
</p>
) : (
<>
<UsageHistoryChart days={history.days} />
{workspaces && members ? (
<div className="grid gap-x-6 gap-y-4 pt-1 sm:grid-cols-2">
<BreakdownList
title={t('auto.components.billing.usage.topWorkspaces', 'Top workspaces')}
rows={workspaces}
/>
<BreakdownList
title={t('auto.components.billing.usage.topMembers', 'Top members')}
rows={members}
/>
</div>
) : (
<p className="text-xs text-muted-foreground tabular-nums">
{yourUsageLine(history, t)}
</p>
)}
</>
)}
</section>
)
}
function BreakdownList({
title,
rows
}: {
title: string
rows: UsageBreakdownRow[]
}): React.JSX.Element {
const t = useTranslate()
return (
<div className="min-w-0 space-y-2">
<div className="flex items-baseline justify-between gap-3 text-xs">
<h4 className="font-medium">{title}</h4>
<span className="text-muted-foreground">
{t('auto.components.billing.usage.hoursColumn', 'Sandbox hours')}
</span>
</div>
<ul className="space-y-2">
{rows.map((row) => (
<li key={row.key} className="space-y-1">
<div className="flex items-baseline justify-between gap-3 text-xs">
<span className={row.other ? 'truncate text-muted-foreground' : 'truncate'}>
{row.label}
</span>
<span className="shrink-0 tabular-nums">{formatHours(row.seconds)}</span>
</div>
{/* Share of the team's hours: decoration; the number beside it carries the value. */}
<div aria-hidden className="h-1 w-full rounded-full bg-muted">
<div
className="h-full rounded-full bg-chart-3 dark:bg-chart-2"
style={{ width: `${Math.max(1, row.share)}%` }}
/>
</div>
</li>
))}
</ul>
</div>
)
}
@@ -0,0 +1,152 @@
import { useState } from 'react'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import type { OrcaBillingUsageHistory } from '../../../../shared/orca-billing'
import {
usageBarPercent,
usageChartMaxHours,
usageDayLabel,
usageDayLine
} from './plan-billing-usage-history'
const HEIGHT_PX = 112
/**
* Sandbox hours per day for the last 30 days: one series, so no legend (the heading names it).
* Hover or arrow keys show a day's hours; a visually hidden table carries every value.
*/
export function UsageHistoryChart({
days
}: {
days: OrcaBillingUsageHistory['days']
}): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const [active, setActive] = useState<number | null>(null)
const maxHours = usageChartMaxHours(days)
const ticks = [maxHours, maxHours / 2, 0]
const activeDay = active === null ? null : days[active]
const last = days.length - 1
const move = (event: React.KeyboardEvent<HTMLDivElement>): void => {
const from = active ?? last
const to =
event.key === 'ArrowLeft'
? Math.max(0, from - 1)
: event.key === 'ArrowRight'
? Math.min(last, from + 1)
: event.key === 'Home'
? 0
: event.key === 'End'
? last
: null
if (to !== null) {
event.preventDefault()
setActive(to)
}
}
return (
<div className="space-y-1.5">
<div className="flex gap-2">
{/* Y axis: hours, top / middle / zero. */}
<div
aria-hidden
className="relative w-6 shrink-0 text-right text-[10px] leading-none tabular-nums text-muted-foreground"
style={{ height: HEIGHT_PX }}
>
{ticks.map((tick) => (
<span
key={tick}
className="absolute right-0 -translate-y-1/2"
style={{ top: `${100 - (tick / maxHours) * 100}%` }}
>
{tick}
</span>
))}
</div>
<div
role="group"
tabIndex={0}
aria-label={t(
'auto.components.billing.usage.chartLabel',
'Sandbox hours per day, last 30 days. Use the arrow keys to read each day.'
)}
onKeyDown={move}
onFocus={() => setActive((current) => current ?? last)}
onBlur={() => setActive(null)}
onPointerLeave={() => setActive(null)}
className="relative min-w-0 flex-1 rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
style={{ height: HEIGHT_PX }}
>
{/* Hairline grid: top and middle; the baseline is drawn solid below. */}
{ticks.slice(0, 2).map((tick) => (
<div
key={tick}
aria-hidden
className="absolute inset-x-0 border-t border-border/60"
style={{ top: `${100 - (tick / maxHours) * 100}%` }}
/>
))}
<div aria-hidden className="absolute inset-x-0 bottom-0 border-t border-border" />
<div aria-hidden className="absolute inset-0 flex items-end gap-[2px]">
{days.map((day, index) => (
// The whole column is the hit target, not just the (often tiny) bar.
<div
key={day.start}
className="flex h-full min-w-0 flex-1 items-end justify-center"
onPointerEnter={() => setActive(index)}
>
<div
className={cn(
'w-full max-w-6 rounded-t-[4px]',
index === active ? 'bg-chart-4 dark:bg-chart-1' : 'bg-chart-3 dark:bg-chart-2'
)}
style={{
height: `${usageBarPercent(day.seconds, maxHours)}%`
}}
/>
</div>
))}
</div>
{activeDay && active !== null ? (
<div
aria-hidden
className="pointer-events-none absolute -top-1 z-10 -translate-y-full rounded-md border border-border bg-popover px-2 py-1 text-xs whitespace-nowrap text-popover-foreground shadow-sm"
style={
active > days.length / 2
? { right: `${((last - active) / days.length) * 100}%` }
: { left: `${(active / days.length) * 100}%` }
}
>
{usageDayLine(activeDay, locale, t)}
</div>
) : null}
</div>
</div>
<div
aria-hidden
className="flex justify-between pl-8 text-[10px] leading-none text-muted-foreground"
>
<span>{usageDayLabel(days[0]?.start ?? 0, locale)}</span>
<span>{t('auto.components.billing.usage.today', 'Today')}</span>
</div>
{/* Screen readers: the active day as it changes, and every day in a table. */}
<p role="status" className="sr-only">
{activeDay ? usageDayLine(activeDay, locale, t) : ''}
</p>
<table className="sr-only">
<caption>
{t('auto.components.billing.usage.tableCaption', 'Sandbox hours per day')}
</caption>
<tbody>
{days.map((day) => (
<tr key={day.start}>
<td>{usageDayLine(day, locale, t)}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
@@ -1,5 +1,10 @@
// Shared sample entitlements for billing tests and component fixtures.
import type { OrcaBillingEntitlement, OrcaBillingOffers } from '../../../../shared/orca-billing'
import type {
OrcaBillingEntitlement,
OrcaBillingOffers,
OrcaBillingUsageHistory
} from '../../../../shared/orca-billing'
import type { UsageNames } from './plan-billing-usage-history'
import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire'
const HOUR = 3600
@@ -88,3 +93,56 @@ export const sampleTrialUsedUp: OrcaBillingEntitlement = {
canStartSandbox: false,
reason: 'trial_used_up'
}
const DAY_MS = 24 * 3600 * 1000
// Hours per day, oldest first: quiet weekends, a busy release week and today in progress.
const DAILY_HOURS = [
0.5, 1.2, 0, 0, 2.4, 3.1, 1.8, 2.2, 0.9, 0, 0, 1.4, 2.8, 4.6, 5.2, 3.9, 0.3, 0, 1.1, 2, 1.7, 2.6,
0.8, 0, 0, 1.9, 3.4, 2.1, 1.5, 0.6
]
const HISTORY_START = Date.UTC(2026, 9, 12, 7)
export const sampleUsageHistory: OrcaBillingUsageHistory = {
days: DAILY_HOURS.map((hours, index) => ({
start: HISTORY_START + index * DAY_MS,
seconds: Math.round(hours * HOUR)
})),
totalSeconds: Math.round(DAILY_HOURS.reduce((sum, hours) => sum + hours, 0) * HOUR),
yourSeconds: 18.4 * HOUR,
members: {
top: [
{ id: 'u-neil', seconds: 18.4 * HOUR },
{ id: 'u-grace', seconds: 15.1 * HOUR },
{ id: 'u-linus', seconds: 8.6 * HOUR },
{ id: 'u-gone', seconds: 4.2 * HOUR }
],
otherCount: 0,
otherSeconds: 1.7 * HOUR
},
sandboxes: {
top: [
{ id: 'sbx_checkout', seconds: 14.2 * HOUR },
{ id: 'sbx_ledger', seconds: 11 * HOUR },
{ id: 'sbx_docs', seconds: 7.3 * HOUR },
{ id: 'sbx_gone', seconds: 5.9 * HOUR },
{ id: 'sbx_deleted', seconds: 3.1 * HOUR }
],
otherCount: 4,
otherSeconds: 6.5 * HOUR
}
}
export const sampleUsageNames: UsageNames = {
selfId: 'u-neil',
members: new Map([
['u-neil', 'Neil Parker'],
['u-grace', 'Grace Hopper'],
['u-linus', 'Linus Torvalds']
]),
workspaces: new Map([
['sbx_checkout', 'Checkout retries'],
['sbx_ledger', 'Ledger migration'],
['sbx_docs', 'Docs search'],
['sbx_flaky', 'Flaky e2e repro']
])
}
@@ -0,0 +1,99 @@
import { describe, expect, it } from 'vitest'
import { translate } from '@/i18n/i18n'
import {
topMemberRows,
topWorkspaceRows,
usageBarPercent,
usageChartMaxHours,
usageTotalLine,
usageWindowTotalLine,
yourUsageLine
} from './plan-billing-usage-history'
import { sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
const HOUR = 3600
const day = (hours: number) => ({ start: 0, seconds: hours * HOUR })
describe('usage chart scale', () => {
it('tops the axis at the nearest clean value just above the busiest day', () => {
expect(usageChartMaxHours([day(0)])).toBe(1)
expect(usageChartMaxHours([day(0.4)])).toBe(1)
expect(usageChartMaxHours([day(1.5), day(0.2)])).toBe(2)
expect(usageChartMaxHours([day(5.2)])).toBe(6)
expect(usageChartMaxHours([day(3)])).toBe(3)
expect(usageChartMaxHours([day(7)])).toBe(8)
expect(usageChartMaxHours([day(48)])).toBe(50)
expect(usageChartMaxHours([day(120)])).toBe(200)
})
it('keeps any used day visible and an idle day empty', () => {
expect(usageBarPercent(0, 10)).toBe(0)
expect(usageBarPercent(36, 10)).toBe(2)
expect(usageBarPercent(5 * HOUR, 10)).toBe(50)
expect(usageBarPercent(20 * HOUR, 10)).toBe(100)
})
})
describe('top workspaces and members', () => {
it('names members, calls the viewer "You", and keeps unknown ids readable', () => {
const rows = topMemberRows(sampleUsageHistory, sampleUsageNames, translate)!
expect(rows.map((row) => row.label)).toEqual([
'You',
'Grace Hopper',
'Linus Torvalds',
'Former member',
'Not attributed to a member'
])
expect(rows[0]!.share).toBeCloseTo((18.4 / 48) * 100)
expect(rows.at(-1)!.other).toBe(true)
})
it('merges unknown ids into one row after the named ones, and folds 0-hour rows into the others line', () => {
const history = {
...sampleUsageHistory,
sandboxes: {
top: [
{ id: 'sbx_gone1', seconds: 0.6 * HOUR },
{ id: 'sbx_docs', seconds: 0.5 * HOUR },
{ id: 'sbx_gone2', seconds: 0.5 * HOUR },
{ id: 'sbx_tiny', seconds: 20 }
],
otherCount: 2,
otherSeconds: 0.4 * HOUR
}
}
const rows = topWorkspaceRows(history, sampleUsageNames, translate)!
expect(rows.map((row) => [row.label, row.seconds])).toEqual([
['Docs search', 0.5 * HOUR],
['2 deleted workspaces', 3960],
['3 other workspaces', 0.4 * HOUR + 20]
])
})
it('titles workspaces and folds the rest into one line', () => {
const rows = topWorkspaceRows(sampleUsageHistory, sampleUsageNames, translate)!
expect(rows.map((row) => row.label)).toEqual([
'Checkout retries',
'Ledger migration',
'Docs search',
'2 deleted workspaces',
'4 other workspaces'
])
})
it('has no breakdown for members', () => {
const memberView = { ...sampleUsageHistory, members: null, sandboxes: null }
expect(topMemberRows(memberView, sampleUsageNames, translate)).toBeNull()
expect(topWorkspaceRows(memberView, sampleUsageNames, translate)).toBeNull()
expect(yourUsageLine(memberView, translate)).toBe(
'You used 18.4 of your team’s 48 sandbox hours.'
)
})
it('formats totals with the meter’s hours (one decimal, whole numbers bare)', () => {
expect(usageTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours')
expect(usageTotalLine(HOUR, translate)).toBe('1 sandbox hour')
expect(usageTotalLine(0.26 * HOUR, translate)).toBe('0.3 sandbox hours')
expect(usageWindowTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours in 30 days')
})
})
@@ -0,0 +1,209 @@
// Pure helpers for Plan & billing's "Last 30 days": the chart's scale and labels, and the top
// workspaces and members with their names resolved. Hours use formatHours, like the meter above.
import type { Translate } from '@/i18n/use-translate'
import type { OrcaBillingUsageHistory, OrcaBillingUsageTop } from '../../../../shared/orca-billing'
import { formatHours } from './plan-billing-format'
const HOUR = 3600
// Axis tops whose half is also a clean tick (0 / mid / max), × a power of ten.
const NICE_TOPS = [1, 2, 3, 4, 5, 6, 8, 10]
/** The y-axis top in hours: the nearest clean value at or above the busiest day (min 1). */
export function usageChartMaxHours(days: OrcaBillingUsageHistory['days']): number {
const busiest = Math.max(0, ...days.map((day) => day.seconds)) / HOUR
if (busiest <= 1) {
return 1
}
const power = 10 ** Math.floor(Math.log10(busiest))
const top = NICE_TOPS.find((step) => busiest <= step * power) ?? 10
return top * power
}
/** A bar's height as a share of the axis (0..100); a day with any usage stays visible (2%). */
export function usageBarPercent(seconds: number, maxHours: number): number {
if (seconds <= 0) {
return 0
}
return Math.min(100, Math.max(2, (seconds / HOUR / maxHours) * 100))
}
export type UsageBreakdownRow = {
key: string
label: string
seconds: number
/** Share of the team's 30-day hours, 0..100, for the row's thin bar. */
share: number
/** True for the "N others" line. */
other?: boolean
}
export type UsageNames = {
/** Display names by member id (the team roster). */
members: ReadonlyMap<string, string>
/** Workspace titles by sandbox id (the team's cloud workspace list). */
workspaces: ReadonlyMap<string, string>
/** The viewer's member id: their row reads "You". */
selfId: string | null
}
function share(seconds: number, total: number): number {
return total > 0 ? Math.min(100, (seconds / total) * 100) : 0
}
function rows(
top: OrcaBillingUsageTop,
total: number,
/** The row's name, or null for an id that's no longer known (one merged row for all of them). */
label: (id: string) => string | null,
unknownLabel: (count: number) => string,
othersLabel: (count: number) => string
): UsageBreakdownRow[] {
const list: UsageBreakdownRow[] = []
let unknown = { count: 0, seconds: 0 }
let others = { count: top.otherCount, seconds: top.otherSeconds }
for (const row of top.top) {
// A row that shows as 0 hours says nothing on its own: it joins the others line.
if (formatHours(row.seconds) === '0') {
others = { count: others.count + 1, seconds: others.seconds + row.seconds }
continue
}
const name = label(row.id)
if (name === null) {
unknown = { count: unknown.count + 1, seconds: unknown.seconds + row.seconds }
} else {
list.push({
key: row.id,
label: name,
seconds: row.seconds,
share: share(row.seconds, total)
})
}
}
// Named rows lead (they're what someone acts on); the merged unknowns always come after them.
list.sort((a, b) => b.seconds - a.seconds)
if (unknown.count > 0) {
list.push({
key: 'unknown',
label: unknownLabel(unknown.count),
seconds: unknown.seconds,
share: share(unknown.seconds, total)
})
}
if (others.seconds > 0) {
list.push({
key: 'other',
label: othersLabel(others.count),
seconds: others.seconds,
share: share(others.seconds, total),
other: true
})
}
return list
}
export function topMemberRows(
history: OrcaBillingUsageHistory,
names: UsageNames,
t: Translate
): UsageBreakdownRow[] | null {
if (!history.members) {
return null
}
return rows(
history.members,
history.totalSeconds,
(id) =>
id === names.selfId
? t('auto.components.billing.usage.you', 'You')
: (names.members.get(id) ?? null),
(count) =>
t('auto.components.billing.usage.formerMembers', '{{count}} former members', {
count,
defaultValue_one: 'Former member'
}),
(count) =>
count > 0
? t('auto.components.billing.usage.otherMembers', '{{count}} others', {
count,
defaultValue_one: '{{count}} other'
})
: t('auto.components.billing.usage.unattributed', 'Not attributed to a member')
)
}
export function topWorkspaceRows(
history: OrcaBillingUsageHistory,
names: UsageNames,
t: Translate
): UsageBreakdownRow[] | null {
if (!history.sandboxes) {
return null
}
return rows(
history.sandboxes,
history.totalSeconds,
(id) => names.workspaces.get(id) ?? null,
(count) =>
t('auto.components.billing.usage.deletedWorkspaces', '{{count}} deleted workspaces', {
count,
defaultValue_one: 'Deleted workspace'
}),
(count) =>
t('auto.components.billing.usage.otherWorkspaces', '{{count}} other workspaces', {
count,
defaultValue_one: '{{count}} other workspace'
})
)
}
/** "48 sandbox hours in 30 days": the chart's total, distinct from the month's meter above. */
export function usageWindowTotalLine(seconds: number, t: Translate): string {
return t('auto.components.billing.usage.windowTotal', '{{value}} sandbox hours in 30 days', {
value: formatHours(seconds),
count: Number(formatHours(seconds)),
defaultValue_one: '{{value}} sandbox hour in 30 days'
})
}
/** "41.5 sandbox hours" (a day's readout). */
export function usageTotalLine(seconds: number, t: Translate): string {
return t('auto.components.billing.usage.total', '{{value}} sandbox hours', {
value: formatHours(seconds),
count: Number(formatHours(seconds)),
defaultValue_one: '{{value}} sandbox hour'
})
}
/** A member's line: "You used 5 of your team's 41.5 sandbox hours." */
export function yourUsageLine(history: OrcaBillingUsageHistory, t: Translate): string {
return t(
'auto.components.billing.usage.yours',
'You used {{yours}} of your team’s {{total}} sandbox hours.',
{
yours: formatHours(history.yourSeconds),
total: formatHours(history.totalSeconds)
}
)
}
/** The bar's readout (tooltip, live region and table): "Nov 3 · 2.5 sandbox hours". */
export function usageDayLine(
day: OrcaBillingUsageHistory['days'][number],
locale: string,
t: Translate
): string {
return t('auto.components.billing.usage.dayLine', '{{date}} · {{hours}}', {
date: usageDayLabel(day.start, locale),
hours: usageTotalLine(day.seconds, t)
})
}
const DAY_FORMAT: Intl.DateTimeFormatOptions = {
month: 'short',
day: 'numeric'
}
export function usageDayLabel(start: number, locale: string): string {
return new Intl.DateTimeFormat(locale, DAY_FORMAT).format(start)
}
@@ -1,5 +1,33 @@
import { useState } from 'react'
import { cn } from '@/lib/utils'
/**
* A teammate's provider profile picture filling its avatar circle, or null when there is none or it
* failed to load (the caller's initials show instead). No referrer goes to the image host.
*/
export function ProfilePicture({
url,
className
}: {
url: string | undefined
className?: string
}): React.JSX.Element | null {
const [failed, setFailed] = useState<string | null>(null)
if (!url || failed === url) {
return null
}
return (
<img
src={url}
alt=""
referrerPolicy="no-referrer"
draggable={false}
onError={() => setFailed(url)}
className={cn('absolute inset-0 size-full rounded-full object-cover', className)}
/>
)
}
/** "Ada Lovelace" → "AL", "ada@x.io" → "A", "Acme Dev" → "AD". */
export function initialsFor(nameOrEmail: string): string {
const base = nameOrEmail.includes('@') ? (nameOrEmail.split('@')[0] ?? '') : nameOrEmail
@@ -15,21 +43,23 @@ export function initialsFor(nameOrEmail: string): string {
return (first + second).toUpperCase()
}
/** Round person avatar (initials). Pending people get a dashed, hollow look. */
/** Round person avatar (picture, else initials). Pending people get a dashed, hollow look. */
export function PersonAvatar({
name,
pending = false,
pictureUrl,
className
}: {
name: string
pending?: boolean
pictureUrl?: string
className?: string
}): React.JSX.Element {
return (
<span
aria-hidden
className={cn(
'flex size-6 shrink-0 items-center justify-center rounded-full text-[10px] font-medium select-none',
'relative flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full text-[10px] font-medium select-none',
pending
? 'border border-dashed border-muted-foreground/50 text-muted-foreground'
: 'border border-border bg-secondary text-secondary-foreground',
@@ -37,6 +67,7 @@ export function PersonAvatar({
)}
>
{initialsFor(name)}
{pending ? null : <ProfilePicture url={pictureUrl} />}
</span>
)
}
@@ -259,7 +259,11 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
className="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"
>
<div className="flex items-center gap-3">
<PersonAvatar name={name} pending={row.status !== 'active'} />
<PersonAvatar
name={name}
pending={row.status !== 'active'}
pictureUrl={row.kind === 'member' ? row.member.pictureUrl : undefined}
/>
<div className="min-w-0 flex-1">
<p className="flex min-w-0 items-center gap-2 text-sm font-medium">
{profileUserId && props.onOpenProfile ? (
@@ -6,6 +6,10 @@ import { sampleTeam } from '../plan-billing-fixtures'
import { TeamDialogContent } from './TeamDialogHost'
import { TeamPageView, type TeamPageViewProps } from './TeamPageView'
// Fixtures render offline: a self-contained stand-in for a provider profile picture.
const ADA_PICTURE =
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='%23f6c38f'/><stop offset='1' stop-color='%23c0713d'/></linearGradient></defs><rect width='64' height='64' fill='url(%23g)'/><circle cx='32' cy='26' r='12' fill='%23fff3e6'/><rect x='14' y='42' width='36' height='22' rx='11' fill='%23fff3e6'/></svg>"
const NOW = Date.UTC(2026, 10, 18, 15)
const DAY = 86_400_000
const width = 1100
@@ -15,7 +19,13 @@ const roster: OrcaOrgMembersRoster = {
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-ada',
email: 'ada@acme.dev',
displayName: 'Ada Lovelace',
role: 'admin',
pictureUrl: ADA_PICTURE
},
{ userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' },
{ userId: null, email: 'linus@acme.dev', role: 'member' }
],
@@ -0,0 +1,114 @@
import { useCallback, useEffect, useState } from 'react'
import type { OrcaBillingUsageHistory } from '../../../../shared/orca-billing'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { useTranslate } from '@/i18n/use-translate'
import { cloudWorkspaceTitle } from '../cloud-workspaces/open-cloud-workspace'
import { useOrgRoster } from './team/use-org-roster'
import type { UsageNames } from './plan-billing-usage-history'
export type PlanBillingUsageState =
| { status: 'loading' }
| { status: 'ok'; history: OrcaBillingUsageHistory; names: UsageNames }
| { status: 'failed' }
/** Minutes east of UTC, so the chart's days are the viewer's local days. */
function utcOffsetMinutes(): number {
return -new Date().getTimezoneOffset()
}
/**
* Reads the 30-day history whenever `readKey` changes (the account, or a new billing read: the
* status re-reads on window focus, so there's no refresh button). A re-read keeps the last answer
* on screen until the new one lands. Owners and admins also get member and workspace names.
*/
export function usePlanBillingUsageHistory(
readKey: string | null,
orgId: string | null,
selfId: string | null,
canSeeBreakdown: boolean
): { state: PlanBillingUsageState; retry: () => void } {
const t = useTranslate()
const [attempt, setAttempt] = useState(0)
const [read, setRead] = useState<
{ key: string; history: OrcaBillingUsageHistory } | { key: string; failed: true } | null
>(null)
const [workspaces, setWorkspaces] = useState<CloudWorkspace[] | null>(null)
const roster = useOrgRoster(canSeeBreakdown ? orgId : null)
useEffect(() => {
if (!readKey) {
return
}
let disposed = false
void window.api.orcaProfiles
.billingUsageHistory({ utcOffsetMinutes: utcOffsetMinutes() })
.catch(() => ({ status: 'failed' as const }))
.then((result) => {
if (disposed) {
return
}
if (result.status === 'ok') {
setRead({ key: readKey, history: result.history })
} else {
// A failed re-read keeps the chart that's already showing for this account.
setRead((previous) =>
previous &&
'history' in previous &&
previous.key.split('|')[0] === readKey.split('|')[0]
? previous
: { key: readKey, failed: true }
)
}
})
return () => {
disposed = true
}
}, [readKey, attempt])
useEffect(() => {
if (!canSeeBreakdown || !orgId) {
return
}
let disposed = false
void (window.api.cloudWorkspaces?.list({ scope: 'all', archived: 'include' }) ?? null)
?.then((result) => {
if (!disposed && result.ok) {
setWorkspaces(result.value)
}
})
.catch(() => {})
return () => {
disposed = true
}
}, [canSeeBreakdown, orgId])
const retry = useCallback(() => setAttempt((count) => count + 1), [])
const sameAccount =
read !== null && readKey !== null && read.key.split('|')[0] === readKey.split('|')[0]
if (!read || !sameAccount) {
return { state: { status: 'loading' }, retry }
}
if (!('history' in read)) {
return { state: { status: 'failed' }, retry }
}
const members = new Map<string, string>()
if (roster.result?.status === 'ok') {
for (const member of roster.result.roster.members) {
if (member.userId) {
members.set(member.userId, member.displayName ?? member.email)
}
}
}
const titles = new Map<string, string>()
for (const workspace of workspaces ?? []) {
titles.set(workspace.id, cloudWorkspaceTitle(workspace, t))
}
return {
state: {
status: 'ok',
history: read.history,
names: { members, workspaces: titles, selfId }
},
retry
}
}
@@ -0,0 +1,180 @@
// One group on Home: Pinned, a section, or "No section". Named sections collapse; every group's
// rows reorder by dragging (or Move up / Move down in the row menu), and the order syncs to your
// other devices through your prefs.
import React, { useState } from 'react'
import { ChevronRight, MoreHorizontal, Pin } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import type { CloudWorkspaceGroup } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
type Group = CloudWorkspaceGroup<CloudWorkspace>
export type GroupDrag = {
/** The row being dragged and the group it came from (rows only drop within their own group). */
dragging: { id: string; group: string } | null
start: (id: string, group: string) => void
drop: (overId: string, group: string) => void
end: () => void
}
/** Drag props for one row's <li>; inert while reduced to a single row. */
export function rowDragProps(
drag: GroupDrag,
group: Group,
id: string
): React.LiHTMLAttributes<HTMLLIElement> & { 'data-drop-target'?: string } {
if (group.rows.length < 2) {
return {}
}
return {
draggable: true,
onDragStart: (event) => {
event.dataTransfer.effectAllowed = 'move'
// Some platforms need data set for the drag to start at all.
event.dataTransfer.setData('text/plain', id)
drag.start(id, group.key)
},
onDragOver: (event) => {
if (drag.dragging?.group === group.key) {
event.preventDefault()
event.dataTransfer.dropEffect = 'move'
}
},
onDrop: (event) => {
if (drag.dragging?.group === group.key) {
event.preventDefault()
drag.drop(id, group.key)
}
},
onDragEnd: () => drag.end()
}
}
export function CloudWorkspaceGroupView({
group,
index,
showHeading,
canMoveUp,
canMoveDown,
onToggleCollapsed,
onMoveSection,
children
}: {
group: Group
index: number
showHeading: boolean
canMoveUp: boolean
canMoveDown: boolean
onToggleCollapsed: (collapsed: boolean) => void
onMoveSection: (delta: number) => void
children: React.ReactNode
}): React.JSX.Element {
const t = useTranslate()
const [menuOpen, setMenuOpen] = useState(false)
// Section names are free text (spaces), so the id uses the position instead.
const headingId = `cloud-workspaces-section-${index}`
const listId = `cloud-workspaces-section-list-${index}`
const label =
group.kind === 'pinned'
? t('auto.components.cloudWorkspaces.pinned', 'Pinned')
: (group.section ?? t('auto.components.cloudWorkspaces.otherWorkspaces', 'Other workspaces'))
const count = (
<>
{/* The bare number is visual; screen readers get the counted phrase. */}
<span aria-hidden className="ml-1.5 tabular-nums text-muted-foreground">
{group.rows.length}
</span>{' '}
<span className="sr-only">
{t('auto.components.cloudWorkspaces.sectionCount', '{{count}} workspaces', {
count: group.rows.length,
defaultValue_one: '{{count}} workspace'
})}
</span>
</>
)
const collapsible = group.kind === 'section'
return (
<div className="py-0.5" data-cloud-workspace-group={group.key}>
{showHeading && (
<div className="group/heading flex items-center gap-1 pr-2">
<h3 id={headingId} className="min-w-0 flex-1 text-2xs font-medium text-muted-foreground">
{collapsible ? (
<button
type="button"
aria-expanded={!group.collapsed}
aria-controls={listId}
onClick={() => onToggleCollapsed(!group.collapsed)}
className="flex w-full items-center gap-1 rounded-md px-3 py-2 text-left outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-focus-ring"
>
<ChevronRight
aria-hidden
className={cn(
'-ml-1 size-3 shrink-0 motion-safe:transition-transform',
!group.collapsed && 'rotate-90'
)}
/>
<span className="truncate">{label}</span>
{count}
</button>
) : (
<span className="flex items-center gap-1 px-3 py-2">
{group.kind === 'pinned' && <Pin aria-hidden className="-ml-0.5 size-3 shrink-0" />}
<span className="truncate">{label}</span>
{count}
</span>
)}
</h3>
{collapsible && (canMoveUp || canMoveDown) && (
<span
className={cn(
'opacity-0 group-focus-within/heading:opacity-100 group-hover/heading:opacity-100',
menuOpen && 'opacity-100'
)}
>
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
<Button
size="icon-xs"
variant="ghost"
aria-label={t(
'auto.components.cloudWorkspaces.sectionActions',
'Actions for section {{name}}',
{ name: label }
)}
>
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem disabled={!canMoveUp} onSelect={() => onMoveSection(-1)}>
{t('auto.components.cloudWorkspaces.moveSectionUp', 'Move section up')}
</DropdownMenuItem>
<DropdownMenuItem disabled={!canMoveDown} onSelect={() => onMoveSection(1)}>
{t('auto.components.cloudWorkspaces.moveSectionDown', 'Move section down')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</span>
)}
</div>
)}
{!group.collapsed && (
<ul
id={listId}
role="list"
aria-labelledby={showHeading ? headingId : 'cloud-workspaces-heading'}
>
{children}
</ul>
)}
</div>
)
}
@@ -0,0 +1,76 @@
// W-123 in the top bar when the workspace in front is a cloud workspace; click copies its link
// (the same as ⌘⌥⇧L) and confirms in place. Renders nothing for local workspaces or before the
// number is known.
import React, { useEffect, useState } from 'react'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { formatOptionalPrimaryShortcutLabel } from '@/hooks/useShortcutLabel'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/store'
import { formatWorkspaceNumber } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { sandboxIdForWorktree, useCloudWorkspaceIdentities } from './cloud-workspace-identity'
import { copyCloudWorkspaceLink } from './open-cloud-workspace'
const COPIED_MS = 1_500
export function CloudWorkspaceNumberChip({
worktreeId
}: {
worktreeId: string
}): React.JSX.Element | null {
const t = useTranslate()
const hostId = useAppStore((s) => s.activeWorkspaceExecutionHostId)
const keybindings = useAppStore((s) => s.keybindings)
const identities = useCloudWorkspaceIdentities()
const [copied, setCopied] = useState(false)
useEffect(() => {
if (!copied) {
return
}
const timer = setTimeout(() => setCopied(false), COPIED_MS)
return () => clearTimeout(timer)
}, [copied])
const sandboxId = sandboxIdForWorktree({ id: worktreeId, hostId }, identities)
const number = sandboxId ? (identities.bySandbox.get(sandboxId)?.number ?? null) : null
if (!sandboxId || !number) {
return null
}
const label = formatWorkspaceNumber(number)
const shortcut = formatOptionalPrimaryShortcutLabel('cloudWorkspace.copyLink', keybindings)
const copiedLabel = t('auto.components.cloudWorkspaces.linkCopiedShort', 'Link copied')
return (
<>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => {
// The workspace only: a teammate opening it shouldn't land on your terminal or chat.
void copyCloudWorkspaceLink(sandboxId, null, { quiet: true }).then(
(ok) => ok && setCopied(true)
)
}}
aria-label={t('auto.components.cloudWorkspaces.copyLinkTo', 'Copy link to {{number}}', {
number: label
})}
className={cn(
'mr-2 flex h-6 items-center rounded-md px-1.5 font-mono text-2xs tabular-nums text-muted-foreground outline-none [-webkit-app-region:no-drag] hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-focus-ring',
copied && 'font-sans text-foreground'
)}
>
{copied ? copiedLabel : label}
</button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
{t('auto.components.cloudWorkspaces.copyLinkTo', 'Copy link to {{number}}', {
number: label
})}
{shortcut ? <span className="ml-1.5 text-muted-foreground">{shortcut}</span> : null}
</TooltipContent>
</Tooltip>
<span aria-live="polite" className="sr-only">
{copied ? copiedLabel : ''}
</span>
</>
)
}
@@ -1,5 +1,5 @@
import React, { useEffect, useId, useRef, useState } from 'react'
import { CalendarClock, GitBranch, Loader2, Lock } from 'lucide-react'
import { GitBranch, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { type Translate, useIntlLocale, useTranslate } from '@/i18n/use-translate'
@@ -11,7 +11,12 @@ import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-w
import { CloudStateDot } from '../orca-cloud/CloudStateDot'
import type { CloudDotState } from '@/lib/orca-cloud/orca-cloud-workspace-state'
import { MemberAvatar, PresenceStack } from './CloudMemberAvatars'
import { CloudWorkspaceRowMenu, isReadableAsleep, type RowActions } from './CloudWorkspaceRowMenu'
import {
CloudWorkspaceRowMenu,
isReadableAsleep,
type RowActions,
type RowArrangement
} from './CloudWorkspaceRowMenu'
import {
formatSandboxHours,
formatRelative,
@@ -23,6 +28,7 @@ import {
type MemberDirectory
} from './cloud-workspace-format'
import { cloudWorkspaceTitle } from './open-cloud-workspace'
import { CloudWorkspaceRowBadges } from './CloudWorkspaceRowBadges'
/** The shared Orca Cloud dot vocabulary (shape and tone), same as the sidebar and panel. */
export function dotState(w: CloudWorkspace): CloudDotState {
@@ -81,7 +87,10 @@ export function CloudWorkspaceRow({
opening,
highlighted,
now,
actions
actions,
arrangement,
dragProps,
dragging = false
}: {
workspace: CloudWorkspace
directory: MemberDirectory
@@ -93,6 +102,11 @@ export function CloudWorkspaceRow({
highlighted: boolean
now: number
actions: RowActions
/** Pinned state and whether Move up / Move down apply (synced prefs). */
arrangement?: RowArrangement
/** Drag-to-reorder within its group (from CloudWorkspaceGroup's rowDragProps). */
dragProps?: React.LiHTMLAttributes<HTMLLIElement>
dragging?: boolean
}): React.JSX.Element {
const t = useTranslate()
const intlLocale = useIntlLocale()
@@ -155,6 +169,7 @@ export function CloudWorkspaceRow({
<li
ref={rowRef}
data-cloud-workspace-row=""
{...dragProps}
onKeyDown={(event) => {
// Menu items render in a portal but still bubble through React; only this row's own DOM counts.
if (!(event.target instanceof Node) || !event.currentTarget.contains(event.target)) {
@@ -174,7 +189,8 @@ export function CloudWorkspaceRow({
}}
className={cn(
'group relative isolate flex items-center gap-3 rounded-lg pr-2 transition-colors hover:bg-accent',
menuOpen && 'bg-accent'
menuOpen && 'bg-accent',
dragging && 'opacity-50'
)}
>
{/* Opened from a link: an accent tint that fades out (instantly under reduced motion). */}
@@ -230,48 +246,12 @@ export function CloudWorkspaceRow({
>
{title}
</span>
{w.visibility === 'private' && (
<Tooltip>
<TooltipTrigger asChild>
<Lock
role="img"
className="size-3 shrink-0 text-muted-foreground"
aria-label={t('auto.components.cloudWorkspaces.private', 'Private')}
/>
</TooltipTrigger>
<TooltipContent side="top">
{w.ownerUserId === selfId
? t(
'auto.components.cloudWorkspaces.privateTooltipYou',
'Private — only you can see it'
)
: t(
'auto.components.cloudWorkspaces.privateTooltip',
'Private — only {{name}} can open it',
{
name: ownerName
}
)}
</TooltipContent>
</Tooltip>
)}
{w.fromRoutine === true && (
<Tooltip>
<TooltipTrigger asChild>
<CalendarClock
role="img"
className="size-3 shrink-0 text-muted-foreground"
aria-label={t('auto.components.cloudWorkspaces.routineRun', 'Routine run')}
/>
</TooltipTrigger>
<TooltipContent side="top">
{t(
'auto.components.cloudWorkspaces.routineRunTooltip',
"Started by a routine. It's deleted when the run ends."
)}
</TooltipContent>
</Tooltip>
)}
<CloudWorkspaceRowBadges
workspace={w}
selfId={selfId}
ownerName={ownerName}
revealNumber={revealOpen}
/>
</span>
<span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
<MemberAvatar userId={w.ownerUserId} directory={directory} selfId={selfId} size="sm" />
@@ -395,6 +375,7 @@ export function CloudWorkspaceRow({
open={menuOpen}
onOpenChange={setMenuOpen}
actions={actions}
arrangement={arrangement}
/>
<span id={descriptionId} className="sr-only">
{description}
@@ -0,0 +1,83 @@
// The small marks after a cloud workspace's title on Home: private, started by a routine, and its
// W-number (shown on hover or focus; its space is held so nothing shifts).
import React from 'react'
import { CalendarClock, Lock } from 'lucide-react'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import {
formatWorkspaceNumber,
type CloudWorkspace
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
export function CloudWorkspaceRowBadges({
workspace: w,
selfId,
ownerName,
revealNumber
}: {
workspace: CloudWorkspace
selfId: string | null
ownerName: string
revealNumber: boolean
}): React.JSX.Element {
const t = useTranslate()
const revealOpen = revealNumber
return (
<>
{w.visibility === 'private' && (
<Tooltip>
<TooltipTrigger asChild>
<Lock
role="img"
className="size-3 shrink-0 text-muted-foreground"
aria-label={t('auto.components.cloudWorkspaces.private', 'Private')}
/>
</TooltipTrigger>
<TooltipContent side="top">
{w.ownerUserId === selfId
? t(
'auto.components.cloudWorkspaces.privateTooltipYou',
'Private — only you can see it'
)
: t(
'auto.components.cloudWorkspaces.privateTooltip',
'Private — only {{name}} can open it',
{
name: ownerName
}
)}
</TooltipContent>
</Tooltip>
)}
{w.fromRoutine === true && (
<Tooltip>
<TooltipTrigger asChild>
<CalendarClock
role="img"
className="size-3 shrink-0 text-muted-foreground"
aria-label={t('auto.components.cloudWorkspaces.routineRun', 'Routine run')}
/>
</TooltipTrigger>
<TooltipContent side="top">
{t(
'auto.components.cloudWorkspaces.routineRunTooltip',
"Started by a routine. It's deleted when the run ends."
)}
</TooltipContent>
</Tooltip>
)}
{/* Its W-number shows on hover or focus only; the space is held so nothing shifts. */}
{w.number ? (
<span
className={cn(
'shrink-0 font-mono text-2xs tabular-nums text-muted-foreground opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 motion-safe:transition-opacity',
revealOpen && 'opacity-100'
)}
>
{formatWorkspaceNumber(w.number)}
</span>
) : null}
</>
)
}
@@ -4,6 +4,8 @@ import {
ArchiveRestore,
Moon,
Trash2,
ArrowDown,
ArrowUp,
ArrowUpRight,
BookOpen,
FolderInput,
@@ -11,6 +13,8 @@ import {
Link2,
Lock,
MoreHorizontal,
Pin,
PinOff,
Play,
UserRoundCog,
Users
@@ -59,8 +63,14 @@ export type RowActions = {
sleep: (w: CloudWorkspace) => void
/** Delete the sandbox and its disk, after a confirmation. */
remove: (w: CloudWorkspace) => void
/** Pin to the top of Home, synced to your other devices (your own pins, not the team's). */
setPinned?: (w: CloudWorkspace, pinned: boolean) => void
/** Move one place up (-1) or down (1) within its group, synced like pins. */
move?: (w: CloudWorkspace, delta: number) => void
}
export type RowArrangement = { pinned: boolean; canMoveUp: boolean; canMoveDown: boolean }
/** Placeholder replaced by the inline section editor in CloudWorkspacesHome. */
export const NEW_SECTION = '\u0000new-section'
// Radio value for "no section"; section names are user text, so a control character cannot clash.
@@ -88,7 +98,8 @@ export function CloudWorkspaceRowMenu({
selfId,
open,
onOpenChange,
actions
actions,
arrangement
}: {
workspace: CloudWorkspace
title: string
@@ -101,6 +112,7 @@ export function CloudWorkspaceRowMenu({
open: boolean
onOpenChange: (open: boolean) => void
actions: RowActions
arrangement?: RowArrangement
}): React.JSX.Element {
const t = useTranslate()
const keybindings = useAppStore((state) => state.keybindings)
@@ -160,6 +172,32 @@ export function CloudWorkspaceRowMenu({
<DropdownMenuShortcut>↵</DropdownMenuShortcut>
</DropdownMenuItem>
)}
{arrangement && actions.setPinned && w.archivedAt === null && (
<DropdownMenuItem onSelect={() => actions.setPinned?.(w, !arrangement.pinned)}>
{arrangement.pinned ? <PinOff /> : <Pin />}
{arrangement.pinned
? t('auto.components.cloudWorkspaces.unpin', 'Unpin')
: t('auto.components.cloudWorkspaces.pin', 'Pin')}
</DropdownMenuItem>
)}
{arrangement && actions.move && (arrangement.canMoveUp || arrangement.canMoveDown) && (
<>
<DropdownMenuItem
disabled={!arrangement.canMoveUp}
onSelect={() => actions.move?.(w, -1)}
>
<ArrowUp />
{t('auto.components.cloudWorkspaces.moveUp', 'Move up')}
</DropdownMenuItem>
<DropdownMenuItem
disabled={!arrangement.canMoveDown}
onSelect={() => actions.move?.(w, 1)}
>
<ArrowDown />
{t('auto.components.cloudWorkspaces.moveDown', 'Move down')}
</DropdownMenuItem>
</>
)}
<DropdownMenuItem onSelect={() => actions.copyLink(w)}>
<Link2 />
{t('auto.components.cloudWorkspaces.copyLink', 'Copy link')}
@@ -7,6 +7,8 @@ import {
workspace
} from './cloud-workspaces.test-fixture'
import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state'
import type { CloudWorkspacePrefsDocument } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { setPrefsAccount } from './cloud-workspace-prefs'
import { getOrcaAccountKey } from '@/hooks/use-orca-account-key'
import { writeHomeSwitches } from './cloud-workspaces-home-prefs'
@@ -33,6 +35,35 @@ export const teamList = defineFixture({
interact: () => waitFor(() => document.querySelector('[data-cloud-workspace-row]') !== null)
})
/** Synced prefs: two pins on top (pin order), Payments collapsed, rows in their manual order. */
export const pinnedAndArranged = defineFixture({
width: WIDTH,
store: { orcaProfileAuthStatus: AUTH_STATUS },
setup: () => {
const rows = teamWorkspaces()
stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows }))
const document: CloudWorkspacePrefsDocument = {
pinned: [rows[3]!.id, rows[0]!.id],
order: [rows[2]!.id],
sections: ['Payments'],
collapsed: []
}
Object.assign(window.api.cloudWorkspaces, {
getPrefs: () =>
Promise.resolve({ ok: true as const, value: { document, revision: 3, updatedAt: 1 } }),
putPrefs: (next: CloudWorkspacePrefsDocument) =>
Promise.resolve({
ok: true as const,
value: { document: next, revision: 4, updatedAt: 2 }
})
})
setPrefsAccount(`fixture:${Math.random()}`)
},
render: () => <CloudWorkspacesHome />,
interact: () =>
waitFor(() => document.querySelector('[data-cloud-workspace-group="pinned"]') !== null)
})
/** A link pointed at this row; Home rings it while it opens. */
export const highlightedFromLink = defineFixture({
width: WIDTH,
@@ -14,6 +14,8 @@ import type {
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { useOrgRoster } from '../billing/team/use-org-roster'
import { CloudWorkspaceRow } from './CloudWorkspaceRow'
import { CloudWorkspaceGroupView, rowDragProps } from './CloudWorkspaceGroup'
import { useCloudWorkspaceArrangement } from './use-cloud-workspace-arrangement'
import { NEW_SECTION } from './CloudWorkspaceRowMenu'
import { ANY, CloudWorkspacesToolbar } from './CloudWorkspacesToolbar'
import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates'
@@ -132,16 +134,9 @@ export function CloudWorkspacesHome({
[all, by, repo, highlightId, filters.running]
)
const highlighted = highlightId ? visible.find((w) => w.id === highlightId) : undefined
const groups = useMemo(() => {
const out = new Map<string, CloudWorkspace[]>()
for (const w of visible) {
const key = w.section ?? ''
out.set(key, [...(out.get(key) ?? []), w])
}
return [...out.entries()].sort(([a], [b]) =>
a === '' ? 1 : b === '' ? -1 : a.localeCompare(b)
)
}, [visible])
// Pinned first, then sections, in the order you arranged them on any of your devices.
const arrangement = useCloudWorkspaceArrangement(visible)
const { groups } = arrangement
const members = useMemo(
() =>
[...directory.entries()].map(([userId, m]) => ({
@@ -245,9 +240,11 @@ export function CloudWorkspacesHome({
copyWorkspaceLink: (w: CloudWorkspace) => void copyCloudWorkspaceLink(w.id),
goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId),
patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change),
setPinned: arrangement.pin,
move: arrangement.move,
...homeArchive.homeArchiveActions({ selfId, t, refresh, confirmArchive: setConfirm })
}),
[open, patch, refresh, selfId, setReadingId, t]
[open, patch, refresh, selfId, setReadingId, t, arrangement.pin, arrangement.move]
)
// Nothing (not even a skeleton) until we know this build has a control plane and you are in.
@@ -315,56 +312,54 @@ export function CloudWorkspacesHome({
/>
)}
{state.status === 'ready' &&
groups.map(([section, rows], index) => {
// Section names are free text (spaces), so the id uses the position instead.
const headingId = `cloud-workspaces-section-${index}`
const showHeading = groups.length > 1 || section !== ''
groups.map((group, index) => {
const sectionIndex = group.section
? arrangement.shownSections.indexOf(group.section)
: -1
return (
<div key={section || '—'} className="py-0.5">
{showHeading && (
<h3
id={headingId}
className="px-3 py-2 text-2xs font-medium text-muted-foreground"
>
{section || t('auto.components.cloudWorkspaces.noSection', 'No section')}
{/* The bare number is visual; screen readers get the counted phrase. */}
<span aria-hidden className="ml-1.5 tabular-nums text-muted-foreground">
{rows.length}
</span>{' '}
<span className="sr-only">
{t('auto.components.cloudWorkspaces.sectionCount', '{{count}} workspaces', {
count: rows.length,
defaultValue_one: '{{count}} workspace'
})}
</span>
</h3>
)}
<ul
role="list"
aria-labelledby={showHeading ? headingId : 'cloud-workspaces-heading'}
>
{rows.map((w) => (
<CloudWorkspaceRow
key={w.id}
workspace={w}
directory={directory}
selfId={selfId}
canAdmin={canAdmin}
sections={sections}
members={members}
opening={opening === w.id}
highlighted={highlightId === w.id}
now={now}
actions={actions}
/>
))}
</ul>
</div>
<CloudWorkspaceGroupView
key={group.key}
group={group}
index={index}
showHeading={groups.length > 1 || group.kind !== 'none'}
canMoveUp={sectionIndex > 0}
canMoveDown={
sectionIndex >= 0 && sectionIndex < arrangement.shownSections.length - 1
}
onToggleCollapsed={(collapsed) =>
group.section && arrangement.toggleCollapsed(group.section, collapsed)
}
onMoveSection={(delta) =>
group.section && arrangement.moveSection(group.section, delta)
}
>
{group.rows.map((w, rowIndex) => (
<CloudWorkspaceRow
key={w.id}
workspace={w}
directory={directory}
selfId={selfId}
canAdmin={canAdmin}
sections={sections}
members={members}
opening={opening === w.id}
highlighted={highlightId === w.id}
now={now}
actions={actions}
arrangement={arrangement.arrangementFor(group, rowIndex)}
dragProps={rowDragProps(arrangement.drag, group, w.id)}
dragging={arrangement.drag.dragging?.id === w.id}
/>
))}
</CloudWorkspaceGroupView>
)
})}
</div>
{/* Polite, so opening from a link is announced without stealing focus. */}
<div aria-live="polite" className="sr-only">
{arrangement.announcement}
</div>
<div aria-live="polite" className="sr-only">
{highlighted
? t('auto.components.cloudWorkspaces.openedFromLink', 'Opened from link: {{title}}', {
@@ -14,7 +14,14 @@ import type { CloudWorkspaceRoutineRuns } from '../../../../shared/cloud-workspa
vi.mock('../new-workspace/run-on/OrcaCloudTrialUsedUpNotice', () => ({
OrcaCloudTrialUsedUpBanner: () => null
}))
vi.mock('@/hooks/useOrcaCloudApiAvailability', () => ({ useOrcaCloudApiAvailable: () => false }))
vi.mock('@/hooks/useOrcaCloudApiAvailability', () => ({ useOrcaCloudApiAvailable: () => true }))
// The switch is behind the parked-Routines flag; flip it per test to cover both states.
const flag = vi.hoisted(() => ({ on: true }))
vi.mock('../../../../shared/cloud-api/cloud-routines-ui', () => ({
get CLOUD_ROUTINES_UI_ENABLED() {
return flag.on
}
}))
afterEach(cleanup)
@@ -52,6 +59,19 @@ const runs = (over: Partial<CloudWorkspaceRoutineRuns> = {}): CloudWorkspaceRout
...over
})
describe('Home toolbar while Routines are parked', () => {
it('offers neither the Routines entry nor the Routine runs switch', () => {
flag.on = false
try {
toolbar(runs({ hidden: 2, hiddenRunning: 1 }), { routines: true })
expect(screen.queryByLabelText('Show routine runs')).toBeNull()
expect(screen.queryByRole('button', { name: 'Routines' })).toBeNull()
} finally {
flag.on = true
}
})
})
describe('Home toolbar: Routine runs switch', () => {
it('is not offered to a team with no routines (or an older control plane)', () => {
toolbar(runs({ routines: 0 }))
@@ -17,6 +17,7 @@ import { cn } from '@/lib/utils'
import { repoLabel, type MemberDirectory } from './cloud-workspace-format'
import type { CloudWorkspaceRoutineRuns } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { OrcaCloudTrialUsedUpBanner } from '../new-workspace/run-on/OrcaCloudTrialUsedUpNotice'
import { CLOUD_ROUTINES_UI_ENABLED } from '../../../../shared/cloud-api/cloud-routines-ui'
export const ANY = '__any'
@@ -78,7 +79,8 @@ export function CloudWorkspacesToolbar({
}): React.JSX.Element {
const t = useTranslate()
// Routines start cloud workspaces on their own, so they sit next to the list they fill.
const routinesAvailable = useOrcaCloudApiAvailable()
// Routines are parked (cloud-routines-ui.ts): no Routines entry and no Routine runs switch.
const routinesAvailable = useOrcaCloudApiAvailable() && CLOUD_ROUTINES_UI_ENABLED
return (
<div className="mb-2 flex flex-col gap-2">
<div className="flex items-center gap-2">
@@ -192,7 +194,8 @@ export function CloudWorkspacesToolbar({
/>
{t('auto.components.cloudWorkspaces.running', 'Running')}
</label>
{(routineRuns?.routines ?? 0) > 0 || filters.routines === true ? (
{CLOUD_ROUTINES_UI_ENABLED &&
((routineRuns?.routines ?? 0) > 0 || filters.routines === true) ? (
<label className="flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.routines === true}
@@ -0,0 +1,129 @@
// Which cloud workspace (sandbox) a sidebar worktree is, and that workspace's number (W-123) and
// link. Numbers and links come from the control plane's list; the worktree mapping comes from this
// desktop: the owner's own hosted runtime (by worktree id) or a teammate's paired runtime
// environment (by host id). A tiny external store so palette rows and headers stay cheap.
import { useSyncExternalStore } from 'react'
import { toRuntimeExecutionHostId } from '../../../../shared/execution-host'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
export type CloudWorkspaceIdentity = {
number: number | null
link: string | null
title: string | null
}
type State = {
bySandbox: ReadonlyMap<string, CloudWorkspaceIdentity>
sandboxByWorktree: ReadonlyMap<string, string>
sandboxByHost: ReadonlyMap<string, string>
}
let state: State = { bySandbox: new Map(), sandboxByWorktree: new Map(), sandboxByHost: new Map() }
const listeners = new Set<() => void>()
function publish(next: State): void {
state = next
listeners.forEach((listener) => listener())
}
function sameIdentity(a: CloudWorkspaceIdentity | undefined, b: CloudWorkspaceIdentity): boolean {
return a !== undefined && a.number === b.number && a.link === b.link && a.title === b.title
}
/** Folds a list (or one workspace) the control plane returned into the cache. */
export function rememberCloudWorkspaces(workspaces: readonly CloudWorkspace[]): void {
let changed = false
const next = new Map(state.bySandbox)
for (const w of workspaces) {
const identity = { number: w.number ?? null, link: w.link ?? null, title: w.title }
if (!sameIdentity(next.get(w.id), identity)) {
next.set(w.id, identity)
changed = true
}
}
if (changed) {
publish({ ...state, bySandbox: next })
}
}
/** Re-reads which local worktrees and runtime hosts are cloud workspaces on this desktop. */
export async function refreshCloudWorktreeBindings(): Promise<void> {
const api = window.api.cloudWorkspaces
const [local, bindings] = await Promise.all([
api.localWorkspaces().catch(() => []),
api.environmentBindings().catch(() => ({}))
])
const sandboxByWorktree = new Map<string, string>()
const sandboxByHost = new Map<string, string>()
for (const entry of local) {
if (entry.worktreeId) {
sandboxByWorktree.set(entry.worktreeId, entry.sandboxId)
}
if (entry.runtimeEnvironmentId) {
sandboxByHost.set(toRuntimeExecutionHostId(entry.runtimeEnvironmentId), entry.sandboxId)
}
}
for (const [sandboxId, binding] of Object.entries(bindings)) {
sandboxByHost.set(toRuntimeExecutionHostId(binding.environmentId), sandboxId)
}
const same = (a: ReadonlyMap<string, string>, b: Map<string, string>) =>
a.size === b.size && [...b].every(([key, value]) => a.get(key) === value)
if (
!same(state.sandboxByWorktree, sandboxByWorktree) ||
!same(state.sandboxByHost, sandboxByHost)
) {
publish({ ...state, sandboxByWorktree, sandboxByHost })
}
}
export function sandboxIdForWorktree(
worktree: { id: string; hostId?: string | null },
current: State = state
): string | null {
return (
(worktree.hostId ? current.sandboxByHost.get(worktree.hostId) : undefined) ??
current.sandboxByWorktree.get(worktree.id) ??
null
)
}
export function cloudWorkspaceIdentity(sandboxId: string | null): CloudWorkspaceIdentity | null {
return sandboxId ? (state.bySandbox.get(sandboxId) ?? null) : null
}
/** W-number of the cloud workspace a worktree belongs to, or null (not cloud, or not known yet). */
export function cloudNumberForWorktree(
worktree: { id: string; hostId?: string | null },
current: State = state
): number | null {
const sandboxId = sandboxIdForWorktree(worktree, current)
return sandboxId ? (current.bySandbox.get(sandboxId)?.number ?? null) : null
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
/** The whole cache; changes identity only when something in it changed (memo dependency). */
export function useCloudWorkspaceIdentities(): State {
return useSyncExternalStore(subscribe, () => state)
}
export function useCloudWorkspaceNumber(sandboxId: string | null | undefined): number | null {
return useSyncExternalStore(subscribe, () =>
sandboxId ? (state.bySandbox.get(sandboxId)?.number ?? null) : null
)
}
export function useCloudWorktreeNumber(
worktree: { id: string; hostId?: string | null } | null | undefined
): number | null {
return useSyncExternalStore(subscribe, () => (worktree ? cloudNumberForWorktree(worktree) : null))
}
/** Test-only. */
export function resetCloudWorkspaceIdentityForTests(): void {
state = { bySandbox: new Map(), sandboxByWorktree: new Map(), sandboxByHost: new Map() }
listeners.clear()
}
@@ -0,0 +1,70 @@
// What a cloud workspace link that didn't resolve tells the user. A W-number link names the
// workspace ("You don't have access to W-12."); one for a team you're in but don't have active
// offers to switch to that team and open it.
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { useAppStore } from '@/store'
import {
formatWorkspaceNumber,
type CloudWorkspaceLinkTarget
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { describeError } from './cloud-workspace-errors'
type Failure = { error: string; reason?: string; orgId?: string }
export function reportCloudWorkspaceLinkFailure(
target: CloudWorkspaceLinkTarget,
failure: Failure,
/** Opens the same link again (after a team switch). */
retry: () => void
): void {
if (target.kind === 'number' && failure.error === 'not_found') {
const label = formatWorkspaceNumber(target.number)
if (failure.reason !== 'other_org' || !offerTeamSwitch(failure.orgId, label, retry)) {
toast.error(
translate(
'auto.components.cloudWorkspaces.linkNoAccess',
"You don't have access to {{number}}.",
{
number: label
}
)
)
}
return
}
toast.error(
failure.error === 'not_found'
? translate(
'auto.components.cloudWorkspaces.linkNotFound',
'This link points to a private workspace, another team, or a workspace that was deleted.'
)
: describeError(failure.error, failure.reason)
)
}
/** False when you are not in that team (then it's plain "no access"). */
function offerTeamSwitch(orgId: string | undefined, label: string, retry: () => void): boolean {
const state = useAppStore.getState()
const org = orgId
? state.orcaProfileAuthStatus?.organizations?.find((o) => o.orgId === orgId)
: undefined
if (!org) {
return false
}
toast.info(
translate('auto.components.cloudWorkspaces.linkOtherTeam2', '{{number}} is in {{team}}.', {
number: label,
team: org.name
}),
{
action: {
label: translate('auto.components.cloudWorkspaces.linkSwitchTeam', 'Switch and open'),
onClick: () => {
void state.selectOrcaProfileOrg(org.orgId).then(retry)
}
}
}
)
return true
}
@@ -3,15 +3,16 @@
import { useSyncExternalStore } from 'react'
import { toast } from 'sonner'
import { useAppStore } from '@/store'
import { translate } from '@/i18n/i18n'
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
import { keybindingMatchesAction } from '../../../../shared/keybindings/matching'
import { parseCloudWorkspaceLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { reportCloudWorkspaceLinkFailure } from './cloud-workspace-link-failure'
import { toRuntimeExecutionHostId } from '../../../../shared/execution-host'
import { describeError } from './cloud-workspace-errors'
import { copyCloudWorkspaceLink, openCloudWorkspace } from './open-cloud-workspace'
import { currentCloudChatId, focusCloudChat } from './cloud-chat-focus'
import { cloudWorkspacesAvailable } from './use-cloud-workspaces'
import { installCloudWorkspaceSync } from './cloud-workspace-sync'
import { rememberCloudWorkspaces } from './cloud-workspace-identity'
const HIGHLIGHT_MS = 4_000
/** No input for this long and the desktop stops reporting presence (and renewing a lease). */
@@ -47,27 +48,27 @@ export async function handleCloudWorkspaceLink(link: string): Promise<void> {
if (!parsed || !(await cloudWorkspacesAvailable())) {
return
}
setHighlight(parsed.workspaceId)
const resolved = await window.api.cloudWorkspaces.resolveLink(parsed.workspaceId, parsed.chatId)
if (parsed.target.kind === 'id') {
setHighlight(parsed.target.workspaceId)
}
const resolved = await window.api.cloudWorkspaces.resolveLink(parsed.target, parsed.chatId)
if (!resolved.ok) {
toast.error(
resolved.error === 'not_found'
? translate(
'auto.components.cloudWorkspaces.linkNotFound',
'This link points to a private workspace, another team, or a workspace that was deleted.'
)
: describeError(resolved.error, resolved.reason)
)
setHighlight(null)
reportCloudWorkspaceLinkFailure(parsed.target, resolved, () => {
void handleCloudWorkspaceLink(link)
})
return
}
const outcome = await openCloudWorkspace(resolved.value.workspace)
const workspace = resolved.value.workspace
rememberCloudWorkspaces([workspace])
setHighlight(workspace.id)
const outcome = await openCloudWorkspace(workspace)
if (!outcome.ok) {
toast.error(outcome.message)
} else if (resolved.value.chatId) {
await focusCloudChat(outcome.worktreeId, resolved.value.chatId)
}
setHighlight(parsed.workspaceId, HIGHLIGHT_MS)
setHighlight(workspace.id, HIGHLIGHT_MS)
}
type Front = {
@@ -128,6 +129,7 @@ export function installCloudWorkspaceLinks(): () => void {
if (!api) {
return () => {}
}
cleanups.push(installCloudWorkspaceSync())
cleanups.push(
api.onOpenLink((link) => {
// The push already delivered it; drain the pending copy so a reload does not replay it.
@@ -0,0 +1,107 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
EMPTY_CLOUD_WORKSPACE_PREFS,
type CloudWorkspacePrefsDocument
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { setPinned } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement'
import {
editCloudWorkspacePrefs,
getCloudWorkspacePrefs,
refreshCloudWorkspacePrefs,
resetCloudWorkspacePrefsForTests,
setPrefsAccount
} from './cloud-workspace-prefs'
const toastError = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({ toast: { error: toastError } }))
const A = `sbx_${'a'.repeat(24)}`
const B = `sbx_${'b'.repeat(24)}`
/** A control plane with compare-and-set, plus a hook to simulate another device writing first. */
function fakeServer() {
const server: { document: CloudWorkspacePrefsDocument; revision: number } = {
document: EMPTY_CLOUD_WORKSPACE_PREFS,
revision: 0
}
const view = () => ({ ok: true as const, value: { ...server, updatedAt: null } })
let failPuts = false
const api = {
getPrefs: vi.fn(async () => view()),
putPrefs: vi.fn(async (document: CloudWorkspacePrefsDocument, revision: number) => {
if (failPuts) {
return { ok: false as const, error: 'unavailable' }
}
if (revision !== server.revision) {
return { ok: false as const, error: 'conflict', reason: 'stale_revision' }
}
server.document = document
server.revision += 1
return view()
})
}
return {
server,
api,
otherDevice: (edit: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument) => {
server.document = edit(server.document)
server.revision += 1
},
failPuts: (value: boolean) => {
failPuts = value
}
}
}
describe('cloud workspace prefs sync', () => {
let fake: ReturnType<typeof fakeServer>
beforeEach(() => {
resetCloudWorkspacePrefsForTests()
toastError.mockReset()
fake = fakeServer()
vi.stubGlobal('window', { api: { cloudWorkspaces: fake.api } })
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('shows an edit at once and saves it', async () => {
setPrefsAccount('u:org')
await refreshCloudWorkspacePrefs()
const saved = editCloudWorkspacePrefs((doc) => setPinned(doc, A, true))
expect(getCloudWorkspacePrefs().document.pinned).toEqual([A])
await saved
expect(fake.server).toMatchObject({ document: { pinned: [A] }, revision: 1 })
expect(getCloudWorkspacePrefs().document.pinned).toEqual([A])
})
it('re-applies an edit on top of a write from another device', async () => {
setPrefsAccount('u:org')
await refreshCloudWorkspacePrefs()
fake.otherDevice((doc) => setPinned(doc, B, true))
await editCloudWorkspacePrefs((doc) => setPinned(doc, A, true))
expect(fake.api.putPrefs).toHaveBeenCalledTimes(2)
expect(fake.server.document.pinned).toEqual([B, A])
expect(getCloudWorkspacePrefs().document.pinned).toEqual([B, A])
})
it('drops a failed edit and says so', async () => {
setPrefsAccount('u:org')
await refreshCloudWorkspacePrefs()
fake.failPuts(true)
await editCloudWorkspacePrefs((doc) => setPinned(doc, A, true))
expect(getCloudWorkspacePrefs().document.pinned).toEqual([])
expect(toastError).toHaveBeenCalledTimes(1)
})
it('picks up remote edits on refresh and starts empty for another account', async () => {
setPrefsAccount('u:org')
await refreshCloudWorkspacePrefs()
fake.otherDevice((doc) => setPinned(doc, B, true))
await refreshCloudWorkspacePrefs()
expect(getCloudWorkspacePrefs().document.pinned).toEqual([B])
setPrefsAccount('u:other')
expect(getCloudWorkspacePrefs()).toMatchObject({ account: 'u:other', loaded: false })
expect(getCloudWorkspacePrefs().document.pinned).toEqual([])
})
})
@@ -0,0 +1,156 @@
// This member's synced arrangement of cloud workspaces (pins, their order, section order and
// collapsed sections), kept on the account (/v1/team/prefs) so every desktop and the phone agree.
// One copy per window. What shows is the server copy with this window's unsaved edits applied on
// top, so an edit shows at once. Edits save one at a time with compare-and-set: each applies to
// the newest server copy, and a stale write re-reads and applies the same edit again, so edits
// from two devices both land. Remote edits arrive by polling while the window is visible.
import { useSyncExternalStore } from 'react'
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import {
EMPTY_CLOUD_WORKSPACE_PREFS,
type CloudWorkspacePrefsDocument
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
/** Remote edits show up within this long while a window is visible. */
export const PREFS_POLL_MS = 15_000
const MAX_ATTEMPTS = 4
type Edit = (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument
export type CloudWorkspacePrefsSnapshot = {
/** `${userId}:${orgId}`; prefs belong to one account, so a team switch starts empty. */
account: string | null
/** The server copy with unsaved edits applied: what to render. */
document: CloudWorkspacePrefsDocument
loaded: boolean
}
let account: string | null = null
let server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false }
let pending: Edit[] = []
let queue: Promise<void> = Promise.resolve()
let snapshot: CloudWorkspacePrefsSnapshot = {
account: null,
document: EMPTY_CLOUD_WORKSPACE_PREFS,
loaded: false
}
const listeners = new Set<() => void>()
function publish(): void {
snapshot = {
account,
document: pending.reduce((doc, edit) => edit(doc), server.document),
loaded: server.loaded
}
listeners.forEach((listener) => listener())
}
export function getCloudWorkspacePrefs(): CloudWorkspacePrefsSnapshot {
return snapshot
}
export function useCloudWorkspacePrefs(): CloudWorkspacePrefsSnapshot {
return useSyncExternalStore(
(listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
() => snapshot
)
}
/** Switches to `next` (empty until read); a no-op when it is already the current account. */
export function setPrefsAccount(next: string | null): void {
if (account === next) {
return
}
account = next
server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false }
pending = []
publish()
}
async function readServer(forAccount: string): Promise<boolean> {
const result = await window.api.cloudWorkspaces.getPrefs()
if (!result.ok || account !== forAccount) {
return false
}
if (!server.loaded || result.value.revision !== server.revision) {
server = { document: result.value.document, revision: result.value.revision, loaded: true }
publish()
}
return true
}
/** Reads the server copy (polling, focus, Home opening). */
export async function refreshCloudWorkspacePrefs(): Promise<void> {
if (account) {
await readServer(account)
}
}
async function save(forAccount: string, edit: Edit): Promise<boolean> {
if (!server.loaded && !(await readServer(forAccount))) {
return false
}
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
const next = edit(server.document)
if (next === server.document) {
return true
}
const result = await window.api.cloudWorkspaces.putPrefs(next, server.revision)
if (account !== forAccount) {
return true
}
if (result.ok) {
server = { document: result.value.document, revision: result.value.revision, loaded: true }
return true
}
// Another device wrote first: take its copy and apply this edit to it.
if (result.error !== 'conflict' || !(await readServer(forAccount))) {
return false
}
}
return false
}
/**
* Shows `edit` now and saves it. If saving fails, the edit is dropped (the server copy shows
* again) and a toast says so.
*/
export function editCloudWorkspacePrefs(edit: Edit): Promise<void> {
const forAccount = account
if (!forAccount || edit(snapshot.document) === snapshot.document) {
return Promise.resolve()
}
pending = [...pending, edit]
publish()
queue = queue.then(async () => {
const saved = await save(forAccount, edit).catch(() => false)
if (account !== forAccount) {
return
}
pending = pending.filter((other) => other !== edit)
publish()
if (!saved) {
toast.error(
translate(
'auto.components.cloudWorkspaces.prefsSaveFailed',
"Couldn't save that change, so your other devices won't show it. Try again."
)
)
}
})
return queue
}
/** Test-only: forget everything. */
export function resetCloudWorkspacePrefsForTests(): void {
account = null
server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false }
pending = []
queue = Promise.resolve()
snapshot = { account: null, document: EMPTY_CLOUD_WORKSPACE_PREFS, loaded: false }
listeners.clear()
}
@@ -0,0 +1,152 @@
// App-level sync for cloud workspace arrangement and identity, installed with the link wiring:
// follows the signed-in account, polls this member's synced prefs (pins, order, sections) while the
// window is visible, keeps W-numbers and links for the palette and headers, and names the org's
// link slug the first time anyone in the org asks (the control plane only knows org ids).
import { useAppStore } from '@/store'
import { getOrcaAccountKey } from '@/hooks/use-orca-account-key'
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
import { cloudWorkspacesAvailable } from './use-cloud-workspaces'
import {
PREFS_POLL_MS,
editCloudWorkspacePrefs,
refreshCloudWorkspacePrefs,
setPrefsAccount
} from './cloud-workspace-prefs'
import {
cloudWorkspaceIdentity,
refreshCloudWorktreeBindings,
rememberCloudWorkspaces,
sandboxIdForWorktree
} from './cloud-workspace-identity'
import { setPinned } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement'
import { onWorktreesPinnedByUser } from '@/lib/orca-cloud/worktree-pin-listeners'
/** Numbers and links rarely change; Home's own polling refreshes them faster while it is open. */
const IDENTITY_POLL_MS = 60_000
const FRONT_RETRY_MS = 5_000
export function installCloudWorkspaceSync(): () => void {
const api = window.api.cloudWorkspaces
if (!api) {
return () => {}
}
let account: string | null = null
const sluggedAccounts = new Set<string>()
const refreshIdentity = async (): Promise<void> => {
if (!account || !(await cloudWorkspacesAvailable())) {
return
}
const forAccount = account
const [list] = await Promise.all([
api.list({ scope: 'team', archived: 'include' }),
refreshCloudWorktreeBindings()
])
if (list.ok && account === forAccount) {
rememberCloudWorkspaces(list.value)
}
}
const ensureSlug = async (): Promise<void> => {
const status = useAppStore.getState().orcaProfileAuthStatus
const orgName = status?.cloud?.activeOrgName
if (!account || !status?.cloud?.activeOrgId || sluggedAccounts.has(account)) {
return
}
const forAccount = account
const result = await api.getOrgSlug(orgName ?? null)
if (result.ok && result.value.slug && account === forAccount) {
sluggedAccounts.add(forAccount)
// Links in the list now carry the slug form.
void refreshIdentity()
}
}
const follow = (): void => {
const status = useAppStore.getState().orcaProfileAuthStatus
const next = status?.state === 'connected' ? getOrcaAccountKey(status) : null
const key = next === 'signed-out' ? null : next
if (key === account) {
return
}
account = key
setPrefsAccount(key)
if (key) {
void cloudWorkspacesAvailable().then((available) => {
if (available && account === key) {
void refreshCloudWorkspacePrefs()
void ensureSlug().then(refreshIdentity)
}
})
}
}
const cleanups: (() => void)[] = []
cleanups.push(
useAppStore.subscribe((state, previous) => {
if (state.orcaProfileAuthStatus !== previous.orcaProfileAuthStatus) {
follow()
}
})
)
follow()
cleanups.push(
installWindowVisibilityInterval({
run: () => void refreshCloudWorkspacePrefs(),
intervalMs: PREFS_POLL_MS
})
)
cleanups.push(
installWindowVisibilityInterval({
run: () => void ensureSlug().then(refreshIdentity),
intervalMs: IDENTITY_POLL_MS
})
)
// Pinning a cloud workspace's row in the sidebar pins it in your synced prefs too.
cleanups.push(
onWorktreesPinnedByUser((targets, isPinned) => {
const ids = [...new Set(targets.flatMap((target) => sandboxIdForWorktree(target) ?? []))]
if (account && ids.length > 0) {
void editCloudWorkspacePrefs((doc) =>
ids.reduce((next, id) => setPinned(next, id, isPinned), doc)
)
}
})
)
// Switching to a workspace (a new cloud one just created or paired, too) re-reads which local
// runtimes are cloud workspaces, and fetches numbers when the one in front has none yet. A
// runtime registers a moment after it opens, so a miss is checked once more shortly after.
let followUp: ReturnType<typeof setTimeout> | undefined
const identifyFront = async (): Promise<boolean> => {
await refreshCloudWorktreeBindings()
const state = useAppStore.getState()
const id = state.activeWorktreeId
const sandboxId = id
? sandboxIdForWorktree({ id, hostId: state.activeWorkspaceExecutionHostId })
: null
if (sandboxId && !cloudWorkspaceIdentity(sandboxId)?.number) {
await refreshIdentity()
}
return sandboxId !== null || !id
}
cleanups.push(
useAppStore.subscribe((state, previous) => {
if (
state.activeWorktreeId !== previous.activeWorktreeId ||
state.activeWorkspaceExecutionHostId !== previous.activeWorkspaceExecutionHostId
) {
clearTimeout(followUp)
void identifyFront().then((known) => {
if (!known) {
followUp = setTimeout(() => void identifyFront(), FRONT_RETRY_MS)
}
})
}
})
)
cleanups.push(() => clearTimeout(followUp))
return () => {
cleanups.forEach((cleanup) => cleanup())
setPrefsAccount(null)
}
}
@@ -65,6 +65,7 @@ export function workspace(overrides: Partial<CloudWorkspace>): CloudWorkspace {
region: 'iad1',
createdAt: FIXTURE_NOW - 86_400_000,
title: null,
number: 40 + next,
repo: { url: 'https://github.com/acme/payments.git', branch: 'main' },
visibility: 'team',
section: null,
@@ -10,7 +10,8 @@ import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-a
import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler'
import { RuntimeRpcCallError, unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity'
import {
getWorktreeExecutionHostId,
toRuntimeExecutionHostId
@@ -236,19 +237,40 @@ export function openCloudWorkspace(workspace: CloudWorkspace): Promise<OpenOutco
return attempt
}
export async function copyCloudWorkspaceLink(id: string, chatId?: string | null): Promise<void> {
/** The org slug + W-number link when the control plane gave one, else the sandbox id form. */
async function shareLinkFor(id: string, chatId?: string | null): Promise<string> {
let link = cloudWorkspaceIdentity(id)?.link ?? null
if (!link) {
const fetched = await window.api.cloudWorkspaces.get(id).catch(() => null)
if (fetched?.ok) {
rememberCloudWorkspaces([fetched.value])
link = fetched.value.link ?? null
}
}
return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId)
}
export async function copyCloudWorkspaceLink(
id: string,
chatId?: string | null,
options: { quiet?: boolean } = {}
): Promise<boolean> {
try {
await navigator.clipboard.writeText(cloudWorkspaceLink(id, chatId))
await navigator.clipboard.writeText(await shareLinkFor(id, chatId))
} catch (error) {
console.warn('[cloud-workspaces] copy link failed', error)
toast.error(
translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.")
)
return
return false
}
if (options.quiet) {
return true
}
toast.success(
chatId
? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied')
: translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied')
)
return true
}
@@ -6,12 +6,15 @@ import {
} from './CloudWorkspacesToolbar'
import { readHomeSwitches, writeHomeSwitches } from './cloud-workspaces-home-prefs'
import { usePendingHomeFilters } from './cloud-workspaces-home-nav'
import { CLOUD_ROUTINES_UI_ENABLED } from '../../../../shared/cloud-api/cloud-routines-ui'
/** Home's list filters for this account. The three switches are remembered; owner/repo/scope start fresh. */
export function useCloudHomeFilters(account: string) {
const initialFilters = (key: string): CloudWorkspacesFilters => ({
...INITIAL_CLOUD_WORKSPACE_FILTERS,
...readHomeSwitches(key)
...readHomeSwitches(key),
// A switch saved before Routines were parked must not keep listing routine runs.
...(CLOUD_ROUTINES_UI_ENABLED ? {} : { routines: false })
})
const [filters, setFilters] = useState(() => initialFilters(account))
usePendingHomeFilters(setFilters)
@@ -0,0 +1,182 @@
// Home's arrangement state: groups from your synced prefs, plus the edits (pin, move, drag,
// collapse, section order) that save back to them.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import {
formatWorkspaceNumber,
type CloudWorkspace
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import {
MAX_PINNED,
arrangeCloudWorkspaces,
dropOnto,
moveSection,
nudge,
reorderGroup,
setCollapsed,
setPinned,
type CloudWorkspaceGroup
} from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement'
import {
editCloudWorkspacePrefs,
getCloudWorkspacePrefs,
refreshCloudWorkspacePrefs,
useCloudWorkspacePrefs
} from './cloud-workspace-prefs'
import type { GroupDrag } from './CloudWorkspaceGroup'
import type { RowArrangement } from './CloudWorkspaceRowMenu'
import { cloudWorkspaceTitle } from './open-cloud-workspace'
/** How a screen reader hears a workspace in move confirmations: its number, else its title. */
function spoken(w: CloudWorkspace | undefined): string {
return !w ? '' : w.number ? formatWorkspaceNumber(w.number) : cloudWorkspaceTitle(w)
}
function groupName(group: CloudWorkspaceGroup<CloudWorkspace>): string {
return group.kind === 'pinned'
? translate('auto.components.cloudWorkspaces.pinned', 'Pinned')
: (group.section ??
translate('auto.components.cloudWorkspaces.otherWorkspaces', 'Other workspaces'))
}
export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) {
const prefs = useCloudWorkspacePrefs()
// Drags and menu moves are confirmed politely for screen readers ("Moved W-12 to position 2 in Pinned").
const [announcement, setAnnouncement] = useState('')
// Opening Home is a good moment to pick up another device's edits without waiting for the poll.
useEffect(() => {
void refreshCloudWorkspacePrefs()
}, [])
const groups = useMemo(
() => arrangeCloudWorkspaces(visible, prefs.document),
[visible, prefs.document]
)
const groupOf = useCallback(
(id: string): CloudWorkspaceGroup<CloudWorkspace> | undefined =>
groups.find((group) => group.rows.some((w) => w.id === id)),
[groups]
)
const reorder = useCallback(
(group: CloudWorkspaceGroup<CloudWorkspace>, ids: string[] | null, movedId: string) => {
if (!ids) {
return
}
void editCloudWorkspacePrefs((doc) => reorderGroup(doc, group, ids))
setAnnouncement(
translate(
'auto.components.cloudWorkspaces.movedTo',
'Moved {{name}} to position {{position}} in {{group}}',
{
name: spoken(group.rows.find((w) => w.id === movedId)),
position: ids.indexOf(movedId) + 1,
group: groupName(group)
}
)
)
},
[]
)
const [dragging, setDragging] = useState<GroupDrag['dragging']>(null)
const drag = useMemo<GroupDrag>(
() => ({
dragging,
start: (id, group) => setDragging({ id, group }),
end: () => setDragging(null),
drop: (overId, groupKey) => {
const group = groups.find((g) => g.key === groupKey)
if (dragging && group) {
reorder(
group,
dropOnto(
group.rows.map((w) => w.id),
dragging.id,
overId
),
dragging.id
)
}
setDragging(null)
}
}),
[dragging, groups, reorder]
)
const pin = useCallback((w: CloudWorkspace, pinned: boolean) => {
if (pinned && getCloudWorkspacePrefs().document.pinned.length >= MAX_PINNED) {
toast.error(
translate(
'auto.components.cloudWorkspaces.pinLimit',
'You can pin up to {{count}} workspaces. Unpin one first.',
{ count: MAX_PINNED }
)
)
return
}
void editCloudWorkspacePrefs((doc) => setPinned(doc, w.id, pinned))
setAnnouncement(
pinned
? translate('auto.components.cloudWorkspaces.pinnedName', 'Pinned {{name}}', {
name: spoken(w)
})
: translate('auto.components.cloudWorkspaces.unpinnedName', 'Unpinned {{name}}', {
name: spoken(w)
})
)
}, [])
const move = useCallback(
(w: CloudWorkspace, delta: number) => {
const group = groupOf(w.id)
if (group) {
reorder(
group,
nudge(
group.rows.map((row) => row.id),
w.id,
delta
),
w.id
)
}
},
[groupOf, reorder]
)
const shownSections = useMemo(
() =>
groups.flatMap((group) => (group.kind === 'section' && group.section ? [group.section] : [])),
[groups]
)
const toggleCollapsed = useCallback((section: string, collapsed: boolean) => {
void editCloudWorkspacePrefs((doc) => setCollapsed(doc, section, collapsed))
}, [])
const moveSectionBy = useCallback(
(section: string, delta: number) => {
void editCloudWorkspacePrefs((doc) => moveSection(doc, shownSections, section, delta) ?? doc)
},
[shownSections]
)
const arrangementFor = useCallback(
(group: CloudWorkspaceGroup<CloudWorkspace>, index: number): RowArrangement => ({
pinned: group.kind === 'pinned',
canMoveUp: index > 0,
canMoveDown: index < group.rows.length - 1
}),
[]
)
return {
announcement,
groups,
drag,
pin,
move,
toggleCollapsed,
moveSection: moveSectionBy,
shownSections,
arrangementFor
}
}
@@ -6,6 +6,7 @@ import type {
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { availabilityRetryDelay } from '@/lib/availability-retry'
import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller'
import { rememberCloudWorkspaces } from './cloud-workspace-identity'
/** Presence is live; the list re-reads on this beat while visible (and on focus). */
const POLL_MS = 8_000
@@ -133,6 +134,7 @@ export function useCloudWorkspaces(
return
}
if (result.ok) {
rememberCloudWorkspaces(result.value)
setState({
status: 'ready',
key,
@@ -82,7 +82,9 @@ export default function RunTargetRowList({
key={row.key}
icon={<HostRowIcon hostId={row.option.hostId} />}
label={row.option.label}
detail={row.option.path}
detail=""
// JA-10: no raw paths in the menu. The folder name, with the full path on hover.
detailNode={<span title={row.option.path}>{folderName(row.option.path)}</span>}
armed={isArmed}
current={row.option === selectedHost}
optionId={optionId}
@@ -171,3 +173,9 @@ export default function RunTargetRowList({
</>
)
}
/** The last segment of a checkout path ("/Users/me/code/acme-web" → "acme-web"). */
function folderName(path: string): string {
const parts = path.split(/[\\/]/).filter(Boolean)
return parts.at(-1) ?? path
}
@@ -0,0 +1,61 @@
// @vitest-environment happy-dom
import { cleanup, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
const { toast } = vi.hoisted(() => ({ toast: { custom: vi.fn(), dismiss: vi.fn() } }))
vi.mock('sonner', () => ({ toast }))
vi.mock('@/store', () => ({
useAppStore: (select: (state: unknown) => unknown) =>
select({ ephemeralVmRuntimesByWorkspaceId: { w1: { runtimeEnvironmentId: 'env-1' } } })
}))
import { CloudSetupNoticesDock, cloudSetupToastId } from './CloudSetupNotices'
import {
dismissCloudSetupNotice,
resetCloudSetupNotices,
setCloudSetupNotices
} from '@/lib/orca-cloud/cloud-setup-notices-store'
afterEach(() => {
cleanup()
resetCloudSetupNotices()
vi.clearAllMocks()
})
describe('CloudSetupNoticesDock (DS-o)', () => {
it('joins the app toast stack under one id and leaves it with its workspace', () => {
setCloudSetupNotices({
environmentId: 'env-1',
path: '/w',
repoId: 'r',
hostId: null,
repoUrl: 'https://github.com/stablyai/orca',
notices: [
{
id: 'git.push',
kind: 'push',
check: { id: 'git.push', category: 'git', status: 'fail', message: 'refused' }
}
]
})
const view = render(<CloudSetupNoticesDock workspaceId="w1" />)
expect(toast.custom).toHaveBeenCalled()
expect(toast.custom.mock.calls.at(-1)?.[1]).toMatchObject({
id: cloudSetupToastId('env-1'),
duration: Infinity
})
// Its last line dismissed: the toast goes too.
dismissCloudSetupNotice('env-1', 'git.push')
view.rerender(<CloudSetupNoticesDock workspaceId="w1" />)
expect(toast.dismiss).toHaveBeenCalledWith(cloudSetupToastId('env-1'))
toast.dismiss.mockClear()
vi.useFakeTimers()
view.unmount()
// Applied a tick later, so a StrictMode remount can claim the toast back first.
expect(toast.dismiss).not.toHaveBeenCalled()
vi.runAllTimers()
expect(toast.dismiss).toHaveBeenCalledWith(cloudSetupToastId('env-1'))
vi.useRealTimers()
})
})
@@ -1,5 +1,6 @@
import React, { useEffect, useId, useRef, useState } from 'react'
import { GitPullRequestArrow, Loader2, Play, TriangleAlert, X } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { useAppStore } from '@/store'
import { useTranslate, type Translate } from '@/i18n/use-translate'
@@ -153,13 +154,11 @@ function usePushRecheck(
/**
* What the environment check found that didn't need to stop the create: one line per problem, one
* action each, each dismissible. Sits with the workspace's other notices, top right.
* action each, each dismissible. It joins the app's toast stack (DS-o), so it stacks with other
* toasts (newest on top, same right edge) instead of floating beside them. Shown while its
* workspace is the active one; leaving the workspace (or its sleep) takes it down again.
*/
export function CloudSetupNotices({
workspaceId
}: {
workspaceId: string
}): React.JSX.Element | null {
export function CloudSetupNoticesDock({ workspaceId }: { workspaceId: string }): null {
const environmentId = useAppStore(
(state) => state.ephemeralVmRuntimesByWorkspaceId?.[workspaceId]?.runtimeEnvironmentId
)
@@ -170,31 +169,68 @@ export function CloudSetupNotices({
environmentId,
notices.some((notice) => notice.kind === 'push')
)
if (!record || notices.length === 0) {
return null
}
return (
<CloudSetupNoticesView
record={record}
notices={notices}
installing={push.installing}
onInstall={() => record.repoUrl && push.startInstall(record.repoUrl)}
onRunSetup={(noticeId) => void runCloudSetupScript(workspaceId, record, noticeId)}
onDismiss={(noticeId) => dismissCloudSetupNotice(record.environmentId, noticeId)}
/>
const toastId = environmentId ? cloudSetupToastId(environmentId) : null
const shown = Boolean(record) && notices.length > 0
// Re-rendering the same id updates the toast in place (installing state, a dismissed line).
useEffect(() => {
if (!toastId) {
return
}
if (!record || !shown) {
toast.dismiss(toastId)
return
}
cancelPendingDismiss(toastId)
toast.custom(
() => (
<CloudSetupNoticesView
record={record}
notices={notices}
installing={push.installing}
onInstall={() => record.repoUrl && push.startInstall(record.repoUrl)}
onRunSetup={(noticeId) => void runCloudSetupScript(workspaceId, record, noticeId)}
onDismiss={(noticeId) => dismissCloudSetupNotice(record.environmentId, noticeId)}
/>
),
{ id: toastId, duration: Infinity, unstyled: true, dismissible: false }
)
})
useEffect(
() => () => {
if (toastId) {
dismissSoon(toastId)
}
},
[toastId]
)
return null
}
// A remount (StrictMode, a re-keyed surface) re-shows the toast in the same tick. Sonner applies a
// dismiss a frame later, after that re-show, so dismiss only once nothing has claimed the id back.
const pendingDismiss = new Map<string, ReturnType<typeof setTimeout>>()
function dismissSoon(toastId: string): void {
cancelPendingDismiss(toastId)
pendingDismiss.set(
toastId,
setTimeout(() => {
pendingDismiss.delete(toastId)
toast.dismiss(toastId)
}, 0)
)
}
/** Bottom right, above the floating-terminal button: top right would cover the prompt's first row. */
export function CloudSetupNoticesDock({ workspaceId }: { workspaceId: string }): React.JSX.Element {
return (
<div
data-cloud-surface=""
className="pointer-events-none absolute right-3 bottom-14 z-30 flex flex-col items-end gap-2"
>
<CloudSetupNotices workspaceId={workspaceId} />
</div>
)
function cancelPendingDismiss(toastId: string): void {
const timer = pendingDismiss.get(toastId)
if (timer !== undefined) {
clearTimeout(timer)
pendingDismiss.delete(toastId)
}
}
export function cloudSetupToastId(environmentId: string): string {
return `cloud-setup:${environmentId}`
}
export function CloudSetupNoticesView({
@@ -219,7 +255,7 @@ export function CloudSetupNoticesView({
role="status"
aria-labelledby={labelId}
data-cloud-notice="setup"
className="pointer-events-auto w-[26rem] max-w-[calc(100%-1.5rem)] rounded-lg border border-border bg-card text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1"
className="w-[var(--width,356px)] max-w-full rounded-lg border border-border bg-card font-sans text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)]"
>
<h2 id={labelId} className="sr-only">
{t('orcaCloud.setupNotices.label', 'Workspace setup')}
@@ -105,17 +105,50 @@ describe('useWakeAttachHold', () => {
const { result, rerender } = hook(() => false, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
expect(result.current.wake?.phase).toBe('connecting')
// Reconnected as soon as main said ready.
expect(retry).toHaveBeenCalledTimes(1)
act(() => vi.advanceTimersByTime(PAST_CAP))
// The quiet retry: still Connecting…, no card yet.
expect(retry).toHaveBeenCalledTimes(1)
expect(retry).toHaveBeenCalledTimes(2)
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake?.phase).toBe('connecting')
act(() => vi.advanceTimersByTime(PAST_CAP))
expect(retry).toHaveBeenCalledTimes(1)
expect(retry).toHaveBeenCalledTimes(2)
expect(result.current.terminalStalled).toBe(true)
expect(result.current.wake?.phase).toBe('failed')
})
it('reconnects the pane in front as soon as main says ready, not at the cap', () => {
// A pane that sat through an app restart asleep has no path back of its own: the reconnect at
// ready is what brings it back, as fast as a normal wake.
let attached: boolean | null = false
const retry = vi.fn(() => {
attached = true
return true
})
const { result, rerender } = hook(() => attached, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
expect(retry).toHaveBeenCalledTimes(1)
expect(retry).toHaveBeenLastCalledWith('ws')
act(() => vi.advanceTimersByTime(WAKE_ATTACH_POLL_MS))
expect(result.current.wake).toBeUndefined()
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(retry).toHaveBeenCalledTimes(1)
expect(result.current.terminalStalled).toBe(false)
})
it('does not reconnect a pane that is attached at ready, or a wake that failed', () => {
let attached: boolean | null = true
const retry = vi.fn(() => true)
const { rerender } = hook(() => attached, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
attached = false
rerender({ wake: { ...waking, startedAt: T0 } })
rerender({ wake: { ...waking, startedAt: T0, phase: 'failed' } })
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(retry).not.toHaveBeenCalled()
})
it('Try again re-runs the attach (not a wake) and waits for the pane once more', () => {
let attached: boolean | null = false
const retry = vi.fn(() => true)
@@ -123,7 +156,10 @@ describe('useWakeAttachHold', () => {
rerender({ wake: { ...waking, phase: 'ready' } })
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(result.current.terminalStalled).toBe(true)
const before = retry.mock.calls.length
act(() => result.current.retry())
// Once: the button's own reconnect, not a second one from the hold restarting.
expect(retry).toHaveBeenCalledTimes(before + 1)
expect(retry).toHaveBeenLastCalledWith('ws')
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake?.phase).toBe('connecting')
@@ -144,7 +180,7 @@ describe('useWakeAttachHold', () => {
act(() => vi.advanceTimersByTime(WAKE_ATTACH_POLL_MS))
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake).toBeUndefined()
expect(retry).toHaveBeenCalledTimes(1)
expect(retry).toHaveBeenCalledTimes(2)
})
it('a restart with no wake in flight never shows the card', () => {
@@ -20,9 +20,17 @@ type Track = {
attempt: number
/** The pane never re-attached within the cap: shown as a failed card, not a dead pane. */
stalled: CloudWakeProgressEvent | undefined
/** Held by main's `ready` (not a Try again, which reconnects itself): reconnect the pane now. */
reconnectNow: boolean
}
const IDLE: Track = { last: undefined, held: undefined, attempt: 0, stalled: undefined }
const IDLE: Track = {
last: undefined,
held: undefined,
attempt: 0,
stalled: undefined,
reconnectNow: false
}
export type WakeAttachHold = {
/** What the overlay shows in place of the store's wake, if anything. */
@@ -77,7 +85,7 @@ export function useWakeAttachHold(
settled && isAttached(workspaceId) === false
? { ...track.last, phase: 'connecting' as const }
: undefined
setTrack({ ...IDLE, attempt: track.attempt + 1, held })
setTrack({ ...IDLE, attempt: track.attempt + 1, held, reconnectNow: held !== undefined })
}
// Release once the pane takes input; at the cap, reconnect it once quietly, then fail visibly.
@@ -85,10 +93,18 @@ export function useWakeAttachHold(
// wake) clears it on its own. The store dropping the settled wake doesn't cancel this.
const waiting = track.held !== undefined || track.stalled !== undefined
const attempt = track.attempt
const reconnectNow = track.reconnectNow
useEffect(() => {
if (!waiting) {
return
}
// The server is up, so reconnect the pane in front now rather than waiting on its own path
// back: a pane that sat through an app restart while asleep has none, and would otherwise only
// come back at the cap. A pane already reconnecting ignores this (the reconnect only acts on a
// pane that is idle or parked), and the quiet retry at the cap stays the safety net.
if (reconnectNow && isAttached(workspaceId) === false) {
retryPane(workspaceId)
}
// Only visible time counts toward the cap: a hidden window pauses this poll (and the pane's
// own re-attach), so time spent hidden must not turn a healthy wake into a stalled card.
let visibleMs = 0
@@ -139,7 +155,7 @@ export function useWakeAttachHold(
},
intervalMs: WAKE_ATTACH_POLL_MS
})
}, [waiting, attempt, workspaceId, isAttached, retryPane])
}, [waiting, attempt, reconnectNow, workspaceId, isAttached, retryPane])
const retry = useCallback(() => {
retryPane(workspaceId)
@@ -149,7 +165,8 @@ export function useWakeAttachHold(
...current,
attempt: current.attempt + 1,
held: { ...current.stalled, phase: 'connecting' },
stalled: undefined
stalled: undefined,
reconnectNow: false
}
: current
)
@@ -10,7 +10,6 @@ import { useTranslate, type Translate } from '@/i18n/use-translate'
import { useAppStore } from '@/store/index'
import { OrcaProfileSignOutConfirmDialog } from '../../../orca-profiles/OrcaProfileSignOutConfirmDialog'
import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress'
import { OrcaCloudSettingsLinks } from '../../orca-cloud/OrcaCloudSettingsLinks'
import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability'
function accountStatusCopy(
@@ -68,7 +67,6 @@ export function OrcaAccountSettingsPane(): React.JSX.Element {
const t = useTranslate()
const authStatus = useAppStore((state) => state.orcaProfileAuthStatus)
const signOut = useAppStore((state) => state.signOutCurrentOrcaProfile)
const openSettingsTarget = useAppStore((state) => state.openSettingsTarget)
const cloudAvailable = useOrcaCloudApiAvailable()
const [signOutOpen, setSignOutOpen] = useState(false)
const [signingOut, setSigningOut] = useState(false)
@@ -133,51 +131,54 @@ export function OrcaAccountSettingsPane(): React.JSX.Element {
{connected ? null : <OrcaSignInWaitNotice className="basis-full" />}
</div>
{connected && cloudAvailable ? (
<OrcaCloudSettingsLinks onOpen={(pane) => openSettingsTarget({ pane, repoId: null })} />
) : null}
<div className="space-y-4 border-t border-border/60 pt-5">
<SettingsGroupHeader
className="px-0"
title={t(
'auto.components.settings.orcaAccount.benefitsTitle',
'Included with your account'
)}
/>
<div className="space-y-5">
<div className="grid gap-5 md:grid-cols-2 md:gap-0 md:divide-x md:divide-border/60">
{/* JA-16: with Orca Cloud the page is identity + Sign out only; plan, team and agents have
their own entries in the Orca Cloud group right beside it. */}
{cloudAvailable ? null : (
<div className="space-y-4 border-t border-border/60 pt-5">
<SettingsGroupHeader
className="px-0"
title={t(
'auto.components.settings.orcaAccount.benefitsTitle',
'Included with your account'
)}
/>
<div className="space-y-5">
<div className="grid gap-5 md:grid-cols-2 md:gap-0 md:divide-x md:divide-border/60">
<AccountBenefit
icon={Files}
className="md:pr-6"
title={t(
'auto.components.settings.orcaAccount.artifactsTitle',
'Artifact sharing'
)}
description={t(
'auto.components.settings.orcaAccount.artifactsDescription',
'Publish HTML and Markdown files, then manage every shared link from Orca.'
)}
/>
<AccountBenefit
icon={Smartphone}
className="md:pl-6"
title={t('auto.components.settings.orcaAccount.relayTitle', 'Orca Relay')}
description={t(
'auto.components.settings.orcaAccount.relayDescription',
'Connect Orca Mobile to this desktop across cellular or any Wi-Fi.'
)}
/>
</div>
{/* Put the third benefit below at full width so it cannot squeeze the existing pair. */}
<AccountBenefit
icon={Files}
className="md:pr-6"
title={t('auto.components.settings.orcaAccount.artifactsTitle', 'Artifact sharing')}
icon={BookOpen}
className="border-t border-border/60 pt-5"
title={t('auto.components.settings.orcaAccount.skillsTitle', 'Skill sharing')}
description={t(
'auto.components.settings.orcaAccount.artifactsDescription',
'Publish HTML and Markdown files, then manage every shared link from Orca.'
)}
/>
<AccountBenefit
icon={Smartphone}
className="md:pl-6"
title={t('auto.components.settings.orcaAccount.relayTitle', 'Orca Relay')}
description={t(
'auto.components.settings.orcaAccount.relayDescription',
'Connect Orca Mobile to this desktop across cellular or any Wi-Fi.'
'auto.components.settings.orcaAccount.skillsDescription',
'Share one skill or a whole set behind an unlisted link, and install them on any machine you use.'
)}
/>
</div>
{/* Put the third benefit below at full width so it cannot squeeze the existing pair. */}
<AccountBenefit
icon={BookOpen}
className="border-t border-border/60 pt-5"
title={t('auto.components.settings.orcaAccount.skillsTitle', 'Skill sharing')}
description={t(
'auto.components.settings.orcaAccount.skillsDescription',
'Share one skill or a whole set behind an unlisted link, and install them on any machine you use.'
)}
/>
</div>
</div>
)}
</div>
<OrcaProfileSignOutConfirmDialog
@@ -274,7 +274,7 @@ function ActorLabel({
return mine ? (
<>{sentence}</>
) : (
<PersonSentence sentence={sentence} name={entry.actor.userName} id={personId} />
<PersonSentence sentence={sentence} name={entry.actor.userName} id={personId} idInTooltip />
)
}
@@ -27,6 +27,7 @@ import type { CloudLoadState } from './cloud-load-state'
import { CreateApiKeyDialog } from './CreateApiKeyDialog'
import { formatKeyPrefix } from './cloud-api-format'
import { PersonSentence } from './PersonName'
import { CLOUD_ROUTINES_UI_ENABLED } from '../../../../../shared/cloud-api/cloud-routines-ui'
import { CloudApiEmptyState, CloudApiSkeletonRows } from './cloud-api-parts'
import { KeyRow } from './ApiKeyRow'
@@ -192,10 +193,17 @@ export function CloudApiKeysView(props: CloudApiKeysViewProps): React.JSX.Elemen
<CloudApiEmptyState
icon={KeyRound}
title={t('auto.components.settings.cloudApi.keys.emptyTitle', 'No Orca API keys yet')}
description={t(
'auto.components.settings.cloudApi.keys.emptyBody',
'Create a key to start workspaces, message agents and run routines from scripts, CI or any MCP client.'
)}
description={
CLOUD_ROUTINES_UI_ENABLED
? t(
'auto.components.settings.cloudApi.keys.emptyBody',
'Create a key to start workspaces, message agents and run routines from scripts, CI or any MCP client.'
)
: t(
'auto.components.settings.cloudApi.keys.emptyBodyNoRoutines',
'Create a key to start workspaces and message agents from scripts, CI or any MCP client.'
)
}
action={createButton}
/>
) : (
@@ -0,0 +1,26 @@
// @vitest-environment happy-dom
import { cleanup, render } from '@testing-library/react'
import { afterEach, expect, it } from 'vitest'
import { PersonName, PersonSentence } from './PersonName'
afterEach(cleanup)
it('shows the display name only, never the raw id inline', () => {
const { container } = render(<PersonName name="Grace Hopper" id="u_grace" />)
expect(container.textContent).toBe('Grace Hopper')
expect(container.querySelector('[title]')).toBeNull()
})
it('says "Former member" when nobody can name the person', () => {
const { container } = render(<PersonName name=" " id="u_7f3k" />)
expect(container.textContent).toBe('Former member')
expect(container.innerHTML).not.toContain('u_7f3k')
})
it('keeps the id one hover away in the audit log only', () => {
const { container } = render(
<PersonSentence sentence="<person></person> via API key" name={null} id="u_7f3k" idInTooltip />
)
expect(container.textContent).toBe('Former member via API key')
expect(container.querySelector('[title]')?.getAttribute('title')).toBe('u_7f3k')
})
@@ -1,32 +1,43 @@
import { Trans } from 'react-i18next'
import { i18n } from '@/i18n/i18n'
import { i18n, translate } from '@/i18n/i18n'
import { useAppStore } from '@/store'
import { useOrgRoster } from '../../billing/team/use-org-roster'
/** The name the control plane sent, else the team roster's (the directory Home uses), else null. */
function useMemberName(name: string | null | undefined, id: string): string | null {
const orgId = useAppStore((s) => s.orcaProfileAuthStatus?.cloud?.activeOrgId ?? null)
const known = name?.trim() || null
// Only read the shared roster when the server could not name this person.
const roster = useOrgRoster(known ? null : orgId)
if (known) {
return known
}
if (roster.result?.status === 'ok') {
const member = roster.result.roster.members.find((m) => m.userId === id)
return member?.displayName?.trim() || member?.email || null
}
return null
}
/**
* A teammate as the control plane knows them: "Ada Lovelace · u_ada" (name, then the id as
* secondary text), or the id alone when no name is known. Never a vague "a teammate".
* A teammate as a display name only, never a raw id inline; "Former member" when nobody can
* name them. `idInTooltip` (audit log only) keeps the id one hover away for admins investigating.
*/
export function PersonName({
name,
id
id,
idInTooltip = false
}: {
name: string | null | undefined
id: string
idInTooltip?: boolean
}): React.JSX.Element {
const display = name?.trim()
if (!display) {
return (
<span className="font-mono text-[0.95em]" title={id}>
{id}
</span>
)
}
const display =
useMemberName(name, id) ??
translate('auto.components.settings.cloudApi.formerMember', 'Former member')
return (
<span title={`${display} · ${id}`}>
<span className="text-foreground">{display}</span>
<span className="text-muted-foreground">
{' · '}
<span className="font-mono text-[0.95em]">{id}</span>
</span>
<span className="text-foreground" title={idInTooltip ? id : undefined}>
{display}
</span>
)
}
@@ -38,17 +49,19 @@ export function PersonName({
export function PersonSentence({
sentence,
name,
id
id,
idInTooltip
}: {
sentence: string
name: string | null | undefined
id: string
idInTooltip?: boolean
}): React.JSX.Element {
return (
<Trans
i18n={i18n}
defaults={sentence}
components={{ person: <PersonName name={name} id={id} /> }}
components={{ person: <PersonName name={name} id={id} idInTooltip={idInTooltip} /> }}
/>
)
}
@@ -1,6 +1,7 @@
import { useTranslate, type Translate } from '@/i18n/use-translate'
import type { CloudApiScope } from '../../../../../shared/cloud-api/cloud-api-types'
import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls'
import { CLOUD_ROUTINES_UI_ENABLED } from '../../../../../shared/cloud-api/cloud-routines-ui'
export type ScopeLevel = 'none' | 'read' | 'write'
@@ -75,54 +76,58 @@ export function ScopeMatrix({
const adminOnly = t('auto.components.settings.cloudApi.matrix.adminOnly', 'Team admins only')
return (
<div className="grid gap-1 rounded-lg border border-border/70 p-2" role="group">
{SCOPE_RESOURCES.map((resource) => {
const labelId = `scope-matrix-${resource.id}`
const canRead = Boolean(resource.read && available.includes(resource.read))
const canWrite = Boolean(resource.write && available.includes(resource.write))
const locked = !canRead && !canWrite
return (
<div key={resource.id} className="flex items-center justify-between gap-3 px-1 py-1">
<span id={labelId} className="min-w-0 truncate text-sm">
{resourceLabel(resource.id, t)}
{locked ? (
<span className="ml-1.5 text-xs text-muted-foreground">· {adminOnly}</span>
) : null}
</span>
<SettingsSegmentedControl<ScopeLevel>
size="sm"
ariaLabelledBy={labelId}
value={levelOf(resource, scopes)}
onChange={(level) => onChange(withLevel(resource, scopes, level))}
options={[
{
value: 'none' as const,
label: t('auto.components.settings.cloudApi.matrix.none', 'None')
},
{
value: 'read' as const,
label: t('auto.components.settings.cloudApi.matrix.read', 'Read'),
disabled: !canRead,
tooltip: resource.read ? (canRead ? undefined : adminOnly) : undefined
},
{
value: 'write' as const,
label:
resource.id === 'messages'
? t('auto.components.settings.cloudApi.matrix.send', 'Send')
: t('auto.components.settings.cloudApi.matrix.write', 'Write'),
disabled: !canWrite
}
].filter((option) =>
option.value === 'read'
? Boolean(resource.read)
: option.value === 'write'
? Boolean(resource.write)
: true
)}
/>
</div>
)
})}
{/* Routines are parked (cloud-routines-ui.ts): their scopes stay in the API and in Full
access, but Custom doesn't offer a row for a feature the desktop no longer shows. */}
{SCOPE_RESOURCES.filter((r) => CLOUD_ROUTINES_UI_ENABLED || r.id !== 'routines').map(
(resource) => {
const labelId = `scope-matrix-${resource.id}`
const canRead = Boolean(resource.read && available.includes(resource.read))
const canWrite = Boolean(resource.write && available.includes(resource.write))
const locked = !canRead && !canWrite
return (
<div key={resource.id} className="flex items-center justify-between gap-3 px-1 py-1">
<span id={labelId} className="min-w-0 truncate text-sm">
{resourceLabel(resource.id, t)}
{locked ? (
<span className="ml-1.5 text-xs text-muted-foreground">· {adminOnly}</span>
) : null}
</span>
<SettingsSegmentedControl<ScopeLevel>
size="sm"
ariaLabelledBy={labelId}
value={levelOf(resource, scopes)}
onChange={(level) => onChange(withLevel(resource, scopes, level))}
options={[
{
value: 'none' as const,
label: t('auto.components.settings.cloudApi.matrix.none', 'None')
},
{
value: 'read' as const,
label: t('auto.components.settings.cloudApi.matrix.read', 'Read'),
disabled: !canRead,
tooltip: resource.read ? (canRead ? undefined : adminOnly) : undefined
},
{
value: 'write' as const,
label:
resource.id === 'messages'
? t('auto.components.settings.cloudApi.matrix.send', 'Send')
: t('auto.components.settings.cloudApi.matrix.write', 'Write'),
disabled: !canWrite
}
].filter((option) =>
option.value === 'read'
? Boolean(resource.read)
: option.value === 'write'
? Boolean(resource.write)
: true
)}
/>
</div>
)
}
)}
</div>
)
}
@@ -9,7 +9,6 @@ import { FIXTURE_NAMES, fixtureCloudSecretsApi } from '../cloud-secrets/cloud-se
import { CloudMcpSyncPanel } from '../runtime-environments/cloud-mcp/CloudMcpSyncPanel'
import { SettingsSection } from '../section-layout/SettingsSection'
import { OrcaCloudMcpServersView, type OrcaCloudMcpWorkspace } from './OrcaCloudMcpServersPane'
import { OrcaCloudSettingsLinks } from './OrcaCloudSettingsLinks'
import { OrcaCloudSignedOutNotice } from './OrcaCloudSettingsPanes'
const noop = (): void => {}
@@ -197,16 +196,6 @@ export const sessionExpired = defineFixture({
)
})
/** Settings › Orca account, signed in: the Orca Cloud panes are one click away. */
export const accountLinks = defineFixture({
width: 720,
render: () => (
<div className="bg-background p-6">
<OrcaCloudSettingsLinks onOpen={noop} />
</div>
)
})
/** Settings › Agent API keys header: desktop keys are not for Orca Cloud; link to Cloud secrets. */
export const agentApiKeysHeader = defineFixture({
width: 784,
@@ -1,54 +0,0 @@
import { Boxes, ChevronRight, CreditCard, LockKeyhole, Plug, Users } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup'
import { useTranslate } from '@/i18n/use-translate'
import type { SettingsNavTarget } from '@/lib/settings-navigation-types'
type OrcaCloudLink = { pane: SettingsNavTarget; icon: LucideIcon; label: string }
/** Settings › Orca account: the Orca Cloud panes live in their own group; this points at them. */
export function OrcaCloudSettingsLinks({
onOpen
}: {
onOpen: (pane: SettingsNavTarget) => void
}): React.JSX.Element {
const t = useTranslate()
const links: OrcaCloudLink[] = [
{
pane: 'cloud-billing',
icon: CreditCard,
label: t('auto.components.billing.title', 'Plan & billing')
},
{ pane: 'cloud-team', icon: Users, label: t('auto.components.billing.team.title', 'Team') },
{ pane: 'cloud-secrets', icon: LockKeyhole, label: t('cloudSecrets.title', 'Cloud secrets') },
{
pane: 'cloud-environments',
icon: Boxes,
label: t('settings.orcaCloud.environments.title', 'Cloud environments')
},
{ pane: 'cloud-mcp', icon: Plug, label: t('cloudMcpSync.title', 'MCP servers') }
]
return (
<nav
className="space-y-3 border-t border-border/60 pt-5"
aria-label={t('settings.groups.orcaCloud', 'Orca Cloud')}
>
<SettingsGroupHeader className="px-0" title={t('settings.groups.orcaCloud', 'Orca Cloud')} />
<ul className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border bg-card shadow-xs">
{links.map(({ pane, icon: Icon, label }) => (
<li key={pane}>
<button
type="button"
onClick={() => onOpen(pane)}
className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-solid focus-visible:outline-focus-ring"
>
<Icon aria-hidden className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{label}</span>
<ChevronRight aria-hidden className="size-4 text-muted-foreground" />
</button>
</li>
))}
</ul>
</nav>
)
}
@@ -4,6 +4,7 @@ import { SettingsSection } from '../section-layout/SettingsSection'
import { translate } from '@/i18n/i18n'
import type { Translate } from '@/i18n/use-translate'
import type { SettingsRenderContext } from './settings-render-context'
import { CLOUD_ROUTINES_UI_ENABLED } from '../../../../../shared/cloud-api/cloud-routines-ui'
// Orca Cloud programmatic access; only builds with a control plane (private/hosted) show these.
export function renderCloudApiSettingsSections(
@@ -29,19 +30,21 @@ export function renderCloudApiSettingsSections(
>
{view.isSectionMounted('cloud-api-keys') ? <CloudApiKeysPane /> : null}
</SettingsSection>
<SettingsSection
id="cloud-routines"
title={t('auto.components.settings.cloudRoutines.sectionTitle', 'Routines')}
badge="Beta"
description={t(
'auto.components.settings.cloudRoutines.sectionDescription',
'Agents that run in Orca Cloud on a schedule, on GitHub events or from a webhook.'
)}
searchEntries={navigation.getSectionSearchEntries('cloud-routines')}
bodyClassName="rounded-none border-0 bg-transparent p-0 shadow-none"
>
{view.isSectionMounted('cloud-routines') ? <CloudRoutinesPane /> : null}
</SettingsSection>
{CLOUD_ROUTINES_UI_ENABLED ? (
<SettingsSection
id="cloud-routines"
title={t('auto.components.settings.cloudRoutines.sectionTitle', 'Routines')}
badge="Beta"
description={t(
'auto.components.settings.cloudRoutines.sectionDescription',
'Agents that run in Orca Cloud on a schedule, on GitHub events or from a webhook.'
)}
searchEntries={navigation.getSectionSearchEntries('cloud-routines')}
bodyClassName="rounded-none border-0 bg-transparent p-0 shadow-none"
>
{view.isSectionMounted('cloud-routines') ? <CloudRoutinesPane /> : null}
</SettingsSection>
) : null}
</>
)
}
@@ -24,10 +24,7 @@ export function renderOrcaAccountSettingsSection(
title={t('auto.components.settings.orcaAccount.title', 'Orca account')}
description={
model.orcaCloudApiAvailable
? t(
'settings.orcaAccount.descriptionWithCloud',
'Sign-in, plan, team and Orca Cloud settings.'
)
? t('settings.orcaAccount.descriptionIdentity', 'The Orca account you’re signed in with.')
: t(
'auto.components.settings.orcaAccount.description',
'Share work instantly and reach your desktop from Orca Mobile wherever you are.'
@@ -27,6 +27,7 @@ import { useWindowBackdropActive } from '@/lib/window-backdrop'
import { useThemeBackgroundStore } from '@/store/appearance/theme-background'
import { EditorRevealFlash } from './EditorRevealFlash'
import { SplitPaneLanding } from './SplitPaneLanding'
import { CloudWorkspaceNumberChip } from '../cloud-workspaces/CloudWorkspaceNumberChip'
import { isSplitLandingGroup } from '@/store/slices/tabs/split-landing-groups'
const EditorPanel = lazy(() => import('../editor/EditorPanel'))
@@ -310,7 +311,10 @@ export default function TabGroupPanel({
className={actionChromeClassName}
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
{/* One Run button per workspace: in the focused split, or the only group. */}
{/* One W-number and Run button per workspace: in the focused split, or the only group. */}
{!hasSplitGroups || isFocused ? (
<CloudWorkspaceNumberChip worktreeId={worktreeId} />
) : null}
{!hasSplitGroups || isFocused ? <RunActionButton worktreeId={worktreeId} /> : null}
<TabBarQuickCommandsButton
worktreeId={worktreeId}
@@ -89,6 +89,7 @@ function ProfileBody({ userId }: { userId: string }): React.JSX.Element {
userId={userId}
name={name}
email={member?.email ?? null}
{...(member?.pictureUrl ? { pictureUrl: member.pictureUrl } : {})}
role={member?.role ?? null}
profile={profile}
error={error}
@@ -4,6 +4,9 @@ import { FIXTURE_NOW, workspace } from '../cloud-workspaces/cloud-workspaces.tes
import { TeammateProfileView, type TeammateProfileViewProps } from './TeammateProfileView'
const DAYS = 182
// Fixtures render offline: a self-contained stand-in for a provider profile picture.
const PICTURE =
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='%23f6c38f'/><stop offset='1' stop-color='%23c0713d'/></linearGradient></defs><rect width='64' height='64' fill='url(%23g)'/><circle cx='32' cy='26' r='12' fill='%23fff3e6'/><rect x='14' y='42' width='36' height='22' rx='11' fill='%23fff3e6'/></svg>"
/** A believable work pattern: weekdays busy, weekends quiet, a vacation gap. Deterministic. */
function levels(): number[] {
@@ -87,6 +90,16 @@ export const teammate = defineFixture({
)
})
/** A teammate with a provider profile picture (falls back to initials if it fails to load). */
export const withPicture = defineFixture({
width: 600,
render: () => (
<Frame>
<TeammateProfileView {...base} pictureUrl={PICTURE} />
</Frame>
)
})
/** Your own profile: amounts in the hover caption, private workspaces included, no Poke. */
export const self = defineFixture({
width: 600,
@@ -10,6 +10,7 @@ import { cn } from '@/lib/utils'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import type { OrcaOrgRole } from '../../../../shared/orca-profiles'
import type { TeammateProfile } from '../../../../shared/cloud-workspaces/team-presence-wire'
import { ProfilePicture } from '../billing/team/TeamAvatar'
import { roleLabel } from '../billing/team/team-roles'
import { dotState, statusLabel } from '../cloud-workspaces/CloudWorkspaceRow'
import {
@@ -33,6 +34,8 @@ export type TeammateProfileViewProps = {
/** Roster name, else the control plane's, else a short id. */
name: string
email: string | null
/** Profile picture from the roster (https only); initials when absent or it fails to load. */
pictureUrl?: string
role: OrcaOrgRole | null
profile: TeammateProfile | null
/** Set when the profile couldn't load; the header still shows from the roster. */
@@ -46,7 +49,15 @@ export type TeammateProfileViewProps = {
onTurnOnPokes: () => void
}
function LargeAvatar({ userId, name }: { userId: string; name: string }): React.JSX.Element {
function LargeAvatar({
userId,
name,
pictureUrl
}: {
userId: string
name: string
pictureUrl: string | undefined
}): React.JSX.Element {
// Same per-member hue as the small avatars on workspace rows, so a teammate keeps one color.
const hueStyle: React.CSSProperties & { '--avatar-hue': string } = {
'--avatar-hue': String(memberHue(userId))
@@ -56,12 +67,13 @@ function LargeAvatar({ userId, name }: { userId: string; name: string }): React.
aria-hidden
style={hueStyle}
className={cn(
'inline-flex size-12 shrink-0 select-none items-center justify-center rounded-full text-base font-medium',
'relative inline-flex size-12 shrink-0 select-none items-center justify-center overflow-hidden rounded-full text-base font-medium',
'bg-[hsl(var(--avatar-hue)_45%_88%)] text-[hsl(var(--avatar-hue)_45%_28%)]',
'dark:bg-[hsl(var(--avatar-hue)_30%_26%)] dark:text-[hsl(var(--avatar-hue)_55%_82%)]'
)}
>
{initials(name)}
<ProfilePicture url={pictureUrl} />
</span>
)
}
@@ -142,7 +154,7 @@ export function TeammateProfileView(props: TeammateProfileViewProps): React.JSX.
return (
<div className="flex flex-col gap-6" aria-busy={loading || undefined}>
<header className="flex items-center gap-4 pr-8">
<LargeAvatar userId={props.userId} name={props.name} />
<LargeAvatar userId={props.userId} name={props.name} pictureUrl={props.pictureUrl} />
<div className="min-w-0 flex-1">
<h2
className="flex min-w-0 items-center gap-2 text-base font-semibold outline-none"
@@ -21,6 +21,10 @@ import {
import type { Worktree } from '../../../../shared/worktree/types'
import { EMPTY_SORTED_WORKTREES } from './worktree-jump-palette-model'
import { buildWorktreeJumpPaletteDocumentIndex } from './worktree-jump-palette-document-index'
import {
cloudNumberForWorktree,
useCloudWorkspaceIdentities
} from '@/components/cloud-workspaces/cloud-workspace-identity'
import { buildWorktreeJumpPaletteWorktreeMaps } from './worktree-jump-palette-worktree-maps'
import type { WorktreeJumpPaletteWorktreesInput } from './worktree-jump-palette-worktrees-input'
@@ -216,6 +220,8 @@ export function useWorktreeJumpPaletteWorktrees({
}),
[workspaces, hostedReviewCache, prCache, repoByHostIdentity, settings]
)
// Cloud workspaces are searchable by number (W-123); the cache changes only when numbers do.
const cloudIdentities = useCloudWorkspaceIdentities()
const worktreeDocuments = useMemo(
() =>
buildWorktreeJumpPaletteDocumentIndex({
@@ -227,11 +233,13 @@ export function useWorktreeJumpPaletteWorktrees({
prCache,
issueCache,
workspacePortScan,
checksReviewByWorktree
checksReviewByWorktree,
cloudNumberForWorktree: (worktree) => cloudNumberForWorktree(worktree, cloudIdentities)
}),
[
workspaces,
checksReviewByWorktree,
cloudIdentities,
hostFilterActive,
hostOptions,
issueCache,
@@ -24,7 +24,8 @@ export function buildWorktreeJumpPaletteDocumentIndex({
prCache,
issueCache,
workspacePortScan,
checksReviewByWorktree
checksReviewByWorktree,
cloudNumberForWorktree
}: {
worktrees: readonly Worktree[]
repoMap: ReadonlyMap<string, Repo>
@@ -35,9 +36,16 @@ export function buildWorktreeJumpPaletteDocumentIndex({
issueCache: AppState['issueCache'] | null
workspacePortScan: WorkspacePortScanResult | null
checksReviewByWorktree: ReadonlyMap<Worktree, HostedReviewInfo | null>
/** W-123 for cloud workspaces (null for everything else). */
cloudNumberForWorktree?: (worktree: Worktree) => number | null
}): Map<string, PaletteDocument> {
const hostLabelByWorktreeId = new Map<string, string>()
const cloudNumberByWorktreeId = new Map<string, number>()
for (const worktree of worktrees) {
const cloudNumber = cloudNumberForWorktree?.(worktree)
if (cloudNumber) {
cloudNumberByWorktreeId.set(getPaletteWorktreeIdentity(worktree), cloudNumber)
}
const repo = resolvePaletteRepoForWorktree(worktree, repoMap, repoByHostIdentity)
const badge = getPaletteHostBadge(
getPaletteWorktreeExecutionHostId(worktree) ?? (repo && getRepoExecutionHostId(repo)),
@@ -57,7 +65,8 @@ export function buildWorktreeJumpPaletteDocumentIndex({
issueCache,
workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree,
hostLabelByWorktreeId
hostLabelByWorktreeId,
cloudNumberByWorktreeId
}
)
}
@@ -338,5 +338,7 @@ export function getPaletteSupportingTextLabel(
return t('worktreeJumpPalette.matchLabel.task', 'Task')
case 'automation':
return t('worktreeJumpPalette.matchLabel.automationItem', 'Automation')
case 'cloudWorkspace':
return t('worktreeJumpPalette.matchLabel.cloudWorkspace', 'Cloud workspace')
}
}

Some files were not shown because too many files have changed in this diff Show More