Merge remote-tracking branch 'private/cloud/integration' into fix/ja02-signin-cancel

# Conflicts:
#	src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx
#	src/renderer/src/i18n/locales/en.json
This commit is contained in:
Neil
2026-11-10 20:58:17 -08:00
155 changed files with 6986 additions and 763 deletions
File diff suppressed because one or more lines are too long
@@ -178,9 +178,12 @@ ca_env=(NODE_USE_SYSTEM_CA="${NODE_USE_SYSTEM_CA:-1}")
for name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do
if [ -n "${!name:-}" ]; then ca_env+=("$name=${!name}"); fi
done
# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's
# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.
env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 TERM=xterm-256color "${ca_env[@]}" \
PATH="$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname "$system_node"):/usr/local/bin:/usr/bin:/bin" \
ORCA_USER_DATA="$HOME/.orcad-data" ORCA_SANDBOX_ID="$ORCA_SANDBOX_ID" "${managed_env[@]}" \
ORCA_HOST_MANAGED_LISTENER_PATHS="$ORCA_HOME" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \
NODE_COMPILE_CACHE="$ORCA_HOME/compile-cache" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR="$ORCA_HOME/startup-qualification" \
ORCA_SESSION_ENV_NAMES="${secret_names[*]}" "${agent_env[@]}" \
setsid nohup "$node" "$ORCA_HOME/bin/orcad-boot" --code-cache "$ORCA_HOME/compile-cache/orcad-server.v8" \
@@ -0,0 +1,35 @@
-- Teammate profiles and Pokes (team-presence). Additive; older Workers ignore all of it.
--
-- member_usage_hours: model spend each member's own client reported, by UTC hour. Filled from the
-- deltas of the cumulative sandboxes.token_usd_micros a client PATCHes, so it accrues from the
-- deploy onward. Compute time comes from usage_outbox and is not copied here.
CREATE TABLE IF NOT EXISTS member_usage_hours (
account_id TEXT NOT NULL,
user_id TEXT NOT NULL,
hour INTEGER NOT NULL, -- floor(ms / 3_600_000)
token_usd_micros INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (account_id, user_id, hour)
);
-- Heatmap reads compute segments per account and time window.
CREATE INDEX IF NOT EXISTS usage_outbox_account_started ON usage_outbox (account_id, started_at);
-- Pokes are opt-in (Settings → Experimental): a poke goes through only when both people have it on.
CREATE TABLE IF NOT EXISTS member_poke_prefs (
account_id TEXT NOT NULL,
user_id TEXT NOT NULL,
enabled INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (account_id, user_id)
);
CREATE TABLE IF NOT EXISTS member_pokes (
id TEXT PRIMARY KEY, -- pok_<24 hex>
account_id TEXT NOT NULL,
from_user_id TEXT NOT NULL,
to_user_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
seen_at INTEGER
);
CREATE INDEX IF NOT EXISTS member_pokes_inbox ON member_pokes (account_id, to_user_id, created_at);
CREATE INDEX IF NOT EXISTS member_pokes_sender ON member_pokes (account_id, from_user_id, created_at);
+6
View File
@@ -29,6 +29,12 @@ export type Env = {
MEMBER_GIT_IDENTITY?: string
/** How long after a member's own send their GitHub identity stays usable (default 30). */
MEMBER_GIT_WINDOW_MINUTES?: string
/**
* Who sees a member's daily activity heatmap on their profile. `opt_in` (default): only members
* who turned on "Pokes and activity". `team`: every teammate (Conductor's default). Config only,
* so flipping it needs no migration.
*/
TEAMMATE_ACTIVITY_SHARING?: string
/** `release:latest` | `release:v1.2.3`: build golden images from Orca's released orca-server tarball. */
GOLDEN_IMAGE_SOURCE?: string
/** TTL for Worker-built golden images; unset/0 keeps them until rotated out. */
+75 -7
View File
@@ -9,6 +9,7 @@
// the public API's POST /v1/workspaces/:id/wake answers the same fields plus `workspace`)
// POST /v1/sandboxes/:id/restart -> {sandbox, connection}
// GET /v1/sandboxes/:id/status -> {sandbox, status} (live metrics, cost)
// GET /v1/sandboxes/boot-plan?repo=<url> -> {repo: 'clone' | 'update'}
// GET /v1/sandboxes/:id/clone -> {clone: {state, percent?, stage?, reason?}}
// POST /v1/sandboxes/:id/archive {pullRequests?, checkouts?} -> {sandbox}
// GET /v1/sandboxes/:id/archive -> {archive}
@@ -28,6 +29,8 @@
// 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, …}
// /v1/team/members/:userId/(profile|poke), /v1/team/pokes[/settings|/seen]
// teammate profiles (usage heatmap, recent workspaces) and opt-in Pokes (src/team-presence.ts)
// /v1/sandboxes/* is the owner's lifecycle API: only the workspace's owner (and, for suspend and
// destroy, an org admin) can reach a row there, because resume hands back an orcad pairing offer.
// Browser (GitHub redirects): GET /v1/github/setup, GET /v1/github/callback
@@ -141,6 +144,8 @@ import { credentialTargets, type CredentialTarget } from './provider-env'
import type { Keyring } from './secrets-crypto'
import { ProviderError, type SandboxProviderApi } from './sandbox-provider'
import { readCloneStatus } from './clone-status'
import { readIdempotencyKey, withIdempotency } from './api/idempotency'
import { ApiError } from './api/caller'
import { ensureAutoEnvironment, expireAutoEnvironments, touchEnvironment } from './auto-environments'
import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands'
import { forgetShareLink, handleShareGateway } from './share-gateway'
@@ -151,7 +156,7 @@ import { getSandbox, getSandboxByProviderName, listAccountSandboxes, markUserSle
import { createVercelSandboxApi } from './vercel-sandbox-api'
import { advanceAllBuilds, tickBuild, unfinishedBuilds, type BuildDeps } from './environment-builds'
import { environmentErrorResponse, handleEnvironmentRoute, isEnvironmentRoute } from './environment-routes'
import { EnvironmentError } from './environments'
import { EnvironmentError, resolveEnvironmentBoot } from './environments'
import type { GoldenImageProviderApi } from './golden-image-provider'
import { CreateRequestSchema, LeaseRequestSchema, parseWakeWait, readyView, sandboxView } from './wire'
import { ArchiveRequestSchema } from './sandbox-vm-inspect'
@@ -202,6 +207,7 @@ import {
workspaceViews
} from './workspaces'
import { rememberCallerName } from './member-names'
import { TeamPresenceError, teamPresenceRoute } from './team-presence'
import { sweepSessionCpu } from './session-cpu'
import type { SandboxCaller } from './auth'
@@ -1480,7 +1486,10 @@ 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.startsWith('/v1/team/members/') ||
url.pathname === '/v1/team/pokes' ||
url.pathname.startsWith('/v1/team/pokes/')
) {
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
if (!caller) {
@@ -1488,6 +1497,20 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
}
return await workspaceRoute(request, url, env, deps, caller)
}
if (url.pathname === '/v1/sandboxes/boot-plan' && request.method === 'GET') {
// Whether a create of this repo would clone it or update a prebuilt copy, so the desktop names
// its repository step once, before the create answers (environments.ts resolveEnvironmentBoot).
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
if (!caller) {
return fail('unauthorized', 401)
}
const repo = url.searchParams.get('repo') ?? ''
if (repo.length === 0 || repo.length > 2048) {
return fail('invalid_request', 400)
}
const source = await resolveEnvironmentBoot(env.SANDBOX_DB, caller.accountId, { repoUrl: repo }).catch(() => null)
return json({ repo: source?.repoDir ? 'update' : 'clone' })
}
const match =
/^\/v1\/sandboxes(?:\/([A-Za-z0-9_]+)(?:\/(suspend|resume|lease|rollover|wake|restart|status|clone|archive|unarchive|env\/refresh|egress\/hosts|ssh-keys|desktop))?)?$/.exec(
url.pathname
@@ -1523,14 +1546,39 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
return fail('not_found', 404)
}
await consumeCreateToken(life.db, life.config.guardrails!, caller.accountId, life.now())
const body = CreateRequestSchema.safeParse(await readJson(request))
const raw = await readJson(request)
const body = CreateRequestSchema.safeParse(raw)
if (!body.success) {
return fail('invalid_request', 400)
}
// Desktops that show the clone as its own step ask for it in the background (GET .../clone).
const ready = await createSandbox(life, caller, { ...body.data, cloneInBackground: features.includes('clone-progress') })
await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode)
return readyResponse(ready, features.includes('repo-update'))
// Idempotency-Key (one per Create press): a re-sent create with the same key and body answers
// with the sandbox the first one made, for 24 h, instead of starting another (PC-8).
let timings: Ready['timings']
try {
const response = await withIdempotency(
life.db,
{ accountId: caller.accountId, scope: `sandbox.create:${caller.userId}`, key: readIdempotencyKey(request), body: raw, now: life.now() },
async () => {
// Desktops that show the clone as its own step ask for it in the background (GET .../clone).
const ready = await createSandbox(life, caller, { ...body.data, cloneInBackground: features.includes('clone-progress') })
await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode)
timings = ready.timings
return { status: 200, body: readyView(ready.row, ready.connection, ready.cloning, features.includes('repo-update')) }
}
)
const timing = Object.entries(timings ?? {})
.map(([phase, ms]) => `${phase};dur=${ms}`)
.join(', ')
if (timing) {
response.headers.set('server-timing', timing)
}
return response
} catch (error) {
if (error instanceof ApiError) {
return fail(error.code, error.status, error.reason)
}
throw error
}
}
const row = await getSandbox(env.SANDBOX_DB, id)
const route = `${request.method} ${action ?? ''}`
@@ -1832,6 +1880,26 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
if (url.pathname === '/v1/team/workspaces') {
return request.method === 'GET' ? json(await listWorkspaces(db, caller, url, now)) : fail('not_found', 404)
}
if (url.pathname.startsWith('/v1/team/members/') || url.pathname.startsWith('/v1/team/pokes')) {
try {
const answer = await teamPresenceRoute(db, caller, request, url, now, () => readJson(request), {
activitySharing: env.TEAMMATE_ACTIVITY_SHARING === 'team' ? 'team' : 'opt_in'
})
return answer === null ? fail('not_found', 404) : json(answer)
} catch (error) {
if (error instanceof TeamPresenceError) {
const response = json(
{ error: error.code, ...(error.reason ? { reason: error.reason } : {}), ...(error.retryAfterMs ? { retryAfterMs: error.retryAfterMs } : {}) },
error.status
)
if (error.retryAfterMs) {
response.headers.set('retry-after', String(Math.ceil(error.retryAfterMs / 1000)))
}
return response
}
throw error
}
}
const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname)
if (!match) {
return fail('not_found', 404)
@@ -28,6 +28,7 @@ import {
ORCAD_PORT,
SHARE_PROXY_PORT,
VmCommandError,
workspaceHostname,
drainOrcad,
runningOrcad,
startOrcad,
@@ -387,6 +388,8 @@ async function boot(
options.timer.time('orcad', async () =>
startOrcad(deps.provider, state, {
sandboxId: row.id,
// The workspace's name, else its repo's: never the provider's per-boot VM id.
hostname: workspaceHostname(row.name ?? (row.repo_url ? parseGitHubRepo(row.repo_url)?.repo : null)),
repo: options.repo,
// Repos hosted outside github.com get no GitHub credential, not even the placeholder.
githubPlaceholder: deps.config.egressProxyUrl && parseGitHubRepo(row.repo_url ?? '') ? githubPlaceholderToken(row) : undefined,
@@ -8,6 +8,7 @@ import type { LifecycleDeps } from './lifecycle'
import { memberChangeTime, recordMemberChange } from './member-changes'
import { revokeMemberReaderKeys } from './read-snapshots'
import { disableMemberRoutines } from './routines/runs'
import { forgetMemberPokes } from './team-presence'
export type MemberRemoval = {
keysRevoked: number
@@ -41,6 +42,8 @@ export async function removeMember(
const devicesRevoked = await revokeMemberDeviceSessions(life.db, accountId, userId, now)
// No device of theirs can open a sleeping workspace's read snapshot again (wrapped keys deleted).
const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now)
// Their Pokes opt-in goes (it doubles as proof of membership for receiving one).
await forgetMemberPokes(life.db, accountId, userId, now)
const grants = await revokeGrantsForMember(life, accountId, userId)
// Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running.
const routines = await disableMemberRoutines({ life }, accountId, userId)
@@ -0,0 +1,26 @@
// Model spend by member and UTC hour, for teammate profiles' heatmap (team-presence.ts). The
// workspace registry keeps only a cumulative per-workspace total; this dates each increase and
// credits whoever's client reported it.
const HOUR_MS = 3_600_000
/** Records the reporter's new model spend: the growth of a workspace's cumulative token total. */
export async function recordTokenSpend(
db: D1Database,
accountId: string,
userId: string,
previousUsdMicros: number | null,
nextUsdMicros: number,
now: number
): Promise<void> {
const delta = nextUsdMicros - (previousUsdMicros ?? 0)
if (delta <= 0) {
return
}
await db
.prepare(
`INSERT INTO member_usage_hours (account_id, user_id, hour, token_usd_micros) VALUES (?, ?, ?, ?)
ON CONFLICT (account_id, user_id, hour) DO UPDATE SET token_usd_micros = token_usd_micros + excluded.token_usd_micros`
)
.bind(accountId, userId, Math.floor(now / HOUR_MS), delta)
.run()
}
@@ -49,8 +49,33 @@ export type StartInputs = {
prelude?: { script: string; env?: Record<string, string> }
/** This session's share-proxy key (src/share-crypto.ts); the proxy keeps it in memory only. */
shareProxyKey?: string
/**
* The VM's hostname for this boot (workspaceHostname): terminal prompts read `ubuntu@<workspace>`
* instead of the provider's VM id, which changes on every wake (JA-27). Set before orcad starts, so
* every shell it opens sees it. Best effort: a failure keeps the provider's name.
*/
hostname?: string
}
/** A hostname label from a workspace name: lowercase letters, digits and dashes, at most 63 chars. */
export function workspaceHostname(name: string | null | undefined): string | undefined {
const label = (name ?? '')
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+/, '')
.slice(0, 63)
.replace(/-+$/, '')
return label.length > 0 ? label : undefined
}
// Inline per boot, no image change: hostname plus an /etc/hosts entry (sudo would warn without one).
const HOSTNAME_STEP = [
'{ [ -n "${ORCA_HOSTNAME:-}" ] && sudo -n hostname "$ORCA_HOSTNAME" &&',
'{ grep -q "[[:space:]]$ORCA_HOSTNAME\\$" /etc/hosts || printf "127.0.1.1 %s\\n" "$ORCA_HOSTNAME" | sudo -n tee -a /etc/hosts; }; }',
'>/dev/null 2>&1 || true; unset ORCA_HOSTNAME'
].join(' ')
/** `NAME=<base64 utf-8 value>` lines, so values with newlines or quotes survive bash intact. */
export function encodeSecretEnv(env: Record<string, string>): string {
return Object.entries(env)
@@ -100,6 +125,10 @@ export async function startOrcad(
if (inputs.shareProxyKey) {
env.ORCA_SHARE_PROXY_KEY = inputs.shareProxyKey
}
if (inputs.hostname) {
env.ORCA_HOSTNAME = inputs.hostname
}
const hostnameStep = inputs.hostname ? `${HOSTNAME_STEP}; ` : ''
// The prelude rides in an env var (the start script's `env -i` keeps it out of orcad) so one
// round trip both prepares the checkout and starts orcad.
const result = await provider.runCommand(
@@ -108,11 +137,16 @@ export async function startOrcad(
? {
command: 'bash',
// The prelude never sees the share-proxy or ready keys; only the start script gets them.
args: ['-c', `env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}`],
args: [
'-c',
`${hostnameStep}env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}`
],
env: { ...env, ...inputs.prelude.env, ORCA_PRELUDE: inputs.prelude.script },
timeoutMs: START_TIMEOUT_MS
}
: { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS }
: hostnameStep
? { command: 'bash', args: ['-c', `${hostnameStep}exec ${START_COMMAND}`], env, timeoutMs: START_TIMEOUT_MS }
: { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS }
)
if (result.exitCode !== 0) {
throw new VmCommandError('orcad_start_failed')
@@ -0,0 +1,350 @@
// Teammate profiles and Pokes (Conductor 0.91 parity).
// GET /v1/team/members/:userId/profile?utcOffsetMin=<-840..840>
// POST /v1/team/members/:userId/poke
// GET /v1/team/pokes the caller's unseen pokes (last 24 h) and their opt-in
// PUT /v1/team/pokes/settings {enabled}
// POST /v1/team/pokes/seen {ids}
// Privacy: a profile shows what a teammate can already see (name, role from the roster, workspaces
// they can open). The 0–4 intensity per day is shared only by people who turned on "Pokes and
// activity" (the same opt-in as Pokes); exact amounts only ever go to the person themself. The
// heatmap counts the member's sandbox time (usage_outbox, attributed to the workspace owner) plus
// model spend their own client reported (member_usage_hours).
import { z } from 'zod'
import type { SandboxCaller } from './auth'
import { memberNamesFor } from './member-names'
import type { SandboxRow } from './store'
import { canSee, COMPUTE_USD_MICROS_PER_HOUR, workspaceViews } from './workspaces'
import {
POKE_INBOX_TTL_MS,
POKE_PAIR_COOLDOWN_MS,
POKE_SENDER_HOURLY_LIMIT,
TEAMMATE_HEATMAP_DAYS,
TEAMMATE_RECENT_WORKSPACES,
type PokeRefusal
} from '../../../../src/shared/cloud-workspaces/team-presence-wire'
const DAY_MS = 86_400_000
const HOUR_MS = 3_600_000
export class TeamPresenceError extends Error {
constructor(
readonly status: number,
readonly code: string,
readonly reason?: PokeRefusal | string,
readonly retryAfterMs?: number
) {
super(reason ? `${code}:${reason}` : code)
this.name = 'TeamPresenceError'
}
}
export const MEMBER_ID = /^[A-Za-z0-9_.:-]{1,128}$/
function isoDate(dayIndex: number): string {
return new Date(dayIndex * DAY_MS).toISOString().slice(0, 10)
}
/** 0 for nothing; otherwise 1–4 relative to the member's own busiest day in the window. */
export function usageLevel(value: number, max: number): number {
if (value <= 0 || max <= 0) {
return 0
}
return Math.min(4, Math.max(1, Math.ceil((value / max) * 4)))
}
/**
* Per local day: sandbox time on workspaces the member owns, and model spend they reported. Days
* are the viewer's calendar days (utcOffsetMin); a segment crossing midnight is split.
*/
export async function memberDailyUsage(
db: D1Database,
accountId: string,
userId: string,
now: number,
utcOffsetMin: number,
days = TEAMMATE_HEATMAP_DAYS
) {
const offsetMs = utcOffsetMin * 60_000
const today = Math.floor((now + offsetMs) / DAY_MS)
const firstDay = today - days + 1
const windowStart = firstDay * DAY_MS - offsetMs
const computeMs = new Array<number>(days).fill(0)
const tokenUsd = new Array<number>(days).fill(0)
const { results: segments } = await db
.prepare(
`SELECT u.started_at, u.ended_at FROM usage_outbox u JOIN sandboxes s ON s.id = u.sandbox_id
WHERE u.account_id = ? AND u.started_at < ? AND u.ended_at > ? AND s.user_id = ?`
)
.bind(accountId, now, windowStart, userId)
.all<{ started_at: number; ended_at: number }>()
for (const seg of segments) {
let from = Math.max(seg.started_at, windowStart)
const to = Math.min(seg.ended_at, now)
while (from < to) {
const day = Math.floor((from + offsetMs) / DAY_MS)
const dayEnd = (day + 1) * DAY_MS - offsetMs
const end = Math.min(to, dayEnd)
const index = day - firstDay
if (index >= 0 && index < days) {
computeMs[index]! += end - from
}
from = end
}
}
const { results: hours } = await db
.prepare(
`SELECT hour, token_usd_micros FROM member_usage_hours WHERE account_id = ? AND user_id = ? AND hour >= ?`
)
.bind(accountId, userId, Math.floor(windowStart / HOUR_MS))
.all<{ hour: number; token_usd_micros: number }>()
for (const row of hours) {
const index = Math.floor((row.hour * HOUR_MS + offsetMs) / DAY_MS) - firstDay
if (index >= 0 && index < days) {
tokenUsd[index]! += row.token_usd_micros
}
}
const rate = COMPUTE_USD_MICROS_PER_HOUR.standard
const usdMicros = computeMs.map((ms, i) => Math.round((ms / HOUR_MS) * rate) + tokenUsd[i]!)
const max = Math.max(0, ...usdMicros)
return {
start: isoDate(firstDay),
levels: usdMicros.map((value) => usageLevel(value, max)),
activeDays: usdMicros.filter((value) => value > 0).length,
computeMs,
usdMicros
}
}
async function pokesEnabled(db: D1Database, accountId: string, userId: string): Promise<boolean> {
const row = await db
.prepare('SELECT enabled FROM member_poke_prefs WHERE account_id = ? AND user_id = ?')
.bind(accountId, userId)
.first<{ enabled: number }>()
return row?.enabled === 1
}
function requireTeam(caller: SandboxCaller): void {
if (!caller.orgId) {
throw new TeamPresenceError(400, 'invalid_request', 'personal_account')
}
}
export type ActivitySharing = 'opt_in' | 'team'
export async function memberProfile(
db: D1Database,
caller: SandboxCaller,
userId: string,
url: URL,
now: number,
activitySharing: ActivitySharing = 'opt_in'
) {
const self = userId === caller.userId
if (!self && !caller.orgId) {
// A personal account has no teammates.
throw new TeamPresenceError(404, 'not_found')
}
const offset = Number(url.searchParams.get('utcOffsetMin') ?? '0')
const utcOffsetMin = Number.isInteger(offset) && Math.abs(offset) <= 14 * 60 ? offset : 0
const { results } = await db
.prepare(
`SELECT * FROM sandboxes WHERE account_id = ? AND status <> 'destroyed' AND archived_at IS NULL
AND (user_id = ? OR created_by = ?) ORDER BY COALESCE(last_activity_at, updated_at) DESC LIMIT 100`
)
.bind(caller.accountId, userId, userId)
.all<SandboxRow>()
// Only workspaces the viewer could already open from Home: a teammate's private ones stay private.
const rows = results.filter((row) => !row.hidden && canSee(caller, row)).slice(0, TEAMMATE_RECENT_WORKSPACES)
const [names, recentWorkspaces, mine, theirs] = await Promise.all([
memberNamesFor(db, caller.accountId, [userId]),
workspaceViews(db, caller, rows, now),
caller.orgId ? pokesEnabled(db, caller.accountId, caller.userId) : Promise.resolve(false),
caller.orgId && !self ? pokesEnabled(db, caller.accountId, userId) : Promise.resolve(false)
])
// Your own heatmap always; a teammate's only when they chose to share it.
const usage = self || theirs || activitySharing === 'team' ? await memberDailyUsage(db, caller.accountId, userId, now, utcOffsetMin) : null
return {
profile: {
userId,
self,
name: names.get(userId) ?? null,
usage: usage && {
start: usage.start,
levels: usage.levels,
activeDays: usage.activeDays,
own: self ? { computeMs: usage.computeMs, usdMicros: usage.usdMicros } : null
},
recentWorkspaces,
pokes: { enabled: mine, teammateEnabled: self ? null : theirs }
}
}
}
export const PokeSettingsBody = z.object({ enabled: z.boolean() }).strict()
export const PokesSeenBody = z.object({ ids: z.array(z.string().regex(/^pok_[0-9a-f]{24}$/)).min(1).max(50) }).strict()
export async function setPokeSettings(db: D1Database, caller: SandboxCaller, enabled: boolean, now: number) {
requireTeam(caller)
const statements = [
db
.prepare(
`INSERT INTO member_poke_prefs (account_id, user_id, enabled, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT (account_id, user_id) DO UPDATE SET enabled = excluded.enabled, updated_at = excluded.updated_at`
)
.bind(caller.accountId, caller.userId, enabled ? 1 : 0, now)
]
if (!enabled) {
// Turning it off drops anything waiting, so turning it back on doesn't replay old pokes.
statements.push(
db
.prepare('UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL')
.bind(now, caller.accountId, caller.userId)
)
}
await db.batch(statements)
return { enabled }
}
export async function pokeInbox(db: D1Database, caller: SandboxCaller, now: number) {
if (!caller.orgId) {
return { enabled: false, pokes: [] }
}
const enabled = await pokesEnabled(db, caller.accountId, caller.userId)
if (!enabled) {
return { enabled, pokes: [] }
}
const { results } = await db
.prepare(
`SELECT id, from_user_id, created_at FROM member_pokes
WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL AND created_at > ?
ORDER BY created_at DESC LIMIT 20`
)
.bind(caller.accountId, caller.userId, now - POKE_INBOX_TTL_MS)
.all<{ id: string; from_user_id: string; created_at: number }>()
const names = await memberNamesFor(db, caller.accountId, results.map((r) => r.from_user_id))
return {
enabled,
pokes: results.map((r) => ({ id: r.id, fromUserId: r.from_user_id, fromName: names.get(r.from_user_id) ?? null, at: r.created_at }))
}
}
export async function markPokesSeen(db: D1Database, caller: SandboxCaller, ids: readonly string[], now: number) {
await db
.prepare(
`UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND to_user_id = ? AND seen_at IS NULL
AND id IN (${ids.map(() => '?').join(', ')})`
)
.bind(now, caller.accountId, caller.userId, ...ids)
.run()
return { ok: true as const }
}
function pokeId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(12))
return `pok_${[...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')}`
}
/**
* Both people must have Pokes on. The teammate's own opt-in (written with their token in this
* account, and dropped when they leave it) is also what proves they are a member.
*/
export async function sendPoke(db: D1Database, caller: SandboxCaller, toUserId: string, now: number) {
requireTeam(caller)
if (toUserId === caller.userId) {
throw new TeamPresenceError(400, 'invalid_request', 'self')
}
if (!(await pokesEnabled(db, caller.accountId, caller.userId))) {
throw new TeamPresenceError(409, 'conflict', 'pokes_off')
}
if (!(await pokesEnabled(db, caller.accountId, toUserId))) {
throw new TeamPresenceError(409, 'conflict', 'teammate_pokes_off')
}
const recent = await db
.prepare(
`SELECT COUNT(*) AS sent, MAX(CASE WHEN to_user_id = ? THEN created_at END) AS last_to_them
FROM member_pokes WHERE account_id = ? AND from_user_id = ? AND created_at > ?`
)
.bind(toUserId, caller.accountId, caller.userId, now - HOUR_MS)
.first<{ sent: number; last_to_them: number | null }>()
const lastToThem = recent?.last_to_them ?? null
if (lastToThem !== null && now - lastToThem < POKE_PAIR_COOLDOWN_MS) {
throw new TeamPresenceError(429, 'rate_limited', 'poke_cooldown', POKE_PAIR_COOLDOWN_MS - (now - lastToThem))
}
if ((recent?.sent ?? 0) >= POKE_SENDER_HOURLY_LIMIT) {
throw new TeamPresenceError(429, 'rate_limited', 'poke_rate', HOUR_MS)
}
const id = pokeId()
await db.batch([
db
.prepare('INSERT INTO member_pokes (id, account_id, from_user_id, to_user_id, created_at) VALUES (?, ?, ?, ?, ?)')
.bind(id, caller.accountId, caller.userId, toUserId, now),
// Keep the table small: nothing older than a day is ever read.
db.prepare('DELETE FROM member_pokes WHERE account_id = ? AND created_at < ?').bind(caller.accountId, now - 2 * POKE_INBOX_TTL_MS)
])
return { poke: { id, at: now } }
}
/** A member left: their opt-in and anything waiting for them goes; pokes they sent stop showing. */
export async function forgetMemberPokes(db: D1Database, accountId: string, userId: string, now: number): Promise<void> {
await db.batch([
db.prepare('DELETE FROM member_poke_prefs WHERE account_id = ? AND user_id = ?').bind(accountId, userId),
db
.prepare('UPDATE member_pokes SET seen_at = ? WHERE account_id = ? AND (to_user_id = ? OR from_user_id = ?) AND seen_at IS NULL')
.bind(now, accountId, userId, userId)
])
}
/** Routes under /v1/team/members and /v1/team/pokes; null when the path isn't one of them. */
export async function teamPresenceRoute(
db: D1Database,
caller: SandboxCaller,
request: Request,
url: URL,
now: number,
readJson: () => Promise<unknown>,
options: { activitySharing?: ActivitySharing } = {}
): Promise<unknown | null> {
const member = /^\/v1\/team\/members\/([^/]+)\/(profile|poke)$/.exec(url.pathname)
if (member) {
let userId: string
try {
userId = decodeURIComponent(member[1]!)
} catch {
throw new TeamPresenceError(400, 'invalid_request')
}
if (!MEMBER_ID.test(userId)) {
throw new TeamPresenceError(400, 'invalid_request')
}
if (member[2] === 'profile' && request.method === 'GET') {
return memberProfile(db, caller, userId, url, now, options.activitySharing)
}
if (member[2] === 'poke' && request.method === 'POST') {
return sendPoke(db, caller, userId, now)
}
return null
}
if (url.pathname === '/v1/team/pokes' && request.method === 'GET') {
return pokeInbox(db, caller, now)
}
if (url.pathname === '/v1/team/pokes/settings') {
if (request.method === 'GET') {
return { enabled: caller.orgId ? await pokesEnabled(db, caller.accountId, caller.userId) : false }
}
if (request.method === 'PUT') {
const body = PokeSettingsBody.safeParse(await readJson())
if (!body.success) {
throw new TeamPresenceError(400, 'invalid_request')
}
return setPokeSettings(db, caller, body.data.enabled, now)
}
return null
}
if (url.pathname === '/v1/team/pokes/seen' && request.method === 'POST') {
const body = PokesSeenBody.safeParse(await readJson())
if (!body.success) {
throw new TeamPresenceError(400, 'invalid_request')
}
return markPokesSeen(db, caller, body.data.ids, now)
}
return null
}
+63 -6
View File
@@ -1,6 +1,6 @@
// Team workspace registry: the cloud-owned list of an org's workspaces (who made it, who owns it,
// repo/branch, state, last activity, visibility, section, cost) and who is in each one right now.
// GET /v1/team/workspaces?scope=mine|team|all&by=<userId>&repo=<url>&section=<s>&archived=exclude|include|only
// GET /v1/team/workspaces?scope=mine|team|all&by=<userId>&repo=<url>&section=<s>&archived=exclude|include|only&routines=exclude|include
// 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?}
@@ -13,6 +13,7 @@ import type { SandboxCaller } from './auth'
import type { MachineSize } from './entitlements'
import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './store'
import { memberNamesFor } from './member-names'
import { recordTokenSpend } from './member-usage'
import { readSnapshotTimes } from './read-snapshots'
import { sandboxView } from './wire'
import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
@@ -210,7 +211,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
// Display names (token `name` claim) for the ids above; the roster wins where it has one.
memberNames,
// When its sleeping read-only copy was saved ("As of"); only for those who may read it.
readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null
readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null,
// Started by a routine run (Home hides these unless its Routine runs filter is on).
fromRoutine: isRoutineRun(row)
}
})
}
@@ -220,9 +223,16 @@ const ListQuery = z.object({
by: z.string().min(1).max(128).optional(),
repo: z.string().min(1).max(2048).optional(),
section: z.string().min(1).max(64).optional(),
archived: z.enum(['exclude', 'include', 'only']).default('exclude')
archived: z.enum(['exclude', 'include', 'only']).default('exclude'),
/** Routine runs stay off Home unless asked for (`include`), like Conductor's routine filter. */
routines: z.enum(['exclude', 'include']).default('exclude')
})
/** A routine run's VM: tagged at create, and keyed `routine-…` while it boots. */
export function isRoutineRun(row: SandboxRow): boolean {
return (row as { origin?: string | null }).origin === 'routine' || row.workspace_id.startsWith('routine-')
}
export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url: URL, now: number) {
const query = ListQuery.safeParse(Object.fromEntries(url.searchParams))
if (!query.success) {
@@ -236,7 +246,7 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
.prepare(`SELECT * FROM sandboxes WHERE account_id = ? AND status <> 'destroyed' ORDER BY COALESCE(last_activity_at, updated_at) DESC LIMIT 500`)
.bind(caller.accountId)
.all<SandboxRow>()
const rows = results.filter((row) => {
const matching = results.filter((row) => {
if (q.scope === 'mine' ? row.user_id !== caller.userId : q.scope === 'team' ? !canSee(caller, row) : false) {
return false
}
@@ -246,7 +256,8 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
if (q.repo && row.repo_url !== q.repo) {
return false
}
if (row.hidden) {
// Hidden rows are machine-made: only routine runs ever come back (below), and only when asked for.
if (row.hidden && !isRoutineRun(row)) {
return false
}
if (q.section && row.section !== q.section) {
@@ -254,7 +265,47 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
}
return q.archived === 'include' || (q.archived === 'only') === (row.archived_at !== null)
})
return { workspaces: await workspaceViews(db, caller, rows, now) }
const runs = matching.filter(isRoutineRun)
const rows = q.routines === 'include' ? matching : matching.filter((row) => !isRoutineRun(row))
const hidden = q.routines === 'include' ? [] : runs
const [views, routineCount, hiddenCompute, routineNames] = await Promise.all([
workspaceViews(db, caller, rows, now),
db.prepare('SELECT COUNT(*) AS n FROM routines WHERE account_id = ? AND deleted_at IS NULL').bind(caller.accountId).first<{ n: number }>(),
computeMsFor(db, hidden.map((row) => row.id)),
routineNamesFor(db, caller.accountId, rows.filter(isRoutineRun))
])
return {
workspaces: views.map((view, i) => ({ ...view, routineName: routineNames.get(rows[i]!.id) ?? null })),
// Home: offer the Routine runs switch only when the team has routines, and say what it hides
// (its count and hours still belong in the team's totals).
routineRuns: {
routines: routineCount?.n ?? 0,
hidden: hidden.length,
hiddenRunning: hidden.filter((row) => row.status === 'running' || row.status === 'creating').length,
hiddenComputeMs: hidden.reduce((sum, row) => sum + costView(row, hiddenCompute.get(row.id) ?? 0, now).computeMs, 0)
}
}
}
/** sandbox id -> its routine's name, for routine runs being listed. */
async function routineNamesFor(db: D1Database, accountId: string, rows: readonly SandboxRow[]): Promise<Map<string, string>> {
const refs = [...new Set(rows.flatMap((row) => ((row as { origin_ref?: string | null }).origin_ref ? [(row as { origin_ref: string }).origin_ref] : [])))]
if (refs.length === 0) {
return new Map()
}
const { results } = await db
.prepare(`SELECT id, name FROM routines WHERE account_id = ? AND id IN (${refs.map(() => '?').join(', ')})`)
.bind(accountId, ...refs)
.all<{ id: string; name: string }>()
const byRoutine = new Map(results.map((r) => [r.id, r.name]))
const out = new Map<string, string>()
for (const row of rows) {
const name = byRoutine.get((row as { origin_ref?: string | null }).origin_ref ?? '')
if (name) {
out.set(row.id, name)
}
}
return out
}
const SECTION = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/)
@@ -322,6 +373,12 @@ export async function patchWorkspace(
if (!next) {
throw new WorkspaceError('not_found')
}
if (patch.tokenUsdMicros !== undefined) {
// Dated per reporter for teammate profiles' heatmap; the label above is only a running total.
await recordTokenSpend(db, row.account_id, caller.userId, row.token_usd_micros, patch.tokenUsdMicros, now).catch((error: unknown) =>
console.warn('member_usage_write_failed', String(error))
)
}
const ownerChanged = patch.ownerUserId !== undefined && patch.ownerUserId !== row.user_id
const wentPrivate = row.visibility === 'team' && next.visibility === 'private'
const archived = patch.archived === true && row.archived_at === null
@@ -105,6 +105,21 @@ describe('automatic environments', () => {
expect(environments().filter((row) => row.kind === 'auto')).toHaveLength(2)
})
it('boot-plan says clone before the environment exists and update after (PC-4)', async () => {
const { h, settle, finishBuild } = await setup()
const plan = async () => (await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`)).body
expect(await plan()).toEqual({ repo: 'clone' })
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } } })
await settle()
expect(await plan()).toEqual({ repo: 'clone' })
await finishBuild()
expect(await plan()).toEqual({ repo: 'update' })
// Another account's environment is never theirs to boot.
expect((await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`, { as: 'bob' })).body).toEqual({
repo: 'clone'
})
})
it('goes after 14 days unused, with its snapshot', async () => {
const { h, settle, environments, finishBuild } = await setup()
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } } })
@@ -137,6 +137,28 @@ describe('repo-backed create', () => {
expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 3, runningSandboxesForUser: 3 })
})
it('an Idempotency-Key makes one sandbox per intent, for that account and member only (PC-8)', async () => {
const h = await createHarness()
const key = { 'idempotency-key': 'create-press-0001' }
const first = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
expect(first.status).toBe(200)
// A re-fired start of the same press (same key, same body): the same sandbox, nothing new.
const again = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
expect(again.status).toBe(200)
expect(again.body.sandbox.id).toBe(first.body.sandbox.id)
expect(h.vercel.boxes.size).toBe(1)
// Same key, different request: refused, not silently merged.
const other = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-b', machineSize: 'standard' }, headers: key })
expect(other.status).toBe(422)
// Keys are per member: someone else's press with the same key is their own create.
const bob = await h.call('POST', '/v1/sandboxes', { as: 'bob', body: { workspaceId: 'w-a', machineSize: 'standard' }, headers: key })
expect(bob.status).toBe(200)
expect(bob.body.sandbox.id).not.toBe(first.body.sandbox.id)
// A bad key is a 400, before anything starts.
const bad = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w-c', machineSize: 'standard' }, headers: { 'idempotency-key': 'x' } })
expect(bad.status).toBe(400)
})
it('a create whose Worker was cut off is failed after 5 minutes, not 15', async () => {
const h = await createHarness()
const { body } = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' } })
@@ -153,3 +175,18 @@ describe('repo-backed create', () => {
expect(h.vercel.boxes.size).toBe(0)
})
})
describe('VM hostname (JA-27)', () => {
it('is the workspace name (else the repo), as a hostname label, set at every start', async () => {
const { workspaceHostname } = await import('../src/sandbox-vm-commands')
expect(workspaceHostname('Fix Login Bug!')).toBe('fix-login-bug')
expect(workspaceHostname('--ja_hello--')).toBe('ja-hello')
expect(workspaceHostname('🙂')).toBeUndefined()
expect(workspaceHostname('a'.repeat(80))).toHaveLength(63)
const h = await createHarness()
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', title: 'Ja Hello', repo } })
const start = h.vercel.commands.find((c) => c.command === START_COMMAND)!
expect(start.env.ORCA_HOSTNAME).toBe('ja-hello')
expect(start.args?.[1]).toContain('sudo -n hostname "$ORCA_HOSTNAME"')
})
})
@@ -0,0 +1,182 @@
import { describe, expect, it } from 'vitest'
import { usageLevel } from '../src/team-presence'
import { createHarness } from './harness'
const MIN = 60_000
const HOUR = 60 * MIN
const DAY = 24 * HOUR
async function team() {
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40) })
type Who = { sub: string; orgRole: 'owner' | 'admin' | 'member'; org?: string; name?: string }
const req = async (who: Who, method: string, path: string, body?: unknown) =>
h.call(method, path, {
bearer: await h.token(who.sub, who.org === undefined ? 'acme' : who.org || undefined, 'sandbox', {
org_role: who.orgRole,
...(who.name ? { name: who.name } : {})
}),
body
})
const alice: Who = { sub: 'alice', orgRole: 'member', name: 'Alice Doe' }
const bob: Who = { sub: 'bob', orgRole: 'member', name: 'Bob Roe' }
return { h, req, alice, bob }
}
describe('teammate profiles', () => {
it('shows a teammate only their team workspaces and a 0–4 heatmap, never amounts', async () => {
const t = await team()
const shared = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-1', machineSize: 'standard', title: 'Shared' })
const secret = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-2', machineSize: 'standard', title: 'Secret' })
expect(shared.status).toBe(200)
const sharedId = shared.body.sandbox.id as string
const secretId = secret.body.sandbox.id as string
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${sharedId}`, { visibility: 'team' })
const now = t.h.now()
// Two hours of sandbox time yesterday on the private one, half an hour today on the shared one.
const outbox = t.h.raw.prepare(
`INSERT INTO usage_outbox (usage_id, sandbox_id, account_id, machine_size, started_at, ended_at) VALUES (?, ?, ?, 'standard', ?, ?)`
)
const accountId = (t.h.raw.prepare('SELECT account_id FROM sandboxes WHERE id = ?').get(sharedId) as { account_id: string }).account_id
outbox.run('u1', secretId, accountId, now - DAY - 2 * HOUR, now - DAY)
outbox.run('u2', sharedId, accountId, now - 30 * MIN, now)
// Not shared until Alice turns on "Pokes and activity"; workspaces she shared still show.
const hidden = (await t.req(t.bob, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')).body.profile
expect(hidden).toMatchObject({ usage: null, pokes: { enabled: false, teammateEnabled: false } })
expect(hidden.recentWorkspaces).toHaveLength(1)
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
const seen = await t.req(t.bob, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')
expect(seen.status).toBe(200)
const profile = seen.body.profile
expect(profile).toMatchObject({ userId: 'alice', self: false, name: 'Alice Doe', pokes: { enabled: false, teammateEnabled: true } })
expect(profile.recentWorkspaces.map((w: { id: string }) => w.id)).toEqual([sharedId])
expect(profile.usage.own).toBeNull()
expect(profile.usage.levels).toHaveLength(182)
expect(profile.usage.activeDays).toBe(2)
// Relative to her own busiest day: yesterday is the max (4), today a quarter of it (1).
expect(profile.usage.levels.slice(-2)).toEqual([4, 1])
expect(JSON.stringify(profile.usage)).not.toMatch(/usdMicros|computeMs/)
const own = await t.req(t.alice, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')
expect(own.body.profile.self).toBe(true)
expect(own.body.profile.recentWorkspaces).toHaveLength(2)
expect(own.body.profile.usage.own.computeMs.slice(-2)).toEqual([2 * HOUR, 30 * MIN])
expect(own.body.profile.usage.own.usdMicros.at(-1)).toBeGreaterThan(0)
})
it('splits a session across local midnight and dates reported model spend', async () => {
const t = await team()
const created = await t.req(t.alice, 'POST', '/v1/sandboxes', { workspaceId: 'ws-1', machineSize: 'standard' })
const id = created.body.sandbox.id as string
const now = t.h.now()
const accountId = (t.h.raw.prepare('SELECT account_id FROM sandboxes WHERE id = ?').get(id) as { account_id: string }).account_id
const midnight = Math.floor(now / DAY) * DAY
t.h.raw
.prepare(`INSERT INTO usage_outbox (usage_id, sandbox_id, account_id, machine_size, started_at, ended_at) VALUES ('u1', ?, ?, 'standard', ?, ?)`)
.run(id, accountId, midnight - HOUR, midnight + HOUR)
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 500_000 })).status).toBe(200)
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 400_000 })).status).toBe(200)
expect((await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { tokenUsdMicros: 700_000 })).status).toBe(200)
const own = (await t.req(t.alice, 'GET', '/v1/team/members/alice/profile?utcOffsetMin=0')).body.profile.usage.own
const today = own.computeMs.length - 1
const tokenAndCompute = own.usdMicros[today]
expect(own.computeMs[today - 1]).toBe(HOUR)
// Only increases count: 500k, then nothing for the drop to 400k, then 300k more.
expect(tokenAndCompute - own.usdMicros[today - 1]).toBe(500_000 + 300_000)
})
it('shares every teammate\'s activity when the account config says team', async () => {
const h = await createHarness({ TEAMMATE_ACTIVITY_SHARING: 'team' })
const bob = await h.token('bob', 'acme', 'sandbox', { org_role: 'member' })
const seen = await h.call('GET', '/v1/team/members/alice/profile', { bearer: bob })
expect(seen.body.profile.usage.levels).toHaveLength(182)
expect(seen.body.profile.usage.own).toBeNull()
})
it('keeps personal accounts to themselves and rejects bad ids', async () => {
const t = await team()
const solo = { sub: 'solo', orgRole: 'owner' as const, org: '' }
expect((await t.req(solo, 'GET', '/v1/team/members/alice/profile')).status).toBe(404)
expect((await t.req(solo, 'GET', '/v1/team/members/solo/profile')).status).toBe(200)
expect((await t.req(t.bob, 'GET', '/v1/team/members/a%20b/profile')).status).toBe(400)
const stranger = { sub: 'eve', orgRole: 'owner' as const, org: 'other' }
expect((await t.req(stranger, 'GET', '/v1/team/members/alice/profile')).body.profile.recentWorkspaces).toEqual([])
})
it('levels are relative to the busiest day', () => {
expect([0, 1, 25, 26, 50, 100].map((v) => usageLevel(v, 100))).toEqual([0, 1, 1, 2, 2, 4])
expect(usageLevel(5, 0)).toBe(0)
})
})
describe('pokes', () => {
it('needs both people opted in, then delivers, rate-limits and acks', async () => {
const t = await team()
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'pokes_off' } })
expect((await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })).body).toEqual({ enabled: true })
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'teammate_pokes_off' } })
const before = (await t.req(t.alice, 'GET', '/v1/team/members/bob/profile')).body.profile.pokes
expect(before).toEqual({ enabled: true, teammateEnabled: false })
await t.req(t.bob, 'PUT', '/v1/team/pokes/settings', { enabled: true })
expect((await t.req(t.alice, 'GET', '/v1/team/members/bob/profile')).body.profile.pokes.teammateEnabled).toBe(true)
const sent = await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')
expect(sent.status).toBe(200)
const again = await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')
expect(again).toMatchObject({ status: 429, body: { reason: 'poke_cooldown' } })
expect(again.body.retryAfterMs).toBeGreaterThan(0)
expect(await t.req(t.alice, 'POST', '/v1/team/members/alice/poke')).toMatchObject({ status: 400, body: { reason: 'self' } })
const inbox = await t.req(t.bob, 'GET', '/v1/team/pokes')
expect(inbox.body.enabled).toBe(true)
expect(inbox.body.pokes).toEqual([{ id: sent.body.poke.id, fromUserId: 'alice', fromName: 'Alice Doe', at: t.h.now() }])
// Alice sees nothing addressed to her; another org sees nothing at all.
expect((await t.req(t.alice, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
expect((await t.req({ sub: 'bob', orgRole: 'member', org: 'other' }, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
expect((await t.req(t.bob, 'POST', '/v1/team/pokes/seen', { ids: [sent.body.poke.id] })).status).toBe(200)
expect((await t.req(t.bob, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
// Poke back works, and after the cooldown Alice may poke again.
expect((await t.req(t.bob, 'POST', '/v1/team/members/alice/poke')).status).toBe(200)
t.h.advance(61_000)
expect((await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).status).toBe(200)
})
it('caps pokes per sender per hour and drops stale or opted-out ones', async () => {
const t = await team()
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
const teammates = Array.from({ length: 21 }, (_, i) => ({ sub: `m${i}`, orgRole: 'member' as const }))
for (const m of teammates) {
await t.req(m, 'PUT', '/v1/team/pokes/settings', { enabled: true })
}
for (const m of teammates.slice(0, 20)) {
expect((await t.req(t.alice, 'POST', `/v1/team/members/${m.sub}/poke`)).status).toBe(200)
}
expect(await t.req(t.alice, 'POST', '/v1/team/members/m20/poke')).toMatchObject({ status: 429, body: { reason: 'poke_rate' } })
// Turning Pokes off clears what was waiting; a day-old poke is never shown.
expect((await t.req(teammates[0]!, 'GET', '/v1/team/pokes')).body.pokes).toHaveLength(1)
await t.req(teammates[0]!, 'PUT', '/v1/team/pokes/settings', { enabled: false })
await t.req(teammates[0]!, 'PUT', '/v1/team/pokes/settings', { enabled: true })
expect((await t.req(teammates[0]!, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
t.h.advance(DAY + MIN)
expect((await t.req(teammates[1]!, 'GET', '/v1/team/pokes')).body.pokes).toEqual([])
})
it('forgets a removed member so nobody can poke them', async () => {
const t = await team()
await t.req(t.alice, 'PUT', '/v1/team/pokes/settings', { enabled: true })
await t.req(t.bob, 'PUT', '/v1/team/pokes/settings', { enabled: true })
const removed = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } })
expect(removed.status).toBe(200)
expect(await t.req(t.alice, 'POST', '/v1/team/members/bob/poke')).toMatchObject({ status: 409, body: { reason: 'teammate_pokes_off' } })
})
it('refuses Pokes on a personal account', async () => {
const t = await team()
const solo = { sub: 'solo', orgRole: 'owner' as const, org: '' }
expect(await t.req(solo, 'PUT', '/v1/team/pokes/settings', { enabled: true })).toMatchObject({ status: 400, body: { reason: 'personal_account' } })
expect((await t.req(solo, 'GET', '/v1/team/pokes')).body).toEqual({ enabled: false, pokes: [] })
})
})
@@ -66,6 +66,35 @@ describe('workspace registry', () => {
expect((await t.req(stranger, 'GET', `/v1/team/links/resolve?w=${t.id}`)).status).toBe(404)
})
it('keeps routine runs off Home unless the Routine runs filter asks for them', async () => {
const t = await team()
// A routine run's VM: hidden and tagged with its routine (what routines/runs.ts creates).
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.routineRuns).toEqual({ routines: 0, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 })
t.h.raw
.prepare(
`INSERT INTO routines (id, account_id, created_by, name, project_id, trigger_kind, trigger_config, agent, prompt, max_runtime_ms, created_at, updated_at)
VALUES ('rtn_1', 'org:acme', 'alice', 'nightly-deps', 'prj_1', 'webhook', '{}', 'claude', 'x', 60000, 0, 0)`
)
.run()
t.h.raw.prepare(`UPDATE sandboxes SET hidden = 1, origin = 'routine', origin_ref = 'rtn_1' WHERE id = ?`).run(t.id)
const off = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')
expect(off.body.workspaces).toEqual([])
// What the switch hides is still counted for Home: the switch label and the team's hours.
expect(off.body.routineRuns).toMatchObject({ routines: 1, hidden: 1, hiddenRunning: 1 })
const shown = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine&routines=include')
expect(shown.body.workspaces.map((w: { id: string; fromRoutine: boolean; routineName: string }) => [w.id, w.fromRoutine, w.routineName])).toEqual([
[t.id, true, 'nightly-deps']
])
expect(shown.body.routineRuns).toMatchObject({ routines: 1, hidden: 0, hiddenRunning: 0 })
// Other machine-made rows stay hidden even then.
t.h.raw.prepare(`UPDATE sandboxes SET origin = 'vm' WHERE id = ?`).run(t.id)
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine&routines=include')).body.workspaces).toEqual([])
// A plain workspace says so.
t.h.raw.prepare(`UPDATE sandboxes SET hidden = 0, origin = 'desktop' WHERE id = ?`).run(t.id)
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0].fromRoutine).toBe(false)
expect((await t.req(t.alice, 'GET', '/v1/team/workspaces?routines=bogus')).status).toBe(400)
})
it('lets admins see private rows for management (scope=all) without access', async () => {
const t = await team()
expect((await t.req(t.bob, 'GET', '/v1/team/workspaces?scope=all')).status).toBe(403)
@@ -195,6 +195,49 @@ describe('response hardening', () => {
expect(parsed.result?.prUrl).toBeUndefined()
expect(parsed.status).toBe('succeeded')
})
it('accepts the run the control plane answers Run now with (object trigger detail)', async () => {
// Exactly what POST /v1/routines/:id/run returns (routines/store.ts runView, private view).
const queued = {
id: 'run_9',
routineId: 'rt_1',
trigger: 'manual',
triggerDetail: { requestedBy: 'usr_1' },
status: 'queued',
workspaceId: null,
result: null,
error: null,
createdAt: 5,
startedAt: null,
finishedAt: null,
durationMs: null
}
const fetchImpl = vi.fn<typeof fetch>(async () => respond(202, { run: queued }))
const { run } = await client(fetchImpl).runRoutine('rt_1')
expect(run).toMatchObject({ id: 'run_9', status: 'queued', triggerDetail: null })
const github = {
...queued,
trigger: 'github',
triggerDetail: {
event: 'pull_request.labeled',
delivery: 'd1',
target: { repo: 'acme/web', number: 482, kind: 'pull_request' },
context: { anything: true }
}
}
const page = vi.fn<typeof fetch>(async () =>
respond(200, {
runs: [github, { ...queued, triggerDetail: 'POST from ci' }],
nextBefore: null
})
)
const { runs } = await client(page).listRoutineRuns('rt_1')
expect(runs.map((r) => r.triggerDetail)).toEqual([
'acme/web#482 pull_request.labeled',
'POST from ci'
])
})
})
describe('classifyCloudApiResponse', () => {
@@ -145,3 +145,45 @@ describe('cloud workspaces client: sleep and delete', () => {
)
})
})
describe('cloud workspaces client: routine runs on Home', () => {
it('asks for routine runs only when the filter is on, and keeps the routine mark', async () => {
const row = {
id: SBX,
workspaceId: 'routine-run_1',
status: 'running',
machineSize: 'standard',
region: 'pdx1',
createdAt: 1,
title: 'Nightly · run',
repo: null,
visibility: 'private',
section: null,
archivedAt: null,
createdBy: 'u1',
ownerUserId: 'u1',
lastActivityAt: 1,
lastActivityBy: null,
cost: {
computeMs: 0,
rateUsdMicrosPerHour: 0,
computeUsdMicros: 0,
tokenUsdMicros: null,
totalUsdMicros: 0
},
access: 'owner',
presence: [],
fromRoutine: true
}
const { client, fetch } = clientAnswering(200, { workspaces: [row] })
const listed = (await client.list({ scope: 'mine', archived: 'exclude', routines: 'include' }))
.workspaces
expect(String(fetch.mock.calls[0]![0])).toBe(
'https://cp.example.test/v1/team/workspaces?scope=mine&archived=exclude&routines=include'
)
expect(listed[0]!.fromRoutine).toBe(true)
// Older control planes omit the mark; it is never required.
const { fromRoutine: _omitted, ...older } = row
expect(CloudWorkspaceSchema.parse(older).fromRoutine).toBeUndefined()
})
})
@@ -18,6 +18,12 @@ import {
type CloudWorkspacePatch,
type OrgPrompts
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
import {
PokeInboxSchema,
PokeSentSchema,
PokeSettingsSchema,
TeammateProfileResponseSchema
} from '../../shared/cloud-workspaces/team-presence-wire'
const NoteSentSchema = z.object({ ok: z.literal(true) })
/** DELETE and POST suspend on /v1/sandboxes/:id answer with the sandbox's new state, not `{ok}`. */
@@ -133,13 +139,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
}
}
const qs = params.toString()
return (
await call(
'GET',
`/v1/team/workspaces${qs ? `?${qs}` : ''}`,
CloudWorkspaceListResponseSchema
)
).workspaces
return call('GET', `/v1/team/workspaces${qs ? `?${qs}` : ''}`, CloudWorkspaceListResponseSchema)
},
async get(id: string) {
return (await call('GET', ws(id), CloudWorkspaceResponseSchema)).workspace
@@ -256,6 +256,35 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
},
putOrgPrompts(document: OrgPrompts['document'], revision: number): Promise<OrgPrompts> {
return call('PUT', '/v1/team/prompts', OrgPromptsSchema, { document, revision })
},
async teammateProfile(userId: string, utcOffsetMin: number) {
const qs = new URLSearchParams({ utcOffsetMin: String(utcOffsetMin) })
return (
await call(
'GET',
`/v1/team/members/${encodeURIComponent(userId)}/profile?${qs}`,
TeammateProfileResponseSchema
)
).profile
},
async poke(userId: string) {
return (
await call(
'POST',
`/v1/team/members/${encodeURIComponent(userId)}/poke`,
PokeSentSchema,
{}
)
).poke
},
pokeInbox() {
return call('GET', '/v1/team/pokes', PokeInboxSchema)
},
async setPokesEnabled(enabled: boolean) {
return (await call('PUT', '/v1/team/pokes/settings', PokeSettingsSchema, { enabled })).enabled
},
async markPokesSeen(ids: string[]) {
await call('POST', '/v1/team/pokes/seen', NoteSentSchema, { ids })
}
}
}
@@ -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 {
CloudWorkspace,
CloudWorkspaceListQuery,
CloudWorkspacePatch,
CloudWorkspaceRoutineRuns,
OrgPrompts
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter'
@@ -30,6 +32,11 @@ export type CloudWorkspacesResult<T> =
| { ok: true; value: T }
| { ok: false; error: string; reason?: string; status?: number }
/** A list read, plus what Home's Routine runs switch hides (absent from older control planes). */
export type CloudWorkspaceListResult =
| { ok: true; value: CloudWorkspace[]; routineRuns?: CloudWorkspaceRoutineRuns }
| { ok: false; error: string; reason?: string; status?: number }
/** Where this desktop already has a cloud workspace locally (owner: the hosted runtime it created). */
export type LocalCloudWorkspace = {
sandboxId: string
@@ -134,13 +141,17 @@ export function createCloudWorkspacesService(deps: {
return {
available: true as const,
list: (query: CloudWorkspaceListQuery) =>
wrap(async () => {
const workspaces = await client.list(query)
list: async (query: CloudWorkspaceListQuery): Promise<CloudWorkspaceListResult> => {
let routineRuns: CloudWorkspaceRoutineRuns | undefined
const result = await wrap(async () => {
const page = await client.list(query)
routineRuns = page.routineRuns
// Cheap when already registered; catches a sign-in or account switch since the last list.
void reader?.register()
return workspaces
}),
return page.workspaces
})
return result.ok && routineRuns ? { ...result, routineRuns } : result
},
/** Sign-out: revoke this device's reader key server-side (callers bound the wait). */
revokeReaderKey: (timeoutMs: number) => reader?.revoke(timeoutMs) ?? Promise.resolve(),
/** A sleeping workspace's sealed snapshot, opened on this device; never wakes it. */
@@ -162,6 +173,12 @@ export function createCloudWorkspacesService(deps: {
getOrgPrompts: () => wrap(() => client.getOrgPrompts()),
putOrgPrompts: (document: OrgPrompts['document'], revision: number) =>
wrap(() => client.putOrgPrompts(document, revision)),
teammateProfile: (userId: string, utcOffsetMin: number) =>
wrap(() => client.teammateProfile(userId, utcOffsetMin)),
poke: (userId: string) => wrap(() => client.poke(userId)),
pokeInbox: () => wrap(() => client.pokeInbox()),
setPokesEnabled: (enabled: boolean) => wrap(() => client.setPokesEnabled(enabled)),
markPokesSeen: (ids: string[]) => wrap(() => client.markPokesSeen(ids)),
localWorkspaces: () => localWorkspaces(),
noteSent: (id: string) => wrap(() => client.noteSent(id)),
sleep: (id: string) => wrap(() => client.sleep(id)),
@@ -20,6 +20,9 @@ export type EnvironmentProviderPhase =
| 'cloning'
/** The repo came prebuilt (an environment build): only what changed is fetched. */
| 'updating'
/** Before the create answers: whether its repository step will clone or update (names the step once). */
| 'plan-clone'
| 'plan-update'
| 'connecting'
| 'suspending'
| 'resuming'
@@ -39,6 +42,8 @@ export type EnvironmentCreateSpec = {
/** Orca's workspace id; one environment per workspace. */
workspaceId: string
workspaceName?: string
/** One per user intent; the provider dedupes creates by it (Idempotency-Key). */
idempotencyKey?: string
projectId?: string
machineSize?: string
region?: string
+3
View File
@@ -33,6 +33,8 @@ export type ProvisionEphemeralVmRuntimeArgs = {
projectId?: string
workspaceId?: string
workspaceName?: string
/** One per Create press (Orca Cloud): the create's Idempotency-Key. */
idempotencyKey?: string
repoUrl?: string
branch?: string
ref?: string
@@ -102,6 +104,7 @@ export async function provisionEphemeralVmRuntime(
projectId: args.projectId,
workspaceId: args.workspaceId,
workspaceName: args.workspaceName,
...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}),
repoUrl: args.repoUrl,
branch: args.branch,
ref: args.ref,
@@ -35,6 +35,7 @@ import {
type HostedSandboxView
} from '../../shared/hosted-sandbox/hosted-sandbox-wire'
import {
HostedBootPlanResponseSchema,
HostedCloneStatusResponseSchema,
type HostedCloneStatus
} from '../../shared/hosted-sandbox/hosted-clone-wire'
@@ -51,9 +52,13 @@ type HostedGithubConnectResponse = z.infer<typeof HostedGithubConnectResponseSch
export type HostedSandboxControlPlaneClient = {
create(
body: HostedSandboxCreateRequest,
signal?: AbortSignal
signal?: AbortSignal,
/** Idempotency-Key: one per user intent; a repeat returns the first create's sandbox (24 h). */
idempotencyKey?: string
): Promise<HostedSandboxReadyResponse>
get(sandboxId: string, signal?: AbortSignal): Promise<HostedSandboxView>
/** Whether a create of `repoUrl` would clone it or update a prebuilt copy (environment build). */
bootPlan(repoUrl: string, signal?: AbortSignal): Promise<'clone' | 'update'>
/** The background clone a create started (create answered with `clone`). */
cloneStatus(sandboxId: string, signal?: AbortSignal): Promise<HostedCloneStatus>
list(signal?: AbortSignal): Promise<HostedSandboxView[]>
@@ -133,15 +138,25 @@ export function createHostedSandboxControlPlaneClient(
`v1/sandboxes/${encodeURIComponent(id)}${suffix}`
return {
create: (body, signal) =>
create: (body, signal, idempotencyKey) =>
call('POST', 'v1/sandboxes', HostedSandboxReadyResponseSchema, {
body,
kind: 'boot',
signal,
...(idempotencyKey ? { headers: { 'idempotency-key': idempotencyKey } } : {}),
// The repo clones after the sandbox is up; the driver shows it as its own step.
// An environment boot reports its incremental fetch as an update (`clone.mode`).
features: ['clone-progress', 'repo-update']
}),
bootPlan: async (repoUrl, signal) =>
(
await call(
'GET',
`v1/sandboxes/boot-plan?repo=${encodeURIComponent(repoUrl)}`,
HostedBootPlanResponseSchema,
{ kind: 'control', signal }
)
).repo,
cloneStatus: async (id, signal) =>
(
await call('GET', sandboxPath(id, '/clone'), HostedCloneStatusResponseSchema, {
@@ -63,14 +63,27 @@ export function createHostedSandboxDriver(
async create(spec, ctx) {
const machineSize = toMachineSize(spec.machineSize)
ctx?.onProgress?.({ phase: 'provisioning' })
// Names the repository step before the create answers (no relabel mid-run). Best effort: an
// older control plane answers 404 and the step is named when the create answers.
if (spec.repo) {
void client
.bootPlan(spec.repo.url, ctx?.signal)
.then((plan) =>
ctx?.onProgress?.({ phase: plan === 'update' ? 'plan-update' : 'plan-clone' })
)
.catch(() => undefined)
}
const ready = await client.create(
{
workspaceId: spec.workspaceId,
machineSize,
// Named rows: Home shows the workspace's name, never an untitled sandbox (PC-8).
...(spec.workspaceName?.trim() ? { title: spec.workspaceName.trim().slice(0, 120) } : {}),
...(spec.region ? { region: spec.region } : {}),
...(spec.repo ? { repo: spec.repo } : {})
},
ctx?.signal
ctx?.signal,
spec.idempotencyKey
)
if (ready.clone) {
await waitForClone(client, ready.sandbox.id, ctx, { mode: ready.clone.mode ?? 'clone' })
@@ -182,6 +182,8 @@ export function createHostedSandboxStepProvider(
{
// One create attempt = one sandbox: a retried attempt reuses the instance id.
workspaceId: context.instanceId ?? context.workspaceId ?? 'workspace',
...(context.workspaceName ? { workspaceName: context.workspaceName } : {}),
...(context.idempotencyKey ? { idempotencyKey: context.idempotencyKey } : {}),
machineSize: 'standard',
...(repoUrl
? { repo: { url: repoUrl, ...(context.branch ? { ref: context.branch } : {}) } }
@@ -29,6 +29,7 @@ export type HostedSandboxRequest = <T>(
kind: 'boot' | 'control'
signal?: AbortSignal
features?: readonly string[]
headers?: Record<string, string>
}
) => Promise<T>
@@ -50,6 +51,8 @@ export function createHostedSandboxRequest(
signal?: AbortSignal
/** Per-call opt-ins on top of the features every call sends. */
features?: readonly string[]
/** Extra request headers (Idempotency-Key); the fixed ones below always win. */
headers?: Record<string, string>
}
): Promise<T> {
const timeoutSignal = AbortSignal.timeout(timeouts[init.kind])
@@ -60,6 +63,7 @@ export function createHostedSandboxRequest(
response = await doFetch(new URL(path, base), {
method,
headers: {
...init.headers,
authorization: `Bearer ${token}`,
accept: 'application/json',
// This client's schemas know the `archived` status.
@@ -31,6 +31,8 @@ class FakeGuest extends EventEmitter {
private waiters: ((answer: string) => void)[] = []
connectAnswer = 'connecting'
pasteAnswer = true
/** What window.orcaDesktop.state() answers (main watches a handed-over ticket connect). */
pageState: unknown = true
getURL(): string {
return this.url
@@ -55,6 +57,9 @@ class FakeGuest extends EventEmitter {
if (code.includes('orcaDesktop.paste(')) {
return this.pasteAnswer
}
if (code.includes('orcaDesktop.state()')) {
return this.pageState
}
return true
}
/** The page asks for a ticket ('ticket') or reports a failed attempt ('retry'). */
@@ -236,7 +241,7 @@ describe('remote desktop page driver', () => {
guest.emit('focus')
expect(events.at(-1)).toEqual({
kind: 'state',
state: { browserPageId: 'page-1', desktop: true, captured: true }
state: { browserPageId: 'page-1', desktop: true, captured: true, connection: 'connecting' }
})
guest.key({ type: 'keyDown', key: 'Control', control: true })
guest.key({ type: 'keyDown', key: 'Meta', control: true, meta: true })
@@ -270,7 +275,91 @@ describe('remote desktop page driver', () => {
expect(isRemoteDesktopGuest(asWebContents(guest))).toBe(false)
expect(events.at(-1)).toEqual({
kind: 'state',
state: { browserPageId: 'page-1', desktop: false, captured: false }
state: { browserPageId: 'page-1', desktop: false, captured: false, connection: 'none' }
})
})
it('reports connected once the page says its session is up', async () => {
const { guest, events } = setup()
guest.pageState = 'connected'
await flush()
guest.ask('ticket')
await flush()
expect(events.at(-1)).toEqual({
kind: 'state',
state: { browserPageId: 'page-1', desktop: true, captured: false, connection: 'connected' }
})
})
it('reports a pause with its reason, so the tab can show the asleep state', async () => {
const { guest, events, failMint } = setup()
await flush()
guest.ask('ticket')
await flush()
failMint('asleep')
guest.ask('ticket')
await flush()
expect(events.at(-1)).toEqual({
kind: 'state',
state: {
browserPageId: 'page-1',
desktop: true,
captured: false,
connection: 'paused',
reason: 'asleep'
}
})
})
it('reports no session for a desktop page this computer has no forward for (restored tab)', async () => {
resetRemoteDesktopSessionsForTest()
const guest = new FakeGuest()
const events: unknown[] = []
const stop = setupRemoteDesktopGuest({
browserPageId: 'page-3',
guest: asWebContents(guest),
notify: (event) => events.push(event),
sleep: async () => {}
})
await flush()
expect(guest.calls).toEqual([])
expect(events).toEqual([
{
kind: 'state',
state: { browserPageId: 'page-3', desktop: false, captured: false, connection: 'none' }
}
])
stop()
})
it('drops to no session when the forward closed under a page that needs a new ticket', async () => {
resetRemoteDesktopSessionsForTest()
let live = true
registerRemoteDesktopSession(
{
environmentId: 'env-1',
localPort: 6081,
path: 'vnc.html',
mint: async () => ({ ok: true, ticket: ticket(9), expiresAt: FAR_FUTURE }),
isLive: () => live
},
{ ticket: ticket(1), expiresAt: FAR_FUTURE }
)
const guest = new FakeGuest()
const events: { kind: string; state?: { connection: string } }[] = []
setupRemoteDesktopGuest({
browserPageId: 'page-4',
guest: asWebContents(guest),
notify: (event) => events.push(event),
sleep: async () => {}
})
await flush()
guest.ask('ticket')
await flush()
live = false // the sandbox slept: its forward closed
guest.ask('ticket')
await flush()
expect(events.at(-1)?.state?.connection).toBe('none')
expect(isRemoteDesktopGuest(asWebContents(guest))).toBe(false)
})
})
+78 -47
View File
@@ -9,12 +9,18 @@
// - pastes this computer's clipboard into the sandbox only on a paste key in the desktop.
import { clipboard } from 'electron'
import { translateMain } from '../i18n/main-i18n'
import { remoteDesktopPauseMessage as pauseMessage } from './remote-desktop-pause-copy'
import { isAgentInjectingInput } from '../browser/cdp/input/agent-input-injection'
import {
isCloudRemoteDesktopUrl,
type RemoteDesktopConnection,
type RemoteDesktopPageState,
type RemoteDesktopPauseReason
} from '../../shared/hosted-sandbox/cloud-remote-desktop'
import {
onRemoteDesktopSessionRefreshed,
remoteDesktopSessionForUrl,
takeRemoteDesktopTicket,
type RemoteDesktopMintFailure,
type RemoteDesktopSession
} from './remote-desktop-sessions'
import {
@@ -31,14 +37,11 @@ const MIN_MINT_INTERVAL_MS = 1_000
const MAX_MINTS_PER_MINUTE = 10
const MAX_PASTE_CHARS = 1 << 20
const PAGE_READY_TIMEOUT_MS = 10_000
/** How long, and how often, main watches a handed-over ticket become a connected session. */
const CONNECT_WATCH_MS = 20_000
const CONNECT_POLL_MS = 150
export type RemoteDesktopGuestState = {
browserPageId: string
/** The page is a remote desktop with Orca's page glue. */
desktop: boolean
/** It has keyboard focus: Orca's shortcuts are off until the release chord. */
captured: boolean
}
export type RemoteDesktopGuestState = RemoteDesktopPageState
export type RemoteDesktopGuestDeps = {
browserPageId: string
@@ -64,37 +67,6 @@ const WAIT_FOR_REQUEST = `(async () => {
return window.orcaDesktop ? window.orcaDesktop.nextTicketRequest() : 'missing'
})()`
function pauseMessage(reason: RemoteDesktopMintFailure | 'failed'): string {
switch (reason) {
case 'asleep':
return translateMain(
'components.cloudRemoteDesktop.pageAsleep',
'This sandbox is asleep. Wake it in Orca, then reconnect.'
)
case 'archived':
return translateMain(
'components.cloudRemoteDesktop.pageArchived',
'This workspace is archived. Unarchive it in Orca, then reconnect.'
)
case 'starting':
return translateMain(
'components.cloudRemoteDesktop.pageStarting',
'The sandbox is starting or waking. Reconnect in a moment.'
)
case 'signed_out':
return translateMain(
'components.cloudRemoteDesktop.pageSignedOut',
'You’re signed out of Orca Cloud. Sign in, then reconnect.'
)
case 'failed':
case 'unavailable':
return translateMain(
'components.cloudRemoteDesktop.pageDisconnected',
'The remote desktop disconnected. Your files are safe.'
)
}
}
export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => void {
const { guest, browserPageId, notify } = deps
const platform = deps.platform ?? process.platform
@@ -106,6 +78,10 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
let stopRefreshListener = (): void => {}
let disposed = false
let published = ''
let connection: RemoteDesktopConnection = 'none'
let pauseReason: RemoteDesktopPauseReason | undefined
/** The page's URL is shaped like a desktop (with or without a session on this computer). */
let shaped = false
/** Settles every in-flight page call when the page goes away (a torn-down page may never answer). */
let cancelInFlight = (): void => {}
let cancelled = new Promise<undefined>((resolve) => {
@@ -120,19 +96,48 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
const alive = (gen: number): boolean => !disposed && gen === generation && !guest.isDestroyed()
const publish = (): void => {
const state = {
const state: RemoteDesktopGuestState = {
browserPageId,
desktop: session !== null,
captured: session !== null && !guest.isDestroyed() && guest.isFocused()
captured: session !== null && !guest.isDestroyed() && guest.isFocused(),
connection: session || shaped ? connection : 'none',
...(connection === 'paused' && pauseReason ? { reason: pauseReason } : {})
}
// Only changes, and nothing at all for ordinary pages' focus churn.
const key = `${state.desktop}:${state.captured}`
if (key === published || (!state.desktop && published === '')) {
const key = `${state.desktop}:${state.captured}:${shaped}:${state.connection}:${state.reason ?? ''}`
if (key === published || (!state.desktop && !shaped && published === '')) {
return
}
published = key
notify({ kind: 'state', state })
}
const setConnection = (
gen: number,
next: RemoteDesktopConnection,
reason?: RemoteDesktopPauseReason
): void => {
if (!alive(gen)) {
return
}
connection = next
pauseReason = next === 'paused' ? reason : undefined
publish()
}
/** The page says when its session is up; main only knows it handed over a ticket. */
const watchConnected = async (gen: number): Promise<void> => {
const until = Date.now() + CONNECT_WATCH_MS
while (alive(gen) && connection === 'connecting' && Date.now() < until) {
const pageState = await run(gen, 'window.orcaDesktop && window.orcaDesktop.state()')
if (pageState === 'connected') {
setConnection(gen, 'connected')
return
}
if (pageState !== 'connecting' && pageState !== 'idle') {
return
}
await sleep(CONNECT_POLL_MS)
}
}
const run = async (gen: number, code: string): Promise<unknown> => {
if (!alive(gen)) {
return undefined
@@ -154,6 +159,7 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
if (!alive(gen) || (ask !== 'ticket' && ask !== 'retry')) {
return
}
setConnection(gen, 'connecting')
// 'retry': the last ticket never got a session (refused, or the forward was down).
failures = ask === 'retry' || refused ? failures + 1 : 0
refused = false
@@ -167,6 +173,13 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
await sleep(Math.max(RETRY_DELAYS_MS[failures] ?? 4_000, MIN_MINT_INTERVAL_MS - sinceLast))
// The forward may have closed meanwhile; a page now on that port gets nothing.
if (!alive(gen) || remoteDesktopSessionForUrl(guest.getURL()) !== current) {
// Its forward closed (the sandbox slept, or this computer dropped it): the renderer
// reopens the desktop once the sandbox is awake.
if (alive(gen)) {
session = null
guestsWithDesktop.delete(guest)
setConnection(gen, 'none')
}
return
}
mintTimes = mintTimes.filter((at) => Date.now() - at < 60_000)
@@ -186,10 +199,14 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
const started = await run(gen, `window.orcaDesktop.connect(${JSON.stringify(minted.ticket)})`)
// Anything but a started attempt still counts against the budget, so this never spins.
refused = started !== 'connecting'
if (!refused) {
void watchConnected(gen)
}
}
}
async function pause(gen: number, reason: RemoteDesktopMintFailure | 'failed'): Promise<void> {
async function pause(gen: number, reason: RemoteDesktopPauseReason): Promise<void> {
setConnection(gen, 'paused', reason)
const label = translateMain('components.cloudRemoteDesktop.reconnect', 'Reconnect')
await run(
gen,
@@ -203,12 +220,20 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
const gen = generation
stopRefreshListener()
stopRefreshListener = () => {}
session = remoteDesktopSessionForUrl(guest.getURL())
const url = guest.getURL()
session = remoteDesktopSessionForUrl(url)
shaped = isCloudRemoteDesktopUrl(url)
connection = session ? 'connecting' : 'none'
pauseReason = undefined
if (session) {
guestsWithDesktop.add(guest)
// Reopening from the menu resumes a page that stopped retrying (asleep, then woken).
stopRefreshListener = onRemoteDesktopSessionRefreshed(session.localPort, () => {
void run(gen, 'window.orcaDesktop && window.orcaDesktop.resume()')
void run(gen, 'window.orcaDesktop && window.orcaDesktop.resume()').then((resumed) => {
if (resumed === true) {
setConnection(gen, 'connecting')
}
})
})
void driveTickets(gen, session)
} else {
@@ -225,6 +250,9 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
generation += 1
cancelPageCalls()
session = null
shaped = false
connection = 'none'
pauseReason = undefined
guestsWithDesktop.delete(guest)
stopRefreshListener()
publish()
@@ -296,8 +324,11 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi
} catch {
// The guest may already be destroyed.
}
if (session) {
if (session || shaped) {
session = null
shaped = false
connection = 'none'
pauseReason = undefined
publish()
}
}
@@ -0,0 +1,34 @@
// What a remote desktop page says when main stops handing it tickets (remote-desktop-guest.ts).
import { translateMain } from '../i18n/main-i18n'
import type { RemoteDesktopPauseReason } from '../../shared/hosted-sandbox/cloud-remote-desktop'
export function remoteDesktopPauseMessage(reason: RemoteDesktopPauseReason): string {
switch (reason) {
case 'asleep':
return translateMain(
'components.cloudRemoteDesktop.pageAsleep',
'This sandbox is asleep. Wake it in Orca, then reconnect.'
)
case 'archived':
return translateMain(
'components.cloudRemoteDesktop.pageArchived',
'This workspace is archived. Unarchive it in Orca, then reconnect.'
)
case 'starting':
return translateMain(
'components.cloudRemoteDesktop.pageStarting',
'The sandbox is starting or waking. Reconnect in a moment.'
)
case 'signed_out':
return translateMain(
'components.cloudRemoteDesktop.pageSignedOut',
'You’re signed out of Orca Cloud. Sign in, then reconnect.'
)
case 'failed':
case 'unavailable':
return translateMain(
'components.cloudRemoteDesktop.pageDisconnected',
'The remote desktop disconnected. Your files are safe.'
)
}
}
@@ -0,0 +1,50 @@
// IPC for teammate profiles and Pokes (registered with the other cloud workspace handlers).
import { z } from 'zod'
import type { CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service'
const MemberId = z.string().regex(/^[A-Za-z0-9_.:-]{1,128}$/)
const NOT_CONFIGURED = { ok: false as const, error: 'not_configured' }
const INVALID = { ok: false as const, error: 'invalid_request' }
export function registerTeamPresenceHandlers(
handle: (channel: string, fn: (args: unknown) => unknown) => void,
getService: () => Promise<CloudWorkspacesService | null>
): void {
handle('cloudWorkspaces:teammateProfile', async (args) => {
const parsed = z
.object({ userId: MemberId, utcOffsetMin: z.number().int().min(-840).max(840) })
.safeParse(args)
const s = await getService()
return !s
? NOT_CONFIGURED
: parsed.success
? s.teammateProfile(parsed.data.userId, parsed.data.utcOffsetMin)
: INVALID
})
handle('cloudWorkspaces:poke', async (args) => {
const parsed = z.object({ userId: MemberId }).safeParse(args)
const s = await getService()
return !s ? NOT_CONFIGURED : parsed.success ? s.poke(parsed.data.userId) : INVALID
})
handle(
'cloudWorkspaces:pokeInbox',
async () => (await getService())?.pokeInbox() ?? NOT_CONFIGURED
)
handle('cloudWorkspaces:setPokesEnabled', async (args) => {
const parsed = z.object({ enabled: z.boolean() }).safeParse(args)
const s = await getService()
return !s ? NOT_CONFIGURED : parsed.success ? s.setPokesEnabled(parsed.data.enabled) : INVALID
})
handle('cloudWorkspaces:markPokesSeen', async (args) => {
const parsed = z
.object({
ids: z
.array(z.string().regex(/^pok_[0-9a-f]{24}$/))
.min(1)
.max(50)
})
.safeParse(args)
const s = await getService()
return !s ? NOT_CONFIGURED : parsed.success ? s.markPokesSeen(parsed.data.ids) : INVALID
})
}
+4 -1
View File
@@ -16,6 +16,7 @@ import {
setCloudReaderKeyRevoker
} from '../cloud-workspaces/cloud-reader-key-store'
import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader'
import { registerTeamPresenceHandlers } from './cloud-workspaces-team-presence'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
@@ -28,7 +29,8 @@ const ListQuery = z
by: z.string().max(128).optional(),
repo: z.string().max(2048).optional(),
section: z.string().max(64).optional(),
archived: z.enum(['exclude', 'include', 'only']).optional()
archived: z.enum(['exclude', 'include', 'only']).optional(),
routines: z.enum(['exclude', 'include']).optional()
})
.strict()
const Patch = z
@@ -305,6 +307,7 @@ export function registerCloudWorkspacesHandlers(): void {
? s.putOrgPrompts(parsed.data.document, parsed.data.revision)
: INVALID
})
registerTeamPresenceHandlers(handle, getService)
// Handlers are re-registered per main window; the quit hook must only be added once.
if (!quitHookInstalled) {
quitHookInstalled = true
@@ -36,6 +36,8 @@ export type EphemeralVmProvisionArgs = {
branch?: string
ref?: string
provisionId?: string
/** Orca Cloud: the Create press's key; a re-fired create gets the first one's sandbox. */
idempotencyKey?: string
}
export type EphemeralVmRecipeCatalogEntry = {
+1
View File
@@ -195,6 +195,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin
projectId: args.projectId,
workspaceId: args.workspaceId,
workspaceName: args.workspaceName,
...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}),
...(repoUrl ? { repoUrl } : {}),
...(args.branch ? { branch: args.branch } : {}),
...(sourceRef ? { ref: sourceRef } : {}),
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest'
import { hostManagedListenerConfig, isHostManagedListener } from './host-managed-listeners'
const config = (roots: string[] = ['/opt/orca'], unownedPorts: number[] = [23456]) => ({
roots,
unownedPorts: new Set(unownedPorts)
})
describe('host-managed listeners', () => {
it('reads absolute roots and platform ports from the environment', () => {
const parsed = hostManagedListenerConfig({
ORCA_HOST_MANAGED_LISTENER_PATHS: '/opt/orca/:relative:/srv/tools',
ORCA_HOST_MANAGED_UNOWNED_PORTS: '23456, x,70000'
})
expect(parsed.roots).toEqual(['/opt/orca', '/srv/tools'])
expect([...parsed.unownedPorts]).toEqual([23456])
expect(hostManagedListenerConfig({})).toEqual({ roots: [], unownedPorts: new Set() })
})
it('marks the server itself and programs started from a managed root', () => {
expect(isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true)
expect(
isHostManagedListener(
{ pid: 90, port: 2222, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' },
config(),
27
)
).toBe(true)
expect(
isHostManagedListener(
{
pid: 91,
port: 6080,
commandLine: 'python3 /opt/orca/bin/orca-desktop-proxy --port 6080'
},
config(),
27
)
).toBe(true)
})
it('marks a pid-less listener only on a declared platform port', () => {
expect(isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true)
// A root-run postgres or Docker-published port has no visible pid but is the user's.
expect(isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false)
expect(isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false)
})
it('leaves user servers alone, matching by program path rather than port', () => {
expect(
isHostManagedListener(
{ pid: 92, port: 6768, commandLine: 'python3 -m http.server 6768' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener(
{ pid: 92, port: 23456, commandLine: 'python3 -m http.server 23456' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener(
{ pid: 93, port: 5173, commandLine: 'node vite --config /opt/orca/x.js' },
config(),
27
)
).toBe(false)
expect(
isHostManagedListener({ pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' }, config(), 27)
).toBe(false)
expect(
isHostManagedListener({ pid: 95, port: 1, commandLine: '/opt/orca/bin/x' }, config([]), 27)
).toBe(false)
})
})
+54
View File
@@ -0,0 +1,54 @@
import type { RawListeningPort } from './local-workspace-port-scan-state'
/** Colon-separated install roots whose binaries are the host's own services (e.g. a sandbox image's tools). */
export const HOST_MANAGED_LISTENER_PATHS_ENV = 'ORCA_HOST_MANAGED_LISTENER_PATHS'
/** Comma-separated ports the host's platform listens on from a process this user cannot see (no pid). */
export const HOST_MANAGED_UNOWNED_PORTS_ENV = 'ORCA_HOST_MANAGED_UNOWNED_PORTS'
export type HostManagedListenerConfig = {
roots: readonly string[]
unownedPorts: ReadonlySet<number>
}
export function hostManagedListenerConfig(
env: Record<string, string | undefined> = process.env
): HostManagedListenerConfig {
const roots = (env[HOST_MANAGED_LISTENER_PATHS_ENV] ?? '')
.split(':')
.map((root) => root.trim().replace(/\/+$/, ''))
.filter((root) => root.startsWith('/') && root.length > 1)
const unownedPorts = new Set(
(env[HOST_MANAGED_UNOWNED_PORTS_ENV] ?? '')
.split(',')
.map((port) => Number(port.trim()))
.filter((port) => Number.isInteger(port) && port > 0 && port < 65536)
)
return { roots, unownedPorts }
}
/**
* Listeners the host runs itself: this server process, a program started from a managed root
* (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too), or a declared platform
* port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or
* Docker-published port) is still the user's.
*/
export function isHostManagedListener(
port: Pick<RawListeningPort, 'pid' | 'commandLine' | 'port'>,
config: HostManagedListenerConfig,
serverPid: number = process.pid
): boolean {
if (port.pid === undefined) {
return config.unownedPorts.has(port.port)
}
if (port.pid === serverPid) {
return true
}
if (config.roots.length === 0 || !port.commandLine) {
return false
}
return port.commandLine
.trim()
.split(/\s+/)
.slice(0, 2)
.some((token) => config.roots.some((root) => token === root || token.startsWith(`${root}/`)))
}
+11 -1
View File
@@ -8,6 +8,7 @@ import {
reconcileAdvertisedUrls
} from './local-workspace-port-attribution'
import { scanPlatformListeningPorts } from './local-workspace-platform-port-scanner'
import { hostManagedListenerConfig, isHostManagedListener } from './host-managed-listeners'
import {
getWorkspacePortScanCooldown,
isWorkspacePortScanCommandTimeout,
@@ -40,6 +41,12 @@ export async function scanWorkspacePorts(
worktrees,
options.requireMetadata
)
const hostManaged = hostManagedListenerConfig()
const managed = new Set(
rawPorts
.filter((port) => isHostManagedListener(port, hostManaged))
.map((port) => `${port.host}:${port.port}:${port.pid ?? 'unknown'}`)
)
// Orca's own listeners (runtime socket, hook server) run with a workspace in their command line but are not its servers.
const attributedPorts = attributePortsToWorkspaces(
rawPorts.map((port) =>
@@ -52,7 +59,10 @@ export async function scanWorkspacePorts(
reconcileAdvertisedUrls(attributedPorts, normalizedWorktrees, urlWatcher)
}
const ports = attributedPorts
.map((port) => enrichPort(port, urlWatcher))
.map((port) => {
const enriched = enrichPort(port, urlWatcher)
return managed.has(enriched.id) ? { ...enriched, hostManaged: true as const } : enriched
})
.sort(compareWorkspacePorts)
.slice(0, MAX_PORTS)
return { platform: process.platform, scannedAt: Date.now(), ports }
+2 -3
View File
@@ -1,3 +1,4 @@
import type { RemoteDesktopPageState } from '../../../shared/hosted-sandbox/cloud-remote-desktop'
import type { BrowserSessionCookieApi } from './browser-session-cookie-api'
import type { BrowserDevToolsDockBounds } from '../../../shared/browser/devtools/browser-devtools-dock'
import type { BrowserSetAnnotationViewportBridgeArgs } from '../../../shared/browser/annotations/browser-annotation-viewport-bridge'
@@ -213,9 +214,7 @@ export type BrowserApi = {
/** Escape pressed in a focused page; the page also receives it unless a grab pick is running. */
onGuestEscape: (callback: (args: { browserPageId: string }) => void) => () => void
/** A browser page became (or stopped being) a remote desktop, or gained or lost the keyboard. */
onRemoteDesktopState: (
callback: (args: { browserPageId: string; desktop: boolean; captured: boolean }) => void
) => () => void
onRemoteDesktopState: (callback: (args: RemoteDesktopPageState) => void) => () => void
/** The release chord was pressed in a remote desktop: give the keyboard back to Orca. */
onRemoteDesktopRelease: (callback: (args: { browserPageId: string }) => void) => () => void
sessionListProfiles: () => Promise<BrowserSessionProfile[]>
@@ -1,3 +1,4 @@
import type { RemoteDesktopPageState } from '../../../shared/hosted-sandbox/cloud-remote-desktop'
import type { GoogleCookieClearLocalTarget } from '../../../shared/browser/cookies/browser-google-cookie-clear'
import { ipcRenderer } from 'electron'
import {
@@ -168,13 +169,9 @@ export const browserPageInteractionAndSessionsApi = {
ipcRenderer.on('browser:guestEscape', listener)
return () => ipcRenderer.removeListener('browser:guestEscape', listener)
},
onRemoteDesktopState: (
callback: (args: { browserPageId: string; desktop: boolean; captured: boolean }) => void
): (() => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
data: { browserPageId: string; desktop: boolean; captured: boolean }
) => callback(data)
onRemoteDesktopState: (callback: (args: RemoteDesktopPageState) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, data: RemoteDesktopPageState) =>
callback(data)
ipcRenderer.on('browser:remoteDesktopState', listener)
return () => ipcRenderer.removeListener('browser:remoteDesktopState', listener)
},
+18 -1
View File
@@ -3,14 +3,21 @@ import type {
CloudWorkspaceGrant,
CloudWorkspaceListQuery,
CloudWorkspacePatch,
CloudWorkspaceRoutineRuns,
OrgPrompts
} from '../../shared/cloud-workspaces/cloud-workspaces-wire'
import type { PokeInbox, TeammateProfile } from '../../shared/cloud-workspaces/team-presence-wire'
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
export type CloudWorkspacesResult<T> =
| { ok: true; value: T }
| { ok: false; error: string; reason?: string; status?: number }
/** A list read, plus what Home's Routine runs switch hides (absent from older control planes). */
export type CloudWorkspaceListResult =
| { ok: true; value: CloudWorkspace[]; routineRuns?: CloudWorkspaceRoutineRuns }
| { ok: false; error: string; reason?: string; status?: number }
export type LocalCloudWorkspace = {
sandboxId: string
worktreeId: string | null
@@ -23,7 +30,7 @@ export type CloudWorkspaceBinding = { environmentId: string; grantId: string | n
export type CloudWorkspacesApi = {
/** False when this build has no Orca Cloud control plane configured. */
available: () => Promise<boolean>
list: (query: CloudWorkspaceListQuery) => Promise<CloudWorkspacesResult<CloudWorkspace[]>>
list: (query: CloudWorkspaceListQuery) => Promise<CloudWorkspaceListResult>
get: (id: string) => Promise<CloudWorkspacesResult<CloudWorkspace>>
patch: (id: string, patch: CloudWorkspacePatch) => Promise<CloudWorkspacesResult<CloudWorkspace>>
resolveLink: (
@@ -62,6 +69,16 @@ export type CloudWorkspacesApi = {
document: OrgPrompts['document'],
revision: number
) => Promise<CloudWorkspacesResult<OrgPrompts>>
/** A teammate's profile: usage heatmap (levels only unless it is you) and workspaces you can see. */
teammateProfile: (
userId: string,
utcOffsetMin: number
) => Promise<CloudWorkspacesResult<TeammateProfile>>
/** Pokes (experimental, opt-in on both sides). */
poke: (userId: string) => Promise<CloudWorkspacesResult<{ id: string; at: number }>>
pokeInbox: () => Promise<CloudWorkspacesResult<PokeInbox>>
setPokesEnabled: (enabled: boolean) => Promise<CloudWorkspacesResult<boolean>>
markPokesSeen: (ids: string[]) => Promise<CloudWorkspacesResult<void>>
onOpenLink: (callback: (link: string) => void) => () => void
consumePendingLink: () => Promise<string | null>
}
@@ -27,6 +27,12 @@ export const cloudWorkspacesApi = {
getOrgPrompts: () => ipcRenderer.invoke('cloudWorkspaces:getOrgPrompts'),
putOrgPrompts: (document, revision) =>
ipcRenderer.invoke('cloudWorkspaces:putOrgPrompts', { document, revision }),
teammateProfile: (userId, utcOffsetMin) =>
ipcRenderer.invoke('cloudWorkspaces:teammateProfile', { userId, utcOffsetMin }),
poke: (userId) => ipcRenderer.invoke('cloudWorkspaces:poke', { userId }),
pokeInbox: () => ipcRenderer.invoke('cloudWorkspaces:pokeInbox'),
setPokesEnabled: (enabled) => ipcRenderer.invoke('cloudWorkspaces:setPokesEnabled', { enabled }),
markPokesSeen: (ids) => ipcRenderer.invoke('cloudWorkspaces:markPokesSeen', { ids }),
onOpenLink: (callback) => {
const listener = (_event: Electron.IpcRendererEvent, link: string): void => callback(link)
ipcRenderer.on('ui:openCloudWorkspaceLink', listener)
+2
View File
@@ -58,6 +58,8 @@ export type EphemeralVmApi = {
branch?: string
ref?: string
provisionId?: string
/** Orca Cloud: one per Create press, sent as the create's Idempotency-Key. */
idempotencyKey?: string
}) => Promise<
| {
ok: true
+6
View File
@@ -8,9 +8,12 @@ import { BrowserExtensionInstallDialog } from './components/browser-extension-in
import { PlansDialogHost } from './components/billing/plans/PlansDialogHost'
import { CloudMoveToComputerDialogMount } from './components/orca-cloud/CloudMoveToComputerDialogMount'
import { CloudSecretsAskDialogHost } from './components/cloud-secrets-ask/CloudSecretsMissingNotice'
import { OrcaCloudSignInSheet } from './components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet'
import { AgentHostPanel } from './components/agent-host-panel/AgentHostPanel'
import { SecretRequestUnseenNotifier } from './components/agent-pane/SecretRequestUnseenNotifier'
import { TeamDialogHost } from './components/billing/team/TeamDialogHost'
import { TeammateProfileDialog } from './components/teammates/TeammateProfileDialog'
import { PokesNotifier } from './components/teammates/PokesNotifier'
import { BrowserPagePrompts } from './components/browser-pane/browser-page-prompts'
import { LinkRoutingPreferenceDialogProvider } from './components/link-routing-preference-dialog'
import { SkillFreshnessNudge } from './components/skills/SkillFreshnessNudge'
@@ -127,8 +130,11 @@ function App(): React.JSX.Element {
<CloudMoveToComputerDialogMount />
<CloudSecretsAskDialogHost />
<AgentHostPanel />
<OrcaCloudSignInSheet />
<SecretRequestUnseenNotifier />
<TeamDialogHost />
<TeammateProfileDialog />
<PokesNotifier />
</LinkRoutingPreferenceDialogProvider>
</ConfirmationDialogProvider>
{createPortal(
@@ -11,6 +11,7 @@ import { FloatingTerminalToggleButton } from '../components/floating-terminal/Fl
import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer'
import { WorkspaceLowDiskBanner } from '../components/low-disk/WorkspaceLowDiskBanner'
import { CloudSetupPageLayer } from '../components/orca-cloud-setup/CloudSetupPageLayer'
import { CloudOpenCoverLayer } from '../components/worktree-creation/CloudOpenCoverLayer'
import type { VirtualizedScrollAnchor } from '../hooks/useVirtualizedScrollAnchor'
import { TitlebarLeftControls } from './TitlebarLeftControls'
import { RightSidebarToggle, TitlebarMainStrip } from './TitlebarMainStrip'
@@ -248,6 +249,9 @@ export function AppWorkspaceShell(props: {
</Suspense>
</div>
<CloudSetupPageLayer />
<CloudOpenCoverLayer
reserveCollapsedSidebarHeaderSpace={layout.leftTitlebarChromeLayout.isFloating}
/>
{floatingWorkspace.showToggleButton && !capturingPluginShot ? (
<MemoFloatingTerminalToggleButton
open={floatingWorkspace.open}
@@ -1,6 +1,7 @@
// The panel's footer links and row actions open Settings over it; the panel closes first so focus
// lands in Settings rather than behind the sheet.
import { useAppStore } from '@/store'
import { openOrcaCloudSignInSheet } from '@/components/settings/agent-accounts/sign-in-sheet/orca-cloud-sign-in-sheet-store'
import type { AgentHostFooterLink } from './agent-host-capabilities'
import { closeAgentHostPanel } from './agent-host-panel-store'
@@ -16,6 +17,10 @@ const TARGET = {
export function openAgentHostSettings(link: AgentHostFooterLink): void {
closeAgentHostPanel()
if (link === 'agentAccounts') {
openOrcaCloudSignInSheet()
return
}
const target: { pane: (typeof TARGET)[AgentHostFooterLink]['pane']; sectionId?: string } =
TARGET[link]
const store = useAppStore.getState()
@@ -2,6 +2,7 @@
// private launch hold waits, or #40228's per-workspace gate while the Orca-account path is paused or
// never offered. It overlays the top 56 px of the pane while the agent hasn't started, so the
// terminal's size never changes. SSH, WSL and paired hosts keep #40228's card.
import { openOrcaCloudSignInSheet } from '@/components/settings/agent-accounts/sign-in-sheet/orca-cloud-sign-in-sheet-store'
import React, { useEffect, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
import { useAppStore } from '@/store'
@@ -51,7 +52,7 @@ export function useCloudGatePaneKeys(controller: TerminalPaneController): Readon
return new Set(joined ? joined.split('\u0000') : [])
}
function openSettings(pane: 'accounts' | 'cloud-secrets', sectionId?: string): void {
function openSettings(pane: 'cloud-secrets', sectionId?: string): void {
const store = useAppStore.getState()
store.openSettingsTarget({ pane, repoId: null, ...(sectionId ? { sectionId } : {}) })
store.openSettingsPage()
@@ -119,7 +120,7 @@ function CloudStripPortal({
primary: (action) => {
switch (action.kind) {
case 'renew':
openSettings('accounts', 'orca-cloud')
openOrcaCloudSignInSheet()
return
case 'signIn':
gateActions.signIn()
@@ -14,6 +14,7 @@ import { createTeamFailureCopy, mutationFailureCopy } from './team-copy'
import { clearTeamPageArrival, closeTeamPage, useTeamPageState } from './team-page-store'
import { useOrgRoster } from './use-org-roster'
import { useTeamActions } from './use-team-actions'
import { openTeammateProfile } from '../../teammates/teammate-profile-store'
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
function TeamPageBody({ arrival }: { arrival: ReturnType<typeof useTeamPageState>['arrival'] }) {
@@ -209,6 +210,11 @@ function TeamPageBody({ arrival }: { arrival: ReturnType<typeof useTeamPageState
telemetrySource: 'unknown'
})
}}
onOpenProfile={(userId) => {
// One dialog at a time: the profile replaces the Team page (as in Conductor 0.91).
closeTeamPage()
openTeammateProfile(userId)
}}
onDismissArrival={clearTeamPageArrival}
onContactSales={(url) => void window.api.shell.openUrl(url)}
/>
@@ -1,4 +1,12 @@
import { Crown, LogOut, MailPlus, MoreHorizontal, UserMinus, XCircle } from 'lucide-react'
import {
Crown,
LogOut,
MailPlus,
MoreHorizontal,
UserMinus,
UserRound,
XCircle
} from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
@@ -39,6 +47,8 @@ export type TeamMemberListProps = {
onResend: (email: string, role: OrcaOrgRole) => void
onRevoke: (email: string) => void
onLeave: () => void
/** Opens a signed-in member's profile (usage heatmap, recent workspaces, Pokes). */
onOpenProfile?: (userId: string) => void
}
function relativeSince(then: number, now: number, locale: string): string {
@@ -118,7 +128,23 @@ function RowMenu({
const name =
row.kind === 'member' ? (row.member.displayName ?? row.member.email) : row.invite.email
const items: React.ReactNode[] = []
const profileUserId = row.kind === 'member' && row.status === 'active' ? row.member.userId : null
if (profileUserId && props.onOpenProfile) {
items.push(
<DropdownMenuItem key="profile" onSelect={() => props.onOpenProfile?.(profileUserId)}>
<UserRound />
{t('auto.components.billing.team.viewProfile', 'View profile')}
</DropdownMenuItem>
)
}
// Profile sits apart from the role and membership actions below it.
const separateFromProfile = (): void => {
if (items.length === 1 && profileUserId && props.onOpenProfile) {
items.push(<DropdownMenuSeparator key="profile-sep" />)
}
}
if (row.kind === 'invite' && row.manageable) {
separateFromProfile()
items.push(
<DropdownMenuItem
key="resend"
@@ -139,6 +165,7 @@ function RowMenu({
)
}
if (row.kind === 'member' && row.manageable) {
separateFromProfile()
if (props.viewerRole === 'owner' && row.member.role !== 'owner') {
items.push(
<DropdownMenuItem key="owner" onSelect={() => props.onMakeOwner(row.member)}>
@@ -160,6 +187,7 @@ function RowMenu({
)
}
if (row.self) {
separateFromProfile()
items.push(
<DropdownMenuItem
key="leave"
@@ -210,6 +238,8 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
const state = props.rowStates[row.key] ?? {}
const name =
row.kind === 'member' ? (row.member.displayName ?? row.member.email) : row.invite.email
const profileUserId =
row.kind === 'member' && row.status === 'active' ? row.member.userId : null
const secondary =
row.kind === 'member'
? row.member.displayName
@@ -232,7 +262,22 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
<PersonAvatar name={name} pending={row.status !== 'active'} />
<div className="min-w-0 flex-1">
<p className="flex min-w-0 items-center gap-2 text-sm font-medium">
<span className="truncate">{name}</span>
{profileUserId && props.onOpenProfile ? (
<button
type="button"
onClick={() => props.onOpenProfile?.(profileUserId)}
aria-label={t(
'auto.components.billing.team.openProfile',
'Open {{value0}}’s profile',
{ value0: name }
)}
className="min-w-0 cursor-default truncate rounded-sm text-left outline-none hover:underline focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-focus-ring"
>
{name}
</button>
) : (
<span className="truncate">{name}</span>
)}
{row.self ? (
<span className="shrink-0 text-xs font-normal text-muted-foreground">
{t('auto.components.billing.team.you', '(you)')}
@@ -44,6 +44,7 @@ export type TeamPageViewProps = {
onResend: (email: string, role: OrcaOrgRole) => void
onRevoke: (email: string) => void
onLeave: () => void
onOpenProfile?: (userId: string) => void
onSeePlans: () => void
onManageBilling: () => void
onCreateWorkspace: () => void
@@ -261,6 +262,7 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
onResend={props.onResend}
onRevoke={props.onRevoke}
onLeave={props.onLeave}
onOpenProfile={props.onOpenProfile}
/>
) : props.roster === null ? (
<SkeletonRows />
@@ -22,6 +22,8 @@ import { getOpenableExternalUrl, toDisplayUrl } from '../describe-page/browser-p
import type { BrowserOverlayViewport } from '../describe-page/browser-annotation-geometry'
import type { BrowserPagePaneProps } from '../describe-page/browser-page-types'
import { BrowserPageChromeHeader } from './browser-page-chrome-header'
import { CloudDesktopTabSurface } from '../../cloud-remote-desktop/CloudDesktopTabSurface'
import { isCloudRemoteDesktopUrl } from '../../../../../shared/hosted-sandbox/cloud-remote-desktop'
import { BrowserPageContextMenu } from './browser-page-context-menu'
import { BrowserPageViewportOverlays } from './browser-page-viewport-overlays'
import { useBrowserPageAnnotationSend } from '../annotate/use-browser-page-annotation-send'
@@ -329,33 +331,46 @@ export function BrowserPagePane({
webviewRef={webviewRef}
onReload={() => reload.reloadWebviewOrRecoverGuest(false)}
/>
<BrowserPageChromeHeader
chromeHeaderRef={chromeHeaderRef}
browserTab={browserTab}
workspaceId={workspaceId}
worktreeId={worktreeId}
sessionProfileId={sessionProfileId}
isActive={isActive}
webviewRef={webviewRef}
addressBarInputRef={addressBarInputRef}
dismissAddressBarSuggestionsRef={dismissAddressBarSuggestionsRef}
reload={reload}
nav={nav}
grab={grab}
grabAnnotations={grabAnnotations}
annotationSend={annotationSend}
onOpenFind={() => setFindOpen(true)}
markupIsActive={markup.isActive}
markupStart={markup.start}
markupCancel={markup.cancel}
grabElementShortcut={grabElementShortcut}
shareableArtifactFile={shareableArtifactFile}
currentBrowserUrl={currentBrowserUrl}
externalUrl={externalUrl}
isBlankTab={isBlankTab}
resourceNotice={resourceNotice}
setResourceNotice={setResourceNotice}
/>
{isCloudRemoteDesktopUrl(browserTab.url) ? (
// A remote desktop tab has no address bar: its own toolbar, and a cover while it can't show.
<CloudDesktopTabSurface
chromeHeaderRef={chromeHeaderRef}
worktreeId={worktreeId}
browserPageId={browserTab.id}
url={browserTab.url}
reload={() => reload.reloadWebviewOrRecoverGuest(false)}
navigate={nav.navigateToUrl}
viewportContainer={pageViewport?.container ?? null}
/>
) : (
<BrowserPageChromeHeader
chromeHeaderRef={chromeHeaderRef}
browserTab={browserTab}
workspaceId={workspaceId}
worktreeId={worktreeId}
sessionProfileId={sessionProfileId}
isActive={isActive}
webviewRef={webviewRef}
addressBarInputRef={addressBarInputRef}
dismissAddressBarSuggestionsRef={dismissAddressBarSuggestionsRef}
reload={reload}
nav={nav}
grab={grab}
grabAnnotations={grabAnnotations}
annotationSend={annotationSend}
onOpenFind={() => setFindOpen(true)}
markupIsActive={markup.isActive}
markupStart={markup.start}
markupCancel={markup.cancel}
grabElementShortcut={grabElementShortcut}
shareableArtifactFile={shareableArtifactFile}
currentBrowserUrl={currentBrowserUrl}
externalUrl={externalUrl}
isBlankTab={isBlankTab}
resourceNotice={resourceNotice}
setResourceNotice={setResourceNotice}
/>
)}
{pageViewport?.container
? createPortal(
<BrowserPageViewportOverlays
@@ -0,0 +1,286 @@
import type React from 'react'
import type { RefObject } from 'react'
import { Loader2, Monitor, Play, RotateCw } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
import { CLOUD_DOT_CLASS } from '@/components/orca-cloud/CloudStateDot'
import {
runUnarchiveCloudWorkspace,
wakeCloudWorkspace
} from '@/components/orca-cloud/cloud-workspace-actions'
import type { CloudDotState } from '@/lib/orca-cloud/orca-cloud-workspace-state'
import type { CloudDesktopPhase } from '@/lib/cloud-remote-desktop/use-cloud-desktop-connection'
import { actionLabel, failureCopy } from './CloudRemoteDesktopToast'
import { remoteDesktopReleaseChordLabel } from './RemoteDesktopKeyboardHint'
function phaseLabel(t: Translate, phase: CloudDesktopPhase): string {
switch (phase.kind) {
case 'connected':
return t('components.cloudRemoteDesktop.tab.connected', 'Connected')
case 'connecting':
return t('components.cloudRemoteDesktop.tab.connecting', 'Connecting…')
case 'reconnecting':
return t('components.cloudRemoteDesktop.tab.reconnecting', 'Reconnecting…')
case 'asleep':
return t('orcaCloudWorkspace.state.asleep', 'Asleep')
case 'waking':
return t('components.cloudRemoteDesktop.tab.waking', 'Waking…')
case 'archived':
return t('orcaCloudWorkspace.state.archived', 'Archived')
case 'wakeFailed':
return t('orcaCloudWorkspace.state.wakeFailed', 'Couldn’t wake')
case 'failed':
case 'paused':
return t('components.cloudRemoteDesktop.tab.disconnected', 'Disconnected')
}
}
/** The status dot reuses the Orca Cloud state shapes (hollow asleep, half waking, …). */
function phaseDot(phase: CloudDesktopPhase): CloudDotState {
switch (phase.kind) {
case 'connected':
return 'running'
case 'connecting':
case 'reconnecting':
case 'waking':
return 'waking'
case 'asleep':
return 'sleeping'
case 'archived':
return 'archived'
case 'wakeFailed':
return 'wakeFailed'
case 'failed':
case 'paused':
return 'unresponsive'
}
}
/** Replaces the address bar on a remote desktop tab: what it is, how it stands, Reconnect. */
export function CloudDesktopTabToolbar({
chromeHeaderRef,
phase,
onReconnect
}: {
chromeHeaderRef: RefObject<HTMLDivElement | null>
phase: CloudDesktopPhase
onReconnect: () => void
}): React.JSX.Element {
const t = useTranslate()
const busy = phase.kind === 'reconnecting' || phase.kind === 'waking'
const sandboxDown =
phase.kind === 'asleep' || phase.kind === 'archived' || phase.kind === 'wakeFailed'
return (
<div ref={chromeHeaderRef} className="pointer-events-auto shrink-0">
<div
data-cloud-desktop-toolbar=""
className="relative z-10 flex h-9 shrink-0 items-center gap-2 border-b border-border/70 bg-background/95 px-3"
>
<Monitor className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="text-xs font-medium text-foreground">
{t('components.cloudRemoteDesktop.tabTitle', 'Remote desktop')}
</span>
<Badge variant="tag">{t('components.cloudRemoteDesktop.beta', 'Beta')}</Badge>
<span
role="status"
className="ml-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
>
<span className={cn('size-2 shrink-0', CLOUD_DOT_CLASS[phaseDot(phase)])} aria-hidden />
<span className="truncate">{phaseLabel(t, phase)}</span>
</span>
<span className="ml-auto flex shrink-0 items-center gap-2">
{phase.kind === 'connected' ? (
<span className="text-xs whitespace-nowrap text-muted-foreground">
{t(
'components.cloudRemoteDesktop.tab.releaseHint',
'{{chord}} returns keys to Orca',
{
chord: remoteDesktopReleaseChordLabel()
}
)}
</span>
) : null}
<Button
type="button"
variant="ghost"
size="xs"
disabled={busy || sandboxDown}
onClick={onReconnect}
>
<RotateCw aria-hidden />
{t('components.cloudRemoteDesktop.reconnect', 'Reconnect')}
</Button>
</span>
</div>
</div>
)
}
function CoverCard({
busy,
title,
detail,
action
}: {
busy?: boolean
title: string
detail?: string
action?: React.ReactNode
}): React.JSX.Element {
return (
<div role="status" className="flex max-w-sm flex-col items-center gap-3 px-6 text-center">
<span className="flex size-10 items-center justify-center rounded-full border border-border bg-muted/40 text-muted-foreground">
{busy ? (
<Loader2 className="size-5 motion-safe:animate-spin" aria-hidden />
) : (
<Monitor className="size-5" aria-hidden />
)}
</span>
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">{title}</p>
{detail ? <p className="text-xs text-muted-foreground">{detail}</p> : null}
</div>
{action}
</div>
)
}
/**
* Over the desktop page whenever there is no live desktop to show: the sandbox is asleep (Wake),
* waking (it reconnects by itself), archived, or reopening it failed. Connected, connecting and
* paused pages show the page itself (noVNC paints its own connect and pause states).
*/
export function CloudDesktopTabCover({
worktreeId,
phase,
onReconnect
}: {
worktreeId: string
phase: CloudDesktopPhase
onReconnect: () => void
}): React.JSX.Element | null {
const t = useTranslate()
let body: React.ReactNode
switch (phase.kind) {
case 'connected':
case 'connecting':
case 'paused':
return null
case 'reconnecting':
body = (
<CoverCard
busy
title={t('components.cloudRemoteDesktop.tab.reconnectingTitle', 'Reconnecting…')}
/>
)
break
case 'waking':
body = (
<CoverCard
busy
title={t('components.cloudRemoteDesktop.waking', 'Waking sandbox…')}
detail={t(
'components.cloudRemoteDesktop.tab.wakingDetail',
'The remote desktop reconnects when it’s awake.'
)}
/>
)
break
case 'asleep':
case 'wakeFailed': {
const failed = phase.kind === 'wakeFailed'
body = (
<CoverCard
title={
failed
? t('components.cloudRemoteDesktop.wakeFailedTitle', 'Couldn’t wake the sandbox.')
: t('components.cloudRemoteDesktop.tab.asleepTitle', 'This workspace is asleep.')
}
detail={
failed
? t('components.cloudRemoteDesktop.wakeFailedDetail', 'Your files are safe.')
: t(
'components.cloudRemoteDesktop.tab.asleepDetail',
'Wake it to reconnect. Apps that were open on the remote desktop need to be started again. Your files are safe.'
)
}
action={
<Button
type="button"
variant="outline"
size="xs"
onClick={() => void wakeCloudWorkspace(worktreeId)}
>
<Play aria-hidden />
{failed
? t('components.cloudRemoteDesktop.retry', 'Try again')
: t('orcaCloudWorkspace.wake', 'Wake')}
</Button>
}
/>
)
break
}
case 'archived':
body = (
<CoverCard
title={t('components.cloudRemoteDesktop.archivedTitle', 'This workspace is archived.')}
detail={t(
'components.cloudRemoteDesktop.archivedDetail',
'Unarchive it to open the remote desktop. Your files are safe.'
)}
action={
<Button
type="button"
variant="outline"
size="xs"
onClick={() => void runUnarchiveCloudWorkspace(worktreeId)}
>
{t('components.cloudRemoteDesktop.unarchive', 'Unarchive')}
</Button>
}
/>
)
break
case 'failed': {
const copy = failureCopy(t, phase.code)
const signIn = copy.action === 'sign_in'
body = (
<div className="w-full max-w-sm px-6">
<InlineError
title={copy.title}
detail={copy.detail}
tone={copy.tone}
action={
<Button
type="button"
variant="outline"
size="xs"
onClick={() =>
signIn ? void useAppStore.getState().connectCurrentOrcaProfile() : onReconnect()
}
>
{signIn
? actionLabel(t, 'sign_in')
: t('components.cloudRemoteDesktop.reconnect', 'Reconnect')}
</Button>
}
/>
</div>
)
break
}
}
return (
<div
data-cloud-desktop-cover={phase.kind}
className="pointer-events-auto absolute inset-0 z-30 flex items-center justify-center bg-background"
>
{body}
</div>
)
}
@@ -0,0 +1,48 @@
import type React from 'react'
import type { RefObject } from 'react'
import { createPortal } from 'react-dom'
import { useCloudDesktopConnection } from '@/lib/cloud-remote-desktop/use-cloud-desktop-connection'
import { CloudDesktopTabCover, CloudDesktopTabToolbar } from './CloudDesktopTabChrome'
/** A remote desktop tab's chrome: a toolbar in place of the address bar, and a cover over the page. */
export function CloudDesktopTabSurface({
chromeHeaderRef,
worktreeId,
browserPageId,
url,
reload,
navigate,
viewportContainer
}: {
chromeHeaderRef: RefObject<HTMLDivElement | null>
worktreeId: string
browserPageId: string
url: string
reload: () => void
navigate: (url: string) => void
viewportContainer: HTMLElement | null
}): React.JSX.Element {
const { phase, reconnect } = useCloudDesktopConnection({
enabled: true,
worktreeId,
browserPageId,
url,
reload,
navigate
})
return (
<>
<CloudDesktopTabToolbar
chromeHeaderRef={chromeHeaderRef}
phase={phase}
onReconnect={reconnect}
/>
{viewportContainer
? createPortal(
<CloudDesktopTabCover worktreeId={worktreeId} phase={phase} onReconnect={reconnect} />,
viewportContainer
)
: null}
</>
)
}
@@ -21,7 +21,7 @@ export type CloudRemoteDesktopToastState =
| { kind: 'waking'; via: 'wake' | 'unarchive' }
| { kind: 'failed'; code: CloudRemoteDesktopToastFailure }
type FailureCopy = {
export type FailureCopy = {
title: string
detail: string
action: CloudRemoteDesktopNextAction | null
@@ -31,7 +31,7 @@ type FailureCopy = {
tone?: 'neutral'
}
function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): FailureCopy {
export function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): FailureCopy {
switch (code) {
case 'not_cloud':
return {
@@ -139,7 +139,7 @@ function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): Failur
}
}
function actionLabel(t: Translate, action: CloudRemoteDesktopNextAction): string {
export function actionLabel(t: Translate, action: CloudRemoteDesktopNextAction): string {
switch (action) {
case 'wake':
return t('components.cloudRemoteDesktop.wake', 'Wake sandbox')
@@ -1,5 +1,5 @@
import React, { useEffect, useId, useRef, useState } from 'react'
import { GitBranch, Loader2, Lock } from 'lucide-react'
import { CalendarClock, GitBranch, Loader2, Lock } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { type Translate, useIntlLocale, useTranslate } from '@/i18n/use-translate'
@@ -25,7 +25,7 @@ import {
import { cloudWorkspaceTitle } from './open-cloud-workspace'
/** The shared Orca Cloud dot vocabulary (shape and tone), same as the sidebar and panel. */
function dotState(w: CloudWorkspace): CloudDotState {
export function dotState(w: CloudWorkspace): CloudDotState {
if (w.archivedAt !== null) {
return 'archived'
}
@@ -48,7 +48,7 @@ function dotState(w: CloudWorkspace): CloudDotState {
}
/** Glossary lifecycle states only: a sandbox going to sleep already reads as Asleep. */
function statusLabel(w: CloudWorkspace, t: Translate): string {
export function statusLabel(w: CloudWorkspace, t: Translate): string {
if (w.archivedAt !== null) {
return t('auto.components.cloudWorkspaces.statusArchived', 'Archived')
}
@@ -255,10 +255,39 @@ export function CloudWorkspaceRow({
</TooltipContent>
</Tooltip>
)}
{w.fromRoutine === true && (
<Tooltip>
<TooltipTrigger asChild>
<CalendarClock
role="img"
className="size-3 shrink-0 text-muted-foreground"
aria-label={t('auto.components.cloudWorkspaces.routineRun', 'Routine run')}
/>
</TooltipTrigger>
<TooltipContent side="top">
{t(
'auto.components.cloudWorkspaces.routineRunTooltip',
"Started by a routine. It's deleted when the run ends."
)}
</TooltipContent>
</Tooltip>
)}
</span>
<span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
<MemberAvatar userId={w.ownerUserId} directory={directory} selfId={selfId} size="sm" />
<span className="shrink-0">{ownerName}</span>
{w.fromRoutine === true && (
<>
<span aria-hidden>·</span>
<span className="truncate">
{w.routineName
? t('auto.components.cloudWorkspaces.routineRunOf', 'Routine · {{name}}', {
name: w.routineName
})
: t('auto.components.cloudWorkspaces.routineRun', 'Routine run')}
</span>
</>
)}
{showStatus && (
<>
<span aria-hidden>·</span>
@@ -38,6 +38,7 @@ import type {
CloudWorkspacePresence
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { MemberAvatar } from './CloudMemberAvatars'
import { openTeammateProfile } from '../teammates/teammate-profile-store'
import { memberName, presentMembers, type MemberDirectory } from './cloud-workspace-format'
export type RowActions = {
@@ -168,6 +169,16 @@ export function CloudWorkspaceRowMenu({
<Link2 />
{t('auto.components.cloudWorkspaces.copyWorkspaceLink', 'Copy workspace link')}
</DropdownMenuItem>
{w.ownerUserId !== selfId && (
<DropdownMenuItem onSelect={() => openTeammateProfile(w.ownerUserId)}>
<MemberAvatar userId={w.ownerUserId} directory={directory} selfId={selfId} size="sm" />
<span className="truncate">
{t('auto.components.cloudWorkspaces.viewOwnerProfile', "View {{name}}'s profile", {
name: memberName(directory, w.ownerUserId, selfId, t)
})}
</span>
</DropdownMenuItem>
)}
{teammatesHere.length > 0 && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
@@ -7,6 +7,10 @@ import {
workspace
} from './cloud-workspaces.test-fixture'
import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state'
import { getOrcaAccountKey } from '@/hooks/use-orca-account-key'
import { writeHomeSwitches } from './cloud-workspaces-home-prefs'
const FIXTURE_ACCOUNT = getOrcaAccountKey(AUTH_STATUS)
const WIDTH = 760
@@ -187,3 +191,90 @@ export const withRoutinesEntry = defineFixture({
[...document.querySelectorAll('button')].some((b) => b.textContent === 'Routines')
)
})
/** Routine runs stay off Home; the Routine runs switch brings in-flight ones back, marked. */
function stubWithRoutineRuns(): void {
writeHomeSwitches(FIXTURE_ACCOUNT, { running: false, archived: false, routines: false })
const rows = teamWorkspaces()
const run = workspace({
id: 'sbx_0000000000000000000000e1',
title: 'nightly-deps · run',
status: 'running',
fromRoutine: true,
routineName: 'nightly-deps',
section: null
})
stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows }))
Object.assign(window.api.cloudWorkspaces, {
list: (query: { routines?: string }) =>
Promise.resolve(
query.routines === 'include'
? {
ok: true as const,
value: [run, ...rows],
routineRuns: { routines: 2, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 }
}
: {
ok: true as const,
value: rows,
routineRuns: {
routines: 2,
hidden: 1,
hiddenRunning: 1,
hiddenComputeMs: run.cost.computeMs
}
}
)
})
}
function routineSwitch(): HTMLElement | null {
return document.querySelector<HTMLElement>('[aria-label="Show routine runs"]')
}
/** A team without routines never sees the switch. */
export const noRoutines = defineFixture({
width: WIDTH,
store: { orcaProfileAuthStatus: AUTH_STATUS },
setup: () => {
const rows = teamWorkspaces()
stubCloudWorkspacesApi(() =>
Promise.resolve({
ok: true,
value: rows,
routineRuns: { routines: 0, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 }
})
)
},
render: () => <CloudWorkspacesHome />,
interact: () => waitFor(() => document.querySelector('[data-cloud-workspace-row]') !== null)
})
/** Default: routine runs are hidden; the switch says how many are running. */
export const routineRunsHidden = defineFixture({
width: WIDTH,
store: { orcaProfileAuthStatus: AUTH_STATUS },
setup: stubWithRoutineRuns,
render: () => <CloudWorkspacesHome />,
interact: () =>
waitFor(
() =>
document.querySelector('[data-cloud-workspace-row]') !== null && routineSwitch() !== null
)
})
/** Switch on: the in-flight run is listed with the routine mark. */
export const routineRunsShown = defineFixture({
width: WIDTH,
store: { orcaProfileAuthStatus: AUTH_STATUS },
setup: stubWithRoutineRuns,
render: () => <CloudWorkspacesHome />,
interact: async () => {
await waitFor(
() =>
document.querySelector('[data-cloud-workspace-row]') !== null && routineSwitch() !== null
)
routineSwitch()!.click()
await waitFor(() => document.querySelector('[aria-label="Routine run"]') !== null)
}
})
@@ -15,13 +15,9 @@ import type {
import { useOrgRoster } from '../billing/team/use-org-roster'
import { CloudWorkspaceRow } from './CloudWorkspaceRow'
import { NEW_SECTION } from './CloudWorkspaceRowMenu'
import {
ANY,
CloudWorkspacesToolbar,
INITIAL_CLOUD_WORKSPACE_FILTERS,
type CloudWorkspacesFilters
} from './CloudWorkspacesToolbar'
import { ANY, CloudWorkspacesToolbar } from './CloudWorkspacesToolbar'
import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates'
import { useCloudHomeFilters } from './use-cloud-home-filters'
import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog'
import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet'
import { useCloudReadPanel } from './use-cloud-read-panel'
@@ -84,14 +80,7 @@ export function CloudWorkspacesHome({
const orgId = cloud?.activeOrgId
const selfId = cloud?.userId ?? null
const account = useOrcaAccountKey()
const [filters, setFilters] = useState(INITIAL_CLOUD_WORKSPACE_FILTERS)
homeArchive.usePendingHomeFilters(setFilters)
// Owner and repo filters name the previous team's people and repos; a team switch starts over.
const [filtersAccount, setFiltersAccount] = useState(account)
if (filtersAccount !== account) {
setFiltersAccount(account)
setFilters(INITIAL_CLOUD_WORKSPACE_FILTERS)
}
const { filters, changeFilters } = useCloudHomeFilters(account)
const [opening, setOpening] = useState<string | null>(null)
const [now, setNow] = useState(() => Date.now())
const [sectionFor, setSectionFor] = useState<CloudWorkspace | null>(null)
@@ -100,7 +89,11 @@ export function CloudWorkspacesHome({
const signIn = useAppStore((s) => s.connectCurrentOrcaProfile)
const scope = orgId ? filters.scope : 'mine'
const { state, stale, reading, refresh, replace } = useCloudWorkspaces(
{ scope, archived: filters.archived ? 'only' : 'exclude' },
{
scope,
archived: filters.archived ? 'only' : 'exclude',
...(filters.routines ? { routines: 'include' as const } : {})
},
Boolean(cloud),
account
)
@@ -111,16 +104,6 @@ export function CloudWorkspacesHome({
[]
)
const changeFilters = useCallback((next: Partial<CloudWorkspacesFilters>) => {
setFilters((previous) => {
// A different list (scope or archived) has different owners and repos; start unfiltered.
const reset =
(next.scope !== undefined && next.scope !== previous.scope) ||
(next.archived !== undefined && next.archived !== previous.archived)
return { ...previous, ...(reset ? { by: ANY, repo: ANY } : {}), ...next }
})
}, [])
// A workspace being deleted (or gone) is not something to open or manage; Home leaves it out.
const all = useHomeWorkspaces(state.status === 'ready' ? state.workspaces : null)
const { directory, canAdmin } = useMemberDirectory(orgId, all)
@@ -170,7 +153,11 @@ export function CloudWorkspacesHome({
})),
[directory, selfId, t]
)
const totalMs = visible.reduce((sum, w) => sum + w.cost.computeMs, 0)
const routineRuns = state.status === 'ready' ? state.routineRuns : undefined
// Hidden routine runs leave the count but not the hours: they are still the team's usage.
const totalMs =
visible.reduce((sum, w) => sum + w.cost.computeMs, 0) +
(filters.routines ? 0 : (routineRuns?.hiddenComputeMs ?? 0))
/** Opens the workspace, then (going to a teammate's chat) the chat they have in front. */
const open = useCallback(
@@ -298,6 +285,7 @@ export function CloudWorkspacesHome({
}
reading={reading}
onRefresh={refresh}
routineRuns={routineRuns}
/>
<div
@@ -0,0 +1,108 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import {
CloudWorkspacesToolbar,
INITIAL_CLOUD_WORKSPACE_FILTERS,
type CloudWorkspacesFilters
} from './CloudWorkspacesToolbar'
import { readHomeSwitches, writeHomeSwitches } from './cloud-workspaces-home-prefs'
import type { CloudWorkspaceRoutineRuns } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
// The toolbar's trial banner and Routines entry read the preload bridge; neither is under test.
vi.mock('../new-workspace/run-on/OrcaCloudTrialUsedUpNotice', () => ({
OrcaCloudTrialUsedUpBanner: () => null
}))
vi.mock('@/hooks/useOrcaCloudApiAvailability', () => ({ useOrcaCloudApiAvailable: () => false }))
afterEach(cleanup)
function toolbar(
routineRuns: CloudWorkspaceRoutineRuns | undefined,
filters: Partial<CloudWorkspacesFilters> = {},
onFiltersChange = vi.fn()
) {
render(
<TooltipProvider>
<CloudWorkspacesToolbar
filters={{ ...INITIAL_CLOUD_WORKSPACE_FILTERS, ...filters }}
onFiltersChange={onFiltersChange}
hasOrg
owners={[]}
repos={[]}
directory={new Map()}
selfId="u1"
meta={null}
metaStale={false}
reading={false}
onRefresh={vi.fn()}
routineRuns={routineRuns}
/>
</TooltipProvider>
)
return onFiltersChange
}
const runs = (over: Partial<CloudWorkspaceRoutineRuns> = {}): CloudWorkspaceRoutineRuns => ({
routines: 1,
hidden: 0,
hiddenRunning: 0,
hiddenComputeMs: 0,
...over
})
describe('Home toolbar: Routine runs switch', () => {
it('is not offered to a team with no routines (or an older control plane)', () => {
toolbar(runs({ routines: 0 }))
expect(screen.queryByLabelText('Show routine runs')).toBeNull()
cleanup()
toolbar(undefined)
expect(screen.queryByLabelText('Show routine runs')).toBeNull()
})
it('is off by default and counts the running runs it hides', () => {
const onChange = toolbar(runs({ hidden: 3, hiddenRunning: 2 }))
const toggle = screen.getByLabelText('Show routine runs')
expect(toggle.getAttribute('aria-checked')).toBe('false')
expect(screen.getByText('Routine runs · 2')).toBeTruthy()
fireEvent.click(toggle)
expect(onChange).toHaveBeenCalledWith({ routines: true })
})
it('drops the count once the runs are listed', () => {
toolbar(runs({ hidden: 0 }), { routines: true })
expect(screen.getByLabelText('Show routine runs').getAttribute('aria-checked')).toBe('true')
expect(screen.getByText('Routine runs')).toBeTruthy()
})
})
describe('Home switch preferences', () => {
it('remembers Running, Archived and Routine runs per account', () => {
const store = new Map<string, string>()
const storage: Storage = {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, v),
removeItem: (k: string) => void store.delete(k),
clear: () => store.clear(),
key: () => null,
get length() {
return store.size
}
}
const off = { running: false, archived: false, routines: false }
expect(readHomeSwitches('u1:org', storage)).toEqual(off)
writeHomeSwitches('u1:org', { routines: true }, storage)
writeHomeSwitches('u1:org', { running: true }, storage)
expect(readHomeSwitches('u1:org', storage)).toEqual({
running: true,
archived: false,
routines: true
})
expect(readHomeSwitches('u2:org', storage)).toEqual(off)
writeHomeSwitches('u1:org', { running: false, routines: false }, storage)
expect(readHomeSwitches('u1:org', storage)).toEqual(off)
store.set('orca.cloudWorkspacesHome.switches', 'not json')
expect(readHomeSwitches('u1:org', storage)).toEqual(off)
})
})
@@ -15,6 +15,7 @@ import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
import { repoLabel, type MemberDirectory } from './cloud-workspace-format'
import type { CloudWorkspaceRoutineRuns } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { OrcaCloudTrialUsedUpBanner } from '../new-workspace/run-on/OrcaCloudTrialUsedUpNotice'
export const ANY = '__any'
@@ -32,6 +33,8 @@ export type CloudWorkspacesFilters = {
archived: boolean
/** Only sandboxes that are running now (where the team's running slots go). */
running?: boolean
/** Also list workspaces routine runs started (hidden by default, like Conductor). */
routines?: boolean
}
export const INITIAL_CLOUD_WORKSPACE_FILTERS: CloudWorkspacesFilters = {
@@ -39,10 +42,11 @@ export const INITIAL_CLOUD_WORKSPACE_FILTERS: CloudWorkspacesFilters = {
by: ANY,
repo: ANY,
archived: false,
running: false
running: false,
routines: false
}
/** Row 1: title, count and cost, refresh. Row 2: whose, by whom, which repo, archived. */
/** Row 1: title, count and cost, refresh. Row 2: whose, by whom, which repo, running, routine runs, archived. */
export function CloudWorkspacesToolbar({
filters,
onFiltersChange,
@@ -54,7 +58,8 @@ export function CloudWorkspacesToolbar({
meta,
metaStale,
reading,
onRefresh
onRefresh,
routineRuns
}: {
filters: CloudWorkspacesFilters
onFiltersChange: (next: Partial<CloudWorkspacesFilters>) => void
@@ -68,6 +73,8 @@ export function CloudWorkspacesToolbar({
metaStale: boolean
reading: boolean
onRefresh: () => void
/** What the Routine runs switch hides; the switch exists only when the team has routines. */
routineRuns?: CloudWorkspaceRoutineRuns
}): React.JSX.Element {
const t = useTranslate()
// Routines start cloud workspaces on their own, so they sit next to the list they fill.
@@ -175,22 +182,51 @@ export function CloudWorkspacesToolbar({
))}
</SelectContent>
</Select>
<label className="ml-auto flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.running === true}
onCheckedChange={(running) => onFiltersChange({ running })}
aria-label={t('auto.components.cloudWorkspaces.showRunningOnly', 'Show running only')}
/>
{t('auto.components.cloudWorkspaces.running', 'Running')}
</label>
<label className="flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.archived}
onCheckedChange={(archived) => onFiltersChange({ archived })}
aria-label={t('auto.components.cloudWorkspaces.showArchived', 'Show archived')}
/>
{t('auto.components.cloudWorkspaces.archived', 'Archived')}
</label>
{/* The switches wrap as one group, so none is left alone on a line of its own. */}
<div className="ml-auto flex items-center gap-2">
<label className="flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.running === true}
onCheckedChange={(running) => onFiltersChange({ running })}
aria-label={t('auto.components.cloudWorkspaces.showRunningOnly', 'Show running only')}
/>
{t('auto.components.cloudWorkspaces.running', 'Running')}
</label>
{(routineRuns?.routines ?? 0) > 0 || filters.routines === true ? (
<label className="flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.routines === true}
onCheckedChange={(routines) => onFiltersChange({ routines })}
aria-label={t(
'auto.components.cloudWorkspaces.showRoutineRuns',
'Show routine runs'
)}
/>
{/* Hidden runs that are running still use hours: say how many, so the total adds up. */}
{filters.routines !== true && (routineRuns?.hiddenRunning ?? 0) > 0 ? (
<span className="tabular-nums">
{t(
'auto.components.cloudWorkspaces.routineRunsHidden',
'Routine runs · {{count}}',
{
count: routineRuns!.hiddenRunning
}
)}
</span>
) : (
t('auto.components.cloudWorkspaces.routineRuns', 'Routine runs')
)}
</label>
) : null}
<label className="flex h-7 cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">
<Switch
checked={filters.archived}
onCheckedChange={(archived) => onFiltersChange({ archived })}
aria-label={t('auto.components.cloudWorkspaces.showArchived', 'Show archived')}
/>
{t('auto.components.cloudWorkspaces.archived', 'Archived')}
</label>
</div>
</div>
{/* T4: the team's trial ran out; running sandboxes sleep until a plan starts. */}
<OrcaCloudTrialUsedUpBanner />
@@ -0,0 +1,60 @@
// Home's three list switches (Running, Archived, Routine runs) are remembered per signed-in account
// (user and team) on this desktop. Preferences only: they never decide access, so local storage is enough.
const KEY = 'orca.cloudWorkspacesHome.switches'
export type HomeSwitches = { running: boolean; archived: boolean; routines: boolean }
const OFF: HomeSwitches = { running: false, archived: false, routines: false }
function read(storage: Storage | undefined): Record<string, Partial<HomeSwitches>> {
try {
const parsed: unknown = JSON.parse(storage?.getItem(KEY) ?? '{}')
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return {}
}
const out: Record<string, Partial<HomeSwitches>> = {}
for (const [account, saved] of Object.entries(parsed)) {
if (saved && typeof saved === 'object') {
const flags: Record<string, unknown> = { ...saved }
out[account] = {
running: flags.running === true,
archived: flags.archived === true,
routines: flags.routines === true
}
}
}
return out
} catch {
return {}
}
}
export function readHomeSwitches(
account: string,
storage: Storage | undefined = globalThis.localStorage
): HomeSwitches {
const saved = read(storage)[account] ?? {}
return {
running: saved.running === true,
archived: saved.archived === true,
routines: saved.routines === true
}
}
export function writeHomeSwitches(
account: string,
next: Partial<HomeSwitches>,
storage: Storage | undefined = globalThis.localStorage
): void {
const all = read(storage)
const merged = { ...OFF, ...readHomeSwitches(account, storage), ...next }
if (!merged.running && !merged.archived && !merged.routines) {
delete all[account]
} else {
all[account] = merged
}
try {
storage?.setItem(KEY, JSON.stringify(all))
} catch {
// Storage full or unavailable: the switches still work for this session.
}
}
@@ -0,0 +1,46 @@
import { useCallback, useState } from 'react'
import {
ANY,
INITIAL_CLOUD_WORKSPACE_FILTERS,
type CloudWorkspacesFilters
} from './CloudWorkspacesToolbar'
import { readHomeSwitches, writeHomeSwitches } from './cloud-workspaces-home-prefs'
import { usePendingHomeFilters } from './cloud-workspaces-home-nav'
/** Home's list filters for this account. The three switches are remembered; owner/repo/scope start fresh. */
export function useCloudHomeFilters(account: string) {
const initialFilters = (key: string): CloudWorkspacesFilters => ({
...INITIAL_CLOUD_WORKSPACE_FILTERS,
...readHomeSwitches(key)
})
const [filters, setFilters] = useState(() => initialFilters(account))
usePendingHomeFilters(setFilters)
// Owner and repo filters name the previous team's people and repos; a team switch starts over.
const [filtersAccount, setFiltersAccount] = useState(account)
if (filtersAccount !== account) {
setFiltersAccount(account)
setFilters(initialFilters(account))
}
const changeFilters = useCallback(
(next: Partial<CloudWorkspacesFilters>) => {
const switches = {
...(next.running !== undefined ? { running: next.running } : {}),
...(next.archived !== undefined ? { archived: next.archived } : {}),
...(next.routines !== undefined ? { routines: next.routines } : {})
}
if (Object.keys(switches).length > 0) {
writeHomeSwitches(account, switches)
}
setFilters((previous) => {
// A different list (scope or archived) has different owners and repos; start unfiltered.
// Routine runs only add rows, so the owner/repo picks stay.
const reset =
(next.scope !== undefined && next.scope !== previous.scope) ||
(next.archived !== undefined && next.archived !== previous.archived)
return { ...previous, ...(reset ? { by: ANY, repo: ANY } : {}), ...next }
})
},
[account]
)
return { filters, changeFilters }
}
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
import type {
CloudWorkspace,
CloudWorkspaceListQuery
CloudWorkspaceListQuery,
CloudWorkspaceRoutineRuns
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { availabilityRetryDelay } from '@/lib/availability-retry'
import { installWindowVisibilityTimeoutPoller } from '@/lib/window-visibility-timeout-poller'
@@ -13,7 +14,13 @@ export type CloudWorkspacesState =
| { status: 'loading' }
| { status: 'unavailable' }
| { status: 'error'; key: string; error: string; reason?: string }
| { status: 'ready'; key: string; workspaces: CloudWorkspace[] }
| {
status: 'ready'
key: string
workspaces: CloudWorkspace[]
/** What the Routine runs switch hides; absent from older control planes. */
routineRuns?: CloudWorkspaceRoutineRuns
}
// Whether this build talks to an Orca Cloud control plane at all (cached per session). The value
// is mirrored into a tiny store so surfaces can render nothing until it is known (no flash).
@@ -126,7 +133,7 @@ export function useCloudWorkspaces(
return
}
if (result.ok) {
setState({ status: 'ready', key, workspaces: result.value })
setState({ status: 'ready', key, workspaces: result.value, routineRuns: result.routineRuns })
} else if (result.error === 'not_configured') {
stopped = true
setAvailable(false)
@@ -37,7 +37,7 @@ export function getRemoteDesktopQuickAction(): CmdJQuickAction {
title: translate('components.cloudRemoteDesktop.openMenuItem', 'Open remote desktop'),
description: translate(
'components.cloudRemoteDesktop.paletteDescription',
'Open the sandbox’s desktop in a browser tab.'
'Open the sandbox’s desktop in a tab.'
),
icon: Monitor,
verbKeywords: [
@@ -2,8 +2,8 @@
// Later" hint: it says how the composer's agent will sign in, links to the one-time setup in
// Settings → Agent accounts, and never blocks Start or signs in per sandbox.
import { useEffect } from 'react'
import { openOrcaCloudSignInSheet } from '@/components/settings/agent-accounts/sign-in-sheet/orca-cloud-sign-in-sheet-store'
import { CircleCheck, CircleDashed, Info, TriangleAlert } from 'lucide-react'
import { useAppStore } from '@/store/index'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
@@ -19,11 +19,9 @@ import { noteComposerAgentCoverage } from '@/lib/orca-cloud/cloud-first-start-ag
import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access'
import { agentName, keySourceLabel } from '../settings/agent-accounts/orca-cloud-accounts-copy'
/** Settings → Agent accounts, scrolled to the Orca Cloud section (S0). The composer stays open. */
/** The focused Orca Cloud sign-in sheet (JA-04), over the composer, which stays open. */
export function openOrcaCloudAgentAccounts(): void {
useAppStore
.getState()
.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' })
openOrcaCloudSignInSheet()
}
export function orcaCloudAgentCoveredLabel(
@@ -40,4 +40,6 @@ export type ComposerModalData = {
setupGuideTourRequestId?: string
/** Orca Cloud setup finished on its page: submit without showing the dialog (falls back to it). */
cloudAutoStart?: boolean
/** The Create press's intent the auto-start may use, once (one press, one server create). */
cloudCreateIntent?: string
}
@@ -24,24 +24,25 @@ describe('Orca Cloud availability', () => {
describe('setup rows and the setup page', () => {
const page = (steps: Parameters<typeof cloudSetupPageModel>[0]) =>
cloudSetupPageModel(steps, { agentSkipped: true }).action
cloudSetupPageModel(steps).action
it('starts directly when the account is entitled', () => {
const steps = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'entitled', remainingSeconds: 3600 }
})
expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(false)
expect(cloudSetupRequired(steps)).toBe(false)
expect(page(steps)).toBe('done')
})
it('an agent with no account opens the page until it is skipped once', () => {
it('an agent with no account never opens the page (PC-1): the create starts at once', () => {
const steps = deriveCloudSetupSteps({
availability: 'offered',
access: { state: 'entitled', remainingSeconds: 3600 }
})
expect(cloudSetupRequired(steps)).toBe(true)
expect(cloudSetupPageModel(steps).action).toBe('agent')
expect(steps.find((s) => s.id === 'agent')?.state).toBe('optional')
expect(cloudSetupRequired(steps)).toBe(false)
expect(cloudSetupPageModel(steps).action).toBe('done')
})
it('signed out: sign-in first, plan checked after sign-in', () => {
@@ -148,7 +149,7 @@ describe('setup rows and the setup page', () => {
access: { state: 'entitled', remainingSeconds: 3600 },
github: { id: 'github', state: 'pending', need: 'github', blocksStart: true }
})
expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(true)
expect(cloudSetupRequired(steps)).toBe(true)
expect(page(steps)).toBe('github-waiting')
})
@@ -189,6 +190,7 @@ describe('setup rows and the setup page', () => {
{ id: 'agent', state: 'loading' }
]
expect(cloudSetupRequired(steps)).toBe(false)
expect(cloudSetupPageModel(steps).action).toBe('done')
})
})
@@ -37,37 +37,6 @@ export function getOrcaCloudHoursChip(
})
}
/** The start toast: "Using sandbox hours · 2 sandbox hours left in your trial". */
export function getOrcaCloudStartToast(
access: OrcaCloudRunTargetAccess,
t: Translate,
locale: string
): string | null {
if (access.state !== 'entitled') {
return null
}
const args = hoursArgs(access.remainingSeconds, locale)
return access.trial
? t(
'components.newWorkspace.cloudHours.trialToast',
'Using sandbox hours · {{hours}} sandbox hours left in your trial',
{
count: args.count,
hours: args.hours,
defaultValue_one: 'Using sandbox hours · {{hours}} sandbox hour left in your trial'
}
)
: t(
'components.newWorkspace.cloudHours.planToast',
'Using sandbox hours · {{hours}} sandbox hours left',
{
count: args.count,
hours: args.hours,
defaultValue_one: 'Using sandbox hours · {{hours}} sandbox hour left'
}
)
}
/** T1: under half an hour of trial left, the hint turns to a warning with the fix. */
export const ORCA_CLOUD_TRIAL_LOW_SECONDS = 30 * 60
@@ -2,7 +2,6 @@
// repositories with no clone here. Picking one keeps Orca Cloud and starts it from GitHub.
import { useCallback, useMemo, useState } from 'react'
import { useAppStore } from '@/store'
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { clearCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft'
import {
@@ -102,7 +101,6 @@ export function useCloudOnlyCreate({
prompt,
agent,
profileId,
hoursToast,
onClose
}: {
cloudOnly: CloudOnlyRepo
@@ -110,8 +108,6 @@ export function useCloudOnlyCreate({
prompt: string
agent: string | null
profileId: string | null
/** "Using sandbox hours · …", or null before billing answers. */
hoursToast: string | null
onClose?: () => void
}): () => void {
const { picked, start } = cloudOnly
@@ -121,12 +117,9 @@ export function useCloudOnlyCreate({
return
}
clearCloudStartDraft(profileId)
if (hoursToast) {
toast.message(hoursToast)
}
void start({ prompt, agent })
onClose?.()
}, [agent, createWorkspace, hoursToast, onClose, picked, profileId, prompt, start])
}, [agent, createWorkspace, onClose, picked, profileId, prompt, start])
}
/**
@@ -2,15 +2,18 @@
// dialog: Start either creates the workspace (everything is set up) or saves the draft, closes the
// dialog and opens the full-page setup, which starts the prompt by itself when done. Also: where
// each project last started (O5), the remembered default (D7) and GitHub-only repositories (D4).
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { toast } from 'sonner'
import { useCallback, useEffect, useMemo } from 'react'
import { useAppStore } from '@/store/index'
import { translate } from '@/i18n/i18n'
import { clearCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft'
import {
isCloudSetupAgentSkipped,
getCloudSetupPageRequest,
openCloudSetupPage
} from '@/lib/orca-cloud/cloud-setup-page-store'
import {
armCloudCreateIdempotency,
consumeCloudCreateIntent,
startCloudCreate
} from '@/lib/orca-cloud/cloud-create-intent'
import { recordSuccessfulRunOn } from '@/lib/orca-cloud/run-on-memory'
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types'
@@ -18,48 +21,22 @@ import { useOrcaCloudRunTargetAccess } from '../orca-cloud-billing-cache'
import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access'
import type { ComposerModalData } from '../composer-modal-data'
import { getOrcaCloudSegmentState } from './cloud-start-model'
import { getOrcaCloudStartToast } from './orca-cloud-hours-copy'
import { useCloudStartSteps } from './use-cloud-start-steps'
import { useSwitchTeamSteps } from '../cloud-setup/use-cloud-setup-tracker'
import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-model'
import { useRunOnDefault } from './use-run-on-default'
import { useCloudOnlyCreate, useCloudOnlyRepo } from './use-cloud-only-repo'
import type { CloudStartView } from './cloud-start-view'
import { openOrcaCloudAgentAccounts } from '../OrcaCloudAgentSetupRow'
import { agentName } from '../../settings/agent-accounts/orca-cloud-accounts-copy'
import { showCloudAgentNotStartedToast } from '@/lib/orca-cloud/cloud-agent-not-started-toast'
import { isOrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire'
export type { CloudStartView } from './cloud-start-view'
/** The workspace started without its agent: one clear way to set the agent up for next time. */
function showAgentNotStartedToast(agent: string | null): void {
const name = isOrcaCloudAccountAgent(agent) ? agentName(agent, translate) : null
toast.message(
name
? translate(
'components.newWorkspace.cloudStart.agentNotStarted',
'{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.',
{ agent: name }
)
: translate(
'components.newWorkspace.cloudStart.agentNotStartedGeneric',
'Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.'
),
{
action: {
label: name
? translate(
'components.newWorkspace.cloudStart.setUpAgentOnce',
'Set up {{agent}} once',
{
agent: name
}
)
: translate('components.newWorkspace.cloudStart.setUpAgentOnceGeneric', 'Set up once'),
onClick: openOrcaCloudAgentAccounts
}
}
)
/** The workspace started without its agent: the one prompt to set it up (design-squad journey). */
function showAgentNotStartedToast(agent: string | null, workspaceName: string): void {
if (isOrcaCloudAccountAgent(agent)) {
showCloudAgentNotStartedToast(agent, workspaceName)
}
}
export function useCloudStartComposer({
@@ -71,7 +48,7 @@ export function useCloudStartComposer({
prompt,
agent,
initialTargetFixed,
autoStart = false,
autoStartIntent = null,
createReady = true,
composerSnapshot,
onCreate: createWorkspace,
@@ -88,8 +65,11 @@ export function useCloudStartComposer({
agent: string | null
/** The composer was opened on an explicit target (Landing card, a recovery). */
initialTargetFixed: boolean
/** Reopened by the setup page once everything is done: submit as soon as the form is ready. */
autoStart?: boolean
/**
* Reopened by the setup page once everything is done: the Create press's intent, submitted once
* the form is ready (and only if nothing has used it yet).
*/
autoStartIntent?: string | null
/** The composer's own create would run now (project picked, agent resolved). */
createReady?: boolean
/** The composer as it is now, for the setup page's Back and its auto-start. */
@@ -129,10 +109,7 @@ export function useCloudStartComposer({
githubOverride: cloudOnly.githubStep
})
const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected)
const setupNeeded = cloudSetupRequired(steps, {
teamSwitch: switchTeam !== null,
agentSkipped: isCloudSetupAgentSkipped(agent)
})
const setupNeeded = cloudSetupRequired(steps, { teamSwitch: switchTeam !== null })
// The agent has no Orca Cloud account (the user skipped setting it up): never launch it into its
// /login. Start a plain terminal and say how to set the agent up once.
const agentUnset =
@@ -143,7 +120,6 @@ export function useCloudStartComposer({
prompt,
agent: agentUnset ? null : agent,
profileId,
hoursToast: getOrcaCloudStartToast(access, translate, navigator.language),
onClose
})
const onCreate = useCallback(() => {
@@ -157,8 +133,8 @@ export function useCloudStartComposer({
} else {
onCreateWithoutAgent()
}
showAgentNotStartedToast(agent)
}, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent])
showAgentNotStartedToast(agent, prompt)
}, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent, prompt])
const { markTouched } = useRunOnDefault({
active,
@@ -176,40 +152,54 @@ export function useCloudStartComposer({
}, [markTouched, setRecipeId])
// Start with setup still open: the dialog closes and the page takes over, prompt kept (N6).
const openSetup = useCallback(() => {
saveCloudStartDraft(profileId, {
prompt,
repoId,
agent,
target: 'orca-cloud',
setupSessionId: null,
createdAt: Date.now()
})
openCloudSetupPage({
prompt,
repoId,
agent,
availability,
cloudOnlyRepo: cloudOnly.picked?.fullName ?? null,
composer: composerSnapshot()
})
onClose?.()
}, [agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId])
const openSetup = useCallback(
(intentId: string) => {
saveCloudStartDraft(profileId, {
prompt,
repoId,
agent,
target: 'orca-cloud',
setupSessionId: null,
createdAt: Date.now()
})
openCloudSetupPage({
prompt,
repoId,
agent,
availability,
cloudOnlyRepo: cloudOnly.picked?.fullName ?? null,
composer: composerSnapshot(),
intentId
})
onClose?.()
},
[agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId]
)
// Reopened by the setup page: submit once the account and form are ready. Anything still open
// (a race, a revoked grant) leaves the composer for the user, never a second trip on its own.
const autoStartedRef = useRef(false)
// One Create press is one server create (P0): the intent is consumed here or nowhere.
const stepsSettled = !steps.some((step) => step.state === 'loading' && step.id !== 'agent')
useEffect(() => {
if (!autoStart || autoStartedRef.current || !cloudSelected || !createReady || !stepsSettled) {
if (!autoStartIntent || !cloudSelected || !createReady || !stepsSettled || setupNeeded) {
return
}
if (setupNeeded) {
return
if (consumeCloudCreateIntent(autoStartIntent)) {
armCloudCreateIdempotency(autoStartIntent)
onCreate()
}
autoStartedRef.current = true
onCreate()
}, [autoStart, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled])
}, [autoStartIntent, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled])
const onCloudPrimary = useCallback(
() =>
startCloudCreate({
setupOpen: getCloudSetupPageRequest() !== null,
setupNeeded,
openSetup,
create: () => onCreate()
}),
[onCreate, openSetup, setupNeeded]
)
const recordCreated = useCallback(() => {
if (!repoId) {
@@ -220,12 +210,8 @@ export function useCloudStartComposer({
return
}
clearCloudStartDraft(profileId)
// O4: the start always says which hours it spends.
const message = getOrcaCloudStartToast(access, translate, navigator.language)
if (message) {
toast.message(message)
}
}, [access, cloudSelected, profileId, repoId])
// PC-5: no "Using sandbox hours" toast on start; hours live in billing (Neil: noise).
}, [cloudSelected, profileId, repoId])
const view = useMemo<CloudStartView | null>(
() =>
@@ -242,5 +228,5 @@ export function useCloudStartComposer({
if (!view || !cloudSelected) {
return { view, onPrimary: null, recordCreated }
}
return { view, onPrimary: setupNeeded ? openSetup : onCreate, recordCreated }
return { view, onPrimary: onCloudPrimary, recordCreated }
}
@@ -66,7 +66,7 @@ export function useComposerCloudStart({
initialTargetFixed: Boolean(
modalData.initialEphemeralVmRecipeId || modalData.initialWorkspaceTarget || modalData.recovery
),
autoStart: modalData.cloudAutoStart === true,
autoStartIntent: modalData.cloudAutoStart ? (modalData.cloudCreateIntent ?? null) : null,
createReady: !createDisabled,
composerSnapshot,
onCreate: runCreate,
@@ -3,24 +3,28 @@
// steps are ticks in the stepper. Browser hops only for sign-in, Stripe and GitHub. When every
// step is done, the saved prompt starts by itself.
import React from 'react'
import { ArrowLeft, Check, Cloud, Copy, ExternalLink, LoaderCircle } from 'lucide-react'
import { ArrowLeft, Check, Copy, ExternalLink, LoaderCircle, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { cn } from '@/lib/utils'
import { useTranslate } from '@/i18n/use-translate'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
import type {
CloudSetupStep,
CloudSetupStepId
} from '@/components/new-workspace/run-on/cloud-start-model'
import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice'
import { currentStepCopy, stepLabel } from './cloud-setup-page-copy'
import { currentStepCopy, doneStepCopy, stepLabel, type StepCopy } from './cloud-setup-page-copy'
import type { CloudSetupFlow } from './use-cloud-setup-flow'
import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow'
export type CloudSetupPageProps = {
flow: CloudSetupFlow
projectName: string | null
prompt: string
agentLabel: string | null
/** Back to the composer with the prompt, project and agent as they were. */
onBack: () => void
/** Back from the first step: Create workspace again, with the prompt, project and agent kept. */
onBackToComposer: () => void
/** The × in the corner: leave setup, keep the draft (nothing starts). */
onExit: () => void
/** "All set": shown for a moment before the workspace starts. */
starting: boolean
}
@@ -30,11 +34,17 @@ type StepState = 'done' | 'current' | 'todo'
function SetupStepper({
steps,
current,
allDone
viewing,
allDone,
onView
}: {
steps: readonly CloudSetupStep[]
current: CloudSetupStep | null
/** A finished step being revisited. */
viewing: CloudSetupStepId | null
allDone: boolean
/** Revisit a finished step; null returns to the current one. */
onView: (id: CloudSetupStepId | null) => void
}): React.JSX.Element {
const t = useTranslate()
const currentIndex = current ? steps.findIndex((step) => step.id === current.id) : steps.length
@@ -47,9 +57,9 @@ function SetupStepper({
const state: StepState =
allDone || index < currentIndex ? 'done' : index === currentIndex ? 'current' : 'todo'
const label = stepLabel(step, t)
return (
<li key={step.id} className="flex items-center gap-2" data-setup-page-step={step.id}>
{index > 0 ? <span aria-hidden className="h-px w-6 bg-border" /> : null}
const shownHere = viewing ? viewing === step.id : state === 'current'
const mark = (
<>
<span
aria-hidden
className={cn(
@@ -67,7 +77,7 @@ function SetupStepper({
<span
className={cn(
'text-xs',
state === 'current' ? 'font-medium text-foreground' : 'text-muted-foreground'
shownHere ? 'font-medium text-foreground' : 'text-muted-foreground'
)}
>
{label}
@@ -79,6 +89,31 @@ function SetupStepper({
: ''}
</span>
</span>
</>
)
// Finished steps (and the current one, to come back to it) open; future ones don't.
const clickable =
!allDone && (state === 'done' || (state === 'current' && viewing !== null))
return (
<li key={step.id} className="flex items-center gap-2" data-setup-page-step={step.id}>
{index > 0 ? <span aria-hidden className="h-px w-6 bg-border" /> : null}
{clickable ? (
<button
type="button"
aria-current={shownHere ? 'step' : undefined}
onClick={() => onView(state === 'current' ? null : step.id)}
className="flex items-center gap-2 rounded-sm outline-none focus-visible:ring-1 focus-visible:ring-focus-ring"
>
{mark}
</button>
) : (
<span
className="flex items-center gap-2"
aria-current={shownHere ? 'step' : undefined}
>
{mark}
</span>
)}
</li>
)
})}
@@ -167,20 +202,6 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu
)
case 'switch-team':
return <div>{flow.teamAction}</div>
case 'agent':
return (
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
onClick={flow.current?.action?.onClick ?? openOrcaCloudAgentAccounts}
>
{flow.current?.action?.label ?? t('cloudSetupPage.agent.setUp', 'Set up once')}
</Button>
<Button type="button" variant="ghost" onClick={flow.skipAgent}>
{t('cloudSetupPage.agent.skip', 'Skip for now')}
</Button>
</div>
)
case 'needs-repository':
return flow.current?.action ? (
<Button type="button" variant="outline" onClick={flow.current.action.onClick}>
@@ -213,59 +234,120 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu
}
}
function StepBody({ copy, checking }: { copy: StepCopy; checking: boolean }): React.JSX.Element {
return (
<>
{checking ? (
<Skeleton className="h-4 w-72" />
) : copy.lead ? (
<p className="text-sm leading-relaxed text-muted-foreground">{copy.lead}</p>
) : null}
{copy.aside ? <p className="text-sm italic text-muted-foreground">{copy.aside}</p> : null}
{copy.note ? <p className="text-xs text-muted-foreground">{copy.note}</p> : null}
</>
)
}
export function CloudSetupPage({
flow,
projectName,
prompt,
agentLabel,
onBack,
onBackToComposer,
onExit,
starting
}: CloudSetupPageProps): React.JSX.Element {
const t = useTranslate()
const titleId = React.useId()
const headingRef = React.useRef<HTMLHeadingElement>(null)
// A finished step opened from the stepper or Back; null shows the current step.
const [viewing, setViewing] = React.useState<CloudSetupStepId | null>(null)
// Every row reads done but hasn't held yet: still "Checking" until the layer says it's starting.
const shown: CloudSetupFlow = starting
? { ...flow, action: 'done' }
: flow.action === 'done'
? { ...flow, action: 'checking' }
: flow
const copy = currentStepCopy(shown, t, agentLabel)
const viewed = viewing && !starting ? flow.steps.find((step) => step.id === viewing) : undefined
const copy: StepCopy = viewed ? doneStepCopy(viewed, t, agentLabel) : currentStepCopy(shown, t)
// Back walks to the previous step; from the first it returns to Create workspace.
const back = (): void => {
const steps = flow.steps
const from = viewing
? steps.findIndex((step) => step.id === viewing)
: flow.current
? steps.findIndex((step) => step.id === flow.current?.id)
: steps.length
const previous = from > 0 ? steps[from - 1] : undefined
if (previous && !starting) {
setViewing(previous.id)
return
}
// Leaving setup cancels a sign-in this page started (it must not finish behind the user).
flow.abandon()
onBackToComposer()
}
const exit = (): void => {
flow.abandon()
onExit()
}
// Each new step moves focus to its heading so screen readers hear the change once.
const stepKey = `${shown.current?.id ?? 'done'}:${shown.action}`
const stepKey = `${viewing ?? shown.current?.id ?? 'done'}:${shown.action}`
React.useEffect(() => {
headingRef.current?.focus({ preventScroll: true })
}, [stepKey])
const context = [
prompt.trim()
? t('cloudSetupPage.headerFor', 'Setting up Orca Cloud for {{name}}', { name: prompt.trim() })
: t('cloudSetupPage.header', 'Setting up Orca Cloud'),
projectName,
agentLabel
]
.filter(Boolean)
.join(' · ')
return (
<section
aria-labelledby={titleId}
data-cloud-setup-page="true"
className="flex h-full min-h-0 w-full flex-col overflow-y-auto bg-background scrollbar-sleek"
>
<div className="mx-auto flex w-full max-w-xl flex-1 flex-col px-8 pb-12 pt-10">
<div className="flex items-center justify-between gap-3">
<Button
type="button"
variant="ghost"
size="sm"
className="-ms-2"
onClick={() => {
flow.abandon()
onBack()
}}
>
<ArrowLeft aria-hidden />
{t('cloudSetupPage.back', 'Back')}
</Button>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Cloud className="size-3.5" aria-hidden />
{t('cloudSetupPage.eyebrow', 'Orca Cloud setup')}
</span>
</div>
<div className="flex shrink-0 items-center gap-3 px-6 pt-5">
<Button type="button" variant="ghost" size="sm" className="-ms-2" onClick={back}>
<ArrowLeft aria-hidden />
{t('cloudSetupPage.back', 'Back')}
</Button>
<span
className="min-w-0 flex-1 truncate text-center text-xs text-muted-foreground"
data-cloud-setup-context="true"
>
{context}
</span>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label={t('cloudSetupPage.exit', 'Exit setup')}
title={t('cloudSetupPage.exit', 'Exit setup')}
onClick={exit}
>
<X aria-hidden />
</Button>
</div>
<div className="mt-8">
<SetupStepper steps={flow.steps} current={flow.current} allDone={starting} />
</div>
{/* The same optically-centred top offset on every step, so nothing jumps between them. */}
<div className="mx-auto w-full max-w-xl px-8 pb-12 pt-[max(2rem,calc(22vh-3.5rem))]">
<SetupStepper
steps={flow.steps}
current={flow.current}
viewing={viewing}
allDone={starting}
onView={setViewing}
/>
<div className="mt-8 space-y-3">
<h1
@@ -276,15 +358,10 @@ export function CloudSetupPage({
>
{copy.title}
</h1>
{shown.action === 'checking' ? (
<Skeleton className="h-4 w-72" />
) : copy.lead ? (
<p className="text-sm leading-relaxed text-muted-foreground">{copy.lead}</p>
) : null}
{copy.note ? <p className="text-xs text-muted-foreground">{copy.note}</p> : null}
<StepBody copy={copy} checking={!viewed && shown.action === 'checking'} />
</div>
{flow.error && !starting ? (
{flow.error && !starting && !viewed ? (
<CloudSetupErrorNotice
error={flow.error}
canManageBilling={flow.canManageBilling}
@@ -295,24 +372,14 @@ export function CloudSetupPage({
/>
) : null}
<div className="mt-6">
<StepActions flow={shown} />
</div>
<div className="mt-12">
<div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
<div className="text-xs font-medium text-muted-foreground">
{t('cloudSetupPage.startsAfter', 'Starts when setup is done')}
</div>
<div className="mt-1 truncate text-sm text-foreground">
{prompt.trim() || t('cloudSetupPage.untitled', 'New cloud workspace')}
</div>
<div className="mt-0.5 truncate text-xs text-muted-foreground">
{[projectName, agentLabel, t('cloudSetupPage.orcaCloud', 'Orca Cloud')]
.filter(Boolean)
.join(' · ')}
</div>
</div>
<div className="mt-6 flex justify-end">
{viewed ? (
<Button type="button" onClick={() => setViewing(null)}>
{t('cloudSetupPage.continue', 'Continue')}
</Button>
) : (
<StepActions flow={shown} />
)}
</div>
</div>
</section>
@@ -4,6 +4,10 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { clearCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft'
import { cancelCloudCreateIntent } from '@/lib/orca-cloud/cloud-create-intent'
import {
closeCloudSetupPage,
useCloudSetupPageRequest,
@@ -15,19 +19,59 @@ import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-clo
import { agentName } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy'
import { prefersReducedMotion } from '@/components/new-workspace/run-on/cloud-start-view'
import { CloudSetupPage } from './CloudSetupPage'
import { closeSetupPageWhenCreateTakesOver } from './cloud-setup-handoff'
import { useCloudSetupFlow } from './use-cloud-setup-flow'
/** How long every row must read done before the page starts the workspace. */
const SETTLE_MS = 1_500
function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void {
/**
* The × leaves setup. Nothing starts later (JA-01): the page and its auto-start go away, and the
* on-disk draft is dropped. The draft stays one click away in a toast, as a filled composer.
*/
function exitSetup(request: CloudSetupPageRequest): void {
cancelCloudCreateIntent(request.intentId)
closeCloudSetupPage()
clearCloudStartDraft(useAppStore.getState().activeOrcaProfileId ?? null)
toast.message(
translate('cloudSetupPage.exited', 'Orca Cloud setup closed. Your draft is kept.'),
{
action: {
label: translate('cloudSetupPage.resumeDraft', 'Open draft'),
onClick: () => reopenComposer(request, false)
}
}
)
}
function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void {
// A GitHub-only repository can't be preselected; the composer opens for one more Start.
const hiddenStart = autoStart && !request.cloudOnlyRepo
if (!hiddenStart) {
// Back, or a start that needs one more press: this setup's intent can never create.
cancelCloudCreateIntent(request.intentId)
closeCloudSetupPage()
clearCloudStartDraft(useAppStore.getState().activeOrcaProfileId ?? null)
} else {
// Warm the start screen's chunk so it is ready the frame the create takes over.
void import('@/components/worktree-creation/WorktreeCreationPanel').catch(() => undefined)
}
useAppStore.getState().openModal('new-workspace-composer', {
...request.composer,
initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID,
// A GitHub-only repository can't be preselected; the composer opens for one more Start.
...(autoStart && !request.cloudOnlyRepo ? { cloudAutoStart: true } : {})
...(hiddenStart ? { cloudAutoStart: true, cloudCreateIntent: request.intentId } : {})
})
if (hiddenStart) {
// The page stays up until the start screen has painted: nothing under it may flash.
closeSetupPageWhenCreateTakesOver({
getState: () => useAppStore.getState(),
subscribe: (listener) => useAppStore.subscribe(listener),
startScreenShown: () => document.querySelector('[data-vm-build-sheet]') !== null,
closePage: closeCloudSetupPage,
setTimer: (callback, ms) => window.setTimeout(callback, ms),
clearTimer: (handle) => window.clearTimeout(handle)
})
}
}
function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): React.JSX.Element {
@@ -58,14 +102,16 @@ function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }):
)
return () => window.clearTimeout(timer)
}, [request, starting])
const onBack = useCallback(() => reopenComposer(request, false), [request])
const onBackToComposer = useCallback(() => reopenComposer(request, false), [request])
const onExit = useCallback(() => exitSetup(request), [request])
return (
<CloudSetupPage
flow={flow}
projectName={projectName}
prompt={request.prompt}
agentLabel={agentLabel}
onBack={onBack}
onBackToComposer={onBackToComposer}
onExit={onExit}
starting={starting}
/>
)
@@ -86,6 +132,7 @@ export function CloudSetupPageLayer(): React.JSX.Element | null {
return
}
if (openedOnRef.current !== activeWorktreeId) {
cancelCloudCreateIntent(request.intentId)
closeCloudSetupPage()
}
}, [activeWorktreeId, request])
@@ -0,0 +1,88 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
closeSetupPageWhenCreateTakesOver,
SETUP_HANDOFF_MAX_MS,
SETUP_HANDOFF_PAINT_MAX_MS
} from './cloud-setup-handoff'
function harness(initial: { activePendingCreationId: string | null; activeModal: string }) {
let state = { ...initial }
let painted = false
const listeners = new Set<(s: typeof state) => void>()
const closePage = vi.fn()
const set = (patch: Partial<typeof state>): void => {
state = { ...state, ...patch }
for (const listener of listeners) {
listener(state)
}
}
const cancel = closeSetupPageWhenCreateTakesOver({
getState: () => state,
subscribe: (listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
startScreenShown: () => painted,
closePage,
setTimer: (callback, ms) => setTimeout(callback, ms),
clearTimer: (handle) => clearTimeout(handle)
})
return { set, paint: () => (painted = true), closePage, cancel, listeners }
}
afterEach(() => {
vi.useRealTimers()
})
describe('closeSetupPageWhenCreateTakesOver', () => {
it('keeps the setup page up until the start screen has painted', () => {
vi.useFakeTimers()
const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' })
// The hidden composer is still filling in: the page must cover the workspace underneath.
vi.advanceTimersByTime(3_000)
expect(h.closePage).not.toHaveBeenCalled()
// Submit publishes the pending create and closes the composer in one go.
h.set({ activePendingCreationId: 'c1', activeModal: 'none' })
// Its start screen's chunk hasn't rendered yet: still covered, never a bare frame.
vi.advanceTimersByTime(200)
expect(h.closePage).not.toHaveBeenCalled()
h.paint()
vi.advanceTimersByTime(20)
expect(h.closePage).toHaveBeenCalledOnce()
expect(h.listeners.size).toBe(0)
})
it('does not give up on a create published a tick after the composer closed', () => {
vi.useFakeTimers()
const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' })
h.set({ activeModal: 'none' })
h.set({ activePendingCreationId: 'c1' })
vi.advanceTimersByTime(100)
expect(h.closePage).not.toHaveBeenCalled()
h.paint()
vi.advanceTimersByTime(20)
expect(h.closePage).toHaveBeenCalledOnce()
})
it('closes when the composer goes away without a create', () => {
vi.useFakeTimers()
const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' })
h.set({ activeModal: 'none' })
vi.advanceTimersByTime(1)
expect(h.closePage).toHaveBeenCalledOnce()
})
it('ignores an older active create, and never covers longer than its caps', () => {
vi.useFakeTimers()
const h = harness({ activePendingCreationId: 'old', activeModal: 'new-workspace-composer' })
h.set({ activePendingCreationId: 'old' })
expect(h.closePage).not.toHaveBeenCalled()
vi.advanceTimersByTime(SETUP_HANDOFF_MAX_MS)
expect(h.closePage).toHaveBeenCalledOnce()
const unpainted = harness({ activePendingCreationId: null, activeModal: 'none' })
unpainted.set({ activePendingCreationId: 'c2' })
vi.advanceTimersByTime(SETUP_HANDOFF_PAINT_MAX_MS + 20)
expect(unpainted.closePage).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,94 @@
// The setup page hands the screen to the start screen. It used to close first and then let the
// hidden composer auto-start, so for a few frames the workspace underneath (a terminal) showed
// before "Starting your cloud workspace" did (Neil, build ff845fe). Now the page stays up until the
// create's start screen has actually painted, or the composer goes away without a create.
type HandoffState = { activePendingCreationId: string | null; activeModal: string }
export type HandoffDeps<Timer> = {
getState: () => HandoffState
subscribe: (listener: (state: HandoffState) => void) => () => void
/** True once the start screen is in the DOM (its lazy chunk may land a few frames later). */
startScreenShown: () => boolean
closePage: () => void
setTimer: (callback: () => void, ms: number) => Timer
clearTimer: (handle: Timer) => void
}
/** The hidden composer reveals itself after 8 s; past that the dialog sits over the page anyway. */
export const SETUP_HANDOFF_MAX_MS = 10_000
/** How long to wait for the start screen to paint once its create is active. */
export const SETUP_HANDOFF_PAINT_MAX_MS = 2_000
const PAINT_POLL_MS = 16
const COMPOSER_MODAL = 'new-workspace-composer'
/** Call right after opening the auto-starting composer. Returns a cancel. */
export function closeSetupPageWhenCreateTakesOver<Timer>(deps: HandoffDeps<Timer>): () => void {
const before = deps.getState().activePendingCreationId
let done = false
const timers = new Set<Timer>()
const later = (callback: () => void, ms: number): void => {
const handle = deps.setTimer(() => {
timers.delete(handle)
callback()
}, ms)
timers.add(handle)
}
const stop = (): void => {
done = true
unsubscribe()
for (const handle of timers) {
deps.clearTimer(handle)
}
timers.clear()
}
const finish = (): void => {
if (!done) {
stop()
deps.closePage()
}
}
let waitingForPaint = false
// The create is active: keep covering until its start screen is on screen (or give up).
const awaitPaint = (): void => {
if (waitingForPaint) {
return
}
waitingForPaint = true
const startedAt = Date.now()
const poll = (): void => {
if (deps.startScreenShown() || Date.now() - startedAt >= SETUP_HANDOFF_PAINT_MAX_MS) {
finish()
return
}
later(poll, PAINT_POLL_MS)
}
poll()
}
let closeGraceArmed = false
const check = (state: HandoffState): void => {
if (done) {
return
}
if (state.activePendingCreationId !== null && state.activePendingCreationId !== before) {
awaitPaint()
return
}
// Closed with no create yet: the submit may publish its pending entry in the same tick.
if (state.activeModal !== COMPOSER_MODAL && !closeGraceArmed && !waitingForPaint) {
closeGraceArmed = true
later(() => {
if (!waitingForPaint) {
finish()
}
}, 0)
}
}
const unsubscribe = deps.subscribe(check)
later(finish, SETUP_HANDOFF_MAX_MS)
return () => {
if (!done) {
stop()
}
}
}
@@ -22,7 +22,13 @@ export function stepLabel(step: CloudSetupStep, t: Translate): string {
}
}
type StepCopy = { title: string; lead: string | null; note?: string | null }
export type StepCopy = {
title: string
lead: string | null
note?: string | null
/** A gentle option under the lead, set apart in muted italics (the agent step's skip hint). */
aside?: string | null
}
function trialHours(step: CloudSetupStep): string | null {
return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null
@@ -30,8 +36,7 @@ function trialHours(step: CloudSetupStep): string | null {
export function currentStepCopy(
flow: Pick<CloudSetupPageModel, 'current' | 'action'>,
t: Translate,
agentLabel: string | null
t: Translate
): StepCopy {
const step = flow.current
const detail = step
@@ -146,16 +151,6 @@ export function currentStepCopy(
'Orca Cloud needs a Team plan. Only owners and admins can choose one.'
)
}
case 'agent':
return {
title: agentLabel
? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel })
: t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'),
lead: t(
'cloudSetupPage.agent.lead',
'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.'
)
}
case 'checking':
return {
title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'),
@@ -168,3 +163,45 @@ export function currentStepCopy(
}
}
}
/** A finished step revisited from the stepper or Back: what it settled, in one calm line. */
export function doneStepCopy(
step: CloudSetupStep,
t: Translate,
agentLabel: string | null
): StepCopy {
switch (step.id) {
case 'account':
return {
title: t('cloudSetupPage.done.accountTitle', 'You’re signed in'),
lead: t('cloudSetupPage.done.accountLead', 'Your Orca account is ready for Orca Cloud.')
}
case 'team':
return {
title: t('cloudSetupPage.done.teamTitle', 'Team selected'),
lead: step.detail ?? null
}
case 'plan':
return {
title:
step.detail === 'trial' || step.need === 'trial'
? t('cloudSetupPage.done.trialTitle', 'Your trial is on')
: t('cloudSetupPage.done.planTitle', 'Your team has Orca Cloud'),
lead: null
}
case 'github':
return {
title: t('cloudSetupPage.done.githubTitle', 'Orca Cloud can reach this repository'),
lead: null
}
case 'agent':
return {
title: agentLabel
? t('cloudSetupPage.done.agentTitle', '{{agent}} is set up for Orca Cloud', {
agent: agentLabel
})
: t('cloudSetupPage.done.agentTitleGeneric', 'Your agent is set up for Orca Cloud'),
lead: null
}
}
}
@@ -16,17 +16,15 @@ describe('cloudSetupPageModel', () => {
expect(sessionNeedsFrom(steps)).toEqual(['plan', 'github'])
})
it('a skipped agent finishes setup', () => {
it('the agent is never a page step and never holds the start (PC-1)', () => {
const steps: CloudSetupStep[] = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'done' },
{ id: 'agent', state: 'optional' }
]
expect(cloudSetupPageModel(steps).action).toBe('agent')
expect(cloudSetupPageModel(steps, { agentSkipped: true })).toMatchObject({
current: null,
action: 'done'
})
const model = cloudSetupPageModel(steps)
expect(model.steps.map((step) => step.id)).toEqual(['account', 'plan'])
expect(model).toMatchObject({ current: null, action: 'done' })
})
it('maps each blocker to its one action', () => {
@@ -41,14 +39,3 @@ describe('cloudSetupPageModel', () => {
expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking')
})
})
describe('page settles before it starts', () => {
it('a still-loading agent row reads Checking, not All set', () => {
const steps: CloudSetupStep[] = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'done' },
{ id: 'agent', state: 'loading' }
]
expect(cloudSetupPageModel(steps).action).toBe('checking')
})
})
@@ -22,8 +22,6 @@ export type CloudSetupPageAction =
| 'needs-repository'
/** A member can't fix billing; an owner or admin has to. */
| 'ask-owner'
/** Optional agent account: set it up once, or skip. */
| 'agent'
/** Still reading account, plan or repository state. */
| 'checking'
/** Every step is done: the prompt starts. */
@@ -35,17 +33,6 @@ export type CloudSetupPageModel = {
action: CloudSetupPageAction
}
function isFinished(step: CloudSetupStep, agentSkipped: boolean): boolean {
if (step.state === 'done') {
return true
}
if (step.id === 'agent') {
// Still loading reads "Checking": the page only says All set once every row has answered.
return agentSkipped && step.state !== 'loading'
}
return false
}
export function actionForStep(
step: CloudSetupStep,
{ teamSwitch = false }: { teamSwitch?: boolean } = {}
@@ -90,23 +77,23 @@ export function actionForStep(
}
return 'github-install'
case 'agent':
return 'agent'
// Never a page step (PC-1): agent sign-in is offered after create.
return 'done'
}
}
/**
* The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub,
* agent); the first unfinished one is current. A signed-out plan row is "pending" until sign-in, so
* account stays current until then.
* The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub); the
* first unfinished one is current. The agent row is never a step (PC-1): it never gates a start, and
* its sign-in is offered after create. A signed-out plan row is "pending" until sign-in, so account
* stays current until then.
*/
export function cloudSetupPageModel(
steps: readonly CloudSetupStep[],
{
agentSkipped = false,
teamSwitch = false
}: { agentSkipped?: boolean; teamSwitch?: boolean } = {}
rows: readonly CloudSetupStep[],
{ teamSwitch = false }: { teamSwitch?: boolean } = {}
): CloudSetupPageModel {
const current = steps.find((step) => !isFinished(step, agentSkipped)) ?? null
const steps = rows.filter((step) => step.id !== 'agent')
const current = steps.find((step) => step.state !== 'done') ?? null
if (!current) {
return { steps, current: null, action: 'done' }
}
@@ -121,23 +108,16 @@ export function sessionNeedsFrom(steps: readonly CloudSetupStep[]): CloudSetupSt
}
/**
* Pressing Start goes straight to create only when nothing is open. An agent without an account
* counts until the user skips it once; a still-loading agent row never holds a start.
* Pressing Start opens the setup page only when the account, team, plan or GitHub is missing. The
* agent never holds a start (PC-1): without an Orca Cloud account it starts as a plain terminal and
* the post-create prompt offers the sign-in.
*/
export function cloudSetupRequired(
steps: readonly CloudSetupStep[],
{
teamSwitch = false,
agentSkipped = false
}: { teamSwitch?: boolean; agentSkipped?: boolean } = {}
{ teamSwitch = false }: { teamSwitch?: boolean } = {}
): boolean {
if (teamSwitch) {
return true
}
return steps.some((step) => {
if (step.id === 'agent') {
return step.state === 'optional' && !agentSkipped
}
return step.state !== 'done'
})
return steps.some((step) => step.id !== 'agent' && step.state !== 'done')
}
@@ -21,11 +21,7 @@ import {
reopenCloudSetup
} from '@/components/new-workspace/cloud-setup/cloud-setup-tracker-actions'
import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam'
import {
isCloudSetupAgentSkipped,
rememberCloudSetupAgentSkipped,
type CloudSetupPageRequest
} from '@/lib/orca-cloud/cloud-setup-page-store'
import type { CloudSetupPageRequest } from '@/lib/orca-cloud/cloud-setup-page-store'
import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry'
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types'
@@ -97,7 +93,6 @@ export type CloudSetupFlow = CloudSetupPageModel & {
startTrial: () => void
fixBilling: () => void
installGitHub: () => void
skipAgent: () => void
checkAgain: () => void
copyLink: (() => void) | null
reopenBrowser: () => void
@@ -116,7 +111,6 @@ export function useCloudSetupFlow(
// opened for, so it waits on all of them; a single hop (GitHub install, billing) only on its own.
const [browserStep, setBrowserStep] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [agentSkipped, setAgentSkipped] = useState(() => isCloudSetupAgentSkipped(request.agent))
const githubOverride = useMemo<CloudSetupStep | null>(
() => (request.cloudOnlyRepo ? { id: 'github', state: 'done' } : null),
[request.cloudOnlyRepo]
@@ -135,14 +129,14 @@ export function useCloudSetupFlow(
githubOverride
})
const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session)
const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null })
const model = cloudSetupPageModel(steps, { teamSwitch: switchTeam !== null })
const error = useMemo(() => {
const parsed = parseCloudSetupError(session?.error)
return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed
}, [session?.error, session?.teamName])
// Rows derived from billing tick on their own: re-read while a step is waiting elsewhere.
const waiting = model.action !== 'done' && model.action !== 'agent'
const waiting = model.action !== 'done'
useEffect(() => {
if (!waiting || accessOverride) {
return
@@ -262,11 +256,6 @@ export function useCloudSetupFlow(
void openInstall()
}, [markInBrowser, openInstall])
const skipAgent = useCallback(() => {
rememberCloudSetupAgentSkipped(request.agent)
setAgentSkipped(true)
}, [request.agent])
const checkAgain = useCallback(() => void prefetchOrcaCloudBilling(true), [])
return {
@@ -284,7 +273,6 @@ export function useCloudSetupFlow(
startTrial,
fixBilling,
installGitHub,
skipAgent,
checkAgain,
copyLink:
sessionId && canCopyCloudSetupLink(sessionId)
@@ -1,7 +1,6 @@
// The status (dot and text) of a cloud agent row that needs sign-in: clicking it opens
// Settings → Agent accounts, where the fix lives. The rest of the row still opens the pane.
import React, { useCallback } from 'react'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
import { AgentStateDot } from '@/components/AgentStateDot'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
@@ -11,10 +10,9 @@ import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloud
/** What the status shows: its label, the agent's catalog name, and the tooltip naming the fix. */
export type CloudAgentRowStatusText = { label: string; agentName: string; tooltip: string | null }
/** The composer's "Set up once" target, plus opening Settings, which the sidebar has closed. */
/** The sidebar row's "Set up once": the focused Orca Cloud sign-in sheet (JA-04). */
export function openCloudAgentAccountsSettings(): void {
openOrcaCloudAgentAccounts()
useAppStore.getState().openSettingsPage()
}
/**
@@ -185,6 +185,18 @@ export function CloudSetupNotices({
)
}
/** Bottom right, above the floating-terminal button: top right would cover the prompt's first row. */
export function CloudSetupNoticesDock({ workspaceId }: { workspaceId: string }): React.JSX.Element {
return (
<div
data-cloud-surface=""
className="pointer-events-none absolute right-3 bottom-14 z-30 flex flex-col items-end gap-2"
>
<CloudSetupNotices workspaceId={workspaceId} />
</div>
)
}
export function CloudSetupNoticesView({
record,
notices,
@@ -207,7 +219,7 @@ export function CloudSetupNoticesView({
role="status"
aria-labelledby={labelId}
data-cloud-notice="setup"
className="pointer-events-auto w-[26rem] max-w-[calc(100%-1.5rem)] rounded-lg border border-border bg-card text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1"
className="pointer-events-auto w-[26rem] max-w-[calc(100%-1.5rem)] rounded-lg border border-border bg-card text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1"
>
<h2 id={labelId} className="sr-only">
{t('orcaCloud.setupNotices.label', 'Workspace setup')}
@@ -1,3 +1,4 @@
import { useReopenRemoteDesktopAfterWake } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen'
import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
import { useAppStore } from '@/store'
@@ -21,7 +22,7 @@ import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/c
import { CloudArchivedWorkspaceView, type ArchiveLoad } from './CloudArchivedWorkspaceView'
import { CloudWakingOverlay } from './CloudWakingOverlay'
import { CloudWorkspaceNotice } from './CloudWorkspaceNotice'
import { CloudSetupNotices } from './CloudSetupNotices'
import { CloudSetupNoticesDock } from './CloudSetupNotices'
import { useConfirmedRestart } from './use-cloud-panel-actions'
import { useCloudVersionSkewNotice } from './use-cloud-version-skew-notice'
import { CloudWorkspaceOfflineView } from './offline/CloudWorkspaceOfflineView'
@@ -223,6 +224,7 @@ function useInertSiblings(cover: React.RefObject<HTMLElement | null>, active: bo
function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Element | null {
const t = useTranslate()
const view = useCloudWorkspaceView(workspaceId)
useReopenRemoteDesktopAfterWake(workspaceId, view.state === 'running')
const name = useAppStore((state) => findWorktreeById(state, workspaceId)?.displayName ?? null)
// Ready means the server answers; the pill stays ("Connecting…") until the pane in front has
// re-attached and can take keys.
@@ -337,10 +339,8 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme
if (layer === null && versionSkewNotice) {
notices.push(versionSkewNotice)
}
if (layer === null && view.state !== 'sleeping' && view.state !== 'archived') {
// What the environment check found that didn't need to stop the create (env-check-ux).
notices.push(<CloudSetupNotices key="setup" workspaceId={workspaceId} />)
}
// What the environment check found that didn't need to stop the create (env-check-ux).
const showSetupNotices = layer === null && view.state !== 'sleeping' && view.state !== 'archived'
if (layer === null && view.oom) {
notices.push(
<CloudWorkspaceNotice
@@ -437,6 +437,7 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme
) : null}
</div>
) : null}
{showSetupNotices ? <CloudSetupNoticesDock workspaceId={workspaceId} /> : null}
{notices.length > 0 ? (
<div
data-cloud-surface=""
@@ -23,6 +23,7 @@ const waking: CloudWakeProgressEvent = {
startedAt: T0 - 5_000,
at: T0
}
const PAST_CAP = WAKE_ATTACH_HOLD_MAX_MS + WAKE_ATTACH_POLL_MS
const start: { wake: CloudWakeProgressEvent | undefined } = { wake: waking }
beforeEach(() => {
@@ -99,18 +100,31 @@ describe('useWakeAttachHold', () => {
expect(result.current.wake).toBeUndefined()
})
it('a pane that never takes input becomes "Couldn’t reconnect the terminal"; Try again reconnects it', () => {
it('at the cap reconnects the pane once on its own, and only then shows the card', () => {
const retry = vi.fn(() => true)
const { result, rerender } = hook(() => false, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
expect(result.current.wake?.phase).toBe('connecting')
act(() => vi.advanceTimersByTime(PAST_CAP))
// The quiet retry: still Connecting…, no card yet.
expect(retry).toHaveBeenCalledTimes(1)
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake?.phase).toBe('connecting')
act(() => vi.advanceTimersByTime(PAST_CAP))
expect(retry).toHaveBeenCalledTimes(1)
expect(result.current.terminalStalled).toBe(true)
expect(result.current.wake?.phase).toBe('failed')
})
it('Try again re-runs the attach (not a wake) and waits for the pane once more', () => {
let attached: boolean | null = false
const retry = vi.fn(() => true)
const { result, rerender } = hook(() => attached, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
expect(result.current.wake?.phase).toBe('connecting')
act(() => vi.advanceTimersByTime(WAKE_ATTACH_HOLD_MAX_MS + WAKE_ATTACH_POLL_MS))
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(result.current.terminalStalled).toBe(true)
expect(result.current.wake?.phase).toBe('failed')
// Try again: the pane reconnects and the pill waits for it once more.
act(() => result.current.retry())
expect(retry).toHaveBeenCalledWith('ws')
expect(retry).toHaveBeenLastCalledWith('ws')
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake?.phase).toBe('connecting')
attached = true
@@ -118,6 +132,48 @@ describe('useWakeAttachHold', () => {
expect(result.current.wake).toBeUndefined()
})
it('the card clears by itself once the pane attaches through any path', () => {
let attached: boolean | null = false
const retry = vi.fn(() => true)
const { result, rerender } = hook(() => attached, retry)
rerender({ wake: { ...waking, phase: 'ready' } })
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(result.current.terminalStalled).toBe(true)
// A restore or account restart brings the pane back; nobody pressed Try again.
attached = true
act(() => vi.advanceTimersByTime(WAKE_ATTACH_POLL_MS))
expect(result.current.terminalStalled).toBe(false)
expect(result.current.wake).toBeUndefined()
expect(retry).toHaveBeenCalledTimes(1)
})
it('a restart with no wake in flight never shows the card', () => {
const retry = vi.fn(() => true)
const { result } = renderHook(() => useWakeAttachHold('ws', undefined, () => false, retry))
// The restored pane takes its time to attach; no wake, so nothing holds or fails over it.
act(() => vi.advanceTimersByTime(PAST_CAP * 3))
expect(result.current.wake).toBeUndefined()
expect(result.current.terminalStalled).toBe(false)
expect(retry).not.toHaveBeenCalled()
})
it('an account restart (no wake ready from main) never shows the card', () => {
const retry = vi.fn(() => true)
const { result, rerender } = hook(() => false, retry)
// A wake entry that never settles through main goes away (stale, quiet failure, Dismiss)
// while the pane respawns for its new account: no hold, no card.
rerender({ wake: undefined })
act(() => vi.advanceTimersByTime(PAST_CAP * 3))
expect(result.current.wake).toBeUndefined()
expect(result.current.terminalStalled).toBe(false)
// Nor a `ready` from a different wake than the one seen in flight.
rerender({ wake: { ...waking, startedAt: T0 } })
rerender({ wake: { ...waking, startedAt: T0 + 1, phase: 'ready' } })
act(() => vi.advanceTimersByTime(PAST_CAP * 3))
expect(result.current.wake).toBeUndefined()
expect(retry).not.toHaveBeenCalled()
})
it('counts only visible time toward the reconnect cap', () => {
let visibility: DocumentVisibilityState = 'visible'
const descriptor = Object.getOwnPropertyDescriptor(document, 'visibilityState')
@@ -142,6 +198,9 @@ describe('useWakeAttachHold', () => {
act(() => vi.advanceTimersByTime(WAKE_ATTACH_HOLD_MAX_MS / 2 - WAKE_ATTACH_POLL_MS * 2))
expect(result.current.terminalStalled).toBe(false)
act(() => vi.advanceTimersByTime(WAKE_ATTACH_POLL_MS * 3))
// The cap's quiet reconnect, counted in visible time too; the card waits one more cap.
expect(result.current.terminalStalled).toBe(false)
act(() => vi.advanceTimersByTime(PAST_CAP))
expect(result.current.terminalStalled).toBe(true)
} finally {
if (descriptor) {
@@ -155,7 +214,8 @@ describe('useWakeAttachHold', () => {
it('Dismiss clears the reconnect card', () => {
const { result, rerender } = hook(() => false)
rerender({ wake: { ...waking, phase: 'ready' } })
act(() => vi.advanceTimersByTime(WAKE_ATTACH_HOLD_MAX_MS + WAKE_ATTACH_POLL_MS))
act(() => vi.advanceTimersByTime(PAST_CAP * 2))
expect(result.current.terminalStalled).toBe(true)
act(() => result.current.dismiss())
expect(result.current.wake).toBeUndefined()
})
@@ -8,7 +8,7 @@ import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/c
/** How often the hold checks the pane in front while it waits. */
export const WAKE_ATTACH_POLL_MS = 100
/** A pane that hasn't re-attached by now gets the "Couldn't reconnect the terminal" card. */
/** A pane that hasn't re-attached by now is reconnected once; after a second cap it gets the card. */
export const WAKE_ATTACH_HOLD_MAX_MS = 8_000
type Track = {
@@ -38,8 +38,11 @@ export type WakeAttachHold = {
* A wake reports ready once the server answers; the pane in front re-attaches to its terminal a
* moment later. Until it takes input (attached, with nothing it was given still unsent), this
* returns the wake as still `connecting` (same start time and source, so the pill keeps counting
* from the wake's start). A pane that hasn't by the cap becomes a failed card with Try again,
* never a silent dead pane. Then `undefined` hands back to the store's wake.
* from the wake's start). A pane that hasn't by the cap is reconnected once quietly; one that
* still hasn't by the next cap becomes a failed card with Try again (re-runs the attach), never a
* silent dead pane, and the card clears itself if the pane attaches after all. Only main's `ready`
* for a wake seen in flight arms this: a restart or an account restart with no wake never does.
* Then `undefined` hands back to the store's wake.
*/
export function useWakeAttachHold(
workspaceId: string,
@@ -65,43 +68,61 @@ export function useWakeAttachHold(
if (track.last || track.held || track.stalled) {
setTrack({ ...IDLE, attempt: track.attempt })
}
} else if (track.last && (!wake || wake.startedAt === track.last.startedAt)) {
// Ready, or the settled entry already dropped: hold only a wake that was in flight here.
} else if (track.last) {
// Only main's own `ready` for the wake seen in flight here holds the pane. An entry that just
// goes away (a stale or quietly failed wake dropped by the store, a Dismiss) never does: no
// wake brought the pane back, so there is nothing to wait for.
const settled = wake?.phase === 'ready' && wake.startedAt === track.last.startedAt
const held =
isAttached(workspaceId) === false
settled && isAttached(workspaceId) === false
? { ...track.last, phase: 'connecting' as const }
: undefined
setTrack({ ...IDLE, attempt: track.attempt + 1, held })
}
// Release once the pane takes input; at the cap, fail visibly. The store dropping the settled
// wake doesn't cancel this: it is keyed on the hold only.
const holding = track.held !== undefined
// Release once the pane takes input; at the cap, reconnect it once quietly, then fail visibly.
// The card keeps watching too: a pane that attaches later (restore, account restart, a slow
// wake) clears it on its own. The store dropping the settled wake doesn't cancel this.
const waiting = track.held !== undefined || track.stalled !== undefined
const attempt = track.attempt
useEffect(() => {
if (!holding) {
if (!waiting) {
return
}
// Only visible time counts toward the cap: a hidden window pauses this poll (and the pane's
// own re-attach), so time spent hidden must not turn a healthy wake into a stalled card.
let visibleMs = 0
let lastAt = Date.now()
let quietRetryDone = false
let shownStalled = false
const check = (): void => {
const attached = isAttached(workspaceId)
if (attached === false && visibleMs < WAKE_ATTACH_HOLD_MAX_MS) {
if (attached === false && (shownStalled || visibleMs < WAKE_ATTACH_HOLD_MAX_MS)) {
return
}
if (attached === false && !quietRetryDone) {
// One reconnect on its own before the card: a pane whose attach got lost usually comes
// back from this, and the person never sees a failure for it.
quietRetryDone = true
visibleMs = 0
retryPane(workspaceId)
return
}
shownStalled = attached === false
setTrack((current) => {
if (current.attempt !== attempt || !current.held) {
if (current.attempt !== attempt || (!current.held && !current.stalled)) {
return current
}
return attached === false
if (attached !== false) {
return { ...current, held: undefined, stalled: undefined }
}
return current.held
? {
...current,
held: undefined,
stalled: { ...current.held, phase: 'failed', at: Date.now() }
}
: { ...current, held: undefined }
: current
})
}
return installWindowVisibilityInterval({
@@ -118,7 +139,7 @@ export function useWakeAttachHold(
},
intervalMs: WAKE_ATTACH_POLL_MS
})
}, [holding, attempt, workspaceId, isAttached])
}, [waiting, attempt, workspaceId, isAttached, retryPane])
const retry = useCallback(() => {
retryPane(workspaceId)
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import type { WorkspacePort } from '../../../../shared/workspace-ports'
import { getLocalWorkspacePortSections } from './local-workspace-port-sections'
const external = (
port: number,
extra: { pid?: number; hostManaged?: true } = {}
): WorkspacePort => ({
id: `x:${port}`,
kind: 'external',
bindHost: '127.0.0.1',
connectHost: 'localhost',
port,
protocol: 'http',
pid: 'pid' in extra ? extra.pid : 100 + port,
...(extra.hostManaged ? { hostManaged: true } : {})
})
const scan = {
ports: [
external(6768, { hostManaged: true }),
external(23456, { pid: undefined, hostManaged: true }),
external(5432, { pid: undefined }),
external(8123)
]
}
describe('getLocalWorkspacePortSections', () => {
it('hides only host-marked services from External, keeping a pid-less user port', () => {
const sections = getLocalWorkspacePortSections(scan, 'r', 'w', true)
expect(sections.externalPorts.map((port) => port.port)).toEqual([5432, 8123])
})
it('keeps every listener on other hosts', () => {
const sections = getLocalWorkspacePortSections(scan, 'r', 'w')
expect(sections.externalPorts.map((port) => port.port)).toEqual([6768, 23456, 5432, 8123])
})
})
@@ -3,13 +3,15 @@ import type { WorkspacePort } from '../../../../shared/workspace-ports'
export function getLocalWorkspacePortSections(
scan: { ports: WorkspacePort[] } | null | undefined,
activeRepoId: string | null | undefined,
activeWorktreeId: string | null | undefined
activeWorktreeId: string | null | undefined,
/** Orca Cloud: the sandbox's own services (marked host-managed by the host) are not the user's ports. */
hideHostServices = false
): {
activePorts: WorkspacePort[]
otherWorkspacePorts: WorkspacePort[]
externalPorts: WorkspacePort[]
} {
const ports = scan?.ports ?? []
const ports = (scan?.ports ?? []).filter((port) => !hideHostServices || port.hostManaged !== true)
return {
activePorts: ports.filter(
(port) =>
@@ -213,8 +213,8 @@ export function LocalWorkspacePortsPanel({
)
const { activePorts, otherWorkspacePorts, externalPorts } = useMemo(
() => getLocalWorkspacePortSections(displayScan, activeRepoId, activeWorktree?.id),
[activeRepoId, activeWorktree?.id, displayScan]
() => getLocalWorkspacePortSections(displayScan, activeRepoId, activeWorktree?.id, isSandbox),
[activeRepoId, activeWorktree?.id, displayScan, isSandbox]
)
const showPortSections = shouldShowLocalWorkspacePortSections(displayScan, {
@@ -12,6 +12,7 @@ import { useTranslate } from '@/i18n/use-translate'
import { AgentDashboardExperimentalSetting } from '../../dashboard/AgentDashboardExperimentalSetting'
import { EphemeralVmsExperimentalSetting } from '../virtual-machines/recipes/EphemeralVmsExperimentalSetting'
import { BrowserExtensionsExperimentalSetting } from '../browser/extensions/BrowserExtensionsExperimentalSetting'
import { PokesExperimentalSetting } from '../../teammates/PokesExperimentalSetting'
import { WslHostsExperimentalSetting } from '../wsl/hosts/WslHostsExperimentalSetting'
import { wslHostsAvailable } from '../../sidebar/use-wsl-hosts-enabled'
import {
@@ -255,6 +256,10 @@ export function ExperimentalPane({
<BrowserExtensionsExperimentalSetting settings={settings} updateSettings={updateSettings} />
{matchesSettingsSearch(searchQuery, [getExperimentalSearchEntry().pokes]) ? (
<PokesExperimentalSetting />
) : null}
{wslHostsAvailable() ? (
<WslHostsExperimentalSetting settings={settings} updateSettings={updateSettings} />
) : null}
@@ -185,7 +185,40 @@ export const getExperimentalSearchEntry = createLocalizedCatalog(
},
newWorktreeCardStyle: getNewWorktreeCardStyleSearchEntry(),
ephemeralVms: getEphemeralVmsSearchEntry(),
browserExtensions: getBrowserExtensionsExperimentalSearchEntry()
browserExtensions: getBrowserExtensionsExperimentalSearchEntry(),
pokes: {
title: translate(
'auto.components.settings.experimental.search.pokes.activityTitle',
'Pokes and activity'
),
description: translate(
'auto.components.settings.experimental.search.pokes.activityDescription',
'Teammates can poke you and see which days you used Orca Cloud. Amounts stay private.'
),
keywords: [
...translateSearchKeyword(
'auto.components.settings.experimental.search.0d24759f14',
'experimental'
),
...translateSearchKeyword(
'auto.components.settings.experimental.search.pokes.poke',
'poke'
),
...translateSearchKeyword(
'auto.components.settings.experimental.search.pokes.nudge',
'nudge'
),
...translateSearchKeyword(
'auto.components.settings.experimental.search.pokes.teammate',
'teammate'
),
...translateSearchKeyword(
'auto.components.settings.experimental.search.pokes.activity',
'activity'
)
],
targetSectionId: 'experimental-pokes'
}
}) satisfies Record<string, SettingsSearchEntry>
)
@@ -153,8 +153,8 @@ export function OrcaCloudAccountsView({
<SettingsGroupHeader
title={t('orcaCloudAccounts.title', 'Orca Cloud')}
description={t(
'orcaCloudAccounts.help',
'Set up once on this computer. Every cloud workspace uses it, including new, cloned and restarted ones.'
'orcaCloudAccounts.helpAccountWide',
'Set up once. Every cloud workspace uses it, including new, cloned and restarted ones.'
)}
/>
)}
@@ -1,11 +1,9 @@
// Wires S3 to the renderer's host list, the per-host sign-in probes and the Orca account. Rows open
// the A16 panel; the Orca Cloud row scrolls to S0 below (one row stands for every cloud workspace).
import React, { useEffect, useMemo, useState } from 'react'
// Wires S3 to the renderer's host list and the per-host sign-in probes. Rows open the A16 panel.
// No Orca Cloud row (JA-04): the page's own Orca Cloud part right below is the one place for it.
import React, { useMemo } from 'react'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
import { useOrcaCloudAgentAccounts } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store'
import { openAgentHostPanel } from '../../../agent-host-panel/agent-host-panel-store'
import { ORCA_CLOUD_ACCOUNTS_SECTION_ID } from '../OrcaCloudAccounts'
import {
overviewRows,
type OverviewAction,
@@ -22,28 +20,6 @@ function openSettings(pane: 'accounts', sectionId?: string): void {
store.openSettingsPage()
}
/** A member can't change team keys: their key cells say "set by your team". */
function useIsCloudMember(enabled: boolean): boolean {
const [member, setMember] = useState(false)
useEffect(() => {
if (!enabled) {
return
}
let cancelled = false
void (window.api.cloudSecrets?.effective({}) ?? Promise.resolve(null))
.catch(() => null)
.then((result) => {
if (!cancelled && result?.ok) {
setMember(!result.value.caller.canWrite.org)
}
})
return () => {
cancelled = true
}
}, [enabled])
return member
}
export function AgentAccountsOverviewSection({
hideHeader = false
}: {
@@ -52,28 +28,11 @@ export function AgentAccountsOverviewSection({
const t = useTranslate()
const hosts = useOverviewHosts()
const { probes, checkAgain, firstPassDone } = useOverviewProbes(hosts)
const accounts = useOrcaCloudAgentAccounts()
const ready = accounts.load.kind === 'ready'
const member = useIsCloudMember(ready)
const signedOutOfOrca = accounts.load.kind === 'failed' && accounts.load.error === 'signed_out'
const rows = useMemo(
() =>
overviewRows({
hosts,
probes,
cloud:
accounts.load.kind === 'ready'
? { status: accounts.load.status, keyKinds: accounts.keyKinds, member }
: null
}),
[hosts, probes, accounts.load, accounts.keyKinds, member]
)
const rows = useMemo(() => overviewRows({ hosts, probes, cloud: null }), [hosts, probes])
const hostById = new Map<string, OverviewHost>(hosts.map((host) => [host.hostId, host]))
const open = (row: OverviewRow, focus?: 'claude' | 'codex'): void => {
const host = row.hostId ? hostById.get(row.hostId) : undefined
if (!host) {
// Orca Cloud: S0 below owns setup and the Source for every cloud workspace.
document.getElementById(ORCA_CLOUD_ACCOUNTS_SECTION_ID)?.scrollIntoView({ block: 'start' })
return
}
openAgentHostPanel({
@@ -111,7 +70,7 @@ export function AgentAccountsOverviewSection({
return (
<AgentAccountsOverview
rows={rows}
signedOutOfOrca={signedOutOfOrca}
signedOutOfOrca={false}
hideHeader={hideHeader}
summary={summary}
onOpenRow={(row) => open(row)}
@@ -0,0 +1,75 @@
// JA-04: the focused Orca Cloud sign-in sheet. Only Claude and Codex, each with its one action and
// status (S0's rows), so "Set up once" never lands on this computer's provider accounts.
import React from 'react'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle
} from '@/components/ui/sheet'
import { OrcaCloudAccountsSection } from '../OrcaCloudAccountsSection'
import {
closeOrcaCloudSignInSheet,
useOrcaCloudSignInSheetOpen
} from './orca-cloud-sign-in-sheet-store'
function openAllAgentAccounts(): void {
closeOrcaCloudSignInSheet()
const store = useAppStore.getState()
store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' })
store.openSettingsPage()
}
/** The sheet's contents; the host owns the Sheet so fixtures can render it open. */
export function OrcaCloudSignInSheetView({
body
}: {
/** S0's rows; fixtures pass a fixed view. */
body: React.ReactNode
}): React.JSX.Element {
const t = useTranslate()
const titleId = React.useId()
return (
<SheetContent side="right" className="w-[600px] sm:max-w-[600px]" aria-labelledby={titleId}>
<div className="border-b border-border pe-8">
<SheetHeader>
<SheetTitle id={titleId}>
{t('orcaCloudSignInSheet.title', 'Agents in Orca Cloud')}
</SheetTitle>
<SheetDescription>
{t(
'orcaCloudSignInSheet.description',
'Set up Claude and Codex once. Every cloud workspace uses them, including new, cloned and restarted ones.'
)}
</SheetDescription>
</SheetHeader>
</div>
<div className="scrollbar-sleek min-h-0 flex-1 overflow-y-auto px-5 py-5">{body}</div>
<nav
aria-label={t('orcaCloudSignInSheet.footerLabel', 'Related settings')}
className="border-t border-border px-5 py-3 text-xs"
>
<button
type="button"
className="text-muted-foreground underline underline-offset-2 hover:text-foreground focus-visible:outline-[var(--focus-ring)]"
onClick={openAllAgentAccounts}
>
{t('orcaCloudSignInSheet.allAccounts', 'All agent accounts')}
</button>
</nav>
</SheetContent>
)
}
/** Mounted once in App; opened by openOrcaCloudSignInSheet(). */
export function OrcaCloudSignInSheet(): React.JSX.Element {
const open = useOrcaCloudSignInSheetOpen()
return (
<Sheet open={open} onOpenChange={(next) => !next && closeOrcaCloudSignInSheet()}>
{open ? <OrcaCloudSignInSheetView body={<OrcaCloudAccountsSection hideHeader />} /> : null}
</Sheet>
)
}
@@ -0,0 +1,37 @@
// JA-04: every "Set up once" / "Renew" for Orca Cloud opens one focused sheet (Claude and Codex
// only) instead of Settings, so nobody scrolls past this computer's provider accounts to reach it.
import { useSyncExternalStore } from 'react'
let open = false
const listeners = new Set<() => void>()
function set(next: boolean): void {
if (open === next) {
return
}
open = next
for (const listener of listeners) {
listener()
}
}
export function openOrcaCloudSignInSheet(): void {
set(true)
}
export function closeOrcaCloudSignInSheet(): void {
set(false)
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
export function useOrcaCloudSignInSheetOpen(): boolean {
return useSyncExternalStore(
subscribe,
() => open,
() => false
)
}
@@ -30,8 +30,8 @@ export function orcaCloudAgentAccountsParts(
id: 'accounts-orca-cloud',
title: t('orcaCloudAccounts.title', 'Orca Cloud'),
description: t(
'orcaCloudAccounts.help',
'Set up once on this computer. Every cloud workspace uses it, including new, cloned and restarted ones.'
'orcaCloudAccounts.helpAccountWide',
'Set up once. Every cloud workspace uses it, including new, cloned and restarted ones.'
),
content: <OrcaCloudAccountsSection hideHeader />
}
@@ -1,5 +1,8 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useCloudRecoveryContext } from '@/lib/orca-cloud/use-cloud-recovery-context'
import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store'
import { useCloudSetupPageRequest } from '@/lib/orca-cloud/cloud-setup-page-store'
import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface'
import { toast } from 'sonner'
import { useAppStore } from '@/store'
import { track } from '@/lib/telemetry'
@@ -71,9 +74,18 @@ function SetupScriptPromptCard(): React.JSX.Element | null {
// An asleep Orca Cloud workspace can't be inspected: wait until it's awake instead of showing
// "Couldn't verify this repo's setup script" with Retry (RA-12).
const asleepCloud = useCloudRecoveryContext(activeWorktreeId)?.asleep === true
// Orca Cloud never shows this nudge: a cloud workspace reports a setup script that hasn't run in
// its own notice, and while a create is setting up, starting or stopped on a check the card would
// flip between states under the start screen (JA-12, PC-7).
const cloudWorkspace = useIsCloudWorkspace(activeWorktreeId)
const creationShown = useAppStore(selectWorktreeCreationSurfaceShown)
const cloudSetupOpen = useCloudSetupPageRequest() !== null
const isDismissed =
provisionedByEnvironmentBuild ||
asleepCloud ||
cloudWorkspace ||
creationShown ||
cloudSetupOpen ||
(activeRepoHostIdentity
? isSetupScriptPromptDismissed(activeRepoHostIdentity, dismissedRepoIds)
: false)
@@ -1,4 +1,5 @@
import { useAppStore } from '@/store'
import { noteRemoteDesktopBeforeSleep } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen'
import {
captureWorkspaceSelection,
restoreWorkspaceSelection,
@@ -55,6 +56,10 @@ export function followWorkspaceSleep(
const state = useAppStore.getState()
const wasActive = state.activeWorktreeId === worktreeId
const selectionBeforeSleep = wasActive ? captureWorkspaceSelection(state) : null
if (!options.keepBrowserTabs) {
// Before the selection clears: whether the desktop tab was in front decides how it comes back.
noteRemoteDesktopBeforeSleep(worktreeId)
}
// Why first: clearing the active workspace unmounts its panes, whose exits must not stamp activity.
markWorktreeSleepIntent(worktreeId)
if (wasActive) {
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useSortable } from '@dnd-kit/sortable'
import { X, Pin, PinOff, Volume2, VolumeX } from 'lucide-react'
import { X, Pin, PinOff, Volume2, VolumeX, Monitor } from 'lucide-react'
import {
ContextMenu,
ContextMenuContent,
@@ -13,6 +13,7 @@ import '../../../../shared/constants'
import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page'
import { redactKagiSessionToken } from '../../../../shared/browser-url'
import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types'
import { isCloudRemoteDesktopUrl } from '../../../../shared/hosted-sandbox/cloud-remote-desktop'
import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus'
import { getLiveBrowserUrl } from '../browser-pane/describe-page/live-browser-url-registry'
import type { TabDragItemData } from '../tab-group/useTabDragSplit'
@@ -55,6 +56,10 @@ export function formatBrowserTabUrlLabel(url: string, t: Translate = translate):
}
export function getBrowserTabLabel(tab: BrowserWorkspace, t?: Translate): string {
// A remote desktop tab is named for what it is, not for its localhost forward.
if (isCloudRemoteDesktopUrl(tab.url)) {
return (t ?? translate)('components.cloudRemoteDesktop.tabTitle', 'Remote desktop')
}
if (
!tab.title ||
tab.title === tab.url ||
@@ -122,6 +127,7 @@ export default function BrowserTab({
// invalid URL — leave disabled
}
const tabLabel = getBrowserTabLabel(tab, t)
const isRemoteDesktop = isCloudRemoteDesktopUrl(tab.url)
const audible = useAppStore((s) =>
(s.browserPagesByWorkspace[tab.id] ?? []).some((page) => s.browserAudiblePageIds[page.id])
)
@@ -206,6 +212,8 @@ export default function BrowserTab({
/>
<AgentCursorGlyph className="pointer-events-none absolute inset-0 size-3" />
</span>
) : isRemoteDesktop ? (
<Monitor className="mr-1 size-3 shrink-0 text-muted-foreground" aria-hidden />
) : (
<BrowserFavicon
faviconUrl={tab.faviconUrl}
@@ -266,7 +274,13 @@ export default function BrowserTab({
<TabHoverCard
title={tabLabel}
showWhenUnclipped={controllerHost !== null}
icon={<BrowserFavicon faviconUrl={tab.faviconUrl} className="size-4" />}
icon={
isRemoteDesktop ? (
<Monitor className="size-4 text-muted-foreground" aria-hidden />
) : (
<BrowserFavicon faviconUrl={tab.faviconUrl} className="size-4" />
)
}
programName={
agentDriving
? agentDrivingLabel
@@ -8,6 +8,7 @@ import {
Globe,
Loader2,
MessageSquare,
Monitor,
Search,
Smartphone,
TerminalSquare
@@ -279,6 +280,8 @@ function getActionPresentation(
const icon =
option.option.kind === 'new-browser' ? (
<Globe className="size-3.5 shrink-0" aria-hidden="true" />
) : option.option.kind === 'open-remote-desktop' ? (
<Monitor className="size-3.5 shrink-0" aria-hidden="true" />
) : option.option.kind === 'new-markdown' ? (
<FilePlus className="size-3.5 shrink-0" aria-hidden="true" />
) : option.option.kind === 'new-plugin-file' ? (
@@ -1,5 +1,5 @@
import React from 'react'
import { FilePlus, FileText, Globe, Smartphone, TerminalSquare } from 'lucide-react'
import { FilePlus, FileText, Globe, Monitor, Smartphone, TerminalSquare } from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { DropdownMenuItem, DropdownMenuShortcut } from '@/components/ui/dropdown-menu'
import { MobileEmulatorTabIntroCallout } from '../emulator-pane/MobileEmulatorTabIntroCallout'
@@ -14,6 +14,10 @@ import {
} from './use-tab-bar-runtime-model'
import type { TabBarProps } from './tab-bar-props'
import { resolveWindowsShellLaunchTarget } from './windows-shell-launch'
import {
openOrGoToRemoteDesktop,
useRemoteDesktopTabEntry
} from '@/lib/cloud-remote-desktop/remote-desktop-tab'
export function TabBarStaticCreateMenu({
groupId,
@@ -116,6 +120,19 @@ export function TabBarStaticCreateMenu({
<DropdownMenuShortcut>{newBrowserShortcut}</DropdownMenuShortcut>
</DropdownMenuItem>
) : null
const remoteDesktop = useRemoteDesktopTabEntry(props.worktreeId)
const remoteDesktopMenuItem =
!terminalOnly && remoteDesktop.available ? (
<DropdownMenuItem
onSelect={() => openOrGoToRemoteDesktop(props.worktreeId)}
className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 font-medium"
>
<Monitor className="size-4 text-muted-foreground" />
{remoteDesktop.isGoTo
? t('components.cloudRemoteDesktop.goToTabMenuItem', 'Go to Remote Desktop')
: t('components.cloudRemoteDesktop.openTabMenuItem', 'Open Remote Desktop')}
</DropdownMenuItem>
) : null
const newSimulatorMenuItem =
!terminalOnly && mobileEmulatorEnabled && mobileEmulatorCreationEnabled && onNewSimulatorTab ? (
workspaceHasSimulatorTab ? (
@@ -199,6 +216,7 @@ export function TabBarStaticCreateMenu({
{openMarkdownMenuItem}
{defaultTerminalMenuItems}
{newBrowserMenuItem}
{remoteDesktopMenuItem}
{newSimulatorMenuItem}
{mobileEmulatorIntroMenuBlock}
</>
@@ -206,6 +224,7 @@ export function TabBarStaticCreateMenu({
<>
{defaultTerminalMenuItems}
{newBrowserMenuItem}
{remoteDesktopMenuItem}
{newMarkdownMenuItem}
{pluginNewFileMenuItems}
{openMarkdownMenuItem}
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import {
buildTabCreateMenuOptions,
findMatchingTabCreateMenuOptions
} from './tab-create-menu-options'
const t = (_key: string, fallback: string): string => fallback
const base = {
hasNewBrowser: true,
hasNewMarkdown: true,
hasOpenMarkdown: false,
hasSimulator: false,
simulatorIsGoTo: false,
terminalOnly: false
}
describe('+ menu remote desktop entry', () => {
it('is offered only for Orca Cloud workspaces, after the browser', () => {
expect(buildTabCreateMenuOptions(base, t).map((o) => o.kind)).not.toContain(
'open-remote-desktop'
)
const options = buildTabCreateMenuOptions({ ...base, remoteDesktop: { isGoTo: false } }, t)
expect(options.map((o) => o.kind)).toEqual([
'new-terminal',
'new-browser',
'open-remote-desktop',
'new-markdown'
])
expect(options[2].label).toBe('Open Remote Desktop')
})
it('goes to the open desktop tab instead of a second one, and is found by "vnc"', () => {
const options = buildTabCreateMenuOptions({ ...base, remoteDesktop: { isGoTo: true } }, t)
expect(options.find((o) => o.kind === 'open-remote-desktop')?.label).toBe(
'Go to Remote Desktop'
)
expect(findMatchingTabCreateMenuOptions('vnc', options)[0]?.kind).toBe('open-remote-desktop')
})
})
@@ -7,6 +7,7 @@ import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard
export type TabCreateMenuOptionKind =
| 'go-to-simulator'
| 'new-browser'
| 'open-remote-desktop'
| 'new-markdown'
| 'new-simulator'
| 'new-terminal'
@@ -40,6 +41,8 @@ export type TabCreateMenuOptionsContext = {
hasOpenMarkdown: boolean
hasSimulator: boolean
simulatorIsGoTo: boolean
/** Orca Cloud workspaces: open the sandbox's desktop, or go to its tab when it is open. */
remoteDesktop?: { isGoTo: boolean } | null
terminalOnly: boolean
windowsShellEntries?: readonly { label: string; shell: BuiltInWindowsTerminalShell }[]
}
@@ -129,6 +132,23 @@ export function buildTabCreateMenuOptions(
})
}
if (context.remoteDesktop) {
const label = context.remoteDesktop.isGoTo
? t('components.cloudRemoteDesktop.goToTabMenuItem', 'Go to Remote Desktop')
: t('components.cloudRemoteDesktop.openTabMenuItem', 'Open Remote Desktop')
options.push({
id: 'open-remote-desktop',
kind: 'open-remote-desktop',
label,
keywords: [
t('components.cloudRemoteDesktop.verbs.remoteDesktop', 'remote desktop'),
t('components.cloudRemoteDesktop.verbs.openDesktop', 'open desktop'),
t('components.cloudRemoteDesktop.verbs.vnc', 'vnc'),
t('components.cloudRemoteDesktop.verbs.screen', 'screen')
]
})
}
if (context.hasNewMarkdown) {
const label = t('auto.components.tab.bar.TabBar.3d5d6c960d', 'New Markdown')
options.push({
@@ -12,6 +12,7 @@ import { useNewTabAgentMenuRows } from './use-new-tab-agent-menu-rows'
import type { AgentDetectionTarget } from '@/hooks/useDetectedAgents'
import type { TabAgentLaunchOption } from './tab-agent-launch-options'
import { buildTabCreateMenuOptions, type TabCreateMenuOption } from './tab-create-menu-options'
import * as remoteDesktopTab from '@/lib/cloud-remote-desktop/remote-desktop-tab'
import { resolveWindowsShellLaunchTarget } from './windows-shell-launch'
import { buildWindowsShellMenuEntries } from './tab-bar-windows-shell-options'
import type {
@@ -154,6 +155,7 @@ export function useTabBarCreateMenuController({
windowsTerminalCapabilities.gitBashAvailable,
windowsTerminalCapabilities.wslAvailable
])
const remoteDesktop = remoteDesktopTab.useRemoteDesktopMenuOption(worktreeId, terminalOnly)
const createMenuOptions = useMemo(
() =>
buildTabCreateMenuOptions({
@@ -167,9 +169,11 @@ export function useTabBarCreateMenuController({
mobileEmulatorEnabled &&
mobileEmulatorCreationEnabled &&
Boolean(onNewSimulatorTab),
simulatorIsGoTo: workspaceHasSimulatorTab
simulatorIsGoTo: workspaceHasSimulatorTab,
remoteDesktop
}),
[
remoteDesktop,
mobileEmulatorEnabled,
managedBrowserCreationEnabled,
mobileEmulatorCreationEnabled,
@@ -203,6 +207,9 @@ export function useTabBarCreateMenuController({
case 'new-browser':
onNewBrowserTab()
break
case 'open-remote-desktop':
remoteDesktopTab.openOrGoToRemoteDesktop(worktreeId)
break
case 'new-markdown':
onNewFileTab?.()
break
@@ -0,0 +1,77 @@
import { useEffect } from 'react'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store/index'
import { SearchableSetting } from '../settings/section-layout/SearchableSetting'
import { getExperimentalSearchEntry } from '../settings/advanced/experimental-search'
import { pokesAccountKey } from './poke-copy'
import { readPokes, setPokesEnabled, usePokesState } from './pokes-store'
/** Settings → Experimental → Pokes and activity (poke and be poked, share your daily activity). Saved on Orca Cloud for this team, so it follows you. */
export function PokesExperimentalSetting(): React.JSX.Element {
const t = useTranslate()
const entry = getExperimentalSearchEntry().pokes
const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud)
const accountKey = pokesAccountKey(cloud?.userId, cloud?.activeOrgId)
const pokes = usePokesState()
const current = pokes.accountKey === accountKey ? pokes : null
useEffect(() => {
if (accountKey) {
void readPokes(accountKey)
}
}, [accountKey])
const enabled = current?.enabled === true
const note = !accountKey
? t(
'auto.components.teammates.pokesNeedTeam',
'Sign in to Orca and switch to a team to use Pokes.'
)
: current?.error === 'save'
? t(
'auto.components.teammates.pokesSaveFailed',
'Couldn’t save. Check your connection and try again.'
)
: current?.error === 'read' && current.enabled === null
? t(
'auto.components.teammates.unreachable',
'Can’t reach Orca Cloud right now. Check your connection.'
)
: null
return (
<SearchableSetting
title={entry.title}
description={entry.description}
keywords={entry.keywords}
className="space-y-3 py-3"
id="experimental-pokes"
>
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 shrink space-y-0.5">
<Label>{entry.title}</Label>
<p className="text-xs text-muted-foreground">
{t(
'auto.components.teammates.pokesActivitySettingCopy',
'Teammates can poke you and see which days you used Orca Cloud. Amounts stay private.'
)}
</p>
{note ? <p className="text-xs text-foreground">{note}</p> : null}
</div>
<Switch
checked={enabled}
disabled={!accountKey || current?.enabled === null || current === null}
aria-busy={current?.saving || undefined}
aria-label={t(
'auto.components.teammates.pokesActivityToggle',
'Toggle Pokes and activity'
)}
onCheckedChange={(next) => {
if (accountKey && !current?.saving) {
void setPokesEnabled(accountKey, next)
}
}}
/>
</div>
</SearchableSetting>
)
}

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