Merge remote-tracking branch 'private/cloud/integration' into cloud/local-command

# Conflicts:
#	src/main/hosted-sandbox/hosted-sandbox-install.ts
#	src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts
#	src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsLinks.tsx
#	src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx
#	src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts
#	src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts
#	src/renderer/src/i18n/locales/en.json
#	src/renderer/src/lib/settings-navigation-types.ts
This commit is contained in:
Neil
2026-11-10 22:39:07 -08:00
173 changed files with 9919 additions and 868 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",
+4 -4
View File
@@ -14,7 +14,7 @@
14 src/main/agent-launch/trust/agent-trust-presets.ts
2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts
1 src/main/agent-launch/trust/execution-host-workspace-trust.ts
2 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts
1 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts
1 src/main/ai-vault-search/session-search-worker-client.ts
4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts
2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts
@@ -54,6 +54,7 @@
5 src/main/browser/cookies/sources/browser-cookie-source-profiles.ts
11 src/main/browser/cookies/staging/browser-session-cookie-staging.ts
1 src/main/browser/downloads/browser-download-destination.ts
2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts
2 src/main/browser/extensions/api-runtime/browser-extension-worker-shim-source.ts
8 src/main/browser/extensions/installation/browser-extension-install-store.ts
1 src/main/browser/extensions/installation/browser-extension-load-directory.ts
@@ -63,7 +64,6 @@
4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts
3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts
1 src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts
2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts
1 src/main/browser/identity/mode/browser-identity-mode-record.ts
2 src/main/browser/identity/mode/browser-identity-mode-store.ts
2 src/main/browser/network/egress/browser-route-egress-electron-launch.ts
@@ -117,7 +117,6 @@
1 src/main/codex-accounts/codex-login-auth-snapshot.ts
5 src/main/codex-accounts/codex-managed-home-lifecycle.ts
6 src/main/codex-accounts/codex-managed-home-path.ts
17 src/main/filesystem/atomic-file-publication.ts
1 src/main/codex-accounts/guest-codex-account-homes.ts
6 src/main/codex-accounts/host-codex-managed-home-ownership.ts
2 src/main/codex-accounts/legacy-shared-auth-migration.ts
@@ -247,6 +246,7 @@
7 src/main/emulator/serve-sim-execution.ts
17 src/main/emulator/serve-sim-runtime-materializer.ts
12 src/main/external-editors/external-editor-launch.ts
17 src/main/filesystem/atomic-file-publication.ts
9 src/main/filesystem/durable-file-write.ts
2 src/main/filesystem/rolling-file-backup.ts
2 src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry-path.ts
@@ -297,6 +297,7 @@
13 src/main/kimi/hook-service.ts
3 src/main/kiro/hook-service.ts
1 src/main/kiro/standalone-hooks.ts
3 src/main/lib/hidden-probe-cwd.ts
4 src/main/linear/linear-credential-paths.ts
3 src/main/linear/linear-legacy-viewer-store.ts
1 src/main/linear/linear-token-store.ts
@@ -465,7 +466,6 @@
1 src/main/qoder/workspace-trust.ts
4 src/main/rate-limits/providers/cursor/cursor-auth.ts
2 src/main/rate-limits/providers/grok/grok-auth.ts
3 src/main/lib/hidden-probe-cwd.ts
2 src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
1 src/main/rate-limits/providers/zcode/zcode-usage-credentials.ts
3 src/main/ripgrep/bundled-ripgrep-path.ts
+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"
}
}
}
@@ -0,0 +1,21 @@
import { createHash } from 'node:crypto'
export type AgentConfigDigestEntry = {
/** Relative path inside a skill folder, or `.` for a command file. */
path: string
executable: boolean
bytes: Buffer
}
/** Content identity of one item. Desktop and host compute it the same way, so either side can tell
* whether a sandbox copy is exactly what this computer sent. */
export function agentConfigDigest(entries: readonly AgentConfigDigestEntry[]): string {
const hash = createHash('sha256')
for (const entry of [...entries].sort((a, b) =>
a.path < b.path ? -1 : a.path > b.path ? 1 : 0
)) {
const body = createHash('sha256').update(entry.bytes).digest('hex')
hash.update(`${entry.path}\0${entry.executable ? 1 : 0}\0${body}\n`)
}
return hash.digest('hex')
}
@@ -0,0 +1,69 @@
import { homedir } from 'node:os'
import { join } from 'node:path'
import type {
AgentConfigItemKind,
AgentConfigItemScope
} from '../../shared/agent-config-sync/agent-config-sync-contract'
import { AGENT_CONFIG_FILE_KINDS } from '../../shared/agent-config-sync/agent-config-sync-contract'
export type AgentConfigHomes = {
/** Claude Code's config dir: $CLAUDE_CONFIG_DIR or ~/.claude. */
claudeDir: string
/** $CODEX_HOME or ~/.codex. */
codexDir: string
home: string
}
export function defaultAgentConfigHomes(env: NodeJS.ProcessEnv = process.env): AgentConfigHomes {
const home = homedir()
return {
claudeDir: env.CLAUDE_CONFIG_DIR?.trim() || join(home, '.claude'),
codexDir: env.CODEX_HOME?.trim() || join(home, '.codex'),
home
}
}
/** The folder that holds every item of a kind; null when the kind has no such scope. */
export function agentConfigRoot(
kind: AgentConfigItemKind,
scope: AgentConfigItemScope,
homes: AgentConfigHomes,
projectPath: string | null
): string | null {
if (scope === 'project') {
if (!projectPath) {
return null
}
switch (kind) {
case 'claude-skill':
return join(projectPath, '.claude', 'skills')
case 'claude-command':
return join(projectPath, '.claude', 'commands')
case 'agents-skill':
return join(projectPath, '.agents', 'skills')
// Codex reads prompts and its older skills folder from home only.
case 'codex-skill':
case 'codex-prompt':
return null
}
}
switch (kind) {
case 'claude-skill':
return join(homes.claudeDir, 'skills')
case 'claude-command':
return join(homes.claudeDir, 'commands')
case 'agents-skill':
return join(homes.home, '.agents', 'skills')
case 'codex-skill':
return join(homes.codexDir, 'skills')
case 'codex-prompt':
return join(homes.codexDir, 'prompts')
}
}
/** Where one item lives under its root: a folder for skills, `<name>.md` for commands. */
export function agentConfigItemPath(root: string, kind: AgentConfigItemKind, name: string): string {
return AGENT_CONFIG_FILE_KINDS.has(kind)
? join(root, ...`${name}.md`.split('/'))
: join(root, name)
}
@@ -0,0 +1,41 @@
/**
* Skills sometimes sit next to keys a script reads. Those files stay on this computer: names that
* hold credentials by convention, and text with a well-known key or token shape.
*/
const SECRET_FILE_NAMES = [
/^\.?env(\..*)?$/i,
/\.(pem|key|p12|pfx|jks|keystore|ppk|asc|gpg|kdbx|der|crt)$/i,
/^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
/^(credentials?|secrets?|tokens?|auth|service[-_]?account)([-_.].*)?\.(json|ya?ml|toml|txt|ini|env)$/i,
/^\.?(npmrc|netrc|pypirc|htpasswd|git-credentials)$/i,
/^client_secret.*\.json$/i
]
const SECRET_CONTENT = [
/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,
/\bAKIA[0-9A-Z]{16}\b/,
/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/,
/\bgithub_pat_[A-Za-z0-9_]{60,}\b/,
/\bglpat-[A-Za-z0-9_-]{20,}\b/,
/\bsk-ant-[A-Za-z0-9_-]{20,}\b/,
/\bsk-(?:proj-|live_|test_)?[A-Za-z0-9_-]{32,}\b/,
/\bxox[abposr]-[A-Za-z0-9-]{10,}\b/,
/\bAIza[0-9A-Za-z_-]{35}\b/,
/\bnpm_[A-Za-z0-9]{36}\b/,
/\b(?:rk|sk)_live_[A-Za-z0-9]{20,}\b/,
/\bvck_[A-Za-z0-9]{20,}\b/
]
export function isSecretFileName(name: string): boolean {
return SECRET_FILE_NAMES.some((pattern) => pattern.test(name))
}
/** Binary files are not scanned: the patterns are text shapes. */
export function hasSecretContent(bytes: Buffer): boolean {
if (bytes.subarray(0, 8000).includes(0)) {
return false
}
const text = bytes.toString('utf8')
return SECRET_CONTENT.some((pattern) => pattern.test(text))
}
@@ -0,0 +1,190 @@
import {
AGENT_CONFIG_LIMITS,
agentConfigItemKey,
type AgentConfigItemKind,
type AgentConfigItemPayload,
type AgentConfigItemRef,
type AgentConfigSyncPlanResult,
type AgentConfigSyncPutResult,
type AgentConfigSyncRow
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import type { AgentConfigDigestEntry } from '../agent-config-digest'
import type { LocalAgentConfigItem } from './local-agent-config-read'
export type DesiredAgentConfigItem = AgentConfigItemRef & {
key: string
files: AgentConfigDigestEntry[]
}
export type AgentConfigSyncPlan = {
rows: AgentConfigSyncRow[]
desired: DesiredAgentConfigItem[]
}
/** The other agent's kind an item converts to; the formats match (SKILL.md folders, Markdown prompts). */
function counterpartKind(item: LocalAgentConfigItem): AgentConfigItemKind | null {
switch (item.kind) {
case 'claude-skill':
return 'agents-skill'
case 'agents-skill':
case 'codex-skill':
return 'claude-skill'
case 'claude-command':
// Codex prompts are flat: a namespaced command has no Codex name.
return item.name.includes('/') ? null : 'codex-prompt'
case 'codex-prompt':
return 'claude-command'
}
}
/** Kinds that already give the other agent an item of that name. */
const NATIVE_FOR: Record<AgentConfigItemKind, AgentConfigItemKind[]> = {
'agents-skill': ['agents-skill', 'codex-skill'],
'codex-skill': ['agents-skill', 'codex-skill'],
'claude-skill': ['claude-skill'],
'claude-command': ['claude-command'],
'codex-prompt': ['codex-prompt']
}
function rowOf(item: LocalAgentConfigItem, key: string, included: boolean): AgentConfigSyncRow {
return {
key,
scope: item.scope,
kind: item.kind,
name: item.name,
bytes: item.bytes,
fileCount: item.fileCount,
withheldFiles: item.withheldFiles,
included,
state: 'pending'
}
}
/** What to send and how each local item shows, before the host answers. */
export function planAgentConfigSync(args: {
items: readonly LocalAgentConfigItem[]
excluded: ReadonlySet<string>
shareAcrossAgents: boolean
}): AgentConfigSyncPlan {
const rows: AgentConfigSyncRow[] = []
const candidates: { row: AgentConfigSyncRow; item: LocalAgentConfigItem }[] = []
const names = new Set(
args.items.filter((item) => item.scope === 'user').map((item) => `${item.kind}:${item.name}`)
)
const converted = new Set<string>()
for (const item of args.items) {
const key = agentConfigItemKey(item.scope, item.kind, item.name)
const included = !args.excluded.has(key)
const row = rowOf(item, key, included)
if (item.skipReason) {
rows.push({ ...row, state: 'skipped', skipReason: item.skipReason })
continue
}
if (!included) {
rows.push({ ...row, state: 'skipped', skipReason: 'turned-off' })
continue
}
rows.push(row)
candidates.push({ row, item })
const target = args.shareAcrossAgents && item.scope === 'user' ? counterpartKind(item) : null
if (
!target ||
NATIVE_FOR[target].some((kind) => names.has(`${kind}:${item.name}`)) ||
converted.has(`${target}:${item.name}`)
) {
continue
}
// One copy per name: .agents and the older .codex skills folder can both hold it.
converted.add(`${target}:${item.name}`)
const copy = { ...item, kind: target }
const copyRow: AgentConfigSyncRow = {
...rowOf(copy, agentConfigItemKey('user', target, item.name), true),
convertedFrom: key
}
rows.push(copyRow)
candidates.push({ row: copyRow, item: copy })
}
// Natives first, so a copy is what falls past the limit.
candidates.sort((a, b) => Number(!!a.row.convertedFrom) - Number(!!b.row.convertedFrom))
const desired: DesiredAgentConfigItem[] = []
let total = 0
for (const { row, item } of candidates) {
if (
desired.length >= AGENT_CONFIG_LIMITS.items ||
total + item.bytes > AGENT_CONFIG_LIMITS.totalBytes ||
!item.digest
) {
row.state = 'skipped'
row.skipReason = 'over-limit'
continue
}
total += item.bytes
desired.push({
key: row.key,
scope: item.scope,
kind: item.kind,
name: item.name,
digest: item.digest,
files: item.files
})
}
return { rows, desired }
}
/** Put calls that each stay under one item's byte budget (and so under the RPC frame). */
export function agentConfigPutBatches(
items: readonly DesiredAgentConfigItem[]
): AgentConfigItemPayload[][] {
const batches: AgentConfigItemPayload[][] = []
let current: AgentConfigItemPayload[] = []
let bytes = 0
for (const item of items) {
const size = item.files.reduce((sum, file) => sum + file.bytes.length, 0)
if (
current.length > 0 &&
(bytes + size > AGENT_CONFIG_LIMITS.itemBytes ||
current.length >= AGENT_CONFIG_LIMITS.putItems)
) {
batches.push(current)
current = []
bytes = 0
}
current.push({
scope: item.scope,
kind: item.kind,
name: item.name,
digest: item.digest,
files: item.files.map((file) => ({
path: file.path,
executable: file.executable,
base64: file.bytes.toString('base64')
}))
})
bytes += size
}
if (current.length > 0) {
batches.push(current)
}
return batches
}
const SYNCED_OUTCOMES: ReadonlySet<string> = new Set(['added', 'updated', 'unchanged'])
/** Rows after the host's plan and puts answered. */
export function applyAgentConfigSyncResults(
rows: readonly AgentConfigSyncRow[],
plan: AgentConfigSyncPlanResult,
put: AgentConfigSyncPutResult['items']
): AgentConfigSyncRow[] {
return rows.map((row) => {
if (row.state === 'skipped') {
return row
}
const outcome = put[row.key] ?? plan.items[row.key]
if (!outcome) {
return row
}
const synced = SYNCED_OUTCOMES.has(outcome)
return { ...row, state: synced ? 'synced' : 'skipped', outcome }
})
}
@@ -0,0 +1,84 @@
import { BrowserWindow, ipcMain } from 'electron'
import {
CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL,
CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL,
type CloudAgentConfigSyncPreferences
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { createCloudAgentConfigSync, type CloudAgentConfigSync } from './cloud-agent-config-sync'
let instance: CloudAgentConfigSync | null = null
function send(channel: string, payload: unknown): void {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, payload)
}
}
}
function environmentIdOf(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null
}
function preferencesOf(value: unknown): Partial<CloudAgentConfigSyncPreferences> {
if (!value || typeof value !== 'object') {
return {}
}
const raw = value as Record<string, unknown>
return {
...(typeof raw.autoSync === 'boolean' ? { autoSync: raw.autoSync } : {}),
...(typeof raw.shareAcrossAgents === 'boolean'
? { shareAcrossAgents: raw.shareAcrossAgents }
: {})
}
}
/** Orca Cloud builds only; other builds answer null so the renderer hides the pane. */
export function installCloudAgentConfigSync(userDataPath: string): CloudAgentConfigSync {
instance ??= createCloudAgentConfigSync({
userDataPath,
broadcast: (status) => send(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, status),
broadcastPreferences: (preferences) =>
send(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, preferences)
})
return instance
}
const CHANNELS = [
'cloudAgentConfigSync:getStatus',
'cloudAgentConfigSync:syncNow',
'cloudAgentConfigSync:getPreferences',
'cloudAgentConfigSync:setPreferences',
'cloudAgentConfigSync:setItemIncluded'
] as const
export function registerCloudAgentConfigSyncHandlers(): void {
for (const channel of CHANNELS) {
ipcMain.removeHandler(channel)
}
ipcMain.handle('cloudAgentConfigSync:getStatus', (_event, value: unknown) => {
const environmentId = environmentIdOf(value)
return environmentId && instance ? instance.getStatus(environmentId) : null
})
ipcMain.handle('cloudAgentConfigSync:syncNow', (_event, value: unknown) => {
const environmentId = environmentIdOf(value)
return environmentId && instance ? instance.sync(environmentId, 'manual') : null
})
ipcMain.handle('cloudAgentConfigSync:getPreferences', async () => {
if (!instance) {
return null
}
await instance.ready
return instance.getPreferences()
})
ipcMain.handle('cloudAgentConfigSync:setPreferences', (_event, value: unknown) =>
instance ? instance.setPreferences(preferencesOf(value)) : null
)
ipcMain.handle(
'cloudAgentConfigSync:setItemIncluded',
(_event, key: unknown, included: unknown) =>
instance && typeof key === 'string' && key.length <= 300 && typeof included === 'boolean'
? instance.setItemIncluded(key, included)
: null
)
}
@@ -0,0 +1,59 @@
import type {
AgentConfigSyncStatus,
CloudAgentConfigSyncPreferences
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { gitExecFileAsync } from '../../git/command-runner/git-exec-file'
export const MAX_EXCLUDED = 1024
// Off until the user turns it on: a cloud workspace can be shared with a team, and skills are
// the user's own prompts. One switch in Settings is the consent.
export const DEFAULT_PREFERENCES: CloudAgentConfigSyncPreferences = {
autoSync: false,
shareAcrossAgents: false,
excluded: []
}
export class RuntimeCallError extends Error {
constructor(
message: string,
readonly code: string | undefined
) {
super(message)
}
}
export function errorCode(error: unknown): AgentConfigSyncStatus['error'] {
const code =
typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : ''
if (code === 'method_not_found') {
return 'host-outdated'
}
return /unavailable|timeout|unreachable/.test(code) ? 'host-unreachable' : 'failed'
}
/** Repo-relative files git tracks under the project agent folders. */
export async function trackedAgentConfigPaths(repoPath: string): Promise<ReadonlySet<string>> {
const { stdout } = await gitExecFileAsync(
['ls-files', '-z', '--', '.claude/skills', '.claude/commands', '.agents/skills'],
{ cwd: repoPath, timeout: 10_000 }
)
return new Set(stdout.split('\0').filter(Boolean))
}
export function parsePreferences(text: string): CloudAgentConfigSyncPreferences {
const raw: unknown = JSON.parse(text)
if (!raw || typeof raw !== 'object') {
return { ...DEFAULT_PREFERENCES, excluded: [] }
}
return {
autoSync: 'autoSync' in raw && raw.autoSync === true,
shareAcrossAgents: 'shareAcrossAgents' in raw && raw.shareAcrossAgents === true,
excluded:
'excluded' in raw && Array.isArray(raw.excluded)
? raw.excluded
.filter((key): key is string => typeof key === 'string' && key.length <= 300)
.slice(0, MAX_EXCLUDED)
: []
}
}
@@ -0,0 +1,263 @@
import { execFileSync } from 'node:child_process'
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
AGENT_CONFIG_SYNC_PLAN_METHOD,
AGENT_CONFIG_SYNC_PUT_METHOD,
AgentConfigSyncPlanParams,
AgentConfigSyncPutParams,
type AgentConfigSyncStatus
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import type { AgentConfigHomes } from '../agent-config-roots'
import { planHostAgentConfigSync, putHostAgentConfig } from '../host/host-agent-config-sync'
import { createCloudAgentConfigSync } from './cloud-agent-config-sync'
import { readLocalAgentConfig } from './local-agent-config-read'
type FakeRuntime = {
runtimeEnvironmentId: string
recipe: { provider: string }
repoPath: string
status: string
}
const runtimes = vi.hoisted((): { list: FakeRuntime[] } => ({ list: [] }))
vi.mock('../../../shared/ephemeral-vm-runtime-store', () => ({
listEphemeralVmRuntimes: () => runtimes.list
}))
let dir: string
let local: AgentConfigHomes
let host: AgentConfigHomes
let hostProject: string
let localRepo: string
let calls: { method: string; params: unknown }[]
function put(path: string, text: string, mode?: number): void {
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, text)
if (mode) {
chmodSync(path, mode)
}
}
function homesUnder(root: string): AgentConfigHomes {
return { home: root, claudeDir: join(root, '.claude'), codexDir: join(root, '.codex') }
}
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'cloud-agent-config-'))
local = homesUnder(join(dir, 'mac'))
host = homesUnder(join(dir, 'vm'))
localRepo = join(dir, 'mac-repo')
hostProject = join(dir, 'vm-project')
mkdirSync(localRepo, { recursive: true })
mkdirSync(hostProject, { recursive: true })
execFileSync('git', ['init', '-q', hostProject])
calls = []
runtimes.list = [
{
runtimeEnvironmentId: 'env-1',
recipe: { provider: 'orca-cloud' },
repoPath: localRepo,
// Not running, so turning sync on doesn't start its own sync under each test.
status: 'stopped'
}
]
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
function create(patch: { outdated?: boolean } = {}) {
const statuses: AgentConfigSyncStatus[] = []
const hostDeps = { homes: host, projectPath: hostProject, ledgerDir: join(dir, 'vm-userdata') }
const sync = createCloudAgentConfigSync({
userDataPath: join(dir, 'mac-userdata'),
broadcast: (status) => statuses.push(status),
readLocal: (repoPath) =>
readLocalAgentConfig({ homes: local, repoPath, trackedPaths: async () => new Set() }),
// The wire schemas run here as they do in orcad, so the test also checks what crosses.
call: async (_environmentId, method, params) => {
calls.push({ method, params })
if (patch.outdated) {
throw Object.assign(new Error('nope'), { code: 'method_not_found' })
}
if (method === AGENT_CONFIG_SYNC_PLAN_METHOD) {
return planHostAgentConfigSync(AgentConfigSyncPlanParams.parse(params), hostDeps)
}
if (method === AGENT_CONFIG_SYNC_PUT_METHOD) {
return putHostAgentConfig(AgentConfigSyncPutParams.parse(params), hostDeps)
}
throw new Error(`unexpected ${method}`)
},
now: () => 1_000
})
mkdirSync(join(dir, 'mac-userdata'), { recursive: true })
return { sync, statuses }
}
const outcomes = (status: AgentConfigSyncStatus | null) =>
Object.fromEntries((status?.rows ?? []).map((row) => [row.key, row.outcome ?? row.skipReason]))
describe('cloud agent config sync, desktop to host', () => {
it('stays off on connect until the user turns it on, then copies skills and commands', async () => {
put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), '---\nname: deploy\n---\nShip.')
put(join(local.claudeDir, 'skills', 'deploy', 'run.sh'), '#!/bin/sh\n', 0o755)
put(join(local.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS')
const { sync } = create()
expect(await sync.sync('env-1', 'connect')).toBeNull()
expect(calls).toEqual([])
sync.setPreferences({ autoSync: true })
const status = await sync.sync('env-1', 'connect')
expect(status?.error).toBeNull()
expect(outcomes(status)).toEqual({
'user:claude-skill:deploy': 'added',
'user:claude-command:review': 'added'
})
expect(readFileSync(join(host.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'utf8')).toContain(
'Ship.'
)
expect(statSync(join(host.claudeDir, 'skills', 'deploy', 'run.sh')).mode & 0o111).not.toBe(0)
expect(readFileSync(join(host.claudeDir, 'commands', 'review.md'), 'utf8')).toBe(
'Review $ARGUMENTS'
)
})
it('sends nothing the host already has, updates its own copies and removes what was dropped', async () => {
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'one')
put(join(local.claudeDir, 'skills', 'b', 'SKILL.md'), 'bee')
const { sync } = create()
sync.setPreferences({ autoSync: true })
await sync.sync('env-1', 'manual')
calls = []
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
'user:claude-skill:a': 'unchanged',
'user:claude-skill:b': 'unchanged'
})
expect(calls.map((call) => call.method)).toEqual([AGENT_CONFIG_SYNC_PLAN_METHOD])
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'two')
rmSync(join(local.claudeDir, 'skills', 'b'), { recursive: true })
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
'user:claude-skill:a': 'updated'
})
expect(readFileSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'), 'utf8')).toBe('two')
expect(existsSync(join(host.claudeDir, 'skills', 'b'))).toBe(false)
})
it('never touches items made or edited in the sandbox', async () => {
put(join(local.claudeDir, 'skills', 'mine', 'SKILL.md'), 'from the mac')
put(join(local.claudeDir, 'skills', 'edited', 'SKILL.md'), 'from the mac')
put(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'made in the sandbox')
const { sync } = create()
sync.setPreferences({ autoSync: true })
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
'user:claude-skill:mine': 'kept-host',
'user:claude-skill:edited': 'added'
})
put(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'changed in the sandbox')
rmSync(join(local.claudeDir, 'skills', 'edited'), { recursive: true })
await sync.sync('env-1', 'manual')
expect(readFileSync(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'utf8')).toBe(
'made in the sandbox'
)
expect(readFileSync(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'utf8')).toBe(
'changed in the sandbox'
)
})
it('shares skills and commands across agents only when asked, keeping each agent’s own', async () => {
put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'claude deploy')
put(join(local.claudeDir, 'skills', 'both', 'SKILL.md'), 'claude both')
put(join(local.home, '.agents', 'skills', 'both', 'SKILL.md'), 'codex both')
put(join(local.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'codex lint')
put(join(local.claudeDir, 'commands', 'review.md'), 'review')
put(join(local.claudeDir, 'commands', 'ns', 'deep.md'), 'namespaced')
put(join(local.codexDir, 'prompts', 'fix.md'), 'fix')
const { sync } = create()
sync.setPreferences({ autoSync: true })
await sync.sync('env-1', 'manual')
expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false)
sync.setPreferences({ shareAcrossAgents: true })
const status = await sync.sync('env-1', 'manual')
const copies = status?.rows.filter((row) => row.convertedFrom).map((row) => row.key)
expect(copies?.sort()).toEqual([
'user:agents-skill:deploy',
'user:claude-command:fix',
'user:claude-skill:lint',
'user:codex-prompt:review'
])
expect(readFileSync(join(host.home, '.agents', 'skills', 'deploy', 'SKILL.md'), 'utf8')).toBe(
'claude deploy'
)
expect(readFileSync(join(host.home, '.agents', 'skills', 'both', 'SKILL.md'), 'utf8')).toBe(
'codex both'
)
expect(readFileSync(join(host.codexDir, 'prompts', 'review.md'), 'utf8')).toBe('review')
expect(readFileSync(join(host.claudeDir, 'commands', 'fix.md'), 'utf8')).toBe('fix')
expect(existsSync(join(host.codexDir, 'prompts', 'deep.md'))).toBe(false)
// Turning an original off takes its copy with it.
sync.setItemIncluded('user:claude-skill:deploy', false)
await sync.sync('env-1', 'manual')
expect(existsSync(join(host.claudeDir, 'skills', 'deploy'))).toBe(false)
expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false)
})
it('puts untracked project items in the workspace and keeps them out of its git status', async () => {
put(join(localRepo, '.claude', 'skills', 'proj', 'SKILL.md'), 'project skill')
const { sync } = create()
sync.setPreferences({ autoSync: true })
expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({
'project:claude-skill:proj': 'added'
})
expect(readFileSync(join(hostProject, '.claude', 'skills', 'proj', 'SKILL.md'), 'utf8')).toBe(
'project skill'
)
const exclude = readFileSync(join(hostProject, '.git', 'info', 'exclude'), 'utf8')
expect(exclude.split('\n')).toContain('/.claude/skills/proj/')
const porcelain = execFileSync('git', ['-C', hostProject, 'status', '--porcelain'], {
encoding: 'utf8'
})
expect(porcelain).toBe('')
})
it('says the sandbox is outdated when its Orca has no skill sync', async () => {
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x')
const { sync } = create({ outdated: true })
const status = await sync.sync('env-1', 'manual')
expect(status?.error).toBe('host-outdated')
expect(status?.rows.map((row) => row.state)).toEqual(['pending'])
})
it('syncs running workspaces as soon as sync is turned on', async () => {
put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x')
runtimes.list[0].status = 'running'
const { sync, statuses } = create()
sync.setPreferences({ autoSync: true })
await vi.waitFor(() =>
expect(statuses.some((status) => status.lastSyncedAt !== null)).toBe(true)
)
expect(existsSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'))).toBe(true)
})
it('answers null for workspaces that are not Orca Cloud', async () => {
const { sync } = create()
expect(await sync.getStatus('env-other')).toBeNull()
expect(await sync.sync('env-other', 'manual')).toBeNull()
})
})
@@ -0,0 +1,295 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
AGENT_CONFIG_SYNC_PLAN_METHOD,
AGENT_CONFIG_SYNC_PUT_METHOD,
AgentConfigSyncPlanResult,
AgentConfigSyncPutResult,
type AgentConfigSyncStatus,
type CloudAgentConfigSyncPreferences
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { listEphemeralVmRuntimes } from '../../../shared/ephemeral-vm-runtime-store'
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing'
import { defaultAgentConfigHomes } from '../agent-config-roots'
import {
agentConfigPutBatches,
applyAgentConfigSyncResults,
planAgentConfigSync
} from './agent-config-sync-plan'
import { readLocalAgentConfig, type LocalAgentConfigItem } from './local-agent-config-read'
import { readOrCreateSyncerId } from './syncer-id'
import {
DEFAULT_PREFERENCES,
MAX_EXCLUDED,
RuntimeCallError,
errorCode,
parsePreferences,
trackedAgentConfigPaths
} from './cloud-agent-config-sync-support'
const PLAN_TIMEOUT_MS = 30_000
const PUT_TIMEOUT_MS = 60_000
export type CloudAgentConfigSyncDeps = {
userDataPath: string
broadcast: (status: AgentConfigSyncStatus) => void
broadcastPreferences?: (preferences: CloudAgentConfigSyncPreferences) => void
readLocal?: (repoPath: string | null) => Promise<LocalAgentConfigItem[]>
call?: (
environmentId: string,
method: string,
params: unknown,
timeoutMs: number
) => Promise<unknown>
now?: () => number
}
export type CloudAgentConfigSync = {
isCloudEnvironment(environmentId: string): boolean
getStatus(environmentId: string): Promise<AgentConfigSyncStatus | null>
sync(environmentId: string, trigger: 'connect' | 'manual'): Promise<AgentConfigSyncStatus | null>
/** Settles once saved preferences are read; getPreferences answers defaults until then. */
ready: Promise<void>
getPreferences(): CloudAgentConfigSyncPreferences
setPreferences(next: Partial<CloudAgentConfigSyncPreferences>): CloudAgentConfigSyncPreferences
setItemIncluded(key: string, included: boolean): CloudAgentConfigSyncPreferences
}
/** Mirrors this computer's skills and slash commands into each Orca Cloud workspace. */
export function createCloudAgentConfigSync(deps: CloudAgentConfigSyncDeps): CloudAgentConfigSync {
const preferencesPath = join(deps.userDataPath, 'cloud-agent-config-sync.json')
const statuses = new Map<string, AgentConfigSyncStatus>()
const queues = new Map<string, Promise<unknown>>()
const now = deps.now ?? Date.now
const readLocal =
deps.readLocal ??
((repoPath) =>
readLocalAgentConfig({
homes: defaultAgentConfigHomes(),
repoPath,
trackedPaths: trackedAgentConfigPaths
}))
const call =
deps.call ??
(async (environmentId: string, method: string, params: unknown, timeoutMs: number) => {
const response = await callRuntimeEnvironment(
deps.userDataPath,
environmentId,
method,
params,
timeoutMs
)
if (response.ok) {
return response.result
}
throw new RuntimeCallError(response.error.message, response.error.code)
})
let preferences: CloudAgentConfigSyncPreferences | null = null
const ready = readFile(preferencesPath, 'utf8')
.then(parsePreferences)
.catch(() => null)
.then((loaded) => {
// A change saved while this read ran wins.
preferences ??= loaded ?? { ...DEFAULT_PREFERENCES, excluded: [] }
})
function getPreferences(): CloudAgentConfigSyncPreferences {
return preferences ?? { ...DEFAULT_PREFERENCES, excluded: [] }
}
function cloudRuntime(environmentId: string) {
return listEphemeralVmRuntimes(deps.userDataPath).find(
(runtime) =>
runtime.runtimeEnvironmentId === environmentId && runtime.recipe?.provider === 'orca-cloud'
)
}
async function plan(environmentId: string) {
const local = await readLocal(cloudRuntime(environmentId)?.repoPath ?? null)
const prefs = getPreferences()
return planAgentConfigSync({
items: local,
excluded: new Set(prefs.excluded),
shareAcrossAgents: prefs.shareAcrossAgents
})
}
function publish(status: AgentConfigSyncStatus): AgentConfigSyncStatus {
statuses.set(status.environmentId, status)
deps.broadcast(status)
return status
}
async function run(environmentId: string): Promise<AgentConfigSyncStatus> {
const previous = statuses.get(environmentId)
const planned = await plan(environmentId).catch(() => null)
if (!planned) {
return publish({
environmentId,
running: false,
lastSyncedAt: previous?.lastSyncedAt ?? null,
error: 'failed',
rows: previous?.rows ?? []
})
}
publish({
environmentId,
running: true,
lastSyncedAt: previous?.lastSyncedAt ?? null,
error: previous?.error ?? null,
rows: previous?.rows.length ? previous.rows : planned.rows
})
const syncer = await readOrCreateSyncerId(deps.userDataPath)
try {
const hostPlan = AgentConfigSyncPlanResult.parse(
await call(
environmentId,
AGENT_CONFIG_SYNC_PLAN_METHOD,
{
syncer,
items: planned.desired.map(({ scope, kind, name, digest }) => ({
scope,
kind,
name,
digest
}))
},
PLAN_TIMEOUT_MS
)
)
const needed = planned.desired.filter((item) => hostPlan.items[item.key] === 'needed')
const put: AgentConfigSyncPutResult['items'] = {}
for (const batch of agentConfigPutBatches(needed)) {
const answer = AgentConfigSyncPutResult.parse(
await call(
environmentId,
AGENT_CONFIG_SYNC_PUT_METHOD,
{ syncer, items: batch },
PUT_TIMEOUT_MS
)
)
Object.assign(put, answer.items)
}
const rows = applyAgentConfigSyncResults(planned.rows, hostPlan, put)
const synced = rows.filter((row) => row.state === 'synced').length
console.info(
`[cloud-agent-config-sync] ${environmentId}: ${synced} synced, ${needed.length} sent, ${hostPlan.removed} removed, ${rows.length - synced} not synced`
)
return publish({ environmentId, running: false, lastSyncedAt: now(), error: null, rows })
} catch (error) {
const code = errorCode(error)
console.warn(`[cloud-agent-config-sync] ${environmentId}: sync failed (${code})`)
return publish({
environmentId,
running: false,
lastSyncedAt: previous?.lastSyncedAt ?? null,
error: code,
rows: planned.rows
})
}
}
function enqueue(environmentId: string): Promise<AgentConfigSyncStatus> {
// One sync per workspace at a time; a click during an auto-sync runs after it.
const next = (queues.get(environmentId) ?? Promise.resolve())
.catch(() => {})
.then(() => run(environmentId))
queues.set(environmentId, next)
void next.finally(() => {
if (queues.get(environmentId) === next) {
queues.delete(environmentId)
}
})
return next
}
/** After a settings change, bring every workspace that already synced in line with it. */
function resyncSynced(): void {
for (const status of statuses.values()) {
if (status.lastSyncedAt !== null && cloudRuntime(status.environmentId)) {
void enqueue(status.environmentId).catch(() => {})
}
}
}
function setPreferences(
next: Partial<CloudAgentConfigSyncPreferences>
): CloudAgentConfigSyncPreferences {
const current = getPreferences()
const merged: CloudAgentConfigSyncPreferences = {
autoSync: next.autoSync ?? current.autoSync,
shareAcrossAgents: next.shareAcrossAgents ?? current.shareAcrossAgents,
excluded: [...new Set(next.excluded ?? current.excluded)].sort().slice(0, MAX_EXCLUDED)
}
writeFileAtomically(preferencesPath, `${JSON.stringify(merged, null, 2)}\n`)
preferences = merged
deps.broadcastPreferences?.(merged)
return merged
}
return {
ready,
isCloudEnvironment: (environmentId) => cloudRuntime(environmentId) !== undefined,
async getStatus(environmentId) {
await ready
if (!cloudRuntime(environmentId)) {
return null
}
const known = statuses.get(environmentId)
if (known) {
return known
}
// Before any sync: what would go, read from this computer only.
const planned = await plan(environmentId).catch(() => null)
return {
environmentId,
running: false,
lastSyncedAt: null,
error: planned ? null : 'failed',
rows: planned?.rows ?? []
}
},
async sync(environmentId, trigger) {
await ready
if (!cloudRuntime(environmentId)) {
return null
}
if (trigger === 'connect' && !getPreferences().autoSync) {
return statuses.get(environmentId) ?? null
}
return enqueue(environmentId)
},
getPreferences,
setPreferences(next) {
const before = getPreferences()
const merged = setPreferences(next)
// Turning sync on reaches the running workspaces now, not at their next wake.
if (merged.autoSync && !before.autoSync) {
for (const runtime of listEphemeralVmRuntimes(deps.userDataPath)) {
if (
runtime.recipe?.provider === 'orca-cloud' &&
runtime.status === 'running' &&
runtime.runtimeEnvironmentId
) {
void enqueue(runtime.runtimeEnvironmentId).catch(() => {})
}
}
} else if (merged.shareAcrossAgents !== before.shareAcrossAgents) {
resyncSynced()
}
return merged
},
setItemIncluded(key, included) {
const excluded = new Set(getPreferences().excluded)
if (included) {
excluded.delete(key)
} else {
excluded.add(key)
}
const merged = setPreferences({ excluded: [...excluded] })
resyncSynced()
return merged
}
}
}
@@ -0,0 +1,137 @@
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { AgentConfigHomes } from '../agent-config-roots'
import { readLocalAgentConfig } from './local-agent-config-read'
let dir: string
let homes: AgentConfigHomes
function put(path: string, text: string | Buffer, mode?: number): void {
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, text)
if (mode) {
chmodSync(path, mode)
}
}
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'agent-config-read-'))
homes = {
home: join(dir, 'home'),
claudeDir: join(dir, 'home', '.claude'),
codexDir: join(dir, 'home', '.codex')
}
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
const read = (repoPath: string | null = null, tracked: string[] | null = []) =>
readLocalAgentConfig({
homes,
repoPath,
trackedPaths: async () => (tracked ? new Set(tracked) : null)
})
describe('readLocalAgentConfig', () => {
it('reads skills with their files and keeps likely secrets on this computer', async () => {
const skill = join(homes.claudeDir, 'skills', 'deploy')
put(join(skill, 'SKILL.md'), '---\nname: deploy\n---\nShip it.')
put(join(skill, 'scripts', 'run.sh'), '#!/bin/sh\necho hi\n', 0o755)
put(join(skill, 'service-account.json'), '{}')
put(join(skill, 'notes.txt'), 'token: ghp_0123456789abcdefghijABCDEFGHIJ0123456789')
put(join(skill, '.env'), 'X=1')
put(join(skill, 'node_modules', 'x', 'index.js'), 'x')
// Not a skill: no SKILL.md.
put(join(homes.claudeDir, 'skills', 'synced', 'blob.bin'), 'x')
// A link out of the skill folder is not followed.
put(join(dir, 'outside.txt'), 'outside')
symlinkSync(join(dir, 'outside.txt'), join(skill, 'link.txt'))
const items = await read()
expect(items).toHaveLength(1)
const [item] = items
expect(item).toMatchObject({
scope: 'user',
kind: 'claude-skill',
name: 'deploy',
withheldFiles: 2
})
expect(item.skipReason).toBeUndefined()
expect(item.files.map((file) => [file.path, file.executable])).toEqual([
['SKILL.md', false],
['scripts/run.sh', true]
])
expect(item.digest).toMatch(/^[a-f0-9]{64}$/)
})
it('skips a skill whose SKILL.md holds a key, and one that is too large', async () => {
put(
join(homes.claudeDir, 'skills', 'leaky', 'SKILL.md'),
'Use sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789'
)
put(join(homes.claudeDir, 'skills', 'huge', 'SKILL.md'), 'x')
put(join(homes.claudeDir, 'skills', 'huge', 'data.bin'), Buffer.alloc(300 * 1024))
const items = await read()
expect(Object.fromEntries(items.map((item) => [item.name, item.skipReason]))).toEqual({
leaky: 'secret',
huge: 'too-large'
})
expect(items.every((item) => item.files.length === 0)).toBe(true)
})
it('reads namespaced Claude commands, flat Codex prompts, and both Codex skill folders', async () => {
put(join(homes.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS')
put(join(homes.claudeDir, 'commands', 'frontend', 'component.md'), 'Make a component')
put(join(homes.claudeDir, 'commands', 'README.txt'), 'not a command')
put(join(homes.codexDir, 'prompts', 'fix.md'), 'Fix it')
put(join(homes.codexDir, 'prompts', 'nested', 'ignored.md'), 'Codex prompts are flat')
put(join(homes.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'Lint')
put(join(homes.codexDir, 'skills', '.system', 'builtin', 'SKILL.md'), 'Codex own')
put(join(homes.codexDir, 'skills', 'legacy', 'SKILL.md'), 'Old home')
const items = await read()
expect(items.map((item) => `${item.kind}:${item.name}`).sort()).toEqual([
'agents-skill:lint',
'claude-command:frontend/component',
'claude-command:review',
'codex-prompt:fix',
'codex-skill:legacy'
])
const review = items.find((item) => item.name === 'review')
expect(review?.files).toEqual([
{ path: '.', executable: false, bytes: Buffer.from('Review $ARGUMENTS') }
])
})
it('sends project items git does not track, and marks committed ones as already in the repo', async () => {
const repo = join(dir, 'repo')
put(join(repo, '.claude', 'skills', 'committed', 'SKILL.md'), 'in git')
put(join(repo, '.claude', 'skills', 'local-only', 'SKILL.md'), 'not in git')
put(join(repo, '.claude', 'commands', 'ship.md'), 'in git')
put(join(repo, '.claude', 'commands', 'mine.md'), 'not in git')
const items = await read(repo, [
'.claude/skills/committed/SKILL.md',
'.claude/commands/ship.md'
])
expect(
Object.fromEntries(
items.map((item) => [`${item.scope}:${item.name}`, item.skipReason ?? 'send'])
)
).toEqual({
'project:committed': 'in-repo',
'project:local-only': 'send',
'project:ship': 'in-repo',
'project:mine': 'send'
})
})
it('treats project items as committed when git cannot answer', async () => {
const repo = join(dir, 'repo')
put(join(repo, '.claude', 'skills', 'a', 'SKILL.md'), 'x')
const items = await read(repo, null)
expect(items.map((item) => item.skipReason)).toEqual(['in-repo'])
})
})
@@ -0,0 +1,314 @@
import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import {
AGENT_CONFIG_COMMAND_NAME,
AGENT_CONFIG_FILE_PATH,
AGENT_CONFIG_LIMITS,
AGENT_CONFIG_PROJECT_KINDS,
AGENT_CONFIG_SELF_PATH,
AGENT_CONFIG_SKILL_NAME,
AgentConfigItemKind,
isSkillKind,
type AgentConfigItemScope,
type AgentConfigSkipReason
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest'
import { agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots'
import { hasSecretContent, isSecretFileName } from './agent-config-secret-scan'
export type LocalAgentConfigItem = {
scope: AgentConfigItemScope
kind: AgentConfigItemKind
name: string
/** Empty when skipped. */
files: AgentConfigDigestEntry[]
fileCount: number
bytes: number
withheldFiles: number
digest: string | null
skipReason?: Extract<AgentConfigSkipReason, 'in-repo' | 'too-large' | 'secret' | 'invalid'>
}
export type LocalAgentConfigReadDeps = {
homes: AgentConfigHomes
/** The workspace's checkout on this computer, for project items. */
repoPath: string | null
/** Repo-relative paths git tracks under the project agent folders; null when git can't say. */
trackedPaths: (repoPath: string) => Promise<ReadonlySet<string> | null>
}
/** Folders a skill never needs in the sandbox. */
const SKIPPED_DIRS = new Set(['node_modules', '__pycache__', 'venv'])
const MAX_DEPTH = 8
const SKILL_FILE = 'SKILL.md'
type Walked =
| { ok: true; files: AgentConfigDigestEntry[]; withheld: number; bytes: number }
| { ok: false; reason: 'too-large' | 'secret' | 'invalid' }
async function isExecutable(path: string): Promise<boolean> {
try {
return ((await stat(path)).mode & 0o111) !== 0
} catch {
return false
}
}
/** One file's verdict: kept, kept back as a likely secret, or too big for any skill. */
async function readItemFile(
path: string,
name: string
): Promise<'too-large' | 'withheld' | { bytes: Buffer; executable: boolean }> {
const info = await stat(path)
if (info.size > AGENT_CONFIG_LIMITS.fileBytes) {
return 'too-large'
}
if (isSecretFileName(name)) {
return 'withheld'
}
const bytes = await readFile(path)
if (hasSecretContent(bytes)) {
return 'withheld'
}
return { bytes, executable: await isExecutable(path) }
}
/** Every regular file in a skill folder; symlinks only when they stay inside it. */
async function walkSkill(dir: string): Promise<Walked> {
const root = await realpath(dir)
const files: AgentConfigDigestEntry[] = []
let withheld = 0
let bytes = 0
const visit = async (current: string, depth: number): Promise<Walked | null> => {
const entries = await readdir(current, { withFileTypes: true })
entries.sort((a, b) => (a.name < b.name ? -1 : 1))
for (const entry of entries) {
if (entry.name.startsWith('.') || SKIPPED_DIRS.has(entry.name)) {
continue
}
const path = join(current, entry.name)
let resolved = path
if (entry.isSymbolicLink()) {
try {
resolved = await realpath(path)
} catch {
continue
}
if (resolved !== root && !resolved.startsWith(root + sep)) {
continue
}
}
const info = await stat(resolved).catch(() => null)
if (!info) {
continue
}
const rel = relative(dir, path).split(sep).join('/')
if (info.isDirectory()) {
if (depth >= MAX_DEPTH) {
continue
}
const nested = await visit(path, depth + 1)
if (nested) {
return nested
}
continue
}
if (!info.isFile()) {
continue
}
if (!AGENT_CONFIG_FILE_PATH.test(rel)) {
return { ok: false, reason: 'invalid' }
}
const read = await readItemFile(resolved, entry.name)
if (read === 'too-large') {
return { ok: false, reason: 'too-large' }
}
if (read === 'withheld') {
if (rel === SKILL_FILE) {
return { ok: false, reason: 'secret' }
}
withheld += 1
continue
}
bytes += read.bytes.length
files.push({ path: rel, executable: read.executable, bytes: read.bytes })
if (
files.length > AGENT_CONFIG_LIMITS.filesPerItem ||
bytes > AGENT_CONFIG_LIMITS.itemBytes
) {
return { ok: false, reason: 'too-large' }
}
}
return null
}
const failed = await visit(dir, 0)
return failed ?? { ok: true, files, withheld, bytes }
}
async function isDirectory(path: string): Promise<boolean> {
return (await stat(path).catch(() => null))?.isDirectory() === true
}
async function isFile(path: string): Promise<boolean> {
return (await stat(path).catch(() => null))?.isFile() === true
}
async function readSkills(
root: string,
kind: AgentConfigItemKind,
scope: AgentConfigItemScope
): Promise<LocalAgentConfigItem[]> {
const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
const items: LocalAgentConfigItem[] = []
for (const entry of entries) {
const dir = join(root, entry.name)
// Hidden folders hold tool state (Codex's .system skills, trash), not the user's skills.
if (entry.name.startsWith('.') || !(await isDirectory(dir))) {
continue
}
if (!(await isFile(join(dir, SKILL_FILE)))) {
continue
}
const base = { scope, kind, name: entry.name, withheldFiles: 0 }
if (!AGENT_CONFIG_SKILL_NAME.test(entry.name)) {
items.push({
...base,
files: [],
fileCount: 0,
bytes: 0,
digest: null,
skipReason: 'invalid'
})
continue
}
const walked = await walkSkill(dir).catch((): Walked => ({ ok: false, reason: 'invalid' }))
if (!walked.ok) {
items.push({
...base,
files: [],
fileCount: 0,
bytes: 0,
digest: null,
skipReason: walked.reason
})
continue
}
items.push({
...base,
files: walked.files,
fileCount: walked.files.length,
bytes: walked.bytes,
withheldFiles: walked.withheld,
digest: agentConfigDigest(walked.files)
})
}
return items
}
/** Markdown commands, namespaced by folder (Claude) or flat (Codex prompts). */
async function readCommands(
root: string,
kind: AgentConfigItemKind,
scope: AgentConfigItemScope
): Promise<LocalAgentConfigItem[]> {
const maxDepth = kind === 'codex-prompt' ? 0 : 2
const items: LocalAgentConfigItem[] = []
const visit = async (dir: string, depth: number): Promise<void> => {
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
for (const entry of entries) {
if (entry.name.startsWith('.')) {
continue
}
const path = join(dir, entry.name)
const info = await stat(path).catch(() => null)
if (info?.isDirectory()) {
if (depth < maxDepth) {
await visit(path, depth + 1)
}
continue
}
if (!info?.isFile() || !entry.name.endsWith('.md')) {
continue
}
const name = relative(root, path).split(sep).join('/').slice(0, -'.md'.length)
const base = { scope, kind, name, withheldFiles: 0, fileCount: 1 }
const skipped = (
skipReason: NonNullable<LocalAgentConfigItem['skipReason']>
): LocalAgentConfigItem => ({
...base,
files: [],
bytes: info.size,
digest: null,
skipReason
})
if (!AGENT_CONFIG_COMMAND_NAME.test(name)) {
items.push(skipped('invalid'))
continue
}
const read = await readItemFile(path, entry.name).catch(() => 'invalid' as const)
if (read === 'too-large' || read === 'invalid') {
items.push(skipped(read))
continue
}
if (read === 'withheld') {
items.push(skipped('secret'))
continue
}
const files = [
{ path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: read.bytes } // commands are never run
]
items.push({ ...base, files, bytes: read.bytes.length, digest: agentConfigDigest(files) })
}
}
await visit(root, 0)
return items
}
/** Repo-relative path of an item, as `git ls-files` prints it. */
function repoRelative(repoPath: string, root: string, kind: AgentConfigItemKind, name: string) {
const rel = relative(repoPath, root).split(sep).join('/')
return isSkillKind(kind) ? `${rel}/${name}/` : `${rel}/${name}.md`
}
/** This computer's Claude Code and Codex skills and commands, user scope and the workspace's project. */
export async function readLocalAgentConfig(
deps: LocalAgentConfigReadDeps
): Promise<LocalAgentConfigItem[]> {
const items: LocalAgentConfigItem[] = []
for (const kind of AgentConfigItemKind.options) {
const root = agentConfigRoot(kind, 'user', deps.homes, null)
if (root) {
items.push(...(await (isSkillKind(kind) ? readSkills : readCommands)(root, kind, 'user')))
}
}
const repoPath = deps.repoPath
if (repoPath) {
const tracked = await deps.trackedPaths(repoPath).catch(() => null)
for (const kind of AgentConfigItemKind.options) {
const root = AGENT_CONFIG_PROJECT_KINDS.has(kind)
? agentConfigRoot(kind, 'project', deps.homes, repoPath)
: null
// A project folder that is a link elsewhere is not the repo's; leave it alone.
if (!root || (await lstat(root).catch(() => null))?.isSymbolicLink()) {
continue
}
for (const item of await (isSkillKind(kind) ? readSkills : readCommands)(
root,
kind,
'project'
)) {
const path = repoRelative(repoPath, root, kind, item.name)
// Committed items reach the sandbox with the clone; unknown means assume committed.
const inRepo =
tracked === null ||
[...tracked].some((file) => (isSkillKind(kind) ? file.startsWith(path) : file === path))
items.push(
inRepo && !item.skipReason
? { ...item, files: [], digest: null, skipReason: 'in-repo' }
: item
)
}
}
}
return items
}
@@ -0,0 +1,37 @@
import { randomBytes } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
// One read per profile; concurrent first syncs share it, so they can't mint two ids.
const cache = new Map<string, Promise<string>>()
async function load(userDataPath: string): Promise<string> {
const path = join(userDataPath, 'mcp-sync-syncer-id')
try {
const stored = (await readFile(path, 'utf8')).trim()
if (/^[a-f0-9]{16}$/.test(stored)) {
return stored
}
} catch {
// First sync from this computer.
}
const id = randomBytes(8).toString('hex')
try {
writeFileAtomically(path, `${id}\n`)
} catch {
// Unwritable profile: this run still syncs as itself; the next launch gets a new id.
}
return id
}
/** This computer's stable sync identity (random, not a device fingerprint). The host keeps one
* ledger per syncer, so two computers syncing one sandbox never remove each other's items. */
export function readOrCreateSyncerId(userDataPath: string): Promise<string> {
let id = cache.get(userDataPath)
if (!id) {
id = load(userDataPath)
cache.set(userDataPath, id)
}
return id
}
@@ -0,0 +1,74 @@
import { runProcess } from '@orca/process-host'
import { appendFile, mkdir, readFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
/** What this host last wrote for one syncing computer: item key -> digest. Never contents. */
export type Ledger = { version: 1; items: Record<string, string> }
export function ledgerPath(ledgerDir: string, syncer: string): string {
return join(ledgerDir, `agent-config-sync-ledger-${syncer}.json`)
}
export async function readLedger(path: string): Promise<Ledger> {
try {
const parsed: unknown = JSON.parse(await readFile(path, 'utf8'))
const items =
parsed && typeof parsed === 'object' && 'items' in parsed ? parsed.items : undefined
const clean: Record<string, string> = {}
if (items && typeof items === 'object') {
for (const [key, value] of Object.entries(items)) {
if (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)) {
clean[key] = value
}
}
}
return { version: 1, items: clean }
} catch {
return { version: 1, items: {} }
}
}
export async function writeLedger(path: string, ledger: Ledger): Promise<void> {
await mkdir(dirname(path), { recursive: true })
writeFileAtomically(path, `${JSON.stringify(ledger, null, 2)}\n`, { mode: 0o600 })
}
/** Keeps a synced project item out of the sandbox's git status (local exclude, never committed). */
export async function excludeFromGit(
projectPath: string,
dest: string,
isDir: boolean
): Promise<void> {
try {
const { code, stdout } = await runProcess({
program: 'git',
args: [
'-C',
projectPath,
'rev-parse',
'--path-format=absolute',
'--git-path',
'info/exclude'
],
timeoutMs: 5_000
})
if (code !== 0) {
return
}
const excludePath = stdout.trim()
if (!excludePath) {
return
}
const rel = dest.slice(projectPath.length).split('\\').join('/')
const line = `${rel.startsWith('/') ? rel : `/${rel}`}${isDir ? '/' : ''}`
const current = await readFile(excludePath, 'utf8').catch(() => '')
if (current.split('\n').includes(line)) {
return
}
await mkdir(dirname(excludePath), { recursive: true })
await appendFile(excludePath, `${current && !current.endsWith('\n') ? '\n' : ''}${line}\n`)
} catch {
// Not a git checkout here; the item still works, it just shows as untracked.
}
}
@@ -0,0 +1,143 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
AgentConfigSyncPlanParams,
AgentConfigSyncPutParams
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { agentConfigDigest } from '../agent-config-digest'
import {
planHostAgentConfigSync,
putHostAgentConfig,
type HostAgentConfigSyncDeps
} from './host-agent-config-sync'
let dir: string
let deps: HostAgentConfigSyncDeps
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'host-agent-config-'))
deps = {
homes: { home: dir, claudeDir: join(dir, '.claude'), codexDir: join(dir, '.codex') },
projectPath: null,
ledgerDir: join(dir, 'userData')
}
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
const skillFiles = [{ path: 'SKILL.md', executable: false, bytes: Buffer.from('hello') }]
const digest = agentConfigDigest(skillFiles)
const payload = (patch: Record<string, unknown> = {}) => ({
scope: 'user' as const,
kind: 'claude-skill' as const,
name: 'hello',
digest,
files: [{ path: 'SKILL.md', executable: false, base64: Buffer.from('hello').toString('base64') }],
...patch
})
describe('host agent config sync', () => {
it('rejects names and paths that could leave the agent folders', () => {
for (const name of ['../x', '.hidden', 'a/b', '']) {
expect(
AgentConfigSyncPlanParams.safeParse({
syncer: 's',
items: [{ scope: 'user', kind: 'claude-skill', name, digest }]
}).success
).toBe(false)
}
for (const path of ['../SKILL.md', '/etc/passwd', 'a/../../b', '.git/config']) {
expect(
AgentConfigSyncPutParams.safeParse({
syncer: 's',
items: [payload({ files: [{ path, executable: false, base64: '' }] })]
}).success
).toBe(false)
}
// Codex prompts and old Codex skills have no project scope.
expect(
AgentConfigSyncPlanParams.safeParse({
syncer: 's',
items: [{ scope: 'project', kind: 'codex-prompt', name: 'x', digest }]
}).success
).toBe(false)
})
it('refuses a payload that does not match its digest or lacks SKILL.md', async () => {
const result = await putHostAgentConfig(
{
syncer: 's',
items: [
payload({ digest: '0'.repeat(64) }),
payload({
name: 'nomain',
digest: agentConfigDigest([
{ path: 'other.md', executable: false, bytes: Buffer.from('x') }
]),
files: [
{ path: 'other.md', executable: false, base64: Buffer.from('x').toString('base64') }
]
})
]
},
deps
)
expect(result.items).toEqual({
'user:claude-skill:hello': 'invalid',
'user:claude-skill:nomain': 'invalid'
})
expect(existsSync(join(dir, '.claude', 'skills'))).toBe(false)
})
it('leaves a symlinked skill alone and keeps project items out without a workspace', async () => {
mkdirSync(join(dir, '.claude', 'skills'), { recursive: true })
mkdirSync(join(dir, 'elsewhere'))
symlinkSync(join(dir, 'elsewhere'), join(dir, '.claude', 'skills', 'hello'))
const plan = await planHostAgentConfigSync(
{
syncer: 's',
items: [
{ scope: 'user', kind: 'claude-skill', name: 'hello', digest },
{ scope: 'project', kind: 'claude-skill', name: 'proj', digest }
]
},
deps
)
expect(plan.items).toEqual({
'user:claude-skill:hello': 'kept-host',
'project:claude-skill:proj': 'no-project'
})
})
it('ignores ledger entries that do not name a valid item', async () => {
mkdirSync(deps.ledgerDir, { recursive: true })
writeFileSync(
join(deps.ledgerDir, 'agent-config-sync-ledger-s.json'),
JSON.stringify({ version: 1, items: { 'user:claude-skill:../../victim': digest } })
)
mkdirSync(join(dir, 'victim'))
writeFileSync(join(dir, 'victim', 'SKILL.md'), 'hello')
const plan = await planHostAgentConfigSync({ syncer: 's', items: [] }, deps)
expect(plan.removed).toBe(0)
expect(existsSync(join(dir, 'victim', 'SKILL.md'))).toBe(true)
})
it('keeps each computer’s items separate', async () => {
await planHostAgentConfigSync(
{ syncer: 'mac-a', items: [{ scope: 'user', kind: 'claude-skill', name: 'hello', digest }] },
deps
)
await putHostAgentConfig({ syncer: 'mac-a', items: [payload()] }, deps)
// Another computer that never sent it doesn't remove it.
const other = await planHostAgentConfigSync({ syncer: 'mac-b', items: [] }, deps)
expect(other.removed).toBe(0)
expect(existsSync(join(dir, '.claude', 'skills', 'hello', 'SKILL.md'))).toBe(true)
const own = await planHostAgentConfigSync({ syncer: 'mac-a', items: [] }, deps)
expect(own.removed).toBe(1)
expect(existsSync(join(dir, '.claude', 'skills', 'hello'))).toBe(false)
})
})
@@ -0,0 +1,273 @@
import { randomBytes } from 'node:crypto'
import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
import { dirname, isAbsolute, join, resolve } from 'node:path'
import {
AGENT_CONFIG_FILE_KINDS,
AGENT_CONFIG_LIMITS,
AGENT_CONFIG_SELF_PATH,
AgentConfigItemKind,
AgentConfigItemScope,
AgentConfigSyncPlanParams,
agentConfigItemKey,
isSkillKind,
type AgentConfigItemPayload,
type AgentConfigPlanOutcome,
type AgentConfigPutOutcome,
type AgentConfigSyncPlanResult,
type AgentConfigSyncPutParams,
type AgentConfigSyncPutResult
} from '../../../shared/agent-config-sync/agent-config-sync-contract'
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
import { excludeFromGit, ledgerPath, readLedger, writeLedger } from './host-agent-config-ledger'
import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest'
import { agentConfigItemPath, agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots'
export type HostAgentConfigSyncDeps = {
homes: AgentConfigHomes
/** The host workspace's checkout (ORCA_WORKSPACE_PATH); project items go there. */
projectPath: string | null
/** Folder for this host's per-computer ledgers. */
ledgerDir: string
}
type ItemId = { scope: AgentConfigItemScope; kind: AgentConfigItemKind; name: string }
function parseKey(key: string): ItemId | null {
const [scope, kind, ...rest] = key.split(':')
const parsedScope = AgentConfigItemScope.safeParse(scope)
const parsedKind = AgentConfigItemKind.safeParse(kind)
const name = rest.join(':')
if (!parsedScope.success || !parsedKind.success || !name) {
return null
}
// Same checks as a fresh request, so a tampered ledger can't name a path outside the roots.
const checked = AgentConfigSyncPlanParams.safeParse({
syncer: 'ledger',
items: [{ scope, kind, name, digest: '0'.repeat(64) }]
})
return checked.success ? { scope: parsedScope.data, kind: parsedKind.data, name } : null
}
function destinationOf(item: ItemId, deps: HostAgentConfigSyncDeps): string | null {
const root = agentConfigRoot(item.kind, item.scope, deps.homes, deps.projectPath)
return root ? agentConfigItemPath(root, item.kind, item.name) : null
}
/** Digest of what is on disk now: null when absent, 'foreign' for anything not a plain copy. */
async function digestOnDisk(path: string, kind: AgentConfigItemKind): Promise<string | null> {
const info = await lstat(path).catch(() => null)
if (!info) {
return null
}
if (info.isSymbolicLink()) {
return 'foreign'
}
if (AGENT_CONFIG_FILE_KINDS.has(kind)) {
if (!info.isFile()) {
return 'foreign'
}
return agentConfigDigest([
{ path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: await readFile(path) }
])
}
if (!info.isDirectory()) {
return 'foreign'
}
const entries: AgentConfigDigestEntry[] = []
const visit = async (dir: string, prefix: string): Promise<boolean> => {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
const full = join(dir, entry.name)
if (entry.isDirectory()) {
if (!(await visit(full, rel))) {
return false
}
} else if (entry.isFile()) {
const stat = await lstat(full)
entries.push({
path: rel,
executable: (stat.mode & 0o111) !== 0,
bytes: await readFile(full)
})
if (entries.length > AGENT_CONFIG_LIMITS.filesPerItem * 2) {
return false
}
} else {
return false
}
}
return true
}
try {
return (await visit(path, '')) ? agentConfigDigest(entries) : 'foreign'
} catch {
return 'foreign'
}
}
/** Decides each item before any bytes move, and removes what this computer stopped sending. */
export async function planHostAgentConfigSync(
params: AgentConfigSyncPlanParams,
deps: HostAgentConfigSyncDeps
): Promise<AgentConfigSyncPlanResult> {
const path = ledgerPath(deps.ledgerDir, params.syncer)
const ledger = await readLedger(path)
const items: Record<string, AgentConfigPlanOutcome> = {}
const wanted = new Set<string>()
for (const item of params.items) {
const key = agentConfigItemKey(item.scope, item.kind, item.name)
wanted.add(key)
const dest = destinationOf(item, deps)
if (!dest) {
items[key] = 'no-project'
continue
}
const onDisk = await digestOnDisk(dest, item.kind)
if (onDisk === null) {
items[key] = 'needed'
} else if (onDisk === item.digest) {
items[key] = 'unchanged'
ledger.items[key] = item.digest
} else if (ledger.items[key] === onDisk) {
items[key] = 'needed'
} else {
// Made or edited in the sandbox: it's the user's now.
items[key] = 'kept-host'
delete ledger.items[key]
}
}
let removed = 0
for (const [key, digest] of Object.entries(ledger.items)) {
if (wanted.has(key)) {
continue
}
delete ledger.items[key]
const id = parseKey(key)
const dest = id ? destinationOf(id, deps) : null
// Only an untouched copy goes; an edited one stays as the user's.
if (id && dest && (await digestOnDisk(dest, id.kind)) === digest) {
await rm(dest, { recursive: true, force: true })
removed += 1
}
}
await writeLedger(path, ledger)
return { items, removed }
}
function decodeFiles(item: AgentConfigItemPayload): AgentConfigDigestEntry[] | null {
const isFileKind = AGENT_CONFIG_FILE_KINDS.has(item.kind)
if (isFileKind && (item.files.length !== 1 || item.files[0].path !== AGENT_CONFIG_SELF_PATH)) {
return null
}
const paths = new Set<string>()
const entries: AgentConfigDigestEntry[] = []
let total = 0
for (const file of item.files) {
if ((!isFileKind && file.path === AGENT_CONFIG_SELF_PATH) || paths.has(file.path)) {
return null
}
paths.add(file.path)
const bytes = Buffer.from(file.base64, 'base64')
total += bytes.length
if (bytes.length > AGENT_CONFIG_LIMITS.fileBytes || total > AGENT_CONFIG_LIMITS.itemBytes) {
return null
}
entries.push({ path: file.path, executable: !isFileKind && file.executable, bytes })
}
if (!isFileKind && !paths.has('SKILL.md')) {
return null
}
return agentConfigDigest(entries) === item.digest ? entries : null
}
async function writeItem(
dest: string,
kind: AgentConfigItemKind,
files: AgentConfigDigestEntry[]
): Promise<void> {
const parent = dirname(dest)
await mkdir(parent, { recursive: true })
const tag = randomBytes(6).toString('hex')
if (AGENT_CONFIG_FILE_KINDS.has(kind)) {
writeFileAtomically(dest, files[0].bytes, { mode: 0o644 })
return
}
// Built beside the target, then swapped in, so an agent never reads half a skill.
const staged = join(parent, `.orca-sync-${tag}`)
try {
for (const file of files) {
const target = resolve(staged, file.path)
if (isAbsolute(file.path) || !target.startsWith(`${staged}/`)) {
throw new Error('Path escapes the skill folder.')
}
await mkdir(dirname(target), { recursive: true })
await writeFile(target, file.bytes, { mode: file.executable ? 0o755 : 0o644 })
}
const old = join(parent, `.orca-sync-old-${tag}`)
const existed = await lstat(dest).then(
() => true,
() => false
)
if (existed) {
await rename(dest, old)
}
await rename(staged, dest)
if (existed) {
await rm(old, { recursive: true, force: true })
}
} finally {
await rm(staged, { recursive: true, force: true })
}
}
/** Writes items the plan asked for. Rechecks ownership, so a file edited since the plan stays. */
export async function putHostAgentConfig(
params: AgentConfigSyncPutParams,
deps: HostAgentConfigSyncDeps
): Promise<AgentConfigSyncPutResult> {
const path = ledgerPath(deps.ledgerDir, params.syncer)
const ledger = await readLedger(path)
const items: Record<string, AgentConfigPutOutcome> = {}
for (const item of params.items) {
const key = agentConfigItemKey(item.scope, item.kind, item.name)
const id = parseKey(key)
const files = id ? decodeFiles(item) : null
if (!id || !files) {
items[key] = 'invalid'
continue
}
const dest = destinationOf(id, deps)
if (!dest) {
items[key] = 'no-project'
continue
}
try {
const onDisk = await digestOnDisk(dest, id.kind)
if (onDisk !== null && onDisk !== item.digest && ledger.items[key] !== onDisk) {
items[key] = 'kept-host'
continue
}
if (onDisk !== item.digest) {
await writeItem(dest, id.kind, files)
}
if (id.scope === 'project' && deps.projectPath) {
await excludeFromGit(deps.projectPath, dest, isSkillKind(id.kind))
}
ledger.items[key] = item.digest
items[key] = onDisk === null ? 'added' : 'updated'
} catch {
items[key] = 'failed'
}
}
await writeLedger(path, ledger)
const counts = Object.values(items).reduce<Record<string, number>>((acc, outcome) => {
acc[outcome] = (acc[outcome] ?? 0) + 1
return acc
}, {})
console.info(
`[agent-config-sync] ${Object.entries(counts)
.map(([outcome, n]) => `${outcome}=${n}`)
.join(',')}`
)
return { items }
}
@@ -1,4 +1,3 @@
import { randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
@@ -18,6 +17,7 @@ import { environmentHandleFromRecipeResult } from '../../environment-providers/e
import { HOSTED_SANDBOX_DRIVER_ID } from '../../hosted-sandbox/hosted-sandbox-driver'
import { readLocalMcpConfig, type LocalMcpConfig } from './local-mcp-config-read'
import type { CloudMcpEgress } from './cloud-mcp-egress'
import { readOrCreateSyncerId } from '../../agent-config-sync/desktop/syncer-id'
const SYNC_TIMEOUT_MS = 30_000
const MAX_EXCLUDED = 512
@@ -146,30 +146,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
}
}
let syncer: string | null = null
/** This computer's stable sync identity (random, not a device fingerprint). */
function syncerId(): string {
if (syncer) {
return syncer
}
const path = join(deps.userDataPath, 'mcp-sync-syncer-id')
try {
const stored = readFileSync(path, 'utf8').trim()
if (/^[a-f0-9]{16}$/.test(stored)) {
syncer = stored
return stored
}
} catch {
// First sync from this computer.
}
syncer = randomBytes(8).toString('hex')
try {
writeFileAtomically(path, `${syncer}\n`)
} catch {
// Unwritable profile: this run still syncs as itself; the next launch gets a new id.
}
return syncer
}
const syncerId = (): Promise<string> => readOrCreateSyncerId(deps.userDataPath)
async function plan(environmentId: string) {
const runtime = cloudRuntime(environmentId)
@@ -180,7 +157,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
repoServerNames: local.repoServerNames,
homeDir: homedir()
})
return { ...planned, params: { ...planned.params, syncer: syncerId() } }
return { ...planned, params: { ...planned.params, syncer: await syncerId() } }
}
function publish(status: McpSyncStatus): McpSyncStatus {
+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))),
@@ -65,6 +65,10 @@ import {
installLocalCommands,
registerLocalCommandHandlers
} from '../local-commands/local-command-service'
import {
installCloudAgentConfigSync,
registerCloudAgentConfigSyncHandlers
} from '../agent-config-sync/desktop/cloud-agent-config-sync-ipc'
/** Capability Orca Cloud auth grants per account (stablyai/orca-cloud#689). */
export const ORCA_CLOUD_SANDBOX_CAPABILITY = 'sandbox'
@@ -91,6 +95,7 @@ export function installHostedSandbox(
restartHostedWorkspace(args.workspaceId)
)
registerCloudMcpSyncHandlers()
registerCloudAgentConfigSyncHandlers()
const userDataPath = app.getPath('userData')
registerLocalCommandHandlers()
const config = getHostedSandboxConfig(
@@ -127,6 +132,7 @@ export function installHostedSandbox(
baseUrl: config.controlPlaneUrl,
getAccessToken: config.getAccessToken
})
const agentConfigSync = installCloudAgentConfigSync(userDataPath)
// Dev rehearsals shorten idle sleep; packaged builds always use the provider's default.
const idleOverride = app.isPackaged
? Number.NaN
@@ -153,7 +159,11 @@ export function installHostedSandbox(
userDataPath,
driver,
windows: () => BrowserWindow.getAllWindows(),
onConnected: (runtimeEnvironmentId) => void mcpSync.sync(runtimeEnvironmentId, 'connect'),
// Create and wake both connect: MCP servers, skills and commands follow this computer's.
onConnected: (runtimeEnvironmentId) => {
void mcpSync.sync(runtimeEnvironmentId, 'connect')
void agentConfigSync.sync(runtimeEnvironmentId, 'connect')
},
onRunningChange: (anyRunning) => usageRefresh.setRunning(anyRunning),
activeAccountId
})
+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)
})
}
+14 -12
View File
@@ -18,12 +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'
import type { CloudWorkspace } from '../../shared/cloud-workspaces/cloud-workspaces-wire'
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(),
@@ -119,15 +127,8 @@ export async function readCloudWorkspaceSnapshot(
return result?.ok ? result.value : null
}
/** The registry row (owner, sharing, title) for a workspace; null when it can't be read. Never wakes it. */
export async function readCloudWorkspaceRecord(sandboxId: string): Promise<CloudWorkspace | null> {
if (!Id.safeParse(sandboxId).success) {
return null
}
const s = await getService().catch(() => null)
const result = await s?.get(sandboxId)
return result?.ok ? result.value : null
}
/** The team registry service, for main-process readers (null when this build has no control plane). */
export const getCloudWorkspacesService = (): Promise<CloudWorkspacesService | null> => getService()
/** Stable per-install id for presence rows (one row per device, not per window). */
async function clientIdFor(userDataPath: string): Promise<string> {
@@ -228,13 +229,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) => {
@@ -318,6 +319,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> =>
@@ -18,7 +18,7 @@ import {
listTeamCloudRuntimes,
readOrcaCloudActiveAccountId
} from '../hosted-sandbox/orca-cloud-active-account'
import { readCloudWorkspaceRecord } from '../ipc/cloud-workspaces'
import { getCloudWorkspacesService } from '../ipc/cloud-workspaces'
import {
callRuntimeEnvironment,
subscribeRuntimeEnvironment
@@ -126,7 +126,9 @@ export function installLocalCommands(userDataPath: string): void {
supported,
listWorkspaces,
readPolicy: async (sandboxId) => {
const record = await readCloudWorkspaceRecord(sandboxId)
const service = await getCloudWorkspacesService().catch(() => null)
const result = await service?.get(sandboxId)
const record = result?.ok ? result.value : null
return record
? {
isOwner: record.access === 'owner',
@@ -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')
}
+55 -15
View File
@@ -7,7 +7,7 @@ const config = (roots: string[] = ['/opt/orca'], unownedPorts: number[] = [23456
})
describe('host-managed listeners', () => {
it('reads absolute roots and platform ports from the environment', () => {
it('reads absolute roots and platform ports from the environment', async () => {
const parsed = hostManagedListenerConfig({
ORCA_HOST_MANAGED_LISTENER_PATHS: '/opt/orca/:relative:/srv/tools',
ORCA_HOST_MANAGED_UNOWNED_PORTS: '23456, x,70000'
@@ -17,17 +17,17 @@ describe('host-managed listeners', () => {
expect(hostManagedListenerConfig({})).toEqual({ roots: [], unownedPorts: new Set() })
})
it('marks the server itself and programs started from a managed root', () => {
expect(isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true)
it('marks the server itself and programs started from a managed root', async () => {
expect(await isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true)
expect(
isHostManagedListener(
await isHostManagedListener(
{ pid: 90, port: 2222, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' },
config(),
27
)
).toBe(true)
expect(
isHostManagedListener(
await isHostManagedListener(
{
pid: 91,
port: 6080,
@@ -39,40 +39,80 @@ describe('host-managed listeners', () => {
).toBe(true)
})
it('marks a pid-less listener only on a declared platform port', () => {
expect(isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true)
it('marks a pid-less listener only on a declared platform port', async () => {
expect(await isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true)
// A root-run postgres or Docker-published port has no visible pid but is the user's.
expect(isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false)
expect(isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false)
expect(await isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false)
expect(await isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false)
})
it('leaves user servers alone, matching by program path rather than port', () => {
it('leaves user servers alone, matching by program path rather than port', async () => {
expect(
isHostManagedListener(
await isHostManagedListener(
{ pid: 92, port: 6768, commandLine: 'python3 -m http.server 6768' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener(
await isHostManagedListener(
{ pid: 92, port: 23456, commandLine: 'python3 -m http.server 23456' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener(
await isHostManagedListener(
{ pid: 93, port: 5173, commandLine: 'node vite --config /opt/orca/x.js' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener({ pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' }, config(), 27)
await isHostManagedListener(
{ pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener({ pid: 95, port: 1, commandLine: '/opt/orca/bin/x' }, config([]), 27)
await isHostManagedListener(
{ pid: 95, port: 1, commandLine: '/opt/orca/bin/x' },
config([]),
27
)
).toBe(false)
})
it('walks ancestry to a managed tool, stopping at the server and at shells', async () => {
const parents: Record<number, { pid: number; commandLine: string }> = {
985: { pid: 941, commandLine: '/opt/orca/runtime/orcad/agent-browser-linux-x64' },
1018: { pid: 985, commandLine: '/usr/bin/google-chrome --headless' },
300: { pid: 27, commandLine: 'node /opt/orca/runtime/orcad/orcad-server.js' },
400: { pid: 399, commandLine: '/bin/bash' },
399: { pid: 27, commandLine: 'node /opt/orca/runtime/orcad/orcad-server.js' },
500: { pid: 499, commandLine: '-bash' },
499: { pid: 498, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' }
}
const read = async (pid: number) => parents[pid]
const chrome = { pid: 985, port: 42063, commandLine: '/usr/bin/google-chrome --headless' }
expect(await isHostManagedListener(chrome, config(), 27, read)).toBe(true)
// Grandchild: a Chrome helper two levels below agent-browser.
expect(
await isHostManagedListener(
{ pid: 1018, port: 42064, commandLine: '/opt/google/chrome/chrome --type=utility' },
config(),
27,
read
)
).toBe(true)
expect(await isHostManagedListener(chrome, config([]), 27, read)).toBe(false)
const user = (pid: number) => ({ pid, port: 8123, commandLine: 'python3 -m http.server' })
// `exec python3 -m http.server` in a terminal: its parent is the server.
expect(await isHostManagedListener(user(300), config(), 27, read)).toBe(false)
// Terminal shell under the server.
expect(await isHostManagedListener(user(400), config(), 27, read)).toBe(false)
// An SSH session's shell under the managed sshd.
expect(await isHostManagedListener(user(500), config(), 27, read)).toBe(false)
})
})
+61 -8
View File
@@ -1,3 +1,4 @@
import { readFile } from 'node:fs/promises'
import type { RawListeningPort } from './local-workspace-port-scan-state'
/** Colon-separated install roots whose binaries are the host's own services (e.g. a sandbox image's tools). */
@@ -28,27 +29,79 @@ export function hostManagedListenerConfig(
/**
* Listeners the host runs itself: this server process, a program started from a managed root
* (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too), or a declared platform
* port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or
* (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too) or its descendant, or a
* declared platform port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or
* Docker-published port) is still the user's.
*/
export function isHostManagedListener(
export async function isHostManagedListener(
port: Pick<RawListeningPort, 'pid' | 'commandLine' | 'port'>,
config: HostManagedListenerConfig,
serverPid: number = process.pid
): boolean {
serverPid: number = process.pid,
readParent: (pid: number) => Promise<ParentProcess | undefined> = readLinuxParentProcess
): Promise<boolean> {
if (port.pid === undefined) {
return config.unownedPorts.has(port.port)
}
if (port.pid === serverPid) {
return true
}
if (config.roots.length === 0 || !port.commandLine) {
if (config.roots.length === 0) {
return false
}
return port.commandLine
if (startedFromRoot(port.commandLine, config.roots)) {
return true
}
// A managed tool's descendant (agent-browser's Chrome DevTools port). The walk stops at the server
// (it spawns the user's terminals) and at a shell (a user session, e.g. over the managed sshd).
let pid = port.pid
for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth++) {
const parent = await readParent(pid)
if (!parent || parent.pid === serverPid || isShell(parent.commandLine)) {
return false
}
if (startedFromRoot(parent.commandLine, config.roots)) {
return true
}
pid = parent.pid
}
return false
}
const MAX_ANCESTRY_DEPTH = 8
const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh', 'fish', 'ksh', 'tcsh', 'csh', 'nu', 'pwsh'])
function isShell(commandLine: string): boolean {
const argv0 = commandLine.trim().split(/\s+/)[0] ?? ''
return SHELLS.has(argv0.replace(/^-/, '').split('/').pop() ?? '')
}
export type ParentProcess = { pid: number; commandLine: string }
function startedFromRoot(commandLine: string | undefined, roots: readonly string[]): boolean {
return (commandLine ?? '')
.trim()
.split(/\s+/)
.slice(0, 2)
.some((token) => config.roots.some((root) => token === root || token.startsWith(`${root}/`)))
.some((token) => roots.some((root) => token === root || token.startsWith(`${root}/`)))
}
async function readLinuxParentProcess(pid: number): Promise<ParentProcess | undefined> {
if (process.platform !== 'linux') {
return undefined
}
try {
// /proc/<pid>/stat: "pid (comm) state ppid ..."; comm may contain spaces or parens.
const stat = await readFile(`/proc/${pid}/stat`, 'utf8')
const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1])
if (!Number.isInteger(ppid) || ppid <= 1) {
return undefined
}
const commandLine = (await readFile(`/proc/${ppid}/cmdline`, 'utf8'))
.split('\0')
.join(' ')
.trim()
return { pid: ppid, commandLine }
} catch {
return undefined
}
}
@@ -42,9 +42,12 @@ export async function scanWorkspacePorts(
options.requireMetadata
)
const hostManaged = hostManagedListenerConfig()
const managedFlags = await Promise.all(
rawPorts.map((port) => isHostManagedListener(port, hostManaged))
)
const managed = new Set(
rawPorts
.filter((port) => isHostManagedListener(port, hostManaged))
.filter((_, index) => managedFlags[index])
.map((port) => `${port.host}:${port.port}:${port.pid ?? 'unknown'}`)
)
// Orca's own listeners (runtime socket, hook server) run with a workspace in their command line but are not its servers.
@@ -1,11 +1,31 @@
import { defineMethod } from '../../core'
import { AgentMcpSyncParams } from '../../../../../shared/agent-mcp-sync/mcp-sync-contract'
import { getAppEnvironment } from '../../../../../shared/app-environment'
import {
AgentConfigSyncPlanParams,
AgentConfigSyncPutParams
} from '../../../../../shared/agent-config-sync/agent-config-sync-contract'
import {
planHostAgentConfigSync,
putHostAgentConfig,
type HostAgentConfigSyncDeps
} from '../../../../agent-config-sync/host/host-agent-config-sync'
import { defaultAgentConfigHomes } from '../../../../agent-config-sync/agent-config-roots'
import {
defaultHostMcpSyncPaths,
syncHostMcpServers
} from '../../../../agent-mcp-sync/host/host-mcp-sync'
function hostAgentConfigDeps(): HostAgentConfigSyncDeps {
return {
homes: defaultAgentConfigHomes(),
projectPath: process.env.ORCA_WORKSPACE_PATH?.trim() || null,
ledgerDir: getAppEnvironment().getPath('userData')
}
}
const DESKTOP_ONLY = 'Only an Orca desktop can sync its skills and commands to this host.'
export const AGENT_CONFIG_METHODS = [
// The owning desktop mirrors its own MCP servers into this host's agent configs.
defineMethod({
@@ -21,5 +41,29 @@ export const AGENT_CONFIG_METHODS = [
projectPath: process.env.ORCA_WORKSPACE_PATH?.trim() || null
})
}
}),
// The owning desktop mirrors its own skills and slash commands into this host's agent configs:
// plan first (no bytes), then put only what the host lacks.
defineMethod({
name: 'agentConfig.planSkillSync',
permission: 'accounts-admin',
params: AgentConfigSyncPlanParams,
handler: async (params, { clientKind }) => {
if (clientKind === 'mobile') {
throw new Error(DESKTOP_ONLY)
}
return planHostAgentConfigSync(params, hostAgentConfigDeps())
}
}),
defineMethod({
name: 'agentConfig.putSkills',
permission: 'accounts-admin',
params: AgentConfigSyncPutParams,
handler: async (params, { clientKind }) => {
if (clientKind === 'mobile') {
throw new Error(DESKTOP_ONLY)
}
return putHostAgentConfig(params, hostAgentConfigDeps())
}
})
]
+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),
+19
View File
@@ -10,6 +10,10 @@ import type {
} from '../../shared/auth-callback-forward'
import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract'
import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences'
import type {
AgentConfigSyncStatus,
CloudAgentConfigSyncPreferences
} from '../../shared/agent-config-sync/agent-config-sync-contract'
import type {
CrewSubscriptionAttemptArgs,
CrewSubscriptionAttemptCallbacks,
@@ -135,6 +139,21 @@ export type RuntimeApi = {
included: boolean
) => Promise<CloudMcpSyncPreferences | null>
onMcpSyncChanged?: (callback: (status: McpSyncStatus) => void) => () => void
// Orca Cloud skills and slash commands sync; desktop only, like MCP sync.
getAgentConfigSyncStatus?: (environmentId: string) => Promise<AgentConfigSyncStatus | null>
syncAgentConfigNow?: (environmentId: string) => Promise<AgentConfigSyncStatus | null>
getAgentConfigSyncPreferences?: () => Promise<CloudAgentConfigSyncPreferences | null>
setAgentConfigSyncPreferences?: (
preferences: Partial<Omit<CloudAgentConfigSyncPreferences, 'excluded'>>
) => Promise<CloudAgentConfigSyncPreferences | null>
setAgentConfigItemIncluded?: (
key: string,
included: boolean
) => Promise<CloudAgentConfigSyncPreferences | null>
onAgentConfigSyncChanged?: (callback: (status: AgentConfigSyncStatus) => void) => () => void
onAgentConfigSyncPreferencesChanged?: (
callback: (preferences: CloudAgentConfigSyncPreferences) => void
) => () => void
getStatusSnapshots: () => Promise<RuntimeHostStatusSnapshot[]>
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void
// Absent in the web client, whose catalog lives in the browser rather than a CLI-editable file.
@@ -38,6 +38,12 @@ import type {
} from '../../shared/auth-callback-forward'
import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract'
import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences'
import {
CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL,
CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL,
type AgentConfigSyncStatus,
type CloudAgentConfigSyncPreferences
} from '../../shared/agent-config-sync/agent-config-sync-contract'
import { managedOrcadApi } from './managed-orcad-api'
import { getWslHostsApi } from './wsl-hosts-api'
@@ -89,6 +95,37 @@ export const runtimeEnvironmentsApi = {
ipcRenderer.on(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener)
return () => ipcRenderer.removeListener(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener)
},
getAgentConfigSyncStatus: (environmentId: string): Promise<AgentConfigSyncStatus | null> =>
ipcRenderer.invoke('cloudAgentConfigSync:getStatus', environmentId),
syncAgentConfigNow: (environmentId: string): Promise<AgentConfigSyncStatus | null> =>
ipcRenderer.invoke('cloudAgentConfigSync:syncNow', environmentId),
getAgentConfigSyncPreferences: (): Promise<CloudAgentConfigSyncPreferences | null> =>
ipcRenderer.invoke('cloudAgentConfigSync:getPreferences'),
setAgentConfigSyncPreferences: (
preferences: Partial<Omit<CloudAgentConfigSyncPreferences, 'excluded'>>
): Promise<CloudAgentConfigSyncPreferences | null> =>
ipcRenderer.invoke('cloudAgentConfigSync:setPreferences', preferences),
setAgentConfigItemIncluded: (
key: string,
included: boolean
): Promise<CloudAgentConfigSyncPreferences | null> =>
ipcRenderer.invoke('cloudAgentConfigSync:setItemIncluded', key, included),
onAgentConfigSyncChanged: (callback: (status: AgentConfigSyncStatus) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, status: AgentConfigSyncStatus): void =>
callback(status)
ipcRenderer.on(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, listener)
return () => ipcRenderer.removeListener(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, listener)
},
onAgentConfigSyncPreferencesChanged: (
callback: (preferences: CloudAgentConfigSyncPreferences) => void
): (() => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
preferences: CloudAgentConfigSyncPreferences
): void => callback(preferences)
ipcRenderer.on(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, listener)
return () => ipcRenderer.removeListener(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, listener)
},
getStatusSnapshots: (): Promise<RuntimeHostStatusSnapshot[]> =>
ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'),
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => {
@@ -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>
)
}
@@ -17,7 +17,14 @@ import { useTeamActions } from './use-team-actions'
import { openTeammateProfile } from '../../teammates/teammate-profile-store'
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
function TeamPageBody({ arrival }: { arrival: ReturnType<typeof useTeamPageState>['arrival'] }) {
export function TeamPageBody({
arrival,
inline
}: {
arrival: ReturnType<typeof useTeamPageState>['arrival']
/** Settings → Team: rendered on the page instead of in the dialog (JA-17). */
inline?: { onOpenPlanBilling: () => void }
}): React.JSX.Element {
const t = useTranslate()
const confirm = useConfirmationDialog()
const authStatus = useAppStore((state) => state.orcaProfileAuthStatus)
@@ -217,6 +224,7 @@ function TeamPageBody({ arrival }: { arrival: ReturnType<typeof useTeamPageState
}}
onDismissArrival={clearTeamPageArrival}
onContactSales={(url) => void window.api.shell.openUrl(url)}
inline={inline}
/>
)
}
@@ -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' }
],
@@ -51,6 +51,8 @@ export type TeamPageViewProps = {
onDismissArrival: () => void
/** Opens the Enterprise contact page (SSO/SCIM are Enterprise; nothing here pretends otherwise). */
onContactSales: (url: string) => void
/** Settings → Team renders the page inline: seats and invoices stay on Plan & billing (linked). */
inline?: { onOpenPlanBilling: () => void }
}
function viewerRoleSentence(role: OrcaOrgRole, t: Translate): string {
@@ -112,15 +114,17 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
const inviteInput = useRef<HTMLInputElement>(null)
const ssoTitleId = useId()
const hasRoster = props.roster !== null
const inline = props.inline ?? null
useEffect(() => {
const active = document.activeElement
if (
!inline &&
hasRoster &&
(!active || active === document.body || active.getAttribute('role') === 'dialog')
) {
document.querySelector<HTMLElement>('[data-team-page-heading]')?.focus()
}
}, [hasRoster])
}, [hasRoster, inline])
const leaveTitleId = useId()
if (!props.org) {
@@ -192,7 +196,18 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
/>
) : null}
{entitlement ? (
{inline ? (
<p className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
{t('auto.components.billing.team.seatsOnPlanBilling', 'Seats and invoices are in')}
<button
type="button"
className="rounded-sm text-foreground underline underline-offset-2 hover:text-foreground/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={inline.onOpenPlanBilling}
>
{t('auto.components.billing.title', 'Plan & billing')}
</button>
</p>
) : entitlement ? (
<TeamBillingBlock
entitlement={entitlement}
members={roster?.members.length ?? 0}
@@ -1,46 +0,0 @@
import { ChevronRight } from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { TeamMark } from './TeamAvatar'
import { memberCountLabel } from './team-copy'
import { openTeamPage } from './team-page-store'
import { useOrgRoster } from './use-org-roster'
/** Settings › Orca Cloud › Team: one row that opens the Team page (members, invites, seats). */
export function TeamSettingsLink({
orgId,
orgName
}: {
orgId: string | null
orgName: string | null
}): React.JSX.Element {
const t = useTranslate()
const roster = useOrgRoster(orgId)
const members = roster.result?.status === 'ok' ? roster.result.roster.members.length : null
return (
<div>
<button
type="button"
onClick={() => openTeamPage()}
className="flex w-full items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-xs transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-focus-ring focus-visible:outline-none"
>
{orgName ? <TeamMark name={orgName} className="size-8 text-xs" /> : null}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">
{orgName ?? t('auto.components.billing.team.createTitle', 'Create a team')}
</span>
<span className="block truncate text-xs text-muted-foreground">
{orgName
? members === null
? t('auto.components.billing.team.manage', 'Members, invites and seats')
: `${memberCountLabel(members, t)} · ${t('auto.components.billing.team.manage', 'Members, invites and seats')}`
: t(
'auto.components.billing.team.createHint',
'Share one Orca Cloud plan with your teammates.'
)}
</span>
</span>
<ChevronRight className="size-4 text-muted-foreground" />
</button>
</div>
)
}
@@ -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
}
}
@@ -124,7 +124,7 @@ export function EnvironmentForm({
<DropdownMenuLabel variant="hint">
{t(
'cloudEnvironment.form.importHint',
'Reads Conductor and dev container setup from a local project.'
'Reads Conductor and Dev Container setup from a local project.'
)}
</DropdownMenuLabel>
{importProjects.map((project) => (
@@ -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()
}

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