diff --git a/cloud/apps/acceptance/live/checkpoints-vm.ts b/cloud/apps/acceptance/live/checkpoints-vm.ts new file mode 100644 index 00000000000..4dbb0419035 --- /dev/null +++ b/cloud/apps/acceptance/live/checkpoints-vm.ts @@ -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//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 +type Vm = { id: string; vsession: string; pairingCode: string } + +const timings: Record = {} +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 { + 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 { + 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 (method: string, params: unknown, timeoutMs = 60_000) => { + const response = await connection.request(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 (method: string, params: unknown, timeoutMs?: number) => (await raw(method, params, timeoutMs)).result + return { raw, call, close: () => connection.close() } +} +type Client = ReturnType + +const tail = (client: Client, sessionId: string) => + client.call('agentSession.history', { sessionId, direction: 'tail', limit: 200 }) + +async function startStandin(vm: Vm): Promise { + 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 { + 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 = { + 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 { + 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 { + 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('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('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 { + 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 = {} + 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) + } +) diff --git a/cloud/apps/acceptance/live/standin-anthropic.py b/cloud/apps/acceptance/live/standin-anthropic.py new file mode 100644 index 00000000000..e409c1629b5 --- /dev/null +++ b/cloud/apps/acceptance/live/standin-anthropic.py @@ -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: " 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() diff --git a/cloud/apps/acceptance/src/catalog.ts b/cloud/apps/acceptance/src/catalog.ts index 2ac4c349064..0eeddfe9036 100644 --- a/cloud/apps/acceptance/src/catalog.ts +++ b/cloud/apps/acceptance/src/catalog.ts @@ -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' }, diff --git a/cloud/apps/sandbox-control/image/env/environment-build.sh b/cloud/apps/sandbox-control/image/env/environment-build.sh index 24f4f10c053..595ab970c83 100644 --- a/cloud/apps/sandbox-control/image/env/environment-build.sh +++ b/cloud/apps/sandbox-control/image/env/environment-build.sh @@ -5,7 +5,7 @@ # Everything printed here streams live to the desktop build log. # # Env from the control plane (validated there): ORCA_BUILD_REPOS (`||| -# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus +# ` 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:: ` 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 diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index 4653e949148..3f8787c7247 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -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 ". +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 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 2>&1 & + run_detached clone_repo else clone_repo 2>"$CLONE_DIR/progress.log" || exit 1 fi diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 58c4fb576bd..5aa062f32a8 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -5,6 +5,6 @@ export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","ima export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

ok

' 2>/dev/null | grep -q '

ok

'\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at)\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of listSessions()) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" -export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" +export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` 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\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n # Detached (own session, no inherited stdio): the start command returns while this runs.\n export -f clone_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n clone_repo >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\n\n# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target\n# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have\n# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.\nupdate_repo() {\n local base target status\n base=\"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\"\n target=\"${ref:-$base}\"\n [ -n \"$target\" ] || return 0\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$target:refs/remotes/origin/$target\"\n status=$?\n if [ \"$status\" -eq 0 ]; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$target\" --\n return $?\n fi\n [ \"$status\" -eq 124 ] && return 124\n { [ -n \"$base\" ] && [ \"$base\" != \"$target\" ]; } || return \"$status\"\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$base:refs/remotes/origin/$base\" || return $?\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$base\" --\n}\n\n# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command\n# returns while it runs; $CLONE_DIR/state reads running, then done or \"failed \".\nrun_detached() {\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n export -f clone_repo update_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\" ORCA_PRELUDE_STEP=\"$1\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n \"$ORCA_PRELUDE_STEP\" >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n elif [ \"$ORCA_PRELUDE_STEP\" = update_repo ]; then\n # Not fatal: the build'\"'\"'s checkout is there, just older. The status says so; the create goes on.\n echo \"done stale\" >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n # The desktop shows this as \"Update repository\" (GET /v1/sandboxes/:id/clone): fetch what changed\n # since the build, in the background. A failure leaves the build's commit, which still opens.\n mkdir -p \"$CLONE_DIR\"\n run_detached update_repo\n elif [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n run_detached clone_repo\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql b/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql new file mode 100644 index 00000000000..d07dcd0dfe1 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql @@ -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); diff --git a/cloud/apps/sandbox-control/migrations/0050_team_presence.sql b/cloud/apps/sandbox-control/migrations/0050_team_presence.sql new file mode 100644 index 00000000000..28ee3094a51 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0050_team_presence.sql @@ -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); diff --git a/cloud/apps/sandbox-control/migrations/0052_workspace_attachments.sql b/cloud/apps/sandbox-control/migrations/0052_workspace_attachments.sql new file mode 100644 index 00000000000..2fb12f98cce --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0052_workspace_attachments.sql @@ -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//, 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); diff --git a/cloud/apps/sandbox-control/src/api/attachments.ts b/cloud/apps/sandbox-control/src/api/attachments.ts new file mode 100644 index 00000000000..233555d2c84 --- /dev/null +++ b/cloud/apps/sandbox-control/src/api/attachments.ts @@ -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 { + 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 { + 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() + 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')}` +} diff --git a/cloud/apps/sandbox-control/src/api/messages.ts b/cloud/apps/sandbox-control/src/api/messages.ts index bed03311306..77df1da52c7 100644 --- a/cloud/apps/sandbox-control/src/api/messages.ts +++ b/cloud/apps/sandbox-control/src/api/messages.ts @@ -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 { + 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) diff --git a/cloud/apps/sandbox-control/src/api/models.ts b/cloud/apps/sandbox-control/src/api/models.ts new file mode 100644 index 00000000000..7202e9c98cc --- /dev/null +++ b/cloud/apps/sandbox-control/src/api/models.ts @@ -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 = { + claude: 'Claude Code', + codex: 'Codex', + opencode: 'OpenCode', + gemini: 'Gemini CLI', + cursor: 'Cursor', + copilot: 'GitHub Copilot' +} + +const CATALOGS: Partial> = { + 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=`); 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 + +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 : [] +} diff --git a/cloud/apps/sandbox-control/src/api/openapi.ts b/cloud/apps/sandbox-control/src/api/openapi.ts index f18428d2ea7..7f3514003b4 100644 --- a/cloud/apps/sandbox-control/src/api/openapi.ts +++ b/cloud/apps/sandbox-control/src/api/openapi.ts @@ -99,6 +99,53 @@ const schemas: Record = { 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> = { '/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> = { '/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> = { 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> = { 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_

Point any MCP client at ${o}/mcp (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 → Approve an app, 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.

claude mcp add --transport http orca-cloud ${o}/mcp
 claude mcp add --transport http orca-cloud ${o}/mcp --header "Authorization: Bearer $ORCA_API_KEY"
-

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.

+

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.

+

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 read_session to see what an agent did.

+

New chat, files, stop

+
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"

Limits and errors

Rate limits120 requests/min per key, 30 messages/min per user, 10 workspace creates/min per team. 429 responses carry Retry-After.
diff --git a/cloud/apps/sandbox-control/src/api/router.ts b/cloud/apps/sandbox-control/src/api/router.ts index ba59b0dc4ab..cdc1c9eff21 100644 --- a/cloud/apps/sandbox-control/src/api/router.ts +++ b/cloud/apps/sandbox-control/src/api/router.ts @@ -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 = {}): 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[0], ctx: ApiContext): Promise { @@ -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) => { 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 => { + 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}` }) diff --git a/cloud/apps/sandbox-control/src/api/vm-agent.ts b/cloud/apps/sandbox-control/src/api/vm-agent.ts index 970defd4880..d74e1b3bf25 100644 --- a/cloud/apps/sandbox-control/src/api/vm-agent.ts +++ b/cloud/apps/sandbox-control/src/api/vm-agent.ts @@ -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 { - 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 { + 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 { + 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 { + await orca(provider, sessionId, ['terminal', 'rename', '--terminal', handle, `--title=${title}`], { timeoutMs: 30_000 }) +} + const TerminalList = z.object({ terminals: z.array( z.object({ diff --git a/cloud/apps/sandbox-control/src/auto-environments.ts b/cloud/apps/sandbox-control/src/auto-environments.ts new file mode 100644 index 00000000000..76476b97ab5 --- /dev/null +++ b/cloud/apps/sandbox-control/src/auto-environments.ts @@ -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) => 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 { + 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 { + 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() + 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() + 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 { + 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 { + 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, + environmentId: string +): Promise { + 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 { + 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 +} diff --git a/cloud/apps/sandbox-control/src/clone-status.ts b/cloud/apps/sandbox-control/src/clone-status.ts index 2e3411b24b5..b162cd27ae1 100644 --- a/cloud/apps/sandbox-control/src/clone-status.ts +++ b/cloud/apps/sandbox-control/src/clone-status.ts @@ -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')) { diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 9223685fff2..08ec6d476de 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -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:,` 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. */ diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index f0d02aaadcf..972bbd360f2 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -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, { diff --git a/cloud/apps/sandbox-control/src/environment-routes.ts b/cloud/apps/sandbox-control/src/environment-routes.ts index c8120dbe085..a1edaae0abc 100644 --- a/cloud/apps/sandbox-control/src/environment-routes.ts +++ b/cloud/apps/sandbox-control/src/environment-routes.ts @@ -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() - 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) diff --git a/cloud/apps/sandbox-control/src/environments.ts b/cloud/apps/sandbox-control/src/environments.ts index 39674e57c5a..25a37008848 100644 --- a/cloud/apps/sandbox-control/src/environments.ts +++ b/cloud/apps/sandbox-control/src/environments.ts @@ -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 { 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() + .all() 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 diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 255b4d8b6ec..5edaae7c49a 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -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= -> {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 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 })) + } } }) ) diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 9d3d7e4cf46..c2e9ed5032c 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -96,6 +96,14 @@ export type LifecycleDeps = { * error after boot. Absent: no check. */ publicRepoCheck?: (repoUrl: string) => Promise + /** + * 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 + touch(environmentId: string): Promise + } /** Work that may finish after the response (Worker ctx.waitUntil); absent means fire-and-forget. */ background?: (work: Promise) => 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 - /** 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 diff --git a/cloud/apps/sandbox-control/src/mcp/server.ts b/cloud/apps/sandbox-control/src/mcp/server.ts index 1c737b3c60a..3a2b3d672e6 100644 --- a/cloud/apps/sandbox-control/src/mcp/server.ts +++ b/cloud/apps/sandbox-control/src/mcp/server.ts @@ -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 diff --git a/cloud/apps/sandbox-control/src/mcp/tools.ts b/cloud/apps/sandbox-control/src/mcp/tools.ts index a01351185d2..9977bfb4626 100644 --- a/cloud/apps/sandbox-control/src/mcp/tools.ts +++ b/cloud/apps/sandbox-control/src/mcp/tools.ts @@ -32,6 +32,7 @@ type ToolDef = { // 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) diff --git a/cloud/apps/sandbox-control/src/member-removal.ts b/cloud/apps/sandbox-control/src/member-removal.ts index d63234aa1ff..ec1c42ddbc6 100644 --- a/cloud/apps/sandbox-control/src/member-removal.ts +++ b/cloud/apps/sandbox-control/src/member-removal.ts @@ -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) diff --git a/cloud/apps/sandbox-control/src/member-usage.ts b/cloud/apps/sandbox-control/src/member-usage.ts new file mode 100644 index 00000000000..d030fad3956 --- /dev/null +++ b/cloud/apps/sandbox-control/src/member-usage.ts @@ -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 { + 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() +} diff --git a/cloud/apps/sandbox-control/src/sandbox-provider.ts b/cloud/apps/sandbox-control/src/sandbox-provider.ts index 9f9852141d6..8eba9363a31 100644 --- a/cloud/apps/sandbox-control/src/sandbox-provider.ts +++ b/cloud/apps/sandbox-control/src/sandbox-provider.ts @@ -111,6 +111,11 @@ export type SandboxProviderApi = { updateSnapshotExpiration(name: string, expirationMs: number): Promise /** A small text file from the VM (files API: not kept as command logs). Null when absent. */ readFile(sessionId: string, path: string): Promise + /** + * 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 /** Resolves when already gone. */ deleteSandbox(name: string): Promise listSnapshots(name: string): Promise diff --git a/cloud/apps/sandbox-control/src/tar-gzip.ts b/cloud/apps/sandbox-control/src/tar-gzip.ts new file mode 100644 index 00000000000..c9ff3a940b7 --- /dev/null +++ b/cloud/apps/sandbox-control/src/tar-gzip.ts @@ -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 { + 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() +} diff --git a/cloud/apps/sandbox-control/src/team-presence.ts b/cloud/apps/sandbox-control/src/team-presence.ts new file mode 100644 index 00000000000..621b21e8911 --- /dev/null +++ b/cloud/apps/sandbox-control/src/team-presence.ts @@ -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(days).fill(0) + const tokenUsd = new Array(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 { + 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() + // 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 { + 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, + options: { activitySharing?: ActivitySharing } = {} +): Promise { + 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 +} diff --git a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts index 088c66da934..c19cbcc76f7 100644 --- a/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts +++ b/cloud/apps/sandbox-control/src/vercel-sandbox-api.ts @@ -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)}`, { diff --git a/cloud/apps/sandbox-control/src/wire.ts b/cloud/apps/sandbox-control/src/wire.ts index efc6303704a..5d91dffaea7 100644 --- a/cloud/apps/sandbox-control/src/wire.ts +++ b/cloud/apps/sandbox-control/src/wire.ts @@ -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 } : {}) } } + : {}) } } diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index f29d0c52e5c..0e1480c8b29 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -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=&repo=§ion=&archived=exclude|include|only +// GET /v1/team/workspaces?scope=mine|team|all&by=&repo=§ion=&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() - 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> { + 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() + 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 diff --git a/cloud/apps/sandbox-control/test/api-sessions.test.ts b/cloud/apps/sandbox-control/test/api-sessions.test.ts new file mode 100644 index 00000000000..75e2b457ada --- /dev/null +++ b/cloud/apps/sandbox-control/test/api-sessions.test.ts @@ -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[] = [] + 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>, 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') + }) +}) diff --git a/cloud/apps/sandbox-control/test/auto-environments.test.ts b/cloud/apps/sandbox-control/test/auto-environments.test.ts new file mode 100644 index 00000000000..cb12b135dc8 --- /dev/null +++ b/cloud/apps/sandbox-control/test/auto-environments.test.ts @@ -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[] = [] + const h = await createHarness({ AUTO_ENVIRONMENTS: 'on' }, { waitUntil: (work: Promise) => 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') + }) +}) diff --git a/cloud/apps/sandbox-control/test/create-speed.test.ts b/cloud/apps/sandbox-control/test/create-speed.test.ts index cb19f543a76..94e72d4d0be 100644 --- a/cloud/apps/sandbox-control/test/create-speed.test.ts +++ b/cloud/apps/sandbox-control/test/create-speed.test.ts @@ -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' } }) diff --git a/cloud/apps/sandbox-control/test/fake-vercel.ts b/cloud/apps/sandbox-control/test/fake-vercel.ts index 54bf12b0bfe..d8e59b79073 100644 --- a/cloud/apps/sandbox-control/test/fake-vercel.ts +++ b/cloud/apps/sandbox-control/test/fake-vercel.ts @@ -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') { diff --git a/cloud/apps/sandbox-control/test/harness.ts b/cloud/apps/sandbox-control/test/harness.ts index f741c315869..6687138c0e5 100644 --- a/cloud/apps/sandbox-control/test/harness.ts +++ b/cloud/apps/sandbox-control/test/harness.ts @@ -50,6 +50,8 @@ export async function createHarness(overrides: Partial = {}, 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. diff --git a/cloud/apps/sandbox-control/test/mcp.test.ts b/cloud/apps/sandbox-control/test/mcp.test.ts index 7abafbeeb85..f9e35ac23a8 100644 --- a/cloud/apps/sandbox-control/test/mcp.test.ts +++ b/cloud/apps/sandbox-control/test/mcp.test.ts @@ -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']) diff --git a/cloud/apps/sandbox-control/test/team-presence.test.ts b/cloud/apps/sandbox-control/test/team-presence.test.ts new file mode 100644 index 00000000000..c8e0c256ddd --- /dev/null +++ b/cloud/apps/sandbox-control/test/team-presence.test.ts @@ -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: [] }) + }) +}) diff --git a/cloud/apps/sandbox-control/test/workspaces.test.ts b/cloud/apps/sandbox-control/test/workspaces.test.ts index 7b090930f83..99cd7abebfc 100644 --- a/cloud/apps/sandbox-control/test/workspaces.test.ts +++ b/cloud/apps/sandbox-control/test/workspaces.test.ts @@ -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) diff --git a/src/main/cloud-sync/cloud-sync-session.test.ts b/src/main/cloud-sync/cloud-sync-session.test.ts index 0c9532ae94e..86ac53e9afc 100644 --- a/src/main/cloud-sync/cloud-sync-session.test.ts +++ b/src/main/cloud-sync/cloud-sync-session.test.ts @@ -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) + }) +}) diff --git a/src/main/cloud-sync/cloud-sync-session.ts b/src/main/cloud-sync/cloud-sync-session.ts index 4c3407ba75c..00751981f6c 100644 --- a/src/main/cloud-sync/cloud-sync-session.ts +++ b/src/main/cloud-sync/cloud-sync-session.ts @@ -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 | null = null let safetyTimer: ReturnType | 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 { + 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. */ diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts index b806fdec7dd..1c065a63055 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.test.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.test.ts @@ -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() + }) +}) diff --git a/src/main/cloud-workspaces/cloud-workspaces-client.ts b/src/main/cloud-workspaces/cloud-workspaces-client.ts index a3c3c944453..eb2c62d80f2 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-client.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-client.ts @@ -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 { 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 }) } } } diff --git a/src/main/cloud-workspaces/cloud-workspaces-service.ts b/src/main/cloud-workspaces/cloud-workspaces-service.ts index b11ebde4099..f85615eaa65 100644 --- a/src/main/cloud-workspaces/cloud-workspaces-service.ts +++ b/src/main/cloud-workspaces/cloud-workspaces-service.ts @@ -5,8 +5,10 @@ import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store import { openSealedGrant } from '../../shared/cloud-workspaces/sealed-grant' import { errorMessage } from '../../shared/error-message' import type { + 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 = | { 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 => { + 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)), diff --git a/src/main/environment-doctor/environment-doctor-setup.ts b/src/main/environment-doctor/environment-doctor-setup.ts index edd30791626..dd431e17663 100644 --- a/src/main/environment-doctor/environment-doctor-setup.ts +++ b/src/main/environment-doctor/environment-doctor-setup.ts @@ -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' }) ] } diff --git a/src/main/environment-providers/environment-provider-driver.ts b/src/main/environment-providers/environment-provider-driver.ts index a722e77cee5..e3c5014ca23 100644 --- a/src/main/environment-providers/environment-provider-driver.ts +++ b/src/main/environment-providers/environment-provider-driver.ts @@ -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 diff --git a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts index e5d8c232070..3becff69371 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts @@ -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 get(sandboxId: string, signal?: AbortSignal): Promise + /** 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 list(signal?: AbortSignal): Promise @@ -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, { diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts index f4204d2d2b4..eba428ab237 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts @@ -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 })) diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.ts index 08093cca61a..36ac6af2dba 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.ts @@ -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, 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 { - 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) { diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index 4e416b7a71a..d2ad91005d6 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -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 } : {}) } } diff --git a/src/main/hosted-sandbox/hosted-sandbox-request.ts b/src/main/hosted-sandbox/hosted-sandbox-request.ts index 8163d9aa5f1..f4520cfd976 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-request.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-request.ts @@ -29,6 +29,7 @@ export type HostedSandboxRequest = ( kind: 'boot' | 'control' signal?: AbortSignal features?: readonly string[] + headers?: Record } ) => Promise @@ -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 } ): Promise { 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. diff --git a/src/main/hosted-sandbox/remote-desktop-guest.test.ts b/src/main/hosted-sandbox/remote-desktop-guest.test.ts index c336278d881..e7ca3436614 100644 --- a/src/main/hosted-sandbox/remote-desktop-guest.test.ts +++ b/src/main/hosted-sandbox/remote-desktop-guest.test.ts @@ -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) + }) }) diff --git a/src/main/hosted-sandbox/remote-desktop-guest.ts b/src/main/hosted-sandbox/remote-desktop-guest.ts index 2e07357d636..2f9b400e345 100644 --- a/src/main/hosted-sandbox/remote-desktop-guest.ts +++ b/src/main/hosted-sandbox/remote-desktop-guest.ts @@ -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((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 => { + 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 => { 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 { + async function pause(gen: number, reason: RemoteDesktopPauseReason): Promise { + 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() } } diff --git a/src/main/hosted-sandbox/remote-desktop-pause-copy.ts b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts new file mode 100644 index 00000000000..bd50b2619d0 --- /dev/null +++ b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts @@ -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.' + ) + } +} diff --git a/src/main/ipc/cloud-workspaces-team-presence.ts b/src/main/ipc/cloud-workspaces-team-presence.ts new file mode 100644 index 00000000000..40191550927 --- /dev/null +++ b/src/main/ipc/cloud-workspaces-team-presence.ts @@ -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 +): 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 + }) +} diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index 1aa5060e4aa..f2964c901fa 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -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 diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index 2d1209de786..a6601134042 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -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 => { diff --git a/src/preload/api/browser/browser-api.ts b/src/preload/api/browser/browser-api.ts index 887ea272d3a..ed85892e5fc 100644 --- a/src/preload/api/browser/browser-api.ts +++ b/src/preload/api/browser/browser-api.ts @@ -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 diff --git a/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts b/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts index c6ce70adebb..e546b24839a 100644 --- a/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts +++ b/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts @@ -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) }, diff --git a/src/preload/api/cloud-workspaces-api.ts b/src/preload/api/cloud-workspaces-api.ts index 3b2f55788dc..c965e85bdea 100644 --- a/src/preload/api/cloud-workspaces-api.ts +++ b/src/preload/api/cloud-workspaces-api.ts @@ -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 = | { 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 - list: (query: CloudWorkspaceListQuery) => Promise> + list: (query: CloudWorkspaceListQuery) => Promise get: (id: string) => Promise> patch: (id: string, patch: CloudWorkspacePatch) => Promise> resolveLink: ( @@ -62,6 +69,16 @@ export type CloudWorkspacesApi = { document: OrgPrompts['document'], revision: number ) => Promise> + /** A teammate's profile: usage heatmap (levels only unless it is you) and workspaces you can see. */ + teammateProfile: ( + userId: string, + utcOffsetMin: number + ) => Promise> + /** Pokes (experimental, opt-in on both sides). */ + poke: (userId: string) => Promise> + pokeInbox: () => Promise> + setPokesEnabled: (enabled: boolean) => Promise> + markPokesSeen: (ids: string[]) => Promise> onOpenLink: (callback: (link: string) => void) => () => void consumePendingLink: () => Promise } diff --git a/src/preload/api/cloud-workspaces-bridge.ts b/src/preload/api/cloud-workspaces-bridge.ts index 43d0b5c7aa6..46bab5fcd06 100644 --- a/src/preload/api/cloud-workspaces-bridge.ts +++ b/src/preload/api/cloud-workspaces-bridge.ts @@ -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) diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index e842143d555..12ae965adef 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -112,6 +112,11 @@ export type EphemeralVmApi = { suspendWorkspace: (args: { workspaceId: string }) => Promise /** 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 /** Orca Cloud: before Delete drops the row, prove the signed-in identity can reach the sandbox. */ preflightCloudDelete?: (args: { diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index 2daca4b1614..cf4e82a6289 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -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), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 65d9149536e..f640e779c0d 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -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 { + + {createPortal( diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index df5297cb06d..cddedd2a414 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -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: {
+ {floatingWorkspace.showToggleButton && !capturingPluginShot ? ( expect(create.hasAttribute('disabled')).toBe(false)) fireEvent.click(create) await waitFor(() => expect(evidence.submit).toHaveBeenCalledOnce()) diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 18d17cd45f9..5e5f9c61cba 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -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 = ( + + ) + if (!visibleModalData) { + return {body} + } return ( !open && handleDismiss()}> @@ -98,12 +111,7 @@ function ComposerModalBody({ getWorkspaceComposerInitialFocusTarget(content)?.focus({ preventScroll: true }) }} > - + {body} ) @@ -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 => { + 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 diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index d074ed1f666..8a76f47e261 100644 --- a/src/renderer/src/components/billing/team/TeamDialogHost.tsx +++ b/src/renderer/src/components/billing/team/TeamDialogHost.tsx @@ -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['arrival'] }) { @@ -209,6 +210,11 @@ function TeamPageBody({ arrival }: { arrival: ReturnType { + // 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)} /> diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index b731209e6aa..eb9ddbb9740 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -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( + props.onOpenProfile?.(profileUserId)}> + + {t('auto.components.billing.team.viewProfile', 'View profile')} + + ) + } + // Profile sits apart from the role and membership actions below it. + const separateFromProfile = (): void => { + if (items.length === 1 && profileUserId && props.onOpenProfile) { + items.push() + } + } if (row.kind === 'invite' && row.manageable) { + separateFromProfile() items.push( props.onMakeOwner(row.member)}> @@ -160,6 +187,7 @@ function RowMenu({ ) } if (row.self) { + separateFromProfile() items.push(

- {name} + {profileUserId && props.onOpenProfile ? ( + + ) : ( + {name} + )} {row.self ? ( {t('auto.components.billing.team.you', '(you)')} diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index 25aa08ef480..233f9541c0e 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -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 ? ( diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx index 015330ae64e..70a948cff4e 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx @@ -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)} /> - 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. + reload.reloadWebviewOrRecoverGuest(false)} + navigate={nav.navigateToUrl} + viewportContainer={pageViewport?.container ?? null} + /> + ) : ( + 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( + 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 ( +

+
+ + + {t('components.cloudRemoteDesktop.tabTitle', 'Remote desktop')} + + {t('components.cloudRemoteDesktop.beta', 'Beta')} + + + {phaseLabel(t, phase)} + + + {phase.kind === 'connected' ? ( + + {t( + 'components.cloudRemoteDesktop.tab.releaseHint', + '{{chord}} returns keys to Orca', + { + chord: remoteDesktopReleaseChordLabel() + } + )} + + ) : null} + + +
+
+ ) +} + +function CoverCard({ + busy, + title, + detail, + action +}: { + busy?: boolean + title: string + detail?: string + action?: React.ReactNode +}): React.JSX.Element { + return ( +
+ + {busy ? ( + + ) : ( + + )} + +
+

{title}

+ {detail ?

{detail}

: null} +
+ {action} +
+ ) +} + +/** + * 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 = ( + + ) + break + case 'waking': + body = ( + + ) + break + case 'asleep': + case 'wakeFailed': { + const failed = phase.kind === 'wakeFailed' + body = ( + void wakeCloudWorkspace(worktreeId)} + > + + {failed + ? t('components.cloudRemoteDesktop.retry', 'Try again') + : t('orcaCloudWorkspace.wake', 'Wake')} + + } + /> + ) + break + } + case 'archived': + body = ( + void runUnarchiveCloudWorkspace(worktreeId)} + > + {t('components.cloudRemoteDesktop.unarchive', 'Unarchive')} + + } + /> + ) + break + case 'failed': { + const copy = failureCopy(t, phase.code) + const signIn = copy.action === 'sign_in' + body = ( +
+ + signIn ? void useAppStore.getState().connectCurrentOrcaProfile() : onReconnect() + } + > + {signIn + ? actionLabel(t, 'sign_in') + : t('components.cloudRemoteDesktop.reconnect', 'Reconnect')} + + } + /> +
+ ) + break + } + } + return ( +
+ {body} +
+ ) +} diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx new file mode 100644 index 00000000000..9333e6b31c5 --- /dev/null +++ b/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx @@ -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 + 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 ( + <> + + {viewportContainer + ? createPortal( + , + viewportContainer + ) + : null} + + ) +} diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx index 80d1f85f836..3477fad70f5 100644 --- a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx +++ b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx @@ -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') diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx index dae60301e33..c0a7bfa6ba8 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRow.tsx @@ -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({ )} + {w.fromRoutine === true && ( + + + + + + {t( + 'auto.components.cloudWorkspaces.routineRunTooltip', + "Started by a routine. It's deleted when the run ends." + )} + + + )} {ownerName} + {w.fromRoutine === true && ( + <> + · + + {w.routineName + ? t('auto.components.cloudWorkspaces.routineRunOf', 'Routine · {{name}}', { + name: w.routineName + }) + : t('auto.components.cloudWorkspaces.routineRun', 'Routine run')} + + + )} {showStatus && ( <> · diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx index 42b3eba01f9..62d4f6c8ae9 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceRowMenu.tsx @@ -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({ {t('auto.components.cloudWorkspaces.copyWorkspaceLink', 'Copy workspace link')} + {w.ownerUserId !== selfId && ( + openTeammateProfile(w.ownerUserId)}> + + + {t('auto.components.cloudWorkspaces.viewOwnerProfile', "View {{name}}'s profile", { + name: memberName(directory, w.ownerUserId, selfId, t) + })} + + + )} {teammatesHere.length > 0 && ( diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx index 065515832eb..be2ff0cacdc 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx @@ -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('[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: () => , + 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: () => , + 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: () => , + interact: async () => { + await waitFor( + () => + document.querySelector('[data-cloud-workspace-row]') !== null && routineSwitch() !== null + ) + routineSwitch()!.click() + await waitFor(() => document.querySelector('[aria-label="Routine run"]') !== null) + } +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index aead29afdf8..d20835f7cad 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -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(null) const [now, setNow] = useState(() => Date.now()) const [sectionFor, setSectionFor] = useState(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) => { - 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} />
({ + OrcaCloudTrialUsedUpBanner: () => null +})) +vi.mock('@/hooks/useOrcaCloudApiAvailability', () => ({ useOrcaCloudApiAvailable: () => false })) + +afterEach(cleanup) + +function toolbar( + routineRuns: CloudWorkspaceRoutineRuns | undefined, + filters: Partial = {}, + onFiltersChange = vi.fn() +) { + render( + + + + ) + return onFiltersChange +} + +const runs = (over: Partial = {}): 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() + 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) + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx index 09a9540431a..2161a861903 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx @@ -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) => 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({ ))} - - + {/* The switches wrap as one group, so none is left alone on a line of its own. */} +
+ + {(routineRuns?.routines ?? 0) > 0 || filters.routines === true ? ( + + ) : null} + +
{/* T4: the team's trial ran out; running sandboxes sleep until a plan starts. */} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspaces-home-prefs.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspaces-home-prefs.ts new file mode 100644 index 00000000000..d8e9f6ebbf0 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspaces-home-prefs.ts @@ -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> { + try { + const parsed: unknown = JSON.parse(storage?.getItem(KEY) ?? '{}') + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return {} + } + const out: Record> = {} + for (const [account, saved] of Object.entries(parsed)) { + if (saved && typeof saved === 'object') { + const flags: Record = { ...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, + 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. + } +} diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-home-filters.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-home-filters.ts new file mode 100644 index 00000000000..4c8113a767e --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-home-filters.ts @@ -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) => { + 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 } +} diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts index 09d9f27a37b..3570d7da413 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspaces.ts @@ -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) diff --git a/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts b/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts index fb7517c94cd..805f5612157 100644 --- a/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts +++ b/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts @@ -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: [ diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx index 1bc6b24bab0..c041625c6e2 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx @@ -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({
) : 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. */} -
+ {/* 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. */} +
{showCreateMultiple ? ( ) : null} -
- {cloudStart?.onUseThisComputer ? ( - - ) : null} - -
- {heldReason ? ( - - {heldReason} - ) : null} +
) diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx index 549cdbf3909..d7f1e67462b 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx @@ -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> & { - 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 - 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 + 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 (
- {/* Run on as segments needs the full width, so it sits under the project (spec E1). */} -
+ {/* 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). */} +
) : null}
- {cloudStart?.tracker && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? ( - // A6: the browser trip is open; the same rows tick in place, with X1 errors. - - ) : cloudStart?.panelVisible && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? ( - // The panel's own Agent row (G) comes from the same model as the standalone one below. - 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 ? ( - - ) : null} {!shouldShowRunTargetPicker && ephemeralVmRecipeError ? (

{ephemeralVmRecipeError}

) : null} diff --git a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx deleted file mode 100644 index e8e371d777f..00000000000 --- a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx +++ /dev/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 ( - <> -

- {hoursLeft} - {canChoose ? ( - <> - · - - - ) : null} -

-

- {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.' - )} -

- - ) -} - -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' ? ( - - ) : null - return ( - // @container: the specs drop out whole when the column is narrow, instead of ellipsizing. -
- {visible && !block && !low ? ( - // Outside the live region: hour ticks on refresh are not re-announced. - <> -

- - - - {hoursLeft ? ( - // pl-1: a flex item trims its leading space, so the gap before "·" comes from padding. - - {'· '} - {hoursLeft} - - ) : null} -

-

- {/* 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' - } - )} -

- - ) : null} - {/* Always mounted, so a block that arrives after the pick (late billing, restored draft) is announced. */} -
- {visible && !block && low ? : null} - {visible && block ? ( - <> -

- {block.tone === 'error' ? ( - - ) : null} - {block.title} - {action ? · : null} - {action} -

- {block.detail ?

{block.detail}

: null} - - ) : null} -
-
- ) -} diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index b07abf4670e..a80779b6e57 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -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} /> void connectHost(option)} onSetLocation={setLocation} /> diff --git a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx index c3f574b3f7e..b23cd91a6c9 100644 --- a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx @@ -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={} + trailing={ + setupAfterStart && !showsMetaAfterStart(access) ? undefined : ( + + ) + } /> ) } diff --git a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx index 89fe146ff91..b8c283ab812 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx @@ -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} /> ) } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx b/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx deleted file mode 100644 index b62a4e322e6..00000000000 --- a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx +++ /dev/null @@ -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 ( -
- -
- ) -} - -export const trackerWaitingGithub = defineFixture({ width: 560, render: () => }) -export const trackerSigningIn = defineFixture({ - width: 560, - render: () => -}) -export const trackerDerivedRows = defineFixture({ - width: 560, - render: () => -}) - -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: () => -}) -export const trackerCheckoutCanceled = defineFixture({ - width: 560, - render: () => -}) -export const trackerBankStep = defineFixture({ - width: 560, - render: () => -}) -export const trackerTrialUnavailable = defineFixture({ - width: 560, - render: () => -}) -export const trackerTrialUnavailableMember = defineFixture({ - width: 560, - render: () => ( - - ) -}) -export const trackerTeamCreateFailed = defineFixture({ - width: 560, - render: () => ( - - ) -}) -export const trackerWrongAccount = defineFixture({ - width: 560, - render: () => ( - - ) -}) - -// X1: every setup error notice, as in the spec's sheet. -export const x1SetupErrors = defineFixture({ - width: 560, - render: () => ( -
- {( - [ - { 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) => ( - - ))} - -
- ) -}) - -// B1: an owner whose team never had a trial: the trial is the first plan, no trip. -export const b1OwnerTrialAvailable = defineFixture({ - width: 560, - render: () => ( -
- -
- ) -}) - -function SwitchTeamPanel({ teams }: { teams: PlannedTeam[] }): React.JSX.Element { - const b2 = useCloudSetupSwitchTeamFor(teams, noop) - return ( -
- -
- ) -} - -// B2: personal account, but a team the user is on has a plan: switch instead of buying. -export const b2SwitchTeam = defineFixture({ - width: 560, - render: () => -}) -export const b2SwitchTeamMenu = defineFixture({ - width: 560, - render: () => ( - - ) -}) diff --git a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx b/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx deleted file mode 100644 index 8b053dca6c1..00000000000 --- a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx +++ /dev/null @@ -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> - /** 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 ( - - {error ? ( - - ) : null} -
- - - {onCopyLink ? ( - - ) : null} - {reopenInError ? null : ( - - )} - -
-
- ) -} diff --git a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts index b8ef4759f3e..07bbbdeb2a9 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts @@ -20,8 +20,8 @@ async function freshLink(sessionId: string): Promise { 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.' ) ) } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts index a169c440a3e..913f163430c 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts @@ -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.' } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts b/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts index a4b64b924a5..7db939a3c06 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts @@ -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 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 "). */ - rowActions?: Partial> - /** 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 } : {}) - } -} diff --git a/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx b/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx new file mode 100644 index 00000000000..c327e43e5c7 --- /dev/null +++ b/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx @@ -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, '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 ( + +
+ {children} +
+
+ ) +} diff --git a/src/renderer/src/components/new-workspace/composer-modal-data.ts b/src/renderer/src/components/new-workspace/composer-modal-data.ts index 482ac94c762..0a2a0f21224 100644 --- a/src/renderer/src/components/new-workspace/composer-modal-data.ts +++ b/src/renderer/src/components/new-workspace/composer-modal-data.ts @@ -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 } diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx deleted file mode 100644 index 177660c20a0..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx +++ /dev/null @@ -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: () => -}) -/** E1 with "⋯" open: today's host picker without the Orca Cloud row. */ -export const e1MorePlaces = defineFixture({ - ...e1RunOnDefault, - interact: (frame) => { - frame.querySelector('[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: () => ( - - ) -}) -/** B1: signed in, the team can still get its trial. */ -export const b1TrialAvailable = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** A6: Finish in your browser; each step ticks in place. */ -export const a6FinishInBrowser = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** A7: everything done; "All set", then the composer starts by itself. */ -export const a7AllSet = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** T1: trial hours in the composer hint. */ -export const t1TrialHint = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T1 under half an hour: warning, with Choose plan for owners. */ -export const t1TrialLow = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T1 low, member: who can choose a plan. */ -export const t1TrialLowMember = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T2: the trial is used up at New workspace; the prompt is kept. */ -export const t2TrialUsedUp = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** C1 with the trial used up: a member can't buy, so ⌘↵ runs on this computer. */ -export const t2TrialUsedUpMember = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D1: GitHub checked up front; "Give access and start". */ -export const d1GitHubNeeded = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D2: waiting for an owner of the GitHub org; ⌘↵ runs on this computer. */ -export const d2GitHubRequested = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D3: the project isn't on GitHub; outranks account and plan rows. */ -export const d3NotOnGitHub = defineFixture({ - width: 560, - setup, - render: () => ( - {} } - }} - /> - ) -}) -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: () => ( - - ), - interact: async (frame) => { - frame.querySelector('[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: () => ( - - ) -}) -/** D3 for a folder: Orca Cloud stays selectable; the panel offers a GitHub repository instead. */ -export const d3FolderProject = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** 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: () => ( - - ) -}) -/** X2: Orca Cloud can't be reached; the segment stays, disabled, with the reason. */ -export const x2Unreachable = defineFixture({ - width: 560, - setup, - render: () => ( - - ), - 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)) - } -}) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx deleted file mode 100644 index 35823b4b3f3..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx +++ /dev/null @@ -1,33 +0,0 @@ -// Cloud-start G inside the "Set up Orca Cloud" panel: the Agent row from the Orca account's setup. -import { defineFixture } from '../../../component-fixtures/component-fixture' -import { translate } from '@/i18n/i18n' -import type { OrcaCloudAgentSetupRowModel } from '@/lib/orca-cloud/orca-cloud-agent-setup-row' -import { OrcaCloudSetupPanel } from './OrcaCloudSetupPanel' -import { cloudStartAgentStep } from './cloud-start-agent-step' -import type { CloudSetupStep } from './cloud-start-model' - -const BASE: CloudSetupStep[] = [ - { id: 'account', state: 'done', detail: 'neil@acme.dev' }, - { id: 'github', state: 'needed', need: 'github', canFix: true } -] - -function panel(row: OrcaCloudAgentSetupRowModel) { - return defineFixture({ - width: 560, - render: () => { - const agent = cloudStartAgentStep({ id: 'agent', state: 'optional' }, row, translate) - return ( -
- -
- ) - } - }) -} - -export const gFromAccount = panel({ kind: 'covered', agent: 'claude', via: 'account' }) -export const gTeamKey = panel({ kind: 'covered', agent: 'codex', via: 'team' }) -export const gNotSetUp = panel({ kind: 'notSetUp', agent: 'claude' }) -export const gKillSwitch = panel({ kind: 'killSwitch', agent: 'claude' }) -export const gSignedOut = panel({ kind: 'signedOut', agent: 'claude' }) -export const gLoading = panel({ kind: 'loading', agent: 'claude' }) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx deleted file mode 100644 index b56940016c5..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// Orca Cloud picked on the segmented Run on, blocked by billing: the hint under Run on names the fix -// for an owner or admin, and says who can for a member (DS-15). These replace the pre-#273 dropdown -// fixtures NewWorkspaceComposerProjectSection:orcaCloudSelected* (DS-33). -import { defineFixture } from '../../../component-fixtures/component-fixture' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { ComposerPreview } from './cloud-start-preview-fixture' - -const setup = (): void => { - window.api.agentApiKeys = undefined - window.api.cloudSecrets = undefined - // No agent-accounts bridge: the Agent row reads "unavailable" instead of awaiting the harness's - // catch-all mock, which resolves to undefined (the page error DS-33 found). - window.api.orcaCloudAgents = undefined - window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true } -} - -function blocked(access: OrcaCloudRunTargetAccess) { - return defineFixture({ - width: 560, - setup, - render: () => - }) -} - -export const noPlanOwner = blocked({ state: 'no-plan', lapsed: false, canManageBilling: true }) -export const noPlanMember = blocked({ state: 'no-plan', lapsed: false, canManageBilling: false }) -export const outOfHoursMember = blocked({ - state: 'out-of-hours', - cause: 'hours', - canManageBilling: false -}) -export const spendCapMember = blocked({ - state: 'out-of-hours', - cause: 'cap', - canManageBilling: false -}) -export const paymentIssueAdmin = blocked({ state: 'payment-issue', canManageBilling: true }) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx deleted file mode 100644 index c0f0b899ede..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// "Start in Orca Cloud" at the real modal's width (sm:max-w-lg, ~448px of content) with its -// "Create more" switch, where np4-e2e saw the primary button overflow the dialog's right edge. -// Also the setup session's plan row (no raw "subscription") and the plan + GitHub subtitle. -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 - window.api.orcaCloudAgents = undefined - window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true } -} -const CARD_WIDTH = 480 -const noPlan: OrcaCloudRunTargetAccess = { - state: 'no-plan', - lapsed: false, - canManageBilling: true -} -const githubNeeded: CloudSetupStep = { - id: 'github', - state: 'needed', - need: 'github', - canFix: true, - label: 'GitHub access', - status: 'Needed', - detail: 'Orca Cloud can’t reach nwparker/orca-sandbox-push-test yet.', - note: 'It clones your code from GitHub. Give access to this repository once.' -} - -/** Signed out at the modal's width: "Create more", "Use this computer instead", "Set up and start". */ -export const modalSignedOut = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** Only GitHub is missing: the longer "Give access and start" at the modal's width. */ -export const modalGiveAccess = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** No plan and no GitHub access: the subtitle names both parts of the one browser visit. */ -export const modalPlanAndGitHub = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** A setup session after Checkout: Team plan done with no raw "subscription" under it. */ -export const sessionPlanDone = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** A setup session mid-Checkout, with an owner's GitHub approval pending: codes read as words. */ -export const sessionCheckoutAndRequested = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) diff --git a/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx b/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx deleted file mode 100644 index d87118dd03c..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx +++ /dev/null @@ -1,30 +0,0 @@ -// The setup panel's way forward for a plain folder on Orca Cloud (design-squad: D3 for folders): -// choose a GitHub repository from the Project picker (D4), or add a GitHub project. -import React from 'react' -import { Button } from '@/components/ui/button' -import { useTranslate } from '@/i18n/use-translate' - -export function FolderGitHubActions({ - canChoose, - onChooseRepository, - onAddProject -}: { - /** Signed in with GitHub access: the Project picker lists repositories to choose from. */ - canChoose: boolean - onChooseRepository: () => void - onAddProject: () => void -}): React.JSX.Element { - const t = useTranslate() - return ( - - {canChoose ? ( - - ) : null} - - - ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx b/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx deleted file mode 100644 index c57a8a6e4eb..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx +++ /dev/null @@ -1,351 +0,0 @@ -// "Set up Orca Cloud": what still stands between this prompt and a running sandbox (spec A1/B1/C1). -// Shown when Orca Cloud is picked and anything required is missing; hidden once everything is done. -// The rows come from billing today and from the one-trip setup session once it exists. -import React from 'react' -import { Check, CircleDashed, CircleDot, Loader2 } from 'lucide-react' -import { Button } from '@/components/ui/button' -import { Skeleton } from '@/components/ui/skeleton' -import { cn } from '@/lib/utils' -import { useTranslate, type Translate } from '@/i18n/use-translate' -import { - cloudSetupNeedsGitHub, - cloudSetupNeedsPlan, - type CloudSetupStep, - type CloudSetupStepId -} from './cloud-start-model' - -type RowCopy = { title: string; detail: string | null; note?: string; status?: string } - -function rowCopy(step: CloudSetupStep, t: Translate): RowCopy { - switch (step.id) { - case 'account': - return { - title: t('components.newWorkspace.cloudSetup.account', 'Orca account'), - detail: - step.state === 'done' - ? null - : t( - 'components.newWorkspace.cloudSetup.accountNeededTeam', - 'Sign in or create one. We’ll make a team for you.' - ) - } - case 'team': - return { title: t('components.newWorkspace.cloudSetup.team', 'Team'), detail: null } - case 'plan': - return step.need === 'trial' ? trialCopy(step, t) : planCopy(step, t) - case 'github': - return { - title: t('components.newWorkspace.cloudSetup.github', 'GitHub access'), - detail: - step.state === 'done' - ? null - : t( - 'components.newWorkspace.cloudSetup.githubNeeded', - 'Orca Cloud clones your code from GitHub. Give access to this repository once.' - ) - } - case 'agent': - // The composer names the agent in `detail`; it never asks for a per-sandbox sign-in (G). - return { - title: t('components.newWorkspace.cloudSetup.agent', 'Agent'), - detail: null, - status: t('components.newWorkspace.cloudSetup.stateOptional', 'Optional') - } - } -} - -/** A1/B1: the one-time trial, counted from billing's offer, never a literal. */ -function trialCopy(step: CloudSetupStep, t: Translate): RowCopy { - const hours = step.trialSeconds ? Math.round((step.trialSeconds / 3600) * 10) / 10 : null - return { - title: t('components.newWorkspace.cloudSetup.trial', 'Trial'), - detail: - hours === null - ? null - : t( - 'components.newWorkspace.cloudSetup.trialOffer', - '{{hours}} sandbox hours to try Orca Cloud', - { - count: hours, - hours: String(hours), - defaultValue_one: '{{hours}} sandbox hour to try Orca Cloud' - } - ), - note: t( - 'components.newWorkspace.cloudSetup.trialNoCard', - 'No card needed. Nothing is charged until you choose a plan.' - ), - status: t('components.newWorkspace.cloudSetup.stateIncluded', 'Included') - } -} - -function planCopy(step: CloudSetupStep, t: Translate): RowCopy { - if (step.need === 'trial-used-up' && step.state === 'needed') { - // T2 / C1: neutral, nothing failed. Members read who can fix it. - return { - title: t('components.newWorkspace.cloudSetup.plan', 'Team plan'), - detail: t('components.newWorkspace.cloudSetup.trialUsedUp', 'Your trial is used up.'), - note: - step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.trialUsedUpMember', - 'Only owners and admins can choose a plan.' - ) - : t( - 'components.newWorkspace.cloudSetup.trialUsedUpOwner', - 'Choose a plan to keep using Orca Cloud. Your prompt is still here.' - ) - } - } - return { - title: t('components.newWorkspace.cloudSetup.plan', 'Team plan'), - detail: planDetail(step, t) - } -} - -function planDetail(step: CloudSetupStep, t: Translate): string | null { - if (step.state === 'pending') { - return t('components.newWorkspace.cloudSetup.planAfterSignIn', 'Checked after you sign in') - } - if (step.state !== 'needed') { - return null - } - const memberSuffix = - step.canFix === false - ? ` ${t('components.newWorkspace.cloudSetup.askOwner', 'Ask an owner or admin to fix it.')}` - : '' - switch (step.need) { - case 'renew-plan': - return ( - t('components.newWorkspace.cloudSetup.planEnded', 'Your Team plan ended.') + memberSuffix - ) - // Members read who fixes it and how, per cause (glossary), not a generic "fix it". - case 'hours': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.outOfHoursMember', - 'Out of sandbox hours. Ask an owner or admin to add hours.' - ) - : t('components.newWorkspace.cloudSetup.outOfHours', 'Out of sandbox hours.') - case 'spend-cap': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.spendCapMember', - 'Spend cap reached. Ask an owner or admin to raise the spend cap.' - ) - : t('components.newWorkspace.cloudSetup.spendCap', 'Spend cap reached.') - case 'payment': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.paymentFailedMember', - 'Payment failed. Ask an owner or admin to update the payment method.' - ) - : t('components.newWorkspace.cloudSetup.paymentFailed', 'Payment failed.') - case 'github': - return t( - 'components.newWorkspace.cloudSetup.githubNeeded', - 'Orca Cloud clones your code from GitHub. Give access to this repository once.' - ) - case 'sign-in': - case 'plan': - case 'trial': - case 'trial-used-up': - case undefined: - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.planMember', - 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' - ) - : t('components.newWorkspace.cloudSetup.planNeeded', 'Orca Cloud needs a Team plan.') - } -} - -/** - * A setup session's rows name how a step is covered with a code ('subscription', 'trial', - * 'checkout', 'requested'); say it in words, or nothing. Undefined: not a session code. - */ -export function sessionDetailCopy(step: CloudSetupStep, t: Translate): string | null | undefined { - if (step.id === 'plan' && step.detail === 'subscription') { - // "Team plan · Done" already says it. - return null - } - if (step.id === 'plan' && step.detail === 'trial') { - return t('components.newWorkspace.cloudSetup.planCoveredByTrial', 'Your trial covers it.') - } - if (step.id === 'plan' && step.detail === 'checkout') { - return t( - 'components.newWorkspace.cloudSetup.planCheckoutOpen', - 'Finish checkout in your browser.' - ) - } - if (step.id === 'github' && step.detail === 'requested') { - return t( - 'components.newWorkspace.cloudSetup.githubRequestedSession', - 'Waiting for an owner on GitHub to approve Orca Cloud.' - ) - } - return undefined -} - -function stateLabel(step: CloudSetupStep, t: Translate): string { - switch (step.state) { - case 'done': - return t('components.newWorkspace.cloudSetup.stateDone', 'Done') - case 'optional': - return t('components.newWorkspace.cloudSetup.stateOptional', 'Optional') - case 'pending': - return t('components.newWorkspace.cloudSetup.stateNext', 'Next') - case 'active': - return t('components.newWorkspace.cloudSetup.stateInBrowser', 'In browser') - case 'failed': - return t('components.newWorkspace.cloudSetup.stateFailed', "Didn't finish") - case 'loading': - return t('components.newWorkspace.cloudSetup.stateChecking', 'Checking') - case 'needed': - return t('components.newWorkspace.cloudSetup.stateNeeded', 'Needed') - } -} - -function StateIcon({ step }: { step: CloudSetupStep }): React.JSX.Element { - // Neutral checks: done and an included trial are facts, not alerts. - if (step.state === 'done' || step.need === 'trial') { - return - } - if (step.state === 'active') { - // The browser is working on this step; static under reduced motion, the label carries the state. - return ( - - ) - } - if (step.state === 'needed' || step.state === 'failed') { - return - } - return -} - -export function OrcaCloudSetupPanel({ - steps, - allSet = false, - title, - subtitle, - children, - rowActions, - className -}: { - steps: readonly CloudSetupStep[] - /** Setup just finished: "All set", then the composer starts the workspace by itself. */ - allSet?: boolean - /** Overrides for variants such as the "Finish in your browser" tracker. */ - title?: string - subtitle?: string - /** Rendered under the rows (tracker errors and actions). */ - children?: React.ReactNode - /** Per-row slot under a row's detail, e.g. the member "Ask for a Team plan" action on 'plan'. */ - rowActions?: Partial> - className?: string -}): React.JSX.Element { - const t = useTranslate() - const titleId = React.useId() - return ( -
-

- {allSet - ? t('components.newWorkspace.cloudSetup.allSet', 'All set') - : (title ?? t('components.newWorkspace.cloudSetup.title', 'Set up Orca Cloud'))} -

-

- {allSet - ? t('components.newWorkspace.cloudSetup.starting', 'Starting your cloud workspace…') - : (subtitle ?? - // No browser trip fixes a project without a GitHub repository (D3): say what holds. - (steps.some((step) => step.blocksStart && step.state === 'failed') - ? t( - 'components.newWorkspace.cloudSetup.subtitleNeedsRepository', - 'Orca Cloud needs a GitHub repository. Your prompt stays here.' - ) - : // A member can't fix billing, and no browser trip will. - steps.some((step) => step.state === 'needed' && step.canFix === false) - ? t( - 'components.newWorkspace.cloudSetup.subtitleOwnerFixes', - 'An owner or admin needs to fix this. Your prompt stays here.' - ) - : cloudSetupNeedsPlan(steps) && cloudSetupNeedsGitHub(steps) - ? t( - 'components.newWorkspace.cloudSetup.subtitleChoosePlanAndGitHub', - 'One visit to your browser to choose a plan and give Orca Cloud access on GitHub. Your prompt stays here and starts when you’re done.' - ) - : cloudSetupNeedsPlan(steps) - ? t( - 'components.newWorkspace.cloudSetup.subtitleChoosePlan', - 'One visit to your browser to choose a plan. Your prompt stays here and starts when you’re done.' - ) - : t( - 'components.newWorkspace.cloudSetup.subtitleNoCard', - 'One visit to your browser, no card. Your prompt stays here and starts when you’re done.' - )))} -

- {/* One polite announcement per row change ("Team plan, done"). */} -
    - {steps.map((step) => { - const copy = rowCopy(step, t) - const title = step.label ?? copy.title - const state = step.status ?? copy.status ?? stateLabel(step, t) - const note = step.note ?? copy.note - const sessionDetail = sessionDetailCopy(step, t) - const detail = sessionDetail === undefined ? (step.detail ?? copy.detail) : sessionDetail - return ( -
  • - - - - - {title} - {step.state === 'loading' ? ( - - ) : detail ? ( - {detail} - ) : null} - {note ? ( - {note} - ) : null} - {step.action ? ( - // One shared in-row action ("Set up once", "How to push"): it must read as a button. - - ) : null} - {rowActions?.[step.id] ?? null} - - - {`${title}, `} - {state} - -
  • - ) - })} -
- {children} -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx b/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx deleted file mode 100644 index 9c3b64cc2ab..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// The hint under Run on for this computer or a "⋯" target: where it runs (spec E1). When Orca -// Cloud can't be reached, the line says so (X2) so the disabled segment never looks like a bug. -import React from 'react' -import { useTranslate } from '@/i18n/use-translate' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import { getRecipeDetail, type EphemeralVmRecipeOption } from '../run-target-options' - -export function RunOnHintLine({ - hostOptions, - selectedHostId, - recipes, - selectedRecipeId, - orcaCloudAvailability -}: { - hostOptions: readonly ProjectHostSetupOption[] - selectedHostId: string | null - recipes: readonly EphemeralVmRecipeOption[] - selectedRecipeId: string | null - orcaCloudAvailability: OrcaCloudAvailability -}): React.JSX.Element | null { - const t = useTranslate() - const recipe = recipes.find((candidate) => candidate.id === selectedRecipeId) ?? null - const host = hostOptions.find((option) => option.id === selectedHostId) ?? null - const where = recipe ? getRecipeDetail(recipe, t) : host ? `${host.label} · ${host.detail}` : null - return ( -
- {where ?

{where}

: null} - {orcaCloudAvailability === 'unreachable' ? ( -

- {t( - 'components.newWorkspace.runOn.cloudUnreachableReason', - "Orca Cloud: can't reach it right now. Check your connection." - )} -

- ) : null} -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx b/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx deleted file mode 100644 index d4bf68717da..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx +++ /dev/null @@ -1,212 +0,0 @@ -// Run on as one click: "This computer · Orca Cloud · ⋯" (spec D1). ⋯ opens today's host picker -// without its Orca Cloud row, and a target picked there replaces ⋯ so the choice stays visible. -import React, { useMemo, useState } from 'react' -import { Cloud, Ellipsis, Monitor } from 'lucide-react' -import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' -import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsSegmentedControl' -import { useTranslate } from '@/i18n/use-translate' -import type { ReadyProjectHostSetupOption } from '@/lib/project-host-setup-options' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' -import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import RunTargetCombobox from '../RunTargetCombobox' -import { isOrcaCloudRecipe } from '../run-target-options' -import { getOrcaCloudSegmentState, getRunOnSegment, type RunOnSegment } from './cloud-start-model' - -type RunTargetComboboxProps = React.ComponentProps - -export type RunOnSegmentedControlProps = RunTargetComboboxProps & { - orcaCloudAvailability: OrcaCloudAvailability - /** Selects Orca Cloud even when the account still needs setup; the panel below says what's missing. */ - onSelectOrcaCloud: () => void - /** Marks the control as touched so a remembered default never overrides a user pick. */ - onUserPick?: () => void - /** D4: the picked project is on GitHub only, so this computer has nothing to run. */ - cloudOnlyRepo?: boolean -} - -export default function RunOnSegmentedControl( - props: RunOnSegmentedControlProps -): React.JSX.Element { - const { - hostOptions, - hostValue, - hostExecutionHostId, - onHostChange, - recipes, - recipeValue, - onRecipeChange, - orcaCloudAvailability, - onSelectOrcaCloud, - onUserPick, - cloudOnlyRepo = false - } = props - const t = useTranslate() - const [moreOpen, setMoreOpen] = useState(false) - - const localOption = useMemo( - () => - hostOptions.find( - (option): option is ReadyProjectHostSetupOption => - option.kind === 'ready' && option.hostId === LOCAL_EXECUTION_HOST_ID - ) ?? null, - [hostOptions] - ) - const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null - const orcaCloudSelected = recipeValue === ORCA_CLOUD_RECIPE_ID - const selectedHost = - hostOptions.find( - (option) => - option.kind === 'ready' && - option.id === hostValue && - (!hostExecutionHostId || option.hostId === hostExecutionHostId) - ) ?? null - const segment = getRunOnSegment({ - orcaCloudSelected, - otherRecipeSelected: selectedRecipe !== null && !orcaCloudSelected, - selectedHostIsLocal: selectedHost ? selectedHost.hostId === LOCAL_EXECUTION_HOST_ID : null - }) - const cloudState = getOrcaCloudSegmentState(orcaCloudAvailability) - const localReason = cloudOnlyRepo - ? t( - 'components.newWorkspace.cloudOnly.notOnThisComputer', - 'Not on this computer · Orca Cloud only' - ) - : t('components.newWorkspace.runOn.locationNotSet', 'Project location not set') - - const pickLocal = (): void => { - if (!localOption || cloudOnlyRepo) { - return - } - onUserPick?.() - onRecipeChange?.(null) - onHostChange?.(localOption.id) - } - const pickCloud = (): void => { - if (cloudState !== 'enabled') { - return - } - onUserPick?.() - onSelectOrcaCloud() - } - - const otherLabel = - segment === 'other' - ? ((selectedRecipe && !isOrcaCloudRecipe(selectedRecipe) - ? selectedRecipe.name - : selectedHost?.label) ?? null) - : null - - const options = [ - { - value: 'local' as const, - label: ( - - - {t('components.newWorkspace.runOn.thisComputer', 'This computer')} - - ), - disabled: !localOption || cloudOnlyRepo, - // A disabled option says why in its accessible name too (spec E1). - ariaLabel: - localOption && !cloudOnlyRepo - ? undefined - : t('components.newWorkspace.runOn.thisComputerUnusable', 'This computer, {{reason}}', { - reason: localReason - }), - tooltip: localOption && !cloudOnlyRepo ? localOption.label : localReason - }, - ...(cloudState === 'hidden' - ? [] - : [ - { - value: 'orca-cloud' as const, - label: ( - - - {t('components.newWorkspace.runOn.orcaCloud', 'Orca Cloud')} - - ), - disabled: cloudState === 'unreachable', - ariaLabel: - cloudState === 'unreachable' - ? t( - 'components.newWorkspace.runOn.cloudUnreachableName', - "Orca Cloud, can't reach it right now" - ) - : undefined, - tooltip: - cloudState === 'unreachable' - ? t( - 'components.newWorkspace.runOn.cloudUnreachableReason', - "Orca Cloud: can't reach it right now. Check your connection." - ) - : t('components.newWorkspace.runOn.cloudHosted', 'Hosted sandbox') - } - ]), - { - value: 'other' as const, - ariaLabel: otherLabel - ? t('components.newWorkspace.runOn.moreWithTarget', 'More places to run: {{name}}', { - name: otherLabel - }) - : t('components.newWorkspace.runOn.more', 'More places to run'), - label: otherLabel ? ( - {otherLabel} - ) : ( - - ), - tooltip: t('components.newWorkspace.runOn.more', 'More places to run') - } - ] - - // The host picker keeps everything except Orca Cloud, which now has its own segment. - const otherRecipes = useMemo( - () => recipes.filter((recipe) => !isOrcaCloudRecipe(recipe)), - [recipes] - ) - - return ( - - -
- - value={segment ?? 'local'} - activation="manual" - size="sm" - ariaLabel={t('auto.components.NewWorkspaceComposerCard.runOn', 'Run on')} - options={options} - onChange={(value) => { - if (value === 'local') { - pickLocal() - } else if (value === 'orca-cloud') { - pickCloud() - } else { - setMoreOpen(true) - } - }} - /> -
-
- - { - onUserPick?.() - onRecipeChange?.(null) - onHostChange?.(setupId) - setMoreOpen(false) - }} - onRecipeChange={(recipeId) => { - onUserPick?.() - onRecipeChange?.(recipeId) - setMoreOpen(false) - }} - /> - -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts similarity index 94% rename from src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx rename to src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts index c36929e963a..7b424cd31b5 100644 --- a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx +++ b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { translate } from '@/i18n/i18n' -import { sessionDetailCopy } from './OrcaCloudSetupPanel' +import { sessionDetailCopy } from './cloud-setup-session-copy' describe('sessionDetailCopy', () => { // np4-e2e: the plan row read the session's raw "subscription". diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts new file mode 100644 index 00000000000..2ad45b29562 --- /dev/null +++ b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts @@ -0,0 +1,30 @@ +// Setup-session codes in words, for the Orca Cloud setup page. +import type { Translate } from '@/i18n/use-translate' +import type { CloudSetupStep } from './cloud-start-model' + +/** + * A setup session's rows name how a step is covered with a code ('subscription', 'trial', + * 'checkout', 'requested'); say it in words, or nothing. Undefined: not a session code. + */ +export function sessionDetailCopy(step: CloudSetupStep, t: Translate): string | null | undefined { + if (step.id === 'plan' && step.detail === 'subscription') { + // "Team plan · Done" already says it. + return null + } + if (step.id === 'plan' && step.detail === 'trial') { + return t('components.newWorkspace.cloudSetup.planCoveredByTrial', 'Your trial covers it.') + } + if (step.id === 'plan' && step.detail === 'checkout') { + return t( + 'components.newWorkspace.cloudSetup.planCheckoutOpen', + 'Finish checkout in your browser.' + ) + } + if (step.id === 'github' && step.detail === 'requested') { + return t( + 'components.newWorkspace.cloudSetup.githubRequestedSession', + 'Waiting for an owner on GitHub to approve Orca Cloud.' + ) + } + return undefined +} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts index c2781995838..054aaaa6ced 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts @@ -1,39 +1,8 @@ -// What the "Start in Orca Cloud" primary button says, and the fix one click runs before a session -// exists (sign in first, else the plan/billing action). -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' +// The fix one click runs before a setup session exists (sign in first, else the plan/billing +// action); the setup page's fallback when the session can't open. import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import { getOrcaCloudPick, type OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import type { CloudPrimaryAction, CloudSetupStep } from './cloud-start-model' - -export function getCloudPrimaryLabel(action: CloudPrimaryAction): string { - switch (action) { - case 'start': - case 'startTrial': - return translate('components.newWorkspace.cloudStart.start', 'Start in Orca Cloud') - case 'setUpAndStart': - return translate('components.newWorkspace.cloudStart.setUpAndStart', 'Set up and start') - case 'choosePlanAndStart': - return translate( - 'components.newWorkspace.cloudStart.choosePlanAndStart', - 'Choose plan and start' - ) - case 'renewAndStart': - return translate('components.newWorkspace.cloudStart.renewAndStart', 'Renew and start') - case 'giveAccessAndStart': - return translate( - 'components.newWorkspace.cloudStart.giveAccessAndStart', - 'Give access and start' - ) - case 'useThisComputer': - return translate( - 'components.newWorkspace.cloudStart.useThisComputer', - 'Use this computer instead' - ) - case 'checking': - return translate('components.newWorkspace.cloudStart.checking', 'Checking Orca Cloud…') - } -} +import type { CloudSetupStep } from './cloud-start-model' /** The fix one click on the primary button runs: sign in first, else the plan/billing action. */ export function setupActionFor( @@ -52,17 +21,3 @@ export function setupActionFor( const pick = getOrcaCloudPick(effective) return pick.kind === 'act' ? pick.run : null } - -/** D2: an owner approved on GitHub while this composer waits; offer the start (never auto). */ -export function showGitHubGrantedToast(repoName: string, onStart: () => void): void { - toast.message( - translate( - 'components.newWorkspace.cloudStart.githubGranted', - 'GitHub access granted for {{repo}}', - { - repo: repoName - } - ), - { action: { label: getCloudPrimaryLabel('start'), onClick: onStart } } - ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts index d5d4fe9bada..7cb5e31ca4b 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts @@ -1,54 +1,18 @@ import { describe, expect, it } from 'vitest' import { - cloudSetupNeedsGitHub, deriveCloudSetupSteps, - getCloudPrimaryAction, getOrcaCloudSegmentState, - getRunOnSegment, - isCloudSetupPanelVisible, resolveDefaultRunOn, + type CloudSetupStep, withReachableGitHub } from './cloud-start-model' +import { + cloudSetupPageModel, + cloudSetupRequired, + sessionNeedsFrom +} from '../../orca-cloud-setup/cloud-setup-page-model' -describe('Run on segment', () => { - it('maps the committed target to a segment', () => { - expect( - getRunOnSegment({ - orcaCloudSelected: true, - otherRecipeSelected: false, - selectedHostIsLocal: true - }) - ).toBe('orca-cloud') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: true, - selectedHostIsLocal: true - }) - ).toBe('other') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: false - }) - ).toBe('other') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: true - }) - ).toBe('local') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: null - }) - ).toBeNull() - }) - +describe('Orca Cloud availability', () => { it('keeps Orca Cloud visible but disabled when it cannot be reached (X2)', () => { expect(getOrcaCloudSegmentState('unreachable')).toBe('unreachable') expect(getOrcaCloudSegmentState('unavailable')).toBe('hidden') @@ -58,17 +22,29 @@ describe('Run on segment', () => { }) }) -describe('setup rows and the primary label', () => { +describe('setup rows and the setup page', () => { + const page = (steps: Parameters[0]) => + cloudSetupPageModel(steps, { agentSkipped: true }).action + it('starts directly when the account is entitled', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 } }) - expect(isCloudSetupPanelVisible(steps)).toBe(false) - expect(getCloudPrimaryAction(steps)).toBe('start') + expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(false) + expect(page(steps)).toBe('done') }) - it('signed out: one setup trip ("Set up and start"), plan checked after sign-in', () => { + it('an agent with no account opens the page until it is skipped once', () => { + const steps = deriveCloudSetupSteps({ + availability: 'offered', + access: { state: 'entitled', remainingSeconds: 3600 } + }) + expect(cloudSetupRequired(steps)).toBe(true) + expect(cloudSetupPageModel(steps).action).toBe('agent') + }) + + it('signed out: sign-in first, plan checked after sign-in', () => { const steps = deriveCloudSetupSteps({ availability: 'needs-sign-in', access: { state: 'loading' } @@ -78,49 +54,57 @@ describe('setup rows and the primary label', () => { ['plan', 'pending'], ['agent', 'optional'] ]) - expect(isCloudSetupPanelVisible(steps)).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('setUpAndStart') + expect(page(steps)).toBe('sign-in') }) - it('owner without a plan: "Choose plan and start"; lapsed: "Renew and start"', () => { + it('owner without a plan chooses one in the browser; lapsed renews there', () => { const noPlan = deriveCloudSetupSteps({ availability: 'needs-capability', access: { state: 'no-plan', lapsed: false, canManageBilling: true } }) - expect(getCloudPrimaryAction(noPlan)).toBe('choosePlanAndStart') + expect(page(noPlan)).toBe('choose-plan') const lapsed = deriveCloudSetupSteps({ - availability: 'needs-capability', + availability: 'offered', access: { state: 'no-plan', lapsed: true, canManageBilling: true } }) - expect(getCloudPrimaryAction(lapsed)).toBe('renewAndStart') + expect(page(lapsed)).toBe('choose-plan') + expect(lapsed.find((s) => s.id === 'plan')?.need).toBe('renew-plan') }) - it('a member who cannot fix it gets "Use this computer instead" and no agent row', () => { + it('a member who cannot fix billing is told to ask an owner, with no agent row', () => { const steps = deriveCloudSetupSteps({ availability: 'needs-capability', access: { state: 'no-plan', lapsed: false, canManageBilling: false } }) expect(steps.some((s) => s.id === 'agent')).toBe(false) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(page(steps)).toBe('ask-owner') const outOfHours = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'out-of-hours', cause: 'hours', canManageBilling: false } }) - expect(getCloudPrimaryAction(outOfHours)).toBe('useThisComputer') + expect(page(outOfHours)).toBe('ask-owner') }) - it('a missing GitHub grant alone reads "Give access and start"', () => { + it('an owner out of hours fixes it in billing', () => { + const steps = deriveCloudSetupSteps({ + availability: 'offered', + access: { state: 'out-of-hours', cause: 'hours', canManageBilling: true } + }) + expect(page(steps)).toBe('fix-billing') + }) + + it('a missing GitHub grant alone is the GitHub step', () => { expect( - getCloudPrimaryAction([ + page([ { id: 'account', state: 'done' }, { id: 'plan', state: 'done' }, { id: 'github', state: 'needed', need: 'github', canFix: true }, { id: 'agent', state: 'optional' } ]) - ).toBe('giveAccessAndStart') + ).toBe('github-install') }) - it('a team that can still get its trial just starts (B1); setup grants it with no card', () => { + it('a team that can still get its trial claims it in the app (B1)', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialOfferSeconds: 7200 } @@ -129,23 +113,21 @@ describe('setup rows and the primary label', () => { expect(plan).toMatchObject({ need: 'trial', trialSeconds: 7200, canFix: true }) // Members aren't blocked from the trial: the agent row stays. expect(steps.some((s) => s.id === 'agent')).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('startTrial') - // An included trial isn't a task: no panel, the hint line carries it. - expect(isCloudSetupPanelVisible(steps)).toBe(false) + expect(page(steps)).toBe('start-trial') }) - it('trial used up: owner "Choose plan and start"; member runs on this computer (T2, C1)', () => { + it('trial used up: owner chooses a plan; member asks an owner (T2, C1)', () => { const owner = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: true, trialUsedUp: true } }) expect(owner.find((s) => s.id === 'plan')?.need).toBe('trial-used-up') - expect(getCloudPrimaryAction(owner)).toBe('choosePlanAndStart') + expect(page(owner)).toBe('choose-plan') const member = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialUsedUp: true } }) - expect(getCloudPrimaryAction(member)).toBe('useThisComputer') + expect(page(member)).toBe('ask-owner') }) it('signed out: the trial row is included and GitHub is checked up front (A1)', () => { @@ -156,17 +138,18 @@ describe('setup rows and the primary label', () => { }) expect(steps.map((s) => s.id)).toEqual(['account', 'plan', 'github', 'agent']) expect(steps.find((s) => s.id === 'plan')?.need).toBe('trial') - expect(getCloudPrimaryAction(steps)).toBe('setUpAndStart') + expect(sessionNeedsFrom(steps)).toEqual(['account', 'plan', 'github']) + expect(page(steps)).toBe('sign-in') }) - it('GitHub waiting on an owner blocks the start, so ⌘↵ runs locally (D2)', () => { + it('GitHub waiting on an owner: the page waits and starts on its own (D2)', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 }, github: { id: 'github', state: 'pending', need: 'github', blocksStart: true } }) - expect(isCloudSetupPanelVisible(steps)).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(true) + expect(page(steps)).toBe('github-waiting') }) it('no GitHub remote outranks account and plan rows (D3)', () => { @@ -176,21 +159,36 @@ describe('setup rows and the primary label', () => { github: { id: 'github', state: 'failed', need: 'github', blocksStart: true } }) expect(steps.map((s) => s.id)).toEqual(['github']) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(page(steps)).toBe('needs-repository') }) - it('a GitHub check still running holds the start (D1 cache miss)', () => { - const steps = deriveCloudSetupSteps({ + it('checks while GitHub or billing are still being read', () => { + const github = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 }, github: { id: 'github', state: 'loading' } }) - expect(getCloudPrimaryAction(steps)).toBe('checking') + expect(page(github)).toBe('checking') + const billing = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'loading' } }) + expect(page(billing)).toBe('checking') }) - it('waits while billing is still being read', () => { - const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'loading' } }) - expect(getCloudPrimaryAction(steps)).toBe('checking') + it('B2: a team switch is its own step and always opens the page', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'needed' } + ] + expect(cloudSetupRequired(steps, { teamSwitch: true })).toBe(true) + expect(cloudSetupPageModel(steps, { teamSwitch: true }).action).toBe('switch-team') + }) + + it('a still-loading agent row never holds a ready start', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'loading' } + ] + expect(cloudSetupRequired(steps)).toBe(false) }) }) @@ -266,7 +264,7 @@ describe('withReachableGitHub', () => { { id: 'plan', state: 'done', detail: 'subscription' }, { id: 'github', state: 'done' } ]) - expect(getCloudPrimaryAction([...withReachableGitHub([...session], true)])).toBe('start') + expect(cloudSetupPageModel([...withReachableGitHub([...session], true)]).action).toBe('done') }) it('leaves the rows alone while the repository is still unreachable', () => { @@ -274,15 +272,3 @@ describe('withReachableGitHub', () => { expect(withReachableGitHub(steps, false)).toBe(steps) }) }) - -describe('cloudSetupNeedsGitHub', () => { - it('counts GitHub access the browser visit gives, not an approval, a missing remote or a check', () => { - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'needed', need: 'github' }])).toBe(true) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'active' }])).toBe(true) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'done' }])).toBe(false) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'loading' }])).toBe(false) - expect( - cloudSetupNeedsGitHub([{ id: 'github', state: 'pending', need: 'github', blocksStart: true }]) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts index 4ea27621248..22137588ce5 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts @@ -1,30 +1,8 @@ -// "Start in Orca Cloud": what the Run on control shows, which setup rows are missing, and what the -// composer's primary button says and does. Pure, so every state the spec draws is unit-tested here. +// Orca Cloud from the composer: whether its Run on option is offered, which setup rows are missing, +// and the remembered default. Pure, so every state the spec draws is unit-tested here. import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -/** The three segments of Run on: this computer, Orca Cloud, and everything else behind "⋯". */ -export type RunOnSegment = 'local' | 'orca-cloud' | 'other' - -export function getRunOnSegment({ - orcaCloudSelected, - otherRecipeSelected, - selectedHostIsLocal -}: { - orcaCloudSelected: boolean - otherRecipeSelected: boolean - /** Null when no host is committed (the picker's "Choose where to run" state). */ - selectedHostIsLocal: boolean | null -}): RunOnSegment | null { - if (orcaCloudSelected) { - return 'orca-cloud' - } - if (otherRecipeSelected || selectedHostIsLocal === false) { - return 'other' - } - return selectedHostIsLocal === null ? null : 'local' -} - /** * How the Orca Cloud segment behaves. `hidden`: this build doesn't ship Orca Cloud. * `unreachable`: it does, but the account check failed (offline); the segment stays visible and @@ -47,7 +25,7 @@ export function getOrcaCloudSegmentState( } } -/** One row of the "Set up Orca Cloud" panel. Shape shared with the setup session (team-billing-ux). */ +/** One step of the Orca Cloud setup page. Shape shared with the setup session (team-billing-ux). */ export type CloudSetupStepId = 'account' | 'team' | 'plan' | 'github' | 'agent' export type CloudSetupStepState = | 'done' @@ -173,79 +151,6 @@ function derivePlanStep( } } -/** Required rows still open; `optional` (agent) never counts. */ -export function getOpenSetupSteps(steps: readonly CloudSetupStep[]): CloudSetupStep[] { - return steps.filter((step) => step.state !== 'done' && step.state !== 'optional') -} - -/** The panel shows while anything required is open (or still loading). */ -export function isCloudSetupPanelVisible(steps: readonly CloudSetupStep[]): boolean { - // An included trial isn't a task: with nothing else open, the hint line carries it (B1). - return getOpenSetupSteps(steps).some((step) => step.need !== 'trial') -} - -/** The browser trip is for choosing a plan (T2, lapsed, no plan), not a free trial. */ -export function cloudSetupNeedsPlan(steps: readonly CloudSetupStep[]): boolean { - return getOpenSetupSteps(steps).some( - (step) => step.need === 'plan' || step.need === 'renew-plan' || step.need === 'trial-used-up' - ) -} - -/** - * The same browser trip also gives Orca Cloud access to the repository on GitHub. An owner's - * approval (D2) or a project not on GitHub (D3) isn't part of the trip; still checking isn't either. - */ -export function cloudSetupNeedsGitHub(steps: readonly CloudSetupStep[]): boolean { - return getOpenSetupSteps(steps).some( - (step) => step.id === 'github' && !step.blocksStart && step.state !== 'loading' - ) -} - -export type CloudPrimaryAction = - | 'start' - | 'setUpAndStart' - | 'choosePlanAndStart' - | 'renewAndStart' - | 'giveAccessAndStart' - /** Only the trial is missing: setup grants it, so the button just says Start (B1). */ - | 'startTrial' - | 'useThisComputer' - | 'checking' - -/** - * The composer's primary action while Orca Cloud is selected. The label names where the work runs - * (spec D10); a member who can't fix a block gets "Use this computer instead" so ⌘↵ always works. - */ -export function getCloudPrimaryAction(steps: readonly CloudSetupStep[]): CloudPrimaryAction { - const open = getOpenSetupSteps(steps) - if (open.length === 0) { - return 'start' - } - if (open.some((step) => (step.state === 'needed' && step.canFix === false) || step.blocksStart)) { - return 'useThisComputer' - } - if (open.every((step) => step.state === 'loading')) { - return 'checking' - } - const needed = open.filter((step) => step.state !== 'pending' && step.state !== 'loading') - if (needed.length === 1) { - const need = needed[0]?.need - if (need === 'plan' || need === 'trial-used-up') { - return 'choosePlanAndStart' - } - if (need === 'trial') { - return 'startTrial' - } - if (need === 'renew-plan') { - return 'renewAndStart' - } - if (need === 'github') { - return 'giveAccessAndStart' - } - } - return 'setUpAndStart' -} - export type RunOnPreference = 'last' | 'local' | 'orca-cloud' /** diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx b/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx deleted file mode 100644 index 15445595c82..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx +++ /dev/null @@ -1,194 +0,0 @@ -// Shared preview for the cloud-start fixtures: the composer's project section and footer wired to -// the pure setup model, so every spec frame renders without a store or network. -import React, { useState } from 'react' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import { NewWorkspaceComposerProjectSection } from '../NewWorkspaceComposerProjectSection' -import { NewWorkspaceComposerFooter } from '../NewWorkspaceComposerFooter' -import type { EphemeralVmRecipeOption } from '../run-target-options' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { - deriveCloudSetupSteps, - getCloudPrimaryAction, - isCloudSetupPanelVisible, - type CloudSetupStep -} from './cloud-start-model' -import type { CloudStartView } from './use-cloud-start-composer' -import { getCloudPrimaryLabel } from './cloud-start-actions' -import { decorateCloudSetupSteps } from './use-cloud-start-steps' -import type { OrcaCloudGitHubRepository } from '@/lib/orca-cloud/use-orca-cloud-github-repositories' - -const projects: NewWorkspaceProjectOption[] = [ - { - kind: 'project', - id: 'web', - projectId: 'web', - displayName: 'acme/web', - badgeColor: 'var(--muted-foreground)', - detail: 'acme/web' - } -] -/** A plain folder (no git): the D3-for-folders frames. */ -const folderProjects: NewWorkspaceProjectOption[] = [ - { - kind: 'project', - id: 'web', - projectId: 'web', - displayName: 'meeting-notes', - badgeColor: 'var(--muted-foreground)', - detail: '~/Documents/meeting-notes' - } -] -const hosts: ProjectHostSetupOption[] = [ - { - kind: 'ready', - id: 'local', - projectId: 'web', - repoId: 'web', - hostId: 'local', - label: 'MacBook Pro', - detail: '~/code/acme-web', - path: '/Users/neil/code/acme-web' - }, - { - kind: 'ready', - id: 'devbox', - projectId: 'web', - repoId: 'web-devbox', - hostId: 'ssh:devbox', - label: 'devbox', - detail: 'SSH', - path: '/home/neil/acme-web' - } -] -const orcaCloudRecipe: EphemeralVmRecipeOption = { - id: 'cloud', - name: 'Orca Cloud', - description: 'Hosted by Orca. Sleeps when idle and keeps your files.', - provider: 'orca-cloud', - create: 'orca-cloud create' -} - -export function ComposerPreview({ - availability, - access, - cloudSelected, - steps: pinnedSteps, - github = null, - allSet = false, - prompt = 'Fix the flaky login test in e2e/auth.spec.ts and open a PR.', - cloudRepos, - pickedCloudRepo = null, - folderProject = false, - showCreateMultiple = false, - width -}: { - availability: OrcaCloudAvailability - access: OrcaCloudRunTargetAccess - cloudSelected: boolean - steps?: CloudSetupStep[] - /** The GitHub row (D1–D3), as the repository check would report it. */ - github?: CloudSetupStep | null - allSet?: boolean - prompt?: string - /** D4: GitHub repositories with no clone here. */ - cloudRepos?: OrcaCloudGitHubRepository[] - pickedCloudRepo?: string | null - /** The project is a plain folder (D3 for folders). */ - folderProject?: boolean - /** The modal's "Create more" switch, which shares the footer row with the actions. */ - showCreateMultiple?: boolean - /** Pins the card's width, e.g. the modal's content width. */ - width?: number -}): React.JSX.Element { - const [picked, setPicked] = useState(pickedCloudRepo) - const [host, setHost] = useState('local') - const [recipe, setRecipe] = useState(cloudSelected ? 'cloud' : null) - const signedOut = availability === 'needs-sign-in' || access.state === 'signed-out' - // G: Claude not set up yet, so the Agent row offers the one-time setup (or waits for sign-in). - const steps = decorateCloudSetupSteps( - pinnedSteps ?? deriveCloudSetupSteps({ availability, access, github }), - signedOut ? { kind: 'signedOut', agent: 'claude' } : { kind: 'notSetUp', agent: 'claude' } - ) - const selected = recipe === 'cloud' - const panelVisible = selected && (isCloudSetupPanelVisible(steps) || allSet) - const action = getCloudPrimaryAction(steps) - const cloudStart: CloudStartView = { - steps, - panelVisible, - allSet, - onSelectOrcaCloud: () => setRecipe('cloud'), - onUserPick: () => {}, - folderProject, - ...(cloudRepos - ? { - cloudOnly: { - repos: cloudRepos, - showMore: () => {}, - picked: cloudRepos.find((repo) => repo.fullName === picked) ?? null, - githubStep: null, - folderProject, - pick: setPicked, - clear: () => setPicked(null), - moreAccess: () => {}, - start: async () => true - } - } - : {}), - ...(panelVisible && !allSet && action !== 'useThisComputer' - ? { onUseThisComputer: () => setRecipe(null) } - : {}) - } - return ( -
-

Create workspace

-

{prompt}

- {}} - projectDescriptionId="fixture-project-description" - onAddProject={() => {}} - focusNameInput={() => {}} - shouldShowRunTargetPicker - projectHostSetupOptions={hosts} - selectedProjectHostSetupId={host} - handleProjectHostSetupChange={(id) => setHost(id)} - ephemeralVmRecipes={availability === 'offered' ? [orcaCloudRecipe] : []} - selectedEphemeralVmRecipeId={recipe} - onEphemeralVmRecipeChange={setRecipe} - orcaCloudAvailability={availability} - orcaCloudAccess={access} - cloudStart={cloudStart} - handleAddSshHost={() => {}} - handleAddRemoteServer={() => {}} - handleConnectRunTargetHost={async () => {}} - handleSetLocation={() => {}} - onConnectSelectedRepo={async () => {}} - sshStatusLabel="Connected" - connectButtonLabel="Connect" - selectedProjectName={folderProject ? 'meeting-notes' : 'acme/web'} - /> - {}} - createDisabled={allSet || action === 'checking'} - creating={allSet} - primaryActionLabel={ - selected ? getCloudPrimaryLabel(allSet ? 'start' : action) : 'Create worktree' - } - submitShortcutModifierLabel="⌘" - cloudStart={cloudStart} - showCreateMultiple={showCreateMultiple} - /> -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts index d2f656c4f3a..36193ccbb95 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts @@ -1,17 +1,11 @@ -// What the composer card renders for "Start in Orca Cloud", shared by the hook and the card. -import type { CloudSetupStep } from './cloud-start-model' +// What the composer card needs for Orca Cloud, shared by the hook and the card. Picking Orca Cloud +// changes nothing else in the dialog (composer-redo): setup lives on its own page after Start. import type { CloudOnlyRepo } from './use-cloud-only-repo' -import type { CloudSetupViewExtras } from '../cloud-setup/use-cloud-setup-tracker' -/** What the card renders: Run on's Orca Cloud segment, the setup panel and the fallback button. */ -export type CloudStartView = CloudSetupViewExtras & { - steps: CloudSetupStep[] - panelVisible: boolean - allSet: boolean +export type CloudStartView = { + /** Picks Orca Cloud even while the account still needs setup; Start walks it on a page. */ onSelectOrcaCloud: () => void onUserPick: () => void - /** Present while setup blocks a start: creates the same prompt on this computer. */ - onUseThisComputer?: () => void /** D4: GitHub repositories with no clone here, and the one picked. */ cloudOnly?: CloudOnlyRepo /** The project is a plain folder: Orca Cloud needs a GitHub repository instead (D3/D4). */ diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index 8f5ae3564e7..28cc960bfd6 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -1,60 +1,81 @@ -// Composer glue for "Start in Orca Cloud": the setup rows, the primary button's label and action, -// setup instead of a build that billing or GitHub would refuse, the start on its own once setup -// finishes (O4), the draft on disk (N7), and where each project last started (O5). -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +// Composer glue for Orca Cloud (composer-redo). Picking Orca Cloud changes nothing else in the +// dialog: Start either creates the workspace (everything is set up) or saves the draft, closes the +// dialog and opens the full-page setup, which starts the prompt by itself when done. Also: where +// each project last started (O5), the remembered default (D7) and GitHub-only repositories (D4). +import { useCallback, useEffect, useMemo, useRef } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store/index' -import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' import { translate } from '@/i18n/i18n' -import type { - ProjectHostSetupOption, - ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +import { clearCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' import { - clearCloudStartDraft, - readCloudStartDraft, - saveCloudStartDraft -} from '@/lib/orca-cloud/cloud-start-draft' -import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam' + isCloudSetupAgentSkipped, + openCloudSetupPage +} from '@/lib/orca-cloud/cloud-setup-page-store' import { recordSuccessfulRunOn } from '@/lib/orca-cloud/run-on-memory' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import { useOrcaCloudRunTargetAccess } from '../orca-cloud-billing-cache' import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { getCloudPrimaryLabel, setupActionFor, showGitHubGrantedToast } from './cloud-start-actions' -import { - getCloudPrimaryAction, - getOpenSetupSteps, - getOrcaCloudSegmentState, - isCloudSetupPanelVisible -} from './cloud-start-model' +import type { ComposerModalData } from '../composer-modal-data' +import { getOrcaCloudSegmentState } from './cloud-start-model' import { getOrcaCloudStartToast } from './orca-cloud-hours-copy' import { useCloudStartSteps } from './use-cloud-start-steps' -import { useSetupAutoStart } from './use-setup-auto-start' -import { - setupViewExtras, - useComposerSetupTracker, - useSwitchTeamSteps -} from '../cloud-setup/use-cloud-setup-tracker' +import { useSwitchTeamSteps } from '../cloud-setup/use-cloud-setup-tracker' +import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-model' import { useRunOnDefault } from './use-run-on-default' import { useCloudOnlyCreate, useCloudOnlyRepo } from './use-cloud-only-repo' import type { CloudStartView } from './cloud-start-view' +import { openOrcaCloudAgentAccounts } from '../OrcaCloudAgentSetupRow' +import { agentName } from '../../settings/agent-accounts/orca-cloud-accounts-copy' +import { isOrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' export type { CloudStartView } from './cloud-start-view' +/** The workspace started without its agent: one clear way to set the agent up for next time. */ +function showAgentNotStartedToast(agent: string | null): void { + const name = isOrcaCloudAccountAgent(agent) ? agentName(agent, translate) : null + toast.message( + name + ? translate( + 'components.newWorkspace.cloudStart.agentNotStarted', + '{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.', + { agent: name } + ) + : translate( + 'components.newWorkspace.cloudStart.agentNotStartedGeneric', + 'Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.' + ), + { + action: { + label: name + ? translate( + 'components.newWorkspace.cloudStart.setUpAgentOnce', + 'Set up {{agent}} once', + { + agent: name + } + ) + : translate('components.newWorkspace.cloudStart.setUpAgentOnceGeneric', 'Set up once'), + onClick: openOrcaCloudAgentAccounts + } + } + ) +} + export function useCloudStartComposer({ active, availability, selectedRecipeId, setRecipeId, - hostOptions, - onHostChange, repoId, prompt, agent, initialTargetFixed, + autoStart = false, + createReady = true, + composerSnapshot, onCreate: createWorkspace, + onCreateWithoutAgent, onClose, accessOverride }: { @@ -62,26 +83,28 @@ export function useCloudStartComposer({ availability: OrcaCloudAvailability selectedRecipeId: string | null setRecipeId: ((recipeId: string | null) => void) | undefined - hostOptions: readonly ProjectHostSetupOption[] - onHostChange: ((setupId: string) => void) | undefined repoId: string prompt: string agent: string | null /** The composer was opened on an explicit target (Landing card, a recovery). */ initialTargetFixed: boolean + /** Reopened by the setup page once everything is done: submit as soon as the form is ready. */ + autoStart?: boolean + /** The composer's own create would run now (project picked, agent resolved). */ + createReady?: boolean + /** The composer as it is now, for the setup page's Back and its auto-start. */ + composerSnapshot: () => ComposerModalData onCreate: () => void - /** Closes the composer once a cloud-only repository has started (D4). */ + /** The same create with no agent launched (the agent has no Orca Cloud account yet). */ + onCreateWithoutAgent?: () => void + /** Closes the composer (setup moves to its page; a cloud-only repository started, D4). */ onClose?: () => void /** Fixtures pin the account's access. */ accessOverride?: OrcaCloudRunTargetAccess }): { view: CloudStartView | null - primaryActionLabel: string | null /** Replaces the plain create while Orca Cloud is selected. */ onPrimary: (() => void) | null - primaryDisabled: boolean - /** False while the primary runs setup or the local fallback instead of a plain create. */ - primaryIsCreate: boolean /** Call from the composer's onCreated: only a successful start is remembered. */ recordCreated: () => void } { @@ -96,66 +119,46 @@ export function useCloudStartComposer({ cloudOffered: segment === 'enabled', signedIn: availability !== 'needs-sign-in' && access.state !== 'signed-out' }) - const onCreate = useCloudOnlyCreate({ - cloudOnly, - createWorkspace, - prompt, - agent, - profileId, - hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), - onClose - }) - const [startedSessionId, setSetupSessionId] = useState(null) - // A composer reopened after setup (e.g. the Checkout return) resumes its saved draft: derived, - // not copied into state, so it is right on the first render. - const restoredDraft = useMemo( - () => (active && cloudSelected ? readCloudStartDraft(profileId) : null), - [active, cloudSelected, profileId] - ) - const [restoreDone, setRestoreDone] = useState(false) - const restored = restoredDraft !== null && restoredDraft.repoId === repoId && !restoreDone - const setupSessionId = startedSessionId ?? (restored ? restoredDraft.setupSessionId : null) - const [startedHere, setSetupStarted] = useState(false) - const setupStarted = startedHere || restored - const setupStartedRef = useRef(setupStarted) - const onCreateRef = useRef(onCreate) - useEffect(() => { - setupStartedRef.current = setupStarted - onCreateRef.current = onCreate - }, [onCreate, setupStarted]) - const { - steps: rowSteps, - session, - openInstall - } = useCloudStartSteps({ + const { steps: rowSteps } = useCloudStartSteps({ availability, access, repoId, agent, cloudSelected, - setupSessionId, - githubOverride: cloudOnly.githubStep, - onGranted: (repoName) => { - // D2: an owner approved on GitHub. Setup already running starts by itself; otherwise ask. - if (setupStartedRef.current) { - return - } - showGitHubGrantedToast(repoName, () => onCreateRef.current()) - } + setupSessionId: null, + githubOverride: cloudOnly.githubStep }) - // B2: on the personal account while a team the user is on has a plan, switch instead of buying. - const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected && !session) - const action = getCloudPrimaryAction(steps) - const panelVisible = cloudSelected && isCloudSetupPanelVisible(steps) - - const localOption = useMemo( - () => - hostOptions.find( - (option): option is ReadyProjectHostSetupOption => - option.kind === 'ready' && option.hostId === LOCAL_EXECUTION_HOST_ID - ) ?? null, - [hostOptions] - ) + const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected) + const setupNeeded = cloudSetupRequired(steps, { + teamSwitch: switchTeam !== null, + agentSkipped: isCloudSetupAgentSkipped(agent) + }) + // The agent has no Orca Cloud account (the user skipped setting it up): never launch it into its + // /login. Start a plain terminal and say how to set the agent up once. + const agentUnset = + cloudSelected && steps.some((step) => step.id === 'agent' && step.state === 'optional') + const onCreateRaw = useCloudOnlyCreate({ + cloudOnly, + createWorkspace, + prompt, + agent: agentUnset ? null : agent, + profileId, + hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), + onClose + }) + const onCreate = useCallback(() => { + if (!agentUnset) { + onCreateRaw() + return + } + // A GitHub-only start already leaves the agent out (above); a local project's create skips it. + if (cloudOnly.picked || !onCreateWithoutAgent) { + onCreateRaw() + } else { + onCreateWithoutAgent() + } + showAgentNotStartedToast(agent) + }, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent]) const { markTouched } = useRunOnDefault({ active, @@ -172,95 +175,41 @@ export function useCloudStartComposer({ setRecipeId?.(ORCA_CLOUD_RECIPE_ID) }, [markTouched, setRecipeId]) - // "Use this computer instead": switch, then submit once the switch has rendered. - const localSubmitPendingRef = useRef(false) - const useThisComputer = useCallback(() => { - if (!localOption) { - return - } - markTouched() - localSubmitPendingRef.current = true - setRecipeId?.(null) - onHostChange?.(localOption.id) - }, [localOption, markTouched, onHostChange, setRecipeId]) - useEffect(() => { - if (localSubmitPendingRef.current && !cloudSelected) { - localSubmitPendingRef.current = false - createWorkspace() - } - }, [cloudSelected, createWorkspace]) - - // O4: setup started here (or its restored draft) starts by itself once every row is done. - const startAfterSetup = useCallback(() => { - setSetupStarted(false) - setRestoreDone(true) - onCreate() - }, [onCreate]) - const allSet = useSetupAutoStart({ - armed: setupStarted && cloudSelected, - done: action === 'start' || session?.finished === true, - setupSessionId, - onStart: startAfterSetup - }) - - // The draft survives the browser trip and a quit; it is cleared once a workspace starts. - const runSetup = useCallback(() => { - const draft = { + // Start with setup still open: the dialog closes and the page takes over, prompt kept (N6). + const openSetup = useCallback(() => { + saveCloudStartDraft(profileId, { prompt, repoId, agent, - target: 'orca-cloud' as const, - setupSessionId, + target: 'orca-cloud', + setupSessionId: null, createdAt: Date.now() - } - saveCloudStartDraft(profileId, draft) - setSetupStarted(true) - const open = getOpenSetupSteps(steps) - // D1: GitHub is the only thing missing, so its install page is the whole trip. - if (open.length > 0 && open.every((step) => step.id === 'github' || step.id === 'agent')) { - void openInstall() - return - } - const startSession = getCloudSetupStarter() - const fallback = setupActionFor(steps, access, availability) - if (!startSession) { - fallback?.() - return - } - // One browser trip for every missing step; the session id rides on the draft across a quit. - void startSession({ repoId, needs: open.map((step) => step.id) }) - .then((opened) => { - if (!opened) { - fallback?.() - return - } - setSetupSessionId(opened.sessionId) - saveCloudStartDraft(profileId, { ...draft, setupSessionId: opened.sessionId }) - }) - .catch(() => fallback?.()) - }, [access, agent, availability, openInstall, profileId, prompt, repoId, setupSessionId, steps]) - - // B1: only the trial is missing. Claiming it is the whole setup; the billing cache then reads - // entitled and the auto-start above submits. A personal account needs a team first: setup trip. - const startTrial = useCallback(() => { - setSetupStarted(true) - void claimOrcaCloudTrial().then((result) => { - if (result.status !== 'ok') { - runSetup() - } }) - }, [runSetup]) + openCloudSetupPage({ + prompt, + repoId, + agent, + availability, + cloudOnlyRepo: cloudOnly.picked?.fullName ?? null, + composer: composerSnapshot() + }) + onClose?.() + }, [agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId]) - const trip = { cloudSelected, setupStarted, allSet, session, steps, access, availability } - const tracker = useComposerSetupTracker({ - ...trip, - profileId, - readyToStart: action === 'start', - sessionId: setupSessionId, - runSetup, - // Ends the trip here; the tracker hook also clears the draft's session id. - onCancel: () => [setSetupStarted(false), setRestoreDone(true), setSetupSessionId(null)] - }) + // Reopened by the setup page: submit once the account and form are ready. Anything still open + // (a race, a revoked grant) leaves the composer for the user, never a second trip on its own. + const autoStartedRef = useRef(false) + const stepsSettled = !steps.some((step) => step.state === 'loading' && step.id !== 'agent') + useEffect(() => { + if (!autoStart || autoStartedRef.current || !cloudSelected || !createReady || !stepsSettled) { + return + } + if (setupNeeded) { + return + } + autoStartedRef.current = true + onCreate() + }, [autoStart, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled]) const recordCreated = useCallback(() => { if (!repoId) { @@ -278,51 +227,20 @@ export function useCloudStartComposer({ } }, [access, cloudSelected, profileId, repoId]) - // Orca Cloud isn't the target (or this build has none): the composer's own create runs. - const plainCreate = { - primaryActionLabel: null, - onPrimary: null, - primaryDisabled: false, - primaryIsCreate: true, - recordCreated - } - if (segment === 'hidden') { - return { view: null, ...plainCreate } - } - const view: CloudStartView = { - steps, - panelVisible: panelVisible || allSet, - allSet, - onSelectOrcaCloud, - onUserPick: markTouched, - cloudOnly, - folderProject: cloudOnly.folderProject, - ...setupViewExtras(switchTeam, tracker), - ...(panelVisible && localOption && action !== 'useThisComputer' && !cloudOnly.picked - ? { onUseThisComputer: useThisComputer } - : {}) - } - if (!cloudSelected) { - return { view, ...plainCreate } - } - const onPrimary = switchTeam - ? () => undefined - : action === 'start' - ? onCreate - : action === 'useThisComputer' - ? useThisComputer - : action === 'checking' - ? () => undefined - : action === 'startTrial' - ? startTrial - : runSetup - return { - view, - primaryActionLabel: getCloudPrimaryLabel(allSet || switchTeam ? 'start' : action), - onPrimary, - primaryDisabled: - action === 'checking' || allSet || (action === 'useThisComputer' && !localOption), - primaryIsCreate: action === 'start', - recordCreated + const view = useMemo( + () => + segment === 'hidden' + ? null + : { + onSelectOrcaCloud, + onUserPick: markTouched, + cloudOnly, + folderProject: cloudOnly.folderProject + }, + [cloudOnly, markTouched, onSelectOrcaCloud, segment] + ) + if (!view || !cloudSelected) { + return { view, onPrimary: null, recordCreated } } + return { view, onPrimary: setupNeeded ? openSetup : onCreate, recordCreated } } diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index b4d3b564034..fd9ec93edc9 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -1,20 +1,22 @@ -// The composer modal's side of "Start in Orca Cloud": feeds the composer state into -// useCloudStartComposer and returns what the primary button and ⌘↵ do. +// The composer modal's side of Orca Cloud: feeds the composer state into useCloudStartComposer and +// returns what the primary button and ⌘↵ do. import { useCallback, useEffect, type MutableRefObject } from 'react' import type { ComposerModalData } from '../composer-modal-data' import type { NewWorkspaceComposerCardProps } from '../new-workspace-composer-card-props' import { useCloudStartComposer } from './use-cloud-start-composer' +import { buildComposerSnapshot } from '../composer-cloud-auto-start' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' type ComposerCardState = Pick< NewWorkspaceComposerCardProps, | 'orcaCloudAvailability' | 'selectedEphemeralVmRecipeId' | 'onEphemeralVmRecipeChange' - | 'projectHostSetupOptions' - | 'onProjectHostSetupChange' | 'repoId' | 'name' -> + | 'baseBranch' + | 'note' +> & { linkedWorkItem?: ComposerModalData['linkedWorkItem'] } export function useComposerCloudStart({ active, @@ -23,15 +25,21 @@ export function useComposerCloudStart({ quickAgent, handleCreate, createDisabled, + quickAgentPick, + noAgentRef, recordCreatedRef, onClose }: { active: boolean modalData: ComposerModalData cardProps: ComposerCardState - quickAgent: string | null + quickAgent: TuiAgent | null handleCreate: () => Promise + /** Set right before a create to start it with no agent. */ + noAgentRef: MutableRefObject createDisabled: boolean + /** The agent pick (surface, draft) as the composer keeps it, for the setup page's snapshot. */ + quickAgentPick: Omit, 'note'> /** The composer's onCreated calls this: only a start that happened is remembered. */ recordCreatedRef: MutableRefObject<(() => void) | null> onClose?: () => void @@ -39,31 +47,39 @@ export function useComposerCloudStart({ // The latest handleCreate, never a ref copied after render: a submit right after an edit must // see that edit. const runCreate = useCallback(() => void handleCreate(), [handleCreate]) + const runCreateWithoutAgent = useCallback(() => { + noAgentRef.current = true + void handleCreate() + }, [handleCreate, noAgentRef]) + const composerSnapshot = useCallback( + () => buildComposerSnapshot(modalData, cardProps, { ...quickAgentPick, agent: quickAgent }), + [cardProps, modalData, quickAgent, quickAgentPick] + ) const cloudStart = useCloudStartComposer({ active, availability: cardProps.orcaCloudAvailability ?? 'unavailable', selectedRecipeId: cardProps.selectedEphemeralVmRecipeId ?? null, setRecipeId: cardProps.onEphemeralVmRecipeChange, - hostOptions: cardProps.projectHostSetupOptions ?? [], - onHostChange: cardProps.onProjectHostSetupChange, repoId: cardProps.repoId, prompt: cardProps.name, agent: quickAgent, initialTargetFixed: Boolean( modalData.initialEphemeralVmRecipeId || modalData.initialWorkspaceTarget || modalData.recovery ), + autoStart: modalData.cloudAutoStart === true, + createReady: !createDisabled, + composerSnapshot, onCreate: runCreate, + onCreateWithoutAgent: runCreateWithoutAgent, onClose }) useEffect(() => { recordCreatedRef.current = cloudStart.recordCreated }, [cloudStart.recordCreated, recordCreatedRef]) - const primaryCreateDisabled = cloudStart.primaryIsCreate - ? createDisabled || cloudStart.primaryDisabled - : cloudStart.primaryDisabled return { cloudStart, - primaryCreateDisabled, + // Local and Orca Cloud share one button: same label, same rules for when it's enabled. + primaryCreateDisabled: createDisabled, onPrimary: cloudStart.onPrimary ?? runCreate } } diff --git a/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts b/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts deleted file mode 100644 index bd3793ddef4..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts +++ /dev/null @@ -1,42 +0,0 @@ -// O4: setup started from this composer (or its restored draft) starts the workspace by itself. -// When every required row is done, hold "All set", then submit as if ⌘↵ had been pressed. -import { useEffect, useState } from 'react' -import { CLOUD_SETUP_ALL_SET_HOLD_MS } from '@/lib/orca-cloud/cloud-setup-session-seam' -import { recordCloudSetupFirstSandbox } from '@/lib/orca-cloud/cloud-setup-telemetry' -import { prefersReducedMotion } from './cloud-start-view' - -/** Returns whether "All set" is showing. `onStart` ends the trip state, then creates. */ -export function useSetupAutoStart({ - armed, - done, - setupSessionId, - onStart -}: { - /** Setup was started here and Orca Cloud is still the target. */ - armed: boolean - /** Every required row is done, or the session says it finished. */ - done: boolean - setupSessionId: string | null - onStart: () => void -}): boolean { - const [allSet, setAllSet] = useState(false) - useEffect(() => { - if (!armed || !done) { - return - } - setAllSet(true) - const timer = window.setTimeout( - () => { - setAllSet(false) - // N10: time to first sandbox, from when the tracker first saw this trip. - if (setupSessionId) { - recordCloudSetupFirstSandbox({ sessionId: setupSessionId, hoursSource: 'unknown' }) - } - onStart() - }, - prefersReducedMotion() ? 0 : CLOUD_SETUP_ALL_SET_HOLD_MS - ) - return () => window.clearTimeout(timer) - }, [armed, done, onStart, setupSessionId]) - return allSet -} diff --git a/src/renderer/src/components/new-workspace/run-target-options.ts b/src/renderer/src/components/new-workspace/run-target-options.ts index 9ed7fe869a5..c484b9d4b5c 100644 --- a/src/renderer/src/components/new-workspace/run-target-options.ts +++ b/src/renderer/src/components/new-workspace/run-target-options.ts @@ -308,3 +308,16 @@ export function buildRunTargetRows( ] return { rows, matchedRecipes, hiddenHostCount: hostRows.hiddenHostCount } } + +/** Add-host actions open dialogs, so the picker closes before they run. */ +export function closingFirst( + close: () => void, + action: (() => void) | undefined +): (() => void) | undefined { + return action + ? () => { + close() + action() + } + : undefined +} diff --git a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts index 2178b08b831..e8d235303eb 100644 --- a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts +++ b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts @@ -1,7 +1,5 @@ import { useMemo } from 'react' import { useAppStore } from '@/store/index' -import { useTranslate } from '@/i18n/use-translate' -import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { agentChoicePending } from '@/lib/host-chat-program' import { useAgentsOfferedForLaunch } from '@/lib/host-chat-program-acquisition' import { @@ -11,7 +9,6 @@ import { } from '@/lib/quick-workspace-agent-selection' import { ORCA_CLOUD_AGENT_IDS, - orcaCloudAgentFallback, orcaCloudAgentMenuModel, pickOrcaCloudAgent } from '@/lib/orca-cloud/orca-cloud-agent-picker' @@ -38,7 +35,6 @@ export function useComposerQuickAgent( quickAgentOverride: TuiAgent | null | undefined, setQuickAgentOverride: (agent: TuiAgent | null | undefined) => void ) { - const t = useTranslate() // The picker rows' workspace when known, so the offered list and the rows read one host. const launchWorkspace = cardProps.agentRows?.target.workspace ?? composerLaunchWorkspace(cardProps) @@ -83,23 +79,8 @@ export function useComposerQuickAgent( const chipAgentIds = offeredAgentIds && new Set([...offeredAgentIds, ...(quickAgent && choicePending(quickAgent) ? [quickAgent] : [])]) - // Said, not silent: the agent the user wanted isn't on the image, so another one is selected. - const orcaCloudFallback = orcaCloud - ? orcaCloudAgentFallback({ - override: quickAgentOverride, - defaultAgent: settings?.defaultTuiAgent, - selected: quickAgent - }) - : null - const agentNotice = orcaCloudFallback - ? t( - 'components.newWorkspace.orcaCloudAgentFallback', - '{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected.', - { - agent: formatAgentTypeLabel(orcaCloudFallback.wanted), - fallback: formatAgentTypeLabel(orcaCloudFallback.selected) - } - ) - : undefined + // Orca Cloud adds nothing to the dialog (Neil): an agent it can't run falls back silently; the + // picker shows what will start. + const agentNotice: string | undefined = undefined return { orcaCloud, orcaCloudModel, quickAgent, chipAgentIds, agentNotice } } diff --git a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts index 0de3f1d8ec9..291b1352c47 100644 --- a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts +++ b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts @@ -51,7 +51,8 @@ export function useRunTargetOrcaCloud({ override, open, close, - selectRecipe + selectRecipe, + onSelectOrcaCloud }: { recipes: readonly EphemeralVmRecipeOption[] offer: OrcaCloudRunTargetAccess | null @@ -60,6 +61,8 @@ export function useRunTargetOrcaCloud({ open: boolean close: () => void selectRecipe: (recipeId: string) => void + /** Picks Orca Cloud whatever setup it still needs (the composer walks it after Start). */ + onSelectOrcaCloud?: () => void }): { access: OrcaCloudRunTargetAccess /** A pick is waiting on billing; the row shows busy. */ @@ -97,6 +100,11 @@ export function useRunTargetOrcaCloud({ const pickFor = useCallback( (resolved: OrcaCloudRunTargetAccess, recipe: EphemeralVmRecipeOption | null): void => { const pick = getOrcaCloudPick(resolved) + if (onSelectOrcaCloud && pick.kind !== 'blocked') { + close() + onSelectOrcaCloud() + return + } if (pick.kind === 'act') { close() // The fix finishes elsewhere (plans, portal, settings): reread billing on return. @@ -106,7 +114,7 @@ export function useRunTargetOrcaCloud({ selectRecipe(recipe.id) } }, - [close, selectRecipe] + [close, onSelectOrcaCloud, selectRecipe] ) const runBlockedAction = useCallback((): void => pickFor(access, null), [access, pickFor]) const select = useCallback( diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx new file mode 100644 index 00000000000..d9dabad6168 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -0,0 +1,296 @@ +// "Set up Orca Cloud" as a page (composer-redo). Start in the composer closes the dialog and opens +// this when the account isn't ready. One step at a time: the current step is the page; finished +// steps are ticks in the stepper. Browser hops only for sign-in, Stripe and GitHub. When every +// step is done, the saved prompt starts by itself. +import React from 'react' +import { ArrowLeft, Check, Cloud, Copy, ExternalLink, LoaderCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Skeleton } from '@/components/ui/skeleton' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice' +import { currentStepCopy, stepLabel } from './cloud-setup-page-copy' +import type { CloudSetupFlow } from './use-cloud-setup-flow' +import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' + +export type CloudSetupPageProps = { + flow: CloudSetupFlow + projectName: string | null + prompt: string + agentLabel: string | null + /** Back to the composer with the prompt, project and agent as they were. */ + onBack: () => void + /** "All set": shown for a moment before the workspace starts. */ + starting: boolean +} + +type StepState = 'done' | 'current' | 'todo' + +function SetupStepper({ + steps, + current, + allDone +}: { + steps: readonly CloudSetupStep[] + current: CloudSetupStep | null + allDone: boolean +}): React.JSX.Element { + const t = useTranslate() + const currentIndex = current ? steps.findIndex((step) => step.id === current.id) : steps.length + return ( +
    + {steps.map((step, index) => { + const state: StepState = + allDone || index < currentIndex ? 'done' : index === currentIndex ? 'current' : 'todo' + const label = stepLabel(step, t) + return ( +
  1. + {index > 0 ? : null} + + {state === 'done' ? : null} + {state === 'current' ? ( + + ) : null} + + + {label} + + {state === 'done' + ? `, ${t('cloudSetupPage.stepDone', 'done')}` + : state === 'current' + ? `, ${t('cloudSetupPage.stepCurrent', 'current step')}` + : ''} + + +
  2. + ) + })} +
+ ) +} + +function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { + const t = useTranslate() + return ( +
+ + + {t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')} + + + {flow.copyLink ? ( + + ) : null} + + +
+ ) +} + +function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | null { + const t = useTranslate() + const browser = (label: string, onClick: () => void): React.JSX.Element => ( + + ) + const inBrowserAction = + flow.action === 'sign-in' || + flow.action === 'choose-plan' || + flow.action === 'fix-billing' || + flow.action === 'github-install' + if (flow.inBrowser && inBrowserAction && !flow.error) { + return + } + const continueLabel = t('cloudSetupPage.continueInBrowser', 'Continue in browser') + switch (flow.action) { + case 'sign-in': + case 'choose-plan': + return browser(continueLabel, flow.continueInBrowser) + case 'fix-billing': + // A failed payment is fixed in the billing portal (browser); hours and the cap in Settings. + return flow.current?.need === 'payment' ? ( + browser(continueLabel, flow.fixBilling) + ) : ( + + ) + case 'github-install': + return browser(continueLabel, flow.installGitHub) + case 'start-trial': + return ( + + ) + case 'switch-team': + return
{flow.teamAction}
+ case 'agent': + return ( +
+ + +
+ ) + case 'needs-repository': + return flow.current?.action ? ( + + ) : null + case 'ask-owner': + return ( + + ) + case 'github-waiting': + return ( + + + {t('cloudSetupPage.github.waiting', 'This page starts the workspace once they approve.')} + + ) + case 'checking': + return + case 'done': + return ( + + + {t('cloudSetupPage.starting', 'Starting…')} + + ) + } +} + +export function CloudSetupPage({ + flow, + projectName, + prompt, + agentLabel, + onBack, + starting +}: CloudSetupPageProps): React.JSX.Element { + const t = useTranslate() + const titleId = React.useId() + const headingRef = React.useRef(null) + // Every row reads done but hasn't held yet: still "Checking" until the layer says it's starting. + const shown: CloudSetupFlow = starting + ? { ...flow, action: 'done' } + : flow.action === 'done' + ? { ...flow, action: 'checking' } + : flow + const copy = currentStepCopy(shown, t, agentLabel) + // Each new step moves focus to its heading so screen readers hear the change once. + const stepKey = `${shown.current?.id ?? 'done'}:${shown.action}` + React.useEffect(() => { + headingRef.current?.focus({ preventScroll: true }) + }, [stepKey]) + return ( +
+
+
+ + + + {t('cloudSetupPage.eyebrow', 'Orca Cloud setup')} + +
+ +
+ +
+ +
+

+ {copy.title} +

+ {shown.action === 'checking' ? ( + + ) : copy.lead ? ( +

{copy.lead}

+ ) : null} + {copy.note ?

{copy.note}

: null} +
+ + {flow.error && !starting ? ( + + action === 'reopen-browser' ? flow.reopenBrowser() : flow.continueInBrowser() + } + className="mt-6" + /> + ) : null} + +
+ +
+ +
+
+
+ {t('cloudSetupPage.startsAfter', 'Starts when setup is done')} +
+
+ {prompt.trim() || t('cloudSetupPage.untitled', 'New cloud workspace')} +
+
+ {[projectName, agentLabel, t('cloudSetupPage.orcaCloud', 'Orca Cloud')] + .filter(Boolean) + .join(' · ')} +
+
+
+
+
+ ) +} diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx new file mode 100644 index 00000000000..3672eddd32d --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -0,0 +1,140 @@ +// Mounts the Orca Cloud setup page over the workspace area while a Start is waiting on setup. Other +// pages (Settings for billing or agent accounts) show over it; coming back shows it again. Opening +// another workspace from the sidebar puts setup away (Back in the composer still has the prompt). +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { + closeCloudSetupPage, + useCloudSetupPageRequest, + type CloudSetupPageRequest +} from '@/lib/orca-cloud/cloud-setup-page-store' +import { CLOUD_SETUP_ALL_SET_HOLD_MS } from '@/lib/orca-cloud/cloud-setup-session-seam' +import { isOrcaCloudAccountAgent } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { agentName } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' +import { prefersReducedMotion } from '@/components/new-workspace/run-on/cloud-start-view' +import { CloudSetupPage } from './CloudSetupPage' +import { closeSetupPageWhenCreateTakesOver } from './cloud-setup-handoff' +import { useCloudSetupFlow } from './use-cloud-setup-flow' + +/** How long every row must read done before the page starts the workspace. */ +const SETTLE_MS = 1_500 + +function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void { + // A GitHub-only repository can't be preselected; the composer opens for one more Start. + const hiddenStart = autoStart && !request.cloudOnlyRepo + if (!hiddenStart) { + closeCloudSetupPage() + } else { + // Warm the start screen's chunk so it is ready the frame the create takes over. + void import('@/components/worktree-creation/WorktreeCreationPanel').catch(() => undefined) + } + useAppStore.getState().openModal('new-workspace-composer', { + ...request.composer, + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + ...(hiddenStart ? { cloudAutoStart: true } : {}) + }) + if (hiddenStart) { + // The page stays up until the start screen has painted: nothing under it may flash. + closeSetupPageWhenCreateTakesOver({ + getState: () => useAppStore.getState(), + subscribe: (listener) => useAppStore.subscribe(listener), + startScreenShown: () => document.querySelector('[data-vm-build-sheet]') !== null, + closePage: closeCloudSetupPage, + setTimer: (callback, ms) => window.setTimeout(callback, ms), + clearTimer: (handle) => window.clearTimeout(handle) + }) + } +} + +function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): React.JSX.Element { + const t = useTranslate() + const flow = useCloudSetupFlow(request, request.debugAccess) + const projectName = useAppStore( + (s) => s.repos.find((repo) => repo.id === request.repoId)?.displayName ?? null + ) + const agentLabel = isOrcaCloudAccountAgent(request.agent) ? agentName(request.agent, t) : null + const [starting, setStarting] = useState(false) + // Rows can all read done for a moment right after a sign-in, before billing, GitHub and agent + // accounts answer for the new account. Done must hold for SETTLE_MS before "All set". + const done = flow.action === 'done' + useEffect(() => { + if (!done) { + return + } + const timer = window.setTimeout(() => setStarting(true), SETTLE_MS) + return () => window.clearTimeout(timer) + }, [done]) + useEffect(() => { + if (!starting) { + return + } + const timer = window.setTimeout( + () => reopenComposer(request, true), + prefersReducedMotion() ? 0 : CLOUD_SETUP_ALL_SET_HOLD_MS + ) + return () => window.clearTimeout(timer) + }, [request, starting]) + const onBack = useCallback(() => reopenComposer(request, false), [request]) + return ( + + ) +} + +export function CloudSetupPageLayer(): React.JSX.Element | null { + const request = useCloudSetupPageRequest() + const onWorkspaceView = useAppStore((s) => s.activeView === 'terminal') + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId ?? null) + const openedOnRef = useRef(undefined) + useEffect(() => { + if (!request) { + openedOnRef.current = undefined + return + } + if (openedOnRef.current === undefined) { + openedOnRef.current = activeWorktreeId + return + } + if (openedOnRef.current !== activeWorktreeId) { + closeCloudSetupPage() + } + }, [activeWorktreeId, request]) + // The right sidebar (files, source control) is noise during setup: hide it while the page shows, + // and put it back as it was when the page closes or another page takes over. + const showing = request !== null && onWorkspaceView + useEffect(() => { + if (!showing) { + return + } + const store = useAppStore.getState() + const wasOpen = store.rightSidebarOpen + if (wasOpen) { + store.setRightSidebarOpen(false) + } + return () => { + if (wasOpen && !useAppStore.getState().rightSidebarOpen) { + useAppStore.getState().setRightSidebarOpen(true) + } + } + }, [showing]) + if (!request) { + return null + } + // Stays mounted under other pages so an open browser trip keeps its session and waiting state. + return ( +
+ +
+ ) +} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts new file mode 100644 index 00000000000..720992382cf --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts @@ -0,0 +1,88 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + closeSetupPageWhenCreateTakesOver, + SETUP_HANDOFF_MAX_MS, + SETUP_HANDOFF_PAINT_MAX_MS +} from './cloud-setup-handoff' + +function harness(initial: { activePendingCreationId: string | null; activeModal: string }) { + let state = { ...initial } + let painted = false + const listeners = new Set<(s: typeof state) => void>() + const closePage = vi.fn() + const set = (patch: Partial): void => { + state = { ...state, ...patch } + for (const listener of listeners) { + listener(state) + } + } + const cancel = closeSetupPageWhenCreateTakesOver({ + getState: () => state, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + startScreenShown: () => painted, + closePage, + setTimer: (callback, ms) => setTimeout(callback, ms), + clearTimer: (handle) => clearTimeout(handle) + }) + return { set, paint: () => (painted = true), closePage, cancel, listeners } +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('closeSetupPageWhenCreateTakesOver', () => { + it('keeps the setup page up until the start screen has painted', () => { + vi.useFakeTimers() + const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' }) + // The hidden composer is still filling in: the page must cover the workspace underneath. + vi.advanceTimersByTime(3_000) + expect(h.closePage).not.toHaveBeenCalled() + // Submit publishes the pending create and closes the composer in one go. + h.set({ activePendingCreationId: 'c1', activeModal: 'none' }) + // Its start screen's chunk hasn't rendered yet: still covered, never a bare frame. + vi.advanceTimersByTime(200) + expect(h.closePage).not.toHaveBeenCalled() + h.paint() + vi.advanceTimersByTime(20) + expect(h.closePage).toHaveBeenCalledOnce() + expect(h.listeners.size).toBe(0) + }) + + it('does not give up on a create published a tick after the composer closed', () => { + vi.useFakeTimers() + const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' }) + h.set({ activeModal: 'none' }) + h.set({ activePendingCreationId: 'c1' }) + vi.advanceTimersByTime(100) + expect(h.closePage).not.toHaveBeenCalled() + h.paint() + vi.advanceTimersByTime(20) + expect(h.closePage).toHaveBeenCalledOnce() + }) + + it('closes when the composer goes away without a create', () => { + vi.useFakeTimers() + const h = harness({ activePendingCreationId: null, activeModal: 'new-workspace-composer' }) + h.set({ activeModal: 'none' }) + vi.advanceTimersByTime(1) + expect(h.closePage).toHaveBeenCalledOnce() + }) + + it('ignores an older active create, and never covers longer than its caps', () => { + vi.useFakeTimers() + const h = harness({ activePendingCreationId: 'old', activeModal: 'new-workspace-composer' }) + h.set({ activePendingCreationId: 'old' }) + expect(h.closePage).not.toHaveBeenCalled() + vi.advanceTimersByTime(SETUP_HANDOFF_MAX_MS) + expect(h.closePage).toHaveBeenCalledOnce() + + const unpainted = harness({ activePendingCreationId: null, activeModal: 'none' }) + unpainted.set({ activePendingCreationId: 'c2' }) + vi.advanceTimersByTime(SETUP_HANDOFF_PAINT_MAX_MS + 20) + expect(unpainted.closePage).toHaveBeenCalledOnce() + }) +}) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts new file mode 100644 index 00000000000..884c4470a93 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts @@ -0,0 +1,94 @@ +// The setup page hands the screen to the start screen. It used to close first and then let the +// hidden composer auto-start, so for a few frames the workspace underneath (a terminal) showed +// before "Starting your cloud workspace" did (Neil, build ff845fe). Now the page stays up until the +// create's start screen has actually painted, or the composer goes away without a create. + +type HandoffState = { activePendingCreationId: string | null; activeModal: string } + +export type HandoffDeps = { + getState: () => HandoffState + subscribe: (listener: (state: HandoffState) => void) => () => void + /** True once the start screen is in the DOM (its lazy chunk may land a few frames later). */ + startScreenShown: () => boolean + closePage: () => void + setTimer: (callback: () => void, ms: number) => Timer + clearTimer: (handle: Timer) => void +} + +/** The hidden composer reveals itself after 8 s; past that the dialog sits over the page anyway. */ +export const SETUP_HANDOFF_MAX_MS = 10_000 +/** How long to wait for the start screen to paint once its create is active. */ +export const SETUP_HANDOFF_PAINT_MAX_MS = 2_000 +const PAINT_POLL_MS = 16 +const COMPOSER_MODAL = 'new-workspace-composer' + +/** Call right after opening the auto-starting composer. Returns a cancel. */ +export function closeSetupPageWhenCreateTakesOver(deps: HandoffDeps): () => void { + const before = deps.getState().activePendingCreationId + let done = false + const timers = new Set() + const later = (callback: () => void, ms: number): void => { + const handle = deps.setTimer(() => { + timers.delete(handle) + callback() + }, ms) + timers.add(handle) + } + const stop = (): void => { + done = true + unsubscribe() + for (const handle of timers) { + deps.clearTimer(handle) + } + timers.clear() + } + const finish = (): void => { + if (!done) { + stop() + deps.closePage() + } + } + let waitingForPaint = false + // The create is active: keep covering until its start screen is on screen (or give up). + const awaitPaint = (): void => { + if (waitingForPaint) { + return + } + waitingForPaint = true + const startedAt = Date.now() + const poll = (): void => { + if (deps.startScreenShown() || Date.now() - startedAt >= SETUP_HANDOFF_PAINT_MAX_MS) { + finish() + return + } + later(poll, PAINT_POLL_MS) + } + poll() + } + let closeGraceArmed = false + const check = (state: HandoffState): void => { + if (done) { + return + } + if (state.activePendingCreationId !== null && state.activePendingCreationId !== before) { + awaitPaint() + return + } + // Closed with no create yet: the submit may publish its pending entry in the same tick. + if (state.activeModal !== COMPOSER_MODAL && !closeGraceArmed && !waitingForPaint) { + closeGraceArmed = true + later(() => { + if (!waitingForPaint) { + finish() + } + }, 0) + } + } + const unsubscribe = deps.subscribe(check) + later(finish, SETUP_HANDOFF_MAX_MS) + return () => { + if (!done) { + stop() + } + } +} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts new file mode 100644 index 00000000000..edd0e67a473 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts @@ -0,0 +1,170 @@ +// Words for the Orca Cloud setup page: each step's stepper label, and the current step's title, +// lead and note. Copy follows the product glossary (Orca Cloud, sandbox hours, Team plan). +import type { Translate } from '@/i18n/use-translate' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { sessionDetailCopy } from '@/components/new-workspace/run-on/cloud-setup-session-copy' +import type { CloudSetupPageModel } from './cloud-setup-page-model' + +export function stepLabel(step: CloudSetupStep, t: Translate): string { + switch (step.id) { + case 'account': + return t('cloudSetupPage.step.account', 'Account') + case 'team': + return t('cloudSetupPage.step.team', 'Team') + case 'plan': + return step.need === 'trial' + ? t('cloudSetupPage.step.trial', 'Trial') + : t('cloudSetupPage.step.plan', 'Plan') + case 'github': + return t('cloudSetupPage.step.github', 'GitHub') + case 'agent': + return t('cloudSetupPage.step.agent', 'Agent') + } +} + +type StepCopy = { title: string; lead: string | null; note?: string | null } + +function trialHours(step: CloudSetupStep): string | null { + return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null +} + +export function currentStepCopy( + flow: Pick, + t: Translate, + agentLabel: string | null +): StepCopy { + const step = flow.current + const detail = step + ? ((sessionDetailCopy(step, t) === undefined ? step.detail : sessionDetailCopy(step, t)) ?? + null) + : null + switch (flow.action) { + case 'sign-in': + return { + title: t('cloudSetupPage.signIn.title', 'Sign in to Orca'), + lead: t( + 'cloudSetupPage.signIn.lead', + 'Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.' + ), + note: t( + 'cloudSetupPage.signIn.note', + 'New teams get a trial with no card needed. This page picks up each step on its own.' + ) + } + case 'start-trial': { + const hours = step ? trialHours(step) : null + return { + title: t('cloudSetupPage.trial.title', 'Start your free trial'), + lead: + hours === null + ? t('cloudSetupPage.trial.leadNoHours', 'Try Orca Cloud on your team. No card needed.') + : t( + 'cloudSetupPage.trial.lead', + '{{hours}} sandbox hours to try Orca Cloud. No card needed.', + { + hours, + count: Number(hours), + defaultValue_one: '{{hours}} sandbox hour to try Orca Cloud. No card needed.' + } + ), + note: t('cloudSetupPage.trial.note', 'Nothing is charged until you choose a plan.') + } + } + case 'choose-plan': + return step?.need === 'trial-used-up' + ? { + title: t('cloudSetupPage.plan.trialUsedUpTitle', 'Your trial is used up'), + lead: t( + 'cloudSetupPage.plan.trialUsedUpLead', + 'Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.' + ) + } + : step?.need === 'renew-plan' + ? { + title: t('cloudSetupPage.plan.renewTitle', 'Renew your Team plan'), + lead: t( + 'cloudSetupPage.plan.renewLead', + 'Your Team plan ended. Renew it in your browser to start this workspace.' + ) + } + : { + title: t('cloudSetupPage.plan.title', 'Choose a Team plan'), + lead: t( + 'cloudSetupPage.plan.lead', + 'Orca Cloud needs a Team plan. Checkout opens in your browser.' + ) + } + case 'fix-billing': + return { + title: + step?.need === 'payment' + ? t('cloudSetupPage.billing.paymentTitle', 'Update your payment method') + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capTitle', 'Spend cap reached') + : t('cloudSetupPage.billing.hoursTitle', 'Out of sandbox hours'), + lead: + step?.need === 'payment' + ? t( + 'cloudSetupPage.billing.paymentLead', + 'The last payment failed. Update the card to keep going.' + ) + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capLead', 'Raise the spend cap to start this workspace.') + : t('cloudSetupPage.billing.hoursLead', 'Turn on overage to start this workspace.') + } + case 'switch-team': + return { title: t('cloudSetupPage.team.title', 'Switch to your team'), lead: detail } + case 'github-install': + return { + title: t('cloudSetupPage.github.title', 'Give Orca Cloud access on GitHub'), + // The row names the repository ("Orca Cloud can't reach acme/web yet"). + lead: detail, + note: t( + 'cloudSetupPage.github.lead', + 'Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.' + ) + } + case 'github-waiting': + return { + title: t('cloudSetupPage.github.waitingTitle', 'Waiting for approval on GitHub'), + lead: detail, + note: step?.note ?? null + } + case 'needs-repository': + return { + title: t('cloudSetupPage.repository.title', 'Orca Cloud needs a GitHub repository'), + lead: detail, + note: step?.note ?? null + } + case 'ask-owner': + return { + title: t('cloudSetupPage.owner.title', 'An owner or admin needs to fix this'), + lead: + detail ?? + t( + 'cloudSetupPage.owner.lead', + 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' + ) + } + case 'agent': + return { + title: agentLabel + ? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel }) + : t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'), + lead: t( + 'cloudSetupPage.agent.lead', + 'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.' + ) + } + case 'checking': + return { + title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'), + lead: null + } + case 'done': + return { + title: t('cloudSetupPage.done.title', 'All set'), + lead: t('cloudSetupPage.done.lead', 'Starting your cloud workspace…') + } + } +} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts new file mode 100644 index 00000000000..1fbeb8eca20 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { actionForStep, cloudSetupPageModel, sessionNeedsFrom } from './cloud-setup-page-model' + +describe('cloudSetupPageModel', () => { + it('walks one step at a time: the first unfinished step is current', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'needed', need: 'trial', canFix: true, trialSeconds: 7200 }, + { id: 'github', state: 'needed', need: 'github', canFix: true }, + { id: 'agent', state: 'optional' } + ] + const model = cloudSetupPageModel(steps) + expect(model.current?.id).toBe('plan') + expect(model.action).toBe('start-trial') + expect(sessionNeedsFrom(steps)).toEqual(['plan', 'github']) + }) + + it('a skipped agent finishes setup', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'optional' } + ] + expect(cloudSetupPageModel(steps).action).toBe('agent') + expect(cloudSetupPageModel(steps, { agentSkipped: true })).toMatchObject({ + current: null, + action: 'done' + }) + }) + + it('maps each blocker to its one action', () => { + expect(actionForStep({ id: 'plan', state: 'pending', need: 'trial' })).toBe('sign-in') + expect(actionForStep({ id: 'plan', state: 'needed', need: 'payment', canFix: true })).toBe( + 'fix-billing' + ) + expect(actionForStep({ id: 'plan', state: 'needed', need: 'plan', canFix: false })).toBe( + 'ask-owner' + ) + expect(actionForStep({ id: 'team', state: 'needed' }, { teamSwitch: true })).toBe('switch-team') + expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') + }) +}) + +describe('page settles before it starts', () => { + it('a still-loading agent row reads Checking, not All set', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'loading' } + ] + expect(cloudSetupPageModel(steps).action).toBe('checking') + }) +}) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts new file mode 100644 index 00000000000..ca7c8884e5f --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts @@ -0,0 +1,143 @@ +// The full-page Orca Cloud setup (composer-redo): which step is current, what its one action is, +// and when the saved prompt can start. Pure, so every state is unit-tested here. +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' + +/** What the current step's primary button does. */ +export type CloudSetupPageAction = + /** Sign in (and whatever the browser trip covers next): one browser hop. */ + | 'sign-in' + /** The team's trial, claimed in the app: no browser, no card. */ + | 'start-trial' + /** Stripe Checkout for a plan: one browser hop. */ + | 'choose-plan' + /** Hours, spend cap or payment, fixed in billing settings or the portal. */ + | 'fix-billing' + /** Personal account while a team has the plan: switch in place (B2). */ + | 'switch-team' + /** Install the GitHub App on this repository: one browser hop. */ + | 'github-install' + /** An owner must approve on GitHub; the page waits and starts on its own. */ + | 'github-waiting' + /** The project isn't on GitHub; nothing here fixes it. */ + | 'needs-repository' + /** A member can't fix billing; an owner or admin has to. */ + | 'ask-owner' + /** Optional agent account: set it up once, or skip. */ + | 'agent' + /** Still reading account, plan or repository state. */ + | 'checking' + /** Every step is done: the prompt starts. */ + | 'done' + +export type CloudSetupPageModel = { + steps: readonly CloudSetupStep[] + current: CloudSetupStep | null + action: CloudSetupPageAction +} + +function isFinished(step: CloudSetupStep, agentSkipped: boolean): boolean { + if (step.state === 'done') { + return true + } + if (step.id === 'agent') { + // Still loading reads "Checking": the page only says All set once every row has answered. + return agentSkipped && step.state !== 'loading' + } + return false +} + +export function actionForStep( + step: CloudSetupStep, + { teamSwitch = false }: { teamSwitch?: boolean } = {} +): CloudSetupPageAction { + if (step.state === 'loading') { + return 'checking' + } + switch (step.id) { + case 'account': + return 'sign-in' + case 'team': + return teamSwitch ? 'switch-team' : 'sign-in' + case 'plan': + if (step.state === 'pending') { + return 'sign-in' + } + if (step.canFix === false) { + return 'ask-owner' + } + switch (step.need) { + case 'trial': + return 'start-trial' + case 'hours': + case 'spend-cap': + case 'payment': + return 'fix-billing' + case 'plan': + case 'renew-plan': + case 'trial-used-up': + case 'sign-in': + case 'github': + case undefined: + return 'choose-plan' + } + return 'choose-plan' + case 'github': + if (step.state === 'failed' && step.blocksStart) { + return 'needs-repository' + } + if (step.state === 'pending' && step.blocksStart) { + return 'github-waiting' + } + return 'github-install' + case 'agent': + return 'agent' + } +} + +/** + * The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub, + * agent); the first unfinished one is current. A signed-out plan row is "pending" until sign-in, so + * account stays current until then. + */ +export function cloudSetupPageModel( + steps: readonly CloudSetupStep[], + { + agentSkipped = false, + teamSwitch = false + }: { agentSkipped?: boolean; teamSwitch?: boolean } = {} +): CloudSetupPageModel { + const current = steps.find((step) => !isFinished(step, agentSkipped)) ?? null + if (!current) { + return { steps, current: null, action: 'done' } + } + return { steps, current, action: actionForStep(current, { teamSwitch }) } +} + +/** Needs that a browser trip (setup session) can cover, from the current step on. */ +export function sessionNeedsFrom(steps: readonly CloudSetupStep[]): CloudSetupStep['id'][] { + return steps + .filter((step) => step.state !== 'done' && step.state !== 'optional' && step.id !== 'agent') + .map((step) => step.id) +} + +/** + * Pressing Start goes straight to create only when nothing is open. An agent without an account + * counts until the user skips it once; a still-loading agent row never holds a start. + */ +export function cloudSetupRequired( + steps: readonly CloudSetupStep[], + { + teamSwitch = false, + agentSkipped = false + }: { teamSwitch?: boolean; agentSkipped?: boolean } = {} +): boolean { + if (teamSwitch) { + return true + } + return steps.some((step) => { + if (step.id === 'agent') { + return step.state === 'optional' && !agentSkipped + } + return step.state !== 'done' + }) +} diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts new file mode 100644 index 00000000000..165dbd03b21 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -0,0 +1,246 @@ +// The setup page's state and actions (composer-redo). It reuses the composer's setup plumbing: the +// rows from billing, the GitHub repository check and the agent accounts (useCloudStartSteps), the +// one-trip setup session (#255) with its deep-link return (#257), B2's team switch, and the +// tracker's error parsing (#260). Only the UI moved: from a card in the dialog to this page. +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' +import { + invalidateOrcaCloudBilling, + prefetchOrcaCloudBilling, + useOrcaCloudRunTargetAccess +} from '@/components/new-workspace/orca-cloud-billing-cache' +import { setupActionFor } from '@/components/new-workspace/run-on/cloud-start-actions' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { useCloudStartSteps } from '@/components/new-workspace/run-on/use-cloud-start-steps' +import { useSwitchTeamSteps } from '@/components/new-workspace/cloud-setup/use-cloud-setup-tracker' +import { parseCloudSetupError } from '@/components/new-workspace/cloud-setup/cloud-setup-errors' +import { + canCopyCloudSetupLink, + copyCloudSetupLink, + reopenCloudSetup +} from '@/components/new-workspace/cloud-setup/cloud-setup-tracker-actions' +import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam' +import { + isCloudSetupAgentSkipped, + rememberCloudSetupAgentSkipped, + type CloudSetupPageRequest +} from '@/lib/orca-cloud/cloud-setup-page-store' +import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' +import { + cloudSetupPageModel, + sessionNeedsFrom, + type CloudSetupPageModel +} from './cloud-setup-page-model' + +/** Billing rows re-read this often while the page waits on a browser step (focus also re-reads). */ +const BILLING_POLL_MS = 4_000 + +/** + * Main's Orca Cloud availability for the project (needs-sign-in, needs-capability, offered), read + * the way the composer reads it and re-read while the page waits, so a sign-in in the browser (or + * the dev sign-in) moves the page on. Starts from the composer's answer at Start. + */ +function useLiveAvailability( + repoId: string, + initial: OrcaCloudAvailability, + enabled: boolean +): OrcaCloudAvailability { + const [availability, setAvailability] = useState(initial) + useEffect(() => { + if (!enabled) { + return + } + let cancelled = false + const read = (): void => { + void Promise.resolve() + .then(() => window.api.ephemeralVm.listRecipes({ repoId })) + .then((result) => { + if (!cancelled && result.orcaCloud) { + setAvailability(result.orcaCloud) + } + }) + .catch(() => undefined) + } + read() + // Paused while the window is hidden; returning from the browser re-reads at once. + const stop = installWindowVisibilityInterval({ run: read, intervalMs: BILLING_POLL_MS }) + window.addEventListener('focus', read) + return () => { + cancelled = true + stop() + window.removeEventListener('focus', read) + } + }, [enabled, repoId]) + return availability +} + +export type CloudSetupFlow = CloudSetupPageModel & { + /** True from the click until the browser opens or the trial answers. */ + busy: boolean + /** The browser trip is open: the current step reads "Waiting for your browser". */ + inBrowser: boolean + error: ReturnType + canManageBilling: boolean + teamAction: React.ReactNode | null + continueInBrowser: () => void + startTrial: () => void + fixBilling: () => void + installGitHub: () => void + skipAgent: () => void + checkAgain: () => void + copyLink: (() => void) | null + reopenBrowser: () => void +} + +export function useCloudSetupFlow( + request: CloudSetupPageRequest, + /** Fixtures pin the account; the app reads billing. */ + accessOverride?: OrcaCloudRunTargetAccess +): CloudSetupFlow { + const fetched = useOrcaCloudRunTargetAccess(!accessOverride) + const access = accessOverride ?? fetched + const availability = useLiveAvailability(request.repoId, request.availability, !accessOverride) + const [sessionId, setSessionId] = useState(null) + // The step that was current when the browser opened. A setup session covers every step it was + // opened for, so it waits on all of them; a single hop (GitHub install, billing) only on its own. + const [browserStep, setBrowserStep] = useState(null) + const [busy, setBusy] = useState(false) + const [agentSkipped, setAgentSkipped] = useState(() => isCloudSetupAgentSkipped(request.agent)) + const githubOverride = useMemo( + () => (request.cloudOnlyRepo ? { id: 'github', state: 'done' } : null), + [request.cloudOnlyRepo] + ) + const { + steps: rowSteps, + session, + openInstall + } = useCloudStartSteps({ + availability, + access, + repoId: request.repoId, + agent: request.agent, + cloudSelected: true, + setupSessionId: sessionId, + githubOverride + }) + const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session) + const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null }) + const error = useMemo(() => { + const parsed = parseCloudSetupError(session?.error) + return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed + }, [session?.error, session?.teamName]) + + // Rows derived from billing tick on their own: re-read while a step is waiting elsewhere. + const waiting = model.action !== 'done' && model.action !== 'agent' + useEffect(() => { + if (!waiting || accessOverride) { + return + } + return installWindowVisibilityInterval({ + run: () => void prefetchOrcaCloudBilling(true), + intervalMs: BILLING_POLL_MS + }) + }, [accessOverride, waiting]) + + useEffect(() => { + if (sessionId) { + reportCloudSetupProgress(sessionId, steps, error?.kind ?? null, { afterTrial: false }) + } + }, [error?.kind, sessionId, steps]) + + const stepsRef = useRef(steps) + useEffect(() => { + stepsRef.current = steps + }, [steps]) + + const markInBrowser = useCallback( + () => setBrowserStep(cloudSetupPageModel(stepsRef.current).current?.id ?? null), + [] + ) + + const fallback = useCallback( + () => setupActionFor(stepsRef.current, access, availability)?.(), + [access, availability] + ) + + // One browser trip for everything still open from here (sign-in, team, trial or Checkout, GitHub). + const continueInBrowser = useCallback(() => { + const needs = sessionNeedsFrom(stepsRef.current) + if (needs.length > 0 && needs.every((need) => need === 'github')) { + markInBrowser() + void openInstall() + return + } + const start = getCloudSetupStarter() + if (!start) { + markInBrowser() + fallback() + return + } + setBusy(true) + void start({ repoId: request.repoId, needs }) + .then((opened) => { + markInBrowser() + if (opened) { + setSessionId(opened.sessionId) + } else { + fallback() + } + }) + .catch(() => fallback()) + .finally(() => setBusy(false)) + }, [fallback, markInBrowser, openInstall, request.repoId]) + + const startTrial = useCallback(() => { + setBusy(true) + void claimOrcaCloudTrial() + .then((result) => { + if (result.status !== 'ok') { + // A personal account needs a team first, or the trial is gone: the browser covers it. + continueInBrowser() + } + }) + .finally(() => setBusy(false)) + }, [continueInBrowser]) + + const fixBilling = useCallback(() => { + markInBrowser() + invalidateOrcaCloudBilling({ refetchNow: false }) + fallback() + }, [fallback, markInBrowser]) + + const installGitHub = useCallback(() => { + markInBrowser() + void openInstall() + }, [markInBrowser, openInstall]) + + const skipAgent = useCallback(() => { + rememberCloudSetupAgentSkipped(request.agent) + setAgentSkipped(true) + }, [request.agent]) + + const checkAgain = useCallback(() => void prefetchOrcaCloudBilling(true), []) + + return { + ...model, + busy, + inBrowser: browserStep !== null && (sessionId !== null || model.current?.id === browserStep), + error, + canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, + teamAction: switchTeam?.action ?? null, + continueInBrowser, + startTrial, + fixBilling, + installGitHub, + skipAgent, + checkAgain, + copyLink: + sessionId && canCopyCloudSetupLink(sessionId) + ? () => void copyCloudSetupLink(sessionId) + : null, + reopenBrowser: () => void reopenCloudSetup(sessionId, continueInBrowser) + } +} diff --git a/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx new file mode 100644 index 00000000000..4cefdfa5a07 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx @@ -0,0 +1,58 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { CloudSetupNotice } from '@/lib/ephemeral-vm-environment-check-triage' +import { CloudSetupNoticesView } from './CloudSetupNotices' + +const noop = (): void => {} + +const PUSH: CloudSetupNotice = { + id: 'git.push', + kind: 'push', + check: { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' } +} +const SETUP: CloudSetupNotice = { + id: 'setup.run', + kind: 'setup', + check: { + id: 'setup.run', + category: 'setup', + status: 'warn', + message: 'Setup script is configured but has not run here.', + code: 'setupNotRun' + } +} +const DISK: CloudSetupNotice = { + id: 'disk.free', + kind: 'check', + check: { + id: 'disk.free', + category: 'disk', + status: 'warn', + message: 'Only 3.2 GB free.', + code: 'diskLow', + params: { free: '3.2' } + } +} + +function notices(list: readonly CloudSetupNotice[], installing = false) { + return defineFixture({ + width: 480, + render: () => ( +
+ +
+ ) + }) +} + +/** The push-access case Neil hit: public repo, App installed only on his personal account. */ +export const pushOnly = notices([PUSH]) +export const pushWaitingForGitHub = notices([PUSH], true) +export const setupOnly = notices([SETUP]) +export const allThree = notices([PUSH, SETUP, DISK]) diff --git a/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx b/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx new file mode 100644 index 00000000000..4cf89f612cd --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx @@ -0,0 +1,265 @@ +import React, { useEffect, useId, useRef, useState } from 'react' +import { GitPullRequestArrow, Loader2, Play, TriangleAlert, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useAppStore } from '@/store' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { environmentCheckCopy } from '@/components/worktree-creation/environment-check-copy' +import type { CloudSetupNotice } from '@/lib/ephemeral-vm-environment-check-triage' +import { + dismissCloudSetupNotice, + useCloudSetupNoticesSnapshot, + visibleCloudSetupNotices, + type CloudSetupNoticesRecord +} from '@/lib/orca-cloud/cloud-setup-notices-store' +import { + openOrcaGitHubAppInstall, + recheckCloudPushAccess, + repoOwner, + repoSlug, + runCloudSetupScript +} from '@/lib/orca-cloud/cloud-setup-notice-actions' + +// After Install: GitHub's webhook usually lands within seconds, then the owner may take a while. +const FAST_POLL_MS = 2_000 +const FAST_POLL_WINDOW_MS = 3 * 60_000 +const SLOW_POLL_MS = 10_000 +const GIVE_UP_MS = 30 * 60_000 + +export type CloudSetupNoticeLine = { + text: string + action: { label: string; icon: React.ReactNode; run: () => void; pending?: boolean } | null +} + +export function cloudSetupNoticeLine( + notice: CloudSetupNotice, + record: Pick, + t: Translate, + handlers: { install: () => void; runSetup: () => void; installing: boolean } +): CloudSetupNoticeLine { + switch (notice.kind) { + case 'push': + if (record.repoUrl) { + const owner = repoOwner(record.repoUrl) + return { + text: t( + 'orcaCloud.setupNotices.pushNeedsApp', + 'Orca Cloud can read {{repo}} but can’t push yet. Install the Orca GitHub App on {{owner}} to push.', + { repo: repoSlug(record.repoUrl), owner } + ), + action: { + label: handlers.installing + ? t('orcaCloud.setupNotices.waitingForGitHub', 'Waiting for GitHub…') + : t('orcaCloud.setupNotices.installOn', 'Install on {{owner}}', { owner }), + icon: handlers.installing ? ( + + ) : ( + + ), + run: handlers.install, + pending: handlers.installing + } + } + } + return { + text: t('orcaCloud.setupNotices.pushRefused', 'Orca Cloud can’t push from this workspace.'), + action: null + } + case 'setup': + return { + text: t('orcaCloud.setupNotices.setupNotRun', 'Setup script hasn’t run yet'), + action: { + label: t('orcaCloud.setupNotices.runSetup', 'Run setup script'), + icon: , + run: handlers.runSetup + } + } + case 'check': + return { text: environmentCheckCopy(notice.check, t, true).message, action: null } + } +} + +/** Polls repo access after Install until the push works, GitHub refuses it, or it gives up. */ +function usePushRecheck( + environmentId: string | undefined, + hasPush: boolean +): { + installing: boolean + startInstall: (repoUrl: string) => void +} { + const [installStartedAt, setInstallStartedAt] = useState(null) + const [tick, setTick] = useState(0) + const busy = useRef(false) + + useEffect(() => { + if (!environmentId || !hasPush || installStartedAt === null) { + return + } + const elapsed = Date.now() - installStartedAt + if (elapsed > GIVE_UP_MS) { + setInstallStartedAt(null) + return + } + const timer = setTimeout( + () => { + if (busy.current) { + setTick((n) => n + 1) + return + } + busy.current = true + void recheckCloudPushAccess(environmentId) + .then((result) => { + if (result !== 'waiting') { + setInstallStartedAt(null) + } + }) + .finally(() => { + busy.current = false + setTick((n) => n + 1) + }) + }, + elapsed < FAST_POLL_WINDOW_MS ? FAST_POLL_MS : SLOW_POLL_MS + ) + return () => clearTimeout(timer) + }, [environmentId, hasPush, installStartedAt, tick]) + + // Installed somewhere else (the browser, another device): check again when Orca is focused. + useEffect(() => { + if (!environmentId || !hasPush) { + return + } + const onFocus = (): void => { + if (!busy.current) { + busy.current = true + void recheckCloudPushAccess(environmentId).finally(() => { + busy.current = false + }) + } + } + window.addEventListener('focus', onFocus) + return () => window.removeEventListener('focus', onFocus) + }, [environmentId, hasPush]) + + return { + installing: installStartedAt !== null, + startInstall: (repoUrl) => { + void openOrcaGitHubAppInstall(repoUrl).then((opened) => { + if (opened) { + setInstallStartedAt(Date.now()) + } + }) + } + } +} + +/** + * What the environment check found that didn't need to stop the create: one line per problem, one + * action each, each dismissible. Sits with the workspace's other notices, top right. + */ +export function CloudSetupNotices({ + workspaceId +}: { + workspaceId: string +}): React.JSX.Element | null { + const environmentId = useAppStore( + (state) => state.ephemeralVmRuntimesByWorkspaceId?.[workspaceId]?.runtimeEnvironmentId + ) + const snapshot = useCloudSetupNoticesSnapshot() + const record = environmentId ? snapshot.records[environmentId] : undefined + const notices = visibleCloudSetupNotices(snapshot, environmentId) + const push = usePushRecheck( + environmentId, + notices.some((notice) => notice.kind === 'push') + ) + if (!record || notices.length === 0) { + return null + } + return ( + record.repoUrl && push.startInstall(record.repoUrl)} + onRunSetup={(noticeId) => void runCloudSetupScript(workspaceId, record, noticeId)} + onDismiss={(noticeId) => dismissCloudSetupNotice(record.environmentId, noticeId)} + /> + ) +} + +export function CloudSetupNoticesView({ + record, + notices, + installing, + onInstall, + onRunSetup, + onDismiss +}: { + record: Pick + notices: readonly CloudSetupNotice[] + installing: boolean + onInstall: () => void + onRunSetup: (noticeId: string) => void + onDismiss: (noticeId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const labelId = useId() + return ( +
+

+ {t('orcaCloud.setupNotices.label', 'Workspace setup')} +

+
    + {notices.map((notice) => { + const line = cloudSetupNoticeLine(notice, record, t, { + install: onInstall, + runSetup: () => onRunSetup(notice.id), + installing + }) + return ( +
  • + + {/* The sentence reads first; its one action sits under it so neither gets squeezed. */} +
    +

    {line.text}

    + {line.action ? ( + + ) : null} +
    + +
  • + ) + })} +
+
+ ) +} diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index a94ff5f056f..f2223d64523 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -1,3 +1,4 @@ +import { useReopenRemoteDesktopAfterWake } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen' import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' @@ -21,6 +22,7 @@ import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/c import { CloudArchivedWorkspaceView, type ArchiveLoad } from './CloudArchivedWorkspaceView' import { CloudWakingOverlay } from './CloudWakingOverlay' import { CloudWorkspaceNotice } from './CloudWorkspaceNotice' +import { CloudSetupNotices } from './CloudSetupNotices' import { useConfirmedRestart } from './use-cloud-panel-actions' import { useCloudVersionSkewNotice } from './use-cloud-version-skew-notice' import { CloudWorkspaceOfflineView } from './offline/CloudWorkspaceOfflineView' @@ -222,6 +224,7 @@ function useInertSiblings(cover: React.RefObject, active: bo function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Element | null { const t = useTranslate() const view = useCloudWorkspaceView(workspaceId) + useReopenRemoteDesktopAfterWake(workspaceId, view.state === 'running') const name = useAppStore((state) => findWorktreeById(state, workspaceId)?.displayName ?? null) // Ready means the server answers; the pill stays ("Connecting…") until the pane in front has // re-attached and can take keys. @@ -336,6 +339,10 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme if (layer === null && versionSkewNotice) { notices.push(versionSkewNotice) } + if (layer === null && view.state !== 'sleeping' && view.state !== 'archived') { + // What the environment check found that didn't need to stop the create (env-check-ux). + notices.push() + } if (layer === null && view.oom) { notices.push( + {matchesSettingsSearch(searchQuery, [getExperimentalSearchEntry().pokes]) ? ( + + ) : null} + {wslHostsAvailable() ? ( ) : null} diff --git a/src/renderer/src/components/settings/advanced/experimental-search.ts b/src/renderer/src/components/settings/advanced/experimental-search.ts index d69b5528840..98fe793f764 100644 --- a/src/renderer/src/components/settings/advanced/experimental-search.ts +++ b/src/renderer/src/components/settings/advanced/experimental-search.ts @@ -185,7 +185,40 @@ export const getExperimentalSearchEntry = createLocalizedCatalog( }, newWorktreeCardStyle: getNewWorktreeCardStyleSearchEntry(), ephemeralVms: getEphemeralVmsSearchEntry(), - browserExtensions: getBrowserExtensionsExperimentalSearchEntry() + browserExtensions: getBrowserExtensionsExperimentalSearchEntry(), + pokes: { + title: translate( + 'auto.components.settings.experimental.search.pokes.activityTitle', + 'Pokes and activity' + ), + description: translate( + 'auto.components.settings.experimental.search.pokes.activityDescription', + 'Teammates can poke you and see which days you used Orca Cloud. Amounts stay private.' + ), + keywords: [ + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.0d24759f14', + 'experimental' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.pokes.poke', + 'poke' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.pokes.nudge', + 'nudge' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.pokes.teammate', + 'teammate' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.pokes.activity', + 'activity' + ) + ], + targetSectionId: 'experimental-pokes' + } }) satisfies Record ) diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts index c6d0e7f9167..ba14d165b55 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts @@ -1,4 +1,5 @@ import { useAppStore } from '@/store' +import { noteRemoteDesktopBeforeSleep } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen' import { captureWorkspaceSelection, restoreWorkspaceSelection, @@ -55,6 +56,10 @@ export function followWorkspaceSleep( const state = useAppStore.getState() const wasActive = state.activeWorktreeId === worktreeId const selectionBeforeSleep = wasActive ? captureWorkspaceSelection(state) : null + if (!options.keepBrowserTabs) { + // Before the selection clears: whether the desktop tab was in front decides how it comes back. + noteRemoteDesktopBeforeSleep(worktreeId) + } // Why first: clearing the active workspace unmounts its panes, whose exits must not stamp activity. markWorktreeSleepIntent(worktreeId) if (wasActive) { diff --git a/src/renderer/src/components/tab-bar/BrowserTab.tsx b/src/renderer/src/components/tab-bar/BrowserTab.tsx index 382282ae121..ea43c0abb82 100644 --- a/src/renderer/src/components/tab-bar/BrowserTab.tsx +++ b/src/renderer/src/components/tab-bar/BrowserTab.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react' import { useSortable } from '@dnd-kit/sortable' -import { X, Pin, PinOff, Volume2, VolumeX } from 'lucide-react' +import { X, Pin, PinOff, Volume2, VolumeX, Monitor } from 'lucide-react' import { ContextMenu, ContextMenuContent, @@ -13,6 +13,7 @@ import '../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { redactKagiSessionToken } from '../../../../shared/browser-url' import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' +import { isCloudRemoteDesktopUrl } from '../../../../shared/hosted-sandbox/cloud-remote-desktop' import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus' import { getLiveBrowserUrl } from '../browser-pane/describe-page/live-browser-url-registry' import type { TabDragItemData } from '../tab-group/useTabDragSplit' @@ -55,6 +56,10 @@ export function formatBrowserTabUrlLabel(url: string, t: Translate = translate): } export function getBrowserTabLabel(tab: BrowserWorkspace, t?: Translate): string { + // A remote desktop tab is named for what it is, not for its localhost forward. + if (isCloudRemoteDesktopUrl(tab.url)) { + return (t ?? translate)('components.cloudRemoteDesktop.tabTitle', 'Remote desktop') + } if ( !tab.title || tab.title === tab.url || @@ -122,6 +127,7 @@ export default function BrowserTab({ // invalid URL — leave disabled } const tabLabel = getBrowserTabLabel(tab, t) + const isRemoteDesktop = isCloudRemoteDesktopUrl(tab.url) const audible = useAppStore((s) => (s.browserPagesByWorkspace[tab.id] ?? []).some((page) => s.browserAudiblePageIds[page.id]) ) @@ -206,6 +212,8 @@ export default function BrowserTab({ /> + ) : isRemoteDesktop ? ( + ) : ( } + icon={ + isRemoteDesktop ? ( + + ) : ( + + ) + } programName={ agentDriving ? agentDrivingLabel diff --git a/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx b/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx index 31305c1f9ab..586400c1e40 100644 --- a/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx +++ b/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx @@ -8,6 +8,7 @@ import { Globe, Loader2, MessageSquare, + Monitor, Search, Smartphone, TerminalSquare @@ -279,6 +280,8 @@ function getActionPresentation( const icon = option.option.kind === 'new-browser' ? (
diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx index 8026c0a8305..06a3c9523fe 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx @@ -10,7 +10,6 @@ import { FAILED_LOG, LOG, frame, - seedCloudAgentAccounts, LOG_LINES, NOW, seedFixtureRepo, @@ -248,52 +247,43 @@ export const checksSkipped = frame( }) ) -const cloudChecks = frame( - entry( - { environmentCheck: { status: 'failed', checks: FAILED_CHECKS, ...CHECKS_FAILED_AT } }, - CLOUD_RECIPE - ) -) -// Claude isn't set up through the Orca account: the sign-in warning says where to set it up. -export const cloudChecksFailed = defineFixture({ - ...cloudChecks, - setup: () => { - cloudChecks.setup?.() - seedCloudAgentAccounts('none') +// Orca Cloud stops only on a fatal check; orcad never answered here, so the doctor couldn't run. +const CLOUD_FATAL_CHECKS: NonNullable['checks'] = [ + { + id: 'environment.doctor', + category: 'workspace', + status: 'fail', + message: 'The environment checks could not finish: Runtime environment is unreachable.' } -}) -// Claude is covered by the Orca account: the sandbox's own sign-in probe isn't shown at all. -export const cloudChecksAgentCovered = defineFixture({ - ...cloudChecks, - setup: () => { - cloudChecks.setup?.() - seedCloudAgentAccounts('active') - } -}) +] +// Rendered relative to the real clock: the note counts down from it. +const sleepsIn = (ms: number): number => Date.now() + ms -// One failure plus a warning: the title counts failures only, in the singular. -const cloudChecksOne = frame( - entry( +function cloudFatal( + extra: Partial> +): PendingWorktreeCreation { + return entry( { environmentCheck: { status: 'failed', - checks: FAILED_CHECKS?.filter((check) => check.id !== 'git.push'), - ...CHECKS_FAILED_AT + checks: CLOUD_FATAL_CHECKS, + ...CHECKS_FAILED_AT, + sleepsAt: sleepsIn(5 * 60_000), + ...extra } }, CLOUD_RECIPE ) -) +} -export const cloudChecksFailedOne = defineFixture({ - ...cloudChecksOne, - setup: () => { - cloudChecksOne.setup?.() - seedCloudAgentAccounts('none') - } -}) +// Unusable sandbox, still awake: Start again leads, and the note says when it sleeps. +export const cloudChecksFailed = frame(cloudFatal({})) +// Five unused minutes later: asleep, so checking again can't help; only Start again or Delete. +export const cloudChecksAsleep = frame(cloudFatal({ sandbox: 'asleep' })) +// It couldn't sleep, so it was deleted: nothing is kept, Start again retries on a new one. +export const cloudChecksDeleted = frame(cloudFatal({ sandbox: 'deleted' })) -// A narrow sheet: the pills keep one column and Delete sandbox wraps under the recovery actions. +// A narrow sheet: Delete sandbox wraps under the recovery actions. export const cloudChecksFailedNarrow = defineFixture({ ...cloudChecksFailed, width: 420 @@ -405,4 +395,3 @@ export const secretsRefused = secretsFrame( export const secretsSkipped = secretsFrame(secretsRow(secretsData('admin'), { phase: 'skipped' })) // The Agents row (spec §5b), as VmBuildSheet:agents*. -export * from './vm-build-sheet-agents-fixtures' diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 4cea68efd6d..e30da2a0085 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -7,19 +7,20 @@ import { useOrcaBillingStatus } from '@/components/billing/use-orca-billing-stat import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { resolveVmEnvironmentCheckDecision } from '@/lib/ephemeral-vm-environment-check-decision' +import { + isAwaitingVmEnvironmentCheckDecision, + resolveVmEnvironmentCheckDecision +} from '@/lib/ephemeral-vm-environment-check-decision' import { openPlansPage } from '@/components/billing/plans/plans-page-store' import { ORCA_BILLING_OVERAGE_SECTION_ID } from '@/components/new-workspace/orca-cloud-run-target-access' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' import { toast } from 'sonner' -import { OrcaCloudHoursChip } from '@/components/new-workspace/run-on/OrcaCloudHoursChip' import type { EnvironmentSetupFailureContext } from '../../../../shared/environment-setup-agent-prompt' import { formatEnvironmentDoctorChecks } from '../../../../shared/environment-doctor-types' import { VmBuildStepRow } from './VmBuildStepRow' import { firstBuildLogErrorLine, VmBuildLog } from './VmBuildLog' import { VmBuildFailureCard } from './VmBuildFailureCard' import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow' -import { VmBuildCloudAgentsRow } from './cloud-agents-row/VmBuildCloudAgentsRow' import { VmBuildSecretsRow } from '../cloud-secrets-ask/VmBuildSecretsRow' import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt' import { @@ -99,7 +100,6 @@ export function VmBuildSheet({ onReturnToComposer, onEditRecipe, agentSignInRow, - cloudAgentsRow, secretsRow, stepTimings }: { @@ -117,8 +117,6 @@ export function VmBuildSheet({ onEditRecipe: () => void /** Fixtures only: a fixed sign-in row in place of the live one. */ agentSignInRow?: React.ReactNode - /** Fixtures only: a fixed cloud Agents row (null for none) in place of the live one. */ - cloudAgentsRow?: React.ReactNode /** Fixtures only: a fixed Secrets row (null for none) in place of the live one. */ secretsRow?: React.ReactNode /** Fixtures only: measured step timings in place of the control plane's. */ @@ -204,7 +202,9 @@ export function VmBuildSheet({ // Failed checks leave a running sandbox that needs a decision, not a broken start. className={cn( 'size-4 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:zoom-in-90 motion-safe:duration-200', - failure?.kind === 'checks' ? 'text-status-warning-text' : 'text-destructive' + failure?.kind === 'checks' && !cloud + ? 'text-status-warning-text' + : 'text-destructive' )} /> )} @@ -222,8 +222,6 @@ export function VmBuildSheet({ {gated || cloud ? null : ( {elapsedLabel} )} - {/* O4: which sandbox hours this start spends, while it starts. */} -
{building ? ( - - - {agents.map((agent) => { - const usable = - status !== null && - status.credentials.providerEnabled[agent] && - isUsableAgentCredential(status.credentials[agent].state) - const keyKind = status?.sources.coveredByKey[agent] ? (keyKinds[agent] ?? 'team') : null - const disabled = view === null || shared - return ( - - - {t('vmBuildAgents.menu.inThisWorkspace', '{{agent}} in this workspace', { - agent: agentName(agent, t) - })} - - { - if (value === 'sign-in' || value === 'key') { - onChoose(agent, value) - } - }} - > - - {t('vmBuildAgents.menu.yourAccount', 'Your account')} - - {keyKind ? ( - - {keyOptionLabel(keyKind, t)} - - ) : null} - - - - ) - })} - {agents.length > 0 && note ? ( - <> -

{note}

- - - ) : null} - {offer ? ( - - {t('vmBuildAgents.menu.useKey', 'Use an API key instead')} - - ) : null} - - {t('vmBuildAgents.menu.manage', 'Manage agent accounts…')} - -
- - ) -} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx deleted file mode 100644 index b61d73246f0..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx +++ /dev/null @@ -1,202 +0,0 @@ -// Live Agents row for an Orca Cloud build. Reads the Orca account once (shared store with S0 and the -// composer), never the sandbox; runs S0's setup inline when nothing is set up (R2), and writes the -// per-workspace Source from the ⋯ menu (S1-b). -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { useTranslate } from '@/i18n/use-translate' -import { - reloadOrcaCloudAgentAccounts, - runOrcaCloudAgentSetups, - stopOrcaCloudAgentSetups, - useOrcaCloudAgentAccounts -} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' -import { - buildAgentsRow, - buildAgentsRowDensity, - buildAgentsToSetUp, - type BuildAgentsRowDensity -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import { - startVmBuildAgentSignIn, - useVmBuildAgentSignIn -} from '@/lib/agent-sign-in/vm-build-agent-sign-in' -import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' -import type { - AgentSource, - OrcaCloudAccountAgent -} from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { useCloudAgentSetup } from '../../cloud-agent-setup/use-cloud-agent-setup' -import { cloudSecretRepoKey } from '../../settings/cloud-secrets/cloud-secret-repos' -import { VmBuildAgentSignInRow } from '../VmBuildAgentSignInRow' -import { VmBuildCloudAgentsMenu, type WorkspaceSourcesLoad } from './VmBuildCloudAgentsMenu' -import { VmBuildCloudAgentsRowView, type DesktopKeySave } from './VmBuildCloudAgentsRowView' - -function openSettings(pane: 'accounts' | 'cloud-secrets', sectionId?: string): void { - const store = useAppStore.getState() - store.openSettingsTarget({ pane, repoId: null, ...(sectionId ? { sectionId } : {}) }) - store.openSettingsPage() -} - -export function VmBuildCloudAgentsRow({ - creationId, - entry -}: { - creationId: string - entry: PendingWorktreeCreation -}): React.JSX.Element | null { - const t = useTranslate() - const accounts = useOrcaCloudAgentAccounts() - const environmentId = entry.vmEnvironmentId ?? null - const runtimeEnvironmentId = - environmentId ?? entry.request.ephemeralVmRuntimeEnvironmentId ?? null - const repoKey = useAppStore((s) => { - const repo = s.repos.find((candidate) => candidate.id === entry.request.repoId) - return repo ? cloudSecretRepoKey(repo) : null - }) - const { model: keysModel, saveDesktopKey } = useCloudAgentSetup({ - repo: repoKey, - runtimeEnvironmentId: environmentId - }) - const desktopKeys = keysModel.status === 'ready' ? keysModel.desktopKeys : [] - const model = buildAgentsRow({ accounts, desktopKeys }) - // Decided on the first render and never re-derived (redesign §5, AC-3). - const [density] = useState(() => buildAgentsRowDensity(model)) - - const [desktopKeySave, setDesktopKeySave] = useState({ kind: 'idle' }) - const saveKey = useCallback(() => { - if (model.kind !== 'desktopKey') { - return - } - setDesktopKeySave({ kind: 'saving' }) - void saveDesktopKey(model.key).then((error) => { - setDesktopKeySave(error ? { kind: 'failed', error } : { kind: 'idle' }) - if (!error) { - // The saved key now covers the agent: the row becomes the ready line. - void reloadOrcaCloudAgentAccounts() - } - }) - }, [model, saveDesktopKey]) - - // §5c: a per-workspace sign-in. Pressed before the sandbox answers, it waits for it (R3); each - // press is its own request, so a cancelled one never starts later. - const [signInHere, setSignInHere] = useState<{ - agent: OrcaCloudAccountAgent - request: number - } | null>(null) - const startedRequest = useRef(0) - const nextRequest = useRef(0) - const hostLabel = useAppStore( - (s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name - ) - useEffect(() => { - if (!signInHere || !environmentId || startedRequest.current === signInHere.request) { - return - } - startedRequest.current = signInHere.request - void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, [ - signInHere.agent - ]) - }, [signInHere, environmentId, creationId, hostLabel]) - const queued = signInHere !== null && !environmentId - const signInRun = useVmBuildAgentSignIn(creationId, environmentId ?? '') - - const [sources, setSources] = useState({ kind: 'loading' }) - const readSources = useCallback(() => { - const api = window.api.orcaCloudAgents - if (!api || !runtimeEnvironmentId) { - setSources({ kind: 'none' }) - return - } - void api - .workspaceSources({ runtimeEnvironmentId }) - .then((result) => - setSources( - result.ok - ? { kind: 'ready', view: result.value } - : { kind: result.error === 'not_found' ? 'none' : 'failed' } - ) - ) - .catch(() => setSources({ kind: 'failed' })) - }, [runtimeEnvironmentId]) - const choose = useCallback( - (agent: OrcaCloudAccountAgent, source: Exclude) => { - const api = window.api.orcaCloudAgents - if (!api || !runtimeEnvironmentId) { - return - } - void api - .setWorkspaceSource({ agent, source, runtimeEnvironmentId }) - .then((result) => { - if (result.ok) { - // This workspace only; the account-wide defaults the store holds are unchanged. - setSources({ kind: 'ready', view: result.value }) - } else { - toast.error( - t('vmBuildAgents.menu.saveFailed', 'Couldn’t change it. Nothing was changed.') - ) - } - }) - .catch(() => undefined) - }, - [runtimeEnvironmentId, t] - ) - - if (model.kind === 'hidden' || entry.status === 'error') { - return null - } - const api = window.api.orcaCloudAgents - const status = accounts.load.kind === 'ready' ? accounts.load.status : null - const menu = - model.kind === 'loading' || model.kind === 'setup' ? undefined : ( - openSettings('accounts', 'orca-cloud')} - onUseKey={() => openSettings('cloud-secrets')} - /> - ) - return ( - <> - runOrcaCloudAgentSetups(buildAgentsToSetUp(model)), - cancel: (agent) => stopOrcaCloudAgentSetups(agent), - reopen: (agent) => void api?.reopen({ agent }), - copyCodeAndOpen: (agent, code) => { - void window.api.ui - .writeClipboardText(code) - .then(() => toast.success(t('vmBuildAgents.codeCopied', 'Code copied'))) - .catch(() => undefined) - void api?.reopen({ agent }) - }, - dismissFailure: (agent) => { - stopOrcaCloudAgentSetups() - void api?.acknowledge({ agent }) - }, - retryLoad: () => void reloadOrcaCloudAgentAccounts(), - manage: () => openSettings('accounts', 'orca-cloud'), - saveDesktopKey: saveKey, - signInHere: (agent) => { - nextRequest.current += 1 - setSignInHere({ agent, request: nextRequest.current }) - }, - cancelSignInHere: () => setSignInHere(null) - }} - /> - {/* §5c only: the per-workspace sign-in's browser and code steps, once it has started. */} - {model.kind === 'killSwitch' && environmentId && signInRun ? ( - - ) : null} - - ) -} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx deleted file mode 100644 index 82f2d478780..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx +++ /dev/null @@ -1,375 +0,0 @@ -// The cloud build sheet's Agents row (spec §5b S1; redesign §5). Its height is decided once, at -// mount: 32 px when every agent was ready then, 48 px otherwise. Every later state renders inside -// that height, so the checklist never moves (AC-3: measured layout shift 0). -import React from 'react' -import { CircleCheck, CircleDashed, Info, KeyRound, Loader2, TriangleAlert, X } from 'lucide-react' -import { useTranslate, type Translate } from '@/i18n/use-translate' -import { Button } from '@/components/ui/button' -import { Skeleton } from '@/components/ui/skeleton' -import { cn } from '@/lib/utils' -import type { - BuildAgentsRowDensity, - BuildAgentsRowModel -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import type { OrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' -import { buildAgentsRowText, deviceHost, readyLine } from './build-agents-row-copy' - -export type DesktopKeySave = - | { kind: 'idle' } - | { kind: 'saving' } - | { kind: 'failed'; error: CloudSecretsErrorCode } - -export type VmBuildCloudAgentsRowActions = { - setUp: () => void - cancel: (agent: OrcaCloudAccountAgent) => void - reopen: (agent: OrcaCloudAccountAgent) => void - copyCodeAndOpen: (agent: OrcaCloudAccountAgent, code: string) => void - dismissFailure: (agent: OrcaCloudAccountAgent) => void - retryLoad: () => void - manage: () => void - saveDesktopKey: () => void - /** §5c only: sign this one workspace in (queued until the sandbox answers). */ - signInHere: (agent: OrcaCloudAccountAgent) => void - cancelSignInHere: () => void -} - -const ICON = 'size-4 shrink-0' -const IDLE_SAVE: DesktopKeySave = { kind: 'idle' } - -function StatusIcon({ model }: { model: BuildAgentsRowModel }): React.JSX.Element { - switch (model.kind) { - case 'ready': - return - case 'setup': - case 'loading': - return - case 'failed': - case 'expired': - case 'error': - return - case 'killSwitch': - return - case 'desktopKey': - return - case 'offer': - case 'hidden': - return - } -} - -function Trailing({ - model, - actions, - desktopKeySave, - queued, - t -}: { - model: BuildAgentsRowModel - actions: VmBuildCloudAgentsRowActions - desktopKeySave: DesktopKeySave - queued: boolean - t: Translate -}): React.ReactNode { - const cancel = (agent: OrcaCloudAccountAgent): React.JSX.Element => ( - - ) - switch (model.kind) { - case 'ready': - return model.expiring ? ( - - ) : null - case 'offer': - return ( - - ) - case 'setup': - switch (model.setup.phase) { - case 'browser': - return ( - <> - {model.setup.canReopen ? ( - - ) : null} - {cancel(model.agent)} - - ) - case 'device': { - const code = model.setup.userCode - return ( - <> - - {cancel(model.agent)} - - ) - } - case 'paste': - return ( - <> - - {cancel(model.agent)} - - ) - case 'preparing': - return cancel(model.agent) - case 'saving': - return null - } - return null - case 'failed': - return ( - <> - - - - ) - case 'expired': - return ( - - ) - case 'killSwitch': - return queued ? ( - - ) : ( - - ) - case 'desktopKey': - return desktopKeySave.kind === 'failed' ? ( - - ) : ( - - ) - case 'error': - return ( - - ) - case 'loading': - case 'hidden': - return null - } -} - -function Lines({ - model, - density, - desktopKeySave, - queued, - t -}: { - model: Exclude - density: BuildAgentsRowDensity - desktopKeySave: DesktopKeySave - queued: boolean - t: Translate -}): React.JSX.Element { - const line = density === 'line' - if (model.kind === 'loading') { - return ( - <> - {t('vmBuildAgents.checking', 'Checking agent sign-in')} - - {line ? null : } - - ) - } - if (model.kind === 'ready') { - const text = readyLine(model, t) - return ( - <> - - {text} - - {line ? null : ( - - {t('vmBuildAgents.readyDetail', 'Every cloud workspace uses it. Nothing to do here.')} - - )} - - ) - } - const text = buildAgentsRowText(model, t) - const detail = - model.kind === 'desktopKey' && desktopKeySave.kind === 'failed' - ? t('vmBuildAgents.keyFailed', 'Couldn’t save {{name}}. Nothing was changed.', { - name: model.key.envName - }) - : model.kind === 'killSwitch' && queued - ? t('vmBuildAgents.queued', 'Opens when the sandbox is ready. Keep Orca open until then.') - : text.detail - const device = model.kind === 'setup' && model.setup.phase === 'device' ? model.setup : null - return ( - <> - - {device ? ( - <> - {t('vmBuildAgents.deviceEnter', 'Enter')}{' '} - - {device.userCode} - {' '} - {t('vmBuildAgents.deviceOn', 'on {{host}}', { - host: deviceHost(device.verificationUrl) - })} - - ) : ( - text.title - )} - {text.tag ? · {text.tag} : null} - - {line ? ( - {detail} - ) : ( - - {detail} - - )} - - ) -} - -export function VmBuildCloudAgentsRowView({ - model, - density, - actions, - menu, - desktopKeySave = IDLE_SAVE, - queued = false -}: { - model: BuildAgentsRowModel - density: BuildAgentsRowDensity - actions: VmBuildCloudAgentsRowActions - /** The ⋯ menu (S1-b); absent while loading or when it has nothing to offer. */ - menu?: React.ReactNode - desktopKeySave?: DesktopKeySave - queued?: boolean -}): React.JSX.Element | null { - const t = useTranslate() - if (model.kind === 'hidden') { - return null - } - // Each state mounts fresh nodes: a reused button or line that changed width would count as a - // layout shift even though the row itself never moves. - const stateKey = [ - model.kind, - model.kind === 'setup' ? model.setup.phase : '', - desktopKeySave.kind, - queued ? 'queued' : '' - ].join(':') - return ( - // A hairline: the agent row is not a build step. -
  • -
    - -
    - -
    - {/* Fixed slots: the actions (184 px, redesign §5), then the ⋯ menu, which never moves. */} -
    - - {model.kind === 'ready' ? ( - - ) : null} -
    -
    {menu}
    -
    -
  • - ) -} diff --git a/src/renderer/src/components/worktree-creation/environment-check-copy.ts b/src/renderer/src/components/worktree-creation/environment-check-copy.ts index 0d0d6e43b7b..09858149bcb 100644 --- a/src/renderer/src/components/worktree-creation/environment-check-copy.ts +++ b/src/renderer/src/components/worktree-creation/environment-check-copy.ts @@ -8,6 +8,13 @@ export function environmentCheckCopy( cloud = false ): { message: string; remediation: string | null } { const p = check.params ?? {} + if (cloud) { + const fatal = cloudFatalCheckMessage(check, t) + if (fatal) { + // The card's body carries the one way forward (Start again), so no per-row fix. + return { message: fatal, remediation: null } + } + } switch (check.code) { case 'gitMissing': return { @@ -78,6 +85,14 @@ export function environmentCheckCopy( } } break + case 'setupNotRun': + return { + message: t( + 'auto.components.worktree.creation.environmentCheckCopy.setupNotRun', + 'Setup script hasn’t run yet.' + ), + remediation: null + } case 'diskVeryLow': case 'diskLow': if (p.free) { @@ -107,6 +122,37 @@ export function environmentCheckCopy( return { message: check.message, remediation: check.remediation ?? null } } +/** Orca Cloud's create-stopping checks in plain words; null for every other check. */ +function cloudFatalCheckMessage(check: EnvironmentDoctorCheck, t: Translate): string | null { + if (check.status !== 'fail') { + return null + } + switch (check.id) { + case 'environment.doctor': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudUnreachable', + 'Orca couldn’t reach the sandbox.' + ) + case 'workspace.path': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudRepoMissing', + 'The repository isn’t in the sandbox.' + ) + case 'git.repo': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudRepoUnreadable', + 'Git can’t read the repository in the sandbox.' + ) + case 'tool.git': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudGitMissing', + 'git isn’t installed in the sandbox.' + ) + default: + return null + } +} + export function environmentCheckBadge( status: EnvironmentDoctorCheck['status'], t: Translate diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 91c7528e9d7..1813c60baa1 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -29,6 +29,11 @@ function phaseLabel(phase: string, t: Translate): string | null { 'auto.components.worktree.creation.orcaCloudBuildLog.cloning', 'Cloning the repository…' ) + case 'updating': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.updating', + 'Updating the repository…' + ) case 'connecting': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.connecting', diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index 023ff4fa8af..5c2337e4097 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -56,48 +56,43 @@ export function vmBuildFailureCopy( ): { title: string; body: string | null } { switch (failure.kind) { case 'checks': { + if (cloud) { + // Orca Cloud stops only when the sandbox can't hold the workspace at all; warnings open it. + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableTitle', + 'This sandbox can’t open your workspace' + ), + body: + failure.sandbox === 'deleted' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableDeletedBody', + 'The sandbox was deleted. Start again to try a new one.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableBody', + 'Start again on a new sandbox, or delete this one.' + ) + } + } // Warnings ride along in the list but don't count as failures in the title. const count = failure.problems.filter((check) => check.status === 'fail').length return { title: count === 0 - ? cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleCloud', - 'The sandbox is up, but some environment checks need attention' - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleVm', - 'The VM is up, but some environment checks need attention' - ) - : cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleCloud', - 'The sandbox is up, but {{count}} environment checks failed', - { - count, - defaultValue_one: 'The sandbox is up, but {{count}} environment check failed' - } - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleVm', - 'The VM is up, but {{count}} environment checks failed', - { - count, - defaultValue_one: 'The VM is up, but {{count}} environment check failed' - } - ), - body: cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksBodyCloud2', - 'Open it anyway and fix them inside the workspace, or run the checks again after changing your project.', - { - count: failure.problems.length, - defaultValue_one: - 'Open it anyway and fix it inside the workspace, or run the checks again after changing your project.' - } - ) - : null + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleVm', + 'The VM is up, but some environment checks need attention' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleVm', + 'The VM is up, but {{count}} environment checks failed', + { + count, + defaultValue_one: 'The VM is up, but {{count}} environment check failed' + } + ), + body: null } } case 'plan': diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index 11111abe37b..3e1102ec397 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -22,7 +22,13 @@ export type VmBuildAccountFailureKind = | 'snapshotMissing' export type VmBuildFailure = - | { kind: 'checks'; problems: readonly EnvironmentDoctorCheck[] } + | { + kind: 'checks' + problems: readonly EnvironmentDoctorCheck[] + /** Orca Cloud: when the unused sandbox sleeps, and what became of it after. */ + sleepsAt?: number + sandbox?: 'sleeping' | 'asleep' | 'deleted' + } | { kind: VmBuildAccountFailureKind } /** The VM did not come up; the raw error is shown only for user-authored recipes. */ | { kind: 'provision'; error: string } @@ -67,7 +73,12 @@ export function classifyVmBuildFailure(args: { const { entry, error, cloud } = args const check = entry.environmentCheck if (check?.status === 'failed') { - return { kind: 'checks', problems: (check.checks ?? []).filter((c) => c.status !== 'pass') } + return { + kind: 'checks', + problems: (check.checks ?? []).filter((c) => c.status !== 'pass'), + ...(check.sleepsAt !== undefined ? { sleepsAt: check.sleepsAt } : {}), + ...(check.sandbox ? { sandbox: check.sandbox } : {}) + } } if (error === null) { return null diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx deleted file mode 100644 index 9bf1be6578c..00000000000 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx +++ /dev/null @@ -1,238 +0,0 @@ -// The cloud build sheet's Agents row (spec §5b; redesign §5), every state, inside the real sheet. -// Re-exported by VmBuildSheet.fixture.tsx as VmBuildSheet:agents*. -import React, { useEffect, useState } from 'react' -import { defineFixture } from '../../component-fixtures/component-fixture' -import { - buildAgentsRowDensity, - type BuildAgentsRowDensity, - type BuildAgentsRowModel -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { - CLOUD_LOG, - CLOUD_RECIPE, - entry, - NOW, - seedFixtureRepo, - sheet -} from './vm-build-sheet-fixture-support' -import { - VmBuildCloudAgentsRowView, - type DesktopKeySave, - type VmBuildCloudAgentsRowActions -} from './cloud-agents-row/VmBuildCloudAgentsRowView' -import { VmBuildCloudAgentsMenu } from './cloud-agents-row/VmBuildCloudAgentsMenu' - -const noop = (): void => {} -const ACTIONS: VmBuildCloudAgentsRowActions = { - setUp: noop, - cancel: noop, - reopen: noop, - copyCodeAndOpen: noop, - dismissFailure: noop, - retryLoad: noop, - manage: noop, - saveDesktopKey: noop, - signInHere: noop, - cancelSignInHere: noop -} - -const CLOUD = entry({ provisioningLog: CLOUD_LOG }, CLOUD_RECIPE) - -const STATUS: OrcaCloudAgentsStatus = { - credentials: { - claude: { state: 'active', label: 'nw@stably.ai' }, - codex: { state: 'active', label: 'nw@stably.ai' }, - providerEnabled: { claude: true, codex: true } - }, - sources: { - defaults: { claude: 'sign-in', codex: 'key' }, - effective: { claude: { source: 'sign-in' }, codex: { source: 'key' } }, - coveredByKey: { claude: false, codex: true } - } -} - -function menu(offer: boolean): React.ReactNode { - return ( - - ) -} - -function agents( - model: BuildAgentsRowModel, - options: { - density?: BuildAgentsRowDensity - desktopKeySave?: DesktopKeySave - queued?: boolean - interact?: (frame: HTMLElement) => Promise - } = {} -) { - const hasMenu = model.kind !== 'loading' && model.kind !== 'setup' - return defineFixture({ - width: 760, - setup: () => seedFixtureRepo(), - interact: options.interact, - render: () => - sheet(CLOUD, null, NOW, undefined, { - cloudAgentsRow: ( - - ) - }) - }) -} - -const ACCOUNT_BOTH: BuildAgentsRowModel = { - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'account' } - ], - label: 'nw@stably.ai', - expiring: null -} - -export const agentsAccount = agents(ACCOUNT_BOTH) -export const agentsAccountAndTeamKey = agents({ - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'team' } - ], - label: null, - expiring: null -}) -export const agentsTeamKeyOnly = agents({ - kind: 'ready', - covered: [{ agent: 'codex', via: 'team' }], - label: null, - expiring: null -}) -export const agentsNotSetUp = agents({ kind: 'offer', agents: ['claude', 'codex'] }) -export const agentsDesktopKeyOnly = agents({ - kind: 'desktopKey', - key: { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } -}) -export const agentsDesktopKeyFailed = agents( - { - kind: 'desktopKey', - key: { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } - }, - { desktopKeySave: { kind: 'failed', error: 'unavailable' } } -) -export const agentsKillSwitch = agents({ kind: 'killSwitch', agent: 'claude', reason: 'paused' }) -/** Flag off on this server: same sign-in-here action, never worded as paused. */ -export const agentsNotOffered = agents({ - kind: 'killSwitch', - agent: 'claude', - reason: 'notOffered' -}) -export const agentsKillSwitchQueued = agents( - { kind: 'killSwitch', agent: 'claude', reason: 'paused' }, - { queued: true } -) -export const agentsLoading = agents({ kind: 'loading' }) -export const agentsSettingUpClaude = agents({ - kind: 'setup', - agent: 'claude', - setup: { phase: 'browser', startedAt: NOW - 8_000, canReopen: true }, - step: 1, - of: 2 -}) -export const agentsSettingUpCodexDevice = agents({ - kind: 'setup', - agent: 'codex', - setup: { - phase: 'device', - startedAt: NOW - 12_000, - userCode: 'K7QF-2M9D', - verificationUrl: 'https://auth.openai.com/codex/device', - expiresAt: NOW + 600_000 - }, - step: 2, - of: 2 -}) -export const agentsSetupFailed = agents({ kind: 'failed', agent: 'claude', error: 'denied' }) -export const agentsExpired = agents({ kind: 'expired', agent: 'claude' }) -/** R1c: mounted ready, then within its renewal window: stays a line with a quiet Renew. */ -export const agentsExpiringLine = agents({ ...ACCOUNT_BOTH, expiring: 'claude' }) -/** R1b: mounted as a line, then expired: stays a line. */ -export const agentsExpiredLine = agents({ kind: 'expired', agent: 'claude' }, { density: 'line' }) -export const agentsError = agents({ kind: 'error' }) -/** S1-b: the ⋯ menu open, Source per agent in this workspace. */ -export const agentsMenu = agents( - { - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'team' } - ], - label: null, - expiring: null - }, - { - interact: async (frame) => { - const trigger = frame.querySelector('[aria-label="Agent sign-in options"]') - trigger?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) - await new Promise((resolve) => setTimeout(resolve, 100)) - } - } -) - -/** - * For the layout-shift test: the row mounts in `start` and moves through states on a window event - * (`orca-fixture-agents`, detail = a model), the way the store and main move it in the app. - */ -// The test sends well-formed models; this only keeps the event's `any` out of the row. -function isRowModel(value: unknown): value is BuildAgentsRowModel { - return typeof value === 'object' && value !== null && 'kind' in value -} - -function SteppedRow({ start }: { start: BuildAgentsRowModel }): React.JSX.Element { - const [model, setModel] = useState(start) - const [density] = useState(() => buildAgentsRowDensity(start)) - useEffect(() => { - const onStep = (event: Event): void => { - if (event instanceof CustomEvent && isRowModel(event.detail)) { - setModel(event.detail) - } - } - window.addEventListener('orca-fixture-agents', onStep) - return () => window.removeEventListener('orca-fixture-agents', onStep) - }, []) - return ( - - ) -} - -function stepped(start: BuildAgentsRowModel) { - return defineFixture({ - width: 760, - setup: () => seedFixtureRepo(), - render: () => - sheet(CLOUD, null, NOW, undefined, { cloudAgentsRow: }) - }) -} - -export const agentsSteppedFromLoading = stepped({ kind: 'loading' }) -export const agentsSteppedFromReady = stepped(ACCOUNT_BOTH) diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts index 3bf0f8fc750..dd34ad13bae 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts @@ -9,7 +9,9 @@ export function stepLabel(step: VmBuildStep, cloud: boolean, t: Translate): stri ? t('auto.components.worktree.creation.VmBuildSheet.provisionCloud', 'Start sandbox') : t('auto.components.worktree.creation.VmBuildSheet.provision', 'Provision VM') case 'clone': - return t('auto.components.worktree.creation.VmBuildSheet.cloneCloud', 'Clone repository') + return step.cloneMode === 'update' + ? t('auto.components.worktree.creation.VmBuildSheet.updateCloud', 'Update repository') + : t('auto.components.worktree.creation.VmBuildSheet.cloneCloud', 'Clone repository') case 'checks': return cloud ? t('auto.components.worktree.creation.VmBuildSheet.checksCloud', 'Prepare environment') @@ -87,8 +89,12 @@ export function headerTitle( /** What the running clone is doing, in plain words. */ export function cloneStageLabel( stage: 'counting' | 'download' | 'checkout' | undefined, - t: Translate + t: Translate, + mode: 'clone' | 'update' = 'clone' ): string { + if (mode === 'update' && stage !== 'checkout') { + return t('auto.components.worktree.creation.VmBuildSheet.updateFetching', 'Fetching changes…') + } if (stage === 'counting') { return t('auto.components.worktree.creation.VmBuildSheet.cloneCounting', 'Counting objects…') } diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx index f78cfb9365d..879850cdce2 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -7,8 +7,6 @@ import { formatElapsedTime } from './worktree-creation-clock' import type { VmBuildStepTimings } from './vm-build-timing' import { useAppStore } from '@/store' import type { Repo } from '../../../../shared/repo-types' -import { IDLE_ORCA_CLOUD_AGENT_SETUPS } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { setOrcaCloudAgentAccountsStateForTest } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' export const LOG_LINES = [ 'Creating sandbox from snapshot snap_7f2c…', @@ -58,7 +56,7 @@ export function sheet( error: string | null, now: number, agentSignInRow?: React.ReactNode, - options: { cloudAgentsRow?: React.ReactNode; secretsRow?: React.ReactNode } = {} + options: { secretsRow?: React.ReactNode } = {} ) { return (
    @@ -75,7 +73,6 @@ export function sheet( onEditRecipe={() => {}} agentSignInRow={agentSignInRow} stepTimings={FIXTURE_STEP_TIMINGS} - cloudAgentsRow={options.cloudAgentsRow ?? null} secretsRow={options.secretsRow ?? null} />
    @@ -118,27 +115,3 @@ export const CLOUD_FAILED_LOG = [ 'Orca Cloud refused the request (provider_unavailable).' ].join('\n') export const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found` - -/** - * The Orca account as the cloud build sheet reads it, fixed for a fixture so nothing calls the bridge - * (the harness's catch-all mock resolves to undefined): Claude set up through the account, or not. - */ -export function seedCloudAgentAccounts(claude: 'active' | 'none'): void { - setOrcaCloudAgentAccountsStateForTest({ - load: { - kind: 'ready', - status: { - credentials: { - claude: { state: claude }, - codex: { state: 'none' }, - providerEnabled: { claude: true, codex: true }, - providerState: { claude: 'on', codex: 'on' } - }, - sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } - } - }, - setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, - keyKinds: { claude: null, codex: null }, - queue: { agents: [], index: 0 } - }) -} diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts index fa99cec518d..6a9bd02377e 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts @@ -7,6 +7,7 @@ import { deriveVmBuildSteps } from './vm-build-steps' import { classifyVmBuildFailure } from './vm-build-failure' import { holdRunningSteps } from './use-minimum-running-steps' import { humanizeOrcaCloudLogLine } from './orca-cloud-build-log' +import { cloneStageLabel, stepLabel } from './vm-build-sheet-copy' import type { Translate } from '@/i18n/use-translate' const base = { @@ -279,6 +280,54 @@ describe('Orca Cloud clone step', () => { ).toEqual({ kind: 'cloneFailed', reason: 'clone_timeout' }) }) + it('names the repository step once, from the boot plan, before it runs (PC-4)', () => { + const pendingStep = (...rows: [string, number][]) => + deriveVmBuildSteps({ ...base, ...lines(...rows) }, 2000, { cloud: true })[1] + // Not known yet: no mode (the row shows a placeholder, never a guessed label). + expect(pendingStep(['[orca-cloud] provisioning', 1000])).toMatchObject({ + state: 'pending' + }) + expect(pendingStep(['[orca-cloud] provisioning', 1000])?.cloneMode).toBeUndefined() + expect( + pendingStep(['[orca-cloud] provisioning', 1000], ['[orca-cloud] plan-update', 1200]) + ).toMatchObject({ state: 'pending', cloneMode: 'update' }) + // The running step keeps the planned name. + const running = deriveVmBuildSteps( + { + ...base, + ...lines( + ['[orca-cloud] plan-update', 1200], + ['[orca-cloud] updating', 4000], + ['[orca-cloud] clone-progress 40 download', 4500] + ) + }, + 5000, + { cloud: true } + )[1] + expect(running).toMatchObject({ state: 'running', cloneMode: 'update' }) + }) + + it('a prebuilt repo (environment build) shows as an update, not a clone', () => { + const t: Translate = (_key, fallback) => fallback + const steps = deriveVmBuildSteps( + { + ...base, + ...lines(['[orca-cloud] updating', 4000], ['[orca-cloud] clone-progress 40 download', 4500]) + }, + 5000, + { cloud: true } + ) + expect(steps[1]).toMatchObject({ + id: 'clone', + state: 'running', + percent: 40, + cloneMode: 'update' + }) + expect(stepLabel(steps[1]!, true, t)).toBe('Update repository') + expect(cloneStageLabel(steps[1]!.stage, t, steps[1]!.cloneMode)).toBe('Fetching changes…') + expect(humanizeOrcaCloudLogLine('[orca-cloud] updating', t)).toBe('Updating the repository…') + }) + it('shows counting (no frozen 0%) until git reports a percent', () => { const at = (...extra: [string, number][]) => deriveVmBuildSteps({ ...base, ...lines(['[orca-cloud] cloning', 6000], ...extra) }, 9000, { diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.ts index dae5d53166c..2a4797f4057 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.ts @@ -6,6 +6,7 @@ import { import type { WorktreeSetupStepState } from './worktree-setup-steps' import { orcaCloudCloneProgress, + orcaCloudPlannedRepoMode, type OrcaCloudCloneProgress } from '@/lib/orca-cloud/orca-cloud-clone-progress' @@ -26,6 +27,8 @@ export type VmBuildStep = { * percent yet (the row shows an indeterminate bar, never a frozen 0%). */ stage?: 'counting' | 'download' | 'checkout' + /** Clone only: 'update' when the repo came prebuilt and only changes are fetched. */ + cloneMode?: 'clone' | 'update' /** When the step started, if it has. */ startedAt: number | null } @@ -82,12 +85,14 @@ function runningClone( startedAt: number ): VmBuildStep { // No percent yet, or git's first 0% while GitHub counts objects: nothing to measure yet. + const cloneMode = clone?.mode ?? 'clone' if (!clone || (!clone.percent && clone.stage !== 'checkout')) { - return { ...step('clone', 'running', elapsedMs, startedAt), stage: 'counting' } + return { ...step('clone', 'running', elapsedMs, startedAt), stage: 'counting', cloneMode } } return { ...step('clone', 'running', elapsedMs, startedAt, { percent: clone.percent }), - stage: clone.stage ?? 'download' + stage: clone.stage ?? 'download', + cloneMode } } @@ -111,6 +116,11 @@ export function deriveVmBuildSteps( ? orcaCloudCloneProgress(entry.provisioningLog ?? '', entry.provisioningLogStamps ?? []) : null const cloneAt = clone?.startedAt ?? undefined + // Known before the step renders (boot plan) or once the create answers; never changes after. + const cloneMode = + clone?.mode ?? + (cloud ? orcaCloudPlannedRepoMode(entry.provisioningLog ?? '') : null) ?? + undefined const afterClone = clone?.endedAt ?? check?.startedAt ?? createAt const provisionDone = Boolean(check) || workspacePhase || cloneAt !== undefined @@ -130,9 +140,15 @@ export function deriveVmBuildSteps( const cloneStep: VmBuildStep | null = !cloud ? null : cloneAt === undefined - ? step('clone', provisionDone ? 'done' : 'pending', null, undefined) + ? { + ...step('clone', provisionDone ? 'done' : 'pending', null, undefined), + ...(cloneMode ? { cloneMode } : {}) + } : clone?.ended || check || workspacePhase - ? step('clone', 'done', span(cloneAt, afterClone), cloneAt) + ? { + ...step('clone', 'done', span(cloneAt, afterClone), cloneAt), + cloneMode: clone?.mode ?? 'clone' + } : failed ? step('clone', 'failed', span(cloneAt, entry.errorAt), cloneAt) : runningClone(clone, span(cloneAt, now), cloneAt) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 03503d3b16a..d13f650fb7a 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -415,8 +415,6 @@ "new": { "workspace": { "RunTargetCombobox": { - "orcaCloudIdleSleep_one": "Sleeps after {{count}} minute idle", - "orcaCloudIdleSleep_other": "Sleeps after {{count}} minutes idle", "orcaCloudSandboxHoursLeft_one": "{{hours}} sandbox hour left", "orcaCloudSandboxHoursLeft_other": "{{hours}} sandbox hours left" } @@ -1315,6 +1313,10 @@ "unavailableCount_one": "{{count}} unavailable", "unavailableCount_other": "{{count}} unavailable" }, + "teammates": { + "daySandboxHours_one": "{{hours}} sandbox hour", + "daySandboxHours_other": "{{hours}} sandbox hours" + }, "terminal": { "pane": { "TerminalErrorToast": { @@ -1342,15 +1344,15 @@ }, "worktree": { "creation": { + "BlockedSandboxHoursNote": { + "sleepsIn_one": "Sleeps in {{count}} minute if unused.", + "sleepsIn_other": "Sleeps in {{count}} minutes if unused." + }, "VmBuildErrorDetails": { "earlierLines_one": "…{{count}} earlier line. Copy details includes it.", "earlierLines_other": "…{{count}} earlier lines. Copy details includes them." }, "VmBuildFailureCard": { - "checksBodyCloud2_one": "Open it anyway and fix it inside the workspace, or run the checks again after changing your project.", - "checksBodyCloud2_other": "Open it anyway and fix them inside the workspace, or run the checks again after changing your project.", - "checksCountTitleCloud_one": "The sandbox is up, but {{count}} environment check failed", - "checksCountTitleCloud_other": "The sandbox is up, but {{count}} environment checks failed", "checksCountTitleVm_one": "The VM is up, but {{count}} environment check failed", "checksCountTitleVm_other": "The VM is up, but {{count}} environment checks failed", "memberLimitBodyCount_one": "You can run {{count}} sandbox at once. Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", @@ -1562,6 +1564,13 @@ "save_one": "Save secret", "save_other": "Save {{count}} secrets" }, + "cloudSetupPage": { + "trial": { + "lead": "{{hours}} sandbox hours to try Orca Cloud. No card needed.", + "lead_one": "{{hours}} sandbox hour to try Orca Cloud. No card needed.", + "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." + } + }, "codeHost": { "bitbucketConnect": { "accessTokenRequired": "Enter an access token.", @@ -2337,7 +2346,6 @@ } }, "orcaCloudSync": { - "ago": "{{ago}} ago", "editedHere_one": "{{count}} file changed on this computer. Edits here don’t sync back. The cloud copy replaces it when it changes.", "editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.", "fileCount_one": "{{n}} file", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 69f86626fdc..78894c55d89 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2289,7 +2289,8 @@ "vmChecksFailed": "Environment checks failed", "preparingCloudEnvironment": "Preparing environment…", "startingSandbox": "Starting sandbox…", - "cloningRepository": "Cloning the repository…" + "cloningRepository": "Cloning the repository…", + "updatingRepository": "Updating the repository…" }, "duplicatePairedServers": { "ambiguousSameServer": "{{value0}} and {{value1}} are the same server paired twice. Remove one in Settings > Remote Orca Servers." @@ -2330,7 +2331,8 @@ "ephemeralVmEnvironmentCheck": { "backgroundFailed": "Environment checks failed for a new VM workspace. Open it in the sidebar to continue.", "openedDegraded": "Creating the workspace on a VM whose environment checks failed.", - "unreachable": "The environment checks could not finish: {{error}}" + "unreachable": "The environment checks could not finish: {{error}}", + "backgroundFailedCloud": "A new cloud workspace couldn’t start. Open it in the sidebar to continue." }, "orcaCloudSession": { "seePlans": "See plans", @@ -4236,7 +4238,10 @@ "cloneCloud": "Clone repository", "cloneCheckout": "Checking out files…", "cloneDownload": "Downloading history…", - "cloneCounting": "Counting objects…" + "cloneCounting": "Counting objects…", + "updateCloud": "Update repository", + "updateFetching": "Fetching changes…", + "repositoryPending": "Repository" }, "VmBuildFailureCard": { "createFailedTitle": "Couldn’t create workspace", @@ -4245,7 +4250,6 @@ "unavailableTitle": "Orca Cloud is unavailable right now", "networkTitle": "Couldn’t reach Orca Cloud", "snapshotTitle": "This project’s saved environment is missing", - "stillRunningCloud": "The sandbox is running and using sandbox hours until you choose.", "stillRunningLocal": "The VM is running and using hours until you choose.", "tryAgain": "Try again", "signIn": "Sign in", @@ -4288,14 +4292,9 @@ "outOfHoursBodyMember3": "Your team has used this month’s sandbox hours, so sandboxes can’t start or keep running. Nothing was created, and you weren’t charged. Ask an owner or admin to add hours.", "spendCapReachedBodyMember4": "Your team has reached this month’s spend cap, so sandboxes can’t start or keep running. Nothing was created, and you weren’t charged. Ask an owner or admin to raise the spend cap.", "paymentFailedBodyMember2": "New sandboxes can’t start until the payment goes through. Nothing was created, and you weren’t charged. Ask an owner or admin to update the payment method.", - "checksAttentionTitleCloud": "The sandbox is up, but some environment checks need attention", "checksAttentionTitleVm": "The VM is up, but some environment checks need attention", - "checksCountTitleCloud_one": "The sandbox is up, but {{count}} environment check failed", - "checksCountTitleCloud_other": "The sandbox is up, but {{count}} environment checks failed", "checksCountTitleVm_one": "The VM is up, but {{count}} environment check failed", "checksCountTitleVm_other": "The VM is up, but {{count}} environment checks failed", - "checksBodyCloud2_one": "Open it anyway and fix it inside the workspace, or run the checks again after changing your project.", - "checksBodyCloud2_other": "Open it anyway and fix them inside the workspace, or run the checks again after changing your project.", "provisionBodyCloudKept": "Something went wrong while starting the sandbox. Try again, or delete the sandbox to stop using sandbox hours.", "provisionBodyCloud2": "Something went wrong while starting the sandbox. Nothing was created, and you weren’t charged.", "provisionBodyVm": "Your VM recipe stopped with an error before the VM was ready.", @@ -4310,7 +4309,11 @@ "cloneDiskFullBody": "This repository doesn’t fit on the sandbox’s disk. The sandbox was deleted.", "cloneFailedBody": "Git stopped with an error while cloning, and the sandbox was deleted. Try again, or open the logs for details.", "githubNotConnectedBody2": "Orca Cloud clones your code from GitHub and needs access to this repository first. Install the Orca GitHub App on {{owner}}, then try again. Nothing was created, and you weren’t charged.", - "cloneFailedTitle": "Couldn’t clone {{repo}}" + "cloneFailedTitle": "Couldn’t clone {{repo}}", + "startAgain": "Start again", + "cloudUnusableTitle": "This sandbox can’t open your workspace", + "cloudUnusableDeletedBody": "The sandbox was deleted. Start again to try a new one.", + "cloudUnusableBody": "Start again on a new sandbox, or delete this one." }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -4348,7 +4351,8 @@ "denyMachineSize2": "This sandbox size isn’t part of your plan.", "refusedProvider2": "Orca Cloud is unavailable right now.", "rollingOver2": "Restarting the sandbox…", - "cloning": "Cloning the repository…" + "cloning": "Cloning the repository…", + "updating": "Updating the repository…" }, "environmentCheckCopy": { "gitMissing": "git isn’t installed.", @@ -4366,7 +4370,12 @@ "failed": "Failed", "warning": "Warning", "passed": "Passed", - "toolMissingFixCloud": "Install {{command}} in the workspace, or add it to your project’s setup script." + "toolMissingFixCloud": "Install {{command}} in the workspace, or add it to your project’s setup script.", + "setupNotRun": "Setup script hasn’t run yet.", + "cloudUnreachable": "Orca couldn’t reach the sandbox.", + "cloudRepoMissing": "The repository isn’t in the sandbox.", + "cloudRepoUnreadable": "Git can’t read the repository in the sandbox.", + "cloudGitMissing": "git isn’t installed in the sandbox." }, "WorktreeCreationTabStrip": { "cancelLabel": "Cancel workspace creation" @@ -4386,6 +4395,12 @@ "copiedStatus": "Details copied", "earlierLines_one": "…{{count}} earlier line. Copy details includes it.", "earlierLines_other": "…{{count}} earlier lines. Copy details includes them." + }, + "BlockedSandboxHoursNote": { + "asleep": "Asleep. It isn’t using sandbox hours.", + "sleeping": "Going to sleep…", + "sleepsIn_one": "Sleeps in {{count}} minute if unused.", + "sleepsIn_other": "Sleeps in {{count}} minutes if unused." } } }, @@ -10949,6 +10964,14 @@ "extension": "extension", "chrome": "chrome", "password": "password manager" + }, + "pokes": { + "poke": "poke", + "nudge": "nudge", + "teammate": "teammate", + "activityTitle": "Pokes and activity", + "activityDescription": "Teammates can poke you and see which days you used Orca Cloud. Amounts stay private.", + "activity": "activity" } } }, @@ -16715,20 +16738,12 @@ "currentSuffix": "(current)", "orcaCloudSignInDetail": "Sign in to start a sandbox", "orcaCloudChecking": "Checking your plan…", - "orcaCloudNeedsTeamPlan": "Orca Cloud needs a Team plan.", "orcaCloudOutOfHours": "Out of sandbox hours", "orcaCloudRaiseSpendCap": "Raise spend cap", - "orcaCloudPaymentEffect": "New sandboxes can't start.", "orcaCloudUpdatePaymentMethod": "Update payment method", "orcaCloudSandboxHoursLeft_one": "{{hours}} sandbox hour left", "orcaCloudSandboxHoursLeft_other": "{{hours}} sandbox hours left", "orcaCloudAskOwnerOrAdmin": "Ask an owner or admin", - "orcaCloudAskPayment": "Ask an owner or admin to update the payment method.", - "orcaCloudIdleSleep_one": "Sleeps after {{count}} minute idle", - "orcaCloudIdleSleep_other": "Sleeps after {{count}} minutes idle", - "orcaCloudAskAddHoursOnly": "Ask an owner or admin to add hours.", - "orcaCloudAskChoosePlan": "Ask an owner or admin to choose one.", - "orcaCloudAskRaiseSpendCap": "Ask an owner or admin to raise the spend cap.", "hintConnect": "{{host}}, not connected. Press Enter to connect.", "hintSetLocation": "{{host}}, project location not set. Press Enter to set it.", "hintSignIn": "Orca Cloud, signed out. Press Enter to sign in.", @@ -20701,7 +20716,9 @@ "createInvalid2": "Use letters, numbers, spaces or underscores (up to 64).", "nameTaken": "That team name is taken. Try another.", "totalPerMonth": "{{total}} per month", - "totalPerYear": "{{total}} per year" + "totalPerYear": "{{total}} per year", + "openProfile": "Open {{value0}}’s profile", + "viewProfile": "View profile" }, "manageBilling": "Manage billing", "comparePlans": "Compare plans", @@ -21011,12 +21028,19 @@ "deleteWorkspace": "Delete…", "showRunningOnly": "Show running only", "running": "Running", + "showRoutineRuns": "Show routine runs", + "routineRuns": "Routine runs", + "routineRun": "Routine run", + "routineRunTooltip": "Started by a routine. It's deleted when the run ends.", + "routineRunOf": "Routine · {{name}}", + "routineRunsHidden": "Routine runs · {{count}}", "errorTeamSandboxLimit_one": "Your team can run {{count}} sandbox at once ({{perSeat}} per seat). Put it to sleep or delete it, then try again.", "errorTeamSandboxLimit_other": "Your team can run {{count}} sandboxes at once ({{perSeat}} per seat). Put one to sleep or delete it, then try again.", "errorSeatSandboxLimitSelf_one": "You already have {{count}} sandbox running, the most one seat can run. Put it to sleep or delete it, then try again.", "errorSeatSandboxLimitSelf_other": "You already have {{count}} sandboxes running, the most one seat can run. Put one to sleep or delete it, then try again.", "errorSeatSandboxLimitOwner_one": "{{name}} already has {{count}} sandbox running. This workspace runs on their seat, so ask them to put it to sleep, then try again.", - "errorSeatSandboxLimitOwner_other": "{{name}} already has {{count}} sandboxes running. This workspace runs on their seat, so ask them to put one to sleep, then try again." + "errorSeatSandboxLimitOwner_other": "{{name}} already has {{count}} sandboxes running. This workspace runs on their seat, so ask them to put one to sleep, then try again.", + "viewOwnerProfile": "View {{name}}'s profile" }, "orcaCloud": { "QueuedPrompt": { @@ -21033,6 +21057,53 @@ "sending": "Sending to {{agent}} next", "edit": "Edit queued prompt" } + }, + "teammates": { + "pokesNeedTeam": "Sign in to Orca and switch to a team to use Pokes.", + "pokesSaveFailed": "Couldn’t save. Check your connection and try again.", + "unreachable": "Can’t reach Orca Cloud right now. Check your connection.", + "someone": "A teammate", + "pokedYou": "{{name}} poked you", + "pokeBack": "Poke back", + "poked": "Poked {{name}}", + "viewProfile": "View profile", + "title": "Teammate profile", + "description": "Role, daily Orca Cloud usage and recent workspaces.", + "pokesOffThem": "{{name}} hasn’t turned on Pokes yet.", + "loadFailed": "Couldn’t load this profile", + "tryAgain": "Try again", + "usageHeading": "Usage", + "recentWorkspaces": "Recent workspaces", + "showAll": "Show all", + "noWorkspacesSelf": "You have no cloud workspaces yet.", + "noWorkspaces": "No cloud workspaces shared with the team.", + "openWorkspace": "Open {{title}}, {{status}}", + "pokeHint": "A poke is a friendly nudge. {{name}} sees it in Orca.", + "openExperimental": "Open settings", + "poke": "Poke", + "levelNone": "No usage", + "levelLight": "Light usage", + "levelModerate": "Moderate usage", + "levelBusy": "Busy day", + "levelPeak": "One of their busiest days", + "daySandboxHours_one": "{{hours}} sandbox hour", + "daySandboxHours_other": "{{hours}} sandbox hours", + "dayAgentUsage": "Agent usage", + "heatmapSummarySelf": "You used Orca Cloud on {{active}} of the last {{days}} days", + "heatmapSummary": "{{name}} used Orca Cloud on {{active}} of the last {{days}} days", + "heatmapEmpty": "No Orca Cloud usage in the last 26 weeks.", + "heatmapHint": "Each day compared with their busiest day. Amounts stay private.", + "legendLess": "Less", + "legendMore": "More", + "pokeCooldown": "You just poked {{name}}. Try again in a minute.", + "pokeRate": "That’s a lot of pokes. Try again later.", + "pokeOffline": "Can’t reach Orca Cloud right now. Check your connection.", + "pokeFailed": "Couldn’t send the poke. Try again.", + "pokesActivitySettingCopy": "Teammates can poke you and see which days you used Orca Cloud. Amounts stay private.", + "pokesActivityToggle": "Toggle Pokes and activity", + "pokesOffYouActivity": "Pokes are off. Turn on Pokes and activity in Settings → Experimental.", + "activityNotShared": "{{name}} hasn’t shared their activity.", + "heatmapHintSelfHover": "Hover a day to see your sandbox hours." } }, "i18n": { @@ -23099,68 +23170,15 @@ "bothSources": "orca.yaml + local", "localSource": "local settings" }, - "cloudStart": { - "useThisComputer": "Use this computer instead", - "start": "Start in Orca Cloud", - "setUpAndStart": "Set up and start", - "choosePlanAndStart": "Choose plan and start", - "renewAndStart": "Renew and start", - "giveAccessAndStart": "Give access and start", - "checking": "Checking Orca Cloud…", - "githubGranted": "GitHub access granted for {{repo}}" - }, "cloudSetup": { - "account": "Orca account", - "team": "Team", - "plan": "Team plan", - "github": "GitHub access", - "githubNeeded": "Orca Cloud clones your code from GitHub. Give access to this repository once.", - "agent": "Agent", - "planAfterSignIn": "Checked after you sign in", - "askOwner": "Ask an owner or admin to fix it.", - "planEnded": "Your Team plan ended.", - "outOfHours": "Out of sandbox hours.", - "spendCap": "Spend cap reached.", - "paymentFailed": "Payment failed.", - "planMember": "Orca Cloud needs a Team plan. Only owners and admins can choose one.", - "planNeeded": "Orca Cloud needs a Team plan.", - "stateDone": "Done", - "stateOptional": "Optional", - "stateNext": "Next", - "stateInBrowser": "In browser", - "stateFailed": "Didn't finish", - "stateChecking": "Checking", - "stateNeeded": "Needed", - "allSet": "All set", - "title": "Set up Orca Cloud", - "starting": "Starting your cloud workspace…", - "accountNeededTeam": "Sign in or create one. We’ll make a team for you.", - "trial": "Trial", - "trialNoCard": "No card needed. Nothing is charged until you choose a plan.", - "stateIncluded": "Included", - "trialUsedUp": "Your trial is used up.", - "trialUsedUpMember": "Only owners and admins can choose a plan.", - "trialUsedUpOwner": "Choose a plan to keep using Orca Cloud. Your prompt is still here.", - "subtitleNoCard": "One visit to your browser, no card. Your prompt stays here and starts when you’re done.", "trialUsedUpTitle": "Your trial is used up", "choosePlan": "Choose plan", "askChoosePlan": "Ask an owner or admin to choose a plan.", - "trialUsedUpChoose": "Choose a plan to keep using Orca Cloud.", "trialOffer_one": "{{hours}} sandbox hour to try Orca Cloud", "trialOffer_other": "{{hours}} sandbox hours to try Orca Cloud", - "subtitleChoosePlan": "One visit to your browser to choose a plan. Your prompt stays here and starts when you’re done.", - "subtitleNeedsRepository": "Orca Cloud needs a GitHub repository. Your prompt stays here.", - "outOfHoursMember": "Out of sandbox hours. Ask an owner or admin to add hours.", - "spendCapMember": "Spend cap reached. Ask an owner or admin to raise the spend cap.", - "paymentFailedMember": "Payment failed. Ask an owner or admin to update the payment method.", - "subtitleOwnerFixes": "An owner or admin needs to fix this. Your prompt stays here.", - "cancelSetup": "Cancel setup", - "copySetupLink": "Copy setup link", "reopenBrowser": "Reopen browser", "tryAgain": "Try again", "switchAccount": "Switch account", - "trackerTitle": "Finish in your browser", - "trackerSubtitle": "Orca picks up each step the moment it’s done, then starts this workspace.", "teamRequired": "Cloud workspaces belong to a team.", "teamHasPlan": "{{team}} has a Team plan. Switch to start this workspace there.", "teamsHavePlans": "{{teams}} have a Team plan. Switch to one to start this workspace there.", @@ -23168,7 +23186,6 @@ "switchTeam": "Switch team", "switchFirst": "Switch to {{team}} first", "switchTeamFirst": "Switch to a team first", - "linkUnavailable": "Couldn’t get a setup link. Try Set up and start again.", "linkCopied": "Setup link copied. Open it in the browser you use for Orca.", "error": { "timedOut": "Setup didn’t finish in your browser. Your prompt is still here.", @@ -23183,18 +23200,11 @@ "planCoveredByTrial": "Your trial covers it.", "planCheckoutOpen": "Finish checkout in your browser.", "githubRequestedSession": "Waiting for an owner on GitHub to approve Orca Cloud.", - "subtitleChoosePlanAndGitHub": "One visit to your browser to choose a plan and give Orca Cloud access on GitHub. Your prompt stays here and starts when you’re done." + "linkUnavailableRetry": "Couldn’t get a setup link. Try Continue in browser again." }, "runOn": { "thisComputer": "This computer", - "orcaCloud": "Orca Cloud", - "moreWithTarget": "More places to run: {{name}}", - "more": "More places to run", - "cloudUnreachableReason": "Orca Cloud: can't reach it right now. Check your connection.", - "thisComputerUnusable": "This computer, {{reason}}", - "locationNotSet": "Project location not set", - "cloudUnreachableName": "Orca Cloud, can't reach it right now", - "cloudHosted": "Hosted sandbox" + "orcaCloud": "Orca Cloud" }, "cloudHours": { "trialChip_one": "Trial · {{hours}} sandbox hour left", @@ -23218,18 +23228,20 @@ "heading": "On GitHub · Orca Cloud only", "detail": "Orca Cloud clones it. No copy on this computer needed.", "moreAccess": "Give Orca Cloud access to more repositories…", - "notOnThisComputer": "Not on this computer · Orca Cloud only", "startFailed": "Couldn’t start the cloud workspace. Nothing was created, and you weren’t charged.", "starting": "Starting {{repo}} in Orca Cloud…", "openLater": "Your cloud workspace started, but this computer couldn’t open it yet. Open it from Cloud workspaces.", "private": "{{owner}} · Private", "public": "{{owner}} · Public", "showMore": "Show more repositories…", - "chooseRepository": "Choose a GitHub repository", - "addGitHubProject": "Add a GitHub project…", "folderDetail": "Orca Cloud starts from a GitHub repository. This project is a folder on this computer." }, - "orcaCloudAgentFallback": "{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected." + "cloudStart": { + "agentNotStarted": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", + "agentNotStartedGeneric": "Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", + "setUpAgentOnce": "Set up {{agent}} once", + "setUpAgentOnceGeneric": "Set up once" + } }, "JiraIssueWorkspace": { "pendingChange": "Another issue change is in progress." @@ -23449,12 +23461,26 @@ "waking": "Waking sandbox…", "unarchiving": "Unarchiving workspace…", "wakingDetail": "The remote desktop opens when it’s awake.", - "paletteDescription": "Open the sandbox’s desktop in a browser tab.", + "paletteDescription": "Open the sandbox’s desktop in a tab.", "verbs": { "remoteDesktop": "remote desktop", "openDesktop": "open desktop", "vnc": "vnc", "screen": "screen" + }, + "openTabMenuItem": "Open Remote Desktop", + "goToTabMenuItem": "Go to Remote Desktop", + "tab": { + "connected": "Connected", + "connecting": "Connecting…", + "reconnecting": "Reconnecting…", + "disconnected": "Disconnected", + "releaseHint": "{{chord}} returns keys to Orca", + "reconnectingTitle": "Reconnecting…", + "wakingDetail": "The remote desktop reconnects when it’s awake.", + "asleepDetail": "Wake it to reconnect. Apps that were open on the remote desktop need to be started again. Your files are safe.", + "asleepTitle": "This workspace is asleep.", + "waking": "Waking…" } }, "orcaCloud": { @@ -27437,6 +27463,19 @@ "public": "{{repo}} is public. Nothing to do.", "doneStatus": "Done" } + }, + "setupNotices": { + "pushNeedsApp": "Orca Cloud can read {{repo}} but can’t push yet. Install the Orca GitHub App on {{owner}} to push.", + "waitingForGitHub": "Waiting for GitHub…", + "installOn": "Install on {{owner}}", + "pushRefused": "Orca Cloud can’t push from this workspace.", + "setupNotRun": "Setup script hasn’t run yet", + "runSetup": "Run setup script", + "label": "Workspace setup", + "dismiss": "Dismiss", + "installFailed": "Couldn’t open GitHub. Check your connection and try again.", + "pushReady": "Orca Cloud can push to {{repo}} now.", + "setupMissing": "Couldn’t read the setup script from orca.yaml in this workspace." } }, "runActions": { @@ -27915,31 +27954,9 @@ "menu": { "notYet": "You can choose once the sandbox is created.", "failed": "Couldn’t read this workspace’s choice.", - "shared": "Personal accounts aren’t used in shared workspaces.", - "label": "Agent sign-in options", - "inThisWorkspace": "{{agent}} in this workspace", "yourAccount": "Your account", - "useKey": "Use an API key instead", - "manage": "Manage agent accounts…", "saveFailed": "Couldn’t change it. Nothing was changed." }, - "codeCopied": "Code copied", - "cancel": "Cancel", - "renew": "Renew", - "setUp": "Set up", - "openAgain": "Open again", - "copyAndOpen": "Copy code and open", - "pasteToken": "Paste token", - "tryAgain": "Try again", - "dismiss": "Dismiss", - "signInHere": "Sign in for this workspace", - "checking": "Checking agent sign-in", - "readyDetail": "Every cloud workspace uses it. Nothing to do here.", - "keyFailed": "Couldn’t save {{name}}. Nothing was changed.", - "queued": "Opens when the sandbox is ready. Keep Orca open until then.", - "deviceEnter": "Enter", - "deviceOn": "on {{host}}", - "manage": "Manage", "separator": " · ", "stepOf": "{{step}} of {{of}}", "settingUp": "Setting up {{agent}}", @@ -28057,31 +28074,113 @@ "cancelledToast": "The agent didn’t start. The shell is still open.", "expiredCompact": "{{agent}} sign-in expired" }, - "cloudAgentCheck": { - "keyAgentSignedOut": "{{agent}} isn’t signed in.", - "keyAgentFix": "Add its API key in Settings → Cloud secrets, or sign in when it starts in this workspace.", - "notSetUp": "{{agent}} isn’t set up for Orca Cloud yet.", - "notSetUpFix": "Set it up once in Settings → Agent accounts. Every cloud workspace uses it.", - "expired": "Your {{agent}} sign-in for Orca Cloud expired.", - "expiredFix": "Renew it once in Settings → Agent accounts. Every cloud workspace uses it.", - "signInHere": "{{agent}} isn’t signed in for this workspace.", - "pausedFix": "Orca account sign-in is paused. Sign in for this workspace; the sign-in stays with this workspace.", - "notOfferedFix": "Signs in for each cloud workspace for now. Sign in for this workspace; the sign-in stays with this workspace." + "cloudSetupPage": { + "agent": { + "lead": "Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.", + "setUp": "Set up once", + "skip": "Skip for now", + "title": "Sign in to {{agent}} once", + "titleGeneric": "Sign in to your agent once" + }, + "back": "Back", + "billing": { + "capLead": "Raise the spend cap to start this workspace.", + "capTitle": "Spend cap reached", + "hoursLead": "Turn on overage to start this workspace.", + "hoursTitle": "Out of sandbox hours", + "paymentLead": "The last payment failed. Update the card to keep going.", + "paymentTitle": "Update your payment method", + "openSettings": "Open billing settings" + }, + "checkAgain": "Check again", + "checking": { + "title": "Checking your Orca Cloud account…" + }, + "continueInBrowser": "Continue in browser", + "copyLink": "Copy link", + "done": { + "lead": "Starting your cloud workspace…", + "title": "All set" + }, + "eyebrow": "Orca Cloud setup", + "github": { + "lead": "Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.", + "title": "Give Orca Cloud access on GitHub", + "waiting": "This page starts the workspace once they approve.", + "waitingTitle": "Waiting for approval on GitHub" + }, + "orcaCloud": "Orca Cloud", + "owner": { + "lead": "Orca Cloud needs a Team plan. Only owners and admins can choose one.", + "title": "An owner or admin needs to fix this" + }, + "plan": { + "lead": "Orca Cloud needs a Team plan. Checkout opens in your browser.", + "renewLead": "Your Team plan ended. Renew it in your browser to start this workspace.", + "renewTitle": "Renew your Team plan", + "title": "Choose a Team plan", + "trialUsedUpLead": "Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.", + "trialUsedUpTitle": "Your trial is used up" + }, + "reopenBrowser": "Reopen browser", + "repository": { + "title": "Orca Cloud needs a GitHub repository" + }, + "signIn": { + "lead": "Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.", + "note": "New teams get a trial with no card needed. This page picks up each step on its own.", + "title": "Sign in to Orca" + }, + "starting": "Starting…", + "startsAfter": "Starts when setup is done", + "step": { + "account": "Account", + "agent": "Agent", + "github": "GitHub", + "plan": "Plan", + "team": "Team", + "trial": "Trial" + }, + "stepCurrent": "current step", + "stepDone": "done", + "stepsLabel": "Setup steps", + "team": { + "title": "Switch to your team" + }, + "trial": { + "lead": "{{hours}} sandbox hours to try Orca Cloud. No card needed.", + "leadNoHours": "Try Orca Cloud on your team. No card needed.", + "note": "Nothing is charged until you choose a plan.", + "start": "Start free trial", + "title": "Start your free trial", + "lead_one": "{{hours}} sandbox hour to try Orca Cloud. No card needed.", + "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." + }, + "untitled": "New cloud workspace", + "waitingBrowser": "Waiting for your browser…" }, "orcaCloudSync": { "menuItem": "Mirror to this computer…", + "gb": "{{value}} GB", + "mb": "{{value}} MB", "kb": "{{value}} KB", "justNow": "just now", - "ago": "{{ago}} ago", + "minutesAgo": "{{count}} min ago", + "hoursAgo": "{{count}} h ago", "copying": "Copying {{done}} of {{total}} files…", "waitingSynced": "Waits until the workspace wakes · synced {{ago}}", "waiting": "Waits until the workspace wakes", "syncing": "Syncing…", - "synced": "Synced · {{files}} · {{size}} · {{ago}}", "fileCount_one": "{{n}} file", "fileCount_other": "{{n}} files", + "syncedToLimit": "Synced up to the limit · {{files}} · {{size}} · {{ago}}", + "synced": "Synced · {{files}} · {{size}} · {{ago}}", "announceSynced": "Files synced to this computer", "error": "Couldn’t sync files. Your files in the cloud are safe.", + "removeConfirmTitle": "Remove the copy on this computer?", + "removalEdited_one": "{{count}} changed file on this computer will be removed.", + "removalEdited_other": "{{count}} changed files on this computer will be removed.", + "removeCopy": "Remove copy", "title": "On this computer", "contextLabel": ".context folder", "contextDescription": "Plans and screenshots from this workspace", @@ -28095,15 +28194,6 @@ "editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.", "overLimit": "The mirror is limited to {{size}}. Larger files and anything past the limit aren’t copied.", "tooLarge": "Files over {{size}} aren’t copied.", - "removalEdited_one": "{{count}} changed file on this computer will be removed.", - "removalEdited_other": "{{count}} changed files on this computer will be removed.", - "removal": "The copy on this computer is removed too.", - "gb": "{{value}} GB", - "mb": "{{value}} MB", - "minutesAgo": "{{count}} min ago", - "hoursAgo": "{{count}} h ago", - "syncedToLimit": "Synced up to the limit · {{files}} · {{size}} · {{ago}}", - "removeConfirmTitle": "Remove the copy on this computer?", - "removeCopy": "Remove copy" + "removal": "The copy on this computer is removed too." } } diff --git a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts new file mode 100644 index 00000000000..aae8d67601d --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const DESKTOP = 'http://localhost:6080/vnc.html?autoconnect=0&reconnect=0&resize=remote' +let state: Record = {} +const reopen = vi.fn(async () => {}) + +vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) +vi.mock('@/lib/workspace/ownership/workspace-runtime-environment', () => ({ + selectWorkspaceRuntimeEnvironmentId: () => 'env-1', + useWorkspaceRuntimeEnvironmentId: () => 'env-1' +})) +vi.mock('./open-cloud-remote-desktop', () => ({ + reopenCloudRemoteDesktopQuietly: reopen, + openCloudRemoteDesktop: vi.fn() +})) +vi.mock('react', () => ({ + useEffect: (fn: () => void) => fn(), + useMemo: (fn: () => unknown) => fn() +})) + +const { + hasRemoteDesktopToReopen, + noteRemoteDesktopBeforeSleep, + resetRemoteDesktopSleepReopenForTest, + useReopenRemoteDesktopAfterWake +} = await import('./desktop-sleep-reopen') + +describe('remote desktop across sleep', () => { + beforeEach(() => { + resetRemoteDesktopSleepReopenForTest() + reopen.mockClear() + }) + + it('remembers a desktop tab that sleep closes and reopens it once the workspace runs', () => { + state = { + activeWorktreeId: 'w1', + activeTabType: 'browser', + activeBrowserTabId: 'tab-d', + browserTabsByWorktree: { + w1: [ + { id: 'tab-b', url: 'https://example.com' }, + { id: 'tab-d', url: DESKTOP } + ] + } + } + noteRemoteDesktopBeforeSleep('w1') + expect(hasRemoteDesktopToReopen('w1')).toBe(true) + useReopenRemoteDesktopAfterWake('w1', false) + expect(reopen).not.toHaveBeenCalled() + useReopenRemoteDesktopAfterWake('w1', true) + expect(reopen).toHaveBeenCalledWith('w1', 'env-1', true) + // Once only. + useReopenRemoteDesktopAfterWake('w1', true) + expect(reopen).toHaveBeenCalledTimes(1) + }) + + it('reopens a desktop that was behind another tab without bringing it to the front', () => { + state = { + activeWorktreeId: 'w1', + activeTabType: 'terminal', + activeBrowserTabId: null, + browserTabsByWorktree: { w1: [{ id: 'tab-d', url: DESKTOP }] } + } + noteRemoteDesktopBeforeSleep('w1') + useReopenRemoteDesktopAfterWake('w1', true) + expect(reopen).toHaveBeenCalledWith('w1', 'env-1', false) + }) + + it('does nothing for a workspace without a desktop tab', () => { + state = { browserTabsByWorktree: { w1: [{ id: 'tab-b', url: 'http://localhost:3000/' }] } } + noteRemoteDesktopBeforeSleep('w1') + expect(hasRemoteDesktopToReopen('w1')).toBe(false) + }) +}) diff --git a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts new file mode 100644 index 00000000000..266971a9600 --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts @@ -0,0 +1,48 @@ +import { useEffect } from 'react' +import { useAppStore } from '@/store' +import { selectWorkspaceRuntimeEnvironmentId } from '@/lib/workspace/ownership/workspace-runtime-environment' +import { selectRemoteDesktopTabId } from './remote-desktop-tab' +import { reopenCloudRemoteDesktopQuietly } from './open-cloud-remote-desktop' + +// Sleep closes a workspace's browser tabs (workspace-sleep-follower.ts), and the desktop's processes +// stop with the sandbox anyway. A remote desktop tab is remembered here and comes back on its own +// once the workspace is awake, in front again if it was in front. +const sleptWithDesktop = new Map() + +/** Call before sleep tears down the workspace's browser tabs. */ +export function noteRemoteDesktopBeforeSleep(worktreeId: string): void { + const state = useAppStore.getState() + const tabId = selectRemoteDesktopTabId(state, worktreeId) + if (!tabId) { + return + } + sleptWithDesktop.set(worktreeId, { + wasInFront: + state.activeWorktreeId === worktreeId && + state.activeTabType === 'browser' && + state.activeBrowserTabId === tabId + }) +} + +/** Reopens it when the workspace is running again (mounted for the workspace on screen). */ +export function useReopenRemoteDesktopAfterWake(worktreeId: string, running: boolean): void { + useEffect(() => { + const entry = running ? sleptWithDesktop.get(worktreeId) : undefined + if (!entry) { + return + } + sleptWithDesktop.delete(worktreeId) + const environmentId = selectWorkspaceRuntimeEnvironmentId(useAppStore.getState(), worktreeId) + if (environmentId) { + void reopenCloudRemoteDesktopQuietly(worktreeId, environmentId, entry.wasInFront) + } + }, [running, worktreeId]) +} + +export function hasRemoteDesktopToReopen(worktreeId: string): boolean { + return sleptWithDesktop.has(worktreeId) +} + +export function resetRemoteDesktopSleepReopenForTest(): void { + sleptWithDesktop.clear() +} diff --git a/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx b/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx index 2420a692019..3a7d9d69887 100644 --- a/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx +++ b/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx @@ -96,7 +96,10 @@ function desktopToast(worktreeId: string): DesktopToast { } } -function requestDesktop(environmentId: string): Promise { +/** Starts the sandbox's desktop and forwards it here; never throws. */ +export function requestCloudRemoteDesktop( + environmentId: string +): Promise { const open = window.api?.ephemeralVm?.openCloudRemoteDesktop if (typeof open !== 'function') { return Promise.resolve({ ok: false, code: 'unavailable' }) @@ -107,26 +110,52 @@ function requestDesktop(environmentId: string): Promise { + return exclusive(worktreeId, async () => { + const result = await requestCloudRemoteDesktop(environmentId) + if (result.ok) { + showDesktopTab(worktreeId, environmentId, result.url, activate) + } + }) +} + /** One open or wake at a time per workspace: a second click while one runs does nothing. */ async function exclusive(worktreeId: string, work: () => Promise): Promise { if (typeof window.api?.ephemeralVm?.openCloudRemoteDesktop !== 'function') { @@ -148,7 +177,7 @@ export function openCloudRemoteDesktop(worktreeId: string, environmentId: string return exclusive(worktreeId, async () => { const view = desktopToast(worktreeId) const stopSlow = view.showStarting() - const result = await requestDesktop(environmentId).finally(stopSlow) + const result = await requestCloudRemoteDesktop(environmentId).finally(stopSlow) if (!result.ok) { view.show({ kind: 'failed', code: result.code }) return @@ -182,7 +211,7 @@ function wakeThenOpen(worktreeId: string, via: 'wake' | 'unarchive'): Promise= startedAt }, environmentId: () => selectWorkspaceRuntimeEnvironmentId(useAppStore.getState(), worktreeId), - open: requestDesktop, + open: requestCloudRemoteDesktop, onAwake: () => { stopSlow = view.showStarting() } diff --git a/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-page-state.ts b/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-page-state.ts new file mode 100644 index 00000000000..1050b14d781 --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-page-state.ts @@ -0,0 +1,56 @@ +import { useSyncExternalStore } from 'react' +import type { RemoteDesktopPageState } from '../../../../shared/hosted-sandbox/cloud-remote-desktop' + +// Main's word on each remote desktop page (connecting, connected, paused, or no session on this +// computer). One IPC subscription for the window, installed on first use, so a state that arrives +// before the page's chrome mounts is not lost. +const states = new Map() +const listeners = new Set<() => void>() +let installed = false + +function install(): void { + if (installed) { + return + } + const on = typeof window !== 'undefined' ? window.api?.browser?.onRemoteDesktopState : undefined + if (typeof on !== 'function') { + return + } + installed = true + on((state) => { + states.set(state.browserPageId, state) + for (const listener of listeners) { + listener() + } + }) +} + +function subscribe(listener: () => void): () => void { + install() + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function getRemoteDesktopPageState(browserPageId: string): RemoteDesktopPageState | null { + install() + return states.get(browserPageId) ?? null +} + +/** Null until main reports on the page (it does once the page loads). */ +export function useRemoteDesktopPageState(browserPageId: string): RemoteDesktopPageState | null { + return useSyncExternalStore(subscribe, () => states.get(browserPageId) ?? null) +} + +export function setRemoteDesktopPageStateForTest( + state: RemoteDesktopPageState | null, + id = '' +): void { + if (state) { + states.set(state.browserPageId, state) + } else { + states.delete(id) + } + for (const listener of listeners) { + listener() + } +} diff --git a/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-tab.ts b/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-tab.ts new file mode 100644 index 00000000000..3de50094bb5 --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/remote-desktop-tab.ts @@ -0,0 +1,67 @@ +import { useEffect, useMemo } from 'react' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { + selectWorkspaceRuntimeEnvironmentId, + useWorkspaceRuntimeEnvironmentId +} from '@/lib/workspace/ownership/workspace-runtime-environment' +import { isCloudRemoteDesktopUrl } from '../../../../shared/hosted-sandbox/cloud-remote-desktop' +import { refreshCloudEnvironmentIds, useIsCloudEnvironment } from './cloud-environment-ids' +import { openCloudRemoteDesktop } from './open-cloud-remote-desktop' + +/** The workspace's remote desktop tab (there is at most one), or null. */ +export function selectRemoteDesktopTabId(state: AppState, worktreeId: string): string | null { + const tab = (state.browserTabsByWorktree[worktreeId] ?? []).find((candidate) => + isCloudRemoteDesktopUrl(candidate.url) + ) + return tab?.id ?? null +} + +/** + * The + menu's "Open Remote Desktop": goes to the workspace's desktop tab when there is one (its + * chrome reconnects it if needed), else starts the desktop and opens the tab. + */ +export function openOrGoToRemoteDesktop(worktreeId: string): void { + const state = useAppStore.getState() + const existing = selectRemoteDesktopTabId(state, worktreeId) + if (existing) { + state.setActiveBrowserTab(existing, worktreeId) + return + } + const environmentId = selectWorkspaceRuntimeEnvironmentId(state, worktreeId) + if (environmentId) { + void openCloudRemoteDesktop(worktreeId, environmentId) + } +} + +export type RemoteDesktopTabEntry = { + /** Orca Cloud workspaces only. */ + available: boolean + /** The workspace already has its desktop tab: the entry goes to it. */ + isGoTo: boolean +} + +export function useRemoteDesktopTabEntry(worktreeId: string): RemoteDesktopTabEntry { + const environmentId = useWorkspaceRuntimeEnvironmentId(worktreeId) + const isCloud = useIsCloudEnvironment(environmentId) + const isGoTo = useAppStore((state) => selectRemoteDesktopTabId(state, worktreeId) !== null) + useEffect(() => { + if (environmentId) { + void refreshCloudEnvironmentIds() + } + }, [environmentId]) + const canOpen = + typeof window !== 'undefined' && + typeof window.api?.ephemeralVm?.openCloudRemoteDesktop === 'function' + return { available: Boolean(environmentId) && isCloud && canOpen, isGoTo } +} + +/** The + menu entry's model, stable across renders: null where it is not offered. */ +export function useRemoteDesktopMenuOption( + worktreeId: string, + terminalOnly: boolean +): { isGoTo: boolean } | null { + const { available, isGoTo } = useRemoteDesktopTabEntry(worktreeId) + const offered = available && !terminalOnly + return useMemo(() => (offered ? { isGoTo } : null), [offered, isGoTo]) +} diff --git a/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.test.ts b/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.test.ts new file mode 100644 index 00000000000..792dc289240 --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest' +import type { RemoteDesktopPageState } from '../../../../shared/hosted-sandbox/cloud-remote-desktop' +import { deriveCloudDesktopPhase, desktopNeedsSession } from './use-cloud-desktop-connection' + +const page = (patch: Partial): RemoteDesktopPageState => ({ + browserPageId: 'p', + desktop: true, + captured: false, + connection: 'connecting', + ...patch +}) +const idle = { status: 'idle' as const, tries: 0 } + +describe('remote desktop tab phase', () => { + it('shows the sandbox state first: asleep, waking, archived, couldn’t wake', () => { + const connected = page({ connection: 'connected' }) + const phase = (sandbox: string) => + deriveCloudDesktopPhase({ isCloud: true, sandbox, page: connected, attempt: idle }).kind + expect(phase('sleeping')).toBe('asleep') + expect(phase('waking')).toBe('waking') + expect(phase('starting')).toBe('waking') + expect(phase('archived')).toBe('archived') + expect(phase('wakeFailed')).toBe('wakeFailed') + expect(phase('running')).toBe('connected') + }) + + it('reconnects a page with no session once the sandbox is up', () => { + const none = page({ desktop: false, connection: 'none' }) + expect(desktopNeedsSession(none)).toBe(true) + expect( + deriveCloudDesktopPhase({ isCloud: true, sandbox: 'running', page: none, attempt: idle }) + ).toEqual({ kind: 'reconnecting' }) + }) + + it('treats a page paused because the sandbox slept as needing a new session', () => { + expect(desktopNeedsSession(page({ connection: 'paused', reason: 'asleep' }))).toBe(true) + expect(desktopNeedsSession(page({ connection: 'paused', reason: 'starting' }))).toBe(true) + // A dropped connection the page itself offers Reconnect for stays the page's to show. + expect(desktopNeedsSession(page({ connection: 'paused', reason: 'failed' }))).toBe(false) + expect( + deriveCloudDesktopPhase({ + isCloud: true, + sandbox: 'running', + page: page({ connection: 'paused', reason: 'failed' }), + attempt: idle + }) + ).toEqual({ kind: 'paused', reason: 'failed' }) + }) + + it('names a failed reopen, and reads "not running" as asleep', () => { + const none = page({ desktop: false, connection: 'none' }) + expect( + deriveCloudDesktopPhase({ + isCloud: true, + sandbox: 'running', + page: none, + attempt: { status: 'failed', tries: 1, code: 'forward_failed' } + }) + ).toEqual({ kind: 'failed', code: 'forward_failed' }) + expect( + deriveCloudDesktopPhase({ + isCloud: true, + sandbox: 'unknown', + page: none, + attempt: { status: 'failed', tries: 1, code: 'not_running' } + }) + ).toEqual({ kind: 'asleep' }) + }) + + it('stops after the automatic attempts and offers Reconnect', () => { + expect( + deriveCloudDesktopPhase({ + isCloud: true, + sandbox: 'running', + page: page({ desktop: false, connection: 'none' }), + attempt: { status: 'idle', tries: 3 } + }).kind + ).toBe('failed') + }) + + it('waits for main before saying anything about a fresh page', () => { + expect( + deriveCloudDesktopPhase({ isCloud: true, sandbox: 'running', page: null, attempt: idle }) + ).toEqual({ kind: 'connecting' }) + }) +}) diff --git a/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.ts b/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.ts new file mode 100644 index 00000000000..00bb4450228 --- /dev/null +++ b/src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.ts @@ -0,0 +1,196 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { selectWorkspaceRuntimeEnvironmentId } from '@/lib/workspace/ownership/workspace-runtime-environment' +import { refreshCloudWorkspaceStatus } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { useCloudWorkspaceView } from '@/components/orca-cloud/use-cloud-workspace-view' +import type { + CloudRemoteDesktopFailureCode, + RemoteDesktopPageState, + RemoteDesktopPauseReason +} from '../../../../shared/hosted-sandbox/cloud-remote-desktop' +import { requestCloudRemoteDesktop } from './open-cloud-remote-desktop' +import { useRemoteDesktopPageState } from './remote-desktop-page-state' + +/** What a remote desktop tab shows, from the sandbox's state and main's word on the page. */ +export type CloudDesktopPhase = + | { kind: 'connected' } + | { kind: 'connecting' } + /** Orca is opening the desktop again (after a wake, a dropped forward, an app restart). */ + | { kind: 'reconnecting' } + | { kind: 'asleep' } + | { kind: 'waking' } + | { kind: 'archived' } + | { kind: 'wakeFailed' } + /** Reopening failed; the tab names why and offers the next step. */ + | { kind: 'failed'; code: CloudRemoteDesktopFailureCode } + /** Main stopped retrying; the page itself says why, with Reconnect. */ + | { kind: 'paused'; reason: RemoteDesktopPauseReason } + +/** Automatic reopen attempts per outage before the tab waits for Reconnect. */ +const MAX_AUTO_ATTEMPTS = 3 +const AUTO_RETRY_DELAYS_MS = [0, 2_000, 6_000] + +type Attempt = + | { status: 'idle'; tries: number } + | { status: 'running'; tries: number } + | { status: 'failed'; tries: number; code: CloudRemoteDesktopFailureCode } + +/** The page has no live session here, or main paused it for a reason a reopen clears. */ +export function desktopNeedsSession(page: RemoteDesktopPageState | null): boolean { + if (!page) { + return false + } + return ( + page.connection === 'none' || + (page.connection === 'paused' && (page.reason === 'asleep' || page.reason === 'starting')) + ) +} + +export function deriveCloudDesktopPhase(input: { + isCloud: boolean + sandbox: string + page: RemoteDesktopPageState | null + attempt: Attempt +}): CloudDesktopPhase { + const { isCloud, sandbox, page, attempt } = input + if (isCloud) { + if (sandbox === 'sleeping') { + return { kind: 'asleep' } + } + if (sandbox === 'waking' || sandbox === 'starting') { + return { kind: 'waking' } + } + if (sandbox === 'archived') { + return { kind: 'archived' } + } + if (sandbox === 'wakeFailed') { + return { kind: 'wakeFailed' } + } + } + if (attempt.status === 'running') { + return { kind: 'reconnecting' } + } + if (desktopNeedsSession(page)) { + if (attempt.status === 'failed') { + // Found asleep on the way: say so even before the status poll catches up. + return attempt.code === 'not_running' + ? { kind: 'asleep' } + : { kind: 'failed', code: attempt.code } + } + // Reopened every time, yet the page still has no session: stop and offer Reconnect. + return attempt.tries >= MAX_AUTO_ATTEMPTS + ? { kind: 'failed', code: 'forward_failed' } + : { kind: 'reconnecting' } + } + if (page?.connection === 'connected') { + return { kind: 'connected' } + } + if (page?.connection === 'paused' && page.reason) { + return { kind: 'paused', reason: page.reason } + } + return { kind: 'connecting' } +} + +/** + * Keeps a remote desktop tab connected: when its page has no session on this computer (the + * sandbox slept and its forward closed, or Orca restarted) and the sandbox is up, it opens the + * desktop again and reloads the page onto the new forward, a few times at most per outage. + */ +export function useCloudDesktopConnection({ + enabled, + worktreeId, + browserPageId, + url, + reload, + navigate +}: { + enabled: boolean + worktreeId: string + browserPageId: string + url: string + reload: () => void + navigate: (url: string) => void +}): { phase: CloudDesktopPhase; reconnect: () => void } { + const view = useCloudWorkspaceView(enabled ? worktreeId : '') + const page = useRemoteDesktopPageState(browserPageId) + const [attempt, setAttempt] = useState({ status: 'idle', tries: 0 }) + const latest = useRef({ url, reload, navigate }) + latest.current = { url, reload, navigate } + const inFlight = useRef(false) + + const run = useCallback( + async (tries: number): Promise => { + if (inFlight.current) { + return + } + inFlight.current = true + setAttempt({ status: 'running', tries }) + try { + const environmentId = selectWorkspaceRuntimeEnvironmentId( + useAppStore.getState(), + worktreeId + ) + const result = environmentId + ? await requestCloudRemoteDesktop(environmentId) + : ({ ok: false, code: 'not_cloud' } as const) + if (!result.ok) { + if (result.code === 'not_running' || result.code === 'starting') { + void refreshCloudWorkspaceStatus(worktreeId) + } + setAttempt({ status: 'failed', tries, code: result.code }) + return + } + // Same forward port: reload so the page picks up the new session; else move the tab to it. + if (result.url === latest.current.url) { + latest.current.reload() + } else { + latest.current.navigate(result.url) + } + setAttempt({ status: 'idle', tries }) + } finally { + inFlight.current = false + } + }, + [worktreeId] + ) + + const sandboxUp = !view.isCloud || view.state === 'running' || view.state === 'unknown' + const needsSession = desktopNeedsSession(page) + const connected = page?.connection === 'connected' + + // A connected page, or a sandbox that went down and came back, starts the budget over. + useEffect(() => { + if (connected || !sandboxUp) { + setAttempt((current) => (current.tries === 0 ? current : { status: 'idle', tries: 0 })) + } + }, [connected, sandboxUp]) + + useEffect(() => { + if (!enabled || !view.isCloud || !sandboxUp || !needsSession) { + return + } + if (attempt.status === 'running' || attempt.tries >= MAX_AUTO_ATTEMPTS) { + return + } + const timer = setTimeout( + () => void run(attempt.tries + 1), + AUTO_RETRY_DELAYS_MS[attempt.tries] ?? 6_000 + ) + return () => clearTimeout(timer) + }, [enabled, view.isCloud, sandboxUp, needsSession, attempt, run]) + + const reconnect = useCallback(() => { + // A person asked: start over, and reopen even a page main still holds a session for. + void run(1) + }, [run]) + + return { + phase: deriveCloudDesktopPhase({ + isCloud: view.isCloud, + sandbox: view.state, + page, + attempt + }), + reconnect + } +} diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts index f06ef5cc4cf..ad0c8a95283 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts @@ -1,4 +1,5 @@ -export type VmEnvironmentCheckDecision = 'open-anyway' | 'retry' | 'cancel' +/** `restart`: delete this sandbox and start the create over on a fresh one. */ +export type VmEnvironmentCheckDecision = 'open-anyway' | 'retry' | 'restart' | 'cancel' // Dependency-free so the pending-creation store can stop a VM build's checks when the user dismisses it. const waiting = new Map void>() @@ -23,6 +24,11 @@ export function awaitVmEnvironmentCheckDecision( }) } +/** True while a paused create is waiting on the user (false once it gave up on its own). */ +export function isAwaitingVmEnvironmentCheckDecision(creationId: string): boolean { + return waiting.has(creationId) +} + export function resolveVmEnvironmentCheckDecision( creationId: string, decision: VmEnvironmentCheckDecision diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts new file mode 100644 index 00000000000..e409bbeb535 --- /dev/null +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { EnvironmentDoctorCheck } from '../../../shared/environment-doctor-types' +import { triageCloudEnvironmentChecks } from './ephemeral-vm-environment-check-triage' + +const c = ( + id: string, + status: EnvironmentDoctorCheck['status'], + category: EnvironmentDoctorCheck['category'] = 'tools' +): EnvironmentDoctorCheck => ({ id, category, status, message: id }) + +describe('triageCloudEnvironmentChecks', () => { + it('stops only on a sandbox nobody can work in', () => { + const { fatal } = triageCloudEnvironmentChecks( + [ + c('environment.doctor', 'fail', 'workspace'), + c('workspace.path', 'fail', 'workspace'), + c('git.repo', 'fail', 'git'), + c('tool.git', 'fail'), + c('git.push', 'fail', 'git'), + c('git.fetch', 'fail', 'git'), + c('tool.pnpm', 'fail'), + c('disk.free', 'fail', 'disk') + ], + { setupRunsOnCreate: true } + ) + expect(fatal.map((check) => check.id)).toEqual([ + 'environment.doctor', + 'workspace.path', + 'git.repo', + 'tool.git' + ]) + }) + + it('drops agent sign-in, advice, and passes; keeps push, setup and the rest as notices', () => { + const { fatal, notices } = triageCloudEnvironmentChecks( + [ + c('tool.git', 'pass'), + c('agent.claude', 'warn', 'agents'), + c('agent.cli', 'warn', 'agents'), + c('git.push', 'fail', 'git'), + c('setup.run', 'warn', 'setup'), + c('setup.script', 'warn', 'setup'), + c('git.remote', 'warn', 'git'), + c('disk.free', 'warn', 'disk') + ], + { setupRunsOnCreate: false } + ) + expect(fatal).toEqual([]) + expect(notices.map((notice) => [notice.id, notice.kind])).toEqual([ + ['git.push', 'push'], + ['setup.run', 'setup'], + ['disk.free', 'check'] + ]) + }) + + it('says nothing about a setup script the create is about to run, or a push with no commits', () => { + const { notices } = triageCloudEnvironmentChecks( + [c('setup.run', 'warn', 'setup'), c('git.push', 'warn', 'git')], + { setupRunsOnCreate: true } + ) + expect(notices).toEqual([]) + }) +}) diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts new file mode 100644 index 00000000000..c2e64885036 --- /dev/null +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts @@ -0,0 +1,84 @@ +// Which environment-check results stop an Orca Cloud create, and which only become a notice in the +// opened workspace. Peers (Conductor, Capy, Codex, Cursor) open the workspace and surface problems +// there; only a sandbox nobody can work in should hold the create on the build sheet. +import type { EnvironmentDoctorCheck } from '../../../shared/environment-doctor-types' + +/** Failed checks that make the sandbox unusable: no checkout, no git, or orcad never answered. */ +const FATAL_CHECK_IDS: ReadonlySet = new Set([ + // The doctor call itself could not finish: orcad is unreachable. + 'environment.doctor', + // The repository isn't where the workspace would open. + 'workspace.path', + // Git can't read the checkout. + 'git.repo', + 'tool.git' +]) + +export type CloudSetupNoticeKind = 'push' | 'setup' | 'check' + +/** One problem the opened workspace shows as a single dismissible line. */ +export type CloudSetupNotice = { + /** Stable per problem, so a dismissal or a re-check replaces the same line. */ + id: string + kind: CloudSetupNoticeKind + check: EnvironmentDoctorCheck +} + +export type CloudEnvironmentCheckTriage = { + /** Fatal failures: the create waits on the user (and the sandbox sleeps if they don't come back). */ + fatal: EnvironmentDoctorCheck[] + /** Everything else worth one line in the opened workspace. */ + notices: CloudSetupNotice[] +} + +export function isFatalEnvironmentCheck(check: EnvironmentDoctorCheck): boolean { + return check.status === 'fail' && FATAL_CHECK_IDS.has(check.id) +} + +/** + * Splits an Orca Cloud doctor result. Agent sign-in is never a check here: the account's agent row + * and the in-workspace sign-in strip own it. A setup script the create is about to run is not news. + */ +export function triageCloudEnvironmentChecks( + checks: readonly EnvironmentDoctorCheck[], + options: { setupRunsOnCreate: boolean } +): CloudEnvironmentCheckTriage { + const fatal: EnvironmentDoctorCheck[] = [] + const notices: CloudSetupNotice[] = [] + for (const check of checks) { + if (check.status === 'pass') { + continue + } + if (isFatalEnvironmentCheck(check)) { + fatal.push(check) + continue + } + const kind = noticeKind(check, options) + if (kind) { + notices.push({ id: check.id, kind, check }) + } + } + return { fatal, notices } +} + +function noticeKind( + check: EnvironmentDoctorCheck, + options: { setupRunsOnCreate: boolean } +): CloudSetupNoticeKind | null { + if (check.category === 'agents') { + return null + } + switch (check.id) { + case 'git.push': + // "No commits yet" is a warn with nothing to do; only a refused push needs access. + return check.status === 'fail' ? 'push' : null + case 'setup.run': + return options.setupRunsOnCreate ? null : 'setup' + // Advice for the repository, not a problem with this workspace. + case 'setup.script': + case 'git.remote': + return null + default: + return 'check' + } +} diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts b/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts index b4af3b7f4c9..56e777f5421 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts @@ -1,7 +1,17 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type Entry = { + environmentCheck?: { + status: string + checks?: { id: string }[] + sleepsAt?: number + finishedAt?: number + sandbox?: string + } +} const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { - const entries: Record = {} + const entries: Record = {} return { callRuntimeRpc: vi.fn(), supportsCapability: vi.fn(async () => true), @@ -9,6 +19,7 @@ const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { entries, getState: () => ({ pendingWorktreeCreations: entries, + activePendingCreationId: 'c1', updatePendingWorktreeCreation: (id: string, patch: Record) => { if (entries[id]) { Object.assign(entries[id], patch) @@ -26,11 +37,19 @@ vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ runtimeEnvironmentSupportsCapability: supportsCapability })) -import { gateVmCreateOnEnvironmentCheck } from './ephemeral-vm-environment-check' +import { + BLOCKED_SANDBOX_SLEEP_MS, + gateVmCreateOnEnvironmentCheck, + type CloudEnvironmentCheckContext +} from './ephemeral-vm-environment-check' import { cancelVmEnvironmentCheck, resolveVmEnvironmentCheckDecision } from './ephemeral-vm-environment-check-decision' +import { + getCloudSetupNoticesRecord, + resetCloudSetupNotices +} from './orca-cloud/cloud-setup-notices-store' const failing = { worktreePath: '/w', @@ -38,6 +57,31 @@ const failing = { checks: [{ id: 'tool.pnpm', category: 'tools', status: 'fail', message: 'pnpm missing' }] } const passing = { worktreePath: '/w', ok: true, checks: [] } +// What Neil saw: agents not set up, push refused, setup not run. None of it should stop the create. +const cloudWarnings = { + worktreePath: '/w', + ok: false, + checks: [ + { id: 'agent.claude', category: 'agents', status: 'warn', message: 'Claude signed out' }, + { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' }, + { id: 'setup.run', category: 'setup', status: 'warn', message: 'not run', code: 'setupNotRun' } + ] +} +const cloudFatal = { + worktreePath: '/w', + ok: false, + checks: [ + { id: 'workspace.path', category: 'workspace', status: 'fail', message: 'no repo' }, + { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' } + ] +} +const CLOUD: CloudEnvironmentCheckContext = { + runtimeId: 'rt-1', + setupRunsOnCreate: false, + repoId: 'repo-1', + hostId: 'runtime:env-1', + repoUrl: 'https://github.com/stablyai/orca' +} async function settle(): Promise { for (let i = 0; i < 10; i++) { @@ -53,6 +97,11 @@ describe('gateVmCreateOnEnvironmentCheck', () => { store.entries.c1 = {} callRuntimeRpc.mockReset() supportsCapability.mockResolvedValue(true) + resetCloudSetupNotices() + }) + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() }) it('pauses on failed checks, re-runs them on retry, and continues once they pass', async () => { @@ -62,7 +111,7 @@ describe('gateVmCreateOnEnvironmentCheck', () => { expect(store.entries.c1.environmentCheck?.status).toBe('failed') resolveVmEnvironmentCheckDecision('c1', 'retry') - await expect(gate).resolves.toBe(true) + await expect(gate).resolves.toBe('proceed') expect(callRuntimeRpc).toHaveBeenCalledTimes(2) expect(store.entries.c1.environmentCheck?.status).toBe('passed') }) @@ -72,13 +121,13 @@ describe('gateVmCreateOnEnvironmentCheck', () => { const opened = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') await settle() resolveVmEnvironmentCheckDecision('c1', 'open-anyway') - await expect(opened).resolves.toBe(true) + await expect(opened).resolves.toBe('proceed') const dismissed = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') await settle() delete store.entries.c1 cancelVmEnvironmentCheck('c1') - await expect(dismissed).resolves.toBe(false) + await expect(dismissed).resolves.toBe('stop') }) it('aborts a running check when the build is dismissed', async () => { @@ -94,14 +143,71 @@ describe('gateVmCreateOnEnvironmentCheck', () => { await settle() delete store.entries.c1 cancelVmEnvironmentCheck('c1') - await expect(gate).resolves.toBe(false) + await expect(gate).resolves.toBe('stop') expect(signal?.aborted).toBe(true) }) it('skips the checks on a VM server that predates them', async () => { supportsCapability.mockResolvedValue(false) - await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w')).resolves.toBe(true) + await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w')).resolves.toBe('proceed') expect(callRuntimeRpc).not.toHaveBeenCalled() expect(store.entries.c1.environmentCheck?.status).toBe('skipped') }) + + it('Orca Cloud opens on warnings and a refused push, and hands them to the workspace', async () => { + callRuntimeRpc.mockResolvedValue(cloudWarnings) + await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD)).resolves.toBe( + 'proceed' + ) + expect(store.entries.c1.environmentCheck?.status).toBe('passed') + const record = getCloudSetupNoticesRecord('env-1') + expect(record?.repoUrl).toBe('https://github.com/stablyai/orca') + // Agent sign-in is never a notice; push and setup are. + expect(record?.notices.map((notice) => notice.kind)).toEqual(['push', 'setup']) + }) + + it('Orca Cloud stops only on a fatal check, lists just it, and can start over', async () => { + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await settle() + const check = store.entries.c1.environmentCheck + expect(check?.status).toBe('failed') + expect(check?.checks?.map((c) => c.id)).toEqual(['workspace.path']) + expect(check?.sleepsAt).toBe((check?.finishedAt ?? 0) + BLOCKED_SANDBOX_SLEEP_MS) + + resolveVmEnvironmentCheckDecision('c1', 'restart') + await expect(gate).resolves.toBe('restart') + }) + + it('puts a blocked sandbox to sleep after five unused minutes', async () => { + vi.useFakeTimers() + const suspendRuntime = vi.fn(async () => ({ ok: true })) + vi.stubGlobal('window', { api: { ephemeralVm: { suspendRuntime } } }) + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await vi.advanceTimersByTimeAsync(0) + expect(store.entries.c1.environmentCheck?.status).toBe('failed') + + await vi.advanceTimersByTimeAsync(BLOCKED_SANDBOX_SLEEP_MS - 1) + expect(suspendRuntime).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(suspendRuntime).toHaveBeenCalledWith({ runtimeId: 'rt-1' }) + expect(store.entries.c1.environmentCheck?.sandbox).toBe('asleep') + + // Still waiting on the user: Delete or Start again. + cancelVmEnvironmentCheck('c1') + await expect(gate).resolves.toBe('stop') + }) + + it('deletes a blocked sandbox that cannot sleep, so it never keeps billing', async () => { + vi.useFakeTimers() + const suspendRuntime = vi.fn(async () => ({ ok: false, error: 'nope' })) + vi.stubGlobal('window', { api: { ephemeralVm: { suspendRuntime } } }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await vi.advanceTimersByTimeAsync(BLOCKED_SANDBOX_SLEEP_MS) + await expect(gate).resolves.toBe('stop') + expect(store.entries.c1.environmentCheck?.sandbox).toBe('deleted') + }) }) diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.ts b/src/renderer/src/lib/ephemeral-vm-environment-check.ts index 6e1738935c1..91f4a2c00a5 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check.ts @@ -7,6 +7,7 @@ import type { EnvironmentDoctorCheck, EnvironmentDoctorResult } from '../../../shared/environment-doctor-types' +import type { ExecutionHostId } from '../../../shared/execution-host' import { ENVIRONMENT_DOCTOR_METHOD, ENVIRONMENT_DOCTOR_RUNTIME_CAPABILITY @@ -14,13 +15,31 @@ import { import { awaitVmEnvironmentCheckDecision, beginVmEnvironmentCheckRun, - endVmEnvironmentCheckRun + endVmEnvironmentCheckRun, + resolveVmEnvironmentCheckDecision, + type VmEnvironmentCheckDecision } from './ephemeral-vm-environment-check-decision' +import { triageCloudEnvironmentChecks } from './ephemeral-vm-environment-check-triage' +import { setCloudSetupNotices } from './orca-cloud/cloud-setup-notices-store' // Two 20s network probes, local probes and a login-shell PATH refresh, with headroom for a slow VM. const ENVIRONMENT_CHECK_TIMEOUT_MS = 150_000 // A paused build holds a running VM; give up after an hour so a forgotten one stops billing. const PAUSE_TIMEOUT_MS = 60 * 60_000 +/** Orca Cloud: a create stopped on a fatal check puts its sandbox to sleep after this long unused. */ +export const BLOCKED_SANDBOX_SLEEP_MS = 5 * 60_000 + +/** What the Orca Cloud gate needs beyond the VM: who to show notices to, and what runs on create. */ +export type CloudEnvironmentCheckContext = { + runtimeId: string | undefined + /** The create runs the setup script itself, so "hasn't run yet" is not news. */ + setupRunsOnCreate: boolean + repoId: string | null + hostId: ExecutionHostId | null + repoUrl: string | null +} + +export type VmEnvironmentCheckGateResult = 'proceed' | 'stop' | 'restart' async function supportsEnvironmentChecks(environmentId: string): Promise { try { @@ -35,18 +54,26 @@ async function supportsEnvironmentChecks(environmentId: string): Promise { - const signal = beginVmEnvironmentCheckRun(creationId) + const signal = creationId ? beginVmEnvironmentCheckRun(creationId) : undefined try { + // Dev builds only: lets a real create exercise the unreachable-sandbox stop (and its sleep). + if ( + import.meta.env.DEV && + typeof localStorage !== 'undefined' && + localStorage.getItem('orca:dev:envCheckFault') === 'unreachable' + ) { + throw new Error('Simulated unreachable sandbox (orca:dev:envCheckFault).') + } return await callRuntimeRpc( { kind: 'environment', environmentId }, ENVIRONMENT_DOCTOR_METHOD, { path }, - { timeoutMs: ENVIRONMENT_CHECK_TIMEOUT_MS, signal } + { timeoutMs: ENVIRONMENT_CHECK_TIMEOUT_MS, ...(signal ? { signal } : {}) } ) } catch (error) { const unreachable: EnvironmentDoctorCheck = { @@ -61,15 +88,12 @@ async function runVmEnvironmentCheck( } return { worktreePath: path, ok: false, checks: [unreachable] } } finally { - endVmEnvironmentCheckRun(creationId, signal) + if (creationId && signal) { + endVmEnvironmentCheckRun(creationId, signal) + } } } -/** - * Check the freshly provisioned VM before creating the workspace. A failure pauses the create on the - * build sheet; it resolves true to continue (passed, unsupported, or "Open anyway") and false to cancel. - * Nothing here tears the VM down: only cancelling does, so a degraded open keeps the VM that provisioned. - */ /** The user decided: fold the wait into pausedMs so the clock resumes where it stopped. */ export function resumeBuildClock(creationId: string, now = Date.now()): void { const state = useAppStore.getState() @@ -84,31 +108,94 @@ export function resumeBuildClock(creationId: string, now = Date.now()): void { }) } +/** + * After BLOCKED_SANDBOX_SLEEP_MS unused, a blocked create's sandbox sleeps. No workspace owns it yet, + * so the window's idle sleep never would. If it can't sleep, it is deleted: it must not keep billing. + */ +function scheduleBlockedSandboxSleep( + creationId: string, + runtimeId: string | undefined, + failedAt: number +): () => void { + const timer = setTimeout(() => { + const state = useAppStore.getState() + const entry = state.pendingWorktreeCreations[creationId] + const check = entry?.environmentCheck + if (check?.status !== 'failed' || check.finishedAt !== failedAt || check.sandbox) { + return + } + const mark = (sandbox: 'sleeping' | 'asleep' | 'deleted'): void => { + const current = useAppStore.getState().pendingWorktreeCreations[creationId]?.environmentCheck + if (current?.status === 'failed' && current.finishedAt === failedAt) { + useAppStore.getState().updatePendingWorktreeCreation(creationId, { + environmentCheck: { ...current, sandbox } + }) + } + } + const suspend = runtimeId ? window.api?.ephemeralVm?.suspendRuntime : undefined + if (!suspend || !runtimeId) { + mark('deleted') + resolveVmEnvironmentCheckDecision(creationId, 'cancel') + return + } + mark('sleeping') + void suspend({ runtimeId }) + .catch((error: unknown) => ({ + ok: false, + error: error instanceof Error ? error.message : String(error) + })) + .then((result) => { + if (result.ok) { + mark('asleep') + return + } + console.warn('[orca-cloud] Could not put a blocked sandbox to sleep:', result.error) + mark('deleted') + resolveVmEnvironmentCheckDecision(creationId, 'cancel') + }) + }, BLOCKED_SANDBOX_SLEEP_MS) + return () => clearTimeout(timer) +} + +/** + * Check the freshly provisioned VM before creating the workspace. Orca Cloud stops only on a fatal + * check (no checkout, no git, orcad unreachable); everything else opens the workspace and shows + * there as a notice. Recipe VMs pause on any failed check. Resolves `proceed` to continue (passed, + * unsupported, or "Open anyway"), `stop` to cancel, `restart` to cancel and start on a new sandbox. + * Nothing here tears the VM down: only the caller does, so a degraded open keeps the VM. + */ export async function gateVmCreateOnEnvironmentCheck( creationId: string, environmentId: string, - path: string -): Promise { + path: string, + cloud?: CloudEnvironmentCheckContext +): Promise { const update = useAppStore.getState().updatePendingWorktreeCreation const isPending = (): boolean => Boolean(useAppStore.getState().pendingWorktreeCreations[creationId]) if (!(await supportsEnvironmentChecks(environmentId))) { const at = Date.now() update(creationId, { environmentCheck: { status: 'skipped', startedAt: at, finishedAt: at } }) - return isPending() + return isPending() ? 'proceed' : 'stop' } for (;;) { // A dismiss during the probe or the previous pause registered nothing to abort. if (!isPending()) { - return false + return 'stop' } const startedAt = Date.now() update(creationId, { environmentCheck: { status: 'running', startedAt } }) const result = await runVmEnvironmentCheck(creationId, environmentId, path) if (!isPending()) { - return false + return 'stop' } - if (result.ok) { + const triage = cloud + ? triageCloudEnvironmentChecks(result.checks, { + setupRunsOnCreate: cloud.setupRunsOnCreate + }) + : null + const blocking = triage ? triage.fatal.length > 0 : !result.ok + if (!blocking) { update(creationId, { environmentCheck: { status: 'passed', @@ -117,32 +204,64 @@ export async function gateVmCreateOnEnvironmentCheck( finishedAt: Date.now() } }) - return true + if (cloud && triage) { + setCloudSetupNotices({ + environmentId, + path: result.worktreePath || path, + repoId: cloud.repoId, + hostId: cloud.hostId, + repoUrl: cloud.repoUrl, + notices: triage.notices + }) + } + return 'proceed' } const failedAt = Date.now() update(creationId, { environmentCheck: { status: 'failed', - checks: result.checks, + // Orca Cloud lists only what stopped it; the rest would show in the workspace. + checks: triage ? triage.fatal : result.checks, startedAt, - finishedAt: failedAt + finishedAt: failedAt, + ...(cloud ? { sleepsAt: failedAt + BLOCKED_SANDBOX_SLEEP_MS } : {}) }, waitingSince: failedAt }) if (useAppStore.getState().activePendingCreationId !== creationId) { // The paused build keeps its VM running, so a background create must say it needs the user. toast.error( - translate( - 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailed', - 'Environment checks failed for a new VM workspace. Open it in the sidebar to continue.' - ) + cloud + ? translate( + 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailedCloud', + 'A new cloud workspace couldn’t start. Open it in the sidebar to continue.' + ) + : translate( + 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailed', + 'Environment checks failed for a new VM workspace. Open it in the sidebar to continue.' + ) ) } - const decision = await awaitVmEnvironmentCheckDecision(creationId, PAUSE_TIMEOUT_MS) + const cancelSleep = cloud + ? scheduleBlockedSandboxSleep(creationId, cloud.runtimeId, failedAt) + : () => {} + let decision: VmEnvironmentCheckDecision + try { + // Orca Cloud has its own (shorter) sleep; recipe VMs give up after an hour. + decision = await awaitVmEnvironmentCheckDecision( + creationId, + cloud ? undefined : PAUSE_TIMEOUT_MS + ) + } finally { + cancelSleep() + } if (decision === 'cancel' || !isPending()) { - return false + return 'stop' } resumeBuildClock(creationId) + if (decision === 'restart') { + return 'restart' + } if (decision === 'open-anyway') { toast.warning( translate( @@ -150,7 +269,7 @@ export async function gateVmCreateOnEnvironmentCheck( 'Creating the workspace on a VM whose environment checks failed.' ) ) - return true + return 'proceed' } } } diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index a4b0b3399c1..2b8adf0d2b2 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -7,6 +7,7 @@ import type { Repo } from '../../../shared/repo-types' import { translate } from '@/i18n/i18n' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { gateVmCreateOnEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' +import { orcaCloudGitHubRepoUrl } from '@/lib/orca-cloud/use-orca-cloud-repo-access' import { showVmBuildFailureToast } from '@/components/worktree-creation/vm-build-failure-toast' import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' @@ -75,8 +76,10 @@ async function prepareEphemeralVmRecipeRequest( const displayName = useAppStore.getState().projects.find((project) => project.id === args.projectId) ?.displayName ?? sourceRepo?.displayName + // Why: the user picked an existing project; the VM's checkout joining it is not a new project. const setup = await store.setupProjectExistingFolder( - displayName ? { ...args, displayName } : args + displayName ? { ...args, displayName } : args, + { quiet: true } ) if (setup) { // Why: until the create adopts it, the VM's primary checkout is not a workspace; the pending row stands for it. @@ -147,16 +150,35 @@ async function prepareEphemeralVmRecipeRequest( path: preparedTarget.setup.repo.path } } - const proceed = - Boolean(useAppStore.getState().pendingWorktreeCreations[creationId]) && - (!preparedTarget.environmentId || - (await gateVmCreateOnEnvironmentCheck( - creationId, - preparedTarget.environmentId, - preparedTarget.setup.repo.path - ))) - if (!proceed) { + const gate = !useAppStore.getState().pendingWorktreeCreations[creationId] + ? 'stop' + : !preparedTarget.environmentId + ? 'proceed' + : await gateVmCreateOnEnvironmentCheck( + creationId, + preparedTarget.environmentId, + preparedTarget.setup.repo.path, + recipe.provider === 'orca-cloud' + ? { + runtimeId: preparedTarget.runtimeId, + // `inherit` follows the project's setup policy, which runs it on create. + setupRunsOnCreate: request.setupDecision !== 'skip', + repoId: preparedTarget.setup.repo.id, + hostId: preparedTarget.setup.setup.hostId, + repoUrl: orcaCloudGitHubRepoUrl( + useAppStore.getState().repos.find((repo) => repo.id === recipe.sourceRepoId) + ) + } + : undefined + ) + if (gate !== 'proceed') { await cleanupEphemeralVmRuntimeForFailedCreate(preparedRequest, creationId) + if (gate === 'restart' && useAppStore.getState().pendingWorktreeCreations[creationId]) { + // Lazy: the creation flow imports this module. + const { retryBackgroundWorktreeCreation } = + await import('@/lib/workspace/creation/worktree-creation-flow') + retryBackgroundWorktreeCreation(creationId) + } return null } useAppStore.getState().updatePendingWorktreeCreation(creationId, { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts new file mode 100644 index 00000000000..58f77c8342b --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts @@ -0,0 +1,118 @@ +// What the in-workspace setup notices do: install the GitHub App so a read-only repository can +// push (then re-check on their own once GitHub's install webhook binds it), and run a setup script +// the create skipped. +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' +import { runVmEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' +import { cloudWorkspaceApi } from './orca-cloud-workspace-store' +import { + fetchOrcaCloudRepoAccess, + invalidateOrcaCloudRepoAccess +} from './use-orca-cloud-repo-access' +import { + dismissCloudSetupNotice, + getCloudSetupNoticesRecord, + setCloudSetupNotices, + type CloudSetupNoticesRecord +} from './cloud-setup-notices-store' + +/** owner/repo from https://github.com//. */ +export function repoSlug(repoUrl: string): string { + return repoUrl.replace(/^https:\/\/github\.com\//, '') +} + +export function repoOwner(repoUrl: string): string { + return repoSlug(repoUrl).split('/')[0] ?? '' +} + +/** GitHub's install page, preselecting this repository (#246). False when it couldn't open. */ +export async function openOrcaGitHubAppInstall(repoUrl: string): Promise { + const result = await cloudWorkspaceApi() + ?.connectGitHub({ repoUrl }) + .catch(() => null) + if (!result?.ok) { + toast.error( + translate( + 'orcaCloud.setupNotices.installFailed', + 'Couldn’t open GitHub. Check your connection and try again.' + ) + ) + return false + } + return true +} + +/** + * Once the App's installation covers the repository (the install webhook bound it), runs the + * sandbox's push check again and drops the notice when the push is now authorized. Returns + * 'granted' when the push works, 'waiting' while GitHub hasn't confirmed yet, 'refused' when the + * installation landed but the sandbox still can't push. + */ +export async function recheckCloudPushAccess( + environmentId: string +): Promise<'granted' | 'waiting' | 'refused'> { + const record = getCloudSetupNoticesRecord(environmentId) + if (!record?.repoUrl || !record.notices.some((notice) => notice.kind === 'push')) { + return 'granted' + } + invalidateOrcaCloudRepoAccess(record.repoUrl) + const access = await fetchOrcaCloudRepoAccess(record.repoUrl, { force: true }) + if (access?.access !== 'granted') { + return 'waiting' + } + const result = await runVmEnvironmentCheck(null, environmentId, record.path) + const push = result.checks.find((check) => check.id === 'git.push') + const current = getCloudSetupNoticesRecord(environmentId) + if (!push || push.status === 'fail') { + return 'refused' + } + if (current) { + setCloudSetupNotices({ + ...current, + notices: current.notices.filter((notice) => notice.kind !== 'push') + }) + } + toast.success( + translate('orcaCloud.setupNotices.pushReady', 'Orca Cloud can push to {{repo}} now.', { + repo: repoSlug(record.repoUrl) + }) + ) + return 'granted' +} + +/** + * Runs the project's setup script in a new "Setup" terminal of the workspace, as a create with + * setup on would have. The script is read from the sandbox's own orca.yaml, never from here. + */ +export async function runCloudSetupScript( + workspaceId: string, + record: Pick, + noticeId: string +): Promise { + let script: string | undefined + try { + if (record.hostId && record.repoId) { + const hooks = await checkRuntimeHooks(record.hostId, record.repoId) + script = hooks.hooks?.scripts?.setup?.trim() || undefined + } + } catch (error) { + console.warn('[orca-cloud] Could not read the setup script:', error) + } + if (!script) { + toast.error( + translate( + 'orcaCloud.setupNotices.setupMissing', + 'Couldn’t read the setup script from orca.yaml in this workspace.' + ) + ) + return + } + const store = useAppStore.getState() + const tab = store.createTab(workspaceId, undefined, undefined, { + pendingStartup: { command: script } + }) + store.setTabCustomTitle(tab.id, translate('worktree.setupTerminalTitle', 'Setup')) + dismissCloudSetupNotice(record.environmentId, noticeId) +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts new file mode 100644 index 00000000000..4392295ab9c --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts @@ -0,0 +1,97 @@ +// Non-fatal environment-check results for an opened Orca Cloud workspace, keyed by the sandbox's +// runtime environment. The build sheet no longer stops on them (env-check-ux); the workspace shows +// each as one dismissible line with one action. Session-only: a restart re-checks nothing, and +// what was worth saying once is not re-raised. +import { useSyncExternalStore } from 'react' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { CloudSetupNotice } from '../ephemeral-vm-environment-check-triage' + +export type CloudSetupNoticesRecord = { + environmentId: string + /** The checkout the doctor ran on, for re-checks. */ + path: string + repoId: string | null + hostId: ExecutionHostId | null + /** https://github.com//, or null when the project isn't on GitHub. */ + repoUrl: string | null + notices: readonly CloudSetupNotice[] +} + +type Snapshot = { + records: Readonly> + dismissed: ReadonlySet +} + +let snapshot: Snapshot = { records: {}, dismissed: new Set() } +const listeners = new Set<() => void>() + +function emit(next: Snapshot): void { + snapshot = next + for (const listener of listeners) { + listener() + } +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +function dismissalKey(environmentId: string, noticeId: string): string { + return `${environmentId}\0${noticeId}` +} + +/** Replaces what an environment shows; an empty list clears it. */ +export function setCloudSetupNotices(record: CloudSetupNoticesRecord): void { + const records = { ...snapshot.records } + if (record.notices.length === 0) { + delete records[record.environmentId] + } else { + records[record.environmentId] = record + } + emit({ ...snapshot, records }) +} + +export function dismissCloudSetupNotice(environmentId: string, noticeId: string): void { + const dismissed = new Set(snapshot.dismissed) + dismissed.add(dismissalKey(environmentId, noticeId)) + emit({ ...snapshot, dismissed }) +} + +export function getCloudSetupNoticesRecord( + environmentId: string +): CloudSetupNoticesRecord | undefined { + return snapshot.records[environmentId] +} + +/** Visible notices first by importance: push access, then setup, then the rest. */ +export function visibleCloudSetupNotices( + state: Snapshot, + environmentId: string | undefined +): readonly CloudSetupNotice[] { + const record = environmentId ? state.records[environmentId] : undefined + if (!record) { + return [] + } + const order = { push: 0, setup: 1, check: 2 } as const + return record.notices + .filter((notice) => !state.dismissed.has(dismissalKey(record.environmentId, notice.id))) + .slice() + .sort((a, b) => order[a.kind] - order[b.kind]) +} + +export function useCloudSetupNoticesSnapshot(): Snapshot { + return useSyncExternalStore(subscribe, () => snapshot) +} + +/** Test seam. */ +export function resetCloudSetupNotices(): void { + emit({ records: {}, dismissed: new Set() }) +} + +// Dev builds: drive the notices from CDP (as `__store` is), e.g. to show one a repo can't produce. +if (import.meta.env.DEV && typeof window !== 'undefined') { + Object.assign(window, { + __cloudSetupNotices: { get: getCloudSetupNoticesRecord, set: setCloudSetupNotices } + }) +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts new file mode 100644 index 00000000000..1a927a81feb --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts @@ -0,0 +1,98 @@ +// The full-page "Set up Orca Cloud" view (composer-redo): Start in the composer closes the dialog +// and opens this page when the account isn't ready yet. The page walks the missing steps, then +// starts the saved prompt. One request at a time; a new Start replaces an older one. +import { useSyncExternalStore } from 'react' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import type { ComposerModalData } from '@/components/new-workspace/composer-modal-data' +import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' +import { e2eConfig } from '@/lib/e2e-config' + +export type CloudSetupPageRequest = { + prompt: string + repoId: string + agent: string | null + /** What main reported when Start was pressed; the page upgrades it once sign-in lands. */ + availability: OrcaCloudAvailability + /** D4: a GitHub repository with no clone here; the start goes through the composer visibly. */ + cloudOnlyRepo: string | null + /** The composer as it was: Back and the auto-start reopen it with everything kept. */ + composer: ComposerModalData + /** + * Dev and e2e only: pins the account's billing answer so every step can be walked against the + * real page (dev sign-in has no billing). Never set by the app. + */ + debugAccess?: OrcaCloudRunTargetAccess + openedAt: number +} + +let current: CloudSetupPageRequest | null = null +const listeners = new Set<() => void>() + +function emit(): void { + for (const listener of listeners) { + listener() + } +} + +export function openCloudSetupPage(request: Omit): void { + current = { ...request, openedAt: Date.now() } + emit() +} + +export function closeCloudSetupPage(): void { + if (current === null) { + return + } + current = null + emit() +} + +export function getCloudSetupPageRequest(): CloudSetupPageRequest | null { + return current +} + +export function useCloudSetupPageRequest(): CloudSetupPageRequest | null { + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => current + ) +} + +const AGENT_SKIP_KEY = 'orca.cloudSetup.agentSkipped.v1' + +/** "Skip for now" on the agent step is remembered, so a ready account isn't asked on every Start. */ +export function isCloudSetupAgentSkipped(agent: string | null): boolean { + if (!agent || typeof localStorage === 'undefined') { + return false + } + try { + return localStorage.getItem(`${AGENT_SKIP_KEY}:${agent}`) === '1' + } catch { + return false + } +} + +export function rememberCloudSetupAgentSkipped(agent: string | null): void { + if (!agent || typeof localStorage === 'undefined') { + return + } + try { + localStorage.setItem(`${AGENT_SKIP_KEY}:${agent}`, '1') + } catch { + // Private mode: the step asks again next time. + } +} + +// Dev and e2e: drive the page from the console or CDP (as `__store` is), e.g. to walk the trial step. +if ((import.meta.env.DEV || e2eConfig.exposeStore) && typeof window !== 'undefined') { + Object.assign(window, { + __cloudSetupPage: { + open: openCloudSetupPage, + close: closeCloudSetupPage, + get: getCloudSetupPageRequest + } + }) +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts b/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts index 3c7d04ed0e7..eecdaa6cef3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-sync-store.ts @@ -101,11 +101,16 @@ export function seedCloudSyncView(view: CloudSyncView): void { /** "Mirror to this computer…" from the workspace menu: the popover opens on the sync section. */ const focusRequests = new Set() const focusListeners = new Set<() => void>() +/** Lets the workspace menu finish closing (it hands focus back to its trigger) before the popover opens. */ +const MENU_CLOSE_SETTLE_MS = 150 + export function requestCloudSyncFocus(workspaceId: string): void { - focusRequests.add(workspaceId) - for (const listener of focusListeners) { - listener() - } + setTimeout(() => { + focusRequests.add(workspaceId) + for (const listener of focusListeners) { + listener() + } + }, MENU_CLOSE_SETTLE_MS) } export function takeCloudSyncFocus(workspaceId: string): boolean { return focusRequests.delete(workspaceId) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts index b4bfe49ebb1..123d3a760de 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts @@ -1,9 +1,11 @@ // The background clone of an Orca Cloud create, read from the provider's build-log lines -// (`[orca-cloud] cloning`, `[orca-cloud] clone-progress `, then the next phase). +// (`[orca-cloud] cloning` or `updating`, `[orca-cloud] clone-progress `, then the next phase). const PHASE_LINE = /^\[orca-cloud\] ([a-z-]+)$/ const CLONE_PROGRESS_LINE = /^\[orca-cloud\] clone-progress (\d{1,3}) (download|checkout)$/ export type OrcaCloudCloneProgress = { + /** 'update': the repo came prebuilt (an environment build) and only changes are fetched. */ + mode: 'clone' | 'update' startedAt: number | null /** The next phase began: the clone finished. */ ended: boolean @@ -26,8 +28,15 @@ export function orcaCloudCloneProgress( lines.forEach((raw, index) => { const line = raw.trim() const stamp = stamps[index] ?? null - if (line === '[orca-cloud] cloning') { - progress = { startedAt: stamp, ended: false, endedAt: null, percent: null, stage: null } + if (line === '[orca-cloud] cloning' || line === '[orca-cloud] updating') { + progress = { + mode: line.endsWith('updating') ? 'update' : 'clone', + startedAt: stamp, + ended: false, + endedAt: null, + percent: null, + stage: null + } return } if (!progress) { @@ -47,3 +56,9 @@ export function orcaCloudCloneProgress( }) return progress } + +/** The repository step's mode as announced before the create answered (`[orca-cloud] plan-clone|plan-update`). */ +export function orcaCloudPlannedRepoMode(log: string): 'clone' | 'update' | null { + const match = /^\[orca-cloud\] plan-(clone|update)$/m.exec(log) + return match ? (match[1] === 'update' ? 'update' : 'clone') : null +} diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 69555fda09f..e0857e3bf00 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -153,6 +153,10 @@ export type PendingVmEnvironmentCheck = { checks?: readonly EnvironmentDoctorCheck[] startedAt?: number finishedAt?: number + /** Orca Cloud, failed: when the unused sandbox is put to sleep so it stops spending hours. */ + sleepsAt?: number + /** Orca Cloud, failed: the sandbox after that timer (absent while it still runs). */ + sandbox?: 'sleeping' | 'asleep' | 'deleted' } /** Session-only creation status drives sidebar/panel and vanishes on reload; completed worktrees reconcile normally. request owns display fields and retry intent so they cannot drift. */ @@ -328,7 +332,9 @@ export function getCreationProgressLabel( ? null : orcaCloudCloneProgress(entry.provisioningLog ?? '', []) if (clone && !clone.ended) { - return t('auto.lib.pendingWorktreeCreation.cloningRepository', 'Cloning the repository…') + return clone.mode === 'update' + ? t('auto.lib.pendingWorktreeCreation.updatingRepository', 'Updating the repository…') + : t('auto.lib.pendingWorktreeCreation.cloningRepository', 'Cloning the repository…') } return entry.environmentCheck || clone ? t('auto.lib.pendingWorktreeCreation.preparingCloudEnvironment', 'Preparing environment…') diff --git a/src/renderer/src/store/projects/project-host-setup-actions.ts b/src/renderer/src/store/projects/project-host-setup-actions.ts index aa4833a7d3b..f70ccbd53e2 100644 --- a/src/renderer/src/store/projects/project-host-setup-actions.ts +++ b/src/renderer/src/store/projects/project-host-setup-actions.ts @@ -41,7 +41,7 @@ export function createProjectHostSetupActions( | 'setupProjectClone' > { return { - setupProjectExistingFolder: async (args) => { + setupProjectExistingFolder: async (args, options) => { try { assertNotSshProjectHost(get(), args.hostId) const target = getProjectSetupRuntimeTarget(args.hostId) @@ -94,9 +94,11 @@ export function createProjectHostSetupActions( projectHostSetups: nextSetups } }) - toast.success(translate('auto.store.slices.repos.8bb3ad7935', 'Project added'), { - description: project.displayName - }) + if (!options?.quiet) { + toast.success(translate('auto.store.slices.repos.8bb3ad7935', 'Project added'), { + description: project.displayName + }) + } return { ...result, project, repo, setup } } catch (err) { console.error('Failed to set up project on host:', err) diff --git a/src/renderer/src/store/repos/repo-state.ts b/src/renderer/src/store/repos/repo-state.ts index b4f327ed498..77c70b69c6a 100644 --- a/src/renderer/src/store/repos/repo-state.ts +++ b/src/renderer/src/store/repos/repo-state.ts @@ -203,7 +203,9 @@ export type RepoSlice = { options?: AddRepoPathOptions ) => Promise setupProjectExistingFolder: ( - args: ProjectHostSetupExistingFolderArgs + args: ProjectHostSetupExistingFolderArgs, + /** `quiet`: no "Project added" toast (a VM create registering its own checkout). */ + options?: { quiet?: boolean } ) => Promise createProjectHostSetup: ( args: ProjectHostSetupCreateArgs diff --git a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts index 327d7443bc8..66647a4a9e4 100644 --- a/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts +++ b/src/renderer/src/web/preload-api/web-cloud-workspaces-api.ts @@ -25,6 +25,11 @@ export function createWebCloudWorkspacesApi(): PreloadApi['cloudWorkspaces'] { setActive: () => Promise.resolve(), getOrgPrompts: () => Promise.resolve(NOT_CONFIGURED), putOrgPrompts: () => Promise.resolve(NOT_CONFIGURED), + teammateProfile: () => Promise.resolve(NOT_CONFIGURED), + poke: () => Promise.resolve(NOT_CONFIGURED), + pokeInbox: () => Promise.resolve(NOT_CONFIGURED), + setPokesEnabled: () => Promise.resolve(NOT_CONFIGURED), + markPokesSeen: () => Promise.resolve(NOT_CONFIGURED), onOpenLink: () => () => {}, consumePendingLink: () => Promise.resolve(null) } diff --git a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts index 0f9da6ad93f..95c98d63a81 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts @@ -53,14 +53,31 @@ export const CloudWorkspaceSchema = z.object({ memberNames: z.record(z.string(), z.string().max(80)).optional().catch(undefined), // When the last sleeping read snapshot was stored (ms), present only when the caller can open the // workspace; drives "As of" in lists without fetching the blob. Older control planes omit it. - readSnapshotAt: z.number().nullable().optional().catch(undefined) + readSnapshotAt: z.number().nullable().optional().catch(undefined), + // Started by a routine run. Home lists these only with its Routine runs filter on (routines=include). + // Older control planes omit it. + fromRoutine: z.boolean().optional().catch(undefined), + // The routine that started it, for routine runs (shown as "Routine · "). + routineName: z.string().max(200).nullable().optional().catch(undefined) }) export type CloudWorkspace = z.infer export type CloudWorkspacePresence = z.infer +/** What Home's Routine runs switch hides (counts and hours stay in the team's totals). */ +export const CloudWorkspaceRoutineRunsSchema = z.object({ + /** Routines the team has: the switch is offered only when there is at least one. */ + routines: z.number().int().min(0), + hidden: z.number().int().min(0), + hiddenRunning: z.number().int().min(0), + hiddenComputeMs: z.number().min(0) +}) +export type CloudWorkspaceRoutineRuns = z.infer + export const CloudWorkspaceListResponseSchema = z.object({ - workspaces: z.array(CloudWorkspaceSchema) + workspaces: z.array(CloudWorkspaceSchema), + // Older control planes omit it. + routineRuns: CloudWorkspaceRoutineRunsSchema.optional().catch(undefined) }) export const CloudWorkspaceResponseSchema = z.object({ workspace: CloudWorkspaceSchema }) export const CloudWorkspacePresenceResponseSchema = z.object({ @@ -131,6 +148,8 @@ export type CloudWorkspaceListQuery = { repo?: string section?: string archived?: 'exclude' | 'include' | 'only' + /** Routine runs are left out unless `include` (older control planes ignore it and leave them out). */ + routines?: 'exclude' | 'include' } export type CloudWorkspacePatch = { diff --git a/src/shared/cloud-workspaces/team-presence-wire.ts b/src/shared/cloud-workspaces/team-presence-wire.ts new file mode 100644 index 00000000000..fff3daa9535 --- /dev/null +++ b/src/shared/cloud-workspaces/team-presence-wire.ts @@ -0,0 +1,83 @@ +// Teammate profiles and Pokes wire types (sandbox control plane /v1/team/members/:id/profile, +// /v1/team/members/:id/poke, /v1/team/pokes). Mirrors cloud/apps/sandbox-control/src/team-presence.ts. +import { z } from 'zod' +import { CloudWorkspaceSchema } from './cloud-workspaces-wire' + +/** 26 full weeks, the window the profile heatmap covers (today included). */ +export const TEAMMATE_HEATMAP_DAYS = 182 +/** Most recent workspaces a profile lists (only ones the viewer can already see). */ +export const TEAMMATE_RECENT_WORKSPACES = 5 +/** One poke per sender → teammate pair per minute. */ +export const POKE_PAIR_COOLDOWN_MS = 60_000 +/** Pokes one person may send per rolling hour, across all teammates. */ +export const POKE_SENDER_HOURLY_LIMIT = 20 +/** A poke not seen within a day is dropped instead of surfacing stale on the next launch. */ +export const POKE_INBOX_TTL_MS = 24 * 60 * 60_000 + +/** Teammates get a 0–4 intensity per day; exact amounts are only ever sent to the person themself. */ +export const TeammateUsageLevelSchema = z.number().int().min(0).max(4) + +export const TeammateUsageSchema = z.object({ + /** Local calendar date (YYYY-MM-DD) of `levels[0]`; one entry per day through today. */ + start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + levels: z.array(TeammateUsageLevelSchema).max(400), + /** Days with any usage in the window. */ + activeDays: z.number().int().min(0), + /** Self only: per-day sandbox time (ms) and spend (USD micros), aligned with `levels`. */ + own: z + .object({ + computeMs: z.array(z.number().min(0)).max(400), + usdMicros: z.array(z.number().min(0)).max(400) + }) + .nullable() +}) + +export const TeammateProfileSchema = z.object({ + userId: z.string().min(1).max(128), + self: z.boolean(), + /** The member's own token name, when the control plane has seen one; the roster wins over it. */ + name: z.string().max(80).nullable(), + /** null: the teammate hasn't turned on "Pokes and activity", so their activity isn't shared. */ + usage: TeammateUsageSchema.nullable(), + recentWorkspaces: z.array(CloudWorkspaceSchema).max(20), + pokes: z.object({ + /** The viewer has Pokes turned on. */ + enabled: z.boolean(), + /** The teammate has it on (it also shares their activity); null on your own profile. */ + teammateEnabled: z.boolean().nullable() + }) +}) + +export const TeammateProfileResponseSchema = z.object({ profile: TeammateProfileSchema }) + +export const PokeSchema = z.object({ + id: z.string().regex(/^pok_[0-9a-f]{24}$/), + fromUserId: z.string().min(1).max(128), + fromName: z.string().max(80).nullable(), + at: z.number() +}) + +export const PokeInboxSchema = z.object({ + enabled: z.boolean(), + pokes: z.array(PokeSchema).max(50) +}) + +export const PokeSettingsSchema = z.object({ enabled: z.boolean() }) + +export const PokeSentSchema = z.object({ poke: z.object({ id: z.string(), at: z.number() }) }) + +export type TeammateUsage = z.infer +export type TeammateProfile = z.infer +export type Poke = z.infer +export type PokeInbox = z.infer + +/** Why a poke didn't go out; the renderer maps each to its own copy. */ +export const POKE_REFUSALS = [ + 'pokes_off', + 'teammate_pokes_off', + 'poke_cooldown', + 'poke_rate', + 'personal_account', + 'self' +] as const +export type PokeRefusal = (typeof POKE_REFUSALS)[number] diff --git a/src/shared/ephemeral-vm-recipe-runner.ts b/src/shared/ephemeral-vm-recipe-runner.ts index afb5c91554b..2146c261f41 100644 --- a/src/shared/ephemeral-vm-recipe-runner.ts +++ b/src/shared/ephemeral-vm-recipe-runner.ts @@ -25,6 +25,11 @@ export type EphemeralVmRecipeContext = { projectId?: string workspaceId?: string workspaceName?: string + /** + * One per user intent (a Create press): sent as the create's Idempotency-Key, so a re-fired start + * gets back the sandbox the first one made instead of a second one. + */ + idempotencyKey?: string repoPath: string repoUrl?: string branch?: string diff --git a/src/shared/hosted-sandbox/cloud-remote-desktop.test.ts b/src/shared/hosted-sandbox/cloud-remote-desktop.test.ts new file mode 100644 index 00000000000..db4751233ba --- /dev/null +++ b/src/shared/hosted-sandbox/cloud-remote-desktop.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { cloudRemoteDesktopUrl, isCloudRemoteDesktopUrl } from './cloud-remote-desktop' + +describe('isCloudRemoteDesktopUrl', () => { + it('recognizes the URL Orca builds for a desktop forward, on any port', () => { + expect(isCloudRemoteDesktopUrl(cloudRemoteDesktopUrl(6080, 'vnc.html'))).toBe(true) + expect(isCloudRemoteDesktopUrl(cloudRemoteDesktopUrl(51234, 'vnc.html'))).toBe(true) + }) + + it('rejects other localhost pages and anything with noVNC overrides', () => { + expect(isCloudRemoteDesktopUrl('http://localhost:6080/vnc.html')).toBe(false) + expect(isCloudRemoteDesktopUrl('http://localhost:3000/')).toBe(false) + expect( + isCloudRemoteDesktopUrl( + 'http://localhost:6080/vnc.html?autoconnect=0&reconnect=0&resize=remote&host=evil.test' + ) + ).toBe(false) + expect( + isCloudRemoteDesktopUrl( + 'http://localhost:6080/vnc.html?autoconnect=0&reconnect=0&resize=remote#port=1' + ) + ).toBe(false) + expect( + isCloudRemoteDesktopUrl( + 'https://example.com:6080/vnc.html?autoconnect=0&reconnect=0&resize=remote' + ) + ).toBe(false) + expect(isCloudRemoteDesktopUrl(null)).toBe(false) + expect(isCloudRemoteDesktopUrl('not a url')).toBe(false) + }) +}) diff --git a/src/shared/hosted-sandbox/cloud-remote-desktop.ts b/src/shared/hosted-sandbox/cloud-remote-desktop.ts index da5fba18935..b1d178382cd 100644 --- a/src/shared/hosted-sandbox/cloud-remote-desktop.ts +++ b/src/shared/hosted-sandbox/cloud-remote-desktop.ts @@ -27,6 +27,63 @@ export type CloudRemoteDesktopResult = * connect and reconnect are off because each attempt needs a ticket from Orca. */ export function cloudRemoteDesktopUrl(localPort: number, path: string): string { - const params = new URLSearchParams({ autoconnect: '0', reconnect: '0', resize: 'remote' }) - return `http://localhost:${localPort}/${path}?${params.toString()}` + return `http://localhost:${localPort}/${path}?${DESKTOP_QUERY}` +} + +const DESKTOP_QUERY = new URLSearchParams({ + autoconnect: '0', + reconnect: '0', + resize: 'remote' +}).toString() + +/** + * True for a page URL shaped like cloudRemoteDesktopUrl, whether or not this computer still + * forwards its port. For presentation and reconnects only (tab icon, chrome, asleep state): main + * alone decides which page gets tickets (remote-desktop-sessions.ts). + */ +export function isCloudRemoteDesktopUrl(url: string | null | undefined): boolean { + if (!url) { + return false + } + let parsed: URL + try { + parsed = new URL(url) + } catch { + return false + } + return ( + parsed.protocol === 'http:' && + (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1') && + parsed.port !== '' && + /^\/[\w.-]+\.html$/.test(parsed.pathname) && + parsed.search.slice(1) === DESKTOP_QUERY && + parsed.hash === '' + ) +} + +/** + * How a desktop page stands with main: `none` = no session for it on this computer (a tab restored + * after a restart, or its forward closed when the sandbox slept), then connecting, connected, or + * paused (main stopped retrying; `reason` says why). + */ +export type RemoteDesktopConnection = 'none' | 'connecting' | 'connected' | 'paused' + +export type RemoteDesktopPauseReason = + | 'asleep' + | 'archived' + | 'starting' + | 'signed_out' + | 'unavailable' + | 'failed' + +/** Main → renderer, per browser page shaped like a remote desktop (and for a page that stops being one). */ +export type RemoteDesktopPageState = { + browserPageId: string + /** The page is a remote desktop with a live session: it gets tickets and keeps the keyboard. */ + desktop: boolean + /** It has keyboard focus: Orca's shortcuts are off until the release chord. */ + captured: boolean + connection: RemoteDesktopConnection + /** Set while paused. */ + reason?: RemoteDesktopPauseReason } diff --git a/src/shared/hosted-sandbox/hosted-clone-wire.ts b/src/shared/hosted-sandbox/hosted-clone-wire.ts index 73cc47f6c73..62905e565e4 100644 --- a/src/shared/hosted-sandbox/hosted-clone-wire.ts +++ b/src/shared/hosted-sandbox/hosted-clone-wire.ts @@ -1,5 +1,8 @@ import { z } from 'zod' +/** GET /v1/sandboxes/boot-plan: what a create of the repo would do with it. */ +export const HostedBootPlanResponseSchema = z.object({ repo: z.enum(['clone', 'update']) }) + /** GET /v1/sandboxes/:id/clone: the background clone of a `clone-progress` create. */ export const HostedCloneStatusResponseSchema = z.object({ clone: z.discriminatedUnion('state', [ diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index 6aa002aedcb..ecc111e0b2f 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -131,7 +131,9 @@ export const HostedSandboxCreateRequestSchema = z .regex(/^bld_[0-9a-f]{8,40}$/) .optional(), /** Default true: boot from the active build of the org environment that lists the repo. */ - useEnvironment: z.boolean().optional() + useEnvironment: z.boolean().optional(), + /** The workspace's name, so lists show it instead of an untitled sandbox. */ + title: z.string().trim().min(1).max(120).optional() }) .strict() export type HostedSandboxCreateRequest = z.infer @@ -153,7 +155,11 @@ export const HostedSandboxReadyResponseSchema = z connection: HostedSandboxConnectionSchema, /** Create with feature `clone-progress`: the repo is still cloning; poll GET .../clone. */ clone: z - .object({ state: z.literal('running') }) + .object({ + state: z.literal('running'), + /** Booted from an environment build: only what changed since it is fetched (feature `repo-update`). */ + mode: z.literal('update').optional() + }) .strict() .optional() })