Merge remote-tracking branch 'private/cloud/integration' into cloud/cloud-sync

# Conflicts:
#	src/renderer/src/i18n/locales/en.json
This commit is contained in:
Neil
2026-11-10 20:28:11 -08:00
208 changed files with 10024 additions and 4662 deletions
@@ -0,0 +1,377 @@
// Live proof on a real dev VM (no model spend): per-turn code checkpoints in an Orca Cloud workspace.
// A real Claude Code chat runs in orcad on the VM, with its model pointed at a stand-in on the VM
// (standin-anthropic.py), and the desktop's own E2EE request connection and client capabilities.
// 1. Each message that opens a turn writes one refs/orca/checkpoints/<chat>/turn/* ref; the user's
// HEAD, staged files and stash list never change.
// 2. Sleep (suspend) and wake (resume): the refs and files are unchanged. A fresh connection, as a
// restarted desktop has, rewinds the chat to turn B and restores its files; Undo brings them back.
// 3. Rollover (host replaced): the refs are still there, a new turn gets its own ref, and the agent's
// context holds only the turns left after the rewind.
// 4. Restart (orcad restarted): rewind to turn A restores the files from before the first turn.
// Dev backends only. The VM is always deleted at the end unless --keep is given.
// Run from the repo root after `pnpm install` there and in cloud/:
// node_modules/.bin/tsx cloud/apps/acceptance/live/checkpoints-vm.ts [--keep]
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { control, vercel } from '../src/clients'
import { RemoteRuntimeRequestConnection } from '../../../../src/shared/remote-runtime/requests/remote-runtime-request-connection'
import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../src/shared/electron-remote-runtime-client-capabilities'
import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection'
import { parsePairingCode } from '../../../../src/shared/remote-runtime/pairing/pairing'
import {
createStructuredAgentSessionId,
structuredAgentSessionCreateParams
} from '../../../../src/shared/agent-session/structured-agent-session-create'
import {
createStructuredAgentSessionOperationId,
structuredAgentSessionPayloadFingerprint
} from '../../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation'
import { structuredAgentSessionMessageSendMutation } from '../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation'
import { agentJournalSubmissionKey } from '../../../../src/shared/agent-session/journal/agent-session-journal-item-key'
import type { AgentSessionHistoryResult } from '../../../../src/shared/agent-session/agent-session-wire'
import type {
AgentSessionCheckpointPreview,
AgentSessionCheckpointRestoreResult
} from '../../../../src/shared/agent-session/lifecycle/agent-session-checkpoint'
const REPO = '/vercel/sandbox/ckvm-repo'
const STANDIN = path.join(path.dirname(fileURLToPath(import.meta.url)), 'standin-anthropic.py')
const MODEL = 'claude-sonnet-4-5-20250929'
const who = { sub: `ckvm-${Date.now().toString(36)}` }
const keep = process.argv.includes('--keep')
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const since = (t0: number) => Math.round(performance.now() - t0)
type Files = Record<string, string>
type Vm = { id: string; vsession: string; pairingCode: string }
const timings: Record<string, number> = {}
const failures: string[] = []
function log(line: string): void {
console.log(`${new Date().toISOString()} ${line}`)
}
function check(ok: boolean, what: string): void {
log(`${ok ? 'PASS' : 'FAIL'} ${what}`)
if (!ok) {
failures.push(what)
}
}
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
async function exec(vm: Vm, script: string, timeoutMs = 120_000): Promise<string> {
const r = await vercel().runCommand(vm.vsession, { command: 'bash', args: ['-lc', script], timeoutMs })
if (r.exitCode !== 0) {
throw new Error(`VM command exited ${r.exitCode}: ${r.stderr.slice(-1500)}`)
}
return r.stdout
}
/** Every file in the repo except .git and .claude, with its content, as the user sees it. */
async function files(vm: Vm): Promise<Files> {
const out = await exec(
vm,
`cd ${REPO} && find . \\( -name .git -o -name .claude \\) -prune -o -type f -print | sort | while read -r f; do printf '%s\\t%s\\n' "\${f#./}" "$(base64 -w0 < "$f")"; done`
)
const result: Files = {}
for (const line of out.split('\n').filter(Boolean)) {
const [name, b64] = line.split('\t')
result[name!] = Buffer.from(b64 ?? '', 'base64').toString('utf8')
}
return result
}
const refs = async (vm: Vm) =>
(await exec(vm, `cd ${REPO} && git for-each-ref --format='%(refname) %(objectname)' refs/orca/`)).trim().split('\n').filter(Boolean)
const turnRefs = async (vm: Vm) => (await refs(vm)).filter((ref) => ref.includes('/turn/'))
/** HEAD, staged paths, stash count: what checkpoints must never touch. */
const userGit = (vm: Vm) =>
exec(vm, `cd ${REPO} && git rev-parse HEAD && git diff --cached --name-only && git stash list | wc -l`).then((s) => s.trim())
/** The desktop's own paired request connection and client capabilities (E2EE WebSocket to orcad). */
function connect(vm: Vm) {
const offer = parsePairingCode(vm.pairingCode)
if (!offer) {
throw new Error('the control plane returned an unreadable pairing code')
}
const connection = new RemoteRuntimeRequestConnection(
pairedRuntimeConnectionFromOffer(offer),
ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES
)
const raw = async <T>(method: string, params: unknown, timeoutMs = 60_000) => {
const response = await connection.request<T>(method, params, timeoutMs)
if (response.ok === false) {
throw new Error(`${method}: ${response.error.message} ${JSON.stringify(response.error.data ?? null)}`)
}
return response
}
const call = async <T>(method: string, params: unknown, timeoutMs?: number) => (await raw<T>(method, params, timeoutMs)).result
return { raw, call, close: () => connection.close() }
}
type Client = ReturnType<typeof connect>
const tail = (client: Client, sessionId: string) =>
client.call<AgentSessionHistoryResult>('agentSession.history', { sessionId, direction: 'tail', limit: 200 })
async function startStandin(vm: Vm): Promise<void> {
const source = readFileSync(STANDIN).toString('base64')
await exec(vm, `echo ${source} | base64 -d > /tmp/standin.py; pkill -f '^python3 /tmp/standin[.]py' || true`)
// Detached: a runCommand's process tree ends with the call.
await vercel().startCommand(vm.vsession, { command: 'python3', args: ['/tmp/standin.py'], timeoutMs: 30 * 60_000 })
const code = await exec(
vm,
`for i in $(seq 1 20); do c=$(curl -s --noproxy '*' -o /dev/null -w '%{http_code}' http://127.0.0.1:8998/v1/models); [ "$c" = 200 ] && break; sleep 0.5; done; echo $c`
)
if (code.trim() !== '200') {
throw new Error(`stand-in model server did not start (${code.trim()})`)
}
}
async function lifecycle(vm: Vm, action: 'resume' | 'rollover' | 'restart'): Promise<void> {
const t0 = performance.now()
const r = await control.as(who, 'POST', `/v1/sandboxes/${vm.id}/${action}`)
if (r.status !== 200) {
throw new Error(`${action} -> ${r.status} ${JSON.stringify(r.body).slice(0, 400)}`)
}
timings[action] = since(t0)
vm.vsession = r.body.sandbox.session.id
vm.pairingCode = r.body.connection.pairingCode
log(`${action}: 200 in ${timings[action]} ms`)
await startStandin(vm)
}
const TURNS: Record<string, string> = {
A: "printf 'one\\n' > feature.txt",
B: "printf 'v2\\n' > app.txt && rm feature.txt && mkdir -p notes && printf 'later\\n' > notes/todo.txt",
C: "printf 'three\\n' > three.txt && printf 'v3\\n' > app.txt",
D: "printf 'after-rewind\\n' > d.txt",
E: "printf 'e\\n' > e.txt"
}
type Turn = { itemId: string; before: Files; after: Files }
/** Sends one message and waits until the agent replied and the chat has gone quiet. */
async function turn(vm: Vm, client: Client, sessionId: string, name: string): Promise<Turn> {
const before = await files(vm)
const refsBefore = (await turnRefs(vm)).length
const clientOperationId = createStructuredAgentSessionOperationId(randomUUID)
const page = (await tail(client, sessionId)).page
await client.call(
'agentSession.send',
structuredAgentSessionMessageSendMutation({
sessionId,
clientOperationId,
expectedRuntimeFence: page.fence ?? 0,
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: `Turn ${name}. RUN: ${TURNS[name]}` }] },
delivery: 'queue-if-active'
}),
120_000
)
const itemId = agentJournalSubmissionKey(clientOperationId)
let last = -1
let quiet = 0
for (let i = 0; i < 150; i++) {
await sleep(2000)
const items = (await tail(client, sessionId)).page.items
const index = items.findIndex((item) => item.itemId === itemId)
const replied =
index !== -1 && items.slice(index + 1).some((item) => item.body.kind === 'message' && item.body.role === 'assistant')
const newest = items.at(-1)?.sequence ?? -1
quiet = newest === last ? quiet + 1 : 0
last = newest
if (replied && quiet >= 3) {
break
}
}
const after = await files(vm)
check((await turnRefs(vm)).length === refsBefore + 1, `turn ${name} wrote one checkpoint ref (${refsBefore} -> ${refsBefore + 1})`)
check(!same(before, after), `turn ${name}: the agent changed files`)
return { itemId, before, after }
}
/** The "Turn X." markers in the context of the model request that ran this turn's command. */
async function modelContext(vm: Vm, name: string): Promise<string> {
const lines = (await exec(vm, 'cat /tmp/standin.log')).split('\n')
const line = lines.reverse().find((l) => l.includes(`-> tool ${TURNS[name]!.slice(0, 40)}`))
return /context=(\[[^\]]*\])/.exec(line ?? '')?.[1] ?? 'none'
}
async function rewindAndRestore(vm: Vm, client: Client, sessionId: string, name: string, t: Turn, undo: boolean) {
const items = (await tail(client, sessionId)).page.items
check(items.some((item) => item.itemId === t.itemId), `fresh connection: turn ${name}'s message is in the chat (${items.length} items)`)
let t0 = performance.now()
const preview = await client.call<AgentSessionCheckpointPreview>('agentSession.checkpointPreview', { sessionId, itemId: t.itemId })
timings[`preview${name}`] = since(t0)
log(`preview ${name}: ${JSON.stringify(preview)}`)
check(preview.available && !preview.busy && !preview.headMoved, `turn ${name} has a restorable checkpoint`)
const filesBefore = await files(vm)
// As the UI does: rewind the chat first, then restore the files.
let rewound = ''
for (let i = 0; i < 40 && !rewound.includes('"ok":true'); i++) {
const page = (await tail(client, sessionId)).page
const fields = { itemId: t.itemId, expectedEpoch: page.epoch }
const response = await client.raw('agentSession.rewind', {
...fields,
envelope: {
sessionId,
clientOperationId: createStructuredAgentSessionOperationId(randomUUID),
expectedRuntimeFence: page.fence,
payloadFingerprint: structuredAgentSessionPayloadFingerprint({ method: 'agentSession.rewind', sessionId, fields })
}
}, 200_000)
rewound = JSON.stringify(response.result)
if (!rewound.includes('"ok":true')) {
await sleep(5000)
}
}
const after = (await tail(client, sessionId)).page.items
check(
rewound.includes('"ok":true') && !after.some((item) => item.itemId === t.itemId),
`rewind ${name}: the chat drops the message and everything after it (${items.length} -> ${after.length} items)`
)
let restored: AgentSessionCheckpointRestoreResult | undefined
t0 = performance.now()
for (let i = 0; i < 30 && !restored; i++) {
try {
restored = await client.call<AgentSessionCheckpointRestoreResult>('agentSession.checkpointRestore', { sessionId, itemId: t.itemId }, 120_000)
} catch (error) {
if (!String(error).includes('busy')) {
throw error
}
await sleep(2000)
}
}
timings[`restore${name}`] = since(t0)
const now = await files(vm)
check(same(now, t.before), `restore ${name}: files are exactly as when turn ${name} was sent (${restored?.changedFiles} changed)`)
if (undo && restored) {
t0 = performance.now()
await client.call('agentSession.checkpointUndo', { sessionId, undoId: restored.undoId }, 120_000)
timings[`undo${name}`] = since(t0)
check(same(await files(vm), filesBefore), `undo ${name}: the agent's later edits are back`)
}
}
async function main(): Promise<void> {
let t0 = performance.now()
const created = await control.as(who, 'POST', '/v1/sandboxes', { machineSize: 'standard', workspaceId: 'ckvm' })
if (created.status !== 200) {
throw new Error(`create -> ${created.status} ${JSON.stringify(created.body)}`)
}
timings.create = since(t0)
const vm: Vm = {
id: created.body.sandbox.id,
vsession: created.body.sandbox.session.id,
pairingCode: created.body.connection.pairingCode
}
log(`create: ${vm.id} (${who.sub}) in ${timings.create} ms, region ${created.body.sandbox.region}`)
try {
await startStandin(vm)
const settingsEnv = Buffer.from(JSON.stringify({
ANTHROPIC_BASE_URL: 'http://127.0.0.1:8998',
ANTHROPIC_AUTH_TOKEN: 'standin-no-cost',
ANTHROPIC_API_KEY: '',
ANTHROPIC_MODEL: MODEL,
ANTHROPIC_SMALL_FAST_MODEL: MODEL,
ANTHROPIC_DEFAULT_HAIKU_MODEL: MODEL,
NO_PROXY: '127.0.0.1,localhost',
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1'
})).toString('base64')
// Claude Code applies settings.json env over its inherited env: its model is the stand-in.
const setup = await exec(vm, `set -e
f="$HOME/.claude/settings.json"; mkdir -p "$(dirname "$f")"; [ -f "$f" ] || echo '{}' > "$f"
python3 -c 'import json,sys,base64; f=sys.argv[1]; d=json.load(open(f)); d.setdefault("env",{}).update(json.loads(base64.b64decode(sys.argv[2]))); json.dump(d,open(f,"w"))' "$f" ${settingsEnv}
claude --version; cat /opt/orca/runtime/orcad/SOURCE_COMMIT
rm -rf ${REPO}; mkdir -p ${REPO}; cd ${REPO}; git init -q; git config user.name E2E; git config user.email e2e@example.test
printf 'build/\\n' > .gitignore; printf 'v0\\n' > app.txt; git add .; git -c commit.gpgsign=false commit -qm base
printf 'staged by the user\\n' > staged.txt; git add staged.txt`)
log(`VM: ${setup.trim().replace(/\n/g, ', ')}`)
const gitAtStart = await userGit(vm)
let client = connect(vm)
const added = await client.call<{ repo: { id: string } }>('repo.add', { path: REPO })
let worktreeId = ''
for (let i = 0; i < 30 && !worktreeId; i++) {
worktreeId = (await client.call<{ worktrees: { id: string }[] }>('worktree.list', { repo: `id:${added.repo.id}` })).worktrees[0]?.id ?? ''
if (!worktreeId) {
await sleep(1000)
}
}
const sessionId = createStructuredAgentSessionId('claude', randomUUID)
await client.call('agentSession.create', structuredAgentSessionCreateParams({
sessionId,
worktree: `id:${worktreeId}`,
agent: 'claude',
options: { permissionMode: 'full-access' },
randomUuid: randomUUID
}))
for (let i = 0; i < 60 && !(await tail(client, sessionId)).page.fence; i++) {
await sleep(2000)
}
const runtimeAtStart = (await client.raw('agentSession.history', { sessionId, direction: 'tail', limit: 1 }))._meta.runtimeId
// 1. One checkpoint per turn; the user's git state untouched.
const turns: Record<string, Turn> = {}
for (const name of ['A', 'B', 'C']) {
turns[name] = await turn(vm, client, sessionId, name)
}
check((await userGit(vm)) === gitAtStart, 'HEAD, staged files and stash list unchanged by snapshots')
client.close()
// 2. Sleep and wake, then a fresh connection (a restarted desktop) rewinds to B and restores.
const refsBeforeSleep = await refs(vm)
const filesBeforeSleep = await files(vm)
t0 = performance.now()
const suspended = await control.as(who, 'POST', `/v1/sandboxes/${vm.id}/suspend`)
timings.suspend = since(t0)
check(suspended.status === 200 && suspended.body.sandbox.status === 'suspended', `suspend -> ${suspended.body?.sandbox?.status} in ${timings.suspend} ms`)
await lifecycle(vm, 'resume')
check(same(await refs(vm), refsBeforeSleep), `after sleep and wake: all ${refsBeforeSleep.length} checkpoint refs are unchanged`)
check(same(await files(vm), filesBeforeSleep), 'after sleep and wake: files unchanged')
client = connect(vm)
await rewindAndRestore(vm, client, sessionId, 'B', turns.B!, true)
check((await userGit(vm)) === gitAtStart, 'after restore and undo: HEAD, staged files and stash list unchanged')
client.close()
// 3. Rollover: refs survive a new host; a new turn checkpoints; the agent only sees A and D.
const refsBeforeRollover = await refs(vm)
await lifecycle(vm, 'rollover')
check(same(await refs(vm), refsBeforeRollover), `after rollover: all ${refsBeforeRollover.length} refs (turn and undo) are unchanged`)
client = connect(vm)
turns.D = await turn(vm, client, sessionId, 'D')
const contextD = await modelContext(vm, 'D')
check(contextD === "['A', 'D']", `after rewind to B, the agent's context holds only A and D (${contextD})`)
client.close()
// 4. Restart orcad, then a fresh connection rewinds to the first turn.
await lifecycle(vm, 'restart')
client = connect(vm)
const runtimeNow = (await client.raw('agentSession.history', { sessionId, direction: 'tail', limit: 1 }))._meta.runtimeId
check(runtimeNow !== runtimeAtStart, `orcad is a new process (runtime ${runtimeAtStart.slice(0, 8)} -> ${runtimeNow.slice(0, 8)})`)
await rewindAndRestore(vm, client, sessionId, 'A', turns.A!, false)
turns.E = await turn(vm, client, sessionId, 'E')
const contextE = await modelContext(vm, 'E')
check(contextE === "['E']", `after rewind to A, the agent's context holds only E (${contextE})`)
check((await userGit(vm)) === gitAtStart, 'end: HEAD, staged files and stash list unchanged')
client.close()
log(`refs at the end:\n${(await refs(vm)).join('\n')}`)
} finally {
if (keep) {
log(`--keep: ${vm.id} left running for ${who.sub}`)
} else {
const deleted = await control.as(who, 'DELETE', `/v1/sandboxes/${vm.id}`)
const listed = await control.as(who, 'GET', '/v1/sandboxes')
log(`delete ${vm.id}: ${deleted.status} ${deleted.body?.sandbox?.status}; sandboxes left: ${JSON.stringify(listed.body?.sandboxes?.map((s: { id: string; status: string }) => [s.id, s.status]) ?? [])}`)
}
}
}
main().then(
() => {
log(`timings (ms): ${JSON.stringify(timings)}`)
log(failures.length ? `FAILED ${failures.length}: ${failures.join('; ')}` : 'checkpoints-vm OK')
process.exit(failures.length ? 1 : 0)
},
(error: unknown) => {
console.error(error)
process.exit(1)
}
)
@@ -0,0 +1,96 @@
# No-cost stand-in for the Anthropic Messages API (checkpoints-vm.ts uploads it to the VM and runs it
# at 127.0.0.1:8998). Claude Code uses it as its model, so a chat turn is real Claude Code with real
# tools and no model spend:
# - a user message containing "RUN: <bash>" gets one Bash tool_use running that command;
# - a tool_result gets the text "DONE";
# - anything else (titles, side calls) gets a short text.
# Each request is logged to /tmp/standin.log with the "Turn X." markers in the model's context, which
# shows whether a rewind also rewound what the agent sees.
import http.server, json, re, time, uuid
LOG = '/tmp/standin.log'
def log(line):
with open(LOG, 'a') as f:
f.write(time.strftime('%H:%M:%S ') + line + '\n')
def texts(content):
if isinstance(content, str):
return [content]
return [b.get('text', '') for b in (content or []) if isinstance(b, dict) and b.get('type') == 'text']
def decide(body):
messages = body.get('messages') or []
if not body.get('tools') or not messages:
return ('text', 'ok')
content = messages[-1].get('content')
if isinstance(content, list) and any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in content):
return ('text', 'DONE')
for text in reversed(texts(content)):
if 'RUN:' in text:
return ('tool', text.split('RUN:', 1)[1].split('\n', 1)[0].strip())
return ('text', 'DONE')
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, *args):
pass
def reply(self, obj, content_type='application/json'):
data = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
self.send_response(200)
self.send_header('content-type', content_type)
self.send_header('content-length', str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
self.reply({'data': [], 'has_more': False})
def do_POST(self):
size = int(self.headers.get('content-length') or 0)
try:
body = json.loads(self.rfile.read(size) or b'{}')
except ValueError:
body = {}
if 'count_tokens' in self.path:
return self.reply({'input_tokens': 10})
kind, value = decide(body)
model = body.get('model', 'claude-standin')
messages = body.get('messages') or []
context = [t for m in messages for text in texts(m.get('content')) for t in re.findall(r'Turn ([A-Z])[.]', text)]
log(f'POST {self.path} tools={len(body.get("tools") or [])} msgs={len(messages)} context={context} -> {kind} {value[:160]}')
usage = {'input_tokens': 10, 'output_tokens': 5, 'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0}
if kind == 'tool':
block = {'type': 'tool_use', 'id': 'toolu_' + uuid.uuid4().hex[:20], 'name': 'Bash',
'input': {'command': value, 'description': 'Scripted edit'}}
stop = 'tool_use'
else:
block = {'type': 'text', 'text': value}
stop = 'end_turn'
message_id = 'msg_' + uuid.uuid4().hex[:20]
if not body.get('stream'):
return self.reply({'id': message_id, 'type': 'message', 'role': 'assistant', 'model': model, 'content': [block],
'stop_reason': stop, 'stop_sequence': None, 'usage': usage})
events = [('message_start', {'type': 'message_start', 'message': {
'id': message_id, 'type': 'message', 'role': 'assistant', 'model': model, 'content': [],
'stop_reason': None, 'stop_sequence': None, 'usage': usage}})]
if kind == 'tool':
events.append(('content_block_start', {'type': 'content_block_start', 'index': 0, 'content_block': {**block, 'input': {}}}))
events.append(('content_block_delta', {'type': 'content_block_delta', 'index': 0,
'delta': {'type': 'input_json_delta', 'partial_json': json.dumps(block['input'])}}))
else:
events.append(('content_block_start', {'type': 'content_block_start', 'index': 0, 'content_block': {'type': 'text', 'text': ''}}))
events.append(('content_block_delta', {'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': value}}))
events.append(('content_block_stop', {'type': 'content_block_stop', 'index': 0}))
events.append(('message_delta', {'type': 'message_delta', 'delta': {'stop_reason': stop, 'stop_sequence': None}, 'usage': {'output_tokens': 5}}))
events.append(('message_stop', {'type': 'message_stop'}))
self.reply(b''.join(f'event: {name}\ndata: {json.dumps(data)}\n\n'.encode() for name, data in events), 'text/event-stream')
http.server.ThreadingHTTPServer(('127.0.0.1', 8998), Handler).serve_forever()
+1
View File
@@ -49,6 +49,7 @@ export const CATALOG: Feature[] = [
{ id: 'life.read-asleep-access', section: S.life, feature: 'Read-while-asleep access control: removed member loses access at once (keys deleted), private workspace is owner-only', conductor: 'Org access to server-held chats', owner: 'gap-read-asleep', priority: 'P0', better: 'End-to-end encrypted; server holds only ciphertext' },
{ id: 'life.read-asleep-phone', section: S.life, feature: 'Phone shows "Latest from this workspace" for a sleeping workspace without waking it', conductor: 'iOS app reads server-held chats', owner: 'gap-read-asleep', priority: 'P1' },
{ id: 'local.checkpoints', section: S.acct, feature: 'Per-turn code checkpoints: revert restores files and chat together', conductor: '0.19 (Claude), 0.44 (Codex) checkpoints', owner: 'gap-checkpoints', priority: 'P0' },
{ id: 'cloud.checkpoints', section: S.life, feature: 'Per-turn checkpoints in a cloud workspace: Rewind restores files and chat on a real VM, after sleep/wake, rollover and an orcad restart (live/checkpoints-vm.ts, no model spend)', conductor: '0.19 (Claude), 0.44 (Codex) checkpoints in cloud', owner: 'checkpoints-vm', priority: 'P0' },
// 1. Substrate
{ id: 'sub.create', section: S.sub, feature: 'Hosted microVM per workspace, one call / one click', conductor: '0.78 GA', owner: 'core', priority: 'P0' },
{ id: 'sub.size', section: S.sub, feature: 'Machine size: Standard 8 vCPU / 16 GB (Conductor parity)', conductor: 'Fixed 8 vCPU / 16 GB', owner: 'core', priority: 'P0' },
+3 -2
View File
@@ -5,7 +5,7 @@
# Everything printed here streams live to the desktop build log.
#
# Env from the control plane (validated there): ORCA_BUILD_REPOS (`<url>|<branch or empty>|<dir>|
# <git auth header or empty>` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus
# <git auth header or empty>` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus
# the org secrets the environment names. `::orca-step:: <name>` lines mark progress.
# Exit codes: 10 clone, 20 install script, 30 recording the result.
set -uo pipefail
@@ -39,7 +39,8 @@ while IFS='|' read -r url branch dir header; do
echo "Cloning $url${branch:+ ($branch)}"
rm -rf -- "$dest"
# The clone's own error shows only when it really failed (an empty repo is recovered below).
if ! git "${git_auth[@]}" clone --quiet ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then
# ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.
if ! git "${git_auth[@]}" clone --quiet ${ORCA_CLONE_FILTER:+--filter="$ORCA_CLONE_FILTER"} ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then
refs=0
git "${git_auth[@]}" ls-remote --exit-code -- "$url" >/dev/null 2>&1 || refs=$?
if [ -n "$branch" ] && [ "$refs" -eq 2 ]; then
+55 -20
View File
@@ -68,9 +68,62 @@ clone_failure_reason() {
fi
}
# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target
# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have
# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.
update_repo() {
local base target status
base="$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null || true)"
target="${ref:-$base}"
[ -n "$target" ] || return 0
timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$target:refs/remotes/origin/$target"
status=$?
if [ "$status" -eq 0 ]; then
# -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.
git -C "$P" checkout --quiet -f -B "$target" "origin/$target" --
return $?
fi
[ "$status" -eq 124 ] && return 124
{ [ -n "$base" ] && [ "$base" != "$target" ]; } || return "$status"
timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$base:refs/remotes/origin/$base" || return $?
git -C "$P" checkout --quiet -f -B "$target" "origin/$base" --
}
# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command
# returns while it runs; $CLONE_DIR/state reads running, then done or "failed <reason>".
run_detached() {
echo running >"$CLONE_DIR/state"
: >"$CLONE_DIR/progress.log"
export -f clone_repo update_repo first_commit clone_failure_reason
export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref
export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}" ORCA_PRELUDE_STEP="$1"
setsid bash -c '
auth=()
[ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH")
unset ORCA_PRELUDE_AUTH
"$ORCA_PRELUDE_STEP" >>"$CLONE_DIR/progress.log" 2>&1
status=$?
if [ "$status" -eq 0 ]; then
echo done >"$CLONE_DIR/state.next"
elif [ "$ORCA_PRELUDE_STEP" = update_repo ]; then
# Not fatal: the build'"'"'s checkout is there, just older. The status says so; the create goes on.
echo "done stale" >"$CLONE_DIR/state.next"
else
echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next"
fi
mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state"
' </dev/null >/dev/null 2>&1 &
}
if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REPO_DIR/.git" ]; then
ln -s "$ROOT/$ORCA_ENV_REPO_DIR" "$P"
if [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then
if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then
# The desktop shows this as "Update repository" (GET /v1/sandboxes/:id/clone): fetch what changed
# since the build, in the background. A failure leaves the build's commit, which still opens.
mkdir -p "$CLONE_DIR"
run_detached update_repo
elif [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then
if timeout 60 git "${auth[@]}" -C "$P" fetch --quiet origin "+refs/heads/$ref:refs/remotes/origin/$ref"; then
# -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.
git -C "$P" checkout --quiet -f -B "$ref" "origin/$ref" -- ||
@@ -83,25 +136,7 @@ if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REP
elif [ ! -e "$P" ] && [ -n "${ORCA_REPO_URL:-}" ]; then
mkdir -p "$P" "$CLONE_DIR"
if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then
echo running >"$CLONE_DIR/state"
: >"$CLONE_DIR/progress.log"
# Detached (own session, no inherited stdio): the start command returns while this runs.
export -f clone_repo first_commit clone_failure_reason
export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref
export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}"
setsid bash -c '
auth=()
[ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH")
unset ORCA_PRELUDE_AUTH
clone_repo >>"$CLONE_DIR/progress.log" 2>&1
status=$?
if [ "$status" -eq 0 ]; then
echo done >"$CLONE_DIR/state.next"
else
echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next"
fi
mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state"
' </dev/null >/dev/null 2>&1 &
run_detached clone_repo
else
clone_repo 2>"$CLONE_DIR/progress.log" || exit 1
fi
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
-- Automatic environments (src/auto-environments.ts): the first create of a repo that no environment
-- lists makes a default environment for it (just the repo) and builds it in the background, so later
-- creates boot with the repo already checked out. 'org' rows are made or edited by an admin; 'auto' rows
-- were made by the system and are deleted after 14 days without a create (an admin's edit makes them 'org').
ALTER TABLE environments ADD COLUMN kind TEXT NOT NULL DEFAULT 'org';
-- Last create that booted from this environment (or asked for one for its repo).
ALTER TABLE environments ADD COLUMN last_used_at INTEGER;
CREATE INDEX environments_kind ON environments (kind, deleted_at);
@@ -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);
@@ -0,0 +1,15 @@
-- Files uploaded through the public API / MCP for an agent to read (G10 attachments). The bytes live
-- on the workspace's own disk (/vercel/sandbox/attachments/<id>/<filename>, outside the repo); this
-- row lets a message reference the file by id. Additive only.
CREATE TABLE IF NOT EXISTS workspace_attachments (
id TEXT PRIMARY KEY,
sandbox_id TEXT NOT NULL,
account_id TEXT NOT NULL,
uploaded_by TEXT NOT NULL,
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
byte_size INTEGER NOT NULL,
path TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS workspace_attachments_sandbox ON workspace_attachments (sandbox_id, created_at);
@@ -0,0 +1,164 @@
// Files for an agent to read (POST /v1/workspaces/:id/attachments, MCP upload_attachment). The
// bytes go straight onto the workspace's own disk through the provider's files API, outside the
// repo so they never show up in git status; D1 keeps only the metadata a message references.
import { z } from 'zod'
import { ApiError } from './caller'
import { randomId } from './keys'
export const ATTACHMENTS_ROOT = '/vercel/sandbox/attachments'
/** Raw uploads (curl --data-binary). Workers buffer the body, so this stays well under memory. */
export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
/** JSON uploads carry base64 (MCP tool calls): the MCP request cap bounds them. */
export const MAX_JSON_ATTACHMENT_BYTES = 5 * 1024 * 1024
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
export type AttachmentRow = {
id: string
sandbox_id: string
account_id: string
uploaded_by: string
filename: string
content_type: string
byte_size: number
path: string
created_at: number
}
export function attachmentView(row: AttachmentRow) {
return {
id: row.id,
workspaceId: row.sandbox_id,
filename: row.filename,
contentType: row.content_type,
byteSize: row.byte_size,
path: row.path,
createdAt: row.created_at
}
}
/** A name safe for one path segment: ASCII letters, digits, `._-` and spaces; never hidden, never empty. */
export function safeFilename(raw: string): string {
const base = raw.split(/[\\/]/).at(-1) ?? ''
const cleaned = base
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^A-Za-z0-9._ -]/g, '_')
.replace(/^[.\s]+/, '')
.trim()
const capped = cleaned.length > 100 ? `${cleaned.slice(0, 80)}${cleaned.slice(cleaned.lastIndexOf('.')).slice(0, 20)}` : cleaned
return capped || 'file'
}
const ContentType = z.string().trim().min(3).max(127).regex(/^[\w.+-]+\/[\w.+-]+$/)
const JsonUpload = z
.object({
filename: z.string().min(1).max(255),
contentType: ContentType.optional(),
/** Base64 (standard or url-safe) file bytes. */
data: z.string().min(1).max(Math.ceil((MAX_JSON_ATTACHMENT_BYTES * 4) / 3) + 4)
})
.strict()
function decodeBase64(data: string): Uint8Array {
const normal = data.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normal)) {
throw new ApiError(400, 'invalid_request', 'data: not base64')
}
const binary = atob(normal)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
}
/**
* Reads an upload: JSON `{filename, contentType?, data}` (base64), or the raw bytes with
* `?filename=` and the file's own Content-Type.
*/
export async function readUpload(request: Request, url: URL): Promise<{ filename: string; contentType: string; bytes: Uint8Array }> {
const declared = (request.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase()
const length = Number(request.headers.get('content-length') ?? NaN)
if (declared === 'application/json') {
if (length > MAX_JSON_ATTACHMENT_BYTES * 1.4) {
throw new ApiError(413, 'too_large', `max ${MAX_JSON_ATTACHMENT_BYTES} bytes as JSON; upload larger files raw`)
}
const parsed = JsonUpload.safeParse(JSON.parse(await request.text()))
if (!parsed.success) {
const issue = parsed.error.issues[0]
throw new ApiError(400, 'invalid_request', issue ? `${issue.path.join('.') || 'body'}: ${issue.message}` : undefined)
}
const bytes = decodeBase64(parsed.data.data)
if (bytes.length > MAX_JSON_ATTACHMENT_BYTES) {
throw new ApiError(413, 'too_large', `max ${MAX_JSON_ATTACHMENT_BYTES} bytes as JSON; upload larger files raw`)
}
return { filename: parsed.data.filename, contentType: parsed.data.contentType ?? 'application/octet-stream', bytes }
}
const filename = url.searchParams.get('filename')
if (!filename || filename.length > 255) {
throw new ApiError(400, 'invalid_request', 'filename: required query parameter for raw uploads')
}
if (length > MAX_ATTACHMENT_BYTES) {
throw new ApiError(413, 'too_large', `max ${MAX_ATTACHMENT_BYTES} bytes`)
}
const bytes = new Uint8Array(await request.arrayBuffer())
if (bytes.length > MAX_ATTACHMENT_BYTES) {
throw new ApiError(413, 'too_large', `max ${MAX_ATTACHMENT_BYTES} bytes`)
}
const contentType = ContentType.safeParse(declared)
return { filename, contentType: contentType.success ? contentType.data : 'application/octet-stream', bytes }
}
export function newAttachment(input: { sandboxId: string; accountId: string; uploadedBy: string; filename: string; contentType: string; byteSize: number }, now: number): AttachmentRow {
const id = randomId('att')
const filename = safeFilename(input.filename)
return {
id,
sandbox_id: input.sandboxId,
account_id: input.accountId,
uploaded_by: input.uploadedBy,
filename,
content_type: input.contentType,
byte_size: input.byteSize,
path: `${ATTACHMENTS_ROOT}/${id}/${filename}`,
created_at: now
}
}
export async function insertAttachment(db: D1Database, row: AttachmentRow): Promise<void> {
await db
.prepare(
`INSERT INTO workspace_attachments (id, sandbox_id, account_id, uploaded_by, filename, content_type, byte_size, path, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
)
.bind(row.id, row.sandbox_id, row.account_id, row.uploaded_by, row.filename, row.content_type, row.byte_size, row.path, row.created_at)
.run()
}
/** The named attachments of this workspace, in the order given; 400 if any is unknown or elsewhere. */
export async function resolveAttachments(db: D1Database, sandboxId: string, ids: readonly string[]): Promise<AttachmentRow[]> {
if (ids.length === 0) {
return []
}
const unique = [...new Set(ids)]
const { results } = await db
.prepare(`SELECT * FROM workspace_attachments WHERE sandbox_id = ? AND id IN (${unique.map(() => '?').join(', ')})`)
.bind(sandboxId, ...unique)
.all<AttachmentRow>()
const byId = new Map(results.map((row) => [row.id, row]))
const missing = unique.filter((id) => !byId.has(id))
if (missing.length > 0) {
throw new ApiError(400, 'invalid_request', `attachments: unknown in this workspace: ${missing.join(',').slice(0, 200)}`)
}
return unique.map((id) => byId.get(id)!)
}
/** The message text an agent gets: the user's words, then where each attached file is on disk. */
export function withAttachmentPaths(text: string, attachments: readonly AttachmentRow[]): string {
if (attachments.length === 0) {
return text
}
const lines = attachments.map((row) => `- ${row.path} (${row.content_type}, ${row.byte_size} bytes)`)
return `${text}\n\nAttached files (read them from disk):\n${lines.join('\n')}`
}
+13 -9
View File
@@ -109,6 +109,18 @@ async function settle(
.run()
}
/**
* What the agent is typed: a teammate's message names its sender (W4: agents address them and
* commit as them via `orca-git-as`); nobody can type a leading envelope to impersonate someone else.
*/
export async function agentText(db: D1Database, workspace: { user_id: string; account_id: string }, sentBy: string, body: string): Promise<string> {
if (sentBy === workspace.user_id) {
return parseSenderEnvelope(body).body
}
const name = (await memberNamesFor(db, workspace.account_id, [sentBy])).get(sentBy) ?? sentBy
return withSenderEnvelope(body, { userId: sentBy, name })
}
/**
* Delivers one queued message: wakes the workspace if needed, then continues the named session or
* starts a new agent session with the text as its first prompt.
@@ -127,15 +139,7 @@ export async function deliverMessage(life: LifecycleDeps, message: MessageRow):
row = (await resumeSandbox(life, row)).row
}
const sessionId = row.session_id!
// A teammate's message names its sender (W4: agents address them and commit as them via
// `orca-git-as`); nobody can type a leading envelope to impersonate someone else.
const text =
message.sent_by === row.user_id
? parseSenderEnvelope(message.body).body
: withSenderEnvelope(message.body, {
userId: message.sent_by,
name: (await memberNamesFor(life.db, message.account_id, [message.sent_by])).get(message.sent_by) ?? message.sent_by
})
const text = await agentText(life.db, row, message.sent_by, message.body)
let handle: string
if (message.session_handle) {
await sendToSession(life.provider, sessionId, message.session_handle, text)
@@ -0,0 +1,77 @@
// GET /v1/models (MCP list_models): the agents a cloud workspace runs and the models/efforts each
// accepts. Built from the same seed catalogs the desktop's model picker uses, so the two never
// disagree; the VM's own CLI may know newer models, which session create also accepts.
import {
CLAUDE_SESSION_OPTION_CATALOG,
CODEX_SESSION_OPTION_CATALOG
} from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-claude-codex'
import {
CURSOR_SESSION_OPTION_CATALOG,
GEMINI_SESSION_OPTION_CATALOG
} from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-gemini-cursor'
import { OPENCODE_LAUNCH_OPTION_CATALOG } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-opencode'
import type { AgentSessionOptionCatalog, CatalogModel } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types'
import { AGENTS, type AgentId } from './vm-agent'
const LABELS: Record<AgentId, string> = {
claude: 'Claude Code',
codex: 'Codex',
opencode: 'OpenCode',
gemini: 'Gemini CLI',
cursor: 'Cursor',
copilot: 'GitHub Copilot'
}
const CATALOGS: Partial<Record<AgentId, AgentSessionOptionCatalog>> = {
claude: CLAUDE_SESSION_OPTION_CATALOG,
codex: CODEX_SESSION_OPTION_CATALOG,
gemini: GEMINI_SESSION_OPTION_CATALOG,
cursor: CURSOR_SESSION_OPTION_CATALOG,
opencode: OPENCODE_LAUNCH_OPTION_CATALOG
}
/** Model ids travel as one argv entry (`--model=<id>`); this keeps them to what agent CLIs use. */
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,127}$/
export const EFFORT_ID = /^[a-z]{2,16}$/
function modelView(model: CatalogModel) {
const effort = model.options.find((option) => option.id === 'effort')
const efforts = effort?.kind.type === 'select' ? effort.kind.choices.map((choice) => String(choice.value)) : []
return {
id: model.id,
label: model.label,
description: model.description ?? null,
default: model.isDefault === true,
efforts,
defaultEffort: effort?.kind.type === 'select' ? effort.kind.defaultValue : null,
fastMode: model.options.some((option) => option.id === 'fastMode' || option.id === 'serviceTier')
}
}
export type ModelsView = ReturnType<typeof modelsView>
export function modelsView() {
return {
agents: AGENTS.map((agent) => {
const models = (CATALOGS[agent]?.models ?? []).map(modelView)
return {
id: agent,
label: LABELS[agent],
default: agent === 'claude',
// Null: the agent's own default (its CLI picks; nothing is passed).
defaultModel: models.find((model) => model.default)?.id ?? null,
models
}
})
}
}
/** The efforts the catalog lists for this agent's model, or null when it lists none (any is passed through). */
export function knownEfforts(agent: AgentId, model: string): string[] | null {
const found = CATALOGS[agent]?.models.find((candidate) => candidate.id === model)
if (!found) {
return null
}
const efforts = modelView(found).efforts
return efforts.length > 0 ? efforts : []
}
+150 -3
View File
@@ -99,6 +99,53 @@ const schemas: Record<string, object> = {
preview: { type: ['string', 'null'], description: 'Last few lines of the session' }
}
},
NewSession: {
type: 'object',
properties: {
handle: { type: 'string', description: 'Session handle (term_…): pass as `session` to send_message' },
workspaceId: { type: 'string' },
agent: { type: 'string', enum: [...AGENTS] },
model: { type: ['string', 'null'] },
effort: { type: ['string', 'null'] },
name: { type: ['string', 'null'] }
}
},
Attachment: {
type: 'object',
properties: {
id: { type: 'string', description: 'att_… — pass in a message\'s `attachments`' },
workspaceId: { type: 'string' },
filename: { type: 'string', description: 'Sanitized file name' },
contentType: { type: 'string' },
byteSize: { type: 'integer' },
path: { type: 'string', description: 'Where the file is on the workspace disk (outside the repo)' },
createdAt: { type: 'integer' }
}
},
AgentModels: {
type: 'object',
properties: {
id: { type: 'string', enum: [...AGENTS] },
label: { type: 'string' },
default: { type: 'boolean', description: 'The agent used when none is given' },
defaultModel: { type: ['string', 'null'], description: "Null: the agent CLI's own default" },
models: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
label: { type: 'string' },
description: { type: ['string', 'null'] },
default: { type: 'boolean' },
efforts: { type: 'array', items: { type: 'string' }, description: 'Values for `effort`; empty when the model takes none' },
defaultEffort: { type: ['string', 'null'] },
fastMode: { type: 'boolean' }
}
}
}
}
},
Routine: {
type: 'object',
properties: {
@@ -213,6 +260,14 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
'/v1/me': {
get: { tags: ['Account'], summary: 'Who the token acts as', responses: { 200: { description: 'Caller', schema: obj({ accountId: { type: 'string' }, userId: { type: 'string' }, role: { type: 'string' }, scopes: { type: 'array', items: { type: 'string' } } }) } } }
},
'/v1/models': {
get: {
tags: ['Agents'],
summary: 'Agents and models a session can run',
description: 'Every agent CLI a cloud workspace ships, with the models, effort levels, defaults and fast-mode support the model picker knows. Pass `agent`, `model` and `effort` when creating a session. A model id newer than this list is passed to the agent CLI as is.',
responses: { 200: { description: 'Agents', schema: obj({ agents: { type: 'array', items: ref('AgentModels') } }) } }
}
},
'/v1/api-keys': {
get: { tags: ['API keys'], sessionOnly: true, summary: 'List Orca API keys', description: 'Owners and admins see every key on the team; members see their own.', responses: { 200: { description: 'Keys', schema: list('keys', 'ApiKey') } } },
post: {
@@ -341,6 +396,39 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
'/v1/workspaces/{id}/archive': {
post: { tags: ['Workspaces'], scope: 'workspaces:write', summary: 'Archive: sleep and hide from default lists', params: [WS], responses: { 200: { description: 'Archived', schema: one('workspace', 'Workspace') } } }
},
'/v1/workspaces/{id}/unarchive': {
post: {
tags: ['Workspaces'],
scope: 'workspaces:write',
summary: 'Unarchive: back in default lists and running again',
description: 'Owner only. Idempotent: a workspace that is not archived is returned unchanged.',
params: [WS],
responses: { 200: { description: 'Running', schema: one('workspace', 'Workspace') } }
}
},
'/v1/workspaces/{id}/rename': {
post: {
tags: ['Workspaces'],
scope: 'workspaces:write',
summary: 'Rename a workspace',
description: 'Changes the display name everywhere (desktop Home, phone, API). The git branch is not renamed.',
params: [WS],
body: obj({ name: { type: 'string', minLength: 1, maxLength: 100 } }, ['name']),
responses: { 200: { description: 'Renamed', schema: one('workspace', 'Workspace') } }
}
},
'/v1/workspaces/{id}/attachments': {
post: {
tags: ['Agents'],
scope: 'messages:write',
summary: 'Upload a file for an agent',
description:
'Puts a file on the workspace disk (outside the repo) and returns its id; pass up to 10 ids as `attachments` when sending a message or creating a session, and the agent is told where each file is. Send the raw bytes (`--data-binary @file`, the file\'s Content-Type, `?filename=`; up to 25 MB) or JSON `{filename, contentType, data}` with base64 data (up to 5 MB, what MCP clients use). A sleeping workspace is woken first.',
params: [WS, { name: 'filename', in: 'query', description: 'File name, for raw uploads', schema: { type: 'string' } }],
body: obj({ filename: { type: 'string' }, contentType: { type: 'string' }, data: { type: 'string', contentEncoding: 'base64' } }, ['filename', 'data']),
responses: { 201: { description: 'Uploaded', schema: one('attachment', 'Attachment') }, 413: 'File too large' }
}
},
'/v1/workspaces/{id}/messages': {
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Recent messages sent to this workspace', params: [WS], responses: { 200: { description: 'Messages', schema: list('messages', 'Message') } } },
post: {
@@ -349,7 +437,15 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
summary: 'Send a message to an agent',
description: 'Queues the message and returns 202 at once. A sleeping workspace is woken first. Without `session` a new agent session starts with the text as its prompt; with `session` the text is typed into that session. Poll the message for `delivered`.',
params: [WS],
body: obj({ text: { type: 'string', maxLength: 32000 }, agent: { type: 'string', enum: [...AGENTS] }, session: { type: 'string' } }, ['text']),
body: obj(
{
text: { type: 'string', maxLength: 32000 },
agent: { type: 'string', enum: [...AGENTS] },
session: { type: 'string' },
attachments: { type: 'array', maxItems: 10, items: { type: 'string' }, description: 'Attachment ids from POST /attachments' }
},
['text']
),
responses: { 202: { description: 'Queued', schema: one('message', 'Message') } }
}
},
@@ -357,7 +453,50 @@ export const OPERATIONS: Record<string, Record<string, Op>> = {
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Delivery status of a message', params: [WS, idParam('messageId', 'Message id')], responses: { 200: { description: 'Message', schema: one('message', 'Message') } } }
},
'/v1/workspaces/{id}/sessions': {
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Agent sessions in a running workspace', params: [WS], responses: { 200: { description: 'Sessions (empty while sleeping)', schema: obj({ workspaceStatus: { type: 'string' }, sessions: { type: 'array', items: ref('Session') } }) } } }
get: { tags: ['Agents'], scope: 'workspaces:read', summary: 'Agent sessions in a running workspace', params: [WS], responses: { 200: { description: 'Sessions (empty while sleeping)', schema: obj({ workspaceStatus: { type: 'string' }, sessions: { type: 'array', items: ref('Session') } }) } } },
post: {
tags: ['Agents'],
scope: 'messages:write',
summary: 'Start a new agent session (a new chat)',
description:
'Starts another agent session in the workspace, waking it first if it sleeps, and returns its handle once the agent is up. Optional: `model` and `effort` (see GET /v1/models; a known model with an effort it does not take answers 400), `name`, and a first `message` with `attachments`. Without `message` the agent waits for send_message.',
params: [WS],
body: obj({
agent: { type: 'string', enum: [...AGENTS], default: 'claude' },
model: { type: 'string' },
effort: { type: 'string', description: 'Requires model' },
name: { type: 'string', maxLength: 100 },
message: { type: 'string', maxLength: 32000 },
attachments: { type: 'array', maxItems: 10, items: { type: 'string' }, description: 'Requires message' }
}),
responses: { 201: { description: 'Started', schema: one('session', 'NewSession') } }
}
},
'/v1/workspaces/{id}/sessions/{handle}/cancel': {
post: {
tags: ['Agents'],
scope: 'messages:write',
summary: "Stop the agent's current turn",
description: "Interrupts the running turn (an Escape, as a person would press) and drops this session's queued messages. Nothing is interrupted while the workspace sleeps; queued messages are still dropped.",
params: [WS, idParam('handle', 'Session handle (term_…)')],
responses: {
200: {
description: 'Canceled',
schema: obj({ workspaceId: { type: 'string' }, session: { type: 'string' }, interrupted: { type: 'boolean' }, canceledQueuedMessages: { type: 'integer' } })
}
}
}
},
'/v1/workspaces/{id}/sessions/{handle}/rename': {
post: {
tags: ['Agents'],
scope: 'messages:write',
summary: 'Rename an agent session',
description: 'Sets the session (tab) title the desktop and phone show. 409 while the workspace sleeps.',
params: [WS, idParam('handle', 'Session handle (term_…)')],
body: obj({ name: { type: 'string', minLength: 1, maxLength: 100 } }, ['name']),
responses: { 200: { description: 'Renamed', schema: obj({ session: obj({ handle: { type: 'string' }, workspaceId: { type: 'string' }, name: { type: 'string' } }) }) } }
}
},
'/v1/workspaces/{id}/sessions/{handle}': {
get: {
@@ -503,7 +642,15 @@ curl -X DELETE ${o}/v1/workspaces/$ID -H "Authorization: Bearer $ORCA_API_
<p>Point any MCP client at <code>${o}/mcp</code> (Streamable HTTP). Clients that support OAuth register themselves and open an approval page in the browser: approve with a one-time code from Orca → Settings → Orca API keys → <i>Approve an app</i>, or with one of your API keys. The app never gets more than that key may do. Clients without OAuth can send an API key as a bearer token.</p>
<pre>claude mcp add --transport http orca-cloud ${o}/mcp
claude mcp add --transport http orca-cloud ${o}/mcp --header "Authorization: Bearer $ORCA_API_KEY"</pre>
<p>Tools: whoami, list_projects, list_workspaces, get_workspace, create_workspace, sleep_workspace, wake_workspace, archive_workspace, destroy_workspace, send_message, get_message, list_sessions, read_session, list_routines, run_routine. They use the same scopes, rate limits and audit log as the REST API.</p>
<p>Tools: whoami, list_models, list_projects, list_workspaces, get_workspace, create_workspace, rename_workspace, sleep_workspace, wake_workspace, archive_workspace, unarchive_workspace, destroy_workspace, create_session, list_sessions, read_session, rename_session, cancel_session, upload_attachment, send_message, get_message, list_routines, run_routine. They use the same scopes, rate limits and audit log as the REST API.</p>
<p>There is no SQL search over transcripts. Chats are end-to-end encrypted on the workspace's own disk, so the control plane cannot read them to index. Use <code>read_session</code> to see what an agent did.</p>
<h2>New chat, files, stop</h2>
<pre>curl -s ${o}/v1/models -H "Authorization: Bearer $ORCA_API_KEY"
curl -s ${o}/v1/workspaces/$ID/attachments?filename=bug.png -H "Authorization: Bearer $ORCA_API_KEY" \\
-H 'content-type: image/png' --data-binary @bug.png
curl -s ${o}/v1/workspaces/$ID/sessions -H "Authorization: Bearer $ORCA_API_KEY" -H 'content-type: application/json' \\
-d '{"agent":"codex","model":"gpt-5.5","effort":"high","message":"Fix what the screenshot shows","attachments":["att_…"]}'
curl -X POST ${o}/v1/workspaces/$ID/sessions/$HANDLE/cancel -H "Authorization: Bearer $ORCA_API_KEY"</pre>
<h2>Limits and errors</h2>
<div class="grid">
<div class="card"><b>Rate limits</b>120 requests/min per key, 30 messages/min per user, 10 workspace creates/min per team. 429 responses carry <code>Retry-After</code>.</div>
+155 -8
View File
@@ -12,9 +12,20 @@ import { allowed, authorize, canSee, isOrgAdmin, isWorkspaceOwner } from './acce
import { ApiError, actorOf, authenticateApi, isAdmin, requireAdmin, requireScope, scopesForRole, type ApiCaller } from './caller'
import { auditCaller, auditView, consumeRate, listAudit, rateHeaders, RateLimitedError, type RateLimit } from './audit'
import { API_SCOPES, ADMIN_SCOPES, apiKeyView, getApiKey, listApiKeys, mintApiKey, revokeApiKey, type ApiScope } from './keys'
import { deliverMessage, getMessage, listMessages, MAX_MESSAGE_CHARS, messageView, queueMessage } from './messages'
import { agentText, deliverMessage, getMessage, listMessages, MAX_MESSAGE_CHARS, messageView, queueMessage } from './messages'
import { getAccountSettings, putAccountSettings } from './settings'
import { listSessions, readSession, VmAgentError } from './vm-agent'
import { interruptSession, launchAgent, listSessions, readSession, renameSession, VmAgentError } from './vm-agent'
import {
attachmentView,
insertAttachment,
MAX_ATTACHMENTS_PER_MESSAGE,
newAttachment,
readUpload,
resolveAttachments,
withAttachmentPaths
} from './attachments'
import { EFFORT_ID, knownEfforts, MODEL_ID, modelsView } from './models'
import { resumeSandbox } from '../lifecycle'
import {
archiveProject,
archiveWorkspace,
@@ -85,14 +96,32 @@ const CreateWorkspaceBody = z
message: z.object({ text: z.string().min(1).max(MAX_MESSAGE_CHARS), agent: z.enum(AGENTS).optional() }).strict().optional()
})
.strict()
const SessionHandle = z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/)
const AttachmentIds = z.array(z.string().regex(/^att_[A-Za-z0-9]{1,64}$/)).min(1).max(MAX_ATTACHMENTS_PER_MESSAGE)
const MessageBody = z
.object({
text: z.string().min(1).max(MAX_MESSAGE_CHARS),
agent: z.enum(AGENTS).optional(),
/** A session handle from GET /sessions or a previous message: continue that conversation. */
session: z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).optional()
session: SessionHandle.optional(),
/** Files uploaded with POST /attachments: their on-disk paths are appended for the agent. */
attachments: AttachmentIds.optional()
})
.strict()
const CreateSessionBody = z
.object({
agent: z.enum(AGENTS).optional(),
model: z.string().regex(MODEL_ID, 'a model id from GET /v1/models').optional(),
effort: z.string().regex(EFFORT_ID).optional(),
name: Name.optional(),
/** Optional first prompt; without it the agent starts idle and waits for send_message. */
message: z.string().min(1).max(MAX_MESSAGE_CHARS).optional(),
attachments: AttachmentIds.optional()
})
.strict()
.refine((body) => !body.effort || body.model, { message: 'effort requires model', path: ['effort'] })
.refine((body) => !body.attachments || body.message, { message: 'attachments require message', path: ['attachments'] })
const RenameBody = z.object({ name: Name }).strict()
function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
return Response.json(body, { status, headers: { 'cache-control': 'no-store', ...headers } })
@@ -152,7 +181,7 @@ import { parseWakeWait } from '../wire'
import { MachineSizeInput } from '../machine-size'
export function isApiPath(pathname: string): boolean {
return /^\/v1\/(me|api-keys|settings|audit|projects|workspaces|routines|oauth-approvals|oauth-grants)(\/|$)/.test(pathname)
return /^\/v1\/(me|models|api-keys|settings|audit|projects|workspaces|routines|oauth-approvals|oauth-grants)(\/|$)/.test(pathname)
}
export async function handleApi(request: Request, url: URL, env: Parameters<typeof authenticateApi>[0], ctx: ApiContext): Promise<Response> {
@@ -243,6 +272,11 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
})
}
if (resource === 'models' && !id && method === 'GET') {
// Static catalog, no account data: any authenticated caller may read it.
return json(modelsView())
}
if (resource === 'api-keys') {
if (caller.via !== 'session') {
// Keys are made and revoked by a signed-in person, never by another key.
@@ -435,7 +469,7 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
const life = () => requireLife(ctx)
const mutate = async (action: string, run: () => Promise<WorkspaceRow>) => {
requireScope(caller, 'workspaces:write')
authorize(caller, row, action === 'wake' ? 'owner' : 'manage')
authorize(caller, row, action === 'wake' || action === 'unarchive' ? 'owner' : 'manage')
if (caller.via === 'workspace' && row.id === caller.sandboxId) {
// An agent must not put its own VM to sleep or delete it from under itself.
throw new ApiError(403, 'forbidden', 'own_workspace')
@@ -477,6 +511,117 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
if (sub === 'archive' && method === 'POST') {
return mutate('archive', () => archiveWorkspace(life(), row))
}
if (sub === 'unarchive' && method === 'POST') {
if (row.status !== 'archived' && row.archived_at === null) {
// Idempotent: a retry after success (or a never-archived workspace) is not an error.
requireScope(caller, 'workspaces:write')
authorize(caller, row, 'owner')
return json({ workspace: workspaceView(row) })
}
// Back in default lists and running again (same path as waking an archived workspace).
return mutate('unarchive', () => wakeWorkspace(life(), row))
}
if (sub === 'rename' && method === 'POST') {
requireScope(caller, 'workspaces:write')
authorize(caller, row, 'manage')
const body = parse(RenameBody, await ctx.readJson())
await ctx.db.prepare('UPDATE sandboxes SET name = ? WHERE id = ?').bind(body.name, row.id).run()
await auditCaller(ctx.db, caller, { action: 'workspace.rename', targetType: 'workspace', targetId: row.id, detail: { chars: body.name.length } }, now)
return json({ workspace: workspaceView({ ...row, name: body.name }) })
}
// The agent's VM, woken if it sleeps (sessions and files need a running sandbox).
const runningSession = async (): Promise<string> => {
if (row.status === 'archived' || row.archived_at !== null) {
throw new ApiError(409, 'conflict', 'workspace_archived')
}
if (row.status === 'running' && row.session_id) {
return row.session_id
}
const ready = await resumeSandbox(life(), row)
return ready.row.session_id!
}
if (sub === 'sessions' && !subId && method === 'POST') {
// A new chat: start another agent session in this workspace (optionally with a first prompt).
requireScope(caller, 'messages:write')
authorize(caller, row, 'open')
const body = parse(CreateSessionBody, await ctx.readJson())
const agent = body.agent ?? 'claude'
if (body.model && body.effort) {
const efforts = knownEfforts(agent, body.model)
if (efforts && !efforts.includes(body.effort)) {
throw new ApiError(400, 'invalid_request', `effort: ${body.model} takes ${efforts.length ? efforts.join(', ') : 'no effort'}`)
}
}
if (body.message) {
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
}
const attachments = await resolveAttachments(ctx.db, row.id, body.attachments ?? [])
const started = performance.now()
const sessionId = await runningSession()
// A teammate's first prompt names its sender, exactly like a message (deliverMessage).
const prompt = body.message ? await agentText(ctx.db, row, caller.userId, withAttachmentPaths(body.message, attachments)) : null
const handle = await launchAgent(life().provider, sessionId, agent, prompt, { model: body.model, effort: body.effort })
if (body.name) {
await renameSession(life().provider, sessionId, handle, body.name)
}
await auditCaller(
ctx.db,
caller,
{ action: 'workspace.session.create', targetType: 'workspace', targetId: row.id, detail: { handle, agent, model: body.model ?? null, prompt: Boolean(prompt), attachments: attachments.length, ms: Math.round(performance.now() - started) } },
ctx.now()
)
return json({ session: { handle, workspaceId: row.id, agent, model: body.model ?? null, effort: body.effort ?? null, name: body.name ?? null } }, 201)
}
if (sub === 'sessions' && subId && parts[4] && method === 'POST') {
requireScope(caller, 'messages:write')
authorize(caller, row, 'open')
if (!SessionHandle.safeParse(subId).success) {
throw new ApiError(404, 'not_found')
}
if (parts[4] === 'cancel' && !parts[5]) {
// Queued messages for this session never get typed; the running turn gets an interrupt.
const dropped = await ctx.db
.prepare(`UPDATE workspace_messages SET status = 'failed', error = 'canceled', updated_at = ? WHERE sandbox_id = ? AND session_handle = ? AND status = 'queued'`)
.bind(now, row.id, subId)
.run()
const running = row.status === 'running' && row.session_id !== null
if (running) {
await interruptSession(life().provider, row.session_id!, subId)
}
const canceledQueuedMessages = dropped.meta.changes ?? 0
await auditCaller(ctx.db, caller, { action: 'workspace.session.cancel', targetType: 'workspace', targetId: row.id, detail: { handle: subId, interrupted: running, canceledQueuedMessages } }, ctx.now())
return json({ workspaceId: row.id, session: subId, interrupted: running, canceledQueuedMessages })
}
if (parts[4] === 'rename' && !parts[5]) {
const body = parse(RenameBody, await ctx.readJson())
if (row.status !== 'running' || !row.session_id) {
throw new ApiError(409, 'conflict', 'workspace_not_running')
}
await renameSession(life().provider, row.session_id, subId, body.name)
await auditCaller(ctx.db, caller, { action: 'workspace.session.rename', targetType: 'workspace', targetId: row.id, detail: { handle: subId } }, ctx.now())
return json({ session: { handle: subId, workspaceId: row.id, name: body.name } })
}
}
if (sub === 'attachments' && !subId && method === 'POST') {
requireScope(caller, 'messages:write')
authorize(caller, row, 'open')
const provider = life().provider
if (!provider.writeFile) {
throw new ApiError(503, 'not_configured')
}
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
const upload = await readUpload(request, url)
const sessionId = await runningSession()
const attachment = newAttachment(
{ sandboxId: row.id, accountId: row.account_id, uploadedBy: caller.userId, filename: upload.filename, contentType: upload.contentType, byteSize: upload.bytes.length },
now
)
const started = performance.now()
await provider.writeFile(sessionId, attachment.path, upload.bytes)
await insertAttachment(ctx.db, attachment)
await auditCaller(ctx.db, caller, { action: 'workspace.attachment', targetType: 'workspace', targetId: row.id, detail: { attachmentId: attachment.id, bytes: attachment.byte_size, ms: Math.round(performance.now() - started) } }, ctx.now())
return json({ attachment: attachmentView(attachment) }, 201)
}
if (sub === 'sessions' && !subId && method === 'GET') {
requireScope(caller, 'workspaces:read')
authorize(caller, row, 'open')
@@ -485,7 +630,7 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
}
return json({ workspaceStatus: 'running', sessions: await listSessions(life().provider, row.session_id) })
}
if (sub === 'sessions' && subId && method === 'GET') {
if (sub === 'sessions' && subId && !parts[4] && method === 'GET') {
requireScope(caller, 'workspaces:read')
authorize(caller, row, 'owner')
if (!/^term_[A-Za-z0-9-]{1,80}$/.test(subId)) {
@@ -518,8 +663,10 @@ async function route(request: Request, url: URL, caller: ApiCaller, ctx: ApiCont
const life = requireLife(ctx)
await consumeRate(ctx.db, messageBucket(caller), MESSAGES_PER_MINUTE, now)
const body = parse(MessageBody, await ctx.readJson())
const queued = await queueMessage(ctx.db, { workspace: row, sentBy: caller.userId, agent: body.agent ?? 'claude', text: body.text, session: body.session }, now)
await auditCaller(ctx.db, caller, { action: 'workspace.message', targetType: 'workspace', targetId: row.id, detail: { messageId: queued.id, chars: body.text.length, continues: Boolean(body.session) } }, now)
const attachments = await resolveAttachments(ctx.db, row.id, body.attachments ?? [])
const text = withAttachmentPaths(body.text, attachments)
const queued = await queueMessage(ctx.db, { workspace: row, sentBy: caller.userId, agent: body.agent ?? 'claude', text, session: body.session }, now)
await auditCaller(ctx.db, caller, { action: 'workspace.message', targetType: 'workspace', targetId: row.id, detail: { messageId: queued.id, chars: body.text.length, continues: Boolean(body.session), attachments: attachments.length } }, now)
// Queued now, delivered in the background (waking the VM if it sleeps); poll the message.
ctx.waitUntil(deliverMessage(life, queued))
return json({ message: messageView(queued) }, 202, { location: `/v1/workspaces/${row.id}/messages/${queued.id}` })
+35 -8
View File
@@ -78,14 +78,28 @@ async function orca(provider: SandboxProviderApi, sessionId: string, args: strin
const LaunchResult = z.object({ outcome: z.object({ kind: z.string(), handle: z.string().optional() }).loose() }).loose()
/** Starts a new agent session with `prompt` in the workspace; returns its terminal handle. */
export async function launchAgent(provider: SandboxProviderApi, sessionId: string, agent: AgentId, prompt: string): Promise<string> {
const result = LaunchResult.safeParse(
await orca(provider, sessionId, ['agent', 'launch', '--agent', agent, '--worktree', `path:${PROJECT_ROOT}`, '--surface', 'terminal', `--prompt=${prompt}`], {
prepare: true,
timeoutMs: 90_000
})
)
/**
* Starts a new agent session in the workspace, optionally with a first prompt and a model/effort
* pick (the CLI maps them onto the agent's own flags); returns its terminal handle.
*/
export async function launchAgent(
provider: SandboxProviderApi,
sessionId: string,
agent: AgentId,
prompt: string | null,
options: { model?: string; effort?: string } = {}
): Promise<string> {
const args = ['agent', 'launch', '--agent', agent, '--worktree', `path:${PROJECT_ROOT}`, '--surface', 'terminal']
if (options.model) {
args.push(`--model=${options.model}`)
if (options.effort) {
args.push(`--effort=${options.effort}`)
}
}
if (prompt) {
args.push(`--prompt=${prompt}`)
}
const result = LaunchResult.safeParse(await orca(provider, sessionId, args, { prepare: true, timeoutMs: 90_000 }))
const handle = result.success ? result.data.outcome.handle : undefined
if (!handle) {
throw new VmAgentError('agent_launch_failed')
@@ -98,6 +112,19 @@ export async function sendToSession(provider: SandboxProviderApi, sessionId: str
await orca(provider, sessionId, ['terminal', 'send', '--terminal', handle, `--text=${text}`, '--enter'], { timeoutMs: 60_000 })
}
/**
* Stops the agent's current turn: one Escape, which the shipped agent CLIs treat as "interrupt"
* and which never quits an idle agent (Ctrl+C can, on a second press). Raw byte, no Enter.
*/
export async function interruptSession(provider: SandboxProviderApi, sessionId: string, handle: string): Promise<void> {
await orca(provider, sessionId, ['terminal', 'send', '--terminal', handle, '--text=\u001b'], { timeoutMs: 30_000 })
}
/** Renames an agent session (its terminal tab title, which the desktop and phone show too). */
export async function renameSession(provider: SandboxProviderApi, sessionId: string, handle: string, title: string): Promise<void> {
await orca(provider, sessionId, ['terminal', 'rename', '--terminal', handle, `--title=${title}`], { timeoutMs: 30_000 })
}
const TerminalList = z.object({
terminals: z.array(
z.object({
@@ -0,0 +1,168 @@
// Automatic environments: Conductor-style "the repo is already there". An environment build (golden +
// the repo checked out, snapshotted) is opt-in for admins; without one every create of a repo cloned it
// from scratch (stablyai/orca: ~55 s). So the first create of a repo that no environment of the account
// lists makes a default environment for it (just the repo, blobless, no install script) and builds it in
// the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and
// only fetch what changed. Scoped per account like every environment; the usual golden refresh keeps
// it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited
// it (that makes it an ordinary 'org' environment).
import type { SandboxCaller } from './auth'
import { listBuilds, startBuild, TERMINAL, type BuildConfig, type BuildDeps } from './environment-builds'
import { canonicalRepoUrl, parseRepos, repoDir, type EnvironmentRow } from './environments'
import { normalizeRepo } from './secrets'
export const AUTO_ENVIRONMENT_USER = 'system:auto-environment'
export const AUTO_ENVIRONMENT_UNUSED_MS = 14 * 24 * 60 * 60_000
/** A failed automatic build is retried by a later create, at most this often. */
export const AUTO_RETRY_AFTER_MS = 60 * 60_000
/** Same cap as admin-made environments. */
const MAX_ENVIRONMENTS = 20
const log = (event: string, fields: Record<string, unknown>) => console.log(JSON.stringify({ event, ...fields }))
function randomId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(10))
return `env_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`
}
function systemCaller(accountId: string): SandboxCaller {
// An org-less caller is its own admin (canAdminEnvironments); the build is billed to the account.
return { userId: AUTO_ENVIRONMENT_USER, accountId }
}
function autoConfig(environment: EnvironmentRow): BuildConfig {
return {
revision: environment.revision,
repos: parseRepos(environment),
installScript: environment.install_script,
envVarNames: [],
machineSize: environment.machine_size,
// History and trees only: a smaller snapshot and a faster build; file contents load on demand.
cloneFilter: 'blob:none'
}
}
export type AutoEnvironmentOutcome = 'created' | 'rebuilt' | 'exists' | 'skipped'
/**
* A create of `repoUrl` booted without an environment: make (or retry building) the account's automatic
* environment for it. Never throws; the create it rides behind already succeeded.
*/
export async function ensureAutoEnvironment(deps: BuildDeps, accountId: string, repoUrl: string): Promise<AutoEnvironmentOutcome> {
try {
return await ensure(deps, accountId, repoUrl)
} catch (error) {
log('auto_environment_failed', { error: String(error).slice(0, 200) })
return 'skipped'
}
}
async function ensure(deps: BuildDeps, accountId: string, repoUrl: string): Promise<AutoEnvironmentOutcome> {
const url = canonicalRepoUrl(repoUrl)
const wanted = normalizeRepo(url)
if (!url || !wanted) {
return 'skipped'
}
const { results: environments } = await deps.db
.prepare('SELECT * FROM environments WHERE account_id = ? AND deleted_at IS NULL')
.bind(accountId)
.all<EnvironmentRow>()
const listing = environments.filter((row) => parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted))
if (listing.some((row) => row.kind !== 'auto')) {
// An admin's environment lists the repo: theirs to build, never ours to shadow.
return 'exists'
}
const auto = listing[0]
if (auto) {
await touchEnvironment(deps.db, auto.id, deps.now())
return (await retryFailedBuild(deps, auto)) ? 'rebuilt' : 'exists'
}
if (environments.length >= MAX_ENVIRONMENTS) {
return 'skipped'
}
const now = deps.now()
const id = randomId()
// UNIQUE(account_id, name): a concurrent first create of the same repo inserts nothing here.
await deps.db
.prepare(
`INSERT OR IGNORE INTO environments (id, account_id, name, repos, install_script, env_var_names, machine_size,
revision, next_build_number, created_by, updated_by, created_at, updated_at, kind, last_used_at)
VALUES (?, ?, ?, ?, '', '[]', 'standard', 1, 1, ?, ?, ?, ?, 'auto', ?)`
)
.bind(id, accountId, repoDir(url), JSON.stringify([{ url, defaultBranch: null }]), AUTO_ENVIRONMENT_USER,
AUTO_ENVIRONMENT_USER, now, now, now)
.run()
const environment = await deps.db
.prepare('SELECT * FROM environments WHERE id = ? AND deleted_at IS NULL')
.bind(id)
.first<EnvironmentRow>()
if (!environment) {
return 'exists'
}
const build = await startBuild(deps, systemCaller(accountId), environment, { config: autoConfig(environment) })
log('auto_environment_created', { environmentId: id, buildId: build.id })
return 'created'
}
/** No active build, none in flight, and the last one failed a while ago: try once more. */
async function retryFailedBuild(deps: BuildDeps, environment: EnvironmentRow): Promise<boolean> {
if (environment.active_build_id) {
return false
}
const [last] = await listBuilds(deps.db, environment.id, 1)
if (last && (!TERMINAL.has(last.status) || deps.now() - (last.finished_at ?? last.created_at) < AUTO_RETRY_AFTER_MS)) {
return false
}
await startBuild(deps, systemCaller(environment.account_id), environment, { config: autoConfig(environment) })
return true
}
/** A create booted from (or asked for) this environment. */
export async function touchEnvironment(db: D1Database, environmentId: string, now: number): Promise<void> {
await db.prepare('UPDATE environments SET last_used_at = ? WHERE id = ?').bind(now, environmentId).run()
}
/**
* Deletes the environment and every snapshot it built (live workspaces run on their own disks).
* Shared by an admin's Delete and the automatic expiry.
*/
export async function deleteEnvironmentAndSnapshots(
deps: Pick<BuildDeps, 'db' | 'provider' | 'now'>,
environmentId: string
): Promise<void> {
await deps.db
.prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?')
.bind(deps.now(), environmentId)
.run()
const { results } = await deps.db
.prepare(`SELECT id, snapshot_id FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`)
.bind(environmentId)
.all<{ id: string; snapshot_id: string }>()
for (const row of results) {
await deps.provider.deleteSnapshot(row.snapshot_id).catch(() => undefined)
await deps.db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run()
}
}
/** Cron: automatic environments no create used for 14 days go, with their snapshots. */
export async function expireAutoEnvironments(deps: BuildDeps): Promise<number> {
const cutoff = deps.now() - AUTO_ENVIRONMENT_UNUSED_MS
const { results } = await deps.db
.prepare(
`SELECT id FROM environments WHERE kind = 'auto' AND deleted_at IS NULL
AND COALESCE(last_used_at, created_at) < ? LIMIT 20`
)
.bind(cutoff)
.all<{ id: string }>()
let expired = 0
for (const { id } of results) {
const inFlight = (await listBuilds(deps.db, id, 5)).some((build) => !TERMINAL.has(build.status))
if (inFlight) {
continue
}
await deleteEnvironmentAndSnapshots(deps, id)
log('auto_environment_expired', { environmentId: id })
expired++
}
return expired
}
@@ -40,7 +40,8 @@ export function parseCloneStatus(stdout: string): CloneStatus {
if (state === 'none' || state === '') {
return { state: 'none' }
}
if (state === 'done') {
if (state === 'done' || state.startsWith('done ')) {
// "done stale": an update after an environment boot failed; the build's checkout still opens.
return { state: 'done' }
}
if (state.startsWith('failed')) {
+8
View File
@@ -23,10 +23,18 @@ export type Env = {
GOLDEN_SNAPSHOT_REGION?: string
/** Non-prod only: pin this image over the rotated active one (preview versions testing new VM entry points). */
GOLDEN_SNAPSHOT_OVERRIDE?: string
/** 'off': no automatic environments (auto-environments.ts); creates without one keep cloning. */
AUTO_ENVIRONMENTS?: string
/** Git as the sender: `on`, `accounts:<id>,<id>` or off (default). See memberGitEnabled in index.ts. */
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. */
@@ -91,6 +91,8 @@ export type BuildConfig = {
installScript: string
envVarNames: string[]
machineSize: MachineSize
/** `git clone --filter`: automatic environments clone blobless (auto-environments.ts). */
cloneFilter?: 'blob:none'
}
export type BuildResult = {
@@ -338,7 +340,8 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P
ORCA_BUILD_REPOS: lines.join('\n'),
ORCA_INSTALL_SCRIPT_B64: base64(config.installScript),
ORCA_LOCKFILES: LOCKFILES.join(' '),
ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK)
ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK),
...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {})
}
log('environment_build_secrets', { buildId: row.id, injected: Object.keys(secrets).length, named: config.envVarNames.length })
const commandId = await deps.provider.startCommand(box.session.id, {
@@ -9,6 +9,7 @@
// GET /v1/environments/:id/builds/:bid/events -> ndjson stream (environment-builds.ts)
// POST /v1/environments/:id/builds/:bid/cancel | /activate -> {build} | {environment}
// GET /v1/environments/:id/staleness -> {staleness}
import { deleteEnvironmentAndSnapshots } from './auto-environments'
import type { SandboxCaller } from './auth'
import {
activateBuild,
@@ -163,16 +164,8 @@ export async function handleEnvironmentRoute(
await cancelBuild(deps, caller, row).catch(() => undefined)
}
}
await db.prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?').bind(deps.now(), envId).run()
// No kept window once deleted: every build snapshot goes (live workspaces run on their own disks).
const { results } = await db
.prepare(`SELECT * FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`)
.bind(envId)
.all<BuildRow>()
for (const row of results) {
await deps.provider.deleteSnapshot(row.snapshot_id!).catch(() => undefined)
await db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run()
}
await deleteEnvironmentAndSnapshots(deps, envId)
return json({ deleted: true })
}
return json({ error: 'not_found' }, 404)
+25 -6
View File
@@ -31,6 +31,12 @@ export type EnvironmentRow = {
created_at: number
updated_at: number
deleted_at: number | null
/**
* 'org': made (or since edited) by an admin. 'auto': made by the first create of a repo no
* environment listed (auto-environments.ts); deleted after 14 days unused unless an admin edits it.
*/
kind?: 'org' | 'auto'
last_used_at?: number | null
}
export class EnvironmentError extends Error {
@@ -223,10 +229,11 @@ export async function updateEnvironment(
next.install_script !== row.install_script ||
next.env_var_names !== row.env_var_names ||
next.machine_size !== row.machine_size
// An admin's edit adopts an automatic environment: it stops expiring.
const result = await db
.prepare(
`UPDATE environments SET name = ?, repos = ?, install_script = ?, env_var_names = ?, machine_size = ?,
revision = revision + ?, updated_by = ?, updated_at = ? WHERE id = ? AND revision = ?`
revision = revision + ?, updated_by = ?, updated_at = ?, kind = 'org' WHERE id = ? AND revision = ?`
)
.bind(next.name, next.repos, next.install_script, next.env_var_names, next.machine_size,
buildInputsChanged ? 1 : 0, caller.userId, now, row.id, row.revision)
@@ -246,6 +253,8 @@ export type BootSource = {
machineSize: MachineSize
/** The build's snapshot only boots here, so the workspace is created here too. */
region: string
/** An automatic environment (auto-environments.ts): the caller's machine size stands. */
auto?: boolean
}
type BootBuildRow = {
@@ -288,7 +297,12 @@ function bootFrom(build: BootBuildRow, repoUrl: string | null | undefined): Boot
export async function resolveEnvironmentBoot(
db: D1Database,
accountId: string,
request: { repoUrl?: string | null; buildId?: string | null }
request: {
repoUrl?: string | null
buildId?: string | null
/** An automatic environment only boots in its build's region: an explicit other region skips it. */
region?: string | null
}
): Promise<BootSource | null> {
if (request.buildId) {
const build = await db
@@ -308,20 +322,25 @@ export async function resolveEnvironmentBoot(
if (!wanted) {
return null
}
// An admin's environment that lists the repo wins over an automatic one.
const { results } = await db
.prepare(
`SELECT e.repos AS repos, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id
WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY e.updated_at DESC`
`SELECT e.repos AS repos, e.kind AS kind, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id
WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY (e.kind = 'org') DESC, e.updated_at DESC`
)
.bind(accountId)
.all<BootBuildRow & { repos: string }>()
.all<BootBuildRow & { repos: string; kind: string }>()
for (const row of results) {
if (!parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted)) {
continue
}
// An automatic environment is only a speed-up: an explicit other region skips it.
if (row.kind === 'auto' && request.region && request.region !== row.region) {
continue
}
const source = bootFrom(row, request.repoUrl)
if (source?.repoDir) {
return source
return row.kind === 'auto' ? { ...source, auto: true } : source
}
}
return null
+92 -10
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,9 @@ 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'
import { handleShareRoute, revokeSandboxShares, sharePathMode, shareSecret, shareSecrets } from './share-links'
@@ -150,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'
@@ -201,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'
@@ -742,8 +749,8 @@ function devCredentials(env: Env): CredentialBroker {
}
/** Ready answers carry phase timings as Server-Timing so clients and dashboards can see the slow step. */
function readyResponse(ready: Ready): Response {
const response = json(readyView(ready.row, ready.connection, ready.cloning))
function readyResponse(ready: Ready, updateAware = false): Response {
const response = json(readyView(ready.row, ready.connection, ready.cloning, updateAware))
const timing = Object.entries(ready.timings ?? {})
.map(([phase, ms]) => `${phase};dur=${ms}`)
.join(', ')
@@ -802,7 +809,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
projectId: env.VERCEL_PROJECT_ID!,
baseUrl: env.VERCEL_API_BASE
})
return {
const life: LifecycleDeps = {
db: env.SANDBOX_DB,
provider,
entitlements: deps.entitlements ?? withDevAccountBypass(env, createEntitlementClient(env)),
@@ -834,6 +841,14 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
env.SESSION_DEADLINE_MS && env.SANDBOX_ENV !== 'prod' ? Number(env.SESSION_DEADLINE_MS) : undefined
}
}
// AUTO_ENVIRONMENTS=off: creates of repos without an environment keep cloning from scratch.
if (env.AUTO_ENVIRONMENTS !== 'off') {
life.autoEnvironment = {
ensure: (accountId, repoUrl) => ensureAutoEnvironment(buildDeps(life, deps, env), accountId, repoUrl),
touch: (environmentId) => touchEnvironment(env.SANDBOX_DB, environmentId, life.now())
}
}
return life
}
/**
@@ -1471,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) {
@@ -1479,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
@@ -1514,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)
// 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 ?? ''}`
@@ -1823,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)
@@ -2138,6 +2215,11 @@ export default {
if (refresh.stale > 0) {
console.log(JSON.stringify({ event: 'environment_golden_refresh', ...refresh }))
}
// Automatic environments unused for 14 days go with their snapshots (storage).
const expired = await expireAutoEnvironments(buildDeps(fresh, {}, env)).catch(() => 0)
if (expired > 0) {
console.log(JSON.stringify({ event: 'auto_environments_expired', expired }))
}
}
})
)
+38 -9
View File
@@ -96,6 +96,14 @@ export type LifecycleDeps = {
* error after boot. Absent: no check.
*/
publicRepoCheck?: (repoUrl: string) => Promise<boolean>
/**
* Automatic environments (auto-environments.ts): `ensure` after a create of a repo no environment
* lists, `touch` when a create booted from an automatic one. Absent: neither happens.
*/
autoEnvironment?: {
ensure(accountId: string, repoUrl: string): Promise<unknown>
touch(environmentId: string): Promise<unknown>
}
/** Work that may finish after the response (Worker ctx.waitUntil); absent means fire-and-forget. */
background?: (work: Promise<unknown>) => void
/** Best-effort side effects of a session starting or ending (workspace tokens, see api/settings.ts). */
@@ -156,8 +164,11 @@ export type Ready = {
row: SandboxRow
connection: OrcadReady
timings?: Record<string, number>
/** The repo is still cloning in the VM (create with cloneInBackground); GET /clone reports it. */
cloning?: boolean
/**
* The repo is still being cloned ('clone') or, after an environment boot, brought up to date
* ('update') in the VM (create with cloneInBackground); GET /clone reports it.
*/
cloning?: 'clone' | 'update'
}
/** Phase durations for one lifecycle call (logged + Server-Timing); counts only, no ids or secrets. */
@@ -515,11 +526,13 @@ export async function createSandbox(
? await timer.time('environment', () =>
resolveEnvironmentBoot(deps.db, caller.accountId, {
repoUrl: request.repo?.url,
buildId: request.environmentBuildId
buildId: request.environmentBuildId,
region: request.region
})
)
: null
const machineSize = source?.machineSize ?? request.machineSize
// An automatic environment is only the repo checked out: the caller's machine size stands.
const machineSize = source && !source.auto ? source.machineSize : request.machineSize
await timer.time('entitlement', () => requireStart(deps, caller.accountId, caller.userId, machineSize))
// A snapshot only boots in its own region: an environment build pins the region it was built in.
const region = source?.region ?? request.region ?? deps.config.defaultRegion
@@ -541,12 +554,16 @@ export async function createSandbox(
deps.background?.(refill)
}
const claimedAt = deps.now()
// An environment build carries the repo prebuilt: nothing clones, so nothing runs in the background.
const cloneInBackground = Boolean(request.repo && request.cloneInBackground && !source?.repoDir)
// In the background after ready: a clone, or (an environment build carries the repo prebuilt) a fetch
// of what changed since the build.
const cloning: Ready['cloning'] = request.repo && request.cloneInBackground ? (source?.repoDir ? 'update' : 'clone') : undefined
const prelude: StartInputs['prelude'] = request.repo
? {
script: WORKSPACE_PRELUDE_SCRIPT,
env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : cloneInBackground ? { ORCA_CLONE_BACKGROUND: '1' } : {}
env: {
...(source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {}),
...(cloning ? { ORCA_CLONE_BACKGROUND: '1' } : {})
}
}
: undefined
const id = pooled?.id ?? randomId()
@@ -590,6 +607,18 @@ export async function createSandbox(
throw error
}
})
// The repo is reachable: the next create of it should find it prebuilt (auto-environments.ts).
if (request.repo && deps.autoEnvironment && !request.environmentBuildId && request.useEnvironment !== false) {
const work = source?.auto
? deps.autoEnvironment.touch(source.environmentId)
: !source
? deps.autoEnvironment.ensure(caller.accountId, request.repo.url)
: null
if (work) {
const settled = work.catch(() => undefined)
deps.background?.(settled)
}
}
if (pooled) {
try {
const state = await timer.time('vm', () =>
@@ -597,7 +626,7 @@ export async function createSandbox(
)
const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, billFrom: claimedAt, prelude })
console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', pooled: true, ms: timer.timings }))
return cloneInBackground ? { ...ready, cloning: true } : ready
return cloning ? { ...ready, cloning } : ready
} catch (error) {
// A pooled VM that will not take the session is discarded; the caller still gets a workspace.
console.log(JSON.stringify({ event: 'pool_adopt_failed', error: String(error).slice(0, 200) }))
@@ -647,7 +676,7 @@ export async function createSandbox(
try {
const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, prelude })
console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', fromBuild: source?.buildId ?? null, ms: timer.timings }))
return cloneInBackground ? { ...ready, cloning: true } : ready
return cloning ? { ...ready, cloning } : ready
} catch (error) {
await failAndRelease(deps, (await getSandbox(deps.db, row.id)) ?? row, createFailureReason(error))
throw error
+4 -2
View File
@@ -5,7 +5,8 @@ import type { ApiCaller } from '../api/caller'
import { callTool, hasTool, toolError, toolList, type ApiCall } from './tools'
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'] as const
const MAX_BODY_BYTES = 256 * 1024
// upload_attachment carries up to 5 MB as base64 (~6.7 MB of JSON); everything else is tiny.
const MAX_BODY_BYTES = 7 * 1024 * 1024 + 512 * 1024
const SERVER_INFO = {
name: 'orca-cloud',
@@ -16,7 +17,8 @@ const SERVER_INFO = {
const INSTRUCTIONS =
'Orca Cloud runs coding agents (Claude Code, Codex) in cloud workspaces. Typical flow: list_projects or list_workspaces; ' +
'create_workspace (optionally with a first message); send_message to give an agent a task; list_sessions to read its progress; ' +
'create_workspace (optionally with a first message); send_message to give an agent a task; list_sessions and read_session to read its progress; ' +
'create_session for another chat (pick models with list_models), upload_attachment to hand an agent a file, cancel_session to stop a turn; ' +
'sleep_workspace when idle and destroy_workspace when done. Destroying is permanent.'
type JsonRpcId = string | number | null
+73 -1
View File
@@ -32,6 +32,7 @@ type ToolDef<T extends z.ZodObject> = {
// Ids go into URL paths: restrict them so a tool argument can never address another route.
const Id = (what: string) => z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, `a ${what} id`).describe(`The ${what} id.`)
const WorkspaceId = z.object({ workspaceId: Id('workspace') }).strict()
const SessionHandle = z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).describe('Session handle (term_…) from list_sessions, create_session or a message.')
const Agent = z.enum(AGENTS).describe(`Agent CLI to run: ${AGENTS.join(', ')} (claude, Claude Code, is the default).`)
const MAX_WAIT_SECONDS = 45
@@ -92,6 +93,14 @@ export const TOOLS = [
annotations: read('Who am I'),
run: async (_args, api) => fromApi(await api('GET', '/v1/me'))
}),
tool({
name: 'list_models',
description:
'Lists the coding agents a cloud workspace runs (claude, codex, opencode, gemini, cursor, copilot) and, for each, the model ids, effort levels, defaults and fast-mode support. Pass agent, model and effort to create_session.',
input: z.object({}).strict(),
annotations: read('List agents and models'),
run: async (_args, api) => fromApi(await api('GET', '/v1/models'))
}),
tool({
name: 'list_projects',
description: 'Lists the Orca Cloud projects in this account. A project is a repository plus default sandbox settings; pass its id to create_workspace to start a workspace from it.',
@@ -153,6 +162,13 @@ export const TOOLS = [
})
)
}),
tool({
name: 'rename_workspace',
description: 'Renames a workspace (the name shown on desktop Home, the phone and in list_workspaces). The git branch keeps its name.',
input: z.object({ workspaceId: Id('workspace'), name: z.string().trim().min(1).max(100).describe('New display name.') }).strict(),
annotations: { title: 'Rename workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/rename`, { name: args.name }))
}),
tool({
name: 'sleep_workspace',
description: 'Puts a running workspace to sleep: its files are kept and no sandbox hours are used until wake_workspace. Running agents are interrupted.',
@@ -174,6 +190,13 @@ export const TOOLS = [
annotations: { title: 'Archive workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/archive`))
}),
tool({
name: 'unarchive_workspace',
description: 'Restores an archived workspace: it is back in default lists and its sandbox is started again with its files intact. A workspace that is not archived is returned unchanged.',
input: WorkspaceId,
annotations: { title: 'Unarchive workspace', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/unarchive`))
}),
tool({
name: 'destroy_workspace',
description: 'Deletes a workspace and its sandbox for good. Uncommitted and unpushed work in it is lost. This cannot be undone.',
@@ -181,6 +204,53 @@ export const TOOLS = [
annotations: { title: 'Delete workspace', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
run: async (args, api) => fromApi(await api('DELETE', `/v1/workspaces/${args.workspaceId}`))
}),
tool({
name: 'create_session',
description:
'Starts a new agent session (a new chat) in an existing workspace, waking it first if it sleeps, and returns its handle once the agent is up. Optionally pick the model and effort (see list_models), name it, and give it a first `message` (with `attachments` from upload_attachment). Continue it with send_message and `session` = the handle.',
input: z
.object({
workspaceId: Id('workspace'),
agent: Agent.optional(),
model: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,127}$/).optional().describe('Model id from list_models (default: the agent\'s own default).'),
effort: z.string().regex(/^[a-z]{2,16}$/).optional().describe('Effort level the model takes (list_models); needs `model`.'),
name: z.string().trim().min(1).max(100).optional().describe('Session (tab) title.'),
message: z.string().min(1).max(32_000).optional().describe('First prompt. Without it the agent starts idle.'),
attachments: z.array(Id('attachment')).min(1).max(10).optional().describe('Attachment ids from upload_attachment; needs `message`.')
})
.strict(),
annotations: { title: 'Start agent session', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
run: async ({ workspaceId, ...body }, api) => fromApi(await api('POST', `/v1/workspaces/${workspaceId}/sessions`, body))
}),
tool({
name: 'cancel_session',
description: "Stops an agent's current turn in a session (like pressing Escape) and drops any of that session's messages still queued. The session stays open for the next send_message.",
input: z.object({ workspaceId: Id('workspace'), session: SessionHandle }).strict(),
annotations: { title: 'Cancel agent turn', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/sessions/${args.session}/cancel`))
}),
tool({
name: 'rename_session',
description: 'Renames an agent session (the tab title the desktop and phone show). The workspace must be running.',
input: z.object({ workspaceId: Id('workspace'), session: SessionHandle, name: z.string().trim().min(1).max(100).describe('New title.') }).strict(),
annotations: { title: 'Rename agent session', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
run: async (args, api) => fromApi(await api('POST', `/v1/workspaces/${args.workspaceId}/sessions/${args.session}/rename`, { name: args.name }))
}),
tool({
name: 'upload_attachment',
description:
'Uploads a file (base64, up to 5 MB) to a workspace for an agent to read, e.g. a screenshot or log. Returns an attachment id; pass it in `attachments` to send_message or create_session and the agent is told where the file is. The file sits outside the repo, so it is never committed.',
input: z
.object({
workspaceId: Id('workspace'),
filename: z.string().min(1).max(255).describe('File name, e.g. bug.png.'),
contentType: z.string().max(127).optional().describe('MIME type, e.g. image/png.'),
data: z.string().min(1).describe('The file bytes, base64-encoded.')
})
.strict(),
annotations: { title: 'Upload attachment', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
run: async ({ workspaceId, ...body }, api) => fromApi(await api('POST', `/v1/workspaces/${workspaceId}/attachments`, body))
}),
tool({
name: 'send_message',
description:
@@ -191,6 +261,7 @@ export const TOOLS = [
text: z.string().min(1).max(32_000).describe('The message or task for the agent.'),
agent: Agent.optional(),
session: z.string().regex(/^term_[A-Za-z0-9-]{1,80}$/).optional().describe('Session handle to continue (from list_sessions or a previous message).'),
attachments: z.array(Id('attachment')).min(1).max(10).optional().describe('Attachment ids from upload_attachment.'),
waitSeconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional().describe(`How long to wait for delivery (0-${MAX_WAIT_SECONDS}, default 20).`)
})
.strict(),
@@ -199,7 +270,8 @@ export const TOOLS = [
const response = await api('POST', `/v1/workspaces/${args.workspaceId}/messages`, {
text: args.text,
...(args.agent ? { agent: args.agent } : {}),
...(args.session ? { session: args.session } : {})
...(args.session ? { session: args.session } : {}),
...(args.attachments ? { attachments: args.attachments } : {})
})
if (!response.ok) {
return fromApi(response)
@@ -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()
}
@@ -111,6 +111,11 @@ export type SandboxProviderApi = {
updateSnapshotExpiration(name: string, expirationMs: number): Promise<void>
/** A small text file from the VM (files API: not kept as command logs). Null when absent. */
readFile(sessionId: string, path: string): Promise<string | null>
/**
* Writes one file (absolute path, parents created) into a running session through the files API,
* so the bytes never pass through argv, env or command logs. Optional: only API attachments use it.
*/
writeFile?(sessionId: string, path: string, bytes: Uint8Array): Promise<void>
/** Resolves when already gone. */
deleteSandbox(name: string): Promise<void>
listSnapshots(name: string): Promise<ProviderSnapshot[]>
@@ -0,0 +1,68 @@
// Minimal ustar writer for the Vercel files API (POST .../fs/write takes a gzipped tarball, the same
// format @vercel/sandbox's FileWriter streams). Workers have no tar library; one regular file plus
// its parent directories is all the control plane ever writes.
const BLOCK = 512
function octal(value: number, width: number): string {
// width includes the trailing NUL.
return value.toString(8).padStart(width - 1, '0')
}
function header(path: string, entry: { type: 'file' | 'dir'; size: number; mode: number; mtime: number }): Uint8Array {
const block = new Uint8Array(BLOCK)
const encoder = new TextEncoder()
const put = (offset: number, text: string, width: number) => {
const bytes = encoder.encode(text)
if (bytes.length > width) {
throw new Error('tar_field_too_long')
}
block.set(bytes, offset)
}
// Long paths split at a slash: prefix (155) + "/" + name (100).
let name = path
let prefix = ''
if (encoder.encode(path).length > 100) {
const cut = path.lastIndexOf('/', path.length - 2)
if (cut <= 0) {
throw new Error('tar_name_too_long')
}
prefix = path.slice(0, cut)
name = path.slice(cut + 1)
}
put(0, name, 100)
put(100, octal(entry.mode, 8), 8)
put(108, octal(0, 8), 8)
put(116, octal(0, 8), 8)
put(124, octal(entry.size, 12), 12)
put(136, octal(Math.floor(entry.mtime / 1000), 12), 12)
block.fill(0x20, 148, 156) // checksum field counts as spaces while summing
put(156, entry.type === 'dir' ? '5' : '0', 1)
put(257, 'ustar\u000000', 8)
put(345, prefix, 155)
const sum = block.reduce((total, byte) => total + byte, 0)
put(148, `${octal(sum, 7)}\u0000 `, 8)
return block
}
/**
* A gzipped tarball holding `dirs` (created first, mode 0755) and one file at `path` (0644). Paths
* are relative to the extraction directory and must not contain `..` segments.
*/
export async function tarGzipFile(input: { dirs: string[]; path: string; bytes: Uint8Array; mtime: number }): Promise<ArrayBuffer> {
for (const p of [...input.dirs, input.path]) {
if (p.startsWith('/') || p.split('/').some((segment) => segment === '..' || segment === '')) {
throw new Error('tar_bad_path')
}
}
const padding = (BLOCK - (input.bytes.length % BLOCK)) % BLOCK
const parts: Uint8Array[] = [
...input.dirs.map((dir) => header(`${dir}/`, { type: 'dir', size: 0, mode: 0o755, mtime: input.mtime })),
header(input.path, { type: 'file', size: input.bytes.length, mode: 0o644, mtime: input.mtime }),
input.bytes,
new Uint8Array(padding),
new Uint8Array(BLOCK * 2) // end-of-archive marker
]
const stream = new Blob(parts as BlobPart[]).stream().pipeThrough(new CompressionStream('gzip'))
return new Response(stream).arrayBuffer()
}
@@ -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
}
@@ -3,6 +3,7 @@
import { z } from 'zod'
import type { NetworkPolicy } from './network-policy'
import type { GoldenImageProviderApi } from './golden-image-provider'
import { tarGzipFile } from './tar-gzip'
import {
ProviderError,
type CommandResult,
@@ -265,6 +266,27 @@ export function createVercelSandboxApi(
}
},
async writeFile(sessionId, path, bytes) {
// Same call @vercel/sandbox's writeFiles makes: a gzipped tarball extracted at `/`.
const relative = path.replace(/^\/+/, '')
const segments = relative.split('/')
const dirs = segments.slice(0, -1).map((_, i) => segments.slice(0, i + 1).join('/'))
const body = await tarGzipFile({ dirs, path: relative, bytes, mtime: Date.now() })
const url = new URL(`${base}/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}/fs/write`)
url.searchParams.set('teamId', config.teamId)
const response = await doFetch(url, {
method: 'POST',
headers: { authorization: `Bearer ${config.token}`, 'content-type': 'application/gzip', 'x-cwd': '/' },
body,
redirect: 'manual'
})
if (!response.ok) {
const parsed = ErrorBody.safeParse(await response.json().catch(() => null))
throw new ProviderError(response.status, parsed.success ? (parsed.data.error?.code ?? null) : null)
}
await response.body?.cancel()
},
deleteSandbox: (name) =>
missingOk(() =>
request('DELETE', `/v2/sandboxes/${encodeURIComponent(name)}`, {
+10 -2
View File
@@ -75,7 +75,13 @@ export function sandboxView(row: SandboxRow, archivedAware = false) {
}
}
export function readyView(row: SandboxRow, connection: OrcadReady, cloning = false) {
export function readyView(
row: SandboxRow,
connection: OrcadReady,
cloning?: 'clone' | 'update',
/** The client knows `mode` (feature `repo-update`); older ones show an update as a clone. */
updateAware = false
) {
return {
sandbox: sandboxView(row),
connection: {
@@ -84,7 +90,9 @@ export function readyView(row: SandboxRow, connection: OrcadReady, cloning = fal
projectRoot: connection.projectRoot
},
// Only for a create that asked (feature `clone-progress`): the repo is still cloning.
...(cloning ? { clone: { state: 'running' as const } } : {})
...(cloning
? { clone: { state: 'running' as const, ...(cloning === 'update' && updateAware ? { mode: 'update' as const } : {}) } }
: {})
}
}
+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
@@ -0,0 +1,222 @@
import { gunzipSync } from 'node:zlib'
import { describe, expect, it } from 'vitest'
import { safeFilename } from '../src/api/attachments'
import { tarGzipFile } from '../src/tar-gzip'
import { createHarness } from './harness'
async function harness() {
const pending: Promise<unknown>[] = []
const h = await createHarness({ PUBLIC_API_URL: 'https://api.test' }, { waitUntil: (p) => void pending.push(p) })
/** Answers the in-VM orca CLI: launches return `term_new`, other terminal commands succeed. */
h.vercel.commandHandler = (params) => {
const args = params.args ?? []
if (args.includes('launch')) {
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: { outcome: { kind: 'terminal', handle: 'term_new' } } }), stderr: '' }
}
if (args.includes('terminal')) {
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: {} }), stderr: '' }
}
return undefined
}
const orcaArgs = (verb: string) => h.vercel.commands.filter((c) => c.args?.includes(verb)).map((c) => c.args!.slice(c.args!.indexOf('orca') + 1))
return { ...h, settle: () => Promise.all(pending.splice(0)), orcaArgs }
}
async function upload(h: Awaited<ReturnType<typeof harness>>, wsId: string, init: { body: BodyInit; contentType: string; query?: string; as?: string }) {
const bearer = await h.token(init.as ?? 'alice')
const response = await h.send(
new Request(`https://sandbox.test/v1/workspaces/${wsId}/attachments${init.query ?? ''}`, {
method: 'POST',
headers: { authorization: `Bearer ${bearer}`, 'content-type': init.contentType },
body: init.body
})
)
return { status: response.status, body: (await response.json()) as any }
}
describe('public API: models', () => {
it('lists every image agent with its catalog models, efforts and defaults', async () => {
const h = await harness()
const res = await h.call('GET', '/v1/models')
expect(res.status).toBe(200)
const agents = res.body.agents as { id: string; default: boolean; defaultModel: string | null; models: { id: string; efforts: string[]; fastMode: boolean }[] }[]
expect(agents.map((a) => a.id)).toEqual(['claude', 'codex', 'opencode', 'gemini', 'cursor', 'copilot'])
const claude = agents.find((a) => a.id === 'claude')!
expect(claude.default).toBe(true)
expect(claude.defaultModel).toBe('sonnet')
expect(claude.models.find((m) => m.id === 'opus')).toMatchObject({ efforts: expect.arrayContaining(['high', 'max']), fastMode: true })
expect(agents.find((a) => a.id === 'codex')!.models.find((m) => m.id === 'gpt-5.5')!.efforts).toContain('xhigh')
// Agents without a seed catalog still appear: their CLI picks the model.
expect(agents.find((a) => a.id === 'copilot')).toMatchObject({ models: [], defaultModel: null })
})
})
describe('public API: sessions', () => {
it('starts a new session with model, effort, name and a first prompt, waking a sleeping workspace', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, {
body: { agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Review', message: 'review the diff; $(rm -rf /)' }
})
expect(res.status).toBe(201)
expect(res.body.session).toEqual({ handle: 'term_new', workspaceId: ws.id, agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Review' })
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.status).toBe('running')
const [launch] = h.orcaArgs('launch')
expect(launch).toEqual(expect.arrayContaining(['--agent', 'codex', '--model=gpt-5.5', '--effort=high', '--prompt=review the diff; $(rm -rf /)']))
expect(h.orcaArgs('rename')[0]).toEqual(expect.arrayContaining(['--terminal', 'term_new', '--title=Review']))
const actions = (await h.call('GET', '/v1/audit')).body.entries.map((e: { action: string }) => e.action)
expect(actions[0]).toBe('workspace.session.create')
})
it('starts an idle session without a prompt and rejects bad model picks', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: {} })).status).toBe(201)
expect(h.orcaArgs('launch')[0]!.some((arg) => arg.startsWith('--prompt'))).toBe(false)
const badEffort = await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { agent: 'claude', model: 'haiku', effort: 'high' } })
expect(badEffort).toMatchObject({ status: 400, body: { error: 'invalid_request', reason: 'effort: haiku takes no effort' } })
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { effort: 'high' } })).status).toBe(400)
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { model: 'x y' } })).status).toBe(400)
// A model newer than the catalog is passed through to the agent CLI.
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { body: { model: 'claude-fable-9', effort: 'max' } })).status).toBe(201)
})
it('cancels a turn: drops the session\'s queued messages and interrupts with Escape', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
// Two messages still waiting for delivery (e.g. a retry backlog): one for this session, one not.
const insert = h.raw.prepare(
`INSERT INTO workspace_messages (id, sandbox_id, account_id, sent_by, agent, session_handle, body, status, created_at, updated_at) VALUES (?, ?, 'user:alice', 'alice', 'claude', ?, 'x', 'queued', 0, 0)`
)
insert.run('msg_q1', ws.id, 'term_abc')
insert.run('msg_q2', ws.id, 'term_other')
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`)
expect(res.body).toEqual({ workspaceId: ws.id, session: 'term_abc', interrupted: true, canceledQueuedMessages: 1 })
expect((await h.call('GET', `/v1/workspaces/${ws.id}/messages/msg_q1`)).body.message).toMatchObject({ status: 'failed', error: 'canceled' })
expect((await h.call('GET', `/v1/workspaces/${ws.id}/messages/msg_q2`)).body.message.status).toBe('queued')
const send = h.orcaArgs('send').at(-1)!
expect(send).toEqual(expect.arrayContaining(['--terminal', 'term_abc', '--text=\u001b']))
expect(send).not.toContain('--enter')
// Asleep: nothing to interrupt, and the VM is not woken for it.
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
const asleep = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`)
expect(asleep.body).toMatchObject({ interrupted: false, canceledQueuedMessages: 0 })
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.status).toBe('sleeping')
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/nope/cancel`)).status).toBe(404)
})
it('renames a session while running and 409s while asleep', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
const res = await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/rename`, { body: { name: 'Docs pass' } })
expect(res.body.session).toEqual({ handle: 'term_abc', workspaceId: ws.id, name: 'Docs pass' })
await h.call('POST', `/v1/workspaces/${ws.id}/sleep`)
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/rename`, { body: { name: 'x' } })).status).toBe(409)
})
it('keeps teammates out of a private workspace\'s sessions', async () => {
const h = await harness()
const owner = await h.token('olive', 'acme', 'sandbox', { orgRole: 'owner' })
const member = await h.token('mel', 'acme', 'sandbox', { orgRole: 'member' })
const ws = (await h.call('POST', '/v1/workspaces', { bearer: owner, body: {} })).body.workspace
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions`, { bearer: member, body: {} })).status).toBe(404)
expect((await h.call('POST', `/v1/workspaces/${ws.id}/sessions/term_abc/cancel`, { bearer: member })).status).toBe(404)
expect((await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { bearer: member, body: { name: 'x' } })).status).toBe(404)
})
})
describe('public API: rename and unarchive', () => {
it('renames a workspace everywhere it is listed', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: { name: 'old' } })).body.workspace
const res = await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { body: { name: ' New name ' } })
expect(res.body.workspace.name).toBe('New name')
expect((await h.call('GET', `/v1/workspaces/${ws.id}`)).body.workspace.name).toBe('New name')
expect((await h.call('GET', '/v1/team/workspaces')).body.workspaces[0].title).toBe('New name')
expect((await h.call('POST', `/v1/workspaces/${ws.id}/rename`, { body: { name: '' } })).status).toBe(400)
})
it('unarchives back into lists and running, idempotently', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
await h.call('POST', `/v1/workspaces/${ws.id}/archive`)
expect((await h.call('GET', '/v1/workspaces')).body.workspaces).toHaveLength(0)
const res = await h.call('POST', `/v1/workspaces/${ws.id}/unarchive`)
expect(res.body.workspace).toMatchObject({ status: 'running', archived: false })
expect((await h.call('GET', '/v1/workspaces')).body.workspaces).toHaveLength(1)
const again = await h.call('POST', `/v1/workspaces/${ws.id}/unarchive`)
expect(again).toMatchObject({ status: 200, body: { workspace: { status: 'running', archived: false } } })
const actions = (await h.call('GET', '/v1/audit')).body.entries.map((e: { action: string }) => e.action)
expect(actions.filter((a: string) => a === 'workspace.unarchive')).toHaveLength(1)
})
})
describe('public API: attachments', () => {
it('writes raw and base64 uploads to the workspace disk and points the agent at them', async () => {
const h = await harness()
const ws = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
const raw = await upload(h, ws.id, { body: new Uint8Array([0x89, 0x50, 0x4e, 0x47]), contentType: 'image/png', query: '?filename=../../etc/Screen%20Shot%201.png' })
expect(raw.status).toBe(201)
const att = raw.body.attachment
expect(att).toMatchObject({ workspaceId: ws.id, filename: 'Screen Shot 1.png', contentType: 'image/png', byteSize: 4 })
expect(att.path).toBe(`/vercel/sandbox/attachments/${att.id}/Screen Shot 1.png`)
const box = [...h.vercel.boxes.values()][0]!
expect(Buffer.from(box.files.get(att.path)!, 'latin1')).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]))
const json = await upload(h, ws.id, { body: JSON.stringify({ filename: 'log.txt', contentType: 'text/plain', data: Buffer.from('boom').toString('base64') }), contentType: 'application/json' })
expect(json.body.attachment).toMatchObject({ filename: 'log.txt', byteSize: 4 })
const sent = await h.call('POST', `/v1/workspaces/${ws.id}/messages`, { body: { text: 'see files', attachments: [att.id, json.body.attachment.id] } })
expect(sent.status).toBe(202)
await h.settle()
const prompt = h.orcaArgs('launch')[0]!.at(-1)!
expect(prompt).toContain('see files\n\nAttached files (read them from disk):')
expect(prompt).toContain(`- ${att.path} (image/png, 4 bytes)`)
expect(prompt).toContain(`- ${json.body.attachment.path} (text/plain, 4 bytes)`)
})
it('rejects unknown, foreign and oversized attachments', async () => {
const h = await harness()
const a = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
const b = (await h.call('POST', '/v1/workspaces', { body: {} })).body.workspace
const att = (await upload(h, b.id, { body: 'x', contentType: 'text/plain', query: '?filename=x.txt' })).body.attachment
const foreign = await h.call('POST', `/v1/workspaces/${a.id}/messages`, { body: { text: 'hi', attachments: [att.id] } })
expect(foreign).toMatchObject({ status: 400, body: { error: 'invalid_request' } })
expect((await h.call('POST', `/v1/workspaces/${a.id}/messages`, { body: { text: 'hi', attachments: ['att_nope'] } })).status).toBe(400)
expect((await upload(h, a.id, { body: 'x', contentType: 'text/plain' })).status).toBe(400)
const big = await upload(h, a.id, { body: JSON.stringify({ filename: 'big.bin', data: Buffer.alloc(5 * 1024 * 1024 + 1).toString('base64') }), contentType: 'application/json' })
expect(big.status).toBe(413)
// Another account cannot upload into it.
expect((await upload(h, a.id, { body: 'x', contentType: 'text/plain', query: '?filename=x', as: 'mallory' })).status).toBe(404)
// Attachments need a message on session create.
expect((await h.call('POST', `/v1/workspaces/${b.id}/sessions`, { body: { attachments: [att.id] } })).status).toBe(400)
})
it('keeps file names to one safe path segment', () => {
expect(safeFilename('../../.ssh/id_rsa')).toBe('id_rsa')
expect(safeFilename('.env')).toBe('env')
expect(safeFilename('résumé $(x).pdf')).toBe('resume __x_.pdf')
expect(safeFilename('')).toBe('file')
expect(safeFilename(`${'a'.repeat(300)}.png`)).toMatch(/^a{80}\.png$/)
})
it('packs a valid ustar archive the files API can extract', async () => {
const bytes = new TextEncoder().encode('hello')
const tgz = new Uint8Array(await tarGzipFile({ dirs: ['vercel', 'vercel/sandbox'], path: 'vercel/sandbox/a.txt', bytes, mtime: 1_700_000_000_000 }))
const tar = gunzipSync(tgz)
expect(tar.length % 512).toBe(0)
const field = (block: number, offset: number, width: number) => tar.subarray(block * 512 + offset, block * 512 + offset + width).toString('latin1').replace(/\0.*$/s, '')
expect([field(0, 0, 100), field(0, 156, 1), field(1, 0, 100), field(2, 0, 100), field(2, 156, 1)]).toEqual(['vercel/', '5', 'vercel/sandbox/', 'vercel/sandbox/a.txt', '0'])
expect(parseInt(field(2, 124, 12), 8)).toBe(5)
expect(field(2, 257, 6)).toBe('ustar')
for (const block of [0, 1, 2]) {
const header = Buffer.from(tar.subarray(block * 512, block * 512 + 512))
const stored = parseInt(field(block, 148, 8), 8)
header.fill(0x20, 148, 156)
expect(header.reduce((sum, b) => sum + b, 0)).toBe(stored)
}
expect(tar.subarray(3 * 512, 3 * 512 + 5).toString()).toBe('hello')
await expect(tarGzipFile({ dirs: [], path: '../x', bytes, mtime: 0 })).rejects.toThrow('tar_bad_path')
})
})
@@ -0,0 +1,141 @@
// Automatic environments: the first create of a repo builds it in the background; later creates boot
// with the repo checked out and only fetch what changed.
import { describe, expect, it } from 'vitest'
import { HostedSandboxReadyResponseSchema } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
import { AUTO_ENVIRONMENT_UNUSED_MS, expireAutoEnvironments } from '../src/auto-environments'
import { START_COMMAND } from '../src/sandbox-vm-commands'
import { GOLDEN, createHarness } from './harness'
const REPO = 'https://github.com/acme/web.git'
const RESULT = JSON.stringify({
durationSec: 3,
repos: [{ url: REPO, dir: 'acme/web', branch: 'main', commit: 'a'.repeat(40), lockfiles: {} }],
diskUsedBytes: 3_000_000_000,
diskTotalBytes: 34_000_000_000
})
const FEATURES = { 'x-orca-sandbox-features': 'clone-progress,repo-update' }
async function setup() {
const pending: Promise<unknown>[] = []
const h = await createHarness({ AUTO_ENVIRONMENTS: 'on' }, { waitUntil: (work: Promise<unknown>) => void pending.push(work) })
h.vercel.buildResult = RESULT
const settle = async () => {
while (pending.length > 0) {
await Promise.all(pending.splice(0))
}
}
const environments = () =>
h.raw.prepare('SELECT id, account_id, kind, name, active_build_id, deleted_at, last_used_at FROM environments').all() as {
id: string
account_id: string
kind: string
name: string
active_build_id: string | null
deleted_at: number | null
last_used_at: number | null
}[]
/** Lets the auto build's VM command succeed and finalizes it. */
async function finishBuild(as = 'alice') {
const env = environments().find((row) => row.deleted_at === null && !row.active_build_id)!
const build = h.raw.prepare('SELECT id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(env.id) as { id: string }
const command = [...h.vercel.buildCommands.values()].at(-1)!
command.logs = `${JSON.stringify({ data: '::orca-step:: clone\n', stream: 'stdout' })}\n`
command.exitCode = 0
h.advance(1000)
const done = await h.call('GET', `/v1/environments/${env.id}/builds/${build.id}`, { as })
expect(done.body.build.status).toBe('succeeded')
return { env, buildId: build.id }
}
return { h, settle, environments, finishBuild }
}
describe('automatic environments', () => {
it('the first create of a repo builds it (blobless); the next boots with it checked out and fetches only changes', async () => {
const { h, settle, environments, finishBuild } = await setup()
const first = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, headers: FEATURES })
expect(first.body.clone).toEqual({ state: 'running' })
await settle()
expect(environments()).toMatchObject([{ kind: 'auto', name: 'acme/web', active_build_id: null }])
const command = [...h.vercel.buildCommands.values()].at(-1)!
expect(command.env.ORCA_CLONE_FILTER).toBe('blob:none')
const { buildId } = await finishBuild()
h.vercel.commands.length = 0
const second = await h.call('POST', '/v1/sandboxes', {
body: { workspaceId: 'w2', machineSize: 'standard', repo: { url: REPO, ref: 'feature' } },
headers: FEATURES
})
expect(second.status).toBe(200)
expect(second.body.sandbox.environmentBuildId).toBe(buildId)
expect(second.body.clone).toEqual({ state: 'running', mode: 'update' })
expect(HostedSandboxReadyResponseSchema.safeParse({ ...second.body, clone: { state: 'running' } }).success).toBe(true)
const start = h.vercel.commands.find((c) => c.command === START_COMMAND)!
expect(start.env).toMatchObject({ ORCA_ENV_REPO_DIR: 'acme/web', ORCA_CLONE_BACKGROUND: '1' })
const box = [...h.vercel.boxes.values()].find((b) => b.params.tags.orcaSandbox === second.body.sandbox.id)!
expect(box.params.snapshotId).not.toBe(GOLDEN)
await settle()
expect(environments()[0]!.last_used_at).toBe(h.now())
// A desktop without `repo-update` sees the plain clone shape it knows.
const older = await h.call('POST', '/v1/sandboxes', {
body: { workspaceId: 'w3', machineSize: 'standard', repo: { url: REPO } },
headers: { 'x-orca-sandbox-features': 'clone-progress' }
})
expect(older.body.clone).toEqual({ state: 'running' })
})
it('is per account, never shadows an admin environment, and makes one environment per repo', async () => {
const { h, settle, environments } = await setup()
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a1', machineSize: 'standard', repo: { url: REPO } } })
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a2', machineSize: 'standard', repo: { url: 'acme/web' } } })
await settle()
const bob = await h.call('POST', '/v1/sandboxes', { as: 'bob', body: { workspaceId: 'b1', machineSize: 'standard', repo: { url: REPO } } })
await settle()
expect(bob.body.sandbox.environmentBuildId).toBeUndefined()
const rows = environments()
expect(rows).toHaveLength(2)
expect(new Set(rows.map((row) => row.account_id)).size).toBe(2)
// An org whose admin lists the repo: no automatic one next to it.
const admin = await h.token('carol', 'acme', 'sandbox', { orgRole: 'admin' })
expect(
(await h.call('POST', '/v1/environments', { bearer: admin, body: { name: 'Web', repos: [{ url: 'acme/web' }], installScript: '' } })).status
).toBe(200)
await h.call('POST', '/v1/sandboxes', { bearer: admin, body: { workspaceId: 'c1', machineSize: 'standard', repo: { url: REPO } } })
await settle()
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 } } })
await settle()
const { buildId } = await finishBuild()
const snapshotId = (h.raw.prepare('SELECT snapshot_id FROM environment_builds WHERE id = ?').get(buildId) as { snapshot_id: string }).snapshot_id
h.advance(AUTO_ENVIRONMENT_UNUSED_MS + 60_000)
const deps = {
db: h.env.SANDBOX_DB,
provider: h.vercel,
entitlements: { checkStart: async () => h.billing.decision, reportUsage: async () => h.billing.usageAnswer, listSuspensions: async () => [] },
now: h.now,
config: { environment: 'test', goldenSnapshotId: GOLDEN, region: 'iad1' }
}
expect(await expireAutoEnvironments(deps as never)).toBe(1)
expect(environments()[0]!.deleted_at).not.toBeNull()
expect(h.vercel.snapshots.get(snapshotId)?.status).not.toBe('created')
})
})
@@ -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' } })
@@ -369,6 +369,13 @@ export function createFakeVercel(now: () => number): FakeVercel {
async readFile(sessionId, path) {
return bySession(sessionId).files.get(path) ?? null
},
async writeFile(sessionId, path, bytes) {
const box = bySession(sessionId)
if (box.status !== 'running') {
throw new ProviderError(410, 'sandbox_stopped')
}
box.files.set(path, Buffer.from(bytes).toString('latin1'))
},
async deleteSandbox(name) {
const box = boxes.get(name)
if (box?.status === 'running') {
@@ -50,6 +50,8 @@ export async function createHarness(overrides: Partial<Env> = {}, extraDeps: Par
GOLDEN_SNAPSHOT_ID: GOLDEN,
VERCEL_TEAM_ID: 'team_orca',
VERCEL_PROJECT_ID: 'prj_orca',
// Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates.
AUTO_ENVIRONMENTS: 'off',
...overrides
}
// No live github.com from tests: repos count as public unless a test says otherwise.
+38 -2
View File
@@ -130,9 +130,13 @@ describe('MCP protocol', () => {
const list = await h.rpc(key, 'tools/list', {}, { 'mcp-protocol-version': '2025-11-25' })
const tools = list.body.result.tools as { name: string; inputSchema: any; annotations: any; description: string }[]
expect(tools.map((t) => t.name)).toEqual([
'whoami', 'list_projects', 'list_workspaces', 'get_workspace', 'create_workspace', 'sleep_workspace', 'wake_workspace',
'archive_workspace', 'destroy_workspace', 'send_message', 'get_message', 'list_sessions', 'read_session', 'list_routines', 'run_routine'
'whoami', 'list_models', 'list_projects', 'list_workspaces', 'get_workspace', 'create_workspace', 'rename_workspace',
'sleep_workspace', 'wake_workspace', 'archive_workspace', 'unarchive_workspace', 'destroy_workspace', 'create_session',
'cancel_session', 'rename_session', 'upload_attachment', 'send_message', 'get_message', 'list_sessions', 'read_session',
'list_routines', 'run_routine'
])
// Conductor's 20 tools minus run_sql (transcripts are end-to-end encrypted on the VM), plus Orca's own.
expect(tools).toHaveLength(22)
for (const t of tools) {
expect(t.inputSchema.type).toBe('object')
expect(t.description.length).toBeGreaterThan(40)
@@ -144,6 +148,38 @@ describe('MCP protocol', () => {
expect(byName.send_message!.inputSchema.required).toEqual(['workspaceId', 'text'])
})
it('starts, renames and cancels sessions, uploads files and lists models through the new tools', async () => {
const h = await harness()
const key = await h.apiKey(['workspaces:read', 'workspaces:write', 'messages:write'])
h.vercel.commandHandler = (params) => {
const args = params.args ?? []
if (args.includes('launch')) {
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: { outcome: { kind: 'terminal', handle: 'term_mcp1' } } }), stderr: '' }
}
if (args.includes('terminal')) {
return { exitCode: 0, stdout: JSON.stringify({ ok: true, result: {} }), stderr: '' }
}
return undefined
}
const models = (await h.tool(key, 'list_models')).structuredContent.agents
expect(models.map((a: { id: string }) => a.id)).toContain('codex')
const ws = (await h.tool(key, 'create_workspace', { name: 'm' })).structuredContent.workspace
expect((await h.tool(key, 'rename_workspace', { workspaceId: ws.id, name: 'renamed' })).structuredContent.workspace.name).toBe('renamed')
const file = await h.tool(key, 'upload_attachment', { workspaceId: ws.id, filename: 'shot.png', contentType: 'image/png', data: Buffer.from('PNGDATA').toString('base64') })
expect(file.isError).toBeUndefined()
const attachment = file.structuredContent.attachment
expect(attachment).toMatchObject({ filename: 'shot.png', byteSize: 7, contentType: 'image/png' })
const session = await h.tool(key, 'create_session', { workspaceId: ws.id, agent: 'codex', model: 'gpt-5.5', effort: 'high', name: 'Second', message: 'look', attachments: [attachment.id] })
expect(session.structuredContent.session).toMatchObject({ handle: 'term_mcp1', agent: 'codex', model: 'gpt-5.5', name: 'Second' })
const launch = h.vercel.commands.find((c) => c.args?.includes('launch'))!
expect(launch.args).toContain('--model=gpt-5.5')
expect(launch.args!.at(-1)).toContain(attachment.path)
expect((await h.tool(key, 'rename_session', { workspaceId: ws.id, session: 'term_mcp1', name: 'Third' })).structuredContent.session.name).toBe('Third')
expect((await h.tool(key, 'cancel_session', { workspaceId: ws.id, session: 'term_mcp1' })).structuredContent).toMatchObject({ interrupted: true, canceledQueuedMessages: 0 })
await h.tool(key, 'archive_workspace', { workspaceId: ws.id })
expect((await h.tool(key, 'unarchive_workspace', { workspaceId: ws.id })).structuredContent.workspace).toMatchObject({ status: 'running', archived: false })
})
it('rejects bad transport input: method, origin, version header, JSON, unknown method/tool', async () => {
const h = await harness()
const key = await h.apiKey(['workspaces:read'])
@@ -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)
+10 -1
View File
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { CloudSyncState } from '../../shared/cloud-sync/cloud-sync-contract'
import { createFakeVm, VM_ROOT, type FakeVm } from './cloud-sync-fake-vm.test-support'
import { createCloudSyncSession } from './cloud-sync-session'
import { createCloudSyncSession, safetyIntervalMs } from './cloud-sync-session'
import { createCloudSyncStore, type CloudSyncChoice } from './cloud-sync-store'
const dirs: string[] = []
@@ -217,3 +217,12 @@ describe('cloud sync session', () => {
expect(await readFile(join(folder, '.context/plan.md'), 'utf8')).toBe('p')
})
})
describe('safetyIntervalMs', () => {
it('re-checks small folders every 30 s and large mirrors at most every 10 min', () => {
expect(safetyIntervalMs(0)).toBe(30_000)
expect(safetyIntervalMs(21)).toBe(30_000)
expect(safetyIntervalMs(2_000)).toBe(60_000)
expect(safetyIntervalMs(100_000)).toBe(600_000)
})
})
+16 -3
View File
@@ -38,8 +38,15 @@ import {
export type { WatchSubscribe, WatchSubscription }
/** Safety net for anything the watch missed. */
const FULL_PASS_INTERVAL_MS = 10 * 60_000
/**
* Safety net for anything the watch missed. The VM's watcher can miss a directory created along
* with its parent (`mkdir -p .context/shots`), so small folders are re-checked often (a few
* calls each) and large mirrors less often: 30 ms per file, between 30 s and 10 min.
*/
const SAFETY_TICK_MS = 30_000
export function safetyIntervalMs(files: number): number {
return Math.min(10 * 60_000, Math.max(SAFETY_TICK_MS, files * 30))
}
const WATCH_RETRY_MIN_MS = 5_000
const WATCH_RETRY_MAX_MS = 5 * 60_000
@@ -69,6 +76,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
let watchRetryMs = WATCH_RETRY_MIN_MS
let watchRetryTimer: ReturnType<typeof setTimeout> | null = null
let safetyTimer: ReturnType<typeof setInterval> | null = null
let lastFullPassAt = 0
const abort = new AbortController()
let state: CloudSyncState = emptySyncState(deps.workspaceId, deps.folder, choice, 'starting')
const changes = createChangeBatcher({
@@ -136,6 +144,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
}
async function fullPass(): Promise<void> {
lastFullPassAt = now()
const { selector } = await ensureWorktree()
const current = await loadIndex()
const limits = limitsFor(choice)
@@ -282,7 +291,11 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
await loadIndex()
await requestFullPass()
await openWatch()
safetyTimer = setInterval(() => void requestFullPass(), FULL_PASS_INTERVAL_MS)
safetyTimer = setInterval(() => {
if (now() - lastFullPassAt >= safetyIntervalMs(state.files)) {
void requestFullPass()
}
}, SAFETY_TICK_MS)
safetyTimer.unref?.()
},
/** This computer woke, or the connection came back: anything may have changed meanwhile. */
@@ -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,11 @@ 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 +260,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)),
@@ -87,7 +87,9 @@ export async function checkSetup(
'Setup script is configured and has run here. Use --run-setup to check its exit code.'
)
: check('setup', 'setup.run', 'warn', 'Setup script is configured but has not run here.', {
remediation: 'Re-run the doctor with --run-setup to run it and check the result.'
remediation: 'Re-run the doctor with --run-setup to run it and check the result.',
// Desktop clients show their own words (no CLI flags) for this code.
code: 'setupNotRun'
})
]
}
@@ -18,6 +18,11 @@ export type EnvironmentProviderPhase =
| 'booting'
/** The repo clones in the VM after it is up; `percent` is git's overall progress. */
| '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'
@@ -37,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
@@ -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,14 +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.
features: ['clone-progress']
// 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, {
@@ -205,6 +205,24 @@ describe('waitForClone', () => {
expect(destroyed).toEqual([])
})
it('an environment boot reports its fetch as an update', async () => {
const { client } = fakeClient([
{ state: 'running', percent: 30, stage: 'download' },
{ state: 'done' }
])
const progress: unknown[] = []
await waitForClone(
client,
'sbx_1',
{ onProgress: (p) => progress.push(p) },
{ pollMs: 0, mode: 'update' }
)
expect(progress).toEqual([
{ phase: 'updating' },
{ phase: 'updating', percent: 30, message: 'download' }
])
})
it('a failed clone deletes the sandbox and fails with its reason', async () => {
const { client, destroyed } = fakeClient([{ state: 'failed', reason: 'repo_unreachable' }])
const error = await rejection(waitForClone(client, 'sbx_1', {}, { pollMs: 0 }))
@@ -63,17 +63,30 @@ 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)
await waitForClone(client, ready.sandbox.id, ctx, { mode: ready.clone.mode ?? 'clone' })
}
ctx?.onProgress?.({ phase: 'connecting' })
return toReady(ready)
@@ -175,9 +188,14 @@ export async function waitForClone(
client: Pick<HostedSandboxControlPlaneClient, 'cloneStatus' | 'destroy'>,
sandboxId: string,
ctx?: EnvironmentProviderCallContext,
{ now = Date.now, pollMs = CLONE_POLL_MS }: { now?: () => number; pollMs?: number } = {}
{
now = Date.now,
pollMs = CLONE_POLL_MS,
mode = 'clone'
}: { now?: () => number; pollMs?: number; mode?: 'clone' | 'update' } = {}
): Promise<void> {
ctx?.onProgress?.({ phase: 'cloning' })
const phase = mode === 'update' ? 'updating' : 'cloning'
ctx?.onProgress?.({ phase })
let lastProgress = ''
let movedAt = now()
try {
@@ -203,7 +221,7 @@ export async function waitForClone(
if (progress !== lastProgress) {
lastProgress = progress
movedAt = now()
ctx?.onProgress?.({ phase: 'cloning', percent: status.percent, message: status.stage })
ctx?.onProgress?.({ phase, percent: status.percent, message: status.stage })
}
}
if (now() - movedAt > CLONE_STALL_MS) {
@@ -170,7 +170,7 @@ export function createHostedSandboxStepProvider(
message?: string
}) =>
onStderr?.(
phase === 'cloning' && percent !== undefined
(phase === 'cloning' || phase === 'updating') && percent !== undefined
? `[orca-cloud] clone-progress ${percent} ${message === 'checkout' ? 'checkout' : 'download'}\n`
: `[orca-cloud] ${phase}\n`
)
@@ -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
@@ -11,6 +11,7 @@ import {
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
import { cleanupOwnedEphemeralVmRuntime } from '../ephemeral-vm/owned-runtime-cleanup'
import { stopEphemeralVmRuntimeCleanup } from '../ephemeral-vm/runtime-cleanup-control'
import { suspendEphemeralVmRuntime } from '../ephemeral-vm/runtime-service'
import {
buildEphemeralVmRecipeCleanupCommand,
buildEphemeralVmRecipeCleanupPayload
@@ -118,6 +119,7 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void {
ipcMain.removeHandler('ephemeralVm:attachWorkspace')
ipcMain.removeHandler('ephemeralVm:listRuntimes')
ipcMain.removeHandler('ephemeralVm:cleanup')
ipcMain.removeHandler('ephemeralVm:suspendRuntime')
ipcMain.removeHandler('ephemeralVm:preflightCloudDelete')
ipcMain.removeHandler('ephemeralVm:stopCleanup')
ipcMain.removeHandler('ephemeralVm:forgetRuntime')
@@ -159,6 +161,32 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void {
}
)
// A create blocked on a failed environment check holds a sandbox no workspace owns yet, so the
// window's idle sleep never sees it. The build sheet sleeps it after a few unused minutes.
ipcMain.handle(
'ephemeralVm:suspendRuntime',
async (_event, args: { runtimeId: string }): Promise<{ ok: boolean; error?: string }> => {
const userDataPath = app.getPath('userData')
const runtimeId = String(args?.runtimeId ?? '')
const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId)
if (!runtime || runtime.workspaceId || runtime.recipe?.provider !== 'orca-cloud') {
return { ok: false, error: 'Not a sandbox waiting on its create.' }
}
try {
const context = getRuntimeRecipeContext(store, userDataPath, runtimeId)
const result = await suspendEphemeralVmRuntime({
userDataPath,
repoPath: context.repoPath,
recipe: context.recipe,
runtimeId
})
return result.ok ? { ok: true } : { ok: false, error: result.error }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
)
ipcMain.handle(
'ephemeralVm:stopCleanup',
async (_event, args: { runtimeId: string }): Promise<EphemeralVmRuntimeRecord> => {
+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)
+5
View File
@@ -112,6 +112,11 @@ export type EphemeralVmApi = {
suspendWorkspace: (args: { workspaceId: string }) => Promise<EphemeralVmWorkspaceLifecycleResult>
/** Fires after any runtime record write; re-list to read the new lifecycle status. */
onRuntimesChanged: (callback: () => void) => () => void
/**
* Orca Cloud: puts a sandbox that never became a workspace to sleep (a create blocked on a
* failed environment check). Optional: the web client has no VM lifecycle.
*/
suspendRuntime?: (args: { runtimeId: string }) => Promise<{ ok: boolean; error?: string }>
cleanup: (args: { runtimeId: string }) => Promise<EphemeralVmRuntimeRecord>
/** Orca Cloud: before Delete drops the row, prove the signed-in identity can reach the sandbox. */
preflightCloudDelete?: (args: {
+1
View File
@@ -56,6 +56,7 @@ export const ephemeralVmApi = {
ipcRenderer.on(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener)
return () => ipcRenderer.removeListener(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener)
},
suspendRuntime: (args) => ipcRenderer.invoke('ephemeralVm:suspendRuntime', args),
cleanup: (args) => ipcRenderer.invoke('ephemeralVm:cleanup', args),
preflightCloudDelete: (args) => ipcRenderer.invoke('ephemeralVm:preflightCloudDelete', args),
stopCleanup: (args) => ipcRenderer.invoke('ephemeralVm:stopCleanup', args),
+4
View File
@@ -11,6 +11,8 @@ import { CloudSecretsAskDialogHost } from './components/cloud-secrets-ask/CloudS
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'
@@ -129,6 +131,8 @@ function App(): React.JSX.Element {
<AgentHostPanel />
<SecretRequestUnseenNotifier />
<TeamDialogHost />
<TeammateProfileDialog />
<PokesNotifier />
</LinkRoutingPreferenceDialogProvider>
</ConfirmationDialogProvider>
{createPortal(
@@ -10,6 +10,7 @@ import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/R
import { FloatingTerminalToggleButton } from '../components/floating-terminal/FloatingTerminalToggleButton'
import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer'
import { WorkspaceLowDiskBanner } from '../components/low-disk/WorkspaceLowDiskBanner'
import { CloudSetupPageLayer } from '../components/orca-cloud-setup/CloudSetupPageLayer'
import type { VirtualizedScrollAnchor } from '../hooks/useVirtualizedScrollAnchor'
import { TitlebarLeftControls } from './TitlebarLeftControls'
import { RightSidebarToggle, TitlebarMainStrip } from './TitlebarMainStrip'
@@ -246,6 +247,7 @@ export function AppWorkspaceShell(props: {
</RecoverableRenderErrorBoundary>
</Suspense>
</div>
<CloudSetupPageLayer />
{floatingWorkspace.showToggleButton && !capturingPluginShot ? (
<MemoFloatingTerminalToggleButton
open={floatingWorkspace.open}
@@ -397,7 +397,7 @@ it('offers Reopen with the submitted target and picker and does not replace a ne
fireEvent.change(textarea(), { target: { value: '--verbose' } })
fireEvent.click(screen.getByRole('radio', { name: 'Low' }))
await useDraft()
const create = await screen.findByRole('button', { name: 'Create worktree' })
const create = await screen.findByRole('button', { name: 'Create workspace' })
await waitFor(() => expect(create.hasAttribute('disabled')).toBe(false))
fireEvent.click(create)
await waitFor(() => expect(evidence.submit).toHaveBeenCalledOnce())
@@ -39,6 +39,7 @@ import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/works
import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows'
import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router'
import { useComposerCloudStart } from './new-workspace/run-on/use-composer-cloud-start'
import { HiddenComposer, useCloudAutoStartReveal } from './new-workspace/composer-cloud-auto-start'
// Keep Add Project’s clone/SSH machinery outside the composer entry render, matching App loading.
const HostedAddRepoDialog = lazyWithRetry(
@@ -80,6 +81,18 @@ function ComposerModalBody({
onClose()
}, [onClose])
const isSubmissionCancelled = useCallback(() => submitCancelledRef.current, [])
const visibleModalData = useCloudAutoStartReveal(modalData)
const body = (
<QuickTabBody
modalData={visibleModalData ?? modalData}
onClose={onClose}
isSubmissionCancelled={isSubmissionCancelled}
active
/>
)
if (!visibleModalData) {
return <HiddenComposer>{body}</HiddenComposer>
}
return (
<Dialog open onOpenChange={(open) => !open && handleDismiss()}>
@@ -98,12 +111,7 @@ function ComposerModalBody({
getWorkspaceComposerInitialFocusTarget(content)?.focus({ preventScroll: true })
}}
>
<QuickTabBody
modalData={modalData}
onClose={onClose}
isSubmissionCancelled={isSubmissionCancelled}
active
/>
{body}
</DialogContent>
</Dialog>
)
@@ -203,14 +211,18 @@ function QuickTabBody({
[observation.contextKey, orcaCloud]
)
// Orca Cloud with an agent that has no account there starts a plain terminal, never the agent's
// /login: the cloud hook sets this around one create (read before the first await).
const noAgentRef = useRef(false)
const handleCreate = useCallback(async (): Promise<void> => {
const agent = noAgentRef.current ? null : quickAgent
if (createDisabled) {
return
}
await submitQuick(quickAgent, {
await submitQuick(agent, {
// Blank Terminal is the setup-only create: no agent, and no extra shell beside setup.
setupOnly: quickAgent === null,
launchChoice: launchSelection.choice,
setupOnly: agent === null,
...(agent === null ? {} : { launchChoice: launchSelection.choice }),
onLegacyPreparationFailure: (error) => {
if (isSubmissionCancelled()) {
return
@@ -266,6 +278,8 @@ function QuickTabBody({
quickAgent,
handleCreate,
createDisabled,
quickAgentPick,
noAgentRef,
recordCreatedRef,
onClose
})
@@ -304,14 +318,10 @@ function QuickTabBody({
const isFolderWorkspaceTarget =
cardProps.projectOptions.find((option) => option.id === cardProps.selectedProjectId)?.kind ===
'project-group'
// An Orca Cloud sandbox is a whole workspace, not a local worktree.
const primaryActionLabel =
cloudStart.primaryActionLabel ??
(isFolderWorkspaceTarget
? getFolderWorkspacePrimaryActionLabel(t)
: cardProps.selectedRepoIsGit && !orcaCloud
? t('auto.components.NewWorkspaceComposerModal.createWorktree', 'Create worktree')
: t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace'))
// Run on never changes the button, and it matches the title for every target (design-squad).
const primaryActionLabel = isFolderWorkspaceTarget
? getFolderWorkspacePrimaryActionLabel(t)
: t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace')
// Let Radix own Escape for the topmost layer. This dialog auto-focuses input, so page-style blur-first handling swallowed its first Escape.
const nestedDialogOpen = agentSettingsOpen || addProjectOpen || setLocationOpen
@@ -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,12 @@ 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: [
@@ -16,7 +16,6 @@ type NewWorkspaceComposerFooterProps = Pick<
| 'createDisabled'
| 'creating'
| 'primaryActionLabel'
| 'cloudStart'
> & {
submitShortcutModifierLabel: string
}
@@ -30,13 +29,9 @@ export function NewWorkspaceComposerFooter({
createDisabled,
creating,
primaryActionLabel,
submitShortcutModifierLabel,
cloudStart
submitShortcutModifierLabel
}: NewWorkspaceComposerFooterProps): React.JSX.Element {
const t = useTranslate()
const heldReasonId = React.useId()
// B2: Start stays focusable but aria-disabled, saying why ("Switch to acme first").
const heldReason = cloudStart?.primaryHeldReason
return (
<>
{createError ? (
@@ -56,16 +51,16 @@ export function NewWorkspaceComposerFooter({
</div>
) : null}
{/* Wraps instead of overflowing: "Use this computer instead" plus a long primary label
("Give access and start") don't fit beside "Create more" in the modal's width. */}
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
{/* One row: "Create more" on the left, the one primary button on the right. Run on never
adds buttons here; Orca Cloud setup happens on its own page after the button. */}
<div className="flex items-center justify-between gap-3">
{showCreateMultiple ? (
<button
type="button"
role="switch"
aria-checked={createMultiple}
onClick={() => onCreateMultipleChange?.(!createMultiple)}
className="group flex w-fit cursor-pointer items-center gap-2 rounded-md text-xs outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-focus-ring"
className="group flex w-fit shrink-0 cursor-pointer items-center gap-2 rounded-md text-xs outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-focus-ring"
>
<SwitchIndicator checked={createMultiple} />
<span className="whitespace-nowrap text-muted-foreground transition-colors group-hover:text-foreground">
@@ -73,32 +68,19 @@ export function NewWorkspaceComposerFooter({
</span>
</button>
) : null}
<div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-2">
{cloudStart?.onUseThisComputer ? (
<Button type="button" variant="ghost" size="sm" onClick={cloudStart.onUseThisComputer}>
{t('components.newWorkspace.cloudStart.useThisComputer', 'Use this computer instead')}
</Button>
) : null}
<Button
onClick={heldReason ? undefined : () => void onCreate()}
disabled={createDisabled}
aria-disabled={heldReason ? true : undefined}
aria-describedby={heldReason ? heldReasonId : undefined}
title={heldReason}
variant={heldReason ? 'default-held' : 'default'}
size="sm"
className="text-xs"
>
<Button
onClick={() => void onCreate()}
disabled={createDisabled}
size="sm"
className="ml-auto shrink-0"
>
{/* The footer's compact type, as before; the Button keeps its own variant styling. */}
<span className="flex items-center gap-1.5 whitespace-nowrap text-xs">
{creating ? <LoaderCircle className="size-4 animate-spin" /> : null}
{primaryActionLabel}
<ButtonKeyHint modifierLabel={submitShortcutModifierLabel} />
</Button>
</div>
{heldReason ? (
<span id={heldReasonId} className="sr-only">
{heldReason}
</span>
) : null}
</Button>
</div>
</>
)
@@ -1,11 +1,10 @@
import React, { useState } from 'react'
import React from 'react'
import { FolderPlus, LoaderCircle, PlugZap } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import ProjectCombobox from '@/components/new-workspace/ProjectCombobox'
import RunTargetCombobox from '@/components/new-workspace/RunTargetCombobox'
import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
import { OrcaCloudAgentSetupRow } from './OrcaCloudAgentSetupRow'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/utils'
import { getSelectedNewWorkspaceProjectOptionId } from '@/lib/new-workspace-project-options'
@@ -15,15 +14,7 @@ import type {
NewWorkspaceComposerCardProps
} from './new-workspace-composer-card-props'
import { EMPTY_PROJECT_OPTIONS } from './new-workspace-composer-card-props'
import { OrcaCloudSelectionHint } from './OrcaCloudSelectionHint'
import RunOnSegmentedControl from './run-on/RunOnSegmentedControl'
import { RunOnHintLine } from './run-on/RunOnHintLine'
import { OrcaCloudSetupPanel } from './run-on/OrcaCloudSetupPanel'
import { CloudSetupBrowserTracker } from './cloud-setup/CloudSetupBrowserTracker'
import { isOrcaCloudRecipe, isOrcaCloudSelection } from './run-target-options'
import { useOrcaCloudRunTargetAccess } from './orca-cloud-billing-cache'
import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access'
import { FolderGitHubActions } from './run-on/FolderGitHubActions'
type NewWorkspaceComposerProjectSectionProps = Pick<
NewWorkspaceComposerCardProps,
@@ -46,26 +37,25 @@ type NewWorkspaceComposerProjectSectionProps = Pick<
| 'ephemeralVmRecipeError'
| 'orcaCloudAvailability'
| 'cloudStart'
> &
Partial<Pick<NewWorkspaceComposerCardProps, 'quickAgent'>> & {
disabled?: boolean
projectDescriptionId: string
onAddProject: () => void
focusNameInput: () => void
shouldShowRunTargetPicker: boolean
projectHostSetupOptions: NewWorkspaceComposerCardProps['projectHostSetupOptions']
ephemeralVmRecipes: EphemeralVmRecipeOption[]
handleProjectHostSetupChange: (setupId: string) => void
handleAddSshHost: () => void
handleAddRemoteServer: () => void
handleConnectRunTargetHost: (option: NeedsProjectHostOption) => Promise<void>
handleSetLocation: (option: NeedsProjectHostOption) => void
sshStatusLabel: string
connectButtonLabel: string
selectedProjectName: string
/** Fixtures pin Orca Cloud entitlement; the app reads it from billing. */
orcaCloudAccess?: OrcaCloudRunTargetAccess
}
> & {
disabled?: boolean
projectDescriptionId: string
onAddProject: () => void
focusNameInput: () => void
shouldShowRunTargetPicker: boolean
projectHostSetupOptions: NewWorkspaceComposerCardProps['projectHostSetupOptions']
ephemeralVmRecipes: EphemeralVmRecipeOption[]
handleProjectHostSetupChange: (setupId: string) => void
handleAddSshHost: () => void
handleAddRemoteServer: () => void
handleConnectRunTargetHost: (option: NeedsProjectHostOption) => Promise<void>
handleSetLocation: (option: NeedsProjectHostOption) => void
sshStatusLabel: string
connectButtonLabel: string
selectedProjectName: string
/** Fixtures pin Orca Cloud entitlement; the app reads it from billing. */
orcaCloudAccess?: OrcaCloudRunTargetAccess
}
export function NewWorkspaceComposerProjectSection({
disabled = false,
@@ -102,7 +92,6 @@ export function NewWorkspaceComposerProjectSection({
connectButtonLabel,
selectedProjectName,
orcaCloudAccess,
quickAgent = null,
cloudStart = null
}: NewWorkspaceComposerProjectSectionProps): React.JSX.Element {
// D4 rows: while Orca Cloud is picked, and for a folder, which can only start from GitHub.
@@ -110,15 +99,12 @@ export function NewWorkspaceComposerProjectSection({
selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID || cloudStart?.folderProject
? cloudStart?.cloudOnly
: undefined
const [pickerSignal, setPickerSignal] = useState(0)
const t = useTranslate()
const orcaCloudOffered = shouldShowRunTargetPicker && ephemeralVmRecipes.some(isOrcaCloudRecipe)
// Shared with the picker; mounting the composer prefetches it so the row rarely shows a skeleton.
const fetchedOrcaCloudAccess = useOrcaCloudRunTargetAccess(orcaCloudOffered && !orcaCloudAccess)
return (
<fieldset disabled={disabled} className="space-y-1">
{/* Run on as segments needs the full width, so it sits under the project (spec E1). */}
<div className={cn('grid gap-3', shouldShowRunTargetPicker && !cloudStart && 'grid-cols-2')}>
{/* One row, two equal columns: Project | Run on. Picking a target never changes the rows
below it, so the dialog keeps its height (composer-redo). */}
<div className={cn('grid gap-3', shouldShowRunTargetPicker && 'grid-cols-2')}>
<div className="min-w-0 space-y-1">
<div className="flex h-5 items-center justify-between gap-2">
<label className="text-xs font-medium text-muted-foreground">
@@ -169,7 +155,6 @@ export function NewWorkspaceComposerProjectSection({
cloudOnly?.pick(fullName)
cloudStart?.onSelectOrcaCloud()
}}
openSignal={pickerSignal}
onMoreCloudAccess={cloudOnly?.moreAccess}
onShowMoreCloudRepos={cloudOnly?.showMore ?? null}
placeholder={
@@ -200,96 +185,37 @@ export function NewWorkspaceComposerProjectSection({
<label className="flex h-5 min-w-0 items-center truncate text-xs font-medium text-muted-foreground">
{t('auto.components.NewWorkspaceComposerCard.runOn', 'Run on')}
</label>
{cloudStart ? (
<RunOnSegmentedControl
cloudOnlyRepo={Boolean(cloudOnly?.picked)}
hostOptions={projectHostSetupOptions ?? []}
hostValue={selectedProjectHostSetupId ?? null}
hostExecutionHostId={selectedRepoExecutionHostId}
onHostChange={handleProjectHostSetupChange}
recipes={ephemeralVmRecipes}
recipeValue={selectedEphemeralVmRecipeId}
onRecipeChange={onEphemeralVmRecipeChange}
onAddSshHost={handleAddSshHost}
onAddRemoteServer={handleAddRemoteServer}
onConnectHost={handleConnectRunTargetHost}
onSetLocation={handleSetLocation}
orcaCloudAvailability={orcaCloudAvailability}
{...(orcaCloudAccess ? { orcaCloudAccess } : {})}
onSelectOrcaCloud={cloudStart.onSelectOrcaCloud}
onUserPick={cloudStart.onUserPick}
/>
) : (
<RunTargetCombobox
hostOptions={projectHostSetupOptions ?? []}
hostValue={selectedProjectHostSetupId ?? null}
hostExecutionHostId={selectedRepoExecutionHostId}
onHostChange={handleProjectHostSetupChange}
recipes={ephemeralVmRecipes}
recipeValue={selectedEphemeralVmRecipeId}
onRecipeChange={onEphemeralVmRecipeChange}
onAddSshHost={handleAddSshHost}
onAddRemoteServer={handleAddRemoteServer}
onConnectHost={handleConnectRunTargetHost}
onSetLocation={handleSetLocation}
orcaCloudAvailability={orcaCloudAvailability}
{...(orcaCloudAccess ? { orcaCloudAccess } : {})}
/>
)}
<RunTargetCombobox
hostOptions={projectHostSetupOptions ?? []}
hostValue={selectedProjectHostSetupId ?? null}
hostExecutionHostId={selectedRepoExecutionHostId}
onHostChange={(setupId) => {
cloudStart?.onUserPick()
handleProjectHostSetupChange(setupId)
}}
recipes={ephemeralVmRecipes}
recipeValue={selectedEphemeralVmRecipeId}
onRecipeChange={(recipeId) => {
cloudStart?.onUserPick()
onEphemeralVmRecipeChange?.(recipeId)
}}
onAddSshHost={handleAddSshHost}
onAddRemoteServer={handleAddRemoteServer}
onConnectHost={handleConnectRunTargetHost}
onSetLocation={handleSetLocation}
orcaCloudAvailability={orcaCloudAvailability}
{...(orcaCloudAccess ? { orcaCloudAccess } : {})}
// Setup happens after Start, on its own page: picking Orca Cloud just picks it.
{...(cloudStart ? { onSelectOrcaCloud: cloudStart.onSelectOrcaCloud } : {})}
/>
{ephemeralVmRecipeError ? (
<p className="whitespace-pre-line text-[11px] text-destructive">
{ephemeralVmRecipeError}
</p>
) : cloudStart && selectedEphemeralVmRecipeId !== ORCA_CLOUD_RECIPE_ID ? (
<RunOnHintLine
hostOptions={projectHostSetupOptions ?? []}
selectedHostId={selectedProjectHostSetupId ?? null}
recipes={ephemeralVmRecipes}
selectedRecipeId={selectedEphemeralVmRecipeId}
orcaCloudAvailability={orcaCloudAvailability}
/>
) : orcaCloudOffered && !cloudStart?.panelVisible ? (
<OrcaCloudSelectionHint
access={orcaCloudAccess ?? fetchedOrcaCloudAccess}
visible={isOrcaCloudSelection({ ephemeralVmRecipes, selectedEphemeralVmRecipeId })}
/>
) : null}
</div>
) : null}
</div>
{cloudStart?.tracker && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? (
// A6: the browser trip is open; the same rows tick in place, with X1 errors.
<CloudSetupBrowserTracker
{...cloudStart.tracker}
steps={cloudStart.steps}
rowActions={cloudStart.rowActions}
/>
) : cloudStart?.panelVisible && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? (
// The panel's own Agent row (G) comes from the same model as the standalone one below.
<OrcaCloudSetupPanel
steps={cloudStart.steps}
allSet={cloudStart.allSet}
rowActions={
cloudStart.folderProject && !cloudOnly?.picked
? {
github: (
<FolderGitHubActions
canChoose={Boolean(cloudOnly?.repos?.length)}
onChooseRepository={() => setPickerSignal((n) => n + 1)}
onAddProject={onAddProject}
/>
)
}
: cloudStart.rowActions
}
/>
) : // Agent row (cloud-start G) without the panel: links to the one-time setup; never blocks Start.
selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? (
<OrcaCloudAgentSetupRow
agent={quickAgent}
access={orcaCloudAccess ?? fetchedOrcaCloudAccess}
/>
) : null}
{!shouldShowRunTargetPicker && ephemeralVmRecipeError ? (
<p className="whitespace-pre-line text-2xs text-destructive">{ephemeralVmRecipeError}</p>
) : null}
@@ -1,283 +0,0 @@
import React from 'react'
import { cn } from '@/lib/utils'
import { useTranslate } from '@/i18n/use-translate'
import { getOrcaCloudPick, type OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access'
import { invalidateOrcaCloudBilling } from './orca-cloud-billing-cache'
import { openPlansPage } from '@/components/billing/plans/plans-page-store'
import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire'
import { OrcaCloudSpecs, useOrcaCloudHoursLeft } from './RunTargetOrcaCloudRow'
import { isOrcaCloudTrialLow } from './run-on/orca-cloud-hours-copy'
/** T1: "Trial · 0.3 sandbox hours left · Choose plan", or who can choose one for members. */
function TrialLowLine({
access,
hoursLeft
}: {
access: OrcaCloudRunTargetAccess
hoursLeft: string | null
}): React.JSX.Element {
const t = useTranslate()
const canChoose = access.state === 'entitled' && access.canManageBilling === true
return (
<>
<p className="flex min-w-0 items-center gap-1.5 font-medium text-status-warning-text">
<span className="truncate">{hoursLeft}</span>
{canChoose ? (
<>
<span aria-hidden>·</span>
<button
type="button"
className="shrink-0 font-medium text-foreground underline underline-offset-2 hover:no-underline"
onClick={() => {
invalidateOrcaCloudBilling({ refetchNow: false })
openPlansPage('sandbox')
}}
>
{t('components.newWorkspace.cloudSetup.choosePlan', 'Choose plan')}
</button>
</>
) : null}
</p>
<p className="truncate">
{canChoose
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudIdleSleep',
'Sleeps after {{count}} minutes idle',
{
count: ORCA_CLOUD_IDLE_SLEEP_MINUTES,
defaultValue_one: 'Sleeps after {{count}} minute idle'
}
)
: t(
'components.newWorkspace.cloudSetup.askChoosePlan',
'Ask an owner or admin to choose a plan.'
)}
</p>
</>
)
}
type BlockCopy = {
title: string
detail: string
tone: 'error' | 'neutral'
/** Owners/admins only; members read who can fix it in `detail`. */
action?: string
}
function useBlockCopy(access: OrcaCloudRunTargetAccess): BlockCopy | null {
const t = useTranslate()
switch (access.state) {
case 'no-plan':
if (access.trialOfferSeconds) {
// B1: the trial is included; Start claims it, so nothing blocks.
return null
}
if (access.trialUsedUp) {
// T2: neutral, nothing failed.
return {
title: t('components.newWorkspace.cloudSetup.trialUsedUpTitle', 'Your trial is used up'),
detail: access.canManageBilling
? t(
'components.newWorkspace.cloudSetup.trialUsedUpChoose',
'Choose a plan to keep using Orca Cloud.'
)
: t(
'components.newWorkspace.cloudSetup.askChoosePlan',
'Ask an owner or admin to choose a plan.'
),
tone: 'neutral',
...(access.canManageBilling
? { action: t('components.newWorkspace.cloudSetup.choosePlan', 'Choose plan') }
: {})
}
}
return {
title: access.lapsed
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudPlanEnded',
'Your Team plan ended'
)
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudNeedsTeamPlan',
'Orca Cloud needs a Team plan.'
),
detail: access.canManageBilling
? ''
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskChoosePlan',
'Ask an owner or admin to choose one.'
),
tone: 'neutral',
...(access.canManageBilling
? {
action: access.lapsed
? t('auto.components.new.workspace.RunTargetCombobox.orcaCloudRenew', 'Renew')
: t('auto.components.new.workspace.RunTargetCombobox.orcaCloudUpgrade', 'Upgrade')
}
: {})
}
case 'out-of-hours': {
const cap = access.cause === 'cap'
// Create time: no workspace exists yet, so "Your files are safe." does not apply here.
return {
title: cap
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudCapReached',
'Spend cap reached'
)
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudOutOfHours',
'Out of sandbox hours'
),
detail: access.canManageBilling
? ''
: cap
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskRaiseSpendCap',
'Ask an owner or admin to raise the spend cap.'
)
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskAddHoursOnly',
'Ask an owner or admin to add hours.'
),
tone: 'neutral',
...(access.canManageBilling
? {
action:
access.cause === 'cap'
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudRaiseSpendCap',
'Raise spend cap'
)
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudTurnOnOverage',
'Turn on overage'
)
}
: {})
}
}
case 'payment-issue':
return {
title: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentFailed',
'Payment failed'
),
detail: access.canManageBilling
? t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentEffect',
"New sandboxes can't start."
)
: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskPayment',
'Ask an owner or admin to update the payment method.'
),
tone: 'error',
...(access.canManageBilling
? {
action: t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudUpdatePaymentMethod',
'Update payment method'
)
}
: {})
}
case 'loading':
case 'unknown':
case 'signed-out':
case 'entitled':
return null
}
}
/**
* Context under Run on once Orca Cloud is the committed target, in exactly two reserved lines so
* neither picking nor a late billing answer moves the form: specs and sandbox hours over idle
* sleep, or what blocks it over who can fix it, with the fix as an inline link. The wrapper is an
* always-mounted polite live region, so a block that arrives after the pick is announced.
*/
export function OrcaCloudSelectionHint({
access,
visible
}: {
access: OrcaCloudRunTargetAccess
/** Orca Cloud is the committed target; otherwise the two lines stay empty. */
visible: boolean
}): React.JSX.Element {
const t = useTranslate()
const block = useBlockCopy(access)
const hoursLeft = useOrcaCloudHoursLeft(access)
// T1: under half an hour of trial left, announced once as it crosses (the live region below).
const low = isOrcaCloudTrialLow(access)
const pick = getOrcaCloudPick(access)
const action =
block?.action && pick.kind === 'act' ? (
<button
type="button"
className="shrink-0 font-medium text-foreground underline underline-offset-2 hover:no-underline"
onClick={() => {
// The fix finishes elsewhere; reread billing when the user comes back.
invalidateOrcaCloudBilling({ refetchNow: false })
pick.run()
}}
>
{block.action}
</button>
) : null
return (
// @container: the specs drop out whole when the column is narrow, instead of ellipsizing.
<div className="@container h-8 text-2xs leading-4 tabular-nums text-muted-foreground">
{visible && !block && !low ? (
// Outside the live region: hour ticks on refresh are not re-announced.
<>
<p className="flex min-w-0">
<span className="truncate">
<OrcaCloudSpecs t={t} />
</span>
{hoursLeft ? (
// pl-1: a flex item trims its leading space, so the gap before "·" comes from padding.
<span className="shrink-0 whitespace-nowrap pl-1">
{'· '}
{hoursLeft}
</span>
) : null}
</p>
<p className="truncate">
{/* One source for n: the control plane, billing and every surface read this constant. */}
{t(
'auto.components.new.workspace.RunTargetCombobox.orcaCloudIdleSleep',
'Sleeps after {{count}} minutes idle',
{
count: ORCA_CLOUD_IDLE_SLEEP_MINUTES,
defaultValue_one: 'Sleeps after {{count}} minute idle'
}
)}
</p>
</>
) : null}
{/* Always mounted, so a block that arrives after the pick (late billing, restored draft) is announced. */}
<div aria-live="polite">
{visible && !block && low ? <TrialLowLine access={access} hoursLeft={hoursLeft} /> : null}
{visible && block ? (
<>
<p
className={cn(
'flex min-w-0 items-center gap-1.5 font-medium',
block.tone === 'error' ? 'text-foreground' : 'text-status-warning-text'
)}
>
{block.tone === 'error' ? (
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-destructive" />
) : null}
<span className="truncate">{block.title}</span>
{action ? <span aria-hidden>·</span> : null}
{action}
</p>
{block.detail ? <p className="truncate">{block.detail}</p> : null}
</>
) : null}
</div>
</div>
)
}
@@ -16,6 +16,7 @@ import {
getRunTargetFieldText,
getRecipeSubmenuItemKey,
getRunTargetSubmenuItemKeys,
closingFirst,
getRunTargetCurrentRowKey,
getRunTargetOptionId,
RUN_TARGET_ADD_HOST_KEY,
@@ -50,19 +51,11 @@ type RunTargetComboboxProps = {
orcaCloudAccess?: OrcaCloudRunTargetAccess
/** From main: drives the sign-in/upsell row when there is no Orca Cloud recipe. */
orcaCloudAvailability?: OrcaCloudAvailability
}
/** Add-host actions open dialogs, so the picker closes before they run. */
function closingFirst(
close: () => void,
action: (() => void) | undefined
): (() => void) | undefined {
return action
? () => {
close()
action()
}
: undefined
/**
* The composer's pick: Orca Cloud is selected even while the account needs setup, which then
* happens on a page after Start. Without it, a blocked account's pick runs the fix instead.
*/
onSelectOrcaCloud?: () => void
}
const ROOT_ATTRIBUTE = 'data-run-target-combobox-root'
@@ -81,7 +74,8 @@ export default function RunTargetCombobox({
onConnectHost,
onSetLocation,
orcaCloudAccess: orcaCloudAccessOverride,
orcaCloudAvailability = 'unavailable'
orcaCloudAvailability = 'unavailable',
onSelectOrcaCloud
}: RunTargetComboboxProps): React.JSX.Element {
const t = useTranslate()
// Track in-flight connects per host so one stalling connect never blocks the others.
@@ -173,7 +167,8 @@ export default function RunTargetCombobox({
override: orcaCloudAccessOverride,
open,
close,
selectRecipe
selectRecipe,
...(onSelectOrcaCloud ? { onSelectOrcaCloud } : {})
})
const addSshHost = useMemo(() => closingFirst(close, onAddSshHost), [close, onAddSshHost])
@@ -332,7 +327,9 @@ export default function RunTargetCombobox({
onKeyDown={handleKeyDown}
/>
<PopoverContent
align="start"
// Right column of the composer: grow leftwards from the trigger so the menu stays inside
// the dialog.
align="end"
sideOffset={4}
className={cn(
'flex w-[var(--radix-popover-trigger-width)] min-w-[18rem] flex-col p-0',
@@ -404,6 +401,7 @@ export default function RunTargetCombobox({
onSelectRecipe={selectRecipe}
onSelectOrcaCloud={selectOrcaCloud}
onOrcaCloudBlockedAction={runOrcaCloudBlockedAction}
orcaCloudSetupAfterStart={Boolean(onSelectOrcaCloud)}
onConnectHost={(option) => void connectHost(option)}
onSetLocation={setLocation}
/>
@@ -270,6 +270,24 @@ function OrcaCloudMeta({
}
}
/**
* In the composer, hours and plan details wait until after create (Neil): the row only keeps what
* explains why it can't be picked, "Ask an owner or admin".
*/
function showsMetaAfterStart(access: OrcaCloudRunTargetAccess): boolean {
switch (access.state) {
case 'no-plan':
case 'out-of-hours':
case 'payment-issue':
return !access.canManageBilling
case 'loading':
case 'entitled':
case 'signed-out':
case 'unknown':
return false
}
}
/** Orca Cloud as a first-class Run-on target, with its hours or the fix for what blocks it. */
export function RunTargetOrcaCloudRow({
recipe,
@@ -280,7 +298,8 @@ export function RunTargetOrcaCloudRow({
optionId,
onArm,
onSelect,
onBlockedAction
onBlockedAction,
setupAfterStart = false
}: {
recipe: EphemeralVmRecipeOption | null
access: OrcaCloudRunTargetAccess
@@ -292,6 +311,8 @@ export function RunTargetOrcaCloudRow({
onArm: () => void
onSelect: () => void
onBlockedAction: () => void
/** The composer walks setup on a page after Start: no inline Sign in / Upgrade here. */
setupAfterStart?: boolean
}): React.JSX.Element {
const t = useTranslate()
return (
@@ -320,7 +341,11 @@ export function RunTargetOrcaCloudRow({
onArm={onArm}
onCommit={onSelect}
description={orcaCloudRowHint(access, t)}
trailing={<OrcaCloudMeta access={access} onAction={onBlockedAction} />}
trailing={
setupAfterStart && !showsMetaAfterStart(access) ? undefined : (
<OrcaCloudMeta access={access} onAction={onBlockedAction} />
)
}
/>
)
}
@@ -34,6 +34,7 @@ export default function RunTargetRowList({
onSelectRecipe,
onSelectOrcaCloud,
onOrcaCloudBlockedAction,
orcaCloudSetupAfterStart = false,
onConnectHost,
onSetLocation
}: {
@@ -61,6 +62,8 @@ export default function RunTargetRowList({
onSelectOrcaCloud: (recipe: EphemeralVmRecipeOption | null) => void
/** Plans or billing, for an account that cannot start a sandbox. */
onOrcaCloudBlockedAction: () => void
/** Picking Orca Cloud just picks it; setup comes after Start, so the row offers no fixes. */
orcaCloudSetupAfterStart?: boolean
onConnectHost: (option: NeedsSetupProjectHostOption) => void
onSetLocation: (option: NeedsSetupProjectHostOption) => void
}): React.JSX.Element {
@@ -101,6 +104,7 @@ export default function RunTargetRowList({
onArm={() => onArm(row.key, null)}
onSelect={() => onSelectOrcaCloud(row.recipe)}
onBlockedAction={onOrcaCloudBlockedAction}
setupAfterStart={orcaCloudSetupAfterStart}
/>
)
}
@@ -1,207 +0,0 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import { OrcaCloudSetupPanel } from '@/components/new-workspace/run-on/OrcaCloudSetupPanel'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
import { CloudSetupBrowserTracker } from './CloudSetupBrowserTracker'
import { CloudSetupErrorNotice } from './CloudSetupErrorNotice'
import { useCloudSetupSwitchTeamFor } from './CloudSetupSwitchTeam'
import type { CloudSetupError } from './cloud-setup-errors'
import type { PlannedTeam } from './use-switch-to-planned-team'
const noop = (): void => {}
// Agent row in agent-accounts v4 wording (glossary "Agent source").
const NOT_SET_UP =
'Claude isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.'
const FROM_ACCOUNT = 'Claude · from your Orca account'
const SET_UP_ONCE = { label: 'Set up once', onClick: noop }
// A6: account and team done in the browser, GitHub in progress.
const waitingGithub: CloudSetupStep[] = [
{ id: 'account', state: 'done', detail: 'neil@acme.dev' },
{ id: 'team', state: 'done', detail: 'acme · 2 sandbox hours to try Orca Cloud' },
{ id: 'github', state: 'active', detail: 'Waiting for GitHub…' },
{ id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE }
]
// Rows derived from billing before the setup session exists: the plan row is the browser's.
const derived: CloudSetupStep[] = [
{ id: 'account', state: 'done' },
{ id: 'plan', state: 'needed', need: 'plan', canFix: true },
{ id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE }
]
// Signed in, nothing finished yet: the account step is in the browser.
const signingIn: CloudSetupStep[] = [
{ id: 'account', state: 'active' },
{ id: 'team', state: 'pending' },
{ id: 'github', state: 'pending' },
{ id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE }
]
function Tracker({
steps = waitingGithub,
error = null,
canManageBilling = true
}: {
steps?: CloudSetupStep[]
error?: CloudSetupError | null
canManageBilling?: boolean
}): React.JSX.Element {
return (
<div className="p-4">
<CloudSetupBrowserTracker
steps={steps}
error={error}
canManageBilling={canManageBilling}
onCancel={noop}
onCopyLink={noop}
onReopen={noop}
onErrorAction={noop}
/>
</div>
)
}
export const trackerWaitingGithub = defineFixture({ width: 560, render: () => <Tracker /> })
export const trackerSigningIn = defineFixture({
width: 560,
render: () => <Tracker steps={signingIn} />
})
export const trackerDerivedRows = defineFixture({
width: 560,
render: () => <Tracker steps={derived} />
})
const stopped: CloudSetupStep[] = [
{ id: 'account', state: 'done', detail: 'neil@acme.dev' },
{ id: 'team', state: 'done', detail: 'acme' },
{ id: 'plan', state: 'needed', need: 'plan', canFix: true },
{ id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE }
]
export const trackerTimedOut = defineFixture({
width: 560,
render: () => <Tracker steps={stopped} error={{ kind: 'timed_out' }} />
})
export const trackerCheckoutCanceled = defineFixture({
width: 560,
render: () => <Tracker steps={stopped} error={{ kind: 'checkout_canceled' }} />
})
export const trackerBankStep = defineFixture({
width: 560,
render: () => <Tracker steps={stopped} error={{ kind: 'bank_step' }} />
})
export const trackerTrialUnavailable = defineFixture({
width: 560,
render: () => <Tracker steps={stopped} error={{ kind: 'trial_unavailable' }} />
})
export const trackerTrialUnavailableMember = defineFixture({
width: 560,
render: () => (
<Tracker steps={stopped} error={{ kind: 'trial_unavailable' }} canManageBilling={false} />
)
})
export const trackerTeamCreateFailed = defineFixture({
width: 560,
render: () => (
<Tracker
steps={[
{ id: 'account', state: 'done', detail: 'neil@acme.dev' },
{ id: 'team', state: 'failed' },
{ id: 'github', state: 'pending' }
]}
error={{ kind: 'team_create_failed' }}
/>
)
})
export const trackerWrongAccount = defineFixture({
width: 560,
render: () => (
<Tracker
steps={[
{ id: 'account', state: 'failed', detail: 'sam@other.dev' },
{ id: 'team', state: 'pending' },
{ id: 'github', state: 'pending' }
]}
error={{ kind: 'wrong_account', detail: 'sam@other.dev', teamName: 'acme' }}
/>
)
})
// X1: every setup error notice, as in the spec's sheet.
export const x1SetupErrors = defineFixture({
width: 560,
render: () => (
<div className="flex flex-col gap-2 p-4">
{(
[
{ kind: 'timed_out' },
{ kind: 'checkout_canceled' },
{ kind: 'bank_step' },
{ kind: 'trial_unavailable' },
{ kind: 'team_create_failed' },
{ kind: 'wrong_account', detail: 'sam@other.dev', teamName: 'acme' }
] satisfies CloudSetupError[]
).map((error) => (
<CloudSetupErrorNotice key={error.kind} error={error} onAction={noop} />
))}
<CloudSetupErrorNotice
error={{ kind: 'trial_unavailable' }}
canManageBilling={false}
onAction={noop}
/>
</div>
)
})
// B1: an owner whose team never had a trial: the trial is the first plan, no trip.
export const b1OwnerTrialAvailable = defineFixture({
width: 560,
render: () => (
<div className="p-4">
<OrcaCloudSetupPanel
steps={[
{
id: 'plan',
state: 'done',
detail: '2 sandbox hours to try Orca Cloud · no card needed'
},
{ id: 'github', state: 'done', detail: 'acme/web' },
{ id: 'agent', state: 'done', detail: FROM_ACCOUNT }
]}
/>
</div>
)
})
function SwitchTeamPanel({ teams }: { teams: PlannedTeam[] }): React.JSX.Element {
const b2 = useCloudSetupSwitchTeamFor(teams, noop)
return (
<div className="h-[260px] p-4">
<OrcaCloudSetupPanel
steps={[
{ id: 'account', state: 'done', detail: 'neil@acme.dev · Personal account' },
...(b2 ? [b2.step] : []),
{ id: 'github', state: 'done', detail: 'acme/web' }
]}
rowActions={b2 ? { team: b2.action } : undefined}
/>
</div>
)
}
// B2: personal account, but a team the user is on has a plan: switch instead of buying.
export const b2SwitchTeam = defineFixture({
width: 560,
render: () => <SwitchTeamPanel teams={[{ orgId: 'org_acme', name: 'acme', planLabel: 'Team' }]} />
})
export const b2SwitchTeamMenu = defineFixture({
width: 560,
render: () => (
<SwitchTeamPanel
teams={[
{ orgId: 'org_acme', name: 'acme', planLabel: 'Team' },
{ orgId: 'org_side', name: 'side-project', planLabel: 'Team' }
]}
/>
)
})
@@ -1,120 +0,0 @@
// A6 "Finish in your browser": while the one setup tab is open, the panel ticks each step in place
// (from the setup session, or rows derived from billing until it exists), says why it stopped (X1)
// and keeps the way back to the browser one click away. The prompt stays editable above it.
import React from 'react'
import { Copy, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useTranslate } from '@/i18n/use-translate'
import { OrcaCloudSetupPanel } from '@/components/new-workspace/run-on/OrcaCloudSetupPanel'
import type {
CloudSetupStep,
CloudSetupStepId
} from '@/components/new-workspace/run-on/cloud-start-model'
import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry'
import { CloudSetupErrorNotice } from './CloudSetupErrorNotice'
import type { CloudSetupError, CloudSetupErrorAction } from './cloud-setup-errors'
export type CloudSetupBrowserTrackerProps = {
steps: readonly CloudSetupStep[]
/** Why setup stopped (X1), from the session's `error`; null while it's going. */
error: CloudSetupError | null
/** Members get "Ask an owner or admin…" instead of Choose plan on trial_unavailable. */
canManageBilling?: boolean
/** Setup session id, for telemetry only (never sent). Omit for derived rows. */
sessionId?: string | null
/** Ends the trip; finished steps stay done. */
onCancel: () => void
/** For a default browser that's the wrong one; hidden when there's no session link to copy. */
onCopyLink?: () => void
onReopen: () => void
onErrorAction: (action: CloudSetupErrorAction) => void
/** Per-row actions passed through to the panel (e.g. the Agent row's "Set up once"). */
rowActions?: Partial<Record<CloudSetupStepId, React.ReactNode>>
/** Trial → plan conversion context for telemetry. */
afterTrial?: boolean
className?: string
}
/**
* Rows derived from billing (before the setup session reports its own) never say 'active'. While
* the browser is open, the first unfinished required row is the one it's working on, so it reads
* "In browser" rather than "Needed". Session rows that already mark a step active pass through.
*/
export function trackerSteps(
steps: readonly CloudSetupStep[],
stopped: boolean
): readonly CloudSetupStep[] {
if (stopped || steps.some((step) => step.state === 'active')) {
return steps
}
const index = steps.findIndex((step) => step.state === 'needed')
if (index === -1) {
return steps
}
return steps.map((step, i) => (i === index ? { ...step, state: 'active' } : step))
}
export function CloudSetupBrowserTracker({
steps,
error,
canManageBilling = true,
sessionId = null,
onCancel,
onCopyLink,
onReopen,
onErrorAction,
rowActions,
afterTrial = false,
className
}: CloudSetupBrowserTrackerProps): React.JSX.Element {
const t = useTranslate()
const errorKind = error?.kind ?? null
const rows = React.useMemo(() => trackerSteps(steps, error !== null), [steps, error])
React.useEffect(() => {
if (sessionId) {
reportCloudSetupProgress(sessionId, rows, errorKind, { afterTrial })
}
}, [sessionId, rows, errorKind, afterTrial])
// The error's own button already offers the browser for these; don't show it twice.
const reopenInError = error !== null && (error.kind === 'timed_out' || error.kind === 'bank_step')
return (
<OrcaCloudSetupPanel
steps={rows}
title={t('components.newWorkspace.cloudSetup.trackerTitle', 'Finish in your browser')}
subtitle={t(
'components.newWorkspace.cloudSetup.trackerSubtitle',
'Orca picks up each step the moment it’s done, then starts this workspace.'
)}
rowActions={rowActions}
className={className}
>
{error ? (
<CloudSetupErrorNotice
error={error}
canManageBilling={canManageBilling}
onAction={onErrorAction}
className="mt-2.5"
/>
) : null}
<div className="mt-2.5 flex flex-wrap items-center gap-2">
<Button type="button" variant="quiet" size="xs" onClick={onCancel}>
{t('components.newWorkspace.cloudSetup.cancelSetup', 'Cancel setup')}
</Button>
<span className="ms-auto flex flex-wrap items-center gap-2">
{onCopyLink ? (
<Button type="button" variant="outline" size="xs" onClick={onCopyLink}>
<Copy aria-hidden />
{t('components.newWorkspace.cloudSetup.copySetupLink', 'Copy setup link')}
</Button>
) : null}
{reopenInError ? null : (
<Button type="button" variant="outline" size="xs" onClick={onReopen}>
{t('components.newWorkspace.cloudSetup.reopenBrowser', 'Reopen browser')}
<ExternalLink aria-hidden />
</Button>
)}
</span>
</div>
</OrcaCloudSetupPanel>
)
}
@@ -20,8 +20,8 @@ async function freshLink(sessionId: string): Promise<string | null> {
function linkUnavailable(): void {
toast.error(
translate(
'components.newWorkspace.cloudSetup.linkUnavailable',
'Couldn’t get a setup link. Try Set up and start again.'
'components.newWorkspace.cloudSetup.linkUnavailableRetry',
'Couldn’t get a setup link. Try Continue in browser again.'
)
)
}
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
import { trackerSteps } from './CloudSetupBrowserTracker'
import { applySwitchTeamStep } from './CloudSetupSwitchTeam'
const derived: CloudSetupStep[] = [
@@ -9,25 +8,6 @@ const derived: CloudSetupStep[] = [
{ id: 'agent', state: 'optional' }
]
describe('trackerSteps', () => {
it('marks the first open row as the browser’s for rows derived from billing', () => {
expect(trackerSteps(derived, false).map((step) => step.state)).toEqual([
'done',
'active',
'optional'
])
})
it('passes session rows that already say active, and stopped trips, through', () => {
const session: CloudSetupStep[] = [
{ id: 'account', state: 'active' },
{ id: 'team', state: 'needed' }
]
expect(trackerSteps(session, false)).toBe(session)
expect(trackerSteps(derived, true)).toBe(derived)
})
})
describe('applySwitchTeamStep', () => {
const team: CloudSetupStep = { id: 'team', state: 'needed', detail: 'acme has a Team plan.' }
@@ -1,117 +1,11 @@
// The composer's side of the setup tracker (A6/X1) and the B2 switch row: what the tracker shows
// while the browser trip is open, and the setup rows with B2's Team row swapped in.
import { useCallback, useMemo, type ReactNode } from 'react'
import { readCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft'
import type { CloudSetupSessionSnapshot } from '@/lib/orca-cloud/cloud-setup-session-seam'
import type {
CloudSetupStep,
CloudSetupStepId
} from '@/components/new-workspace/run-on/cloud-start-model'
import { setupActionFor } from '@/components/new-workspace/run-on/cloud-start-actions'
import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access'
import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types'
import type { CloudSetupBrowserTrackerProps } from './CloudSetupBrowserTracker'
// B2 for Orca Cloud setup: the setup rows with the "Switch to <team>" Team row swapped in.
import { useMemo } from 'react'
import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model'
import {
applySwitchTeamStep,
useCloudSetupSwitchTeam,
type CloudSetupSwitchTeam
} from './CloudSetupSwitchTeam'
import { parseCloudSetupError } from './cloud-setup-errors'
import {
canCopyCloudSetupLink,
copyCloudSetupLink,
reopenCloudSetup
} from './cloud-setup-tracker-actions'
export type CloudSetupTrackerView = Omit<
CloudSetupBrowserTrackerProps,
'steps' | 'rowActions' | 'className'
>
/** What the tracker and B2 add to the composer's CloudStartView. */
export type CloudSetupViewExtras = {
/** Per-row actions in the setup panel (B2's "Switch to <team>"). */
rowActions?: Partial<Record<CloudSetupStepId, ReactNode>>
/** While the setup trip is open in the browser: the tracker replaces the panel (A6, X1). */
tracker?: CloudSetupTrackerView
/** Start is held (aria-disabled) with this reason, e.g. "Switch to acme first" (B2). */
primaryHeldReason?: string
}
/** "Cancel setup": the draft keeps its prompt but forgets the trip (finished steps stay done). */
export function clearCloudSetupSessionFromDraft(profileId: string | null): void {
const draft = readCloudStartDraft(profileId)
if (draft) {
saveCloudStartDraft(profileId, { ...draft, setupSessionId: null })
}
}
/**
* The tracker's props while a trip from this composer is still waiting in the browser, or stopped
* on an error; undefined otherwise. Rows derived from billing (no session yet) work too: Reopen then
* re-runs today's setup action and there is no link to copy.
*/
export function useComposerSetupTracker({
cloudSelected,
setupStarted,
allSet,
readyToStart,
session,
sessionId,
steps,
access,
availability,
profileId,
runSetup,
onCancel
}: {
cloudSelected: boolean
setupStarted: boolean
allSet: boolean
readyToStart: boolean
session: CloudSetupSessionSnapshot | null
sessionId: string | null
steps: readonly CloudSetupStep[]
access: OrcaCloudRunTargetAccess
availability: OrcaCloudAvailability
profileId: string | null
/** A fresh setup trip for whatever is still open. */
runSetup: () => void
/** Ends the trip in the composer; the draft forgets the session here. */
onCancel: () => unknown
}): CloudSetupTrackerView | undefined {
const error = useMemo(() => {
const parsed = parseCloudSetupError(session?.error)
return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed
}, [session?.error, session?.teamName])
const open = cloudSelected && setupStarted && !allSet && (!readyToStart || error !== null)
const rerun = useCallback(
() => setupActionFor(steps, access, availability)?.(),
[access, availability, steps]
)
const canManageBilling = access.state === 'no-plan' ? access.canManageBilling : true
return useMemo(() => {
if (!open) {
return undefined
}
const reopen = (): void => void reopenCloudSetup(sessionId, rerun)
return {
error,
canManageBilling,
sessionId,
onCancel: () => {
onCancel()
clearCloudSetupSessionFromDraft(profileId)
},
...(sessionId && canCopyCloudSetupLink(sessionId)
? { onCopyLink: () => void copyCloudSetupLink(sessionId) }
: {}),
onReopen: reopen,
// A canceled Checkout, a used trial or a failed team: a fresh trip covers what's still open.
onErrorAction: (action) => (action === 'reopen-browser' ? reopen() : runSetup())
}
}, [canManageBilling, error, onCancel, open, profileId, rerun, runSetup, sessionId])
}
/** B2 applied to the setup rows: the rows to show, and the switch when it holds Start. */
export function useSwitchTeamSteps(
@@ -126,16 +20,3 @@ export function useSwitchTeamSteps(
)
return { steps: switched ?? baseSteps, held: switched ? switchTeam : null }
}
/** The view fields the tracker and B2 add. */
export function setupViewExtras(
switchTeam: CloudSetupSwitchTeam | null,
tracker: CloudSetupTrackerView | undefined
): CloudSetupViewExtras {
return {
...(switchTeam
? { rowActions: { team: switchTeam.action }, primaryHeldReason: switchTeam.startHeldReason }
: {}),
...(tracker ? { tracker } : {})
}
}
@@ -0,0 +1,61 @@
// The composer's side of the Orca Cloud setup page (composer-redo): the snapshot the page keeps for
// Back and for its auto-start, and the hidden composer that submits once setup is done.
import React, { useEffect, useState } from 'react'
import { Dialog } from '@/components/ui/dialog'
import type { ComposerModalData } from './composer-modal-data'
/** How long a hidden Orca Cloud auto-start may take before the dialog shows instead. */
const CLOUD_AUTO_START_REVEAL_MS = 8_000
/** The composer as it is now: prompt, project, base branch, linked item and agent pick. */
export function buildComposerSnapshot(
modalData: ComposerModalData,
card: {
name: string
repoId: string
baseBranch?: string
linkedWorkItem?: ComposerModalData['linkedWorkItem']
note: string
},
agentPick: Omit<NonNullable<ComposerModalData['recovery']>, 'note'>
): ComposerModalData {
return {
...modalData,
prefilledName: card.name,
initialRepoId: card.repoId,
...(card.baseBranch ? { initialBaseBranch: card.baseBranch } : {}),
linkedWorkItem: card.linkedWorkItem ?? null,
recovery: { ...agentPick, note: card.note }
}
}
/**
* Setup finished on its page: the composer submits with the dialog unseen. If the start can't run
* by itself in time (a form error, a revoked grant), the dialog appears with everything kept.
* Returns the modal data to render once visible (no second auto-start), or null while hidden.
*/
export function useCloudAutoStartReveal(modalData: ComposerModalData): ComposerModalData | null {
const [revealed, setRevealed] = useState(false)
useEffect(() => {
if (!modalData.cloudAutoStart) {
return
}
const timer = window.setTimeout(() => setRevealed(true), CLOUD_AUTO_START_REVEAL_MS)
return () => window.clearTimeout(timer)
}, [modalData.cloudAutoStart])
if (!modalData.cloudAutoStart) {
return modalData
}
return revealed ? { ...modalData, cloudAutoStart: false } : null
}
/** A closed Root still gives the title its context; nothing is portaled or shown. */
export function HiddenComposer({ children }: { children: React.ReactNode }): React.JSX.Element {
return (
<Dialog open={false}>
<div className="hidden" aria-hidden>
{children}
</div>
</Dialog>
)
}
@@ -38,4 +38,6 @@ export type ComposerModalData = {
telemetrySource?: WorkspaceCreateTelemetrySource
contextualTourSource?: string
setupGuideTourRequestId?: string
/** Orca Cloud setup finished on its page: submit without showing the dialog (falls back to it). */
cloudAutoStart?: boolean
}
@@ -1,328 +0,0 @@
// "Start in Orca Cloud" composer frames from cloud-start-onboarding spec v2: E1, A1, A6, A7, T1,
// T2, E, X2, the panel's GitHub rows D1–D3 and D4's GitHub-only projects. Entry points and T4 are in CloudStartSurfaces.
import { defineFixture } from '../../../component-fixtures/component-fixture'
import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access'
import type { CloudSetupStep } from './cloud-start-model'
import { ComposerPreview } from './cloud-start-preview-fixture'
const setup = (): void => {
window.api.agentApiKeys = undefined
window.api.cloudSecrets = undefined
// No agent-accounts bridge (as in builds without it): the Agent row reads "unavailable" instead
// of awaiting the fixture harness's catch-all mock, which resolves to undefined.
window.api.orcaCloudAgents = undefined
window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true }
}
const entitled: OrcaCloudRunTargetAccess = { state: 'entitled', remainingSeconds: 41 * 3600 }
const trial = (hours: number, canManageBilling = true): OrcaCloudRunTargetAccess => ({
state: 'entitled',
remainingSeconds: hours * 3600,
trial: true,
canManageBilling
})
const githubDone: CloudSetupStep = {
id: 'github',
state: 'done',
label: 'GitHub access',
status: 'Done',
detail: 'acme/web'
}
const githubNeeded: CloudSetupStep = {
id: 'github',
state: 'needed',
need: 'github',
canFix: true,
label: 'GitHub access',
status: 'Needed',
detail: 'Orca Cloud can’t reach acme/billing yet.',
note: 'It clones your code from GitHub. Give access to this repository once.'
}
/** E1: Run on as segments, this computer picked; the machine moves to the hint line. */
export const e1RunOnDefault = defineFixture({
width: 560,
setup,
render: () => <ComposerPreview availability="offered" access={entitled} cloudSelected={false} />
})
/** E1 with "⋯" open: today's host picker without the Orca Cloud row. */
export const e1MorePlaces = defineFixture({
...e1RunOnDefault,
interact: (frame) => {
frame.querySelector<HTMLButtonElement>('[aria-label="More places to run"]')?.click()
}
})
/** A1: Orca Cloud picked while signed out; trial included, one setup trip. */
export const a1SignedOut = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="needs-sign-in"
access={{ state: 'signed-out' }}
cloudSelected
github={{
...githubNeeded,
detail: 'acme/web is private. Orca Cloud needs access to clone it.',
note: undefined
}}
/>
)
})
/** B1: signed in, the team can still get its trial. */
export const b1TrialAvailable = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={{ state: 'no-plan', lapsed: false, canManageBilling: true, trialOfferSeconds: 7200 }}
cloudSelected
github={githubDone}
/>
)
})
/** A6: Finish in your browser; each step ticks in place. */
export const a6FinishInBrowser = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
steps={[
{ id: 'account', state: 'done', detail: 'neil@acme.dev' },
{ id: 'team', state: 'done', detail: 'acme · 2 sandbox hours to try Orca Cloud' },
{ id: 'github', state: 'active', status: 'In browser', detail: 'Waiting for GitHub…' },
{ id: 'agent', state: 'optional' }
]}
/>
)
})
/** A7: everything done; "All set", then the composer starts by itself. */
export const a7AllSet = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={trial(2)}
cloudSelected
allSet
steps={[
{ id: 'account', state: 'done', detail: 'neil@acme.dev' },
{ id: 'plan', state: 'done', label: 'Trial', detail: 'acme · 2 sandbox hours left' },
{ ...githubDone }
]}
/>
)
})
/** T1: trial hours in the composer hint. */
export const t1TrialHint = defineFixture({
width: 560,
setup,
render: () => <ComposerPreview availability="offered" access={trial(1.4)} cloudSelected />
})
/** T1 under half an hour: warning, with Choose plan for owners. */
export const t1TrialLow = defineFixture({
width: 560,
setup,
render: () => <ComposerPreview availability="offered" access={trial(0.3)} cloudSelected />
})
/** T1 low, member: who can choose a plan. */
export const t1TrialLowMember = defineFixture({
width: 560,
setup,
render: () => <ComposerPreview availability="offered" access={trial(0.3, false)} cloudSelected />
})
/** T2: the trial is used up at New workspace; the prompt is kept. */
export const t2TrialUsedUp = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={{ state: 'no-plan', lapsed: false, canManageBilling: true, trialUsedUp: true }}
cloudSelected
prompt="Upgrade Next.js to 16 and fix the type errors."
/>
)
})
/** C1 with the trial used up: a member can't buy, so ⌘↵ runs on this computer. */
export const t2TrialUsedUpMember = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={{ state: 'no-plan', lapsed: false, canManageBilling: false, trialUsedUp: true }}
cloudSelected
prompt="Add rate limiting to the public API routes."
/>
)
})
/** D1: GitHub checked up front; "Give access and start". */
export const d1GitHubNeeded = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
github={githubNeeded}
prompt="Write integration tests for the billing webhooks."
/>
)
})
/** D2: waiting for an owner of the GitHub org; ⌘↵ runs on this computer. */
export const d2GitHubRequested = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
github={{
id: 'github',
state: 'pending',
need: 'github',
blocksStart: true,
label: 'GitHub access',
status: 'Requested',
detail: 'Waiting for an owner of acme on GitHub to approve Orca Cloud.',
note: 'GitHub sent them the request. This workspace starts once they approve, if Orca is open.'
}}
/>
)
})
/** D3: the project isn't on GitHub; outranks account and plan rows. */
export const d3NotOnGitHub = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
github={{
id: 'github',
state: 'failed',
need: 'github',
blocksStart: true,
label: 'GitHub repository',
status: '',
detail: 'Orca Cloud starts from a GitHub repository.',
note: 'Push this project to GitHub, or pick a repository Orca Cloud can reach from Project.',
action: { label: 'How to push', onClick: () => {} }
}}
/>
)
})
const cloudRepos = [
{ fullName: 'acme/billing', url: 'https://github.com/acme/billing', private: true },
{ fullName: 'acme/infra', url: 'https://github.com/acme/infra', private: true },
{ fullName: 'acme/docs', url: 'https://github.com/acme/docs', private: false }
]
/** D4: Orca Cloud picked; the Project picker adds GitHub repositories with no clone here. */
export const d4GitHubProjects = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
cloudRepos={cloudRepos}
/>
),
interact: async (frame) => {
frame.querySelector<HTMLButtonElement>('[aria-label="Browse projects"]')?.click()
await new Promise((resolve) => setTimeout(resolve, 200))
}
})
/** D4 picked: the repository stands in for the project; This computer says why it can't run it. */
export const d4GitHubProjectPicked = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
cloudRepos={cloudRepos}
pickedCloudRepo="acme/billing"
prompt="Write integration tests for the billing webhooks."
/>
)
})
/** D3 for a folder: Orca Cloud stays selectable; the panel offers a GitHub repository instead. */
export const d3FolderProject = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
folderProject
cloudRepos={cloudRepos}
github={{
id: 'github',
state: 'failed',
need: 'github',
blocksStart: true,
label: 'GitHub repository',
status: 'Needed',
detail:
'Orca Cloud starts from a GitHub repository. This project is a folder on this computer.'
}}
prompt="Summarize the notes in this folder."
/>
)
})
/** D3 for a folder, after "Choose a GitHub repository": the picker opens at the D4 section. */
export const d3FolderChooseRepository = defineFixture({
...d3FolderProject,
interact: async (frame) => {
const link = [...frame.querySelectorAll('button')].find((b) =>
b.textContent?.includes('Choose a GitHub repository')
)
link?.click()
await new Promise((resolve) => setTimeout(resolve, 300))
}
})
/** E: returning, entitled; remembered Orca Cloud, no panel, "Start in Orca Cloud". */
export const eReturning = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="offered"
access={entitled}
cloudSelected
github={githubDone}
steps={[{ id: 'account', state: 'done' }, { id: 'plan', state: 'done' }, githubDone]}
prompt="Bump eslint to v10 and fix the new warnings."
/>
)
})
/** X2: Orca Cloud can't be reached; the segment stays, disabled, with the reason. */
export const x2Unreachable = defineFixture({
width: 560,
setup,
render: () => (
<ComposerPreview
availability="unreachable"
access={{ state: 'unknown' }}
cloudSelected={false}
/>
),
interact: async (frame) => {
frame
.querySelector('[role="radio"][aria-disabled="true"]')
?.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' }))
await new Promise((resolve) => setTimeout(resolve, 500))
}
})

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