diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index 7a4c658d575..d4b98e106c7 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -7,6 +7,7 @@ // POST /v1/billing/portal -> { url } Stripe Customer Portal // POST /v1/billing/team-plans {orgIds} other teams' plan state ("Switch to "), read-only // POST /v1/billing/trial claim the team's one-time trial -> entitlement (trial.ts) +// GET /v1/billing/usage?utcOffset= 30 days of sandbox hours; top members/sandboxes for admins // Stripe: // POST /v1/stripe/webhook signed events // Sandbox control plane (CONTROL_PLANE_TOKEN): @@ -50,6 +51,7 @@ import { OverageRequestSchema, updateOverage } from './overage' import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe' import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage' import { handleStripeWebhook } from './webhook' +import { UsageHistoryQuerySchema, usageHistory } from './usage-history' import { renderReturnPage, returnOutcome } from './return-page' import { BindTeamSchema, @@ -316,6 +318,19 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo return json(await desktopEntitlement(env, caller, request, now)) } + case 'GET /v1/billing/usage': { + // Any member reads the team's daily hours and their own; the breakdown is owners/admins only. + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const query = UsageHistoryQuerySchema.safeParse(Object.fromEntries(url.searchParams)) + if (!query.success) { + return json({ error: 'invalid_request' }, 400) + } + return json(await usageHistory(env.BILLING_DB, caller, now, query.data.utcOffset)) + } + case 'POST /v1/billing/trial': { // Any member may start the team's trial the first time they pick Orca Cloud (spec B1). const caller = await authenticateDesktop(env, request) diff --git a/cloud/apps/billing/src/overage.ts b/cloud/apps/billing/src/overage.ts index 590e00f1d1f..13a24cb725d 100644 --- a/cloud/apps/billing/src/overage.ts +++ b/cloud/apps/billing/src/overage.ts @@ -2,14 +2,23 @@ // Opting in puts exactly one metered overage item, at STRIPE_PRICE_OVERAGE, on the Stripe // subscription: an item still on an older overage price is moved to the current one rather than a // second added (two items on the same meter would bill the same seconds twice). Opting out stops -// metering immediately but leaves the item, so usage already reported is still invoiced. +// metering immediately. The item is removed once it has nothing left to invoice (no meter report +// this Stripe period): at once if none was sent, otherwise at a sync after the period rolls over, +// so usage already reported is still invoiced and no $0 overage line is left on later invoices. import { z } from 'zod' import type { BillingCaller } from './auth' import { OPEN_STATUSES } from './checkout' import type { Env } from './env' import { planCatalog, planForPrice } from './plans' import type { StripeClient, StripeSubscription } from './stripe' -import { accountSettings, currentSubscription, setOverageSettings, upsertSubscription, type SubscriptionRow } from './store' +import { + accountSettings, + currentSubscription, + meterReportsSince, + setOverageSettings, + upsertSubscription, + type SubscriptionRow +} from './store' export const OverageRequestSchema = z .object({ @@ -51,9 +60,35 @@ export async function updateOverage( ? (await accountSettings(env.BILLING_DB, caller.accountId)).spend_cap_cents : request.spendCapCents await setOverageSettings(env.BILLING_DB, caller.accountId, { optIn: request.enabled, spendCapCents }, now) + if (!request.enabled) { + // Best effort: the opt-out already stops metering; a failed removal is retried by the next sync. + await retireOverageItem(env, stripe, subscription, now).catch((error: unknown) => { + console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' })) + }) + } return { ok: true } } +/** + * Removes an opted-out account's overage item once nothing on it is left to invoice: no meter + * report (sent or pending) since the Stripe period began. Returns whether it removed one. + */ +export async function retireOverageItem(env: Env, stripe: StripeClient, subscription: SubscriptionRow, now: number): Promise { + if (!subscription.overage_item_id) { + return false + } + const settings = await accountSettings(env.BILLING_DB, subscription.account_id) + if (settings.overage_opt_in === 1) { + return false + } + if ((await meterReportsSince(env.BILLING_DB, subscription.account_id, subscription.current_period_start)) > 0) { + return false + } + await stripe.deleteSubscriptionItem(subscription.overage_item_id) + await upsertSubscription(env.BILLING_DB, { ...subscription, overage_enabled: 0, overage_item_id: null, updated_at: now }) + return true +} + /** A metered item that is not a seat price and not the current overage price: an older overage price. */ function isStaleOverageItem(env: Env, item: StripeSubscription['items']['data'][number]): boolean { return ( @@ -84,6 +119,17 @@ async function ensureOverageItem(env: Env, stripe: StripeClient, subscription: S } return replace.id } - // Idempotent per subscription+price, so a retried opt-in cannot add a second item. - return (await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE })).id + // Idempotent per subscription+price, so a retried opt-in cannot add a second item. Opting out + // can remove the item, so a later opt-in may get the removed item's id replayed (Stripe keeps + // idempotent answers for 24 hours): then add again under a key that names the removed item. + let after: string | undefined + for (let attempt = 0; attempt < 3; attempt++) { + const added = await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE, after }) + const fresh = await stripe.retrieveSubscription(subscription.stripe_subscription_id) + if (fresh.items.data.some((item) => item.id === added.id)) { + return added.id + } + after = added.id + } + throw new Error('overage_item_replayed') } diff --git a/cloud/apps/billing/src/store.ts b/cloud/apps/billing/src/store.ts index af9f27f66eb..a9c8af04233 100644 --- a/cloud/apps/billing/src/store.ts +++ b/cloud/apps/billing/src/store.ts @@ -220,6 +220,18 @@ export async function insertUsage(db: D1Database, usage: UsageInsert): Promise 0 } +/** Meter reports (any status) for usage that ended since `since`, plus any still pending. */ +export async function meterReportsSince(db: D1Database, accountId: string, since: number): Promise { + const row = await db + .prepare( + `SELECT COUNT(*) AS n FROM meter_reports m JOIN usage_events p ON p.usage_id = m.usage_id + WHERE p.account_id = ?1 AND (m.event_timestamp >= ?2 OR m.status = 'pending')` + ) + .bind(accountId, since) + .first<{ n: number }>() + return row?.n ?? 0 +} + /** Overage seconds already metered (billed) in an allowance window. */ export async function meteredSeconds(db: D1Database, accountId: string, windowStart: number): Promise { const row = await db diff --git a/cloud/apps/billing/src/stripe.ts b/cloud/apps/billing/src/stripe.ts index 8d493a6fd58..30b89ef0b15 100644 --- a/cloud/apps/billing/src/stripe.ts +++ b/cloud/apps/billing/src/stripe.ts @@ -143,13 +143,14 @@ export function createStripeClient(env: Env, fetchImpl: typeof fetch = fetch) { idempotencyKey ) }, - addSubscriptionItem(args: { subscription: string; price: string }) { + /** `after`: the id a replayed add returned for an item since removed, so this add is a new one. */ + addSubscriptionItem(args: { subscription: string; price: string; after?: string }) { return request<{ id: string }>( 'POST', '/v1/subscription_items', // Metered: nothing to prorate; usage is billed in arrears. { subscription: args.subscription, price: args.price, proration_behavior: 'none' }, - `overage-item:${args.subscription}:${args.price}` + `overage-item:${args.subscription}:${args.price}${args.after ? `:after:${args.after}` : ''}` ) }, /** Moves an item to another price in place (an older overage price to the current one). */ diff --git a/cloud/apps/billing/src/usage-history.ts b/cloud/apps/billing/src/usage-history.ts new file mode 100644 index 00000000000..55f4ac11436 --- /dev/null +++ b/cloud/apps/billing/src/usage-history.ts @@ -0,0 +1,103 @@ +// Usage history for Plan & billing: sandbox hours per day for the last 30 days, the caller's own +// share, and (for owners and admins only) the top members and sandboxes. Read-only over +// usage_events; hours are the same weighted seconds the included-hours meter counts. A segment +// counts on the day it ended, as it counts in the allowance window it ended in. +import { z } from 'zod' +import type { BillingCaller } from './auth' + +export const USAGE_HISTORY_DAYS = 30 +export const USAGE_HISTORY_TOP = 5 +const DAY_MS = 24 * 3600 * 1000 + +/** `utcOffset`: the viewer's minutes east of UTC, so days start at their local midnight. */ +export const UsageHistoryQuerySchema = z.object({ + utcOffset: z.coerce.number().int().min(-840).max(840).default(0) +}) + +export type UsageHistoryTop = { + top: Array<{ [key in K]: string } & { seconds: number }> + /** Everyone (or everything) past the top entries, plus segments with no member recorded. */ + otherCount: number + otherSeconds: number +} + +export type UsageHistory = { + /** Oldest first, exactly USAGE_HISTORY_DAYS entries; `start` is the local midnight in epoch ms. */ + days: Array<{ start: number; seconds: number }> + totalSeconds: number + /** The caller's own sandbox hours in the same days. */ + yourSeconds: number + /** Owners and admins only; null for members. */ + members: UsageHistoryTop<'userId'> | null + sandboxes: UsageHistoryTop<'sandboxId'> | null +} + +/** Epoch ms of the local midnight that starts the oldest day shown. */ +export function usageHistoryStart(now: number, utcOffsetMinutes: number): number { + const offset = utcOffsetMinutes * 60_000 + const today = Math.floor((now + offset) / DAY_MS) * DAY_MS - offset + return today - (USAGE_HISTORY_DAYS - 1) * DAY_MS +} + +function topOf( + key: K, + rows: Array<{ id: string | null; seconds: number }> +): UsageHistoryTop { + const named = rows.filter((row) => row.id !== null).sort((a, b) => b.seconds - a.seconds) + const top = named.slice(0, USAGE_HISTORY_TOP) + const rest = [...named.slice(USAGE_HISTORY_TOP), ...rows.filter((row) => row.id === null)] + return { + top: top.map((row) => ({ [key]: row.id, seconds: row.seconds }) as { [k in K]: string } & { seconds: number }), + otherCount: rest.filter((row) => row.id !== null).length, + otherSeconds: rest.reduce((sum, row) => sum + row.seconds, 0) + } +} + +export async function usageHistory( + db: D1Database, + caller: BillingCaller, + now: number, + utcOffsetMinutes: number +): Promise { + const start = usageHistoryStart(now, utcOffsetMinutes) + const range = 'account_id = ?1 AND ended_at >= ?2 AND ended_at <= ?3' + const [byDay, mine, byMember, bySandbox] = await Promise.all([ + db + .prepare( + `SELECT CAST((ended_at - ?2) / ${DAY_MS} AS INTEGER) AS day, SUM(weighted_seconds) AS seconds + FROM usage_events WHERE ${range} GROUP BY day` + ) + .bind(caller.accountId, start, now) + .all<{ day: number; seconds: number }>(), + db + .prepare(`SELECT COALESCE(SUM(weighted_seconds), 0) AS seconds FROM usage_events WHERE ${range} AND user_id = ?4`) + .bind(caller.accountId, start, now, caller.userId) + .first<{ seconds: number }>(), + caller.canManage + ? db + .prepare(`SELECT user_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY user_id`) + .bind(caller.accountId, start, now) + .all<{ id: string | null; seconds: number }>() + : null, + caller.canManage + ? db + .prepare(`SELECT sandbox_id AS id, SUM(weighted_seconds) AS seconds FROM usage_events WHERE ${range} GROUP BY sandbox_id`) + .bind(caller.accountId, start, now) + .all<{ id: string; seconds: number }>() + : null + ]) + const days = Array.from({ length: USAGE_HISTORY_DAYS }, (_, index) => ({ start: start + index * DAY_MS, seconds: 0 })) + for (const row of byDay.results) { + const day = days[row.day] + if (day) { + day.seconds += row.seconds + } + } + return { + days, + totalSeconds: days.reduce((sum, day) => sum + day.seconds, 0), + yourSeconds: mine?.seconds ?? 0, + members: byMember ? topOf('userId', byMember.results) : null, + sandboxes: bySandbox ? topOf('sandboxId', bySandbox.results) : null + } +} diff --git a/cloud/apps/billing/src/webhook.ts b/cloud/apps/billing/src/webhook.ts index e4373aecd8a..c2118c32d45 100644 --- a/cloud/apps/billing/src/webhook.ts +++ b/cloud/apps/billing/src/webhook.ts @@ -3,7 +3,8 @@ import type { Env } from './env' import { planForPrice } from './plans' import { allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe' -import { accountForCustomer, claimEvent, customerFor, finishEvent, upsertSubscription } from './store' +import { accountForCustomer, claimEvent, currentSubscription, customerFor, finishEvent, upsertSubscription } from './store' +import { retireOverageItem } from './overage' import { splitSecrets, verifyStripeSignature } from './webhook-signature' const MAX_BODY_BYTES = 512 * 1024 @@ -112,6 +113,15 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript // Membership comes from auth, not Stripe: keep the stored count. member_count: null }) + if (overageItemId) { + // An opted-out account's overage item goes once the period it was used in has been invoiced. + const stored = await currentSubscription(db, accountId) + if (stored?.stripe_subscription_id === subscription.id) { + await retireOverageItem(env, stripe, stored, now).catch((error: unknown) => { + console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' })) + }) + } + } } export async function handleStripeWebhook(env: Env, stripe: StripeClient, request: Request, now: number): Promise { diff --git a/cloud/apps/billing/test/overage-opt-out.test.ts b/cloud/apps/billing/test/overage-opt-out.test.ts new file mode 100644 index 00000000000..544550aad18 --- /dev/null +++ b/cloud/apps/billing/test/overage-opt-out.test.ts @@ -0,0 +1,97 @@ +// Opting out of overage: nothing more is metered or billed, and the metered item comes off the +// subscription once nothing on it is left to invoice (no $0 overage line on later invoices). +import { describe, expect, it } from 'vitest' +import { checkoutCompleted, stripeEvent } from './stripe-fake' +import { createHarness } from './harness' + +const HOUR = 3600 +const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR +const PERIOD_END = PERIOD_START + 30 * 24 * HOUR + +async function optedInTeam() { + const h = await createHarness() + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ + customer, + accountId: 'org:o1', + basePrice: 'price_team_month', + quantity: 2, + periodStart: PERIOD_START, + periodEnd: PERIOD_END + }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + const overage = (body: unknown) => h.call('POST', '/v1/billing/overage', { body, headers: auth }) + expect((await overage({ enabled: true })).status).toBe(200) + const prices = () => subscription.items.data.map((item) => item.price.id) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + let n = 0 + const use = (hours: number) => { + const endedAt = Date.now() - 60_000 + return h.controlPlane('/v1/internal/usage', { + usageId: `u-${n++}`, + accountId: 'org:o1', + sandboxId: 'sbx_1', + machineSize: 'standard', + startedAt: endedAt - hours * HOUR * 1000, + endedAt + }) + } + const stored = () => + h.raw.prepare('SELECT overage_enabled, overage_item_id IS NOT NULL AS has_item FROM subscriptions').get() + return { h, auth, subscription, overage, prices, use, stored } +} + +describe('overage opt-out', () => { + it('removes the unused metered item at once, and opting back in adds it again', async () => { + const { h, overage, prices, use, stored } = await optedInTeam() + expect((await overage({ enabled: false })).status).toBe(200) + expect(prices()).toEqual(['price_team_month']) + expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 }) + // Past the included hours with overage off: nothing is metered. + for (let i = 0; i < 6; i++) { + await use(24) + } + expect(h.stripe.meterEvents).toHaveLength(0) + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 }) + expect((await overage({ enabled: true })).status).toBe(200) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + }) + + it('a $0 cap never meters, even with overage on', async () => { + const { h, overage, use } = await optedInTeam() + expect((await overage({ enabled: true, spendCapCents: 0 })).status).toBe(200) + for (let i = 0; i < 6; i++) { + await use(24) + } + expect(h.stripe.meterEvents).toHaveLength(0) + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 }) + }) + + it('keeps an item with usage to invoice until the period rolls over, then removes it', async () => { + const { h, overage, prices, use, stored, subscription } = await optedInTeam() + for (let i = 0; i < 5; i++) { + await use(24) + } + await use(2) + expect(h.stripe.meterEvents).toHaveLength(1) + expect((await overage({ enabled: false })).status).toBe(200) + // The 2 overage hours still have to be invoiced on this item. + expect(prices()).toEqual(['price_team_month', 'price_overage']) + await use(3) + expect(h.stripe.meterEvents).toHaveLength(1) + // A sync inside the same period keeps it. + await h.webhook(stripeEvent('customer.subscription.updated', subscription)) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + // Renewal: the next period has nothing metered, so the sync takes the item off. + for (const item of subscription.items.data) { + item.current_period_start = PERIOD_END + item.current_period_end = PERIOD_END + 30 * 24 * HOUR + } + await h.webhook(stripeEvent('customer.subscription.updated', subscription)) + expect(prices()).toEqual(['price_team_month']) + expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 }) + }) +}) diff --git a/cloud/apps/billing/test/usage-history.test.ts b/cloud/apps/billing/test/usage-history.test.ts new file mode 100644 index 00000000000..3c7373d0dc8 --- /dev/null +++ b/cloud/apps/billing/test/usage-history.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' +import { createHarness } from './harness' +import { USAGE_HISTORY_DAYS, usageHistoryStart } from '../src/usage-history' + +const HOUR = 3600 +const DAY_MS = 24 * 3600 * 1000 +// Tokens are checked against the real clock, so the fixture's "now" is real too. +const NOW = Date.now() +const utcMidnight = Math.floor(NOW / DAY_MS) * DAY_MS +// Today's segment, kept inside today even just after midnight. +const END = Math.max(utcMidnight, NOW - 60_000) + +async function seeded() { + const h = await createHarness() + h.setNow(NOW) + const insert = h.raw.prepare( + `INSERT INTO usage_events (usage_id, account_id, sandbox_id, machine_size, started_at, ended_at, weighted_seconds, + period_start, overage_seconds, created_at, user_id) VALUES (?, ?, ?, 'standard', ?, ?, ?, NULL, 0, ?, ?)` + ) + let n = 0 + const add = (endedAt: number, hours: number, sandboxId: string, userId: string | null, account = 'org:o1') => { + insert.run(`u${n++}`, account, sandboxId, endedAt - 60_000, endedAt, hours * HOUR, endedAt, userId) + } + add(END, 2, 'sbx_a', 'alice') + add(END - DAY_MS, 1, 'sbx_b', 'bob') + add(END - 3 * DAY_MS, 3, 'sbx_a', 'alice') + // Six more members, half an hour each: three make the top five, three don't. + for (const user of ['c', 'd', 'e', 'f', 'g', 'h']) { + add(END - 5 * DAY_MS, 0.5, `sbx_${user}`, user) + } + // A segment from before members were recorded. + add(END - 6 * DAY_MS, 0.25, 'sbx_old', null) + // Outside the 30 days, and another team's: never counted. + add(NOW - 31 * DAY_MS, 9, 'sbx_a', 'alice') + add(NOW - DAY_MS, 9, 'sbx_z', 'zed', 'org:o2') + return h +} + +async function read(h: Awaited>, role: string, sub = 'alice', query = '') { + const token = await h.desktopToken({ sub, org: 'o1', orgRole: role }) + return h.call('GET', `/v1/billing/usage${query}`, { headers: { authorization: `Bearer ${token}` } }) +} + +describe('GET /v1/billing/usage', () => { + it('returns 30 local days of team hours and the owner/admin breakdown', async () => { + const h = await seeded() + const { status, body } = await read(h, 'owner') + expect(status).toBe(200) + expect(body.days).toHaveLength(USAGE_HISTORY_DAYS) + expect(body.days.at(-1)).toEqual({ start: utcMidnight, seconds: 2 * HOUR }) + expect(body.days.at(-2).seconds).toBe(1 * HOUR) + expect(body.days.at(-4).seconds).toBe(3 * HOUR) + expect(body.totalSeconds).toBe(9.25 * HOUR) + expect(body.yourSeconds).toBe(5 * HOUR) + expect(body.members.top.map((m: { userId: string }) => m.userId).slice(0, 2)).toEqual(['alice', 'bob']) + expect(body.members.top).toHaveLength(5) + expect(body.members.otherCount).toBe(3) + // Three members past the top five (1.5 hours) plus the unattributed quarter hour. + expect(body.members.otherSeconds).toBe(1.75 * HOUR) + expect(body.sandboxes.top[0]).toEqual({ sandboxId: 'sbx_a', seconds: 5 * HOUR }) + }) + + it('gives members the team chart and their own hours, never the breakdown', async () => { + const h = await seeded() + const { body } = await read(h, 'member', 'bob') + expect(body.totalSeconds).toBe(9.25 * HOUR) + expect(body.yourSeconds).toBe(1 * HOUR) + expect(body.members).toBeNull() + expect(body.sandboxes).toBeNull() + }) + + it('starts days at the viewer’s local midnight', async () => { + const h = await seeded() + const { body } = await read(h, 'admin', 'alice', '?utcOffset=-480') + // In UTC-8 a day starts at 08:00 UTC. + const today = body.days.at(-1).start + expect(new Date(today).getUTCHours()).toBe(8) + expect(today).toBeLessThanOrEqual(NOW) + expect(NOW - today).toBeLessThan(DAY_MS) + expect(body.days[0].start).toBe(usageHistoryStart(NOW, -480)) + }) + + it('rejects a bad offset and an unsigned caller', async () => { + const h = await seeded() + expect((await read(h, 'owner', 'alice', '?utcOffset=9999')).status).toBe(400) + expect((await h.call('GET', '/v1/billing/usage')).status).toBe(401) + }) + + it('returns zeroed days for a team with no usage', async () => { + const h = await createHarness() + h.setNow(NOW) + const token = await h.desktopToken({ sub: 'u1', org: 'o9', orgRole: 'owner' }) + const { body } = await h.call('GET', '/v1/billing/usage', { headers: { authorization: `Bearer ${token}` } }) + expect(body.totalSeconds).toBe(0) + expect(body.days.every((day: { seconds: number }) => day.seconds === 0)).toBe(true) + expect(body.members).toEqual({ top: [], otherCount: 0, otherSeconds: 0 }) + }) +}) diff --git a/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql new file mode 100644 index 00000000000..329a96abb2d --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql @@ -0,0 +1,40 @@ +-- G14: every cloud workspace gets a short number in its account (W-123), allocated from a per-account +-- counter so a number is never reused, even after the row is destroyed. Orgs get a URL slug for links +-- (orca://cloud//W-123). G13: each member's sidebar prefs for cloud workspaces (pins, their +-- order, and the order of sections) live on the account so every device shows the same sidebar. +ALTER TABLE sandboxes ADD COLUMN number INTEGER; + +-- Backfill: existing rows numbered by creation order within their account. +UPDATE sandboxes SET number = ( + SELECT COUNT(*) FROM sandboxes AS earlier + WHERE earlier.account_id = sandboxes.account_id + AND (earlier.created_at < sandboxes.created_at OR (earlier.created_at = sandboxes.created_at AND earlier.id <= sandboxes.id)) +); + +CREATE UNIQUE INDEX sandboxes_account_number ON sandboxes (account_id, number) WHERE number IS NOT NULL; + +CREATE TABLE org_workspace_counters ( + account_id TEXT PRIMARY KEY, + last_number INTEGER NOT NULL +); + +INSERT INTO org_workspace_counters (account_id, last_number) + SELECT account_id, MAX(number) FROM sandboxes GROUP BY account_id; + +CREATE TABLE org_slugs ( + account_id TEXT PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + created_by TEXT NOT NULL, + updated_at INTEGER NOT NULL +); + +CREATE TABLE workspace_prefs ( + account_id TEXT NOT NULL, + user_id TEXT NOT NULL, + document TEXT NOT NULL, + revision INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + updated_by_device TEXT, + PRIMARY KEY (account_id, user_id) +); diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 08ec6d476de..c0c9c9faa5a 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -132,6 +132,12 @@ export type Env = { /** Operator routes (/v1/internal/*): kill switch, drain, bindings. Secret, >= 32 chars; unset = no routes. */ OPERATOR_TOKEN?: string + /** + * Auth's bearer for POST /v1/internal/org-members/removed only (PropelAuth offboarding and + * Orca-side removals). Secret, >= 32 chars; lets auth push removals without holding the + * operator token. The operator token is still accepted on that route. + */ + MEMBER_REMOVED_TOKEN?: string /** `true` refuses every create/resume/rollover (static kill switch; the D1 flag is the runtime one). */ SANDBOX_CREATES_DISABLED?: string /** Warm pool size (pool.ts); unset or 0 = off. */ diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 5edaae7c49a..80752e89649 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -25,7 +25,8 @@ // POST /v1/device-sessions | GET | DELETE /:id per-phone access (see device-sessions.ts) // Phones sign their own EdDSA tokens (device-sessions.ts) and act as their user, except that they // cannot enroll devices, manage secrets or connect GitHub. -// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts +// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts, +// /v1/team/prefs (src/workspace-prefs.ts), /v1/team/org (src/org-slugs.ts) // team workspace registry, presence, per-device grants (src/workspaces.ts, src/grants.ts) // POST /v1/team/workspaces/:id/wake?wait=30s: any member who can open it wakes it (single-flight, // billed to the account, counted on the owner's seat like every wake) -> {state, endpoint: null, …} @@ -191,7 +192,10 @@ import { userAuthorizeUrl } from './github-user-tokens' import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git' +import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs' +import { getOrgSlug, putOrgSlug } from './org-slugs' import { + LinkOtherOrgError, PatchSchema, PresenceSchema, WORKSPACE_ERROR_STATUS, @@ -1146,7 +1150,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) return await internalInstallUrl(env, deps, url) } if (url.pathname.startsWith('/v1/internal/')) { - if (!(await isOperator(request, env.OPERATOR_TOKEN))) { + // Auth's member-removed push holds a token good for that one route, not the operator token. + const memberRemovedOnly = + url.pathname === '/v1/internal/org-members/removed' && + request.method === 'POST' && + (await isOperator(request, env.MEMBER_REMOVED_TOKEN)) + if (!memberRemovedOnly && !(await isOperator(request, env.OPERATOR_TOKEN))) { return fail('not_found', 404) } const life = await lifecycleDeps(env, deps) @@ -1487,6 +1496,8 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) url.pathname.startsWith('/v1/team/workspaces/') || url.pathname === '/v1/team/links/resolve' || url.pathname === '/v1/team/prompts' || + url.pathname === '/v1/team/prefs' || + url.pathname === '/v1/team/org' || url.pathname.startsWith('/v1/team/members/') || url.pathname === '/v1/team/pokes' || url.pathname.startsWith('/v1/team/pokes/') @@ -1866,7 +1877,32 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, // Labels for teammates' lists; a failure here must never fail the request itself. await rememberCallerName(db, caller, now).catch((error: unknown) => console.warn('member_name_write_failed', String(error))) if (url.pathname === '/v1/team/links/resolve' && request.method === 'GET') { - return json(await resolveLink(db, caller, url, now)) + try { + return json(await resolveLink(db, caller, url, now)) + } catch (error) { + if (error instanceof LinkOtherOrgError) { + return json({ error: 'not_found', reason: 'other_org', orgId: error.orgId }, 404) + } + throw error + } + } + if (url.pathname === '/v1/team/prefs') { + if (request.method === 'GET') { + return json(await getWorkspacePrefs(db, caller)) + } + if (request.method === 'PUT') { + return json(await putWorkspacePrefs(db, caller, await readJson(request), now)) + } + return fail('not_found', 404) + } + if (url.pathname === '/v1/team/org') { + if (request.method === 'GET') { + return json(await getOrgSlug(db, caller, url, now)) + } + if (request.method === 'PUT') { + return json(await putOrgSlug(db, caller, await readJson(request), now)) + } + return fail('not_found', 404) } if (url.pathname === '/v1/team/prompts') { if (request.method === 'GET') { diff --git a/cloud/apps/sandbox-control/src/org-slugs.ts b/cloud/apps/sandbox-control/src/org-slugs.ts new file mode 100644 index 00000000000..dfbc9191883 --- /dev/null +++ b/cloud/apps/sandbox-control/src/org-slugs.ts @@ -0,0 +1,123 @@ +// Org URL slugs for workspace links (orca://cloud//W-123). +// GET /v1/team/org?name= -> {slug, orgId}; the first call names it from `name` +// PUT /v1/team/org {slug} org owner/admin renames it (409 when another org has it) +// Auth owns orgs and knows their names; this Worker only sees ids. So the first member to ask +// proposes a slug from the name their client shows, and the Worker makes it unique. Personal +// accounts have no slug: their links keep the sandbox id form (orca://cloud/w/). +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { WorkspaceError, isOrgAdmin } from './workspaces' + +/** Path words a slug can't take: they'd read as a different link form. */ +const RESERVED = new Set(['w', 'c', 'me', 'api', 'app', 'new', 'org', 'team', 'settings', 'cloud', 'orca', 'admin', 'help', 'setup']) + +export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/ + +export function isValidSlug(value: string): boolean { + return SLUG.test(value) && !value.includes('--') && !RESERVED.has(value) +} + +/** "Acme Labs, Inc." → "acme-labs-inc"; falls back to "team" when nothing usable is left. */ +export function slugify(name: string): string { + const base = name + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 32) + .replace(/-+$/g, '') + return base.length >= 2 && !RESERVED.has(base) ? base : base ? `${base}-team` : 'team' +} + +type Row = { account_id: string; slug: string } + +/** `org:abc` / `dev:org:abc` → `abc` (the id the desktop's org list uses). */ +export function orgIdOf(accountId: string): string | null { + const match = /^(?:dev:)?org:(.+)$/.exec(accountId) + return match ? match[1]! : null +} + +export async function slugForAccount(db: D1Database, accountId: string): Promise { + const row = await db.prepare('SELECT slug FROM org_slugs WHERE account_id = ?').bind(accountId).first<{ slug: string }>() + return row?.slug ?? null +} + +export async function accountForSlug(db: D1Database, slug: string): Promise { + if (!isValidSlug(slug)) { + return null + } + const row = await db.prepare('SELECT account_id FROM org_slugs WHERE slug = ?').bind(slug).first() + return row?.account_id ?? null +} + +const NameQuery = z.string().trim().min(1).max(120) + +export async function getOrgSlug(db: D1Database, caller: SandboxCaller, url: URL, now: number) { + const orgId = caller.orgId ? orgIdOf(caller.accountId) : null + if (!orgId) { + return { slug: null, orgId: null } + } + const existing = await slugForAccount(db, caller.accountId) + if (existing) { + return { slug: existing, orgId } + } + const name = NameQuery.safeParse(url.searchParams.get('name') ?? '') + if (!name.success) { + // Nothing to name it from yet; the next client that knows the org's name will. + return { slug: null, orgId } + } + const base = slugify(name.data) + for (let attempt = 0; attempt < 20; attempt += 1) { + const candidate = attempt === 0 ? base : `${base.slice(0, 32)}-${attempt + 1}` + const result = await db + .prepare('INSERT OR IGNORE INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)') + .bind(caller.accountId, candidate, now, caller.userId, now) + .run() + if (result.meta.changes === 1) { + return { slug: candidate, orgId } + } + // Either another org holds this slug, or a teammate just named ours (then use theirs). + const raced = await slugForAccount(db, caller.accountId) + if (raced) { + return { slug: raced, orgId } + } + } + throw new WorkspaceError('conflict', 'slug_exhausted') +} + +const PutSchema = z.object({ slug: z.string().min(1).max(40) }).strict() + +export async function putOrgSlug(db: D1Database, caller: SandboxCaller, body: unknown, now: number) { + const orgId = caller.orgId ? orgIdOf(caller.accountId) : null + if (!orgId) { + throw new WorkspaceError('invalid_request', 'personal_account') + } + if (!isOrgAdmin(caller)) { + throw new WorkspaceError('forbidden', 'admin_only') + } + const parsed = PutSchema.safeParse(body) + if (!parsed.success || !isValidSlug(parsed.data.slug)) { + throw new WorkspaceError('invalid_request', 'invalid_slug') + } + const slug = parsed.data.slug + const holder = await accountForSlug(db, slug) + if (holder && holder !== caller.accountId) { + throw new WorkspaceError('conflict', 'slug_taken') + } + await db + .prepare( + `INSERT INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (account_id) DO UPDATE SET slug = excluded.slug, updated_at = excluded.updated_at` + ) + .bind(caller.accountId, slug, now, caller.userId, now) + .run() + .catch((error: unknown) => { + // The UNIQUE index lost a race with another org claiming the same slug. + if (String(error).includes('UNIQUE')) { + throw new WorkspaceError('conflict', 'slug_taken') + } + throw error + }) + return { slug, orgId } +} diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index 14ec858457b..64a5c48b88a 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -71,6 +71,8 @@ export type SandboxRow = { last_activity_at: number | null last_activity_by: string | null token_usd_micros: number | null + /** 0051: this workspace's number in its account (shown as W-123); null only on rows from before it. */ + number?: number | null } export type WorkspaceVisibility = 'private' | 'team' @@ -118,18 +120,28 @@ export async function insertSandbox( Partial>, now: number ): Promise { - await db - .prepare( - `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, - machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id, - source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by) - VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` - ) - .bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name, - row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null, - row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null, - row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id) - .run() + // One transaction: bump the account's counter, then take its value as this row's number (W-123). + // A failed insert rolls the bump back; a destroyed row keeps its number, so none is ever reused. + await db.batch([ + db + .prepare( + `INSERT INTO org_workspace_counters (account_id, last_number) VALUES (?, 1) + ON CONFLICT (account_id) DO UPDATE SET last_number = last_number + 1` + ) + .bind(row.account_id), + db + .prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, + machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id, + source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by, number) + VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + (SELECT last_number FROM org_workspace_counters WHERE account_id = ?))` + ) + .bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name, + row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null, + row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null, + row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id, row.account_id) + ]) const inserted = await getSandbox(db, row.id) if (!inserted) { throw new Error('sandbox insert lost') diff --git a/cloud/apps/sandbox-control/src/workspace-prefs.ts b/cloud/apps/sandbox-control/src/workspace-prefs.ts new file mode 100644 index 00000000000..49fca99c3d0 --- /dev/null +++ b/cloud/apps/sandbox-control/src/workspace-prefs.ts @@ -0,0 +1,86 @@ +// A member's own sidebar arrangement of cloud workspaces, stored on the account so every device +// (desktops and the phone) shows the same pins, order and sections. +// GET /v1/team/prefs -> {document, revision, updatedAt} +// PUT /v1/team/prefs {document, revision} `revision` is the one the client edited (compare-and-set: +// a stale write gets 409 and the client re-applies its edit) +// Per member, per account: switching teams switches arrangements. Ids that no longer exist are +// harmless (clients skip them) and are dropped the next time that client writes. +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { WorkspaceError } from './workspaces' + +const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/) +const SectionName = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/) + +const unique = (list: readonly string[]) => new Set(list).size === list.length + +export const WorkspacePrefsDocumentSchema = z + .object({ + /** Pinned workspaces, top to bottom. */ + pinned: z.array(SandboxId).max(200).refine(unique, 'duplicate id'), + /** Manual order of the rest (drag to reorder); workspaces not listed follow, newest first. */ + order: z.array(SandboxId).max(500).refine(unique, 'duplicate id'), + /** Section order, including sections that are empty right now. */ + sections: z.array(SectionName).max(50).refine(unique, 'duplicate section'), + /** Sections this member keeps collapsed. */ + collapsed: z.array(SectionName).max(50).refine(unique, 'duplicate section') + }) + .strict() + .refine((doc) => !doc.pinned.some((id) => doc.order.includes(id)), 'pinned ids stay out of order') + +export type WorkspacePrefsDocument = z.infer + +const PutSchema = z + .object({ + document: WorkspacePrefsDocumentSchema, + revision: z.number().int().min(0), + /** Which device wrote it (a label for debugging sync, never trusted for access). */ + deviceId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() + }) + .strict() + +export const EMPTY_PREFS: WorkspacePrefsDocument = { pinned: [], order: [], sections: [], collapsed: [] } + +type Row = { document: string; revision: number; updated_at: number } + +export async function getWorkspacePrefs(db: D1Database, caller: SandboxCaller) { + const row = await db + .prepare('SELECT document, revision, updated_at FROM workspace_prefs WHERE account_id = ? AND user_id = ?') + .bind(caller.accountId, caller.userId) + .first() + if (!row) { + return { document: EMPTY_PREFS, revision: 0, updatedAt: null } + } + // A document from a newer schema parses leniently: unknown keys are ignored, bad ones reset. + const parsed = WorkspacePrefsDocumentSchema.safeParse(JSON.parse(row.document)) + return { document: parsed.success ? parsed.data : EMPTY_PREFS, revision: row.revision, updatedAt: row.updated_at } +} + +export async function putWorkspacePrefs(db: D1Database, caller: SandboxCaller, body: unknown, now: number) { + const parsed = PutSchema.safeParse(body) + if (!parsed.success) { + throw new WorkspaceError('invalid_request') + } + const { document, revision, deviceId } = parsed.data + const text = JSON.stringify(document) + const result = + revision === 0 + ? await db + .prepare( + `INSERT OR IGNORE INTO workspace_prefs (account_id, user_id, document, revision, updated_at, updated_by_device) + VALUES (?, ?, ?, 1, ?, ?)` + ) + .bind(caller.accountId, caller.userId, text, now, deviceId ?? null) + .run() + : await db + .prepare( + `UPDATE workspace_prefs SET document = ?, revision = revision + 1, updated_at = ?, updated_by_device = ? + WHERE account_id = ? AND user_id = ? AND revision = ?` + ) + .bind(text, now, deviceId ?? null, caller.accountId, caller.userId, revision) + .run() + if (result.meta.changes !== 1) { + throw new WorkspaceError('conflict', 'stale_revision') + } + return getWorkspacePrefs(db, caller) +} diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 0e1480c8b29..28664ab1184 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -4,7 +4,7 @@ // GET /v1/team/workspaces/:id // PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?} // POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?} -// GET /v1/team/links/resolve?w=&c= +// GET /v1/team/links/resolve?w=&c= or ?org=&n=&c= // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a // departed member's workspaces can be reassigned or archived — metadata only, never access. @@ -16,6 +16,7 @@ import { memberNamesFor } from './member-names' import { recordTokenSpend } from './member-usage' import { readSnapshotTimes } from './read-snapshots' import { sandboxView } from './wire' +import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs' import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' export const PRESENCE_TTL_MS = 45_000 @@ -171,11 +172,12 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted, readAt] = await Promise.all([ + const [presence, compute, granted, readAt, slug] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), activeGrantUsers(db, ids, caller.userId), - readSnapshotTimes(db, ids) + readSnapshotTimes(db, ids), + rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null) ]) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( @@ -197,6 +199,10 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows return { ...sandboxView(row), title: row.name, + // W-123 in its account; null only for a row that predates numbering and was never backfilled. + number: row.number ?? null, + // The link to copy: org slug + number when both exist, else the sandbox id form. + link: workspaceLink(row, slug), repo: repoView(row), visibility: row.visibility, section: row.section, @@ -425,27 +431,56 @@ export async function reportPresence( return { presence: view!.presence } } -const LinkQuery = z.object({ - w: z.string().regex(/^sbx_[0-9a-f]{24}$/), - c: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() -}) +const ChatParam = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() +const LinkQuery = z.union([ + z.object({ w: z.string().regex(/^sbx_[0-9a-f]{24}$/), c: ChatParam }), + z.object({ org: z.string().min(1).max(40), n: z.coerce.number().int().min(1).max(1e9), c: ChatParam }) +]) -/** orca://cloud/w/[/c/] → the workspace if the caller can see it; otherwise not_found. */ +/** A slug link that names a different org than the caller's current one. */ +export class LinkOtherOrgError extends WorkspaceError { + constructor(readonly orgId: string | null) { + super('not_found', 'other_org') + } +} + +/** + * orca://cloud/w/[/c/] or orca://cloud//W-[/c/] → the workspace if the caller + * can see it; otherwise not_found. A slug link for another org answers not_found with reason + * `other_org` and that org's id, so a client that belongs to it can offer to switch teams. + */ export async function resolveLink(db: D1Database, caller: SandboxCaller, url: URL, now: number) { const query = LinkQuery.safeParse(Object.fromEntries(url.searchParams)) if (!query.success) { throw new WorkspaceError('invalid_request') } - const row = await getSandbox(db, query.data.w) + const q = query.data + let row: SandboxRow | null + if ('w' in q) { + row = await getSandbox(db, q.w) + } else { + const accountId = await accountForSlug(db, q.org) + if (!accountId) { + throw new WorkspaceError('not_found') + } + if (accountId !== caller.accountId) { + throw new LinkOtherOrgError(orgIdOf(accountId)) + } + row = await db + .prepare('SELECT * FROM sandboxes WHERE account_id = ? AND number = ?') + .bind(accountId, q.n) + .first() + } if (!row || !canSee(caller, row)) { // Private, other org, or gone: the link reveals nothing about which. throw new WorkspaceError('not_found') } const [view] = await workspaceViews(db, caller, [row], now) - return { workspace: view, chatId: query.data.c ?? null } + return { workspace: view, chatId: q.c ?? null } } /** Canonical deep link for a workspace (and optionally a chat in it). */ -export function workspaceLink(id: string, chatId?: string): string { - return `orca://cloud/w/${id}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}` +export function workspaceLink(row: Pick, slug: string | null, chatId?: string): string { + const chat = chatId ? `/c/${encodeURIComponent(chatId)}` : '' + return slug && row.number ? `orca://cloud/${slug}/W-${row.number}${chat}` : `orca://cloud/w/${row.id}${chat}` } diff --git a/cloud/apps/sandbox-control/test/team-presence.test.ts b/cloud/apps/sandbox-control/test/team-presence.test.ts index c8e0c256ddd..8a47fe8e2f7 100644 --- a/cloud/apps/sandbox-control/test/team-presence.test.ts +++ b/cloud/apps/sandbox-control/test/team-presence.test.ts @@ -180,3 +180,18 @@ describe('pokes', () => { expect((await t.req(solo, 'GET', '/v1/team/pokes')).body).toEqual({ enabled: false, pokes: [] }) }) }) + +describe('member-removed token', () => { + it('authorizes only POST /v1/internal/org-members/removed, never other operator routes', async () => { + const MR = 'm'.repeat(40) + const body = { accountId: 'org:acme', userId: 'bob' } + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: MR }) + expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: MR, body })).status).toBe(200) + expect((await h.call('GET', '/v1/internal/status', { bearer: MR })).status).toBe(404) + expect((await h.call('POST', '/v1/internal/members/removed', { bearer: MR, body })).status).toBe(404) + // The operator token still works on the route; a short token is never accepted. + expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body })).status).toBe(200) + const weak = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: 'short' }) + expect((await weak.call('POST', '/v1/internal/org-members/removed', { bearer: 'short', body })).status).toBe(404) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts new file mode 100644 index 00000000000..270c1d2be83 --- /dev/null +++ b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts @@ -0,0 +1,175 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { isValidSlug, slugify } from '../src/org-slugs' +import { createHarness } from './harness' + +type Role = 'owner' | 'admin' | 'member' +type Who = { sub: string; org?: string; role: Role } + +async function setup() { + const h = await createHarness() + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', who.org ? { org_role: who.role } : {}), body }) + let n = 0 + const create = async (who: Who, extra: Record = {}) => { + n += 1 + const res = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${n}`, machineSize: 'standard', ...extra }) + expect(res.status).toBe(200) + return res.body.sandbox.id as string + } + const alice: Who = { sub: 'alice', org: 'acme', role: 'member' } + const bob: Who = { sub: 'bob', org: 'acme', role: 'member' } + const admin: Who = { sub: 'carol', org: 'acme', role: 'admin' } + const eve: Who = { sub: 'eve', org: 'other', role: 'owner' } + const solo: Who = { sub: 'sam', role: 'member' } + return { h, req, create, alice, bob, admin, eve, solo } +} + +describe('workspace numbers (W-123)', () => { + it('numbers workspaces per account and never reuses a number', async () => { + const t = await setup() + const a1 = await t.create(t.alice) + const a2 = await t.create(t.bob, { visibility: 'team' }) + const e1 = await t.create(t.eve) + const view = async (who: Who, id: string) => (await t.req(who, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + expect((await view(t.alice, a1)).number).toBe(1) + expect((await view(t.bob, a2)).number).toBe(2) + expect((await view(t.eve, e1)).number).toBe(1) + expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${a1}`)).status).toBe(200) + const a3 = await t.create(t.alice) + expect((await view(t.alice, a3)).number).toBe(3) + }) + + it('backfills existing rows by creation order and seeds the counter', () => { + const raw = new DatabaseSync(':memory:') + const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href) + const files = readdirSync(dir).filter((f) => f.endsWith('.sql')).sort() + const at = files.indexOf('0051_workspace_numbers_prefs.sql') + for (const file of files.slice(0, at)) { + raw.exec(readFileSync(`${dir}${file}`, 'utf8')) + } + const insert = raw.prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region, + generation, created_at, updated_at) VALUES (?, ?, 'u', ?, 'vercel', ?, 'destroyed', 'standard', 'iad1', 0, ?, ?)` + ) + insert.run('sbx_b', 'org:a', 'w2', 'p2', 20, 20) + insert.run('sbx_a', 'org:a', 'w1', 'p1', 10, 10) + insert.run('sbx_c', 'org:a', 'w3', 'p3', 20, 20) + insert.run('sbx_z', 'org:b', 'w1', 'pz', 5, 5) + for (const file of files.slice(at)) { + raw.exec(readFileSync(`${dir}${file}`, 'utf8')) + } + expect(raw.prepare('SELECT id, number FROM sandboxes ORDER BY id').all()).toEqual([ + { id: 'sbx_a', number: 1 }, + { id: 'sbx_b', number: 2 }, + { id: 'sbx_c', number: 3 }, + { id: 'sbx_z', number: 1 } + ]) + expect(raw.prepare('SELECT * FROM org_workspace_counters ORDER BY account_id').all()).toEqual([ + { account_id: 'org:a', last_number: 3 }, + { account_id: 'org:b', last_number: 1 } + ]) + }) +}) + +describe('org slugs', () => { + it('slugifies names and refuses reserved or malformed slugs', () => { + expect(slugify('Acme Labs, Inc.')).toBe('acme-labs-inc') + expect(slugify('Ünïcode Crew')).toBe('unicode-crew') + expect(slugify('!!!')).toBe('team') + expect(slugify('w')).toBe('w-team') + expect(isValidSlug('acme')).toBe(true) + expect(isValidSlug('w')).toBe(false) + expect(isValidSlug('-acme')).toBe(false) + expect(isValidSlug('a--b')).toBe(false) + expect(isValidSlug('Acme')).toBe(false) + }) + + it('names an org once from the first name it hears, uniquely across orgs', async () => { + const t = await setup() + expect((await t.req(t.alice, 'GET', '/v1/team/org')).body).toEqual({ slug: null, orgId: 'acme' }) + expect((await t.req(t.alice, 'GET', '/v1/team/org?name=Acme%20Labs')).body).toEqual({ slug: 'acme-labs', orgId: 'acme' }) + // A teammate whose client shows another name still gets the org's slug. + expect((await t.req(t.bob, 'GET', '/v1/team/org?name=Whatever')).body.slug).toBe('acme-labs') + expect((await t.req(t.eve, 'GET', '/v1/team/org?name=Acme%20Labs')).body.slug).toBe('acme-labs-2') + expect((await t.req(t.solo, 'GET', '/v1/team/org?name=Sam')).body).toEqual({ slug: null, orgId: null }) + }) + + it('lets only admins rename, and not onto another org', async () => { + const t = await setup() + await t.req(t.alice, 'GET', '/v1/team/org?name=Acme') + await t.req(t.eve, 'GET', '/v1/team/org?name=Other') + expect((await t.req(t.alice, 'PUT', '/v1/team/org', { slug: 'acme-co' })).status).toBe(403) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'other' })).status).toBe(409) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'w' })).status).toBe(400) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'acme-co' })).body).toEqual({ slug: 'acme-co', orgId: 'acme' }) + expect((await t.req(t.bob, 'GET', '/v1/team/org')).body.slug).toBe('acme-co') + }) +}) + +describe('slug links', () => { + it('copies org slug links and resolves them only for those who can see the workspace', async () => { + const t = await setup() + const id = await t.create(t.alice) + const before = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + // No slug yet: the id form still works. + expect(before.link).toBe(`orca://cloud/w/${id}`) + await t.req(t.alice, 'GET', '/v1/team/org?name=Acme') + const after = (await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0] + expect(after.link).toBe('orca://cloud/acme/W-1') + + const resolved = await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=1&c=s:abc') + expect(resolved.status).toBe(200) + expect(resolved.body).toMatchObject({ workspace: { id, number: 1 }, chatId: 's:abc' }) + // Private to Alice: Bob sees nothing until she shares it. + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).status).toBe(404) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).body.workspace.id).toBe(id) + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=2')).status).toBe(404) + // Another org: not found, but says which org so a member of both can switch. + const other = await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=acme&n=1') + expect(other.status).toBe(404) + expect(other.body).toEqual({ error: 'not_found', reason: 'other_org', orgId: 'acme' }) + expect((await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=nope&n=1')).body).toEqual({ error: 'not_found' }) + expect((await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=0')).status).toBe(400) + }) +}) + +describe('workspace prefs (synced pins and order)', () => { + const A = `sbx_${'a'.repeat(24)}` + const B = `sbx_${'b'.repeat(24)}` + + it('stores one document per member and account with compare-and-set', async () => { + const t = await setup() + expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body).toEqual({ + document: { pinned: [], order: [], sections: [], collapsed: [] }, + revision: 0, + updatedAt: null + }) + const doc = { pinned: [A], order: [B], sections: ['Auth', 'Billing'], collapsed: ['Billing'] } + const first = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: doc, revision: 0, deviceId: 'desk-1' }) + expect(first.status).toBe(200) + expect(first.body).toMatchObject({ document: doc, revision: 1 }) + // A second device that still holds revision 0 must re-read before writing. + const stale = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [] }, revision: 0 }) + expect(stale.status).toBe(409) + const second = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [B, A], order: [] }, revision: 1 }) + expect(second.body.revision).toBe(2) + expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body.document.pinned).toEqual([B, A]) + // Teammates and other accounts have their own. + expect((await t.req(t.bob, 'GET', '/v1/team/prefs')).body.revision).toBe(0) + expect((await t.req({ ...t.alice, org: 'other' }, 'GET', '/v1/team/prefs')).body.revision).toBe(0) + expect((await t.req(t.solo, 'PUT', '/v1/team/prefs', { document: doc, revision: 0 })).status).toBe(200) + }) + + it('rejects malformed documents', async () => { + const t = await setup() + const put = (document: unknown) => t.req(t.alice, 'PUT', '/v1/team/prefs', { document, revision: 0 }) + expect((await put({ pinned: [A], order: [A], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: [A, A], order: [], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: ['nope'], order: [], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: [], order: [], sections: ['x'], collapsed: [], extra: 1 })).status).toBe(400) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 99cd7abebfc..881006ae296 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -443,7 +443,7 @@ describe('desktop wire contract', () => { ).body ) wire.CloudWorkspaceGrantListSchema.parse((await t.req(t.bob, 'GET', `/v1/team/workspaces/${t.id}/grants`)).body) - expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ workspaceId: t.id, chatId: 'chat 1' }) + expect(wire.parseCloudWorkspaceLink(wire.cloudWorkspaceLink(t.id, 'chat 1'))).toEqual({ target: { kind: 'id', workspaceId: t.id }, chatId: 'chat 1' }) expect(issued.grant.status).toBe('active') }) diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index abfae50fd7f..d6960e64ae5 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -188,6 +188,13 @@ "dynamic": false, "count": 1 }, + { + "filePath": "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts", + "kind": "object-property:accessibilityLabel", + "text": "Cloud workspace number", + "dynamic": false, + "count": 1 + }, { "filePath": "src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx", "kind": "jsx-attribute:title", diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index ff125bd74d6..107660aeac1 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -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 diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 494a66abf56..28090cb988c 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -230,6 +230,7 @@ export default function RootLayout() { + /W-123, the desktop's "Copy link") open here. */ +export default function CloudWorkspaceNumberLinkRoute() { + const t = useMobileTranslation() + const router = useRouter() + const params = useLocalSearchParams<{ org?: string; number?: string }>() + const link = `orca://cloud/${params.org ?? ''}/${params.number ?? ''}` + const [resolved, setResolved] = useState({ kind: 'loading' }) + useEffect(() => { + let live = true + const parsed = parseCloudWorkspaceLink(link) + void (async () => { + const plane = parsed ? await loadCloudControlPlane() : null + const sandboxId = + plane && parsed ? await resolveCloudWorkspaceLink(plane, parsed.target) : null + if (live) { + setResolved(sandboxId ? { kind: 'found', sandboxId } : { kind: 'missing' }) + } + })().catch(() => live && setResolved({ kind: 'missing' })) + return () => { + live = false + } + }, [link]) + if (resolved.kind === 'found') { + return + } + return ( + + {resolved.kind === 'loading' ? ( + + ) : ( + router.replace('/') }} + /> + )} + + ) +} diff --git a/mobile/src/cloud/CloudWorkspaceActions.tsx b/mobile/src/cloud/CloudWorkspaceActions.tsx index fd876698b39..1ff6df5822b 100644 --- a/mobile/src/cloud/CloudWorkspaceActions.tsx +++ b/mobile/src/cloud/CloudWorkspaceActions.tsx @@ -1,4 +1,4 @@ -import { Archive, Moon } from 'lucide-react-native' +import { Archive, Moon, Pin, PinOff } from 'lucide-react-native' import { useState } from 'react' import { View } from 'react-native' import { ConfirmModal } from '../components/ConfirmModal' @@ -8,6 +8,41 @@ import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import type { CloudWorkspace } from './cloud-control-plane-client' import { cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles' +import { useCloudWorkspacePrefs } from './cloud-workspace-prefs' +import { useCloudEnrollment } from './use-cloud-workspaces' +import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement' + +/** Pin to the top of the Cloud list on every device of yours (your own pins, not the team's). */ +function CloudWorkspacePinRow(props: { workspace: CloudWorkspace }) { + const t = useMobileTranslation() + const enrollment = useCloudEnrollment() + const prefs = useCloudWorkspacePrefs(enrollment?.deviceSessionId ?? null) + const [busy, setBusy] = useState(false) + if (!enrollment || props.workspace.status === 'archived') { + return null + } + const pinned = prefs.document.pinned.includes(props.workspace.id) + const Icon = pinned ? PinOff : Pin + return ( + + + } + title={pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top')} + subtitle={t('cloud.actions.pinCaption', 'On all your devices. Only you see your pins.')} + busy={busy} + onPress={() => { + setBusy(true) + void prefs + .edit((doc) => setPinned(doc, props.workspace.id, !pinned)) + .finally(() => setBusy(false)) + }} + /> + + + ) +} /** Sleep (no sandbox hours, files kept) and Archive, each behind a confirm because both stop agents. */ export function CloudWorkspaceActions(props: { @@ -29,6 +64,7 @@ export function CloudWorkspaceActions(props: { const running = props.workspace.status === 'running' return ( <> + {running ? ( diff --git a/mobile/src/cloud/cloud-control-plane-client.ts b/mobile/src/cloud/cloud-control-plane-client.ts index 33043dc67d0..529e76670b7 100644 --- a/mobile/src/cloud/cloud-control-plane-client.ts +++ b/mobile/src/cloud/cloud-control-plane-client.ts @@ -47,6 +47,9 @@ export type CloudWorkspace = { createdByUserId: string | null /** When the last sleeping read snapshot was stored (ms); null when none or unknown. */ readSnapshotAt: number | null + /** Its number in the account (W-123); absent on older control planes and the owner-only list. */ + number?: number | null + section?: string | null } const SANDBOX_STATUS: Record = { creating: 'creating', @@ -99,7 +102,9 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace { lastActivityAt: row.lastActivityAt, sandboxMs: row.cost.computeMs, createdByUserId: row.createdBy, - readSnapshotAt: row.readSnapshotAt ?? null + readSnapshotAt: row.readSnapshotAt ?? null, + number: row.number ?? null, + section: row.section } } diff --git a/mobile/src/cloud/cloud-workspace-prefs.test.ts b/mobile/src/cloud/cloud-workspace-prefs.test.ts new file mode 100644 index 00000000000..3e835be9771 --- /dev/null +++ b/mobile/src/cloud/cloud-workspace-prefs.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from 'vitest' +import { z } from 'zod' + +vi.mock('./cloud-session', () => ({ loadCloudControlPlane: vi.fn() })) + +import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement' +import { editCloudWorkspacePrefsOn, resolveCloudWorkspaceLink } from './cloud-workspace-prefs' +import type { CloudControlPlane } from './cloud-control-plane-request' + +const PutBody = z.object({ + document: z.object({ + pinned: z.array(z.string()), + order: z.array(z.string()), + sections: z.array(z.string()), + collapsed: z.array(z.string()) + }), + revision: z.number() +}) + +const A = `sbx_${'a'.repeat(24)}` +const B = `sbx_${'b'.repeat(24)}` + +function plane(handler: (method: string, url: URL, body: unknown) => [number, unknown]) { + const calls: string[] = [] + const fetchFn: typeof fetch = async (input, init = {}) => { + const url = new URL(String(input)) + calls.push(`${init.method} ${url.pathname}${url.search}`) + const [status, body] = handler( + init.method ?? 'GET', + url, + init.body ? JSON.parse(String(init.body)) : undefined + ) + return new Response(JSON.stringify(body), { status }) + } + const p: CloudControlPlane = { baseUrl: 'https://cp.example', token: () => 't', fetch: fetchFn } + return { plane: p, calls } +} + +describe('phone prefs sync', () => { + it('re-applies a pin on top of a desktop that wrote first', async () => { + let server: z.infer = { + document: { pinned: [B], order: [], sections: [], collapsed: [] }, + revision: 3 + } + let firstPut = true + const { plane: p, calls } = plane((method, _url, body) => { + if (method === 'GET') { + return [200, { ...server, updatedAt: 1 }] + } + const put = PutBody.parse(body) + if (firstPut) { + // A desktop wrote between our read and our write. + firstPut = false + server = { ...server, revision: 4 } + return [409, { error: 'conflict', reason: 'stale_revision' }] + } + expect(put.revision).toBe(4) + server = { document: put.document, revision: 5 } + return [200, { ...server, updatedAt: 2 }] + }) + const saved = await editCloudWorkspacePrefsOn(p, (doc) => setPinned(doc, A, true)) + expect(saved.document.pinned).toEqual([B, A]) + expect(calls).toEqual([ + 'GET /v1/team/prefs', + 'PUT /v1/team/prefs', + 'GET /v1/team/prefs', + 'PUT /v1/team/prefs' + ]) + }) + + it('resolves number links and treats not found as null', async () => { + const { plane: p, calls } = plane((_method, url) => + url.searchParams.get('n') === '7' + ? [200, { workspace: { id: A }, chatId: null }] + : [404, { error: 'not_found' }] + ) + await expect( + resolveCloudWorkspaceLink(p, { kind: 'number', org: 'acme', number: 8 }) + ).resolves.toBeNull() + expect(calls).toEqual(['GET /v1/team/links/resolve?org=acme&n=8']) + await expect(resolveCloudWorkspaceLink(p, { kind: 'id', workspaceId: B })).resolves.toBe(B) + }) +}) diff --git a/mobile/src/cloud/cloud-workspace-prefs.ts b/mobile/src/cloud/cloud-workspace-prefs.ts new file mode 100644 index 00000000000..fd2259d8e0f --- /dev/null +++ b/mobile/src/cloud/cloud-workspace-prefs.ts @@ -0,0 +1,125 @@ +// The phone's side of synced cloud workspace prefs (/v1/team/prefs): the same pins and order as +// the member's desktops, read and written with the phone's own device-signed token, and W-number +// links (orca://cloud//W-123) resolved to a workspace. +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { useCallback } from 'react' +import { + CloudWorkspaceLinkResponseSchema, + CloudWorkspacePrefsSchema, + EMPTY_CLOUD_WORKSPACE_PREFS, + type CloudWorkspaceLinkTarget, + type CloudWorkspacePrefs, + type CloudWorkspacePrefsDocument +} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire' +import { + CloudRequestError, + cloudRequest as request, + type CloudControlPlane +} from './cloud-control-plane-request' +import { loadCloudControlPlane } from './cloud-session' + +const MAX_ATTEMPTS = 4 + +export function getCloudWorkspacePrefs( + plane: CloudControlPlane, + signal?: AbortSignal +): Promise { + return request(plane, 'GET', '/v1/team/prefs', CloudWorkspacePrefsSchema, { signal }) +} + +/** + * Applies `edit` to the newest server copy and writes it with compare-and-set; when a desktop wrote + * first it re-reads and applies the same edit again. + */ +export async function editCloudWorkspacePrefsOn( + plane: CloudControlPlane, + edit: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument +): Promise { + let current = await getCloudWorkspacePrefs(plane) + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) { + const next = edit(current.document) + if (next === current.document) { + return current + } + try { + return await request(plane, 'PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, { + body: { document: next, revision: current.revision } + }) + } catch (error) { + if (!(error instanceof CloudRequestError) || error.code !== 'conflict') { + throw error + } + current = await getCloudWorkspacePrefs(plane) + } + } + throw new CloudRequestError('conflict', 409, 'stale_revision') +} + +/** Either link form → the workspace's sandbox id (null when this account can't see it). */ +export async function resolveCloudWorkspaceLink( + plane: CloudControlPlane, + target: CloudWorkspaceLinkTarget +): Promise { + if (target.kind === 'id') { + return target.workspaceId + } + const params = new URLSearchParams({ org: target.org, n: String(target.number) }) + try { + const body = await request( + plane, + 'GET', + `/v1/team/links/resolve?${params}`, + CloudWorkspaceLinkResponseSchema + ) + return body.workspace.id + } catch (error) { + if (error instanceof CloudRequestError && error.status === 404) { + return null + } + throw error + } +} + +export const cloudWorkspacePrefsQueryKey = (sessionId: string | null) => + ['orca-cloud', 'prefs', sessionId] as const + +/** This member's synced prefs and an edit that saves them (shown at once, rolled back on failure). */ +export function useCloudWorkspacePrefs(sessionId: string | null) { + const client = useQueryClient() + const query = useQuery({ + queryKey: cloudWorkspacePrefsQueryKey(sessionId), + enabled: sessionId !== null, + queryFn: async ({ signal }) => { + const plane = await loadCloudControlPlane() + return plane + ? (await getCloudWorkspacePrefs(plane, signal)).document + : EMPTY_CLOUD_WORKSPACE_PREFS + }, + // Desktops edit it too; pick their edits up whenever Home is in front. + refetchInterval: 15_000, + staleTime: 5_000 + }) + const edit = useCallback( + async (change: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument) => { + const key = cloudWorkspacePrefsQueryKey(sessionId) + const previous = client.getQueryData(key) + client.setQueryData(key, (doc) => + change(doc ?? EMPTY_CLOUD_WORKSPACE_PREFS) + ) + try { + const plane = await loadCloudControlPlane() + if (!plane) { + throw new CloudRequestError('not_enrolled', 0) + } + const saved = await editCloudWorkspacePrefsOn(plane, change) + client.setQueryData(key, saved.document) + return true + } catch { + client.setQueryData(key, previous) + return false + } + }, + [client, sessionId] + ) + return { document: query.data ?? EMPTY_CLOUD_WORKSPACE_PREFS, edit } +} diff --git a/mobile/src/home/MobileHomeCloudSection.tsx b/mobile/src/home/MobileHomeCloudSection.tsx index 66b154f6125..a6d73053710 100644 --- a/mobile/src/home/MobileHomeCloudSection.tsx +++ b/mobile/src/home/MobileHomeCloudSection.tsx @@ -1,7 +1,7 @@ import { useRouter } from 'expo-router' -import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native' -import { Fragment, useState } from 'react' -import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { ChevronRight, Cloud, Pin, Plus, RotateCw } from 'lucide-react-native' +import { Fragment, useMemo, useState } from 'react' +import { ActivityIndicator, Alert, Pressable, Text, View } from 'react-native' import { CloudStatusDot } from '../cloud/CloudStatusDot' import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection' import type { CloudWorkspace } from '../cloud/cloud-control-plane-client' @@ -10,6 +10,12 @@ import { takeCloudReturnTo } from '../cloud/cloud-return-to' import type { CloudEnrollment } from '../cloud/cloud-device-identity' import { cloudRepoLine, cloudStatusLabel } from '../cloud/cloud-workspace-display' import { useCloudWorkspaces } from '../cloud/use-cloud-workspaces' +import { useCloudWorkspacePrefs } from '../cloud/cloud-workspace-prefs' +import { + arrangeCloudWorkspaces, + setPinned +} from '../../../src/shared/cloud-workspaces/cloud-workspace-arrangement' +import { formatWorkspaceNumber } from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire' import { formatTimeAgo } from '../worktree/agent-row-display' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { colors } from '../theme/mobile-theme' @@ -35,13 +41,43 @@ export function MobileHomeCloudSection(props: { const t = useMobileTranslation() useMobileColorScheme() const query = useCloudWorkspaces(props.enrollment) + // Pins and order are the member's own and sync with their desktops. + const prefs = useCloudWorkspacePrefs(props.enrollment?.deviceSessionId ?? null) + const workspaces = useMemo( + () => + arrangeCloudWorkspaces( + (query.data ?? []).filter((workspace) => workspace.status !== 'archived'), + prefs.document + ).flatMap((group) => + group.rows.map((workspace) => ({ workspace, pinned: group.kind === 'pinned' })) + ), + [query.data, prefs.document] + ) if (props.enrollment === undefined) { return null } if (props.enrollment === null) { return } - const workspaces = (query.data ?? []).filter((workspace) => workspace.status !== 'archived') + const togglePin = (workspace: CloudWorkspace, pinned: boolean) => { + Alert.alert(workspace.title, undefined, [ + { + text: pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top'), + onPress: () => + void prefs + .edit((doc) => setPinned(doc, workspace.id, !pinned)) + .then((saved) => { + if (!saved) { + Alert.alert( + t('cloud.home.pinFailed', 'Couldn’t save that change'), + t('cloud.home.pinFailedDetail', 'Check your connection and try again.') + ) + } + }) + }, + { text: t('common.cancel', 'Cancel'), style: 'cancel' } + ]) + } const now = query.dataUpdatedAt || 0 return ( <> @@ -94,12 +130,14 @@ export function MobileHomeCloudSection(props: { ) : ( - workspaces.map((workspace) => ( + workspaces.map(({ workspace, pinned }) => ( props.onOpenWorkspace(workspace)} + onLongPress={() => togglePin(workspace, pinned)} /> @@ -135,12 +173,16 @@ function SkeletonRow() { function CloudWorkspaceRow({ workspace, + pinned, now, - onPress + onPress, + onLongPress }: { workspace: CloudWorkspace + pinned: boolean now: number onPress: () => void + onLongPress: () => void }) { const t = useMobileTranslation() const status = cloudStatusLabel(workspace.status, t) @@ -175,7 +217,9 @@ function CloudWorkspaceRow({ : createdLine && lastActive - workspace.createdAt < 60_000 ? null : formatTimeAgo(lastActive, reference) - const line = [status, detail, when].filter(Boolean).join(' · ') + const number = workspace.number ? formatWorkspaceNumber(workspace.number) : null + const line = [status, number, detail, when].filter(Boolean).join(' · ') + const optionsLabel = pinned ? t('cloud.home.unpin', 'Unpin') : t('cloud.home.pin', 'Pin to top') return ( { + if (event.nativeEvent.actionName === 'longpress') { + onLongPress() + } + }} style={({ pressed }) => [styles.row, pressed && styles.rowPressed]} onPress={onPress} + onLongPress={onLongPress} + delayLongPress={400} > @@ -204,13 +257,14 @@ function CloudWorkspaceRow({ {status} - {[detail, when] + {[number, detail, when] .filter(Boolean) .map((part) => ` · ${part}`) .join('')} + {pinned ? : null} diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index d3411f6ac91..584bf445524 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -5020,7 +5020,8 @@ "actions": { "sleep": "Sleep", "sleepCaption": "Sandbox hours stop. Files are kept; agents restart when it wakes.", - "archive": "Archive" + "archive": "Archive", + "pinCaption": "On all your devices. Only you see your pins." }, "sleep": { "title": "Sleep {{title}}?", @@ -5122,7 +5123,12 @@ "new": "New cloud workspace", "createdAgo": "Created {{ago}} ago", "createdJustNow": "Created just now", - "workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}" + "workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}", + "unpin": "Unpin", + "pin": "Pin to top", + "pinFailed": "Couldn’t save that change", + "pinFailedDetail": "Check your connection and try again.", + "pinnedHint": "Pinned" }, "connect": { "signedOut": "Sign in to Orca on {{desktop}}, then try again.", @@ -5231,6 +5237,12 @@ "idle": { "sleeps_one": "Sleeps after {{count}} minute idle.", "sleeps_other": "Sleeps after {{count}} minutes idle." + }, + "link": { + "opening": "Opening workspace…", + "missingTitle": "Can’t open this workspace", + "missing": "It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.", + "home": "Go to Home" } } } diff --git a/src/main/agent-config-sync/agent-config-digest.ts b/src/main/agent-config-sync/agent-config-digest.ts new file mode 100644 index 00000000000..798d38cd28a --- /dev/null +++ b/src/main/agent-config-sync/agent-config-digest.ts @@ -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') +} diff --git a/src/main/agent-config-sync/agent-config-roots.ts b/src/main/agent-config-sync/agent-config-roots.ts new file mode 100644 index 00000000000..a97863805b8 --- /dev/null +++ b/src/main/agent-config-sync/agent-config-roots.ts @@ -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, `.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) +} diff --git a/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts b/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts new file mode 100644 index 00000000000..4638368c1d9 --- /dev/null +++ b/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts @@ -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)) +} diff --git a/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts b/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts new file mode 100644 index 00000000000..9cd665f6660 --- /dev/null +++ b/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts @@ -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 = { + '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 + 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() + 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 = 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 } + }) +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts new file mode 100644 index 00000000000..830c47a73a1 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts @@ -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 { + if (!value || typeof value !== 'object') { + return {} + } + const raw = value as Record + 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 + ) +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts new file mode 100644 index 00000000000..d8729ef0ff5 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts @@ -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> { + 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) + : [] + } +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts new file mode 100644 index 00000000000..1d52ae730cb --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts @@ -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() + }) +}) diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts new file mode 100644 index 00000000000..b2aed817bf5 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts @@ -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 + call?: ( + environmentId: string, + method: string, + params: unknown, + timeoutMs: number + ) => Promise + now?: () => number +} + +export type CloudAgentConfigSync = { + isCloudEnvironment(environmentId: string): boolean + getStatus(environmentId: string): Promise + sync(environmentId: string, trigger: 'connect' | 'manual'): Promise + /** Settles once saved preferences are read; getPreferences answers defaults until then. */ + ready: Promise + getPreferences(): CloudAgentConfigSyncPreferences + setPreferences(next: Partial): 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() + const queues = new Map>() + 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 { + 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 { + // 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 { + 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 + } + } +} diff --git a/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts b/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts new file mode 100644 index 00000000000..445995e8815 --- /dev/null +++ b/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts @@ -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']) + }) +}) diff --git a/src/main/agent-config-sync/desktop/local-agent-config-read.ts b/src/main/agent-config-sync/desktop/local-agent-config-read.ts new file mode 100644 index 00000000000..a40626d3993 --- /dev/null +++ b/src/main/agent-config-sync/desktop/local-agent-config-read.ts @@ -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 +} + +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 | 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 { + 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 { + const root = await realpath(dir) + const files: AgentConfigDigestEntry[] = [] + let withheld = 0 + let bytes = 0 + const visit = async (current: string, depth: number): Promise => { + 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 { + return (await stat(path).catch(() => null))?.isDirectory() === true +} + +async function isFile(path: string): Promise { + return (await stat(path).catch(() => null))?.isFile() === true +} + +async function readSkills( + root: string, + kind: AgentConfigItemKind, + scope: AgentConfigItemScope +): Promise { + 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 { + const maxDepth = kind === 'codex-prompt' ? 0 : 2 + const items: LocalAgentConfigItem[] = [] + const visit = async (dir: string, depth: number): Promise => { + 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 => ({ + ...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 { + 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 +} diff --git a/src/main/agent-config-sync/desktop/syncer-id.ts b/src/main/agent-config-sync/desktop/syncer-id.ts new file mode 100644 index 00000000000..11d62650060 --- /dev/null +++ b/src/main/agent-config-sync/desktop/syncer-id.ts @@ -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>() + +async function load(userDataPath: string): Promise { + 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 { + let id = cache.get(userDataPath) + if (!id) { + id = load(userDataPath) + cache.set(userDataPath, id) + } + return id +} diff --git a/src/main/agent-config-sync/host/host-agent-config-ledger.ts b/src/main/agent-config-sync/host/host-agent-config-ledger.ts new file mode 100644 index 00000000000..9242f4c3a46 --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-ledger.ts @@ -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 } + +export function ledgerPath(ledgerDir: string, syncer: string): string { + return join(ledgerDir, `agent-config-sync-ledger-${syncer}.json`) +} + +export async function readLedger(path: string): Promise { + 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 = {} + 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 { + 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 { + 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. + } +} diff --git a/src/main/agent-config-sync/host/host-agent-config-sync.test.ts b/src/main/agent-config-sync/host/host-agent-config-sync.test.ts new file mode 100644 index 00000000000..65f9949217e --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-sync.test.ts @@ -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 = {}) => ({ + 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) + }) +}) diff --git a/src/main/agent-config-sync/host/host-agent-config-sync.ts b/src/main/agent-config-sync/host/host-agent-config-sync.ts new file mode 100644 index 00000000000..81a2c169543 --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-sync.ts @@ -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 { + 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 => { + 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 { + const path = ledgerPath(deps.ledgerDir, params.syncer) + const ledger = await readLedger(path) + const items: Record = {} + const wanted = new Set() + 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() + 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 { + 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 { + const path = ledgerPath(deps.ledgerDir, params.syncer) + const ledger = await readLedger(path) + const items: Record = {} + 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>((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 } +} diff --git a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts index 34056e67a44..da47d8e9391 100644 --- a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts +++ b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts @@ -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 => 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 { diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index 31cf315a419..9d717c1d38d 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -141,7 +141,10 @@ const EntitlementSchema = z.object({ interval: z.enum(ORCA_BILLING_INTERVALS).nullable().catch(null), seats: seconds, seatChange: z - .object({ seatsAtRenewal: z.number().int().min(1), effectiveAt: z.number() }) + .object({ + seatsAtRenewal: z.number().int().min(1), + effectiveAt: z.number() + }) .nullable() .catch(null), period: window, @@ -172,7 +175,13 @@ const EntitlementSchema = z.object({ spentCents: seconds, centsPerHour: seconds }) - .catch({ optedIn: false, active: false, spendCapCents: 0, spentCents: 0, centsPerHour: 0 }), + .catch({ + optedIn: false, + active: false, + spendCapCents: 0, + spentCents: 0, + centsPerHour: 0 + }), payment: z .object({ pastDueSince: z.number().nullable().catch(null), diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index 89d92d3fa96..c150019aa9a 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -11,7 +11,8 @@ import type { OrcaBillingOverageResult, OrcaBillingStatusResult, OrcaBillingTeamPlansResult, - OrcaBillingTrialClaimResult + OrcaBillingTrialClaimResult, + OrcaBillingUsageHistoryResult } from '../../shared/orca-billing' import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh' @@ -28,6 +29,7 @@ import { type BillingEndpoints } from './billing-client' import { getBillingEndpoints } from './billing-config' +import { fetchUsageHistory } from './billing-usage-client' import { getBillingDevKeyFile, mintDevBillingToken } from './billing-dev-token' import { cleanCloudServiceUrl } from '../../shared/cloud-service-url' import { listOrcaProfileOrgMembers } from '../orca-profiles/profile-cloud-org-members-service' @@ -55,7 +57,10 @@ function prepareDev(userDataPath: string, keyFile: string): Ready { if (!cloud) { return { ok: false, status: 'signed-out' } } - const endpoints: BillingEndpoints = { billingApiUrl, billingTokenEndpoint: billingApiUrl } + const endpoints: BillingEndpoints = { + billingApiUrl, + billingTokenEndpoint: billingApiUrl + } return { ok: true, run: async (call) => { @@ -139,6 +144,25 @@ export async function getOrcaBillingStatus(userDataPath: string): Promise { + const ready = prepare(userDataPath) + if (!ready.ok) { + return { status: ready.status } + } + try { + const history = await ready.run((token, endpoints) => + fetchUsageHistory(endpoints, token, utcOffsetMinutes) + ) + return history === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', history } + } catch (error) { + return { status: 'failed', error: message(error) } + } +} + /** Plan state for other teams the signed-in user is on (cloud start B2); never switches teams. */ export async function getOrcaBillingTeamPlans( userDataPath: string, diff --git a/src/main/billing/billing-usage-client.test.ts b/src/main/billing/billing-usage-client.test.ts new file mode 100644 index 00000000000..342838d7cb7 --- /dev/null +++ b/src/main/billing/billing-usage-client.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { fetchUsageHistory } from './billing-usage-client' + +const endpoints = { + billingApiUrl: 'https://billing.example.test', + billingTokenEndpoint: 'https://login.example.test/v1/desktop/auth/billing-token' +} + +type Seen = { url: string; init: RequestInit | undefined } + +function fakeFetch(responses: Record, seen: Seen[] = []): typeof fetch { + return async (input, init) => { + const url = String(input) + seen.push({ url, init }) + const response = responses[url] + if (!response) { + throw new Error(`unexpected ${url}`) + } + return response + } +} + +describe('fetchUsageHistory', () => { + const url = 'https://billing.example.test/v1/billing/usage?utcOffset=-480' + const body = { + days: [{ start: 1, seconds: 3600 }], + totalSeconds: 3600, + yourSeconds: 1800, + members: { top: [{ userId: 'u1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 }, + sandboxes: { top: [{ sandboxId: 'sbx_1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 } + } + + it('sends the local offset and maps both breakdowns to one row shape', async () => { + const seen: Seen[] = [] + const history = await fetchUsageHistory( + endpoints, + 'bt', + -480, + fakeFetch({ [url]: Response.json(body) }, seen) + ) + expect(seen[0]!.init?.method).toBe('GET') + expect(history.members).toEqual({ + top: [{ id: 'u1', seconds: 3600 }], + otherCount: 0, + otherSeconds: 0 + }) + expect(history.sandboxes?.top).toEqual([{ id: 'sbx_1', seconds: 3600 }]) + }) + + it('accepts a member’s view and rejects malformed rows', async () => { + const member = await fetchUsageHistory( + endpoints, + 'bt', + -480, + fakeFetch({ [url]: Response.json({ ...body, members: null, sandboxes: null }) }) + ) + expect(member.members).toBeNull() + await expect( + fetchUsageHistory( + endpoints, + 'bt', + -480, + fakeFetch({ + [url]: Response.json({ + ...body, + members: { top: [{ userId: '