From 46b467d84792d99b5c565e3b443c0964ff4eaba7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:22:39 -0800 Subject: [PATCH 01/26] feat(cloud): workspace numbers (W-123), org slug links and synced sidebar prefs on the control plane (G13, G14) --- .../0051_workspace_numbers_prefs.sql | 40 ++++ cloud/apps/sandbox-control/src/index.ts | 37 +++- cloud/apps/sandbox-control/src/org-slugs.ts | 123 ++++++++++++ cloud/apps/sandbox-control/src/store.ts | 36 ++-- .../sandbox-control/src/workspace-prefs.ts | 86 +++++++++ cloud/apps/sandbox-control/src/workspaces.ts | 59 ++++-- .../test/workspace-numbers-prefs.test.ts | 175 ++++++++++++++++++ 7 files changed, 529 insertions(+), 27 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql create mode 100644 cloud/apps/sandbox-control/src/org-slugs.ts create mode 100644 cloud/apps/sandbox-control/src/workspace-prefs.ts create mode 100644 cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts 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/index.ts b/cloud/apps/sandbox-control/src/index.ts index 8d833367e3e..6723096d443 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -24,7 +24,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, …} @@ -186,7 +187,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, @@ -1480,7 +1484,9 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) url.pathname === '/v1/team/workspaces' || url.pathname.startsWith('/v1/team/workspaces/') || url.pathname === '/v1/team/links/resolve' || - url.pathname === '/v1/team/prompts' + url.pathname === '/v1/team/prompts' || + url.pathname === '/v1/team/prefs' || + url.pathname === '/v1/team/org' ) { const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) if (!caller) { @@ -1818,7 +1824,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..90de39782e2 --- /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']) + +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 f29d0c52e5c..880544bc536 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. @@ -15,6 +15,7 @@ import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './st import { memberNamesFor } from './member-names' 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 @@ -170,11 +171,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( @@ -196,6 +198,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, @@ -368,27 +374,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/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) + }) +}) From 8f28913dbaa81572300ab72aa2d494d54ce23e5f Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:50:22 -0800 Subject: [PATCH 02/26] feat(cloud): W-numbers, org slug links, and pins/order/sections that sync across desktops and the phone (G13, G14) --- cloud/apps/sandbox-control/src/org-slugs.ts | 2 +- mobile/app/_layout.tsx | 1 + mobile/app/cloud/[org]/[number].tsx | 57 ++++++ .../src/cloud/cloud-control-plane-client.ts | 7 +- .../src/cloud/cloud-workspace-prefs.test.ts | 76 ++++++++ mobile/src/cloud/cloud-workspace-prefs.ts | 125 ++++++++++++ mobile/src/home/MobileHomeCloudSection.tsx | 70 ++++++- .../cloud-workspaces-client.ts | 42 +++- .../cloud-workspaces-service.ts | 20 +- src/main/ipc/cloud-workspaces-prefs.ts | 31 +++ src/main/ipc/cloud-workspaces.ts | 14 +- src/preload/api/cloud-workspaces-api.ts | 18 +- src/preload/api/cloud-workspaces-bridge.ts | 8 +- .../src/app-shell/TitlebarMainStrip.tsx | 4 + .../cloud-workspaces/CloudWorkspaceGroup.tsx | 177 +++++++++++++++++ .../CloudWorkspaceNumberChip.tsx | 55 ++++++ .../cloud-workspaces/CloudWorkspaceRow.tsx | 32 ++- .../CloudWorkspaceRowMenu.tsx | 40 +++- .../cloud-workspaces/CloudWorkspacesHome.tsx | 102 +++++----- .../cloud-workspace-identity.ts | 129 +++++++++++++ .../cloud-workspaces/cloud-workspace-links.ts | 52 ++++- .../cloud-workspace-prefs.test.ts | 107 ++++++++++ .../cloud-workspaces/cloud-workspace-prefs.ts | 156 +++++++++++++++ .../cloud-workspaces/cloud-workspace-sync.ts | 126 ++++++++++++ .../cloud-workspaces/open-cloud-workspace.ts | 18 +- .../use-cloud-workspace-arrangement.ts | 140 ++++++++++++++ .../cloud-workspaces/use-cloud-workspaces.ts | 2 + .../use-worktree-jump-palette-worktrees.ts | 10 +- .../worktree-jump-palette-document-index.ts | 13 +- .../worktree-jump-palette-primitives.tsx | 2 + .../lib/orca-cloud/worktree-pin-listeners.ts | 28 +++ .../worktrees/worktree-palette-document.ts | 7 + .../worktrees/worktree-palette-evidence.ts | 16 ++ .../worktrees/worktree-palette-search.test.ts | 17 ++ .../worktree-palette-task-url-result.ts | 3 +- .../worktrees/session/worktree-pin-reveal.ts | 8 + .../preload-api/web-cloud-workspaces-api.ts | 3 + .../cloud-workspace-arrangement.test.ts | 94 +++++++++ .../cloud-workspace-arrangement.ts | 182 ++++++++++++++++++ .../cloud-workspaces/cloud-workspaces-wire.ts | 113 +++++++++-- .../cloud-workspaces/cloud-workspaces.test.ts | 47 ++++- 41 files changed, 2041 insertions(+), 113 deletions(-) create mode 100644 mobile/app/cloud/[org]/[number].tsx create mode 100644 mobile/src/cloud/cloud-workspace-prefs.test.ts create mode 100644 mobile/src/cloud/cloud-workspace-prefs.ts create mode 100644 src/main/ipc/cloud-workspaces-prefs.ts create mode 100644 src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx create mode 100644 src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-identity.ts create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.ts create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-sync.ts create mode 100644 src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts create mode 100644 src/renderer/src/lib/orca-cloud/worktree-pin-listeners.ts create mode 100644 src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts create mode 100644 src/shared/cloud-workspaces/cloud-workspace-arrangement.ts diff --git a/cloud/apps/sandbox-control/src/org-slugs.ts b/cloud/apps/sandbox-control/src/org-slugs.ts index 90de39782e2..dfbc9191883 100644 --- a/cloud/apps/sandbox-control/src/org-slugs.ts +++ b/cloud/apps/sandbox-control/src/org-slugs.ts @@ -9,7 +9,7 @@ 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']) +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])?$/ 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/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..e7a621cbcdb --- /dev/null +++ b/mobile/src/cloud/cloud-workspace-prefs.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest' + +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 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 = vi.fn(async (input: string, init: RequestInit) => { + const url = new URL(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 as unknown as typeof fetch + } + return { plane: p, calls } +} + +describe('phone prefs sync', () => { + it('re-applies a pin on top of a desktop that wrote first', async () => { + let server = { + 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 = body as { document: typeof server.document; revision: number } + 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/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index a3c3c944453..0b63635d515 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -13,7 +13,13 @@ import { CloudWorkspaceListResponseSchema, CloudWorkspacePresenceResponseSchema, CloudWorkspaceResponseSchema, + CloudOrgSlugSchema, + CloudWorkspacePrefsSchema, OrgPromptsSchema, + type CloudOrgSlug, + type CloudWorkspaceLinkTarget, + type CloudWorkspacePrefs, + type CloudWorkspacePrefsDocument, type CloudWorkspaceListQuery, type CloudWorkspacePatch, type OrgPrompts @@ -29,7 +35,9 @@ export class CloudWorkspacesError extends Error { constructor( readonly status: number, readonly code: string, - readonly reason?: string + readonly reason?: string, + /** A slug link for another org (`reason: other_org`) names that org, so a member can switch. */ + readonly orgId?: string ) { super(reason ? `${code}:${reason}` : code) this.name = 'CloudWorkspacesError' @@ -112,7 +120,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption throw new CloudWorkspacesError( response.status, typeof err.error === 'string' ? err.error : 'error', - typeof err.reason === 'string' ? err.reason : undefined + typeof err.reason === 'string' ? err.reason : undefined, + typeof err.orgId === 'string' ? err.orgId.slice(0, 128) : undefined ) } const parsed = schema.safeParse(payload) @@ -204,8 +213,12 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption CloudWorkspaceGrantListSchema.partial().passthrough() ) }, - async resolveLink(workspaceId: string, chatId?: string | null) { - const params = new URLSearchParams({ w: workspaceId }) + async resolveLink(target: CloudWorkspaceLinkTarget, chatId?: string | null) { + const params = new URLSearchParams( + target.kind === 'id' + ? { w: target.workspaceId } + : { org: target.org, n: String(target.number) } + ) if (chatId) { params.set('c', chatId) } @@ -256,6 +269,27 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption }, putOrgPrompts(document: OrgPrompts['document'], revision: number): Promise { return call('PUT', '/v1/team/prompts', OrgPromptsSchema, { document, revision }) + }, + /** This member's synced arrangement (pins, order, sections) for the current account. */ + getPrefs(): Promise { + return call('GET', '/v1/team/prefs', CloudWorkspacePrefsSchema) + }, + /** Compare-and-set: a stale `revision` answers 409 `conflict`; re-read and re-apply. */ + putPrefs( + document: CloudWorkspacePrefsDocument, + revision: number, + deviceId?: string + ): Promise { + return call('PUT', '/v1/team/prefs', CloudWorkspacePrefsSchema, { + document, + revision, + ...(deviceId ? { deviceId } : {}) + }) + }, + /** The org's link slug; `name` (the org name this client shows) names it the first time. */ + getOrgSlug(name?: string | null): Promise { + const qs = name ? `?${new URLSearchParams({ name: name.slice(0, 120) })}` : '' + return call('GET', `/v1/team/org${qs}`, CloudOrgSlugSchema) } } } diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index b11ebde4099..e684685405f 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -5,8 +5,10 @@ import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store import { openSealedGrant } from '../../shared/cloud-workspaces/sealed-grant' import { errorMessage } from '../../shared/error-message' import type { + CloudWorkspaceLinkTarget, CloudWorkspaceListQuery, CloudWorkspacePatch, + CloudWorkspacePrefsDocument, OrgPrompts } from '../../shared/cloud-workspaces/cloud-workspaces-wire' import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter' @@ -28,7 +30,7 @@ const TYPING_HOLD_MS = 6_000 export type CloudWorkspacesResult = | { ok: true; value: T } - | { ok: false; error: string; reason?: string; status?: number } + | { ok: false; error: string; reason?: string; status?: number; orgId?: string } /** Where this desktop already has a cloud workspace locally (owner: the hosted runtime it created). */ export type LocalCloudWorkspace = { @@ -42,7 +44,13 @@ async function wrap(run: () => Promise): Promise> return { ok: true, value: await run() } } catch (error) { if (error instanceof CloudWorkspacesError) { - return { ok: false, error: error.code, reason: error.reason, status: error.status } + return { + ok: false, + error: error.code, + reason: error.reason, + status: error.status, + ...(error.orgId ? { orgId: error.orgId } : {}) + } } return { ok: false, error: 'internal_error', reason: errorMessage(error).slice(0, 200) } } @@ -154,8 +162,12 @@ export function createCloudWorkspacesService(deps: { get: (id: string) => wrap(() => client.get(id)), patch: (id: string, patch: CloudWorkspacePatch) => wrap(async () => (await client.patch(id, patch)).workspace), - resolveLink: (workspaceId: string, chatId?: string | null) => - wrap(() => client.resolveLink(workspaceId, chatId)), + resolveLink: (target: CloudWorkspaceLinkTarget, chatId?: string | null) => + wrap(() => client.resolveLink(target, chatId)), + getPrefs: () => wrap(() => client.getPrefs()), + putPrefs: (document: CloudWorkspacePrefsDocument, revision: number) => + wrap(() => client.putPrefs(document, revision, deps.clientId)), + getOrgSlug: (name?: string | null) => wrap(() => client.getOrgSlug(name)), listGrants: (id: string) => wrap(() => client.listGrants(id)), revokeGrant: (id: string, grantId: string) => wrap(async () => void (await client.revokeGrant(id, grantId))), diff --git a/src/main/ipc/cloud-workspaces-prefs.ts b/src/main/ipc/cloud-workspaces-prefs.ts new file mode 100644 index 00000000000..03cefe190fb --- /dev/null +++ b/src/main/ipc/cloud-workspaces-prefs.ts @@ -0,0 +1,31 @@ +// IPC for synced cloud workspace prefs (pins, order, sections) and the org's link slug. +// Registered with the other cloud workspace handlers; same `not_configured` contract. +import { z } from 'zod' +import { CloudWorkspacePrefsDocumentSchema } from '../../shared/cloud-workspaces/cloud-workspaces-wire' +import type { CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service' + +const NOT_CONFIGURED = { ok: false as const, error: 'not_configured' } +const INVALID = { ok: false as const, error: 'invalid_request' } + +export function registerCloudWorkspacePrefsHandlers( + handle: (channel: string, fn: (args: unknown) => unknown) => void, + getService: () => Promise +): void { + handle('cloudWorkspaces:getPrefs', async () => (await getService())?.getPrefs() ?? NOT_CONFIGURED) + handle('cloudWorkspaces:putPrefs', async (args) => { + const parsed = z + .object({ document: CloudWorkspacePrefsDocumentSchema, revision: z.number().int().min(0) }) + .safeParse(args) + const s = await getService() + return !s + ? NOT_CONFIGURED + : parsed.success + ? s.putPrefs(parsed.data.document, parsed.data.revision) + : INVALID + }) + handle('cloudWorkspaces:getOrgSlug', async (args) => { + const parsed = z.object({ orgName: z.string().max(200).nullable().optional() }).safeParse(args) + const s = await getService() + return !s ? NOT_CONFIGURED : s.getOrgSlug(parsed.success ? parsed.data.orgName : null) + }) +} diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 1aa5060e4aa..523f08b57ab 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -17,11 +17,20 @@ import { } from '../cloud-workspaces/cloud-reader-key-store' import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import { registerCloudWorkspacePrefsHandlers } from './cloud-workspaces-prefs' import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/) const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/) const ChatId = z.string().min(1).max(256) +const LinkTarget = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('id'), workspaceId: Id }), + z.object({ + kind: z.literal('number'), + org: z.string().regex(/^[a-z0-9-]{1,40}$/), + number: z.number().int().min(1).max(999_999_999) + }) +]) const ListQuery = z .object({ scope: z.enum(['mine', 'team', 'all']).optional(), @@ -215,13 +224,13 @@ export function registerCloudWorkspacesHandlers(): void { }) handle('cloudWorkspaces:resolveLink', async (args) => { const parsed = z - .object({ workspaceId: Id, chatId: ChatId.nullable().optional() }) + .object({ target: LinkTarget, chatId: ChatId.nullable().optional() }) .safeParse(args) const s = await getService() return !s ? NOT_CONFIGURED : parsed.success - ? s.resolveLink(parsed.data.workspaceId, parsed.data.chatId) + ? s.resolveLink(parsed.data.target, parsed.data.chatId) : INVALID }) handle('cloudWorkspaces:openGrant', async (args) => { @@ -305,6 +314,7 @@ export function registerCloudWorkspacesHandlers(): void { ? s.putOrgPrompts(parsed.data.document, parsed.data.revision) : INVALID }) + registerCloudWorkspacePrefsHandlers(handle, getService) // Handlers are re-registered per main window; the quit hook must only be added once. if (!quitHookInstalled) { quitHookInstalled = true diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 3b2f55788dc..cf48b1d8288 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -1,15 +1,19 @@ import type { CloudWorkspace, CloudWorkspaceGrant, + CloudOrgSlug, + CloudWorkspaceLinkTarget, CloudWorkspaceListQuery, CloudWorkspacePatch, + CloudWorkspacePrefs, + CloudWorkspacePrefsDocument, OrgPrompts } from '../../shared/cloud-workspaces/cloud-workspaces-wire' import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' export type CloudWorkspacesResult = | { ok: true; value: T } - | { ok: false; error: string; reason?: string; status?: number } + | { ok: false; error: string; reason?: string; status?: number; orgId?: string } export type LocalCloudWorkspace = { sandboxId: string @@ -26,8 +30,9 @@ export type CloudWorkspacesApi = { list: (query: CloudWorkspaceListQuery) => Promise> get: (id: string) => Promise> patch: (id: string, patch: CloudWorkspacePatch) => Promise> + /** Resolves either link form; a slug link for another org fails with reason `other_org` and its `orgId`. */ resolveLink: ( - workspaceId: string, + target: CloudWorkspaceLinkTarget, chatId?: string | null ) => Promise> /** A fresh per-device pairing link for a teammate's workspace (E2EE grant, opened in main). */ @@ -62,6 +67,15 @@ export type CloudWorkspacesApi = { document: OrgPrompts['document'], revision: number ) => Promise> + /** This member's synced sidebar arrangement of cloud workspaces (pins, order, sections). */ + getPrefs: () => Promise> + /** Compare-and-set on `revision`; a stale write fails with `conflict`. */ + putPrefs: ( + document: CloudWorkspacePrefsDocument, + revision: number + ) => Promise> + /** The org's link slug; `orgName` names it the first time anyone asks. */ + getOrgSlug: (orgName?: string | null) => Promise> onOpenLink: (callback: (link: string) => void) => () => void consumePendingLink: () => Promise } diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index 43d0b5c7aa6..d65216d786d 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -6,8 +6,8 @@ export const cloudWorkspacesApi = { list: (query) => ipcRenderer.invoke('cloudWorkspaces:list', query), get: (id) => ipcRenderer.invoke('cloudWorkspaces:get', { id }), patch: (id, patch) => ipcRenderer.invoke('cloudWorkspaces:patch', { id, patch }), - resolveLink: (workspaceId, chatId) => - ipcRenderer.invoke('cloudWorkspaces:resolveLink', { workspaceId, chatId }), + resolveLink: (target, chatId) => + ipcRenderer.invoke('cloudWorkspaces:resolveLink', { target, chatId }), openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }), readSnapshot: (id) => ipcRenderer.invoke('cloudWorkspaces:readSnapshot', { id }), listGrants: (id) => ipcRenderer.invoke('cloudWorkspaces:listGrants', { id }), @@ -27,6 +27,10 @@ export const cloudWorkspacesApi = { getOrgPrompts: () => ipcRenderer.invoke('cloudWorkspaces:getOrgPrompts'), putOrgPrompts: (document, revision) => ipcRenderer.invoke('cloudWorkspaces:putOrgPrompts', { document, revision }), + getPrefs: () => ipcRenderer.invoke('cloudWorkspaces:getPrefs'), + putPrefs: (document, revision) => + ipcRenderer.invoke('cloudWorkspaces:putPrefs', { document, revision }), + getOrgSlug: (orgName) => ipcRenderer.invoke('cloudWorkspaces:getOrgSlug', { orgName }), onOpenLink: (callback) => { const listener = (_event: Electron.IpcRendererEvent, link: string): void => callback(link) ipcRenderer.on('ui:openCloudWorkspaceLink', listener) diff --git a/src/renderer/src/app-shell/TitlebarMainStrip.tsx b/src/renderer/src/app-shell/TitlebarMainStrip.tsx index df831509cef..8845a4a8c59 100644 --- a/src/renderer/src/app-shell/TitlebarMainStrip.tsx +++ b/src/renderer/src/app-shell/TitlebarMainStrip.tsx @@ -10,6 +10,7 @@ import { selectActiveTerminalChromeState } from './active-terminal-chrome-select import { hasCustomTitleBar } from './app-window-chrome' import type { AppChromeLayout } from './use-app-chrome-layout' import { RunActionButton } from '../components/run-actions/RunActionButton' +import { CloudWorkspaceNumberChip } from '../components/cloud-workspaces/CloudWorkspaceNumberChip' export function RightSidebarToggle(): React.JSX.Element { const t = useTranslate() @@ -68,6 +69,9 @@ export function TitlebarMainStrip({ layout }: { layout: AppChromeLayout }): Reac className={`flex flex-1 min-w-0 self-stretch${!layout.workspaceChromeActive ? ' invisible pointer-events-none' : ''}`} /> )} + {layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? ( + + ) : null} {layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? ( ) : null} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx new file mode 100644 index 00000000000..b3d60a06fc3 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx @@ -0,0 +1,177 @@ +// One group on Home: Pinned, a section, or "No section". Named sections collapse; every group's +// rows reorder by dragging (or Move up / Move down in the row menu), and the order syncs to your +// other devices through your prefs. +import React, { useState } from 'react' +import { ChevronRight, MoreHorizontal, Pin } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { CloudWorkspaceGroup } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' + +type Group = CloudWorkspaceGroup + +export type GroupDrag = { + /** The row being dragged and the group it came from (rows only drop within their own group). */ + dragging: { id: string; group: string } | null + start: (id: string, group: string) => void + drop: (overId: string, group: string) => void + end: () => void +} + +/** Drag props for one row's
  • ; inert while reduced to a single row. */ +export function rowDragProps( + drag: GroupDrag, + group: Group, + id: string +): React.LiHTMLAttributes & { 'data-drop-target'?: string } { + if (group.rows.length < 2) { + return {} + } + return { + draggable: true, + onDragStart: (event) => { + event.dataTransfer.effectAllowed = 'move' + // Some platforms need data set for the drag to start at all. + event.dataTransfer.setData('text/plain', id) + drag.start(id, group.key) + }, + onDragOver: (event) => { + if (drag.dragging?.group === group.key) { + event.preventDefault() + event.dataTransfer.dropEffect = 'move' + } + }, + onDrop: (event) => { + if (drag.dragging?.group === group.key) { + event.preventDefault() + drag.drop(id, group.key) + } + }, + onDragEnd: () => drag.end() + } +} + +export function CloudWorkspaceGroupView({ + group, + index, + showHeading, + canMoveUp, + canMoveDown, + onToggleCollapsed, + onMoveSection, + children +}: { + group: Group + index: number + showHeading: boolean + canMoveUp: boolean + canMoveDown: boolean + onToggleCollapsed: (collapsed: boolean) => void + onMoveSection: (delta: number) => void + children: React.ReactNode +}): React.JSX.Element { + const t = useTranslate() + const [menuOpen, setMenuOpen] = useState(false) + // Section names are free text (spaces), so the id uses the position instead. + const headingId = `cloud-workspaces-section-${index}` + const listId = `cloud-workspaces-section-list-${index}` + const label = + group.kind === 'pinned' + ? t('auto.components.cloudWorkspaces.pinned', 'Pinned') + : (group.section ?? t('auto.components.cloudWorkspaces.noSection', 'No section')) + const count = ( + <> + {/* The bare number is visual; screen readers get the counted phrase. */} + + {group.rows.length} + {' '} + + {t('auto.components.cloudWorkspaces.sectionCount', '{{count}} workspaces', { + count: group.rows.length, + defaultValue_one: '{{count}} workspace' + })} + + + ) + const collapsible = group.kind === 'section' + return ( +
    + {showHeading && ( +
    +

    + {collapsible ? ( + + ) : ( + + {group.kind === 'pinned' && } + {label} + {count} + + )} +

    + {collapsible && (canMoveUp || canMoveDown) && ( + + + + + + onMoveSection(-1)}> + {t('auto.components.cloudWorkspaces.moveSectionUp', 'Move section up')} + + onMoveSection(1)}> + {t('auto.components.cloudWorkspaces.moveSectionDown', 'Move section down')} + + + + )} +
    + )} + {!group.collapsed && ( +
      + {children} +
    + )} +
    + ) +} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx new file mode 100644 index 00000000000..33ff34cce80 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx @@ -0,0 +1,55 @@ +// W-123 in the top bar when the workspace in front is a cloud workspace; click copies its link +// (the same as ⌘⌥⇧L). Renders nothing for local workspaces or before the number is known. +import React from 'react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { formatOptionalPrimaryShortcutLabel } from '@/hooks/useShortcutLabel' +import { useTranslate } from '@/i18n/use-translate' +import { useAppStore } from '@/store' +import { formatWorkspaceNumber } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { sandboxIdForWorktree, useCloudWorkspaceIdentities } from './cloud-workspace-identity' +import { frontCloudChat } from './cloud-workspace-links' +import { copyCloudWorkspaceLink } from './open-cloud-workspace' + +export function CloudWorkspaceNumberChip({ + worktreeId +}: { + worktreeId: string +}): React.JSX.Element | null { + const t = useTranslate() + const hostId = useAppStore((s) => s.activeWorkspaceExecutionHostId) + const keybindings = useAppStore((s) => s.keybindings) + const identities = useCloudWorkspaceIdentities() + const sandboxId = sandboxIdForWorktree({ id: worktreeId, hostId }, identities) + const number = sandboxId ? (identities.bySandbox.get(sandboxId)?.number ?? null) : null + if (!sandboxId || !number) { + return null + } + const label = formatWorkspaceNumber(number) + const shortcut = formatOptionalPrimaryShortcutLabel('cloudWorkspace.copyLink', keybindings) + return ( + + + + + + {t('auto.components.cloudWorkspaces.copyLink', 'Copy link')} + {shortcut ? {shortcut} : null} + + + ) +} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index dae60301e33..a10782d92c4 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -7,11 +7,19 @@ import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' -import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { + formatWorkspaceNumber, + type CloudWorkspace +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { CloudStateDot } from '../orca-cloud/CloudStateDot' import type { CloudDotState } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { MemberAvatar, PresenceStack } from './CloudMemberAvatars' -import { CloudWorkspaceRowMenu, isReadableAsleep, type RowActions } from './CloudWorkspaceRowMenu' +import { + CloudWorkspaceRowMenu, + isReadableAsleep, + type RowActions, + type RowArrangement +} from './CloudWorkspaceRowMenu' import { formatSandboxHours, formatRelative, @@ -81,7 +89,10 @@ export function CloudWorkspaceRow({ opening, highlighted, now, - actions + actions, + arrangement, + dragProps, + dragging = false }: { workspace: CloudWorkspace directory: MemberDirectory @@ -93,6 +104,11 @@ export function CloudWorkspaceRow({ highlighted: boolean now: number actions: RowActions + /** Pinned state and whether Move up / Move down apply (synced prefs). */ + arrangement?: RowArrangement + /** Drag-to-reorder within its group (from CloudWorkspaceGroup's rowDragProps). */ + dragProps?: React.LiHTMLAttributes + dragging?: boolean }): React.JSX.Element { const t = useTranslate() const intlLocale = useIntlLocale() @@ -155,6 +171,7 @@ export function CloudWorkspaceRow({
  • { // Menu items render in a portal but still bubble through React; only this row's own DOM counts. if (!(event.target instanceof Node) || !event.currentTarget.contains(event.target)) { @@ -174,7 +191,8 @@ export function CloudWorkspaceRow({ }} className={cn( 'group relative isolate flex items-center gap-3 rounded-lg pr-2 transition-colors hover:bg-accent', - menuOpen && 'bg-accent' + menuOpen && 'bg-accent', + dragging && 'opacity-50' )} > {/* Opened from a link: an accent tint that fades out (instantly under reduced motion). */} @@ -230,6 +248,11 @@ export function CloudWorkspaceRow({ > {title} + {w.number ? ( + + {formatWorkspaceNumber(w.number)} + + ) : null} {w.visibility === 'private' && ( @@ -366,6 +389,7 @@ export function CloudWorkspaceRow({ open={menuOpen} onOpenChange={setMenuOpen} actions={actions} + arrangement={arrangement} /> {description} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx index 42b3eba01f9..57b84de3296 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx @@ -4,6 +4,8 @@ import { ArchiveRestore, Moon, Trash2, + ArrowDown, + ArrowUp, ArrowUpRight, BookOpen, FolderInput, @@ -11,6 +13,8 @@ import { Link2, Lock, MoreHorizontal, + Pin, + PinOff, Play, UserRoundCog, Users @@ -58,8 +62,14 @@ export type RowActions = { sleep: (w: CloudWorkspace) => void /** Delete the sandbox and its disk, after a confirmation. */ remove: (w: CloudWorkspace) => void + /** Pin to the top of Home, synced to your other devices (your own pins, not the team's). */ + setPinned?: (w: CloudWorkspace, pinned: boolean) => void + /** Move one place up (-1) or down (1) within its group, synced like pins. */ + move?: (w: CloudWorkspace, delta: number) => void } +export type RowArrangement = { pinned: boolean; canMoveUp: boolean; canMoveDown: boolean } + /** Placeholder replaced by the inline section editor in CloudWorkspacesHome. */ export const NEW_SECTION = '\u0000new-section' // Radio value for "no section"; section names are user text, so a control character cannot clash. @@ -87,7 +97,8 @@ export function CloudWorkspaceRowMenu({ selfId, open, onOpenChange, - actions + actions, + arrangement }: { workspace: CloudWorkspace title: string @@ -100,6 +111,7 @@ export function CloudWorkspaceRowMenu({ open: boolean onOpenChange: (open: boolean) => void actions: RowActions + arrangement?: RowArrangement }): React.JSX.Element { const t = useTranslate() const keybindings = useAppStore((state) => state.keybindings) @@ -159,6 +171,32 @@ export function CloudWorkspaceRowMenu({ ↵ )} + {arrangement && actions.setPinned && w.archivedAt === null && ( + actions.setPinned?.(w, !arrangement.pinned)}> + {arrangement.pinned ? : } + {arrangement.pinned + ? t('auto.components.cloudWorkspaces.unpin', 'Unpin') + : t('auto.components.cloudWorkspaces.pin', 'Pin')} + + )} + {arrangement && actions.move && (arrangement.canMoveUp || arrangement.canMoveDown) && ( + <> + actions.move?.(w, -1)} + > + + {t('auto.components.cloudWorkspaces.moveUp', 'Move up')} + + actions.move?.(w, 1)} + > + + {t('auto.components.cloudWorkspaces.moveDown', 'Move down')} + + + )} actions.copyLink(w)}> {t('auto.components.cloudWorkspaces.copyLink', 'Copy link')} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index aead29afdf8..e83ebd1c9ec 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -14,6 +14,8 @@ import type { } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { useOrgRoster } from '../billing/team/use-org-roster' import { CloudWorkspaceRow } from './CloudWorkspaceRow' +import { CloudWorkspaceGroupView, rowDragProps } from './CloudWorkspaceGroup' +import { useCloudWorkspaceArrangement } from './use-cloud-workspace-arrangement' import { NEW_SECTION } from './CloudWorkspaceRowMenu' import { ANY, @@ -149,16 +151,9 @@ export function CloudWorkspacesHome({ [all, by, repo, highlightId, filters.running] ) const highlighted = highlightId ? visible.find((w) => w.id === highlightId) : undefined - const groups = useMemo(() => { - const out = new Map() - for (const w of visible) { - const key = w.section ?? '' - out.set(key, [...(out.get(key) ?? []), w]) - } - return [...out.entries()].sort(([a], [b]) => - a === '' ? 1 : b === '' ? -1 : a.localeCompare(b) - ) - }, [visible]) + // Pinned first, then sections, in the order you arranged them on any of your devices. + const arrangement = useCloudWorkspaceArrangement(visible) + const { groups } = arrangement const members = useMemo( () => [...directory.entries()].map(([userId, m]) => ({ @@ -258,9 +253,11 @@ export function CloudWorkspacesHome({ copyWorkspaceLink: (w: CloudWorkspace) => void copyCloudWorkspaceLink(w.id), goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId), patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change), + setPinned: arrangement.pin, + move: arrangement.move, ...homeArchive.homeArchiveActions({ selfId, t, refresh, confirmArchive: setConfirm }) }), - [open, patch, refresh, selfId, setReadingId, t] + [open, patch, refresh, selfId, setReadingId, t, arrangement.pin, arrangement.move] ) // Nothing (not even a skeleton) until we know this build has a control plane and you are in. @@ -327,51 +324,46 @@ export function CloudWorkspacesHome({ /> )} {state.status === 'ready' && - groups.map(([section, rows], index) => { - // Section names are free text (spaces), so the id uses the position instead. - const headingId = `cloud-workspaces-section-${index}` - const showHeading = groups.length > 1 || section !== '' + groups.map((group, index) => { + const sectionIndex = group.section + ? arrangement.shownSections.indexOf(group.section) + : -1 return ( -
    - {showHeading && ( -

    - {section || t('auto.components.cloudWorkspaces.noSection', 'No section')} - {/* The bare number is visual; screen readers get the counted phrase. */} - - {rows.length} - {' '} - - {t('auto.components.cloudWorkspaces.sectionCount', '{{count}} workspaces', { - count: rows.length, - defaultValue_one: '{{count}} workspace' - })} - -

    - )} -
      - {rows.map((w) => ( - - ))} -
    -
    + 1 || group.kind !== 'none'} + canMoveUp={sectionIndex > 0} + canMoveDown={ + sectionIndex >= 0 && sectionIndex < arrangement.shownSections.length - 1 + } + onToggleCollapsed={(collapsed) => + group.section && arrangement.toggleCollapsed(group.section, collapsed) + } + onMoveSection={(delta) => + group.section && arrangement.moveSection(group.section, delta) + } + > + {group.rows.map((w, rowIndex) => ( + + ))} + ) })} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-identity.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-identity.ts new file mode 100644 index 00000000000..d2cd8a43baa --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-identity.ts @@ -0,0 +1,129 @@ +// Which cloud workspace (sandbox) a sidebar worktree is, and that workspace's number (W-123) and +// link. Numbers and links come from the control plane's list; the worktree mapping comes from this +// desktop: the owner's own hosted runtime (by worktree id) or a teammate's paired runtime +// environment (by host id). A tiny external store so palette rows and headers stay cheap. +import { useSyncExternalStore } from 'react' +import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' + +export type CloudWorkspaceIdentity = { + number: number | null + link: string | null + title: string | null +} + +type State = { + bySandbox: ReadonlyMap + sandboxByWorktree: ReadonlyMap + sandboxByHost: ReadonlyMap +} + +let state: State = { bySandbox: new Map(), sandboxByWorktree: new Map(), sandboxByHost: new Map() } +const listeners = new Set<() => void>() + +function publish(next: State): void { + state = next + listeners.forEach((listener) => listener()) +} + +function sameIdentity(a: CloudWorkspaceIdentity | undefined, b: CloudWorkspaceIdentity): boolean { + return a !== undefined && a.number === b.number && a.link === b.link && a.title === b.title +} + +/** Folds a list (or one workspace) the control plane returned into the cache. */ +export function rememberCloudWorkspaces(workspaces: readonly CloudWorkspace[]): void { + let changed = false + const next = new Map(state.bySandbox) + for (const w of workspaces) { + const identity = { number: w.number ?? null, link: w.link ?? null, title: w.title } + if (!sameIdentity(next.get(w.id), identity)) { + next.set(w.id, identity) + changed = true + } + } + if (changed) { + publish({ ...state, bySandbox: next }) + } +} + +/** Re-reads which local worktrees and runtime hosts are cloud workspaces on this desktop. */ +export async function refreshCloudWorktreeBindings(): Promise { + const api = window.api.cloudWorkspaces + const [local, bindings] = await Promise.all([ + api.localWorkspaces().catch(() => []), + api.environmentBindings().catch(() => ({})) + ]) + const sandboxByWorktree = new Map() + const sandboxByHost = new Map() + for (const entry of local) { + if (entry.worktreeId) { + sandboxByWorktree.set(entry.worktreeId, entry.sandboxId) + } + if (entry.runtimeEnvironmentId) { + sandboxByHost.set(toRuntimeExecutionHostId(entry.runtimeEnvironmentId), entry.sandboxId) + } + } + for (const [sandboxId, binding] of Object.entries(bindings)) { + sandboxByHost.set(toRuntimeExecutionHostId(binding.environmentId), sandboxId) + } + const same = (a: ReadonlyMap, b: Map) => + a.size === b.size && [...b].every(([key, value]) => a.get(key) === value) + if ( + !same(state.sandboxByWorktree, sandboxByWorktree) || + !same(state.sandboxByHost, sandboxByHost) + ) { + publish({ ...state, sandboxByWorktree, sandboxByHost }) + } +} + +export function sandboxIdForWorktree( + worktree: { id: string; hostId?: string | null }, + current: State = state +): string | null { + return ( + (worktree.hostId ? current.sandboxByHost.get(worktree.hostId) : undefined) ?? + current.sandboxByWorktree.get(worktree.id) ?? + null + ) +} + +export function cloudWorkspaceIdentity(sandboxId: string | null): CloudWorkspaceIdentity | null { + return sandboxId ? (state.bySandbox.get(sandboxId) ?? null) : null +} + +/** W-number of the cloud workspace a worktree belongs to, or null (not cloud, or not known yet). */ +export function cloudNumberForWorktree( + worktree: { id: string; hostId?: string | null }, + current: State = state +): number | null { + const sandboxId = sandboxIdForWorktree(worktree, current) + return sandboxId ? (current.bySandbox.get(sandboxId)?.number ?? null) : null +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +/** The whole cache; changes identity only when something in it changed (memo dependency). */ +export function useCloudWorkspaceIdentities(): State { + return useSyncExternalStore(subscribe, () => state) +} + +export function useCloudWorkspaceNumber(sandboxId: string | null | undefined): number | null { + return useSyncExternalStore(subscribe, () => + sandboxId ? (state.bySandbox.get(sandboxId)?.number ?? null) : null + ) +} + +export function useCloudWorktreeNumber( + worktree: { id: string; hostId?: string | null } | null | undefined +): number | null { + return useSyncExternalStore(subscribe, () => (worktree ? cloudNumberForWorktree(worktree) : null)) +} + +/** Test-only. */ +export function resetCloudWorkspaceIdentityForTests(): void { + state = { bySandbox: new Map(), sandboxByWorktree: new Map(), sandboxByHost: new Map() } + listeners.clear() +} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts index 6a9728af08d..542a2f35efc 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts @@ -12,6 +12,8 @@ import { describeError } from './cloud-workspace-errors' import { copyCloudWorkspaceLink, openCloudWorkspace } from './open-cloud-workspace' import { currentCloudChatId, focusCloudChat } from './cloud-chat-focus' import { cloudWorkspacesAvailable } from './use-cloud-workspaces' +import { installCloudWorkspaceSync } from './cloud-workspace-sync' +import { rememberCloudWorkspaces } from './cloud-workspace-identity' const HIGHLIGHT_MS = 4_000 /** No input for this long and the desktop stops reporting presence (and renewing a lease). */ @@ -47,9 +49,15 @@ export async function handleCloudWorkspaceLink(link: string): Promise { if (!parsed || !(await cloudWorkspacesAvailable())) { return } - setHighlight(parsed.workspaceId) - const resolved = await window.api.cloudWorkspaces.resolveLink(parsed.workspaceId, parsed.chatId) + if (parsed.target.kind === 'id') { + setHighlight(parsed.target.workspaceId) + } + const resolved = await window.api.cloudWorkspaces.resolveLink(parsed.target, parsed.chatId) if (!resolved.ok) { + if (resolved.reason === 'other_org' && offerTeamSwitch(resolved.orgId, link)) { + setHighlight(null) + return + } toast.error( resolved.error === 'not_found' ? translate( @@ -61,13 +69,48 @@ export async function handleCloudWorkspaceLink(link: string): Promise { setHighlight(null) return } - const outcome = await openCloudWorkspace(resolved.value.workspace) + const workspace = resolved.value.workspace + rememberCloudWorkspaces([workspace]) + setHighlight(workspace.id) + const outcome = await openCloudWorkspace(workspace) if (!outcome.ok) { toast.error(outcome.message) } else if (resolved.value.chatId) { await focusCloudChat(outcome.worktreeId, resolved.value.chatId) } - setHighlight(parsed.workspaceId, HIGHLIGHT_MS) + setHighlight(workspace.id, HIGHLIGHT_MS) +} + +/** + * A W-number link from a team you belong to but don't have active: say which team, and offer to + * switch and open it. False when you are not in that team (the generic not-found copy applies). + */ +function offerTeamSwitch(orgId: string | undefined, link: string): boolean { + const state = useAppStore.getState() + const org = orgId + ? state.orcaProfileAuthStatus?.organizations?.find((o) => o.orgId === orgId) + : undefined + if (!org) { + return false + } + toast.info( + translate('auto.components.cloudWorkspaces.linkOtherTeam', 'This workspace is in {{team}}', { + team: org.name + }), + { + description: translate( + 'auto.components.cloudWorkspaces.linkOtherTeamHint', + 'Switch teams to open it.' + ), + action: { + label: translate('auto.components.cloudWorkspaces.linkSwitchTeam', 'Switch and open'), + onClick: () => { + void state.selectOrcaProfileOrg(org.orgId).then(() => handleCloudWorkspaceLink(link)) + } + } + } + ) + return true } type Front = { @@ -128,6 +171,7 @@ export function installCloudWorkspaceLinks(): () => void { if (!api) { return () => {} } + cleanups.push(installCloudWorkspaceSync()) cleanups.push( api.onOpenLink((link) => { // The push already delivered it; drain the pending copy so a reload does not replay it. diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts new file mode 100644 index 00000000000..31faa3ac23a --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + EMPTY_CLOUD_WORKSPACE_PREFS, + type CloudWorkspacePrefsDocument +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { setPinned } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement' +import { + editCloudWorkspacePrefs, + getCloudWorkspacePrefs, + refreshCloudWorkspacePrefs, + resetCloudWorkspacePrefsForTests, + setPrefsAccount +} from './cloud-workspace-prefs' + +const toastError = vi.hoisted(() => vi.fn()) +vi.mock('sonner', () => ({ toast: { error: toastError } })) + +const A = `sbx_${'a'.repeat(24)}` +const B = `sbx_${'b'.repeat(24)}` + +/** A control plane with compare-and-set, plus a hook to simulate another device writing first. */ +function fakeServer() { + const server = { + document: EMPTY_CLOUD_WORKSPACE_PREFS as CloudWorkspacePrefsDocument, + revision: 0 + } + const view = () => ({ ok: true as const, value: { ...server, updatedAt: null } }) + let failPuts = false + const api = { + getPrefs: vi.fn(async () => view()), + putPrefs: vi.fn(async (document: CloudWorkspacePrefsDocument, revision: number) => { + if (failPuts) { + return { ok: false as const, error: 'unavailable' } + } + if (revision !== server.revision) { + return { ok: false as const, error: 'conflict', reason: 'stale_revision' } + } + server.document = document + server.revision += 1 + return view() + }) + } + return { + server, + api, + otherDevice: (edit: (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument) => { + server.document = edit(server.document) + server.revision += 1 + }, + failPuts: (value: boolean) => { + failPuts = value + } + } +} + +describe('cloud workspace prefs sync', () => { + let fake: ReturnType + beforeEach(() => { + resetCloudWorkspacePrefsForTests() + toastError.mockReset() + fake = fakeServer() + vi.stubGlobal('window', { api: { cloudWorkspaces: fake.api } }) + }) + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('shows an edit at once and saves it', async () => { + setPrefsAccount('u:org') + await refreshCloudWorkspacePrefs() + const saved = editCloudWorkspacePrefs((doc) => setPinned(doc, A, true)) + expect(getCloudWorkspacePrefs().document.pinned).toEqual([A]) + await saved + expect(fake.server).toMatchObject({ document: { pinned: [A] }, revision: 1 }) + expect(getCloudWorkspacePrefs().document.pinned).toEqual([A]) + }) + + it('re-applies an edit on top of a write from another device', async () => { + setPrefsAccount('u:org') + await refreshCloudWorkspacePrefs() + fake.otherDevice((doc) => setPinned(doc, B, true)) + await editCloudWorkspacePrefs((doc) => setPinned(doc, A, true)) + expect(fake.api.putPrefs).toHaveBeenCalledTimes(2) + expect(fake.server.document.pinned).toEqual([B, A]) + expect(getCloudWorkspacePrefs().document.pinned).toEqual([B, A]) + }) + + it('drops a failed edit and says so', async () => { + setPrefsAccount('u:org') + await refreshCloudWorkspacePrefs() + fake.failPuts(true) + await editCloudWorkspacePrefs((doc) => setPinned(doc, A, true)) + expect(getCloudWorkspacePrefs().document.pinned).toEqual([]) + expect(toastError).toHaveBeenCalledTimes(1) + }) + + it('picks up remote edits on refresh and starts empty for another account', async () => { + setPrefsAccount('u:org') + await refreshCloudWorkspacePrefs() + fake.otherDevice((doc) => setPinned(doc, B, true)) + await refreshCloudWorkspacePrefs() + expect(getCloudWorkspacePrefs().document.pinned).toEqual([B]) + setPrefsAccount('u:other') + expect(getCloudWorkspacePrefs()).toMatchObject({ account: 'u:other', loaded: false }) + expect(getCloudWorkspacePrefs().document.pinned).toEqual([]) + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.ts new file mode 100644 index 00000000000..51902428b4c --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.ts @@ -0,0 +1,156 @@ +// This member's synced arrangement of cloud workspaces (pins, their order, section order and +// collapsed sections), kept on the account (/v1/team/prefs) so every desktop and the phone agree. +// One copy per window. What shows is the server copy with this window's unsaved edits applied on +// top, so an edit shows at once. Edits save one at a time with compare-and-set: each applies to +// the newest server copy, and a stale write re-reads and applies the same edit again, so edits +// from two devices both land. Remote edits arrive by polling while the window is visible. +import { useSyncExternalStore } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { + EMPTY_CLOUD_WORKSPACE_PREFS, + type CloudWorkspacePrefsDocument +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' + +/** Remote edits show up within this long while a window is visible. */ +export const PREFS_POLL_MS = 15_000 +const MAX_ATTEMPTS = 4 + +type Edit = (doc: CloudWorkspacePrefsDocument) => CloudWorkspacePrefsDocument + +export type CloudWorkspacePrefsSnapshot = { + /** `${userId}:${orgId}`; prefs belong to one account, so a team switch starts empty. */ + account: string | null + /** The server copy with unsaved edits applied: what to render. */ + document: CloudWorkspacePrefsDocument + loaded: boolean +} + +let account: string | null = null +let server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false } +let pending: Edit[] = [] +let queue: Promise = Promise.resolve() +let snapshot: CloudWorkspacePrefsSnapshot = { + account: null, + document: EMPTY_CLOUD_WORKSPACE_PREFS, + loaded: false +} +const listeners = new Set<() => void>() + +function publish(): void { + snapshot = { + account, + document: pending.reduce((doc, edit) => edit(doc), server.document), + loaded: server.loaded + } + listeners.forEach((listener) => listener()) +} + +export function getCloudWorkspacePrefs(): CloudWorkspacePrefsSnapshot { + return snapshot +} + +export function useCloudWorkspacePrefs(): CloudWorkspacePrefsSnapshot { + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => snapshot + ) +} + +/** Switches to `next` (empty until read); a no-op when it is already the current account. */ +export function setPrefsAccount(next: string | null): void { + if (account === next) { + return + } + account = next + server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false } + pending = [] + publish() +} + +async function readServer(forAccount: string): Promise { + const result = await window.api.cloudWorkspaces.getPrefs() + if (!result.ok || account !== forAccount) { + return false + } + if (!server.loaded || result.value.revision !== server.revision) { + server = { document: result.value.document, revision: result.value.revision, loaded: true } + publish() + } + return true +} + +/** Reads the server copy (polling, focus, Home opening). */ +export async function refreshCloudWorkspacePrefs(): Promise { + if (account) { + await readServer(account) + } +} + +async function save(forAccount: string, edit: Edit): Promise { + if (!server.loaded && !(await readServer(forAccount))) { + return false + } + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) { + const next = edit(server.document) + if (next === server.document) { + return true + } + const result = await window.api.cloudWorkspaces.putPrefs(next, server.revision) + if (account !== forAccount) { + return true + } + if (result.ok) { + server = { document: result.value.document, revision: result.value.revision, loaded: true } + return true + } + // Another device wrote first: take its copy and apply this edit to it. + if (result.error !== 'conflict' || !(await readServer(forAccount))) { + return false + } + } + return false +} + +/** + * Shows `edit` now and saves it. If saving fails, the edit is dropped (the server copy shows + * again) and a toast says so. + */ +export function editCloudWorkspacePrefs(edit: Edit): Promise { + const forAccount = account + if (!forAccount || edit(snapshot.document) === snapshot.document) { + return Promise.resolve() + } + pending = [...pending, edit] + publish() + queue = queue.then(async () => { + const saved = await save(forAccount, edit).catch(() => false) + if (account !== forAccount) { + return + } + pending = pending.filter((other) => other !== edit) + publish() + if (!saved) { + toast.error( + translate( + 'auto.components.cloudWorkspaces.prefsSaveFailed', + "Couldn't save that change, so your other devices won't show it. Try again." + ) + ) + } + }) + return queue +} + +/** Test-only: forget everything. */ +export function resetCloudWorkspacePrefsForTests(): void { + account = null + server = { document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0, loaded: false } + pending = [] + queue = Promise.resolve() + snapshot = { account: null, document: EMPTY_CLOUD_WORKSPACE_PREFS, loaded: false } + listeners.clear() +} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-sync.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-sync.ts new file mode 100644 index 00000000000..e90898936a8 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-sync.ts @@ -0,0 +1,126 @@ +// App-level sync for cloud workspace arrangement and identity, installed with the link wiring: +// follows the signed-in account, polls this member's synced prefs (pins, order, sections) while the +// window is visible, keeps W-numbers and links for the palette and headers, and names the org's +// link slug the first time anyone in the org asks (the control plane only knows org ids). +import { useAppStore } from '@/store' +import { getOrcaAccountKey } from '@/hooks/use-orca-account-key' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { cloudWorkspacesAvailable } from './use-cloud-workspaces' +import { + PREFS_POLL_MS, + editCloudWorkspacePrefs, + refreshCloudWorkspacePrefs, + setPrefsAccount +} from './cloud-workspace-prefs' +import { + refreshCloudWorktreeBindings, + rememberCloudWorkspaces, + sandboxIdForWorktree +} from './cloud-workspace-identity' +import { setPinned } from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement' +import { onWorktreesPinnedByUser } from '@/lib/orca-cloud/worktree-pin-listeners' + +/** Numbers and links rarely change; Home's own polling refreshes them faster while it is open. */ +const IDENTITY_POLL_MS = 60_000 + +export function installCloudWorkspaceSync(): () => void { + const api = window.api.cloudWorkspaces + if (!api) { + return () => {} + } + let account: string | null = null + const sluggedAccounts = new Set() + + const refreshIdentity = async (): Promise => { + if (!account || !(await cloudWorkspacesAvailable())) { + return + } + const forAccount = account + const [list] = await Promise.all([ + api.list({ scope: 'team', archived: 'include' }), + refreshCloudWorktreeBindings() + ]) + if (list.ok && account === forAccount) { + rememberCloudWorkspaces(list.value) + } + } + + const ensureSlug = async (): Promise => { + const status = useAppStore.getState().orcaProfileAuthStatus + const orgName = status?.cloud?.activeOrgName + if (!account || !status?.cloud?.activeOrgId || sluggedAccounts.has(account)) { + return + } + const forAccount = account + const result = await api.getOrgSlug(orgName ?? null) + if (result.ok && result.value.slug && account === forAccount) { + sluggedAccounts.add(forAccount) + // Links in the list now carry the slug form. + void refreshIdentity() + } + } + + const follow = (): void => { + const status = useAppStore.getState().orcaProfileAuthStatus + const next = status?.state === 'connected' ? getOrcaAccountKey(status) : null + const key = next === 'signed-out' ? null : next + if (key === account) { + return + } + account = key + setPrefsAccount(key) + if (key) { + void cloudWorkspacesAvailable().then((available) => { + if (available && account === key) { + void refreshCloudWorkspacePrefs() + void ensureSlug().then(refreshIdentity) + } + }) + } + } + + const cleanups: (() => void)[] = [] + cleanups.push( + useAppStore.subscribe((state, previous) => { + if (state.orcaProfileAuthStatus !== previous.orcaProfileAuthStatus) { + follow() + } + }) + ) + follow() + cleanups.push( + installWindowVisibilityInterval({ + run: () => void refreshCloudWorkspacePrefs(), + intervalMs: PREFS_POLL_MS + }) + ) + cleanups.push( + installWindowVisibilityInterval({ + run: () => void ensureSlug().then(refreshIdentity), + intervalMs: IDENTITY_POLL_MS + }) + ) + // Pinning a cloud workspace's row in the sidebar pins it in your synced prefs too. + cleanups.push( + onWorktreesPinnedByUser((targets, isPinned) => { + const ids = [...new Set(targets.flatMap((target) => sandboxIdForWorktree(target) ?? []))] + if (account && ids.length > 0) { + void editCloudWorkspacePrefs((doc) => + ids.reduce((next, id) => setPinned(next, id, isPinned), doc) + ) + } + }) + ) + // Pairing a teammate's workspace adds a runtime host; switching workspaces is a cheap re-read. + cleanups.push( + useAppStore.subscribe((state, previous) => { + if (state.activeWorkspaceExecutionHostId !== previous.activeWorkspaceExecutionHostId) { + void refreshCloudWorktreeBindings() + } + }) + ) + return () => { + cleanups.forEach((cleanup) => cleanup()) + setPrefsAccount(null) + } +} diff --git a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts index 2137b1572ae..27ed59a8420 100644 --- a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts +++ b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts @@ -10,7 +10,8 @@ import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-a import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler' import { RuntimeRpcCallError, unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' -import { cloudWorkspaceLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity' import { getWorktreeExecutionHostId, toRuntimeExecutionHostId @@ -236,9 +237,22 @@ export function openCloudWorkspace(workspace: CloudWorkspace): Promise { + let link = cloudWorkspaceIdentity(id)?.link ?? null + if (!link) { + const fetched = await window.api.cloudWorkspaces.get(id).catch(() => null) + if (fetched?.ok) { + rememberCloudWorkspaces([fetched.value]) + link = fetched.value.link ?? null + } + } + return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId) +} + export async function copyCloudWorkspaceLink(id: string, chatId?: string | null): Promise { try { - await navigator.clipboard.writeText(cloudWorkspaceLink(id, chatId)) + await navigator.clipboard.writeText(await shareLinkFor(id, chatId)) } catch (error) { console.warn('[cloud-workspaces] copy link failed', error) toast.error( diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts new file mode 100644 index 00000000000..6e74544d677 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts @@ -0,0 +1,140 @@ +// Home's arrangement state: groups from your synced prefs, plus the edits (pin, move, drag, +// collapse, section order) that save back to them. +import { useCallback, useEffect, useMemo, useState } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { + MAX_PINNED, + arrangeCloudWorkspaces, + dropOnto, + moveSection, + nudge, + reorderGroup, + setCollapsed, + setPinned, + type CloudWorkspaceGroup +} from '../../../../shared/cloud-workspaces/cloud-workspace-arrangement' +import { + editCloudWorkspacePrefs, + getCloudWorkspacePrefs, + refreshCloudWorkspacePrefs, + useCloudWorkspacePrefs +} from './cloud-workspace-prefs' +import type { GroupDrag } from './CloudWorkspaceGroup' +import type { RowArrangement } from './CloudWorkspaceRowMenu' + +export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) { + const prefs = useCloudWorkspacePrefs() + // Opening Home is a good moment to pick up another device's edits without waiting for the poll. + useEffect(() => { + void refreshCloudWorkspacePrefs() + }, []) + const groups = useMemo( + () => arrangeCloudWorkspaces(visible, prefs.document), + [visible, prefs.document] + ) + const groupOf = useCallback( + (id: string): CloudWorkspaceGroup | undefined => + groups.find((group) => group.rows.some((w) => w.id === id)), + [groups] + ) + const reorder = useCallback( + (group: CloudWorkspaceGroup, ids: string[] | null) => { + if (ids) { + void editCloudWorkspacePrefs((doc) => reorderGroup(doc, group, ids)) + } + }, + [] + ) + + const [dragging, setDragging] = useState(null) + const drag = useMemo( + () => ({ + dragging, + start: (id, group) => setDragging({ id, group }), + end: () => setDragging(null), + drop: (overId, groupKey) => { + const group = groups.find((g) => g.key === groupKey) + if (dragging && group) { + reorder( + group, + dropOnto( + group.rows.map((w) => w.id), + dragging.id, + overId + ) + ) + } + setDragging(null) + } + }), + [dragging, groups, reorder] + ) + + const pin = useCallback((w: CloudWorkspace, pinned: boolean) => { + if (pinned && getCloudWorkspacePrefs().document.pinned.length >= MAX_PINNED) { + toast.error( + translate( + 'auto.components.cloudWorkspaces.pinLimit', + 'You can pin up to {{count}} workspaces. Unpin one first.', + { count: MAX_PINNED } + ) + ) + return + } + void editCloudWorkspacePrefs((doc) => setPinned(doc, w.id, pinned)) + }, []) + + const move = useCallback( + (w: CloudWorkspace, delta: number) => { + const group = groupOf(w.id) + if (group) { + reorder( + group, + nudge( + group.rows.map((row) => row.id), + w.id, + delta + ) + ) + } + }, + [groupOf, reorder] + ) + + const shownSections = useMemo( + () => + groups.flatMap((group) => (group.kind === 'section' && group.section ? [group.section] : [])), + [groups] + ) + const toggleCollapsed = useCallback((section: string, collapsed: boolean) => { + void editCloudWorkspacePrefs((doc) => setCollapsed(doc, section, collapsed)) + }, []) + const moveSectionBy = useCallback( + (section: string, delta: number) => { + void editCloudWorkspacePrefs((doc) => moveSection(doc, shownSections, section, delta) ?? doc) + }, + [shownSections] + ) + + const arrangementFor = useCallback( + (group: CloudWorkspaceGroup, index: number): RowArrangement => ({ + pinned: group.kind === 'pinned', + canMoveUp: index > 0, + canMoveDown: index < group.rows.length - 1 + }), + [] + ) + + return { + groups, + drag, + pin, + move, + toggleCollapsed, + moveSection: moveSectionBy, + shownSections, + arrangementFor + } +} diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts index 09d9f27a37b..bcddaeb3939 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts @@ -5,6 +5,7 @@ import type { } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { availabilityRetryDelay } from '@/lib/availability-retry' import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller' +import { rememberCloudWorkspaces } from './cloud-workspace-identity' /** Presence is live; the list re-reads on this beat while visible (and on focus). */ const POLL_MS = 8_000 @@ -126,6 +127,7 @@ export function useCloudWorkspaces( return } if (result.ok) { + rememberCloudWorkspaces(result.value) setState({ status: 'ready', key, workspaces: result.value }) } else if (result.error === 'not_configured') { stopped = true diff --git a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-worktrees.ts b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-worktrees.ts index 18a031aa237..76dc47733a8 100644 --- a/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-worktrees.ts +++ b/src/renderer/src/components/worktree-jump/use-worktree-jump-palette-worktrees.ts @@ -21,6 +21,10 @@ import { import type { Worktree } from '../../../../shared/worktree/types' import { EMPTY_SORTED_WORKTREES } from './worktree-jump-palette-model' import { buildWorktreeJumpPaletteDocumentIndex } from './worktree-jump-palette-document-index' +import { + cloudNumberForWorktree, + useCloudWorkspaceIdentities +} from '@/components/cloud-workspaces/cloud-workspace-identity' import { buildWorktreeJumpPaletteWorktreeMaps } from './worktree-jump-palette-worktree-maps' import type { WorktreeJumpPaletteWorktreesInput } from './worktree-jump-palette-worktrees-input' @@ -216,6 +220,8 @@ export function useWorktreeJumpPaletteWorktrees({ }), [workspaces, hostedReviewCache, prCache, repoByHostIdentity, settings] ) + // Cloud workspaces are searchable by number (W-123); the cache changes only when numbers do. + const cloudIdentities = useCloudWorkspaceIdentities() const worktreeDocuments = useMemo( () => buildWorktreeJumpPaletteDocumentIndex({ @@ -227,11 +233,13 @@ export function useWorktreeJumpPaletteWorktrees({ prCache, issueCache, workspacePortScan, - checksReviewByWorktree + checksReviewByWorktree, + cloudNumberForWorktree: (worktree) => cloudNumberForWorktree(worktree, cloudIdentities) }), [ workspaces, checksReviewByWorktree, + cloudIdentities, hostFilterActive, hostOptions, issueCache, diff --git a/src/renderer/src/components/worktree-jump/worktree-jump-palette-document-index.ts b/src/renderer/src/components/worktree-jump/worktree-jump-palette-document-index.ts index 7a93ce3e84a..556b74e4205 100644 --- a/src/renderer/src/components/worktree-jump/worktree-jump-palette-document-index.ts +++ b/src/renderer/src/components/worktree-jump/worktree-jump-palette-document-index.ts @@ -24,7 +24,8 @@ export function buildWorktreeJumpPaletteDocumentIndex({ prCache, issueCache, workspacePortScan, - checksReviewByWorktree + checksReviewByWorktree, + cloudNumberForWorktree }: { worktrees: readonly Worktree[] repoMap: ReadonlyMap @@ -35,9 +36,16 @@ export function buildWorktreeJumpPaletteDocumentIndex({ issueCache: AppState['issueCache'] | null workspacePortScan: WorkspacePortScanResult | null checksReviewByWorktree: ReadonlyMap + /** W-123 for cloud workspaces (null for everything else). */ + cloudNumberForWorktree?: (worktree: Worktree) => number | null }): Map { const hostLabelByWorktreeId = new Map() + const cloudNumberByWorktreeId = new Map() for (const worktree of worktrees) { + const cloudNumber = cloudNumberForWorktree?.(worktree) + if (cloudNumber) { + cloudNumberByWorktreeId.set(getPaletteWorktreeIdentity(worktree), cloudNumber) + } const repo = resolvePaletteRepoForWorktree(worktree, repoMap, repoByHostIdentity) const badge = getPaletteHostBadge( getPaletteWorktreeExecutionHostId(worktree) ?? (repo && getRepoExecutionHostId(repo)), @@ -57,7 +65,8 @@ export function buildWorktreeJumpPaletteDocumentIndex({ issueCache, workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan), checksReviewByWorktree, - hostLabelByWorktreeId + hostLabelByWorktreeId, + cloudNumberByWorktreeId } ) } diff --git a/src/renderer/src/components/worktree-jump/worktree-jump-palette-primitives.tsx b/src/renderer/src/components/worktree-jump/worktree-jump-palette-primitives.tsx index 78c1e79c8b7..8e4cc6066b8 100644 --- a/src/renderer/src/components/worktree-jump/worktree-jump-palette-primitives.tsx +++ b/src/renderer/src/components/worktree-jump/worktree-jump-palette-primitives.tsx @@ -338,5 +338,7 @@ export function getPaletteSupportingTextLabel( return t('worktreeJumpPalette.matchLabel.task', 'Task') case 'automation': return t('worktreeJumpPalette.matchLabel.automationItem', 'Automation') + case 'cloudWorkspace': + return t('worktreeJumpPalette.matchLabel.cloudWorkspace', 'Cloud workspace') } } diff --git a/src/renderer/src/lib/orca-cloud/worktree-pin-listeners.ts b/src/renderer/src/lib/orca-cloud/worktree-pin-listeners.ts new file mode 100644 index 00000000000..7dab77f29d7 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/worktree-pin-listeners.ts @@ -0,0 +1,28 @@ +// Someone pinned or unpinned sidebar rows by hand (menu, drag onto Pinned, board). Cloud workspaces +// listen so the pin also lands in your synced prefs and shows on your other devices. Only explicit +// user actions notify; a pin read back from a workspace's own store does not. +export type WorktreePinTarget = { id: string; hostId?: string | null } +type Listener = (targets: readonly WorktreePinTarget[], isPinned: boolean) => void + +const listeners = new Set() + +export function onWorktreesPinnedByUser(listener: Listener): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function notifyWorktreesPinnedByUser( + targets: readonly WorktreePinTarget[], + isPinned: boolean +): void { + if (targets.length === 0) { + return + } + for (const listener of listeners) { + try { + listener(targets, isPinned) + } catch (error) { + console.warn('[worktree-pin-listeners] listener failed', error) + } + } +} diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts index afe11465436..b361d4bd8fe 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-document.ts @@ -11,6 +11,7 @@ import type { PaletteComposedEvidence } from '../../../../../../shared/palette-m import { buildWorktreeAttachmentEvidence, buildWorktreeAutomationEvidence, + buildWorktreeCloudNumberEvidence, buildWorktreeCommentEvidence, buildWorktreeIssueEvidence, buildWorktreeLinkedTaskEvidence, @@ -58,6 +59,8 @@ export type WorktreePaletteDocumentSources = { > checksReviewByWorktree?: ReadonlyMap hostLabelByWorktreeId?: ReadonlyMap + /** Cloud workspace numbers (W-123) by palette identity, then bare worktree id. */ + cloudNumberByWorktreeId?: ReadonlyMap evidencePolicy?: WorktreePaletteEvidencePolicy } @@ -130,6 +133,10 @@ function buildEvidence( const units = [ comment, buildWorktreeAutomationEvidence(worktree), + buildWorktreeCloudNumberEvidence( + sources.cloudNumberByWorktreeId?.get(getPaletteWorktreeIdentity(worktree)) ?? + sources.cloudNumberByWorktreeId?.get(worktree.id) + ), buildWorktreeLinkedTaskEvidence(worktree), buildWorktreeReviewEvidence(resolveReviewSource(worktree, repo, sources)), buildWorktreeIssueEvidence({ diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts index 22c85bfe935..6ad73577ef5 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts @@ -16,6 +16,7 @@ export type PaletteSupportingKind = | 'port' | 'task' | 'automation' + | 'cloudWorkspace' export type WorktreePaletteReviewSource = { provider: HostedReviewInfo['provider'] @@ -183,6 +184,21 @@ export function buildWorktreeIssueEvidence(args: { }) } +/** A cloud workspace's number: "W-123" (searching 123, w123 or W-123 finds it). */ +export function buildWorktreeCloudNumberEvidence( + number: number | null | undefined +): PaletteComposedEvidence | null { + if (!number) { + return null + } + return composePaletteEvidence({ + id: `cloud-number:${number}`, + kind: 'cloudWorkspace', + accessibilityLabel: 'Cloud workspace number', + parts: [{ key: 'number', text: `W-${number}`, profile: 'structured-label' }] + }) +} + export function buildWorktreePortEvidence( port: Readonly<{ port: number; processName?: string }> ): PaletteComposedEvidence | null { diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts index e84b675bf1b..1bd12511abb 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts @@ -56,6 +56,23 @@ function gitLabReview(overrides: Partial = {}): HostedReviewIn } describe('worktree-palette-search', () => { + it('finds a cloud workspace by its number and says why it matched', () => { + const cloud = makeWorktree({ id: 'wt-cloud', displayName: 'Fix login' }) + const local = makeWorktree({ id: 'wt-local', displayName: 'Release 123 notes' }) + const cloudNumberByWorktreeId = new Map([['wt-cloud', 123]]) + for (const query of ['W-123', 'w123']) { + const results = searchWorktrees([cloud, local], query, repoMap, { cloudNumberByWorktreeId }) + expect(results.map((r) => r.worktreeId)).toEqual(['wt-cloud']) + expect(results[0]?.supportingText?.labelKind).toBe('cloudWorkspace') + expect(results[0]?.supportingText?.text).toBe('W-123') + } + expect( + searchWorktrees([cloud, local], '123', repoMap, { cloudNumberByWorktreeId }).map( + (r) => r.worktreeId + ) + ).toContain('wt-cloud') + }) + it('falls back to branch text when a cleared display name left it undefined', () => { const cleared = makeWorktree({ displayName: undefined as unknown as string, diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-result.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-result.ts index 8518d6e6786..4e6d7deed07 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-result.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-result.ts @@ -9,7 +9,8 @@ const ACCESSIBILITY_LABELS: Record = pr: 'Pull request', mr: 'Merge request', issue: 'Linked issue', - port: 'Listening port' + port: 'Listening port', + cloudWorkspace: 'Cloud workspace number' } /** diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-pin-reveal.ts b/src/renderer/src/store/slices/worktrees/session/worktree-pin-reveal.ts index 596ca9a2f71..ab0ca26700b 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-pin-reveal.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-pin-reveal.ts @@ -16,6 +16,10 @@ import { getIndexedWorktreesById } from '../listing/worktree-catalog-index' import '@/lib/workspace/ownership/worktree-runtime-owner-index' import { worktreeOwnerHostIds } from '@/lib/workspace/ownership/workspace-catalog-owner-index' import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' +import { + notifyWorktreesPinnedByUser, + type WorktreePinTarget +} from '@/lib/orca-cloud/worktree-pin-listeners' type WorktreeWithEmbeddedLineage = Worktree & { lineage?: WorktreeLineage | null } function getProjectedLineage(get: WorktreeSliceGet, worktree: Worktree): WorktreeLineage | null { @@ -75,6 +79,7 @@ export function createSetWorktreesPinnedAndReveal( const activeHostId = get().activeWorkspaceExecutionHostId ?? null // Skip worktrees already in the target state so a no-op toggle doesn't scroll the viewport away. const updates: WorktreeMetaBatchUpdate[] = [] + const pinTargets: WorktreePinTarget[] = [] const changedWorktreeIds = new Set() let didChange = false let revealWorktreeId: string | null = null @@ -91,6 +96,7 @@ export function createSetWorktreesPinnedAndReveal( } const executionHostId = target.hostId ?? current.hostId ?? 'local' didChange = true + pinTargets.push({ id: worktreeId, hostId: executionHostId }) // A server-proxied row answers to its own SSH host and to its server's runtime alias. const onFocusedHost = !activeHostId || @@ -116,6 +122,8 @@ export function createSetWorktreesPinnedAndReveal( if (!didChange) { return } + // Cloud workspaces mirror this into the member's synced prefs (their other devices). + notifyWorktreesPinnedByUser(pinTargets, isPinned) if ( revealWorktreeId === null && activeSidebarWorktreeId !== null && diff --git a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts index 327d7443bc8..b6f3b8b1cff 100644 --- a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts +++ b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts @@ -25,6 +25,9 @@ export function createWebCloudWorkspacesApi(): PreloadApi['cloudWorkspaces'] { setActive: () => Promise.resolve(), getOrgPrompts: () => Promise.resolve(NOT_CONFIGURED), putOrgPrompts: () => Promise.resolve(NOT_CONFIGURED), + getPrefs: () => Promise.resolve(NOT_CONFIGURED), + putPrefs: () => Promise.resolve(NOT_CONFIGURED), + getOrgSlug: () => Promise.resolve(NOT_CONFIGURED), onOpenLink: () => () => {}, consumePendingLink: () => Promise.resolve(null) } diff --git a/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts b/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts new file mode 100644 index 00000000000..9ea52f03bfd --- /dev/null +++ b/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest' +import { + EMPTY_CLOUD_WORKSPACE_PREFS, + type CloudWorkspace, + type CloudWorkspacePrefsDocument +} from './cloud-workspaces-wire' +import { + arrangeCloudWorkspaces, + dropOnto, + moveSection, + nudge, + reorderGroup, + setCollapsed, + setPinned +} from './cloud-workspace-arrangement' + +const id = (n: number) => `sbx_${String(n).padStart(24, '0')}` +function ws(n: number, section: string | null = null, archived = false): CloudWorkspace { + return { id: id(n), section, archivedAt: archived ? 1 : null } as CloudWorkspace +} +const doc = (patch: Partial): CloudWorkspacePrefsDocument => ({ + ...EMPTY_CLOUD_WORKSPACE_PREFS, + ...patch +}) +const shape = (groups: ReturnType) => + groups.map((g) => [g.key, g.rows.map((w) => Number(w.id.slice(4))), g.collapsed]) + +describe('arrangeCloudWorkspaces', () => { + const rows = [ws(1, 'B'), ws(2), ws(3, 'A'), ws(4, 'B'), ws(5, null, true)] + + it('keeps the server order and sorts sections by name with No section last, by default', () => { + expect(shape(arrangeCloudWorkspaces(rows, EMPTY_CLOUD_WORKSPACE_PREFS))).toEqual([ + ['section:A', [3], false], + ['section:B', [1, 4], false], + ['none', [2, 5], false] + ]) + }) + + it('puts pins on top in pin order, follows manual and section order, and collapses', () => { + const prefs = doc({ + pinned: [id(4), id(9), id(2), id(5)], + order: [id(3)], + sections: ['B', 'A'], + collapsed: ['A'] + }) + expect(shape(arrangeCloudWorkspaces(rows, prefs))).toEqual([ + // id 5 is archived: it keeps its pin but never sits in Pinned. + ['pinned', [4, 2], false], + ['section:B', [1], false], + ['section:A', [3], true], + ['none', [5], false] + ]) + }) +}) + +describe('arrangement edits', () => { + it('pins to the bottom of Pinned and leaves the manual order', () => { + const start = doc({ pinned: [id(1)], order: [id(2), id(3)] }) + expect(setPinned(start, id(2), true)).toEqual(doc({ pinned: [id(1), id(2)], order: [id(3)] })) + expect(setPinned(start, id(1), false)).toEqual(doc({ order: [id(2), id(3)] })) + expect(setPinned(start, id(1), true)).toBe(start) + }) + + it('reorders a group without disturbing ids it does not show', () => { + const start = doc({ pinned: [id(1), id(2), id(3)], order: [id(7), id(8), id(9)] }) + expect(reorderGroup(start, { kind: 'pinned' }, [id(3), id(1)]).pinned).toEqual([ + id(3), + id(1), + id(2) + ]) + expect(reorderGroup(start, { kind: 'section' }, [id(9), id(5)]).order).toEqual([ + id(9), + id(5), + id(7), + id(8) + ]) + }) + + it('moves rows by one place and onto another row', () => { + expect(nudge(['a', 'b', 'c'], 'a', 1)).toEqual(['b', 'a', 'c']) + expect(nudge(['a', 'b', 'c'], 'a', -1)).toBeNull() + expect(dropOnto(['a', 'b', 'c'], 'a', 'c')).toEqual(['b', 'c', 'a']) + expect(dropOnto(['a', 'b', 'c'], 'c', 'a')).toEqual(['c', 'a', 'b']) + expect(dropOnto(['a', 'b'], 'a', 'a')).toBeNull() + }) + + it('orders sections among those shown and toggles collapse', () => { + const start = doc({ sections: ['Old'] }) + expect(moveSection(start, ['A', 'B'], 'B', -1)?.sections).toEqual(['B', 'A', 'Old']) + expect(moveSection(start, ['A', 'B'], 'A', -1)).toBeNull() + expect(setCollapsed(start, 'A', true).collapsed).toEqual(['A']) + expect(setCollapsed(doc({ collapsed: ['A'] }), 'A', false).collapsed).toEqual([]) + }) +}) diff --git a/src/shared/cloud-workspaces/cloud-workspace-arrangement.ts b/src/shared/cloud-workspaces/cloud-workspace-arrangement.ts new file mode 100644 index 00000000000..e31ad1f5271 --- /dev/null +++ b/src/shared/cloud-workspaces/cloud-workspace-arrangement.ts @@ -0,0 +1,182 @@ +// How a member's cloud workspace list is arranged from their synced prefs (/v1/team/prefs): Pinned +// on top in pin order, then sections in their order, rows in their manual order. Pure and shared, +// so the desktop's Home and the phone follow the same rules. +import type { CloudWorkspacePrefsDocument } from './cloud-workspaces-wire' + +/** What arranging needs from a workspace (the desktop's and the phone's shapes both fit). */ +export type ArrangeableWorkspace = { + id: string + section?: string | null + archivedAt?: number | null +} + +export const MAX_PINNED = 200 +const MAX_ORDER = 500 + +export type CloudWorkspaceGroup = { + /** Stable React key and drag scope: `pinned`, `section:` or `none`. */ + key: string + kind: 'pinned' | 'section' | 'none' + section: string | null + rows: W[] + collapsed: boolean +} + +/** Rows ranked by an explicit id list first (in that order), then the rest in their incoming order. */ +function rankBy(rows: readonly T[], ids: readonly string[]): T[] { + const rank = new Map(ids.map((id, index) => [id, index])) + return rows + .map((row, index) => ({ row, index, rank: rank.get(row.id) })) + .sort((a, b) => + a.rank !== undefined && b.rank !== undefined + ? a.rank - b.rank + : a.rank !== undefined + ? -1 + : b.rank !== undefined + ? 1 + : a.index - b.index + ) + .map((entry) => entry.row) +} + +/** Archived workspaces never sit in Pinned (they keep their pin for when they come back). */ +export function isPinnedRow(w: ArrangeableWorkspace, doc: CloudWorkspacePrefsDocument): boolean { + return (w.archivedAt ?? null) === null && doc.pinned.includes(w.id) +} + +export function arrangeCloudWorkspaces( + visible: readonly W[], + doc: CloudWorkspacePrefsDocument +): CloudWorkspaceGroup[] { + const pinned = rankBy( + visible.filter((w) => isPinnedRow(w, doc)), + doc.pinned + ) + const rest = rankBy( + visible.filter((w) => !isPinnedRow(w, doc)), + doc.order + ) + const bySection = new Map() + for (const w of rest) { + const key = w.section ?? '' + bySection.set(key, [...(bySection.get(key) ?? []), w]) + } + const sectionRank = new Map(doc.sections.map((name, index) => [name, index])) + const sections = [...bySection.keys()].sort((a, b) => { + if (a === '' || b === '') { + return a === '' ? 1 : -1 + } + const ra = sectionRank.get(a) + const rb = sectionRank.get(b) + if (ra !== undefined || rb !== undefined) { + return ra === undefined ? 1 : rb === undefined ? -1 : ra - rb + } + return a.localeCompare(b) + }) + const groups: CloudWorkspaceGroup[] = [] + if (pinned.length > 0) { + groups.push({ key: 'pinned', kind: 'pinned', section: null, rows: pinned, collapsed: false }) + } + for (const section of sections) { + groups.push({ + key: section ? `section:${section}` : 'none', + kind: section ? 'section' : 'none', + section: section || null, + rows: bySection.get(section)!, + collapsed: section !== '' && doc.collapsed.includes(section) + }) + } + return groups +} + +export function setPinned( + doc: CloudWorkspacePrefsDocument, + id: string, + pinned: boolean +): CloudWorkspacePrefsDocument { + if (pinned === doc.pinned.includes(id)) { + return doc + } + return pinned + ? { + ...doc, + // A new pin goes to the bottom of Pinned, like dropping it there. + pinned: [...doc.pinned, id].slice(-MAX_PINNED), + order: doc.order.filter((other) => other !== id) + } + : { ...doc, pinned: doc.pinned.filter((other) => other !== id) } +} + +/** + * The group's rows now read `ids` top to bottom (after a drag or Move up/down). Pinned rewrites + * pin order; a section moves those rows to the front of the manual order, keeping their sequence. + * Ids outside the group (other sections, or rows a filter hides) keep their places. + */ +export function reorderGroup( + doc: CloudWorkspacePrefsDocument, + group: Pick, + ids: readonly string[] +): CloudWorkspacePrefsDocument { + const moved = new Set(ids) + if (group.kind === 'pinned') { + const hidden = doc.pinned.filter((id) => !moved.has(id)) + return { ...doc, pinned: [...ids, ...hidden].slice(0, MAX_PINNED) } + } + const others = doc.order.filter((id) => !moved.has(id)) + return { + ...doc, + order: [...ids.filter((id) => !doc.pinned.includes(id)), ...others].slice(0, MAX_ORDER) + } +} + +/** Moves `id` by `delta` places within the group's current rows (Move up / Move down). */ +export function nudge(ids: readonly string[], id: string, delta: number): string[] | null { + const from = ids.indexOf(id) + const to = from + delta + if (from === -1 || to < 0 || to >= ids.length) { + return null + } + const next = [...ids] + next.splice(from, 1) + next.splice(to, 0, id) + return next +} + +/** Moves `id` to sit where `overId` is (drag and drop within one group). */ +export function dropOnto(ids: readonly string[], id: string, overId: string): string[] | null { + if (id === overId || !ids.includes(id) || !ids.includes(overId)) { + return null + } + return nudge(ids, id, ids.indexOf(overId) - ids.indexOf(id)) +} + +/** Section order after moving `section` by `delta` among the sections shown right now. */ +export function moveSection( + doc: CloudWorkspacePrefsDocument, + shown: readonly string[], + section: string, + delta: number +): CloudWorkspacePrefsDocument | null { + const next = nudge(shown, section, delta) + if (!next) { + return null + } + const rest = doc.sections.filter((name) => !next.includes(name)) + return { ...doc, sections: [...next, ...rest].slice(0, 50) } +} + +export function setCollapsed( + doc: CloudWorkspacePrefsDocument, + section: string, + collapsed: boolean +): CloudWorkspacePrefsDocument { + if (collapsed === doc.collapsed.includes(section)) { + return doc + } + return { + ...doc, + collapsed: collapsed + ? [...doc.collapsed, section].slice(-50) + : doc.collapsed.filter((name) => name !== section) + } +} diff --git a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts index 0f9da6ad93f..59a9eba8c00 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts @@ -37,6 +37,10 @@ export const CloudWorkspaceSchema = z.object({ region: z.string(), createdAt: z.number(), title: z.string().nullable(), + // Its number in the account, shown as W-123 (formatWorkspaceNumber). Older control planes omit it. + number: z.number().int().positive().nullable().optional().catch(undefined), + // The link to copy (org slug + number, or the sandbox id form). Older control planes omit it. + link: z.string().max(512).optional().catch(undefined), repo: z.object({ url: z.string(), branch: z.string().nullable() }).nullable(), visibility: z.enum(['private', 'team']), section: z.string().nullable(), @@ -154,27 +158,106 @@ export const OrgPromptsSchema = z.object({ }) export type OrgPrompts = z.infer -/** Deep links: orca://cloud/w/[/c/] (desktop and mobile). */ -const LINK = /^orca:\/\/cloud\/w\/(sbx_[0-9a-f]{24})(?:\/c\/([A-Za-z0-9_.:%-]{1,256}))?\/?$/ +/** W-123: how a workspace's number reads everywhere (list, top bar, palette, links). */ +export function formatWorkspaceNumber(n: number): string { + return `W-${n}` +} + +/** "W-123", "w123", "#123" or "123" → 123; anything else is null (palette search, pasted ids). */ +export function parseWorkspaceNumber(text: string): number | null { + const match = /^\s*(?:w-?|#)?(\d{1,9})\s*$/i.exec(text) + const n = match ? Number(match[1]) : Number.NaN + return Number.isSafeInteger(n) && n > 0 ? n : null +} + +// Synced sidebar arrangement (/v1/team/prefs; mirrors sandbox-control src/workspace-prefs.ts). +const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/) +const SectionName = z.string().min(1).max(64) +export const CloudWorkspacePrefsDocumentSchema = z.object({ + pinned: z.array(SandboxId).max(200), + order: z.array(SandboxId).max(500), + sections: z.array(SectionName).max(50), + collapsed: z.array(SectionName).max(50) +}) +export type CloudWorkspacePrefsDocument = z.infer +export const CloudWorkspacePrefsSchema = z.object({ + document: CloudWorkspacePrefsDocumentSchema, + revision: z.number().int().min(0), + updatedAt: z.number().nullable() +}) +export type CloudWorkspacePrefs = z.infer +export const EMPTY_CLOUD_WORKSPACE_PREFS: CloudWorkspacePrefsDocument = { + pinned: [], + order: [], + sections: [], + collapsed: [] +} + +/** /v1/team/org: the org's URL slug for links (null for personal accounts or before it is named). */ +export const CloudOrgSlugSchema = z.object({ + slug: z.string().nullable(), + orgId: z.string().nullable() +}) +export type CloudOrgSlug = z.infer + +/** What a link names: a sandbox id (orca://cloud/w/) or an org slug and number (orca://cloud//W-). */ +export type CloudWorkspaceLinkTarget = + | { kind: 'id'; workspaceId: string } + | { kind: 'number'; org: string; number: number } + +/** + * Deep links (desktop and mobile): + * orca://cloud/w/[/c/] works for any account + * orca://cloud//W-[/c/] what Copy link gives in a team + */ +const ID_LINK = /^orca:\/\/cloud\/w\/(sbx_[0-9a-f]{24})(?:\/c\/([A-Za-z0-9_.:%-]{1,256}))?\/?$/ +const NUMBER_LINK = + /^orca:\/\/cloud\/([a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)\/[Ww]-(\d{1,9})(?:\/c\/([A-Za-z0-9_.:%-]{1,256}))?\/?$/ export function cloudWorkspaceLink(id: string, chatId?: string | null): string { return `orca://cloud/w/${id}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}` } -export function parseCloudWorkspaceLink( - url: string -): { workspaceId: string; chatId: string | null } | null { - const match = LINK.exec(url.trim()) - if (!match) { +/** The server's link for a workspace (slug form when it has one), with a chat appended. */ +export function cloudWorkspaceShareLink( + workspace: { id: string; link?: string }, + chatId?: string | null +): string { + const base = workspace.link && parseCloudWorkspaceLink(workspace.link) ? workspace.link : null + if (!base) { + return cloudWorkspaceLink(workspace.id, chatId) + } + return `${base.replace(/\/$/, '')}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}` +} + +function decodeChat(raw: string | undefined): string | null | undefined { + if (!raw) { return null } - let chatId: string | null = null - if (match[2]) { - try { - chatId = decodeURIComponent(match[2]) - } catch { - return null - } + try { + return decodeURIComponent(raw) + } catch { + return undefined } - return { workspaceId: match[1]!, chatId } +} + +export function parseCloudWorkspaceLink( + url: string +): { target: CloudWorkspaceLinkTarget; chatId: string | null } | null { + const text = url.trim() + const byId = ID_LINK.exec(text) + if (byId) { + const chatId = decodeChat(byId[2]) + return chatId === undefined ? null : { target: { kind: 'id', workspaceId: byId[1]! }, chatId } + } + const byNumber = NUMBER_LINK.exec(text) + if (!byNumber || byNumber[1]!.includes('--')) { + return null + } + const number = Number(byNumber[2]) + const chatId = decodeChat(byNumber[3]) + if (!Number.isSafeInteger(number) || number < 1 || chatId === undefined) { + return null + } + return { target: { kind: 'number', org: byNumber[1]!, number }, chatId } } diff --git a/src/shared/cloud-workspaces/cloud-workspaces.test.ts b/src/shared/cloud-workspaces/cloud-workspaces.test.ts index 0bc74a18539..ea084bb12b1 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces.test.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces.test.ts @@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest' import { CloudWorkspaceSchema, cloudWorkspaceLink, - parseCloudWorkspaceLink + cloudWorkspaceShareLink, + formatWorkspaceNumber, + parseCloudWorkspaceLink, + parseWorkspaceNumber } from './cloud-workspaces-wire' import { base64ToBytes, bytesToBase64 } from './sealed-grant' import { parseSenderEnvelope, withSenderEnvelope } from './sender-envelope' @@ -12,25 +15,61 @@ const ID = 'sbx_0123456789abcdef01234567' describe('cloud workspace links', () => { it('round-trips workspace and chat links', () => { expect(parseCloudWorkspaceLink(cloudWorkspaceLink(ID))).toEqual({ - workspaceId: ID, + target: { kind: 'id', workspaceId: ID }, chatId: null }) expect(parseCloudWorkspaceLink(cloudWorkspaceLink(ID, 'chat 1/2'))).toEqual({ - workspaceId: ID, + target: { kind: 'id', workspaceId: ID }, chatId: 'chat 1/2' }) }) + it('parses org slug and number links', () => { + expect(parseCloudWorkspaceLink('orca://cloud/acme-labs/W-123')).toEqual({ + target: { kind: 'number', org: 'acme-labs', number: 123 }, + chatId: null + }) + expect(parseCloudWorkspaceLink('orca://cloud/acme/w-7/c/s%3Aabc/')).toEqual({ + target: { kind: 'number', org: 'acme', number: 7 }, + chatId: 's:abc' + }) + }) + + it('copies the server link with the chat appended, or falls back to the id form', () => { + expect(cloudWorkspaceShareLink({ id: ID, link: 'orca://cloud/acme/W-3' }, 's:1')).toBe( + 'orca://cloud/acme/W-3/c/s%3A1' + ) + expect(cloudWorkspaceShareLink({ id: ID })).toBe(`orca://cloud/w/${ID}`) + expect(cloudWorkspaceShareLink({ id: ID, link: 'https://evil.example/x' })).toBe( + `orca://cloud/w/${ID}` + ) + }) + it('rejects anything that is not a cloud workspace link', () => { for (const bad of [ 'orca://cloud/w/sbx_nothex', `https://cloud/w/${ID}`, `orca://cloud/w/${ID}/x`, - `orca://cloud/w/${ID}/c/%E0%A4%A` + `orca://cloud/w/${ID}/c/%E0%A4%A`, + 'orca://cloud/setup/return?session=cs_1', + 'orca://cloud/Acme/W-1', + 'orca://cloud/a--b/W-1', + 'orca://cloud/acme/W-0', + 'orca://cloud/acme/W-x' ]) { expect(parseCloudWorkspaceLink(bad)).toBeNull() } }) + + it('formats and parses workspace numbers', () => { + expect(formatWorkspaceNumber(42)).toBe('W-42') + for (const text of ['W-42', 'w42', '#42', ' 42 ']) { + expect(parseWorkspaceNumber(text)).toBe(42) + } + for (const text of ['W-', 'W-0', 'fix 42', '4.2', '']) { + expect(parseWorkspaceNumber(text)).toBeNull() + } + }) }) describe('sealed grant base64', () => { From 8f0da9a0c02ea330fbc4a5b0260dfe9931f30cfc Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:56:39 -0800 Subject: [PATCH 03/26] =?UTF-8?q?fix(cloud):=20design-squad=20notes=20for?= =?UTF-8?q?=20G13/G14=20=E2=80=94=20W-number=20on=20hover,=20chip=20confir?= =?UTF-8?q?ms=20in=20place,=20other-team=20copy,=20move=20announcements,?= =?UTF-8?q?=20phone=20Pin=20row?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mobile/src/cloud/CloudWorkspaceActions.tsx | 38 +++++++++- .../CloudWorkspaceNumberChip.tsx | 72 ++++++++++++------- .../cloud-workspaces/CloudWorkspaceRow.tsx | 16 +++-- .../CloudWorkspacesHome.fixture.tsx | 31 ++++++++ .../cloud-workspaces/CloudWorkspacesHome.tsx | 3 + .../cloud-workspace-link-failure.ts | 70 ++++++++++++++++++ .../cloud-workspaces/cloud-workspace-links.ts | 50 ++----------- .../cloud-workspaces.test-fixture.ts | 1 + .../cloud-workspaces/open-cloud-workspace.ts | 12 +++- .../use-cloud-workspace-arrangement.ts | 52 ++++++++++++-- 10 files changed, 261 insertions(+), 84 deletions(-) create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-link-failure.ts 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/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx index 33ff34cce80..ba526b56884 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx @@ -1,15 +1,19 @@ // W-123 in the top bar when the workspace in front is a cloud workspace; click copies its link -// (the same as ⌘⌥⇧L). Renders nothing for local workspaces or before the number is known. -import React from 'react' +// (the same as ⌘⌥⇧L) and confirms in place. Renders nothing for local workspaces or before the +// number is known. +import React, { useEffect, useState } from 'react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { formatOptionalPrimaryShortcutLabel } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { formatWorkspaceNumber } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { sandboxIdForWorktree, useCloudWorkspaceIdentities } from './cloud-workspace-identity' import { frontCloudChat } from './cloud-workspace-links' import { copyCloudWorkspaceLink } from './open-cloud-workspace' +const COPIED_MS = 1_500 + export function CloudWorkspaceNumberChip({ worktreeId }: { @@ -19,6 +23,14 @@ export function CloudWorkspaceNumberChip({ const hostId = useAppStore((s) => s.activeWorkspaceExecutionHostId) const keybindings = useAppStore((s) => s.keybindings) const identities = useCloudWorkspaceIdentities() + const [copied, setCopied] = useState(false) + useEffect(() => { + if (!copied) { + return + } + const timer = setTimeout(() => setCopied(false), COPIED_MS) + return () => clearTimeout(timer) + }, [copied]) const sandboxId = sandboxIdForWorktree({ id: worktreeId, hostId }, identities) const number = sandboxId ? (identities.bySandbox.get(sandboxId)?.number ?? null) : null if (!sandboxId || !number) { @@ -26,30 +38,42 @@ export function CloudWorkspaceNumberChip({ } const label = formatWorkspaceNumber(number) const shortcut = formatOptionalPrimaryShortcutLabel('cloudWorkspace.copyLink', keybindings) + const copiedLabel = t('auto.components.cloudWorkspaces.linkCopiedShort', 'Link copied') return ( - - - + + + {t('auto.components.cloudWorkspaces.copyLinkTo', 'Copy link to {{number}}', { number: label })} - className="mr-2 flex h-6 items-center rounded-md px-1.5 font-mono text-2xs tabular-nums text-muted-foreground outline-none [-webkit-app-region:no-drag] hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-focus-ring" - > - {label} - -
    - - {t('auto.components.cloudWorkspaces.copyLink', 'Copy link')} - {shortcut ? {shortcut} : null} - -
    + {shortcut ? {shortcut} : null} + + + + {copied ? copiedLabel : ''} + + ) } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index a10782d92c4..de842b69ba1 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -248,11 +248,6 @@ export function CloudWorkspaceRow({ > {title} - {w.number ? ( - - {formatWorkspaceNumber(w.number)} - - ) : null} {w.visibility === 'private' && ( @@ -278,6 +273,17 @@ export function CloudWorkspaceRow({ )} + {/* Its W-number shows on hover or focus only; the space is held so nothing shifts. */} + {w.number ? ( + + {formatWorkspaceNumber(w.number)} + + ) : null} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx index 065515832eb..dcf8f9a9f50 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx @@ -7,6 +7,8 @@ import { workspace } from './cloud-workspaces.test-fixture' import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state' +import type { CloudWorkspacePrefsDocument } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { setPrefsAccount } from './cloud-workspace-prefs' const WIDTH = 760 @@ -29,6 +31,35 @@ export const teamList = defineFixture({ interact: () => waitFor(() => document.querySelector('[data-cloud-workspace-row]') !== null) }) +/** Synced prefs: two pins on top (pin order), Payments collapsed, rows in their manual order. */ +export const pinnedAndArranged = defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => { + const rows = teamWorkspaces() + stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) + const document: CloudWorkspacePrefsDocument = { + pinned: [rows[3]!.id, rows[0]!.id], + order: [rows[2]!.id], + sections: ['Payments'], + collapsed: [] + } + Object.assign(window.api.cloudWorkspaces, { + getPrefs: () => + Promise.resolve({ ok: true as const, value: { document, revision: 3, updatedAt: 1 } }), + putPrefs: (next: CloudWorkspacePrefsDocument) => + Promise.resolve({ + ok: true as const, + value: { document: next, revision: 4, updatedAt: 2 } + }) + }) + setPrefsAccount(`fixture:${Math.random()}`) + }, + render: () => , + interact: () => + waitFor(() => document.querySelector('[data-cloud-workspace-group="pinned"]') !== null) +}) + /** A link pointed at this row; Home rings it while it opens. */ export const highlightedFromLink = defineFixture({ width: WIDTH, diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index e83ebd1c9ec..2bca60961da 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -369,6 +369,9 @@ export function CloudWorkspacesHome({ {/* Polite, so opening from a link is announced without stealing focus. */} +
    + {arrangement.announcement} +
    {highlighted ? t('auto.components.cloudWorkspaces.openedFromLink', 'Opened from link: {{title}}', { diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-link-failure.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-link-failure.ts new file mode 100644 index 00000000000..a5af4144a47 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-link-failure.ts @@ -0,0 +1,70 @@ +// What a cloud workspace link that didn't resolve tells the user. A W-number link names the +// workspace ("You don't have access to W-12."); one for a team you're in but don't have active +// offers to switch to that team and open it. +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import { + formatWorkspaceNumber, + type CloudWorkspaceLinkTarget +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { describeError } from './cloud-workspace-errors' + +type Failure = { error: string; reason?: string; orgId?: string } + +export function reportCloudWorkspaceLinkFailure( + target: CloudWorkspaceLinkTarget, + failure: Failure, + /** Opens the same link again (after a team switch). */ + retry: () => void +): void { + if (target.kind === 'number' && failure.error === 'not_found') { + const label = formatWorkspaceNumber(target.number) + if (failure.reason !== 'other_org' || !offerTeamSwitch(failure.orgId, label, retry)) { + toast.error( + translate( + 'auto.components.cloudWorkspaces.linkNoAccess', + "You don't have access to {{number}}.", + { + number: label + } + ) + ) + } + return + } + toast.error( + failure.error === 'not_found' + ? translate( + 'auto.components.cloudWorkspaces.linkNotFound', + 'This link points to a private workspace, another team, or a workspace that was deleted.' + ) + : describeError(failure.error, failure.reason) + ) +} + +/** False when you are not in that team (then it's plain "no access"). */ +function offerTeamSwitch(orgId: string | undefined, label: string, retry: () => void): boolean { + const state = useAppStore.getState() + const org = orgId + ? state.orcaProfileAuthStatus?.organizations?.find((o) => o.orgId === orgId) + : undefined + if (!org) { + return false + } + toast.info( + translate('auto.components.cloudWorkspaces.linkOtherTeam2', '{{number}} is in {{team}}.', { + number: label, + team: org.name + }), + { + action: { + label: translate('auto.components.cloudWorkspaces.linkSwitchTeam', 'Switch and open'), + onClick: () => { + void state.selectOrcaProfileOrg(org.orgId).then(retry) + } + } + } + ) + return true +} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts index 542a2f35efc..4f1df5920ad 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-links.ts @@ -3,12 +3,11 @@ import { useSyncExternalStore } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' -import { translate } from '@/i18n/i18n' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' import { parseCloudWorkspaceLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { reportCloudWorkspaceLinkFailure } from './cloud-workspace-link-failure' import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' -import { describeError } from './cloud-workspace-errors' import { copyCloudWorkspaceLink, openCloudWorkspace } from './open-cloud-workspace' import { currentCloudChatId, focusCloudChat } from './cloud-chat-focus' import { cloudWorkspacesAvailable } from './use-cloud-workspaces' @@ -54,19 +53,10 @@ export async function handleCloudWorkspaceLink(link: string): Promise { } const resolved = await window.api.cloudWorkspaces.resolveLink(parsed.target, parsed.chatId) if (!resolved.ok) { - if (resolved.reason === 'other_org' && offerTeamSwitch(resolved.orgId, link)) { - setHighlight(null) - return - } - toast.error( - resolved.error === 'not_found' - ? translate( - 'auto.components.cloudWorkspaces.linkNotFound', - 'This link points to a private workspace, another team, or a workspace that was deleted.' - ) - : describeError(resolved.error, resolved.reason) - ) setHighlight(null) + reportCloudWorkspaceLinkFailure(parsed.target, resolved, () => { + void handleCloudWorkspaceLink(link) + }) return } const workspace = resolved.value.workspace @@ -81,38 +71,6 @@ export async function handleCloudWorkspaceLink(link: string): Promise { setHighlight(workspace.id, HIGHLIGHT_MS) } -/** - * A W-number link from a team you belong to but don't have active: say which team, and offer to - * switch and open it. False when you are not in that team (the generic not-found copy applies). - */ -function offerTeamSwitch(orgId: string | undefined, link: string): boolean { - const state = useAppStore.getState() - const org = orgId - ? state.orcaProfileAuthStatus?.organizations?.find((o) => o.orgId === orgId) - : undefined - if (!org) { - return false - } - toast.info( - translate('auto.components.cloudWorkspaces.linkOtherTeam', 'This workspace is in {{team}}', { - team: org.name - }), - { - description: translate( - 'auto.components.cloudWorkspaces.linkOtherTeamHint', - 'Switch teams to open it.' - ), - action: { - label: translate('auto.components.cloudWorkspaces.linkSwitchTeam', 'Switch and open'), - onClick: () => { - void state.selectOrcaProfileOrg(org.orgId).then(() => handleCloudWorkspaceLink(link)) - } - } - } - ) - return true -} - type Front = { sandboxId: string owner: boolean diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts index d8e39892b67..7685f70f93d 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts @@ -65,6 +65,7 @@ export function workspace(overrides: Partial): CloudWorkspace { region: 'iad1', createdAt: FIXTURE_NOW - 86_400_000, title: null, + number: 40 + next, repo: { url: 'https://github.com/acme/payments.git', branch: 'main' }, visibility: 'team', section: null, diff --git a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts index 27ed59a8420..aed4fcffd94 100644 --- a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts +++ b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts @@ -250,7 +250,11 @@ async function shareLinkFor(id: string, chatId?: string | null): Promise return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId) } -export async function copyCloudWorkspaceLink(id: string, chatId?: string | null): Promise { +export async function copyCloudWorkspaceLink( + id: string, + chatId?: string | null, + options: { quiet?: boolean } = {} +): Promise { try { await navigator.clipboard.writeText(await shareLinkFor(id, chatId)) } catch (error) { @@ -258,11 +262,15 @@ export async function copyCloudWorkspaceLink(id: string, chatId?: string | null) toast.error( translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.") ) - return + return false + } + if (options.quiet) { + return true } toast.success( chatId ? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied') : translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied') ) + return true } diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts index 6e74544d677..b432f2e78a5 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts @@ -3,7 +3,10 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { + formatWorkspaceNumber, + type CloudWorkspace +} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { MAX_PINNED, arrangeCloudWorkspaces, @@ -24,8 +27,21 @@ import { import type { GroupDrag } from './CloudWorkspaceGroup' import type { RowArrangement } from './CloudWorkspaceRowMenu' +/** How a screen reader hears a workspace in move confirmations: its number, else its title. */ +function spoken(w: CloudWorkspace | undefined): string { + return w?.number ? formatWorkspaceNumber(w.number) : (w?.title ?? '') +} + +function groupName(group: CloudWorkspaceGroup): string { + return group.kind === 'pinned' + ? translate('auto.components.cloudWorkspaces.pinned', 'Pinned') + : (group.section ?? translate('auto.components.cloudWorkspaces.noSection', 'No section')) +} + export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) { const prefs = useCloudWorkspacePrefs() + // Drags and menu moves are confirmed politely for screen readers ("Moved W-12 to position 2 in Pinned"). + const [announcement, setAnnouncement] = useState('') // Opening Home is a good moment to pick up another device's edits without waiting for the poll. useEffect(() => { void refreshCloudWorkspacePrefs() @@ -40,10 +56,22 @@ export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) [groups] ) const reorder = useCallback( - (group: CloudWorkspaceGroup, ids: string[] | null) => { - if (ids) { - void editCloudWorkspacePrefs((doc) => reorderGroup(doc, group, ids)) + (group: CloudWorkspaceGroup, ids: string[] | null, movedId: string) => { + if (!ids) { + return } + void editCloudWorkspacePrefs((doc) => reorderGroup(doc, group, ids)) + setAnnouncement( + translate( + 'auto.components.cloudWorkspaces.movedTo', + 'Moved {{name}} to position {{position}} in {{group}}', + { + name: spoken(group.rows.find((w) => w.id === movedId)), + position: ids.indexOf(movedId) + 1, + group: groupName(group) + } + ) + ) }, [] ) @@ -63,7 +91,8 @@ export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) group.rows.map((w) => w.id), dragging.id, overId - ) + ), + dragging.id ) } setDragging(null) @@ -84,6 +113,15 @@ export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) return } void editCloudWorkspacePrefs((doc) => setPinned(doc, w.id, pinned)) + setAnnouncement( + pinned + ? translate('auto.components.cloudWorkspaces.pinnedName', 'Pinned {{name}}', { + name: spoken(w) + }) + : translate('auto.components.cloudWorkspaces.unpinnedName', 'Unpinned {{name}}', { + name: spoken(w) + }) + ) }, []) const move = useCallback( @@ -96,7 +134,8 @@ export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) group.rows.map((row) => row.id), w.id, delta - ) + ), + w.id ) } }, @@ -128,6 +167,7 @@ export function useCloudWorkspaceArrangement(visible: readonly CloudWorkspace[]) ) return { + announcement, groups, drag, pin, From 077d4c81046d7a6441e1ef7c23f4b5929248a00b Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:02:29 -0800 Subject: [PATCH 04/26] feat(billing): usage history, top workspaces and members, one spend cap field (JA-18) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plan & billing now reads ' · Team plan', shows the last 30 days of sandbox hours as a bar chart, and (owners/admins) the top workspaces and members. Members see the team chart and their own hours. The overage toggle becomes one 'Monthly spend cap' field ($0 = off, 'Turn on with a $25 cap'); the rate is a one-line hint; alert levels are read-only values. The manual refresh icon is gone. Billing Worker: additive GET /v1/billing/usage (read-only over usage_events, no migration). --- cloud/apps/billing/src/index.ts | 15 + cloud/apps/billing/src/usage-history.ts | 103 ++++++ cloud/apps/billing/test/usage-history.test.ts | 98 ++++++ src/main/billing/billing-client.ts | 13 +- src/main/billing/billing-service.ts | 28 +- src/main/billing/billing-usage-client.test.ts | 72 ++++ src/main/billing/billing-usage-client.ts | 67 ++++ .../profiles/orca-profile-billing-handlers.ts | 31 +- src/preload/api/orca-profile-api.ts | 7 +- src/preload/api/orca-profiles-bridge.ts | 1 + .../billing/PlanBillingSection.fixture.tsx | 22 +- .../components/billing/PlanBillingSection.tsx | 113 +++--- .../billing/PlanBillingUsage.test.tsx | 154 ++++++++ .../components/billing/PlanBillingUsage.tsx | 331 +++++++++--------- .../PlanBillingUsageHistory.fixture.tsx | 101 ++++++ .../billing/PlanBillingUsageHistory.tsx | 137 ++++++++ .../components/billing/UsageHistoryChart.tsx | 152 ++++++++ .../billing/plan-billing-fixtures.ts | 60 +++- .../plan-billing-usage-history.test.ts | 75 ++++ .../billing/plan-billing-usage-history.ts | 169 +++++++++ .../billing/use-plan-billing-usage-history.ts | 114 ++++++ .../web/preload-api/web-orca-profiles-api.ts | 1 + src/shared/orca-billing.ts | 37 +- 23 files changed, 1682 insertions(+), 219 deletions(-) create mode 100644 cloud/apps/billing/src/usage-history.ts create mode 100644 cloud/apps/billing/test/usage-history.test.ts create mode 100644 src/main/billing/billing-usage-client.test.ts create mode 100644 src/main/billing/billing-usage-client.ts create mode 100644 src/renderer/src/components/billing/PlanBillingUsage.test.tsx create mode 100644 src/renderer/src/components/billing/PlanBillingUsageHistory.fixture.tsx create mode 100644 src/renderer/src/components/billing/PlanBillingUsageHistory.tsx create mode 100644 src/renderer/src/components/billing/UsageHistoryChart.tsx create mode 100644 src/renderer/src/components/billing/plan-billing-usage-history.test.ts create mode 100644 src/renderer/src/components/billing/plan-billing-usage-history.ts create mode 100644 src/renderer/src/components/billing/use-plan-billing-usage-history.ts 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/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/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/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: '