diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index 7a4c658d575..d4b98e106c7 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -7,6 +7,7 @@ // POST /v1/billing/portal -> { url } Stripe Customer Portal // POST /v1/billing/team-plans {orgIds} other teams' plan state ("Switch to "), 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) diff --git a/cloud/apps/billing/src/overage.ts b/cloud/apps/billing/src/overage.ts index 590e00f1d1f..13a24cb725d 100644 --- a/cloud/apps/billing/src/overage.ts +++ b/cloud/apps/billing/src/overage.ts @@ -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 { + 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') } diff --git a/cloud/apps/billing/src/store.ts b/cloud/apps/billing/src/store.ts index af9f27f66eb..a9c8af04233 100644 --- a/cloud/apps/billing/src/store.ts +++ b/cloud/apps/billing/src/store.ts @@ -220,6 +220,18 @@ export async function insertUsage(db: D1Database, usage: UsageInsert): Promise 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 { + 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 { const row = await db diff --git a/cloud/apps/billing/src/stripe.ts b/cloud/apps/billing/src/stripe.ts index 8d493a6fd58..30b89ef0b15 100644 --- a/cloud/apps/billing/src/stripe.ts +++ b/cloud/apps/billing/src/stripe.ts @@ -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). */ diff --git a/cloud/apps/billing/src/usage-history.ts b/cloud/apps/billing/src/usage-history.ts new file mode 100644 index 00000000000..55f4ac11436 --- /dev/null +++ b/cloud/apps/billing/src/usage-history.ts @@ -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 = { + 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( + key: K, + rows: Array<{ id: string | null; seconds: number }> +): UsageHistoryTop { + 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 { + 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 + } +} diff --git a/cloud/apps/billing/src/webhook.ts b/cloud/apps/billing/src/webhook.ts index e4373aecd8a..c2118c32d45 100644 --- a/cloud/apps/billing/src/webhook.ts +++ b/cloud/apps/billing/src/webhook.ts @@ -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 { diff --git a/cloud/apps/billing/test/overage-opt-out.test.ts b/cloud/apps/billing/test/overage-opt-out.test.ts new file mode 100644 index 00000000000..544550aad18 --- /dev/null +++ b/cloud/apps/billing/test/overage-opt-out.test.ts @@ -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 }) + }) +}) diff --git a/cloud/apps/billing/test/usage-history.test.ts b/cloud/apps/billing/test/usage-history.test.ts new file mode 100644 index 00000000000..3c7373d0dc8 --- /dev/null +++ b/cloud/apps/billing/test/usage-history.test.ts @@ -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>, 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 }) + }) +}) diff --git a/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql new file mode 100644 index 00000000000..329a96abb2d --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql @@ -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//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) +); diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 08ec6d476de..c0c9c9faa5a 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -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. */ diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 5edaae7c49a..80752e89649 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -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') { diff --git a/cloud/apps/sandbox-control/src/org-slugs.ts b/cloud/apps/sandbox-control/src/org-slugs.ts new file mode 100644 index 00000000000..dfbc9191883 --- /dev/null +++ b/cloud/apps/sandbox-control/src/org-slugs.ts @@ -0,0 +1,123 @@ +// Org URL slugs for workspace links (orca://cloud//W-123). +// GET /v1/team/org?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/). +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 { + 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 { + if (!isValidSlug(slug)) { + return null + } + const row = await db.prepare('SELECT account_id FROM org_slugs WHERE slug = ?').bind(slug).first() + 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 } +} diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index 14ec858457b..64a5c48b88a 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -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>, now: number ): Promise { - 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') diff --git a/cloud/apps/sandbox-control/src/workspace-prefs.ts b/cloud/apps/sandbox-control/src/workspace-prefs.ts new file mode 100644 index 00000000000..49fca99c3d0 --- /dev/null +++ b/cloud/apps/sandbox-control/src/workspace-prefs.ts @@ -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 + +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() + 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) +} diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 0e1480c8b29..28664ab1184 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -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=&c= +// GET /v1/team/links/resolve?w=&c= or ?org=&n=&c= // 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/[/c/] → 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/[/c/] or orca://cloud//W-[/c/] → 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() + } 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, 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}` } diff --git a/cloud/apps/sandbox-control/test/team-presence.test.ts b/cloud/apps/sandbox-control/test/team-presence.test.ts index c8e0c256ddd..8a47fe8e2f7 100644 --- a/cloud/apps/sandbox-control/test/team-presence.test.ts +++ b/cloud/apps/sandbox-control/test/team-presence.test.ts @@ -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) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts new file mode 100644 index 00000000000..270c1d2be83 --- /dev/null +++ b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts @@ -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 = {}) => { + 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) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 99cd7abebfc..881006ae296 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -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') }) diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index abfae50fd7f..d6960e64ae5 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -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", diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 494a66abf56..28090cb988c 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -230,6 +230,7 @@ export default function RootLayout() { + /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({ 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 + } + return ( + + {resolved.kind === 'loading' ? ( + + ) : ( + router.replace('/') }} + /> + )} + + ) +} diff --git a/mobile/src/cloud/CloudWorkspaceActions.tsx b/mobile/src/cloud/CloudWorkspaceActions.tsx index fd876698b39..1ff6df5822b 100644 --- a/mobile/src/cloud/CloudWorkspaceActions.tsx +++ b/mobile/src/cloud/CloudWorkspaceActions.tsx @@ -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 ( + + + } + 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)) + }} + /> + + + ) +} /** 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 ( <> + {running ? ( diff --git a/mobile/src/cloud/cloud-control-plane-client.ts b/mobile/src/cloud/cloud-control-plane-client.ts index 33043dc67d0..529e76670b7 100644 --- a/mobile/src/cloud/cloud-control-plane-client.ts +++ b/mobile/src/cloud/cloud-control-plane-client.ts @@ -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 = { 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 } } diff --git a/mobile/src/cloud/cloud-workspace-prefs.test.ts b/mobile/src/cloud/cloud-workspace-prefs.test.ts new file mode 100644 index 00000000000..3e835be9771 --- /dev/null +++ b/mobile/src/cloud/cloud-workspace-prefs.test.ts @@ -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 = { + 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) + }) +}) diff --git a/mobile/src/cloud/cloud-workspace-prefs.ts b/mobile/src/cloud/cloud-workspace-prefs.ts new file mode 100644 index 00000000000..fd2259d8e0f --- /dev/null +++ b/mobile/src/cloud/cloud-workspace-prefs.ts @@ -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//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 { + 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 { + 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 { + 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(key) + client.setQueryData(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 } +} diff --git a/mobile/src/home/MobileHomeCloudSection.tsx b/mobile/src/home/MobileHomeCloudSection.tsx index 66b154f6125..a6d73053710 100644 --- a/mobile/src/home/MobileHomeCloudSection.tsx +++ b/mobile/src/home/MobileHomeCloudSection.tsx @@ -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 } - 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: { ) : ( - workspaces.map((workspace) => ( + workspaces.map(({ workspace, pinned }) => ( props.onOpenWorkspace(workspace)} + onLongPress={() => togglePin(workspace, pinned)} /> @@ -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 ( { + if (event.nativeEvent.actionName === 'longpress') { + onLongPress() + } + }} style={({ pressed }) => [styles.row, pressed && styles.rowPressed]} onPress={onPress} + onLongPress={onLongPress} + delayLongPress={400} > @@ -204,13 +257,14 @@ function CloudWorkspaceRow({ {status} - {[detail, when] + {[number, detail, when] .filter(Boolean) .map((part) => ` · ${part}`) .join('')} + {pinned ? : null} diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index d3411f6ac91..584bf445524 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -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" } } } diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index 31cf315a419..9d717c1d38d 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -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), diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index 89d92d3fa96..c150019aa9a 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -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 { + 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, diff --git a/src/main/billing/billing-usage-client.test.ts b/src/main/billing/billing-usage-client.test.ts new file mode 100644 index 00000000000..342838d7cb7 --- /dev/null +++ b/src/main/billing/billing-usage-client.test.ts @@ -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, 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: '